{"version":3,"sources":["../src/encryption.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv, randomBytes, scrypt } from 'node:crypto';\nimport { promisify } from 'node:util';\n\nconst scryptAsync = promisify(scrypt);\n\nexport type EncryptionKey = {\n  id: string;\n  key: Buffer;\n  createdAt: Date;\n  expiresAt?: Date;\n  isActive: boolean;\n};\n\nexport type EnvelopeEncryptionConfig = {\n  masterKey: string;\n  keyRotationDays: number;\n  keySize: number;\n  algorithm: string;\n};\n\nexport class AdvancedEncryptionManager {\n  private readonly keys: Map<string, EncryptionKey> = new Map();\n  private currentKeyId: string;\n\n  constructor(private readonly config: EnvelopeEncryptionConfig) {\n    this.currentKeyId = this.generateKeyId();\n    void this.initializeKeys();\n  }\n\n  private async initializeKeys(): Promise<void> {\n    // Create initial data encryption key\n    const key = await this.deriveKey(this.config.masterKey, this.currentKeyId);\n    this.keys.set(this.currentKeyId, {\n      id: this.currentKeyId,\n      key,\n      createdAt: new Date(),\n      isActive: true,\n    });\n  }\n\n  private generateKeyId(): string {\n    return `key_${Date.now()}_${randomBytes(4).toString('hex')}`;\n  }\n\n  private async deriveKey(masterKey: string, salt: string): Promise<Buffer> {\n    const key = await scryptAsync(masterKey, salt, this.config.keySize);\n    return key as Buffer;\n  }\n\n  encrypt(plaintext: string): Promise<{\n    ciphertext: string;\n    keyId: string;\n    iv: string;\n  }> {\n    const currentKey = this.keys.get(this.currentKeyId);\n    if (!currentKey) {\n      throw new Error('No active encryption key available');\n    }\n\n    const iv = randomBytes(16);\n    const cipher = createCipheriv(this.config.algorithm, currentKey.key, iv);\n\n    let encrypted = cipher.update(plaintext, 'utf8', 'hex');\n    encrypted += cipher.final('hex');\n\n    return Promise.resolve({\n      ciphertext: encrypted,\n      keyId: this.currentKeyId,\n      iv: iv.toString('hex'),\n    });\n  }\n\n  decrypt(ciphertext: string, keyId: string, iv: string): Promise<string> {\n    const key = this.keys.get(keyId);\n    if (!key) {\n      return Promise.reject(new Error(`Encryption key ${keyId} not found`));\n    }\n\n    const decipher = createDecipheriv(this.config.algorithm, key.key, Buffer.from(iv, 'hex'));\n\n    let decrypted = decipher.update(ciphertext, 'hex', 'utf8');\n    decrypted += decipher.final('utf8');\n\n    return Promise.resolve(decrypted);\n  }\n\n  async rotateKey(): Promise<string> {\n    // Create new key\n    const newKeyId = this.generateKeyId();\n    const newKey = await this.deriveKey(this.config.masterKey, newKeyId);\n\n    this.keys.set(newKeyId, {\n      id: newKeyId,\n      key: newKey,\n      createdAt: new Date(),\n      isActive: true,\n    });\n\n    // Mark old key as inactive but keep for decryption\n    const oldKey = this.keys.get(this.currentKeyId);\n    if (oldKey) {\n      oldKey.isActive = false;\n    }\n\n    this.currentKeyId = newKeyId;\n    return newKeyId;\n  }\n\n  shouldRotateKey(): Promise<boolean> {\n    const currentKey = this.keys.get(this.currentKeyId);\n    if (!currentKey) {\n      return Promise.resolve(true);\n    }\n\n    const ageInDays = (Date.now() - currentKey.createdAt.getTime()) / (1000 * 60 * 60 * 24);\n    return Promise.resolve(ageInDays >= this.config.keyRotationDays);\n  }\n\n  getActiveKeyId(): string {\n    return this.currentKeyId;\n  }\n\n  getKeyInfo(keyId: string): EncryptionKey | undefined {\n    return this.keys.get(keyId);\n  }\n\n  listKeys(): EncryptionKey[] {\n    return Array.from(this.keys.values());\n  }\n\n  cleanupExpiredKeys(): Promise<void> {\n    const now = Date.now();\n    for (const [keyId, key] of this.keys) {\n      if (key.expiresAt && key.expiresAt.getTime() < now && !key.isActive) {\n        this.keys.delete(keyId);\n      }\n    }\n    return Promise.resolve();\n  }\n}\n\nexport class BackupManager {\n  constructor(\n    _storagePath: string,\n    private readonly retentionDays = 30\n  ) {}\n\n  createBackup(data: unknown): Promise<string> {\n    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n    const backupId = `backup_${timestamp}`;\n\n    // In a real implementation, this would:\n    // 1. Serialize the data\n    // 2. Encrypt it\n    // 3. Store it in the configured storage backend\n    // 4. Create metadata about the backup\n\n    console.info(`Creating backup ${backupId} with ${JSON.stringify(data).length} bytes of data`);\n    return Promise.resolve(backupId);\n  }\n\n  restoreFromBackup(backupId: string): Promise<unknown> {\n    // In a real implementation, this would:\n    // 1. Locate the backup\n    // 2. Decrypt it\n    // 3. Deserialize and return the data\n\n    console.info(`Restoring from backup ${backupId}`);\n    return Promise.reject(new Error('Backup restoration not yet implemented'));\n  }\n\n  listBackups(): Promise<string[]> {\n    // Return list of available backup IDs\n    return Promise.resolve([]);\n  }\n\n  cleanupOldBackups(): Promise<void> {\n    const cutoffDate = new Date();\n    cutoffDate.setDate(cutoffDate.getDate() - this.retentionDays);\n\n    console.info(`Cleaning up backups older than ${cutoffDate.toISOString()}`);\n    // In a real implementation, this would delete old backups\n    return Promise.resolve();\n  }\n}\n"],"mappings":";;;;;AAAA,SAAS,gBAAgB,kBAAkB,aAAa,cAAc;AACtE,SAAS,iBAAiB;AAE1B,IAAM,cAAc,UAAU,MAAM;AAiB7B,IAAM,4BAAN,MAAgC;AAAA,EAIrC,YAA6B,QAAkC;AAAlC;AAH7B,wBAAiB,QAAmC,oBAAI,IAAI;AAC5D,wBAAQ;AAGN,SAAK,eAAe,KAAK,cAAc;AACvC,SAAK,KAAK,eAAe;AAAA,EAC3B;AAAA,EAEA,MAAc,iBAAgC;AAE5C,UAAM,MAAM,MAAM,KAAK,UAAU,KAAK,OAAO,WAAW,KAAK,YAAY;AACzE,SAAK,KAAK,IAAI,KAAK,cAAc;AAAA,MAC/B,IAAI,KAAK;AAAA,MACT;AAAA,MACA,WAAW,oBAAI,KAAK;AAAA,MACpB,UAAU;AAAA,IACZ,CAAC;AAAA,EACH;AAAA,EAEQ,gBAAwB;AAC9B,WAAO,OAAO,KAAK,IAAI,CAAC,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC;AAAA,EAC5D;AAAA,EAEA,MAAc,UAAU,WAAmB,MAA+B;AACxE,UAAM,MAAM,MAAM,YAAY,WAAW,MAAM,KAAK,OAAO,OAAO;AAClE,WAAO;AAAA,EAC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