encryption-context.ts raw

   1  /**
   2   * Context containing the cryptographic parameters needed for encryption/decryption.
   3   * This abstracts away the vault version differences (v1 PBKDF2 vs v2 Argon2id).
   4   */
   5  export type EncryptionContext =
   6    | EncryptionContextV1
   7    | EncryptionContextV2;
   8  
   9  /**
  10   * v1: PBKDF2-derived key from password
  11   */
  12  export interface EncryptionContextV1 {
  13    version: 1;
  14    iv: string;
  15    password: string;
  16  }
  17  
  18  /**
  19   * v2: Pre-derived Argon2id key
  20   */
  21  export interface EncryptionContextV2 {
  22    version: 2;
  23    iv: string;
  24    keyBase64: string;
  25  }
  26  
  27  /**
  28   * Type guard for v1 context
  29   */
  30  export function isV1Context(ctx: EncryptionContext): ctx is EncryptionContextV1 {
  31    return ctx.version === 1;
  32  }
  33  
  34  /**
  35   * Type guard for v2 context
  36   */
  37  export function isV2Context(ctx: EncryptionContext): ctx is EncryptionContextV2 {
  38    return ctx.version === 2;
  39  }
  40  
  41  /**
  42   * Create an encryption context from session data.
  43   * Returns undefined if no valid context can be created.
  44   */
  45  export function createEncryptionContext(params: {
  46    iv: string;
  47    vaultPassword?: string;
  48    vaultKey?: string;
  49  }): EncryptionContext | undefined {
  50    if (params.vaultKey) {
  51      return {
  52        version: 2,
  53        iv: params.iv,
  54        keyBase64: params.vaultKey,
  55      };
  56    }
  57  
  58    if (params.vaultPassword) {
  59      return {
  60        version: 1,
  61        iv: params.iv,
  62        password: params.vaultPassword,
  63      };
  64    }
  65  
  66    return undefined;
  67  }
  68