@fgv/ts-extras 5.1.0-40 → 5.1.0-41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/packlets/crypto-utils/hpkeProvider.js +34 -12
- package/dist/packlets/crypto-utils/hpkeProvider.js.map +1 -1
- package/dist/packlets/crypto-utils/index.browser.js +1 -1
- package/dist/packlets/crypto-utils/index.browser.js.map +1 -1
- package/dist/packlets/crypto-utils/index.js +1 -1
- package/dist/packlets/crypto-utils/index.js.map +1 -1
- package/dist/packlets/crypto-utils/keystore/converters.js +3 -4
- package/dist/packlets/crypto-utils/keystore/converters.js.map +1 -1
- package/dist/packlets/crypto-utils/keystore/keyStore.js +155 -16
- package/dist/packlets/crypto-utils/keystore/keyStore.js.map +1 -1
- package/dist/packlets/crypto-utils/keystore/model.js +8 -3
- package/dist/packlets/crypto-utils/keystore/model.js.map +1 -1
- package/dist/packlets/crypto-utils/model.js.map +1 -1
- package/dist/packlets/crypto-utils/nodeCryptoProvider.js +66 -0
- package/dist/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -1
- package/dist/packlets/crypto-utils/spkiHelpers.js +31 -0
- package/dist/packlets/crypto-utils/spkiHelpers.js.map +1 -1
- package/dist/ts-extras.d.ts +289 -7
- package/lib/packlets/crypto-utils/hpkeProvider.d.ts +11 -3
- package/lib/packlets/crypto-utils/hpkeProvider.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/hpkeProvider.js +34 -12
- package/lib/packlets/crypto-utils/hpkeProvider.js.map +1 -1
- package/lib/packlets/crypto-utils/index.browser.d.ts +1 -1
- package/lib/packlets/crypto-utils/index.browser.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/index.browser.js +2 -1
- package/lib/packlets/crypto-utils/index.browser.js.map +1 -1
- package/lib/packlets/crypto-utils/index.d.ts +1 -1
- package/lib/packlets/crypto-utils/index.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/index.js +2 -1
- package/lib/packlets/crypto-utils/index.js.map +1 -1
- package/lib/packlets/crypto-utils/keystore/converters.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/keystore/converters.js +2 -3
- package/lib/packlets/crypto-utils/keystore/converters.js.map +1 -1
- package/lib/packlets/crypto-utils/keystore/keyStore.d.ts +68 -3
- package/lib/packlets/crypto-utils/keystore/keyStore.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/keystore/keyStore.js +154 -15
- package/lib/packlets/crypto-utils/keystore/keyStore.js.map +1 -1
- package/lib/packlets/crypto-utils/keystore/model.d.ts +75 -2
- package/lib/packlets/crypto-utils/keystore/model.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/keystore/model.js +9 -4
- package/lib/packlets/crypto-utils/keystore/model.js.map +1 -1
- package/lib/packlets/crypto-utils/model.d.ts +89 -0
- package/lib/packlets/crypto-utils/model.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/model.js.map +1 -1
- package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts +25 -1
- package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/nodeCryptoProvider.js +66 -0
- package/lib/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -1
- package/lib/packlets/crypto-utils/spkiHelpers.d.ts +15 -0
- package/lib/packlets/crypto-utils/spkiHelpers.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/spkiHelpers.js +32 -0
- package/lib/packlets/crypto-utils/spkiHelpers.js.map +1 -1
- package/package.json +7 -7
|
@@ -19,17 +19,22 @@
|
|
|
19
19
|
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
20
|
// SOFTWARE.
|
|
21
21
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
-
exports.DEFAULT_SECRET_ITERATIONS = exports.allKeyStoreSecretTypes = exports.allKeyStoreAsymmetricSecretTypes = exports.allKeyStoreSymmetricSecretTypes = exports.MIN_SALT_LENGTH = exports.DEFAULT_KEYSTORE_ITERATIONS = exports.KEYSTORE_FORMAT = exports.allKeyPairAlgorithms = void 0;
|
|
22
|
+
exports.DEFAULT_SECRET_ITERATIONS = exports.allKeyStoreSecretTypes = exports.allKeyStoreAsymmetricSecretTypes = exports.allKeyStoreSymmetricSecretTypes = exports.MIN_SALT_LENGTH = exports.DEFAULT_KEYSTORE_ITERATIONS = exports.KEYSTORE_FORMAT = exports.allKeyStoreFormats = exports.allKeyPairAlgorithms = void 0;
|
|
23
23
|
exports.isKeyStoreFile = isKeyStoreFile;
|
|
24
24
|
// Re-export so consumers can continue to access the algorithm enum via the
|
|
25
25
|
// CryptoUtils.KeyStore namespace alongside the rest of the keystore types.
|
|
26
26
|
var model_1 = require("../model");
|
|
27
27
|
Object.defineProperty(exports, "allKeyPairAlgorithms", { enumerable: true, get: function () { return model_1.allKeyPairAlgorithms; } });
|
|
28
28
|
/**
|
|
29
|
-
*
|
|
29
|
+
* All recognized key store format versions (readable by the current library).
|
|
30
30
|
* @public
|
|
31
31
|
*/
|
|
32
|
-
exports.
|
|
32
|
+
exports.allKeyStoreFormats = ['keystore-v1', 'keystore-v2'];
|
|
33
|
+
/**
|
|
34
|
+
* Current format version constant. New vaults are written as `'keystore-v2'`.
|
|
35
|
+
* @public
|
|
36
|
+
*/
|
|
37
|
+
exports.KEYSTORE_FORMAT = 'keystore-v2';
|
|
33
38
|
/**
|
|
34
39
|
* Default PBKDF2 iterations for key store encryption.
|
|
35
40
|
* Higher than regular files since this protects the master key vault.
|
|
@@ -85,6 +90,6 @@ function isKeyStoreFile(json) {
|
|
|
85
90
|
return false;
|
|
86
91
|
}
|
|
87
92
|
const obj = json;
|
|
88
|
-
return obj.format === exports.
|
|
93
|
+
return typeof obj.format === 'string' && exports.allKeyStoreFormats.includes(obj.format);
|
|
89
94
|
}
|
|
90
95
|
//# sourceMappingURL=model.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","sourceRoot":"","sources":["../../../../src/packlets/crypto-utils/keystore/model.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;;;AAqmBZ,wCAMC;AA/lBD,2EAA2E;AAC3E,2EAA2E;AAC3E,kCAAkE;AAAzD,6GAAA,oBAAoB,OAAA;AAY7B;;;GAGG;AACU,QAAA,eAAe,GAAmB,aAAa,CAAC;AAE7D;;;;GAIG;AACU,QAAA,2BAA2B,GAAW,MAAM,CAAC;AAE1D;;;GAGG;AACU,QAAA,eAAe,GAAW,EAAE,CAAC;AAc1C;;;GAGG;AACU,QAAA,+BAA+B,GAA+C;IACzF,gBAAgB;IAChB,SAAS;CACV,CAAC;AAWF;;;GAGG;AACU,QAAA,gCAAgC,GAAgD;IAC3F,oBAAoB;CACrB,CAAC;AAQF;;;GAGG;AACU,QAAA,sBAAsB,GAAsC;IACvE,GAAG,wCAAgC;IACnC,GAAG,uCAA+B;CACnC,CAAC;AAsYF;;;;GAIG;AACU,QAAA,yBAAyB,GAAW,MAAM,CAAC;AA+GxD,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;GAMG;AACH,SAAgB,cAAc,CAAC,IAAa;IAC1C,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;QAC9C,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,GAAG,GAAG,IAA+B,CAAC;IAC5C,OAAO,GAAG,CAAC,MAAM,KAAK,uBAAe,CAAC;AACxC,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport {\n EncryptionAlgorithm,\n ICryptoProvider,\n IArgon2idParams,\n IKeyDerivationParams,\n IPbkdf2KeyDerivationParams,\n KeyPairAlgorithm\n} from '../model';\nimport { IPrivateKeyStorage } from './privateKeyStorage';\n\n// Re-export so consumers can continue to access the algorithm enum via the\n// CryptoUtils.KeyStore namespace alongside the rest of the keystore types.\nexport { allKeyPairAlgorithms, KeyPairAlgorithm } from '../model';\n\n// ============================================================================\n// Key Store Format Types\n// ============================================================================\n\n/**\n * Format version for key store files.\n * @public\n */\nexport type KeyStoreFormat = 'keystore-v1';\n\n/**\n * Current format version constant.\n * @public\n */\nexport const KEYSTORE_FORMAT: KeyStoreFormat = 'keystore-v1';\n\n/**\n * Default PBKDF2 iterations for key store encryption.\n * Higher than regular files since this protects the master key vault.\n * @public\n */\nexport const DEFAULT_KEYSTORE_ITERATIONS: number = 600000;\n\n/**\n * Minimum salt length for key derivation.\n * @public\n */\nexport const MIN_SALT_LENGTH: number = 16;\n\n// ============================================================================\n// Key Store Vault Contents (Decrypted State)\n// ============================================================================\n\n/**\n * Discriminator for symmetric secret types stored in the vault.\n * - `'encryption-key'`: A 32-byte AES-256 encryption key.\n * - `'api-key'`: An arbitrary-length API key string (UTF-8 encoded).\n * @public\n */\nexport type KeyStoreSymmetricSecretType = 'encryption-key' | 'api-key';\n\n/**\n * All valid symmetric secret types.\n * @public\n */\nexport const allKeyStoreSymmetricSecretTypes: ReadonlyArray<KeyStoreSymmetricSecretType> = [\n 'encryption-key',\n 'api-key'\n];\n\n/**\n * Discriminator for asymmetric secret types stored in the vault.\n * - `'asymmetric-keypair'`: A public/private key pair. The public key is held in\n * the vault as a JWK; the private key lives in the supplied\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage} provider.\n * @public\n */\nexport type KeyStoreAsymmetricSecretType = 'asymmetric-keypair';\n\n/**\n * All valid asymmetric secret types.\n * @public\n */\nexport const allKeyStoreAsymmetricSecretTypes: ReadonlyArray<KeyStoreAsymmetricSecretType> = [\n 'asymmetric-keypair'\n];\n\n/**\n * Discriminator for any secret type stored in the vault.\n * @public\n */\nexport type KeyStoreSecretType = KeyStoreSymmetricSecretType | KeyStoreAsymmetricSecretType;\n\n/**\n * All valid key store secret types.\n * @public\n */\nexport const allKeyStoreSecretTypes: ReadonlyArray<KeyStoreSecretType> = [\n ...allKeyStoreAsymmetricSecretTypes,\n ...allKeyStoreSymmetricSecretTypes\n];\n\n/**\n * A symmetric secret entry stored in the vault (in-memory representation).\n * Holds the raw key material directly — for `'encryption-key'` it is a 32-byte\n * AES-256 key; for `'api-key'` it is the UTF-8 encoded API key string.\n * @public\n */\nexport interface IKeyStoreSymmetricEntry {\n /**\n * Unique name for this secret (used as lookup key).\n */\n readonly name: string;\n\n /**\n * Symmetric secret type discriminator.\n */\n readonly type: KeyStoreSymmetricSecretType;\n\n /**\n * The secret data.\n * - For `'encryption-key'`: 32-byte AES-256 key.\n * - For `'api-key'`: UTF-8 encoded API key string (arbitrary length).\n */\n readonly key: Uint8Array;\n\n /**\n * Optional description for this secret.\n */\n readonly description?: string;\n\n /**\n * When this secret was added (ISO 8601).\n */\n readonly createdAt: string;\n}\n\n/**\n * An asymmetric keypair entry stored in the vault (in-memory representation).\n * Holds only the public key (as a JWK) and a stable handle (`id`) the\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage} provider uses to fetch the private key.\n * @public\n */\nexport interface IKeyStoreAsymmetricEntry {\n /**\n * Unique name for this entry (used as vault lookup key, renameable).\n */\n readonly name: string;\n\n /**\n * Asymmetric secret type discriminator.\n */\n readonly type: KeyStoreAsymmetricSecretType;\n\n /**\n * Immutable handle used by {@link CryptoUtils.KeyStore.IPrivateKeyStorage} to address the\n * private key. Independent of `name`; survives renames.\n */\n readonly id: string;\n\n /**\n * Algorithm used to generate this keypair.\n */\n readonly algorithm: KeyPairAlgorithm;\n\n /**\n * The public key as a JSON Web Key.\n */\n readonly publicKeyJwk: JsonWebKey;\n\n /**\n * Optional description for this entry.\n */\n readonly description?: string;\n\n /**\n * When this entry was added (ISO 8601).\n */\n readonly createdAt: string;\n}\n\n/**\n * Any vault entry, discriminated by `type`.\n * @public\n */\nexport type IKeyStoreEntry = IKeyStoreSymmetricEntry | IKeyStoreAsymmetricEntry;\n\n/**\n * Backwards-compatible alias for {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntry}.\n * @deprecated Use {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntry} for symmetric\n * entries or {@link CryptoUtils.KeyStore.IKeyStoreEntry} for the discriminated union.\n * @public\n */\nexport type IKeyStoreSecretEntry = IKeyStoreSymmetricEntry;\n\n/**\n * JSON-serializable representation of a symmetric secret entry.\n *\n * @remarks\n * Describes the *normalized* shape after parsing. `type` is required here\n * because the converter (see\n * {@link CryptoUtils.KeyStore.Converters.keystoreSymmetricEntryJson | keystoreSymmetricEntryJson})\n * injects the default `'encryption-key'` when reading vaults written before\n * asymmetric-keypair support added the discriminator. Raw on-wire bytes from\n * a legacy vault may therefore omit `type`; downstream code only ever sees\n * the post-conversion shape declared here.\n *\n * @public\n */\nexport interface IKeyStoreSymmetricEntryJson {\n /**\n * Unique name for this secret.\n */\n readonly name: string;\n\n /**\n * Symmetric secret type discriminator.\n *\n * Required on this normalized model type. Vaults written prior to the\n * asymmetric-keypair support may omit this field on the wire; the\n * converter injects `'encryption-key'` when missing for backwards\n * compatibility, so by the time a value of this type is observed the\n * discriminator is always present.\n */\n readonly type: KeyStoreSymmetricSecretType;\n\n /**\n * Base64-encoded secret data.\n */\n readonly key: string;\n\n /**\n * Optional description.\n */\n readonly description?: string;\n\n /**\n * When this secret was added (ISO 8601).\n */\n readonly createdAt: string;\n}\n\n/**\n * JSON-serializable representation of an asymmetric keypair entry.\n * The private key is not present here — it lives in the\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage} provider, addressed by `id`.\n * @public\n */\nexport interface IKeyStoreAsymmetricEntryJson {\n /**\n * Unique name for this entry.\n */\n readonly name: string;\n\n /**\n * Asymmetric secret type discriminator.\n */\n readonly type: KeyStoreAsymmetricSecretType;\n\n /**\n * Immutable handle used by {@link CryptoUtils.KeyStore.IPrivateKeyStorage} to address the\n * private key.\n */\n readonly id: string;\n\n /**\n * Algorithm used to generate this keypair.\n */\n readonly algorithm: KeyPairAlgorithm;\n\n /**\n * The public key as a JSON Web Key.\n */\n readonly publicKeyJwk: JsonWebKey;\n\n /**\n * Optional description.\n */\n readonly description?: string;\n\n /**\n * When this entry was added (ISO 8601).\n */\n readonly createdAt: string;\n}\n\n/**\n * Any JSON vault entry, discriminated by `type`.\n * @public\n */\nexport type IKeyStoreEntryJson = IKeyStoreSymmetricEntryJson | IKeyStoreAsymmetricEntryJson;\n\n/**\n * Backwards-compatible alias for {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntryJson}.\n * @deprecated Use {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntryJson} for\n * symmetric entries or {@link CryptoUtils.KeyStore.IKeyStoreEntryJson} for the\n * discriminated union.\n * @public\n */\nexport type IKeyStoreSecretEntryJson = IKeyStoreSymmetricEntryJson;\n\n/**\n * The decrypted vault contents - a versioned map of entries.\n * @public\n */\nexport interface IKeyStoreVaultContents {\n /**\n * Format version for vault contents.\n */\n readonly version: KeyStoreFormat;\n\n /**\n * Map of entry name to entry (symmetric or asymmetric).\n */\n readonly secrets: Record<string, IKeyStoreEntryJson>;\n}\n\n// ============================================================================\n// Key Store File Format (Encrypted State)\n// ============================================================================\n\n/**\n * The encrypted key store file format.\n * @public\n */\nexport interface IKeyStoreFile {\n /**\n * Format identifier.\n */\n readonly format: KeyStoreFormat;\n\n /**\n * Algorithm used for encryption.\n */\n readonly algorithm: EncryptionAlgorithm;\n\n /**\n * Base64-encoded initialization vector.\n */\n readonly iv: string;\n\n /**\n * Base64-encoded authentication tag.\n */\n readonly authTag: string;\n\n /**\n * Base64-encoded encrypted vault contents.\n */\n readonly encryptedData: string;\n\n /**\n * Key derivation parameters for the vault master key (always PBKDF2).\n */\n readonly keyDerivation: IPbkdf2KeyDerivationParams;\n}\n\n// ============================================================================\n// Key Store State and Configuration\n// ============================================================================\n\n/**\n * Key store lock state.\n * @public\n */\nexport type KeyStoreLockState = 'locked' | 'unlocked';\n\n/**\n * Parameters for creating a new key store.\n * @public\n */\nexport interface IKeyStoreCreateParams {\n /**\n * Crypto provider to use.\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * PBKDF2 iterations (defaults to DEFAULT_KEYSTORE_ITERATIONS).\n */\n readonly iterations?: number;\n\n /**\n * Optional private-key storage backend. Required to use `addKeyPair` /\n * `getKeyPair`; absent backends still permit opening, listing, and reading\n * public-key metadata for asymmetric entries.\n */\n readonly privateKeyStorage?: IPrivateKeyStorage;\n}\n\n/**\n * Parameters for opening an existing key store.\n * @public\n */\nexport interface IKeyStoreOpenParams {\n /**\n * Crypto provider to use.\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * The encrypted key store file content.\n */\n readonly keystoreFile: IKeyStoreFile;\n\n /**\n * Optional private-key storage backend. Required to use `addKeyPair` /\n * `getKeyPair`; absent backends still permit opening, listing, and reading\n * public-key metadata for asymmetric entries.\n */\n readonly privateKeyStorage?: IPrivateKeyStorage;\n}\n\n/**\n * Result of adding a secret to the key store.\n * @public\n */\nexport interface IAddSecretResult {\n /**\n * The secret entry that was added.\n */\n readonly entry: IKeyStoreSymmetricEntry;\n\n /**\n * Whether this replaced an existing secret.\n */\n readonly replaced: boolean;\n\n /**\n * Best-effort warning from displaced-resource cleanup. Set when this call\n * replaced an asymmetric-keypair entry but the corresponding\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage}.delete failed; the new\n * entry is still committed and the orphaned blob is left for consumer-side\n * GC to reconcile.\n */\n readonly warning?: string;\n}\n\n/**\n * Options for adding a secret.\n * @public\n */\nexport interface IAddSecretOptions {\n /**\n * Optional description for the secret.\n */\n readonly description?: string;\n}\n\n/**\n * Options for importing a secret.\n * @public\n */\nexport interface IImportSecretOptions extends IAddSecretOptions {\n /**\n * Whether to replace an existing secret with the same name.\n */\n readonly replace?: boolean;\n}\n\n/**\n * Options for importing raw key material via {@link KeyStore.importSecret}.\n * Extends {@link IImportSecretOptions} with a type classification.\n * @public\n */\nexport interface IImportKeyOptions extends IImportSecretOptions {\n /**\n * Symmetric secret type classification for the imported key material.\n * @defaultValue 'encryption-key'\n */\n readonly type?: KeyStoreSymmetricSecretType;\n}\n\n/**\n * Options for adding a secret derived from a password.\n * @public\n */\nexport interface IAddSecretFromPasswordOptions extends IAddSecretOptions {\n /**\n * Whether to replace an existing secret with the same name.\n */\n readonly replace?: boolean;\n\n /**\n * PBKDF2 iterations for key derivation.\n * @defaultValue DEFAULT_SECRET_ITERATIONS (350000)\n */\n readonly iterations?: number;\n}\n\n/**\n * Default PBKDF2 iterations for secret-level key derivation.\n * Lower than keystore encryption since these are used more frequently.\n * @public\n */\nexport const DEFAULT_SECRET_ITERATIONS: number = 350000;\n\n/**\n * Result of adding a password-derived secret.\n * Extends {@link IAddSecretResult} with key derivation parameters\n * needed to store alongside encrypted files.\n * @public\n */\nexport interface IAddSecretFromPasswordResult extends IAddSecretResult {\n /**\n * Key derivation parameters used to derive the secret key.\n * Store these in encrypted file metadata so the password alone\n * can re-derive the same key for decryption.\n */\n readonly keyDerivation: IKeyDerivationParams;\n}\n\n/**\n * Options for adding an Argon2id password-derived secret.\n * @public\n */\nexport interface IAddSecretFromPasswordArgon2idOptions {\n /**\n * Argon2id parameters. Defaults to {@link CryptoUtils.ARGON2ID_OWASP_MIN}.\n */\n readonly params?: IArgon2idParams;\n /**\n * Optional description for the secret.\n */\n readonly description?: string;\n /**\n * Whether to replace an existing secret with the same name.\n */\n readonly replace?: boolean;\n}\n\n/**\n * Options for adding an asymmetric keypair to the key store.\n * @public\n */\nexport interface IAddKeyPairOptions {\n /**\n * Algorithm to use for the new keypair.\n */\n readonly algorithm: KeyPairAlgorithm;\n\n /**\n * Optional description for the entry.\n */\n readonly description?: string;\n\n /**\n * Whether to replace an existing entry with the same name.\n * Replacement mints a fresh storage `id` and best-effort deletes the\n * displaced storage blob; see the keystore design doc for details.\n */\n readonly replace?: boolean;\n\n /**\n * Overrides the storage-backend-derived extractability for this key only.\n * Omit to keep the default (`!privateKeyStorage.supportsNonExtractable`).\n * A value the backend cannot honor fails loudly rather than silently\n * downgrading.\n */\n readonly extractable?: boolean;\n}\n\n/**\n * Result of adding an asymmetric keypair to the key store.\n * @public\n */\nexport interface IAddKeyPairResult {\n /**\n * The asymmetric entry that was added.\n */\n readonly entry: IKeyStoreAsymmetricEntry;\n\n /**\n * Whether this replaced an existing entry.\n */\n readonly replaced: boolean;\n\n /**\n * Best-effort warning from displaced-resource cleanup. Set when this call\n * replaced a prior entry but the corresponding\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage}.delete failed; the new\n * keypair is still committed and the orphaned blob is left for consumer-side\n * GC to reconcile.\n */\n readonly warning?: string;\n}\n\n/**\n * Result of removing a secret from the key store.\n * @public\n */\nexport interface IRemoveSecretResult {\n /**\n * The secret entry that was removed from the vault.\n */\n readonly entry: IKeyStoreEntry;\n\n /**\n * Best-effort warning from {@link CryptoUtils.KeyStore.IPrivateKeyStorage}.delete\n * for asymmetric entries when the storage call failed. The vault entry is\n * still considered removed and the orphaned blob is left for consumer-side\n * GC to reconcile.\n */\n readonly warning?: string;\n}\n\n// ============================================================================\n// Detection Helper\n// ============================================================================\n\n/**\n * Checks if a JSON object appears to be a key store file.\n * Uses the format field as a discriminator.\n * @param json - JSON object to check\n * @returns true if the object has the key store format field\n * @public\n */\nexport function isKeyStoreFile(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) {\n return false;\n }\n const obj = json as Record<string, unknown>;\n return obj.format === KEYSTORE_FORMAT;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"model.js","sourceRoot":"","sources":["../../../../src/packlets/crypto-utils/keystore/model.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;;;AAmrBZ,wCAMC;AA7qBD,2EAA2E;AAC3E,2EAA2E;AAC3E,kCAAkE;AAAzD,6GAAA,oBAAoB,OAAA;AAkB7B;;;GAGG;AACU,QAAA,kBAAkB,GAAkC,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;AAEhG;;;GAGG;AACU,QAAA,eAAe,GAAmB,aAAa,CAAC;AAE7D;;;;GAIG;AACU,QAAA,2BAA2B,GAAW,MAAM,CAAC;AAE1D;;;GAGG;AACU,QAAA,eAAe,GAAW,EAAE,CAAC;AAc1C;;;GAGG;AACU,QAAA,+BAA+B,GAA+C;IACzF,gBAAgB;IAChB,SAAS;CACV,CAAC;AAWF;;;GAGG;AACU,QAAA,gCAAgC,GAAgD;IAC3F,oBAAoB;CACrB,CAAC;AAQF;;;GAGG;AACU,QAAA,sBAAsB,GAAsC;IACvE,GAAG,wCAAgC;IACnC,GAAG,uCAA+B;CACnC,CAAC;AA6ZF;;;;GAIG;AACU,QAAA,yBAAyB,GAAW,MAAM,CAAC;AA0JxD,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;GAMG;AACH,SAAgB,cAAc,CAAC,IAAa;IAC1C,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;QAC9C,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,GAAG,GAAG,IAA+B,CAAC;IAC5C,OAAO,OAAO,GAAG,CAAC,MAAM,KAAK,QAAQ,IAAK,0BAA4C,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;AAC9G,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport {\n EncryptionAlgorithm,\n ICryptoProvider,\n IArgon2idParams,\n IKeyDerivationParams,\n IPbkdf2KeyDerivationParams,\n KeyPairAlgorithm\n} from '../model';\nimport { IPrivateKeyStorage } from './privateKeyStorage';\n\n// Re-export so consumers can continue to access the algorithm enum via the\n// CryptoUtils.KeyStore namespace alongside the rest of the keystore types.\nexport { allKeyPairAlgorithms, KeyPairAlgorithm } from '../model';\n\n// ============================================================================\n// Key Store Format Types\n// ============================================================================\n\n/**\n * Format version for key store files.\n *\n * - `'keystore-v1'`: the original format (no private-key escrow).\n * - `'keystore-v2'`: adds the optional `escrowedPrivateKeyJwk` field on\n * asymmetric-keypair entries. A strict superset of v1 — the field is\n * optional, so a v2 reader opens a v1 vault with no special-casing, and a\n * v1 vault opened and re-saved is silently upgraded to v2.\n * @public\n */\nexport type KeyStoreFormat = 'keystore-v1' | 'keystore-v2';\n\n/**\n * All recognized key store format versions (readable by the current library).\n * @public\n */\nexport const allKeyStoreFormats: ReadonlyArray<KeyStoreFormat> = ['keystore-v1', 'keystore-v2'];\n\n/**\n * Current format version constant. New vaults are written as `'keystore-v2'`.\n * @public\n */\nexport const KEYSTORE_FORMAT: KeyStoreFormat = 'keystore-v2';\n\n/**\n * Default PBKDF2 iterations for key store encryption.\n * Higher than regular files since this protects the master key vault.\n * @public\n */\nexport const DEFAULT_KEYSTORE_ITERATIONS: number = 600000;\n\n/**\n * Minimum salt length for key derivation.\n * @public\n */\nexport const MIN_SALT_LENGTH: number = 16;\n\n// ============================================================================\n// Key Store Vault Contents (Decrypted State)\n// ============================================================================\n\n/**\n * Discriminator for symmetric secret types stored in the vault.\n * - `'encryption-key'`: A 32-byte AES-256 encryption key.\n * - `'api-key'`: An arbitrary-length API key string (UTF-8 encoded).\n * @public\n */\nexport type KeyStoreSymmetricSecretType = 'encryption-key' | 'api-key';\n\n/**\n * All valid symmetric secret types.\n * @public\n */\nexport const allKeyStoreSymmetricSecretTypes: ReadonlyArray<KeyStoreSymmetricSecretType> = [\n 'encryption-key',\n 'api-key'\n];\n\n/**\n * Discriminator for asymmetric secret types stored in the vault.\n * - `'asymmetric-keypair'`: A public/private key pair. The public key is held in\n * the vault as a JWK; the private key lives in the supplied\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage} provider.\n * @public\n */\nexport type KeyStoreAsymmetricSecretType = 'asymmetric-keypair';\n\n/**\n * All valid asymmetric secret types.\n * @public\n */\nexport const allKeyStoreAsymmetricSecretTypes: ReadonlyArray<KeyStoreAsymmetricSecretType> = [\n 'asymmetric-keypair'\n];\n\n/**\n * Discriminator for any secret type stored in the vault.\n * @public\n */\nexport type KeyStoreSecretType = KeyStoreSymmetricSecretType | KeyStoreAsymmetricSecretType;\n\n/**\n * All valid key store secret types.\n * @public\n */\nexport const allKeyStoreSecretTypes: ReadonlyArray<KeyStoreSecretType> = [\n ...allKeyStoreAsymmetricSecretTypes,\n ...allKeyStoreSymmetricSecretTypes\n];\n\n/**\n * A symmetric secret entry stored in the vault (in-memory representation).\n * Holds the raw key material directly — for `'encryption-key'` it is a 32-byte\n * AES-256 key; for `'api-key'` it is the UTF-8 encoded API key string.\n * @public\n */\nexport interface IKeyStoreSymmetricEntry {\n /**\n * Unique name for this secret (used as lookup key).\n */\n readonly name: string;\n\n /**\n * Symmetric secret type discriminator.\n */\n readonly type: KeyStoreSymmetricSecretType;\n\n /**\n * The secret data.\n * - For `'encryption-key'`: 32-byte AES-256 key.\n * - For `'api-key'`: UTF-8 encoded API key string (arbitrary length).\n */\n readonly key: Uint8Array;\n\n /**\n * Optional description for this secret.\n */\n readonly description?: string;\n\n /**\n * When this secret was added (ISO 8601).\n */\n readonly createdAt: string;\n}\n\n/**\n * An asymmetric keypair entry stored in the vault (in-memory representation).\n * Holds only the public key (as a JWK) and a stable handle (`id`) the\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage} provider uses to fetch the private key.\n * @public\n */\nexport interface IKeyStoreAsymmetricEntry {\n /**\n * Unique name for this entry (used as vault lookup key, renameable).\n */\n readonly name: string;\n\n /**\n * Asymmetric secret type discriminator.\n */\n readonly type: KeyStoreAsymmetricSecretType;\n\n /**\n * Immutable handle used by {@link CryptoUtils.KeyStore.IPrivateKeyStorage} to address the\n * private key. Independent of `name`; survives renames.\n */\n readonly id: string;\n\n /**\n * Algorithm used to generate this keypair.\n */\n readonly algorithm: KeyPairAlgorithm;\n\n /**\n * The public key as a JSON Web Key.\n */\n readonly publicKeyJwk: JsonWebKey;\n\n /**\n * Optional escrowed copy of the private key, as a JSON Web Key. Present only\n * when the entry was created with `addKeyPair(name, { escrow: true })`.\n *\n * This is an opt-in cross-device recovery affordance: the private key is\n * carried inside the vault's AES-GCM ciphertext (same custody class as\n * `publicKeyJwk`), so a recovered vault plus the master password can\n * reconstitute the signing/decryption identity on a fresh device via\n * `getKeyPair(name, { rehydrate: true })`.\n *\n * SECURITY: when present, the master password becomes the sole gate\n * protecting this private key. Use a strong KDF for escrow-bearing stores.\n * See the {@link CryptoUtils.KeyStore.KeyStore} class docs.\n */\n readonly escrowedPrivateKeyJwk?: JsonWebKey;\n\n /**\n * Optional description for this entry.\n */\n readonly description?: string;\n\n /**\n * When this entry was added (ISO 8601).\n */\n readonly createdAt: string;\n}\n\n/**\n * Any vault entry, discriminated by `type`.\n * @public\n */\nexport type IKeyStoreEntry = IKeyStoreSymmetricEntry | IKeyStoreAsymmetricEntry;\n\n/**\n * Backwards-compatible alias for {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntry}.\n * @deprecated Use {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntry} for symmetric\n * entries or {@link CryptoUtils.KeyStore.IKeyStoreEntry} for the discriminated union.\n * @public\n */\nexport type IKeyStoreSecretEntry = IKeyStoreSymmetricEntry;\n\n/**\n * JSON-serializable representation of a symmetric secret entry.\n *\n * @remarks\n * Describes the *normalized* shape after parsing. `type` is required here\n * because the converter (see\n * {@link CryptoUtils.KeyStore.Converters.keystoreSymmetricEntryJson | keystoreSymmetricEntryJson})\n * injects the default `'encryption-key'` when reading vaults written before\n * asymmetric-keypair support added the discriminator. Raw on-wire bytes from\n * a legacy vault may therefore omit `type`; downstream code only ever sees\n * the post-conversion shape declared here.\n *\n * @public\n */\nexport interface IKeyStoreSymmetricEntryJson {\n /**\n * Unique name for this secret.\n */\n readonly name: string;\n\n /**\n * Symmetric secret type discriminator.\n *\n * Required on this normalized model type. Vaults written prior to the\n * asymmetric-keypair support may omit this field on the wire; the\n * converter injects `'encryption-key'` when missing for backwards\n * compatibility, so by the time a value of this type is observed the\n * discriminator is always present.\n */\n readonly type: KeyStoreSymmetricSecretType;\n\n /**\n * Base64-encoded secret data.\n */\n readonly key: string;\n\n /**\n * Optional description.\n */\n readonly description?: string;\n\n /**\n * When this secret was added (ISO 8601).\n */\n readonly createdAt: string;\n}\n\n/**\n * JSON-serializable representation of an asymmetric keypair entry.\n * The private key is not present here — it lives in the\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage} provider, addressed by `id`.\n * @public\n */\nexport interface IKeyStoreAsymmetricEntryJson {\n /**\n * Unique name for this entry.\n */\n readonly name: string;\n\n /**\n * Asymmetric secret type discriminator.\n */\n readonly type: KeyStoreAsymmetricSecretType;\n\n /**\n * Immutable handle used by {@link CryptoUtils.KeyStore.IPrivateKeyStorage} to address the\n * private key.\n */\n readonly id: string;\n\n /**\n * Algorithm used to generate this keypair.\n */\n readonly algorithm: KeyPairAlgorithm;\n\n /**\n * The public key as a JSON Web Key.\n */\n readonly publicKeyJwk: JsonWebKey;\n\n /**\n * Optional escrowed copy of the private key, as a JSON Web Key. Present only\n * on `'keystore-v2'` vaults whose entry was created with escrow enabled. A\n * v1 vault omits the field; a v2 reader treats its absence as \"no escrow\".\n */\n readonly escrowedPrivateKeyJwk?: JsonWebKey;\n\n /**\n * Optional description.\n */\n readonly description?: string;\n\n /**\n * When this entry was added (ISO 8601).\n */\n readonly createdAt: string;\n}\n\n/**\n * Any JSON vault entry, discriminated by `type`.\n * @public\n */\nexport type IKeyStoreEntryJson = IKeyStoreSymmetricEntryJson | IKeyStoreAsymmetricEntryJson;\n\n/**\n * Backwards-compatible alias for {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntryJson}.\n * @deprecated Use {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntryJson} for\n * symmetric entries or {@link CryptoUtils.KeyStore.IKeyStoreEntryJson} for the\n * discriminated union.\n * @public\n */\nexport type IKeyStoreSecretEntryJson = IKeyStoreSymmetricEntryJson;\n\n/**\n * The decrypted vault contents - a versioned map of entries.\n * @public\n */\nexport interface IKeyStoreVaultContents {\n /**\n * Format version for vault contents.\n */\n readonly version: KeyStoreFormat;\n\n /**\n * Map of entry name to entry (symmetric or asymmetric).\n */\n readonly secrets: Record<string, IKeyStoreEntryJson>;\n}\n\n// ============================================================================\n// Key Store File Format (Encrypted State)\n// ============================================================================\n\n/**\n * The encrypted key store file format.\n * @public\n */\nexport interface IKeyStoreFile {\n /**\n * Format identifier.\n */\n readonly format: KeyStoreFormat;\n\n /**\n * Algorithm used for encryption.\n */\n readonly algorithm: EncryptionAlgorithm;\n\n /**\n * Base64-encoded initialization vector.\n */\n readonly iv: string;\n\n /**\n * Base64-encoded authentication tag.\n */\n readonly authTag: string;\n\n /**\n * Base64-encoded encrypted vault contents.\n */\n readonly encryptedData: string;\n\n /**\n * Key derivation parameters for the vault master key (always PBKDF2).\n */\n readonly keyDerivation: IPbkdf2KeyDerivationParams;\n}\n\n// ============================================================================\n// Key Store State and Configuration\n// ============================================================================\n\n/**\n * Key store lock state.\n * @public\n */\nexport type KeyStoreLockState = 'locked' | 'unlocked';\n\n/**\n * Parameters for creating a new key store.\n * @public\n */\nexport interface IKeyStoreCreateParams {\n /**\n * Crypto provider to use.\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * PBKDF2 iterations (defaults to DEFAULT_KEYSTORE_ITERATIONS).\n */\n readonly iterations?: number;\n\n /**\n * Optional private-key storage backend. Required to use `addKeyPair` /\n * `getKeyPair`; absent backends still permit opening, listing, and reading\n * public-key metadata for asymmetric entries.\n */\n readonly privateKeyStorage?: IPrivateKeyStorage;\n}\n\n/**\n * Parameters for opening an existing key store.\n * @public\n */\nexport interface IKeyStoreOpenParams {\n /**\n * Crypto provider to use.\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * The encrypted key store file content.\n */\n readonly keystoreFile: IKeyStoreFile;\n\n /**\n * Optional private-key storage backend. Required to use `addKeyPair` /\n * `getKeyPair`; absent backends still permit opening, listing, and reading\n * public-key metadata for asymmetric entries.\n */\n readonly privateKeyStorage?: IPrivateKeyStorage;\n}\n\n/**\n * Result of adding a secret to the key store.\n * @public\n */\nexport interface IAddSecretResult {\n /**\n * The secret entry that was added.\n */\n readonly entry: IKeyStoreSymmetricEntry;\n\n /**\n * Whether this replaced an existing secret.\n */\n readonly replaced: boolean;\n\n /**\n * Best-effort warning from displaced-resource cleanup. Set when this call\n * replaced an asymmetric-keypair entry but the corresponding\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage}.delete failed; the new\n * entry is still committed and the orphaned blob is left for consumer-side\n * GC to reconcile.\n */\n readonly warning?: string;\n}\n\n/**\n * Options for adding a secret.\n * @public\n */\nexport interface IAddSecretOptions {\n /**\n * Optional description for the secret.\n */\n readonly description?: string;\n}\n\n/**\n * Options for importing a secret.\n * @public\n */\nexport interface IImportSecretOptions extends IAddSecretOptions {\n /**\n * Whether to replace an existing secret with the same name.\n */\n readonly replace?: boolean;\n}\n\n/**\n * Options for importing raw key material via {@link KeyStore.importSecret}.\n * Extends {@link IImportSecretOptions} with a type classification.\n * @public\n */\nexport interface IImportKeyOptions extends IImportSecretOptions {\n /**\n * Symmetric secret type classification for the imported key material.\n * @defaultValue 'encryption-key'\n */\n readonly type?: KeyStoreSymmetricSecretType;\n}\n\n/**\n * Options for adding a secret derived from a password.\n * @public\n */\nexport interface IAddSecretFromPasswordOptions extends IAddSecretOptions {\n /**\n * Whether to replace an existing secret with the same name.\n */\n readonly replace?: boolean;\n\n /**\n * PBKDF2 iterations for key derivation.\n * @defaultValue DEFAULT_SECRET_ITERATIONS (350000)\n */\n readonly iterations?: number;\n}\n\n/**\n * Default PBKDF2 iterations for secret-level key derivation.\n * Lower than keystore encryption since these are used more frequently.\n * @public\n */\nexport const DEFAULT_SECRET_ITERATIONS: number = 350000;\n\n/**\n * Result of adding a password-derived secret.\n * Extends {@link IAddSecretResult} with key derivation parameters\n * needed to store alongside encrypted files.\n * @public\n */\nexport interface IAddSecretFromPasswordResult extends IAddSecretResult {\n /**\n * Key derivation parameters used to derive the secret key.\n * Store these in encrypted file metadata so the password alone\n * can re-derive the same key for decryption.\n */\n readonly keyDerivation: IKeyDerivationParams;\n}\n\n/**\n * Options for adding an Argon2id password-derived secret.\n * @public\n */\nexport interface IAddSecretFromPasswordArgon2idOptions {\n /**\n * Argon2id parameters. Defaults to {@link CryptoUtils.ARGON2ID_OWASP_MIN}.\n */\n readonly params?: IArgon2idParams;\n /**\n * Optional description for the secret.\n */\n readonly description?: string;\n /**\n * Whether to replace an existing secret with the same name.\n */\n readonly replace?: boolean;\n}\n\n/**\n * Options for adding an asymmetric keypair to the key store.\n * @public\n */\nexport interface IAddKeyPairOptions {\n /**\n * Algorithm to use for the new keypair.\n */\n readonly algorithm: KeyPairAlgorithm;\n\n /**\n * Optional description for the entry.\n */\n readonly description?: string;\n\n /**\n * Whether to replace an existing entry with the same name.\n * Replacement mints a fresh storage `id` and best-effort deletes the\n * displaced storage blob; see the keystore design doc for details.\n */\n readonly replace?: boolean;\n\n /**\n * Overrides the storage-backend-derived extractability for this key only.\n * Omit to keep the default (`!privateKeyStorage.supportsNonExtractable`).\n * A value the backend cannot honor fails loudly rather than silently\n * downgrading.\n */\n readonly extractable?: boolean;\n\n /**\n * Opt in to private-key escrow. When `true`, an encrypted copy of the\n * private key (as a JWK) is carried inside the vault entry\n * (`escrowedPrivateKeyJwk`), enabling cross-device recovery from the vault\n * file plus the master password alone via\n * `getKeyPair(name, { rehydrate: true })`.\n *\n * Orthogonal to `extractable`: the escrow copy is always captured (the\n * transient keypair is generated extractable so it can be exported to JWK),\n * while the LIVE stored key's extractability still follows the normal rule\n * (`extractable` override, else the backend default). So escrow does not\n * change how extractable the day-to-day key is — only whether a recovery\n * copy is retained in the vault.\n *\n * @defaultValue false — no escrow copy is written (today's behavior).\n *\n * SECURITY: escrow makes the master password the sole gate protecting a\n * private key that would otherwise be unrecoverable from the vault. Use a\n * strong KDF (Argon2id-derived or high-iteration PBKDF2) for escrow-bearing\n * stores. See the {@link CryptoUtils.KeyStore.KeyStore} class docs.\n */\n readonly escrow?: boolean;\n}\n\n/**\n * Options for retrieving an asymmetric keypair via {@link CryptoUtils.KeyStore.KeyStore.getKeyPair}.\n * @public\n */\nexport interface IGetKeyPairOptions {\n /**\n * Opt in to escrow rehydration. When `true` AND no private-key blob exists\n * under the entry's storage `id` AND the entry carries an\n * `escrowedPrivateKeyJwk`, the escrowed JWK is imported (non-extractable\n * where the backend supports it) and stored under the entry's `id` before\n * being returned — filling a gap on a fresh device from the recovered vault.\n *\n * Fill-a-gap only: an existing storage blob is never overwritten. When a\n * blob is present it is loaded as usual and the escrow copy is ignored.\n *\n * @defaultValue false — today's behavior: load from storage or fail.\n */\n readonly rehydrate?: boolean;\n}\n\n/**\n * Result of adding an asymmetric keypair to the key store.\n * @public\n */\nexport interface IAddKeyPairResult {\n /**\n * The asymmetric entry that was added.\n */\n readonly entry: IKeyStoreAsymmetricEntry;\n\n /**\n * Whether this replaced an existing entry.\n */\n readonly replaced: boolean;\n\n /**\n * Best-effort warning from displaced-resource cleanup. Set when this call\n * replaced a prior entry but the corresponding\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage}.delete failed; the new\n * keypair is still committed and the orphaned blob is left for consumer-side\n * GC to reconcile.\n */\n readonly warning?: string;\n}\n\n/**\n * Result of removing a secret from the key store.\n * @public\n */\nexport interface IRemoveSecretResult {\n /**\n * The secret entry that was removed from the vault.\n */\n readonly entry: IKeyStoreEntry;\n\n /**\n * Best-effort warning from {@link CryptoUtils.KeyStore.IPrivateKeyStorage}.delete\n * for asymmetric entries when the storage call failed. The vault entry is\n * still considered removed and the orphaned blob is left for consumer-side\n * GC to reconcile.\n */\n readonly warning?: string;\n}\n\n// ============================================================================\n// Detection Helper\n// ============================================================================\n\n/**\n * Checks if a JSON object appears to be a key store file.\n * Uses the format field as a discriminator.\n * @param json - JSON object to check\n * @returns true if the object has the key store format field\n * @public\n */\nexport function isKeyStoreFile(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) {\n return false;\n }\n const obj = json as Record<string, unknown>;\n return typeof obj.format === 'string' && (allKeyStoreFormats as ReadonlyArray<string>).includes(obj.format);\n}\n"]}
|
|
@@ -54,6 +54,33 @@ export interface IEncryptionResult {
|
|
|
54
54
|
*/
|
|
55
55
|
readonly encryptedData: Uint8Array;
|
|
56
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Result of a raw-byte AES-256-GCM encryption via
|
|
59
|
+
* {@link CryptoUtils.ICryptoProvider.encryptBytes | encryptBytes}. The
|
|
60
|
+
* authentication tag is returned separately from the ciphertext, mirroring the
|
|
61
|
+
* separated-tag convention of {@link CryptoUtils.IEncryptionResult}. The exact
|
|
62
|
+
* byte layout is:
|
|
63
|
+
* - `ciphertext`: the AES-GCM ciphertext, byte-for-byte the same length as the
|
|
64
|
+
* input plaintext (GCM is a stream cipher — no padding). Empty plaintext
|
|
65
|
+
* yields an empty `ciphertext`.
|
|
66
|
+
* - `authTag`: the 16-byte (128-bit) GCM authentication tag, computed over the
|
|
67
|
+
* ciphertext, the nonce, and any `aad`.
|
|
68
|
+
*
|
|
69
|
+
* The caller persists both fields alongside the (caller-owned) nonce and feeds
|
|
70
|
+
* them back to {@link CryptoUtils.ICryptoProvider.decryptBytes | decryptBytes}.
|
|
71
|
+
* @public
|
|
72
|
+
*/
|
|
73
|
+
export interface IEncryptBytesResult {
|
|
74
|
+
/**
|
|
75
|
+
* The AES-256-GCM ciphertext. Same length as the input plaintext (no tag
|
|
76
|
+
* appended — the tag is carried separately in the `authTag` field).
|
|
77
|
+
*/
|
|
78
|
+
readonly ciphertext: Uint8Array;
|
|
79
|
+
/**
|
|
80
|
+
* The 16-byte (128-bit) GCM authentication tag.
|
|
81
|
+
*/
|
|
82
|
+
readonly authTag: Uint8Array;
|
|
83
|
+
}
|
|
57
84
|
/**
|
|
58
85
|
* Asymmetric keypair algorithms supported by the crypto provider.
|
|
59
86
|
* - `'ecdsa-p256'`: ECDSA over the P-256 curve, for signing.
|
|
@@ -300,6 +327,68 @@ export interface ICryptoProvider {
|
|
|
300
327
|
* @returns Success with decrypted UTF-8 string, or Failure with error
|
|
301
328
|
*/
|
|
302
329
|
decrypt(encryptedData: Uint8Array, key: Uint8Array, iv: Uint8Array, authTag: Uint8Array): Promise<Result<string>>;
|
|
330
|
+
/**
|
|
331
|
+
* Encrypts raw bytes using AES-256-GCM with a **caller-supplied nonce** and
|
|
332
|
+
* optional additional authenticated data (AAD).
|
|
333
|
+
*
|
|
334
|
+
* This is the raw-byte sibling of {@link CryptoUtils.ICryptoProvider.encrypt | encrypt}.
|
|
335
|
+
* Unlike `encrypt`, it takes and returns `Uint8Array` (no UTF-8 coding), the
|
|
336
|
+
* caller owns the nonce (rather than the provider generating one), and it
|
|
337
|
+
* binds optional `aad` into the GCM authentication. Use it when you need to
|
|
338
|
+
* bind context (e.g. an actor id, key version, or row kind) into the
|
|
339
|
+
* authentication so a wrapped secret cannot be replayed across
|
|
340
|
+
* users/versions/kinds, or when you manage nonces yourself.
|
|
341
|
+
*
|
|
342
|
+
* @remarks
|
|
343
|
+
* **⚠️ NONCE UNIQUENESS IS THE CALLER'S RESPONSIBILITY AND IS CRITICAL.**
|
|
344
|
+
* Because the caller supplies the nonce, this primitive cannot guarantee
|
|
345
|
+
* uniqueness. Reusing a `(key, nonce)` pair for two different messages is
|
|
346
|
+
* **catastrophic** for AES-GCM: it breaks confidentiality (the XOR of the two
|
|
347
|
+
* plaintexts leaks) AND authentication (the GCM authentication key can be
|
|
348
|
+
* recovered, letting an attacker forge tags for arbitrary messages under that
|
|
349
|
+
* key). The caller MUST use a unique nonce for every message encrypted under a
|
|
350
|
+
* given key — draw it from {@link CryptoUtils.ICryptoProvider.generateRandomBytes | generateRandomBytes(12)}
|
|
351
|
+
* (12 random bytes has negligible collision probability well within a single
|
|
352
|
+
* key's message budget) or from a strictly-increasing counter. Never hardcode
|
|
353
|
+
* a nonce and never reuse one.
|
|
354
|
+
*
|
|
355
|
+
* @param key - 32-byte AES-256 key. Wrong lengths fail with error context.
|
|
356
|
+
* @param nonce - 12-byte (96-bit) GCM nonce. MUST be unique per message under
|
|
357
|
+
* `key` (see the nonce-uniqueness warning above). Wrong lengths fail with
|
|
358
|
+
* error context.
|
|
359
|
+
* @param plaintext - The bytes to encrypt. Empty plaintext is permitted and
|
|
360
|
+
* round-trips (GCM produces a valid tag over zero-length plaintext).
|
|
361
|
+
* @param aad - Optional additional authenticated data bound into the GCM tag
|
|
362
|
+
* but NOT encrypted. If provided at encrypt time, the identical bytes must be
|
|
363
|
+
* supplied to `decryptBytes` or decryption fails authentication. Absent means
|
|
364
|
+
* no AAD.
|
|
365
|
+
* @returns `Success` with the {@link CryptoUtils.IEncryptBytesResult | ciphertext and 16-byte auth tag},
|
|
366
|
+
* or `Failure` with error context.
|
|
367
|
+
*/
|
|
368
|
+
encryptBytes(key: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array, aad?: Uint8Array): Promise<Result<IEncryptBytesResult>>;
|
|
369
|
+
/**
|
|
370
|
+
* Decrypts raw bytes produced by
|
|
371
|
+
* {@link CryptoUtils.ICryptoProvider.encryptBytes | encryptBytes} using
|
|
372
|
+
* AES-256-GCM. The inverse of `encryptBytes`: the `ciphertext` and `authTag`
|
|
373
|
+
* from an `encryptBytes` result, together with the same `key`, `nonce`, and
|
|
374
|
+
* `aad`, recover the original plaintext.
|
|
375
|
+
*
|
|
376
|
+
* Fails (never throws) on any authentication failure: a tampered ciphertext
|
|
377
|
+
* or tag, the wrong key or nonce, or an `aad` that differs from the one used
|
|
378
|
+
* at encrypt time. AES-GCM authentication is fail-closed — a mismatched `aad`
|
|
379
|
+
* fails exactly as a tampered ciphertext does.
|
|
380
|
+
*
|
|
381
|
+
* @param key - 32-byte AES-256 key (the same key used to encrypt).
|
|
382
|
+
* @param nonce - 12-byte (96-bit) GCM nonce (the same nonce used to encrypt).
|
|
383
|
+
* @param ciphertext - The ciphertext from the `encryptBytes` result.
|
|
384
|
+
* @param authTag - The 16-byte (128-bit) GCM authentication tag from the
|
|
385
|
+
* `encryptBytes` result.
|
|
386
|
+
* @param aad - The identical additional authenticated data supplied at encrypt
|
|
387
|
+
* time (or absent if none was supplied). A mismatch fails authentication.
|
|
388
|
+
* @returns `Success` with the decrypted plaintext bytes, or `Failure` with
|
|
389
|
+
* error context (including all authentication failures).
|
|
390
|
+
*/
|
|
391
|
+
decryptBytes(key: Uint8Array, nonce: Uint8Array, ciphertext: Uint8Array, authTag: Uint8Array, aad?: Uint8Array): Promise<Result<Uint8Array>>;
|
|
303
392
|
/**
|
|
304
393
|
* Generates a random 32-byte key suitable for AES-256.
|
|
305
394
|
* @returns Success with generated key, or Failure with error
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/model.ts"],"names":[],"mappings":"AAoBA,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAEpD,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,CAAC;AAMrB;;;;;;;;GAQG;AACH,MAAM,MAAM,sBAAsB,GAAG,KAAK,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAAC;AAM7E;;;GAGG;AACH,MAAM,MAAM,mBAAmB,GAAG,OAAO,SAAS,CAAC,iBAAiB,CAAC;AAErE;;;GAGG;AACH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CACT,CAAC;AAqFF;;;;GAIG;AACU,QAAA,kBAAkB,GAAoB;IACjD,SAAS,EAAE,KAAK;IAChB,UAAU,EAAE,CAAC;IACb,WAAW,EAAE,CAAC;IACd,WAAW,EAAE,EAAE;CACP,CAAC;AAEX;;;GAGG;AACU,QAAA,mBAAmB,GAAoB;IAClD,SAAS,EAAE,KAAK;IAChB,UAAU,EAAE,CAAC;IACb,WAAW,EAAE,CAAC;IACd,WAAW,EAAE,EAAE;CACP,CAAC;AAubX,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;GAMG;AACH,SAAgB,eAAe,CAAC,IAAa;IAC3C,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;QAC9C,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,GAAG,GAAG,IAA+B,CAAC;IAC5C,OAAO,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,qBAAqB,CAAC;AACxD,CAAC","sourcesContent":["// Copyright (c) 2024 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { JsonValue } from '@fgv/ts-json-base';\nimport { Brand, Result, Uuid } from '@fgv/ts-utils';\n\nimport * as Constants from './constants';\nexport { Constants };\n\n// ============================================================================\n// Public Key Types\n// ============================================================================\n\n/**\n * A multibase base64url-encoded SPKI (SubjectPublicKeyInfo) public key string —\n * a `'m'` multibase prefix followed by a base64url-no-pad body. Produced by\n * {@link CryptoUtils.exportPublicKeyAsMultibaseSpki} and consumed by\n * {@link CryptoUtils.importPublicKeyFromMultibaseSpki}. Obtain the brand at a\n * boundary via {@link CryptoUtils.isValidMultibaseSpkiPublicKey} or the\n * {@link CryptoUtils.Converters.multibaseSpkiPublicKey} converter.\n * @public\n */\nexport type MultibaseSpkiPublicKey = Brand<string, 'MultibaseSpkiPublicKey'>;\n\n// ============================================================================\n// Encryption Types\n// ============================================================================\n\n/**\n * Supported encryption algorithms.\n * @public\n */\nexport type EncryptionAlgorithm = typeof Constants.DEFAULT_ALGORITHM;\n\n/**\n * Format version for encrypted files.\n * @public\n */\nexport type EncryptedFileFormat = typeof Constants.ENCRYPTED_FILE_FORMAT;\n\n/**\n * Named secret for encryption/decryption.\n * @public\n */\nexport interface INamedSecret {\n /**\n * Unique name for this secret (referenced in encrypted files).\n */\n readonly name: string;\n\n /**\n * The actual secret key (32 bytes for AES-256).\n */\n readonly key: Uint8Array;\n}\n\n/**\n * Result of an encryption operation.\n * @public\n */\nexport interface IEncryptionResult {\n /**\n * Initialization vector used for encryption (12 bytes for GCM).\n */\n readonly iv: Uint8Array;\n\n /**\n * Authentication tag from GCM mode (16 bytes).\n */\n readonly authTag: Uint8Array;\n\n /**\n * The encrypted data.\n */\n readonly encryptedData: Uint8Array;\n}\n\n/**\n * Asymmetric keypair algorithms supported by the crypto provider.\n * - `'ecdsa-p256'`: ECDSA over the P-256 curve, for signing.\n * - `'rsa-oaep-2048'`: RSA-OAEP, 2048-bit modulus with SHA-256, for encryption.\n * - `'ecdh-p256'`: ECDH over the P-256 curve, for key agreement\n * (e.g. as the recipient keypair in\n * {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes} /\n * {@link CryptoUtils.ICryptoProvider.unwrapBytes | unwrapBytes}).\n * - `'ed25519'`: EdDSA over the Edwards25519 curve, for signing.\n * Deterministic — the per-signature nonce is derived from the private key\n * and message rather than sampled randomly, eliminating the random-nonce\n * reuse risk that ECDSA carries. Distinct from X25519 (key agreement over\n * the Montgomery form, Curve25519).\n * - `'x25519'`: Diffie-Hellman key agreement over the Montgomery form of\n * Curve25519. Key-agreement only — use `deriveBits`/`deriveKey` to produce\n * a shared secret from one party's private key and the peer's public key.\n * Distinct from Ed25519 (which uses the twisted-Edwards form for signing).\n * @public\n */\nexport type KeyPairAlgorithm = 'ecdsa-p256' | 'rsa-oaep-2048' | 'ecdh-p256' | 'ed25519' | 'x25519';\n\n/**\n * Caller-supplied HKDF parameters that domain-separate one\n * {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes} call from another.\n * Two wraps that share recipient but differ on `salt` or `info` derive distinct\n * wrap keys, so callers should pick values that bind the wrap to its\n * application context (e.g. a content hash for `salt` and a secret name for\n * `info`).\n *\n * Both fields are required; pass an empty `Uint8Array` if the caller has no\n * value to bind on a given axis. Silent defaulting would hide protocol\n * mistakes, so the API does not pick defaults.\n * @public\n */\nexport interface IWrapBytesOptions {\n /**\n * HKDF salt. Domain-separates this wrap from others in different contexts.\n * Caller picks; common choices include a content hash, document id, channel\n * id, etc.\n */\n readonly salt: Uint8Array;\n\n /**\n * HKDF info. Further binds the derived key to a specific use within the\n * calling application. Caller picks; common choices include a secret name,\n * message type, or version tag.\n */\n readonly info: Uint8Array;\n}\n\n/**\n * Output of {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes}. The\n * shape is JSON-serializable so it can travel directly over the wire or be\n * persisted as-is.\n * @public\n */\nexport interface IWrappedBytes {\n /**\n * Sender's ephemeral ECDH P-256 public key as a JSON Web Key. The matching\n * ephemeral private key is dropped after the shared-secret derive.\n */\n readonly ephemeralPublicKey: JsonWebKey;\n\n /**\n * AES-GCM nonce, base64-encoded. 12 bytes (96 bits) — the standard AES-GCM\n * nonce length.\n */\n readonly nonce: string;\n\n /**\n * AES-GCM ciphertext concatenated with the 16-byte authentication tag,\n * base64-encoded. Tampering with either the nonce or the ciphertext causes\n * unwrap to fail GCM authentication.\n */\n readonly ciphertext: string;\n}\n\n/**\n * All valid key pair algorithms.\n * @public\n */\nexport const allKeyPairAlgorithms: ReadonlyArray<KeyPairAlgorithm> = [\n 'ecdsa-p256',\n 'rsa-oaep-2048',\n 'ecdh-p256',\n 'ed25519',\n 'x25519'\n];\n\n/**\n * Supported key derivation functions.\n * @public\n */\nexport type KeyDerivationFunction = 'pbkdf2' | 'argon2id';\n\n/**\n * PBKDF2 key derivation parameters.\n * @public\n */\nexport interface IPbkdf2KeyDerivationParams {\n /** Key derivation function discriminator. */\n readonly kdf: 'pbkdf2';\n /** Base64-encoded salt used for key derivation. */\n readonly salt: string;\n /** Number of iterations used for key derivation. */\n readonly iterations: number;\n}\n\n/**\n * Argon2id key derivation parameters (RFC 9106).\n * @public\n */\nexport interface IArgon2idKeyDerivationParams {\n /** Key derivation function discriminator. */\n readonly kdf: 'argon2id';\n /** Base64-encoded salt used for key derivation. */\n readonly salt: string;\n /** Memory cost in kibibytes. */\n readonly memoryKiB: number;\n /** Number of passes (time cost). */\n readonly iterations: number;\n /** Degree of parallelism. */\n readonly parallelism: number;\n}\n\n/**\n * Key derivation parameters stored in encrypted files.\n * Discriminated union on `kdf` field: `'pbkdf2'` or `'argon2id'`.\n * @public\n */\nexport type IKeyDerivationParams = IPbkdf2KeyDerivationParams | IArgon2idKeyDerivationParams;\n\n// ============================================================================\n// Argon2id Types\n// ============================================================================\n\n/**\n * Parameters for Argon2id key derivation (RFC 9106).\n * All fields are required; fgv does not pick defaults silently.\n * @public\n */\nexport interface IArgon2idParams {\n /**\n * Memory cost in kibibytes (KiB).\n * OWASP 2023 minimum: 19456 (19 MiB). Stronger: 65536 (64 MiB).\n * Constraint: \\>= 8.\n */\n readonly memoryKiB: number;\n\n /**\n * Number of passes (iterations / time cost).\n * OWASP 2023 minimum: 2. Range: \\>= 1.\n */\n readonly iterations: number;\n\n /**\n * Degree of parallelism (threads).\n * Note: WASM-based implementations compute sequentially regardless of this value,\n * but the value is wired into the algorithm and AFFECTS the output hash bytes.\n * Callers must use the same parallelism value consistently for a given secret.\n * Range: 1–255.\n */\n readonly parallelism: number;\n\n /**\n * Number of output bytes (hash length).\n * Typical values: 16 (128-bit), 32 (256-bit, AES-256 key), 64 (512-bit).\n * Constraint: \\>= 4.\n */\n readonly outputBytes: number;\n}\n\n/**\n * Recommended OWASP 2023 minimum Argon2id parameters.\n * Suitable for recovery-row key derivation (high-entropy inputs).\n * @public\n */\nexport const ARGON2ID_OWASP_MIN: IArgon2idParams = {\n memoryKiB: 19456,\n iterations: 2,\n parallelism: 1,\n outputBytes: 32\n} as const;\n\n/**\n * Stronger Argon2id parameters suitable for user-typed passphrases.\n * @public\n */\nexport const ARGON2ID_PASSPHRASE: IArgon2idParams = {\n memoryKiB: 65536,\n iterations: 3,\n parallelism: 1,\n outputBytes: 32\n} as const;\n\n/**\n * Argon2id key derivation provider (RFC 9106).\n *\n * Implementations are in separate packages to avoid WASM bundle costs for\n * consumers who don't need Argon2id:\n * - Node: `@fgv/ts-extras-argon2` (`NodeArgon2Provider`)\n * - Browser: `@fgv/ts-web-extras-argon2` (`BrowserArgon2Provider`)\n *\n * @public\n */\nexport interface IArgon2idProvider {\n /**\n * Derives key material from a password using Argon2id (RFC 9106 §3.1).\n *\n * Returns the raw derived bytes as a `Uint8Array`. Both Node and browser\n * implementations produce bit-identical output for identical inputs.\n *\n * @param password - Password or passphrase. Accepts string (UTF-8) or raw bytes.\n * @param salt - Salt bytes. Must be random and unique per credential (\\>= 16 bytes recommended).\n * @param params - Argon2id parameters. Use `ARGON2ID_OWASP_MIN` as a starting point.\n * @returns Success with derived bytes, Failure with error context.\n */\n argon2id(\n password: Uint8Array | string,\n salt: Uint8Array,\n params: IArgon2idParams\n ): Promise<Result<Uint8Array>>;\n}\n\n/**\n * Generic encrypted file format.\n * This is the JSON structure stored in encrypted files.\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @public\n */\nexport interface IEncryptedFile<TMetadata = JsonValue> {\n /**\n * Format identifier for versioning.\n */\n readonly format: EncryptedFileFormat;\n\n /**\n * Name of the secret required to decrypt (references INamedSecret.name).\n */\n readonly secretName: string;\n\n /**\n * Algorithm used for encryption.\n */\n readonly algorithm: EncryptionAlgorithm;\n\n /**\n * Base64-encoded initialization vector.\n */\n readonly iv: string;\n\n /**\n * Base64-encoded authentication tag (for GCM mode).\n */\n readonly authTag: string;\n\n /**\n * Base64-encoded encrypted data (JSON string when decrypted).\n */\n readonly encryptedData: string;\n\n /**\n * Optional unencrypted metadata for display/filtering.\n */\n readonly metadata?: TMetadata;\n\n /**\n * Optional key derivation parameters.\n * If present, allows decryption using a password with these parameters.\n * If absent, a pre-derived key must be provided.\n */\n readonly keyDerivation?: IKeyDerivationParams;\n}\n\n// ============================================================================\n// Crypto Provider Interface\n// ============================================================================\n\n/**\n * Crypto provider interface for cross-platform encryption.\n * Implementations provided for Node.js (crypto module) and browser (Web Crypto API).\n * @public\n */\nexport interface ICryptoProvider {\n /**\n * Encrypts plaintext using AES-256-GCM.\n * @param plaintext - UTF-8 string to encrypt\n * @param key - 32-byte encryption key\n * @returns Success with encryption result, or Failure with error\n */\n encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>>;\n\n /**\n * Decrypts ciphertext using AES-256-GCM.\n * @param encryptedData - Encrypted bytes\n * @param key - 32-byte decryption key\n * @param iv - Initialization vector (12 bytes)\n * @param authTag - GCM authentication tag (16 bytes)\n * @returns Success with decrypted UTF-8 string, or Failure with error\n */\n decrypt(\n encryptedData: Uint8Array,\n key: Uint8Array,\n iv: Uint8Array,\n authTag: Uint8Array\n ): Promise<Result<string>>;\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns Success with generated key, or Failure with error\n */\n generateKey(): Promise<Result<Uint8Array>>;\n\n /**\n * Derives a key from a password using PBKDF2.\n * @param password - Password string\n * @param salt - Salt bytes (should be at least 16 bytes)\n * @param iterations - Number of iterations (recommend 100000+)\n * @returns Success with derived 32-byte key, or Failure with error\n */\n deriveKey(password: string, salt: Uint8Array, iterations: number): Promise<Result<Uint8Array>>;\n\n /**\n * Computes a SHA-256 hash of the given data.\n * @param data - UTF-8 string to hash\n * @returns Success with hex-encoded hash string, or Failure with error\n */\n sha256(data: string): Promise<Result<string>>;\n\n // ============================================================================\n // Platform Utility Methods\n // ============================================================================\n\n /**\n * Generates cryptographically secure random bytes.\n * @param length - Number of bytes to generate\n * @returns Success with random bytes, or Failure with error\n */\n generateRandomBytes(length: number): Result<Uint8Array>;\n\n /**\n * Generates a cryptographically random UUIDv4 using the provider's\n * underlying source of randomness. The default Node and browser\n * implementations delegate to `globalThis.crypto.randomUUID`;\n * deterministic providers (e.g. test stubs) may override to produce\n * reproducible values.\n * @returns Success with a canonical UUID, or Failure with error.\n */\n generateUuid(): Result<Uuid>;\n\n /**\n * Encodes binary data to base64 string.\n * @param data - Binary data to encode\n * @returns Base64-encoded string\n */\n toBase64(data: Uint8Array): string;\n\n /**\n * Decodes base64 string to binary data.\n * @param base64 - Base64-encoded string\n * @returns Success with decoded bytes, or Failure if invalid base64\n */\n fromBase64(base64: string): Result<Uint8Array>;\n\n // ============================================================================\n // Asymmetric Key Operations\n // ============================================================================\n\n /**\n * Generates a new asymmetric keypair for the requested algorithm.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} to use.\n * @param extractable - Whether the resulting `CryptoKey` objects may be exported.\n * Set `false` on backends that store `CryptoKey` references directly (e.g.\n * IndexedDB). Set `true` when the private key must round-trip through JWK or\n * PKCS#8 (e.g. encrypted-file backends).\n * @returns Success with the generated `CryptoKeyPair`, or Failure with error context.\n */\n generateKeyPair(algorithm: KeyPairAlgorithm, extractable: boolean): Promise<Result<CryptoKeyPair>>;\n\n /**\n * Exports the public half of a keypair as a JSON Web Key.\n * @param publicKey - The public `CryptoKey` to export. Must be an `extractable`\n * key generated for an asymmetric algorithm.\n * @returns Success with the JWK, or Failure with error context.\n */\n exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>>;\n\n /**\n * Re-imports a public-key JWK as a `CryptoKey` usable for verification or\n * encryption (depending on algorithm).\n * @param jwk - The JSON Web Key produced by {@link CryptoUtils.ICryptoProvider.exportPublicKeyJwk | exportPublicKeyJwk}.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} the\n * key was generated for. Determines the import parameters and key usages.\n * @returns Success with the imported public `CryptoKey`, or Failure with error context.\n */\n importPublicKeyJwk(jwk: JsonWebKey, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>>;\n\n /**\n * Exports a public `CryptoKey` as a DER-encoded SPKI (SubjectPublicKeyInfo) blob.\n * SPKI is the standard algorithm-agnostic format for public key storage and transport.\n * @param publicKey - The `CryptoKey` to export. Must have `key.type === 'public'`.\n * @returns `Success` with the raw SPKI bytes, or `Failure` with error context.\n */\n exportPublicKeySpki(publicKey: CryptoKey): Promise<Result<Uint8Array>>;\n\n /**\n * Imports a public key from a DER-encoded SPKI blob.\n * @param spkiBytes - The raw SPKI bytes produced by {@link CryptoUtils.ICryptoProvider.exportPublicKeySpki | exportPublicKeySpki}.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} the key was generated for.\n * @returns `Success` with the imported public `CryptoKey`, or `Failure` with error context.\n */\n importPublicKeySpki(spkiBytes: Uint8Array, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>>;\n\n /**\n * Wraps `plaintext` for delivery to the holder of the private key paired\n * with `recipientPublicKey`. Uses ECIES with ECDH P-256, HKDF-SHA256, and\n * AES-GCM-256.\n *\n * Generates a fresh ephemeral keypair per call; the ephemeral private key\n * is discarded after the shared-secret derive. Only the recipient (with the\n * matching private key) and the same HKDF parameters can recover\n * `plaintext`.\n *\n * Empty `plaintext` is permitted; the resulting wrap contains only the\n * 16-byte GCM authentication tag and round-trips back to an empty\n * `Uint8Array`.\n * @param plaintext - The bytes to wrap. Any length supported by AES-GCM\n * (in practice, well below 2^39 - 256 bits).\n * @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.\n * Must have algorithm name `'ECDH'` and named curve `'P-256'`; mismatched\n * algorithm or curve yields a `Failure` with error context.\n * @param options - HKDF parameters; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.\n * @returns `Success` with the wrapped payload, or `Failure` with error context.\n */\n wrapBytes(\n plaintext: Uint8Array,\n recipientPublicKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<IWrappedBytes>>;\n\n /**\n * Inverse of {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes}.\n * Recovers the original `plaintext` from a wrapped payload using the\n * recipient's private key.\n *\n * Returns a `Failure` (never throws) on any of:\n * - Tampered nonce or ciphertext (AES-GCM authentication fails)\n * - Wrong private key (different shared secret derives a different wrap key)\n * - Wrong HKDF parameters (different wrap key)\n * - Malformed `ephemeralPublicKey` JWK\n * - Malformed base64 in `nonce` or `ciphertext`\n * @param wrapped - The wrapped payload produced by `wrapBytes`.\n * @param recipientPrivateKey - The recipient's ECDH P-256 private\n * `CryptoKey`. Must have algorithm name `'ECDH'` and named curve `'P-256'`,\n * and key usages including `'deriveKey'` or `'deriveBits'`.\n * @param options - The same HKDF parameters used at wrap time.\n * @returns `Success` with the original `plaintext`, or `Failure` with error context.\n */\n unwrapBytes(\n wrapped: IWrappedBytes,\n recipientPrivateKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<Uint8Array>>;\n\n // ============================================================================\n // Signing Operations\n // ============================================================================\n\n /**\n * Signs `data` with `privateKey` using the algorithm inferred from the key.\n * Delegates to `crypto.subtle.sign`; the algorithm is derived from\n * `privateKey.algorithm.name` — ECDSA keys are augmented with\n * `hash: 'SHA-256'` at sign time (the hash is not stored in the key);\n * all other algorithm names are passed through as-is.\n * Intended for Ed25519 and ECDSA-P256 asymmetric private keys; for\n * HMAC-SHA256 authentication codes use {@link ICryptoProvider.hmacSha256} instead.\n * @param privateKey - A `CryptoKey` with `'sign'` usage (e.g. generated by\n * {@link CryptoUtils.ICryptoProvider.generateKeyPair | generateKeyPair} with\n * `'ecdsa-p256'` or `'ed25519'`).\n * @param data - The bytes to sign.\n * @returns `Success` with the raw signature bytes, or `Failure` with error context.\n */\n sign(privateKey: CryptoKey, data: Uint8Array): Promise<Result<Uint8Array>>;\n\n /**\n * Verifies a signature produced by {@link ICryptoProvider.sign}.\n * Delegates to `crypto.subtle.verify`; the algorithm is derived from\n * `publicKey.algorithm.name` — ECDSA keys are augmented with\n * `hash: 'SHA-256'`; all other algorithm names are passed through as-is.\n * Intended for Ed25519 and ECDSA-P256 asymmetric public keys; for\n * HMAC-SHA256 verification use {@link ICryptoProvider.verifyHmacSha256} instead.\n * @param publicKey - A `CryptoKey` with `'verify'` usage (e.g. the public\n * half of a keypair generated by\n * {@link CryptoUtils.ICryptoProvider.generateKeyPair | generateKeyPair} with\n * `'ecdsa-p256'` or `'ed25519'`).\n * @param signature - The raw signature bytes produced by `sign`.\n * @param data - The original data that was signed.\n * @returns `Success` with `true` if the signature is valid, `false` if it is\n * not, or `Failure` with error context if the operation itself failed.\n */\n verify(publicKey: CryptoKey, signature: Uint8Array, data: Uint8Array): Promise<Result<boolean>>;\n\n /**\n * Compares two byte arrays in constant time.\n *\n * The comparison visits all bytes of `a` and `b` regardless of where they\n * diverge, accumulating XOR differences with bitwise-OR. No early-return is\n * possible once the length check passes, making timing independent of the\n * byte values. This prevents timing side-channels when comparing MAC outputs,\n * signed-token bytes, or any secret-derived byte sequences.\n *\n * Returns `false` immediately (before the loop) when `a.length !== b.length`;\n * the length mismatch itself is not secret in normal use.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns `true` if the arrays have the same length and identical contents,\n * `false` otherwise.\n */\n timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;\n\n /**\n * Computes an HMAC-SHA256 authentication code for `data` using `key`.\n *\n * The key must be a `CryptoKey` with `'sign'` usage and algorithm name\n * `'HMAC'` (e.g. derived via PBKDF2 or imported with\n * `crypto.subtle.importKey`). Use {@link ICryptoProvider.verifyHmacSha256}\n * for constant-time verification of the output.\n * @param key - An HMAC `CryptoKey` with `'sign'` usage.\n * @param data - The bytes to authenticate.\n * @returns `Success` with the 32-byte MAC, or `Failure` with error context.\n */\n hmacSha256(key: CryptoKey, data: Uint8Array): Promise<Result<Uint8Array>>;\n\n /**\n * Verifies an HMAC-SHA256 authentication code in constant time.\n *\n * Computes the expected MAC over `data` with `key`, then compares it to\n * `signature` using {@link ICryptoProvider.timingSafeEqual} so that\n * mismatches do not leak information through timing.\n * @param key - An HMAC `CryptoKey` with `'sign'` usage.\n * @param signature - The MAC bytes to verify (typically 32 bytes).\n * @param data - The original data that was authenticated.\n * @returns `Success` with `true` if the MAC is valid, `false` if it is not,\n * or `Failure` with error context if the MAC computation itself failed.\n */\n verifyHmacSha256(key: CryptoKey, signature: Uint8Array, data: Uint8Array): Promise<Result<boolean>>;\n}\n\n// ============================================================================\n// Encryption Provider Interface\n// ============================================================================\n\n/**\n * High-level interface for encrypting JSON content by secret name.\n *\n * This abstraction unifies two common encryption workflows:\n * - **KeyStore**: looks up the named secret and crypto provider from the vault\n * - **DirectEncryptionProvider**: uses a pre-supplied key and crypto provider,\n * optionally bound to a specific secret name for safety\n *\n * Callers that need to encrypt (e.g. `EditableCollection.save()`) depend on\n * this interface rather than on `KeyStore` directly, allowing mix-and-match.\n *\n * @public\n */\nexport interface IEncryptionProvider {\n /**\n * Encrypts JSON content under a named secret.\n *\n * @param secretName - Name of the secret to encrypt with\n * @param content - JSON-safe content to encrypt\n * @param metadata - Optional unencrypted metadata to include in the encrypted file\n * @returns Success with encrypted file structure, or Failure with error context\n */\n encryptByName<TMetadata = JsonValue>(\n secretName: string,\n content: JsonValue,\n metadata?: TMetadata\n ): Promise<Result<IEncryptedFile<TMetadata>>>;\n}\n\n// ============================================================================\n// Encryption Configuration\n// ============================================================================\n\n/**\n * Behavior when an encrypted file cannot be decrypted.\n * @public\n */\nexport type EncryptedFileErrorMode =\n | 'fail' // Return failure, abort loading\n | 'skip' // Skip file silently, continue loading others\n | 'warn'; // Log warning, skip file, continue loading\n\n/**\n * Function type for dynamic secret retrieval.\n * @public\n */\nexport type SecretProvider = (secretName: string) => Promise<Result<Uint8Array>>;\n\n/**\n * Configuration for encrypted file handling during loading.\n * @public\n */\nexport interface IEncryptionConfig {\n /**\n * Named secrets available for decryption.\n */\n readonly secrets?: ReadonlyArray<INamedSecret>;\n\n /**\n * Alternative: dynamic secret provider function.\n * Called when a secret is not found in the secrets array.\n */\n readonly secretProvider?: SecretProvider;\n\n /**\n * Crypto provider implementation (Node.js or browser).\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * Behavior when decryption key is missing (default: 'fail').\n */\n readonly onMissingKey?: EncryptedFileErrorMode;\n\n /**\n * Behavior when decryption fails (default: 'fail').\n */\n readonly onDecryptionError?: EncryptedFileErrorMode;\n}\n\n// ============================================================================\n// Detection Helper\n// ============================================================================\n\n/**\n * Checks if a JSON object appears to be an encrypted file.\n * Uses the format field as a discriminator.\n * @param json - JSON object to check\n * @returns true if the object has the encrypted file format field\n * @public\n */\nexport function isEncryptedFile(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) {\n return false;\n }\n const obj = json as Record<string, unknown>;\n return obj.format === Constants.ENCRYPTED_FILE_FORMAT;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"model.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/model.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuzBZ,0CAMC;AAxzBD,uDAAyC;AAChC,8BAAS;AAgLlB;;;GAGG;AACU,QAAA,oBAAoB,GAAoC;IACnE,YAAY;IACZ,eAAe;IACf,WAAW;IACX,SAAS;IACT,QAAQ;CACT,CAAC;AAqFF;;;;GAIG;AACU,QAAA,kBAAkB,GAAoB;IACjD,SAAS,EAAE,KAAK;IAChB,UAAU,EAAE,CAAC;IACb,WAAW,EAAE,CAAC;IACd,WAAW,EAAE,EAAE;CACP,CAAC;AAEX;;;GAGG;AACU,QAAA,mBAAmB,GAAoB;IAClD,SAAS,EAAE,KAAK;IAChB,UAAU,EAAE,CAAC;IACb,WAAW,EAAE,CAAC;IACd,WAAW,EAAE,EAAE;CACP,CAAC;AAkgBX,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;GAMG;AACH,SAAgB,eAAe,CAAC,IAAa;IAC3C,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;QAC9C,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,GAAG,GAAG,IAA+B,CAAC;IAC5C,OAAO,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,qBAAqB,CAAC;AACxD,CAAC","sourcesContent":["// Copyright (c) 2024 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { JsonValue } from '@fgv/ts-json-base';\nimport { Brand, Result, Uuid } from '@fgv/ts-utils';\n\nimport * as Constants from './constants';\nexport { Constants };\n\n// ============================================================================\n// Public Key Types\n// ============================================================================\n\n/**\n * A multibase base64url-encoded SPKI (SubjectPublicKeyInfo) public key string —\n * a `'m'` multibase prefix followed by a base64url-no-pad body. Produced by\n * {@link CryptoUtils.exportPublicKeyAsMultibaseSpki} and consumed by\n * {@link CryptoUtils.importPublicKeyFromMultibaseSpki}. Obtain the brand at a\n * boundary via {@link CryptoUtils.isValidMultibaseSpkiPublicKey} or the\n * {@link CryptoUtils.Converters.multibaseSpkiPublicKey} converter.\n * @public\n */\nexport type MultibaseSpkiPublicKey = Brand<string, 'MultibaseSpkiPublicKey'>;\n\n// ============================================================================\n// Encryption Types\n// ============================================================================\n\n/**\n * Supported encryption algorithms.\n * @public\n */\nexport type EncryptionAlgorithm = typeof Constants.DEFAULT_ALGORITHM;\n\n/**\n * Format version for encrypted files.\n * @public\n */\nexport type EncryptedFileFormat = typeof Constants.ENCRYPTED_FILE_FORMAT;\n\n/**\n * Named secret for encryption/decryption.\n * @public\n */\nexport interface INamedSecret {\n /**\n * Unique name for this secret (referenced in encrypted files).\n */\n readonly name: string;\n\n /**\n * The actual secret key (32 bytes for AES-256).\n */\n readonly key: Uint8Array;\n}\n\n/**\n * Result of an encryption operation.\n * @public\n */\nexport interface IEncryptionResult {\n /**\n * Initialization vector used for encryption (12 bytes for GCM).\n */\n readonly iv: Uint8Array;\n\n /**\n * Authentication tag from GCM mode (16 bytes).\n */\n readonly authTag: Uint8Array;\n\n /**\n * The encrypted data.\n */\n readonly encryptedData: Uint8Array;\n}\n\n/**\n * Result of a raw-byte AES-256-GCM encryption via\n * {@link CryptoUtils.ICryptoProvider.encryptBytes | encryptBytes}. The\n * authentication tag is returned separately from the ciphertext, mirroring the\n * separated-tag convention of {@link CryptoUtils.IEncryptionResult}. The exact\n * byte layout is:\n * - `ciphertext`: the AES-GCM ciphertext, byte-for-byte the same length as the\n * input plaintext (GCM is a stream cipher — no padding). Empty plaintext\n * yields an empty `ciphertext`.\n * - `authTag`: the 16-byte (128-bit) GCM authentication tag, computed over the\n * ciphertext, the nonce, and any `aad`.\n *\n * The caller persists both fields alongside the (caller-owned) nonce and feeds\n * them back to {@link CryptoUtils.ICryptoProvider.decryptBytes | decryptBytes}.\n * @public\n */\nexport interface IEncryptBytesResult {\n /**\n * The AES-256-GCM ciphertext. Same length as the input plaintext (no tag\n * appended — the tag is carried separately in the `authTag` field).\n */\n readonly ciphertext: Uint8Array;\n\n /**\n * The 16-byte (128-bit) GCM authentication tag.\n */\n readonly authTag: Uint8Array;\n}\n\n/**\n * Asymmetric keypair algorithms supported by the crypto provider.\n * - `'ecdsa-p256'`: ECDSA over the P-256 curve, for signing.\n * - `'rsa-oaep-2048'`: RSA-OAEP, 2048-bit modulus with SHA-256, for encryption.\n * - `'ecdh-p256'`: ECDH over the P-256 curve, for key agreement\n * (e.g. as the recipient keypair in\n * {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes} /\n * {@link CryptoUtils.ICryptoProvider.unwrapBytes | unwrapBytes}).\n * - `'ed25519'`: EdDSA over the Edwards25519 curve, for signing.\n * Deterministic — the per-signature nonce is derived from the private key\n * and message rather than sampled randomly, eliminating the random-nonce\n * reuse risk that ECDSA carries. Distinct from X25519 (key agreement over\n * the Montgomery form, Curve25519).\n * - `'x25519'`: Diffie-Hellman key agreement over the Montgomery form of\n * Curve25519. Key-agreement only — use `deriveBits`/`deriveKey` to produce\n * a shared secret from one party's private key and the peer's public key.\n * Distinct from Ed25519 (which uses the twisted-Edwards form for signing).\n * @public\n */\nexport type KeyPairAlgorithm = 'ecdsa-p256' | 'rsa-oaep-2048' | 'ecdh-p256' | 'ed25519' | 'x25519';\n\n/**\n * Caller-supplied HKDF parameters that domain-separate one\n * {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes} call from another.\n * Two wraps that share recipient but differ on `salt` or `info` derive distinct\n * wrap keys, so callers should pick values that bind the wrap to its\n * application context (e.g. a content hash for `salt` and a secret name for\n * `info`).\n *\n * Both fields are required; pass an empty `Uint8Array` if the caller has no\n * value to bind on a given axis. Silent defaulting would hide protocol\n * mistakes, so the API does not pick defaults.\n * @public\n */\nexport interface IWrapBytesOptions {\n /**\n * HKDF salt. Domain-separates this wrap from others in different contexts.\n * Caller picks; common choices include a content hash, document id, channel\n * id, etc.\n */\n readonly salt: Uint8Array;\n\n /**\n * HKDF info. Further binds the derived key to a specific use within the\n * calling application. Caller picks; common choices include a secret name,\n * message type, or version tag.\n */\n readonly info: Uint8Array;\n}\n\n/**\n * Output of {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes}. The\n * shape is JSON-serializable so it can travel directly over the wire or be\n * persisted as-is.\n * @public\n */\nexport interface IWrappedBytes {\n /**\n * Sender's ephemeral ECDH P-256 public key as a JSON Web Key. The matching\n * ephemeral private key is dropped after the shared-secret derive.\n */\n readonly ephemeralPublicKey: JsonWebKey;\n\n /**\n * AES-GCM nonce, base64-encoded. 12 bytes (96 bits) — the standard AES-GCM\n * nonce length.\n */\n readonly nonce: string;\n\n /**\n * AES-GCM ciphertext concatenated with the 16-byte authentication tag,\n * base64-encoded. Tampering with either the nonce or the ciphertext causes\n * unwrap to fail GCM authentication.\n */\n readonly ciphertext: string;\n}\n\n/**\n * All valid key pair algorithms.\n * @public\n */\nexport const allKeyPairAlgorithms: ReadonlyArray<KeyPairAlgorithm> = [\n 'ecdsa-p256',\n 'rsa-oaep-2048',\n 'ecdh-p256',\n 'ed25519',\n 'x25519'\n];\n\n/**\n * Supported key derivation functions.\n * @public\n */\nexport type KeyDerivationFunction = 'pbkdf2' | 'argon2id';\n\n/**\n * PBKDF2 key derivation parameters.\n * @public\n */\nexport interface IPbkdf2KeyDerivationParams {\n /** Key derivation function discriminator. */\n readonly kdf: 'pbkdf2';\n /** Base64-encoded salt used for key derivation. */\n readonly salt: string;\n /** Number of iterations used for key derivation. */\n readonly iterations: number;\n}\n\n/**\n * Argon2id key derivation parameters (RFC 9106).\n * @public\n */\nexport interface IArgon2idKeyDerivationParams {\n /** Key derivation function discriminator. */\n readonly kdf: 'argon2id';\n /** Base64-encoded salt used for key derivation. */\n readonly salt: string;\n /** Memory cost in kibibytes. */\n readonly memoryKiB: number;\n /** Number of passes (time cost). */\n readonly iterations: number;\n /** Degree of parallelism. */\n readonly parallelism: number;\n}\n\n/**\n * Key derivation parameters stored in encrypted files.\n * Discriminated union on `kdf` field: `'pbkdf2'` or `'argon2id'`.\n * @public\n */\nexport type IKeyDerivationParams = IPbkdf2KeyDerivationParams | IArgon2idKeyDerivationParams;\n\n// ============================================================================\n// Argon2id Types\n// ============================================================================\n\n/**\n * Parameters for Argon2id key derivation (RFC 9106).\n * All fields are required; fgv does not pick defaults silently.\n * @public\n */\nexport interface IArgon2idParams {\n /**\n * Memory cost in kibibytes (KiB).\n * OWASP 2023 minimum: 19456 (19 MiB). Stronger: 65536 (64 MiB).\n * Constraint: \\>= 8.\n */\n readonly memoryKiB: number;\n\n /**\n * Number of passes (iterations / time cost).\n * OWASP 2023 minimum: 2. Range: \\>= 1.\n */\n readonly iterations: number;\n\n /**\n * Degree of parallelism (threads).\n * Note: WASM-based implementations compute sequentially regardless of this value,\n * but the value is wired into the algorithm and AFFECTS the output hash bytes.\n * Callers must use the same parallelism value consistently for a given secret.\n * Range: 1–255.\n */\n readonly parallelism: number;\n\n /**\n * Number of output bytes (hash length).\n * Typical values: 16 (128-bit), 32 (256-bit, AES-256 key), 64 (512-bit).\n * Constraint: \\>= 4.\n */\n readonly outputBytes: number;\n}\n\n/**\n * Recommended OWASP 2023 minimum Argon2id parameters.\n * Suitable for recovery-row key derivation (high-entropy inputs).\n * @public\n */\nexport const ARGON2ID_OWASP_MIN: IArgon2idParams = {\n memoryKiB: 19456,\n iterations: 2,\n parallelism: 1,\n outputBytes: 32\n} as const;\n\n/**\n * Stronger Argon2id parameters suitable for user-typed passphrases.\n * @public\n */\nexport const ARGON2ID_PASSPHRASE: IArgon2idParams = {\n memoryKiB: 65536,\n iterations: 3,\n parallelism: 1,\n outputBytes: 32\n} as const;\n\n/**\n * Argon2id key derivation provider (RFC 9106).\n *\n * Implementations are in separate packages to avoid WASM bundle costs for\n * consumers who don't need Argon2id:\n * - Node: `@fgv/ts-extras-argon2` (`NodeArgon2Provider`)\n * - Browser: `@fgv/ts-web-extras-argon2` (`BrowserArgon2Provider`)\n *\n * @public\n */\nexport interface IArgon2idProvider {\n /**\n * Derives key material from a password using Argon2id (RFC 9106 §3.1).\n *\n * Returns the raw derived bytes as a `Uint8Array`. Both Node and browser\n * implementations produce bit-identical output for identical inputs.\n *\n * @param password - Password or passphrase. Accepts string (UTF-8) or raw bytes.\n * @param salt - Salt bytes. Must be random and unique per credential (\\>= 16 bytes recommended).\n * @param params - Argon2id parameters. Use `ARGON2ID_OWASP_MIN` as a starting point.\n * @returns Success with derived bytes, Failure with error context.\n */\n argon2id(\n password: Uint8Array | string,\n salt: Uint8Array,\n params: IArgon2idParams\n ): Promise<Result<Uint8Array>>;\n}\n\n/**\n * Generic encrypted file format.\n * This is the JSON structure stored in encrypted files.\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @public\n */\nexport interface IEncryptedFile<TMetadata = JsonValue> {\n /**\n * Format identifier for versioning.\n */\n readonly format: EncryptedFileFormat;\n\n /**\n * Name of the secret required to decrypt (references INamedSecret.name).\n */\n readonly secretName: string;\n\n /**\n * Algorithm used for encryption.\n */\n readonly algorithm: EncryptionAlgorithm;\n\n /**\n * Base64-encoded initialization vector.\n */\n readonly iv: string;\n\n /**\n * Base64-encoded authentication tag (for GCM mode).\n */\n readonly authTag: string;\n\n /**\n * Base64-encoded encrypted data (JSON string when decrypted).\n */\n readonly encryptedData: string;\n\n /**\n * Optional unencrypted metadata for display/filtering.\n */\n readonly metadata?: TMetadata;\n\n /**\n * Optional key derivation parameters.\n * If present, allows decryption using a password with these parameters.\n * If absent, a pre-derived key must be provided.\n */\n readonly keyDerivation?: IKeyDerivationParams;\n}\n\n// ============================================================================\n// Crypto Provider Interface\n// ============================================================================\n\n/**\n * Crypto provider interface for cross-platform encryption.\n * Implementations provided for Node.js (crypto module) and browser (Web Crypto API).\n * @public\n */\nexport interface ICryptoProvider {\n /**\n * Encrypts plaintext using AES-256-GCM.\n * @param plaintext - UTF-8 string to encrypt\n * @param key - 32-byte encryption key\n * @returns Success with encryption result, or Failure with error\n */\n encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>>;\n\n /**\n * Decrypts ciphertext using AES-256-GCM.\n * @param encryptedData - Encrypted bytes\n * @param key - 32-byte decryption key\n * @param iv - Initialization vector (12 bytes)\n * @param authTag - GCM authentication tag (16 bytes)\n * @returns Success with decrypted UTF-8 string, or Failure with error\n */\n decrypt(\n encryptedData: Uint8Array,\n key: Uint8Array,\n iv: Uint8Array,\n authTag: Uint8Array\n ): Promise<Result<string>>;\n\n /**\n * Encrypts raw bytes using AES-256-GCM with a **caller-supplied nonce** and\n * optional additional authenticated data (AAD).\n *\n * This is the raw-byte sibling of {@link CryptoUtils.ICryptoProvider.encrypt | encrypt}.\n * Unlike `encrypt`, it takes and returns `Uint8Array` (no UTF-8 coding), the\n * caller owns the nonce (rather than the provider generating one), and it\n * binds optional `aad` into the GCM authentication. Use it when you need to\n * bind context (e.g. an actor id, key version, or row kind) into the\n * authentication so a wrapped secret cannot be replayed across\n * users/versions/kinds, or when you manage nonces yourself.\n *\n * @remarks\n * **⚠️ NONCE UNIQUENESS IS THE CALLER'S RESPONSIBILITY AND IS CRITICAL.**\n * Because the caller supplies the nonce, this primitive cannot guarantee\n * uniqueness. Reusing a `(key, nonce)` pair for two different messages is\n * **catastrophic** for AES-GCM: it breaks confidentiality (the XOR of the two\n * plaintexts leaks) AND authentication (the GCM authentication key can be\n * recovered, letting an attacker forge tags for arbitrary messages under that\n * key). The caller MUST use a unique nonce for every message encrypted under a\n * given key — draw it from {@link CryptoUtils.ICryptoProvider.generateRandomBytes | generateRandomBytes(12)}\n * (12 random bytes has negligible collision probability well within a single\n * key's message budget) or from a strictly-increasing counter. Never hardcode\n * a nonce and never reuse one.\n *\n * @param key - 32-byte AES-256 key. Wrong lengths fail with error context.\n * @param nonce - 12-byte (96-bit) GCM nonce. MUST be unique per message under\n * `key` (see the nonce-uniqueness warning above). Wrong lengths fail with\n * error context.\n * @param plaintext - The bytes to encrypt. Empty plaintext is permitted and\n * round-trips (GCM produces a valid tag over zero-length plaintext).\n * @param aad - Optional additional authenticated data bound into the GCM tag\n * but NOT encrypted. If provided at encrypt time, the identical bytes must be\n * supplied to `decryptBytes` or decryption fails authentication. Absent means\n * no AAD.\n * @returns `Success` with the {@link CryptoUtils.IEncryptBytesResult | ciphertext and 16-byte auth tag},\n * or `Failure` with error context.\n */\n encryptBytes(\n key: Uint8Array,\n nonce: Uint8Array,\n plaintext: Uint8Array,\n aad?: Uint8Array\n ): Promise<Result<IEncryptBytesResult>>;\n\n /**\n * Decrypts raw bytes produced by\n * {@link CryptoUtils.ICryptoProvider.encryptBytes | encryptBytes} using\n * AES-256-GCM. The inverse of `encryptBytes`: the `ciphertext` and `authTag`\n * from an `encryptBytes` result, together with the same `key`, `nonce`, and\n * `aad`, recover the original plaintext.\n *\n * Fails (never throws) on any authentication failure: a tampered ciphertext\n * or tag, the wrong key or nonce, or an `aad` that differs from the one used\n * at encrypt time. AES-GCM authentication is fail-closed — a mismatched `aad`\n * fails exactly as a tampered ciphertext does.\n *\n * @param key - 32-byte AES-256 key (the same key used to encrypt).\n * @param nonce - 12-byte (96-bit) GCM nonce (the same nonce used to encrypt).\n * @param ciphertext - The ciphertext from the `encryptBytes` result.\n * @param authTag - The 16-byte (128-bit) GCM authentication tag from the\n * `encryptBytes` result.\n * @param aad - The identical additional authenticated data supplied at encrypt\n * time (or absent if none was supplied). A mismatch fails authentication.\n * @returns `Success` with the decrypted plaintext bytes, or `Failure` with\n * error context (including all authentication failures).\n */\n decryptBytes(\n key: Uint8Array,\n nonce: Uint8Array,\n ciphertext: Uint8Array,\n authTag: Uint8Array,\n aad?: Uint8Array\n ): Promise<Result<Uint8Array>>;\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns Success with generated key, or Failure with error\n */\n generateKey(): Promise<Result<Uint8Array>>;\n\n /**\n * Derives a key from a password using PBKDF2.\n * @param password - Password string\n * @param salt - Salt bytes (should be at least 16 bytes)\n * @param iterations - Number of iterations (recommend 100000+)\n * @returns Success with derived 32-byte key, or Failure with error\n */\n deriveKey(password: string, salt: Uint8Array, iterations: number): Promise<Result<Uint8Array>>;\n\n /**\n * Computes a SHA-256 hash of the given data.\n * @param data - UTF-8 string to hash\n * @returns Success with hex-encoded hash string, or Failure with error\n */\n sha256(data: string): Promise<Result<string>>;\n\n // ============================================================================\n // Platform Utility Methods\n // ============================================================================\n\n /**\n * Generates cryptographically secure random bytes.\n * @param length - Number of bytes to generate\n * @returns Success with random bytes, or Failure with error\n */\n generateRandomBytes(length: number): Result<Uint8Array>;\n\n /**\n * Generates a cryptographically random UUIDv4 using the provider's\n * underlying source of randomness. The default Node and browser\n * implementations delegate to `globalThis.crypto.randomUUID`;\n * deterministic providers (e.g. test stubs) may override to produce\n * reproducible values.\n * @returns Success with a canonical UUID, or Failure with error.\n */\n generateUuid(): Result<Uuid>;\n\n /**\n * Encodes binary data to base64 string.\n * @param data - Binary data to encode\n * @returns Base64-encoded string\n */\n toBase64(data: Uint8Array): string;\n\n /**\n * Decodes base64 string to binary data.\n * @param base64 - Base64-encoded string\n * @returns Success with decoded bytes, or Failure if invalid base64\n */\n fromBase64(base64: string): Result<Uint8Array>;\n\n // ============================================================================\n // Asymmetric Key Operations\n // ============================================================================\n\n /**\n * Generates a new asymmetric keypair for the requested algorithm.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} to use.\n * @param extractable - Whether the resulting `CryptoKey` objects may be exported.\n * Set `false` on backends that store `CryptoKey` references directly (e.g.\n * IndexedDB). Set `true` when the private key must round-trip through JWK or\n * PKCS#8 (e.g. encrypted-file backends).\n * @returns Success with the generated `CryptoKeyPair`, or Failure with error context.\n */\n generateKeyPair(algorithm: KeyPairAlgorithm, extractable: boolean): Promise<Result<CryptoKeyPair>>;\n\n /**\n * Exports the public half of a keypair as a JSON Web Key.\n * @param publicKey - The public `CryptoKey` to export. Must be an `extractable`\n * key generated for an asymmetric algorithm.\n * @returns Success with the JWK, or Failure with error context.\n */\n exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>>;\n\n /**\n * Re-imports a public-key JWK as a `CryptoKey` usable for verification or\n * encryption (depending on algorithm).\n * @param jwk - The JSON Web Key produced by {@link CryptoUtils.ICryptoProvider.exportPublicKeyJwk | exportPublicKeyJwk}.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} the\n * key was generated for. Determines the import parameters and key usages.\n * @returns Success with the imported public `CryptoKey`, or Failure with error context.\n */\n importPublicKeyJwk(jwk: JsonWebKey, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>>;\n\n /**\n * Exports a public `CryptoKey` as a DER-encoded SPKI (SubjectPublicKeyInfo) blob.\n * SPKI is the standard algorithm-agnostic format for public key storage and transport.\n * @param publicKey - The `CryptoKey` to export. Must have `key.type === 'public'`.\n * @returns `Success` with the raw SPKI bytes, or `Failure` with error context.\n */\n exportPublicKeySpki(publicKey: CryptoKey): Promise<Result<Uint8Array>>;\n\n /**\n * Imports a public key from a DER-encoded SPKI blob.\n * @param spkiBytes - The raw SPKI bytes produced by {@link CryptoUtils.ICryptoProvider.exportPublicKeySpki | exportPublicKeySpki}.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} the key was generated for.\n * @returns `Success` with the imported public `CryptoKey`, or `Failure` with error context.\n */\n importPublicKeySpki(spkiBytes: Uint8Array, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>>;\n\n /**\n * Wraps `plaintext` for delivery to the holder of the private key paired\n * with `recipientPublicKey`. Uses ECIES with ECDH P-256, HKDF-SHA256, and\n * AES-GCM-256.\n *\n * Generates a fresh ephemeral keypair per call; the ephemeral private key\n * is discarded after the shared-secret derive. Only the recipient (with the\n * matching private key) and the same HKDF parameters can recover\n * `plaintext`.\n *\n * Empty `plaintext` is permitted; the resulting wrap contains only the\n * 16-byte GCM authentication tag and round-trips back to an empty\n * `Uint8Array`.\n * @param plaintext - The bytes to wrap. Any length supported by AES-GCM\n * (in practice, well below 2^39 - 256 bits).\n * @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.\n * Must have algorithm name `'ECDH'` and named curve `'P-256'`; mismatched\n * algorithm or curve yields a `Failure` with error context.\n * @param options - HKDF parameters; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.\n * @returns `Success` with the wrapped payload, or `Failure` with error context.\n */\n wrapBytes(\n plaintext: Uint8Array,\n recipientPublicKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<IWrappedBytes>>;\n\n /**\n * Inverse of {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes}.\n * Recovers the original `plaintext` from a wrapped payload using the\n * recipient's private key.\n *\n * Returns a `Failure` (never throws) on any of:\n * - Tampered nonce or ciphertext (AES-GCM authentication fails)\n * - Wrong private key (different shared secret derives a different wrap key)\n * - Wrong HKDF parameters (different wrap key)\n * - Malformed `ephemeralPublicKey` JWK\n * - Malformed base64 in `nonce` or `ciphertext`\n * @param wrapped - The wrapped payload produced by `wrapBytes`.\n * @param recipientPrivateKey - The recipient's ECDH P-256 private\n * `CryptoKey`. Must have algorithm name `'ECDH'` and named curve `'P-256'`,\n * and key usages including `'deriveKey'` or `'deriveBits'`.\n * @param options - The same HKDF parameters used at wrap time.\n * @returns `Success` with the original `plaintext`, or `Failure` with error context.\n */\n unwrapBytes(\n wrapped: IWrappedBytes,\n recipientPrivateKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<Uint8Array>>;\n\n // ============================================================================\n // Signing Operations\n // ============================================================================\n\n /**\n * Signs `data` with `privateKey` using the algorithm inferred from the key.\n * Delegates to `crypto.subtle.sign`; the algorithm is derived from\n * `privateKey.algorithm.name` — ECDSA keys are augmented with\n * `hash: 'SHA-256'` at sign time (the hash is not stored in the key);\n * all other algorithm names are passed through as-is.\n * Intended for Ed25519 and ECDSA-P256 asymmetric private keys; for\n * HMAC-SHA256 authentication codes use {@link ICryptoProvider.hmacSha256} instead.\n * @param privateKey - A `CryptoKey` with `'sign'` usage (e.g. generated by\n * {@link CryptoUtils.ICryptoProvider.generateKeyPair | generateKeyPair} with\n * `'ecdsa-p256'` or `'ed25519'`).\n * @param data - The bytes to sign.\n * @returns `Success` with the raw signature bytes, or `Failure` with error context.\n */\n sign(privateKey: CryptoKey, data: Uint8Array): Promise<Result<Uint8Array>>;\n\n /**\n * Verifies a signature produced by {@link ICryptoProvider.sign}.\n * Delegates to `crypto.subtle.verify`; the algorithm is derived from\n * `publicKey.algorithm.name` — ECDSA keys are augmented with\n * `hash: 'SHA-256'`; all other algorithm names are passed through as-is.\n * Intended for Ed25519 and ECDSA-P256 asymmetric public keys; for\n * HMAC-SHA256 verification use {@link ICryptoProvider.verifyHmacSha256} instead.\n * @param publicKey - A `CryptoKey` with `'verify'` usage (e.g. the public\n * half of a keypair generated by\n * {@link CryptoUtils.ICryptoProvider.generateKeyPair | generateKeyPair} with\n * `'ecdsa-p256'` or `'ed25519'`).\n * @param signature - The raw signature bytes produced by `sign`.\n * @param data - The original data that was signed.\n * @returns `Success` with `true` if the signature is valid, `false` if it is\n * not, or `Failure` with error context if the operation itself failed.\n */\n verify(publicKey: CryptoKey, signature: Uint8Array, data: Uint8Array): Promise<Result<boolean>>;\n\n /**\n * Compares two byte arrays in constant time.\n *\n * The comparison visits all bytes of `a` and `b` regardless of where they\n * diverge, accumulating XOR differences with bitwise-OR. No early-return is\n * possible once the length check passes, making timing independent of the\n * byte values. This prevents timing side-channels when comparing MAC outputs,\n * signed-token bytes, or any secret-derived byte sequences.\n *\n * Returns `false` immediately (before the loop) when `a.length !== b.length`;\n * the length mismatch itself is not secret in normal use.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns `true` if the arrays have the same length and identical contents,\n * `false` otherwise.\n */\n timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;\n\n /**\n * Computes an HMAC-SHA256 authentication code for `data` using `key`.\n *\n * The key must be a `CryptoKey` with `'sign'` usage and algorithm name\n * `'HMAC'` (e.g. derived via PBKDF2 or imported with\n * `crypto.subtle.importKey`). Use {@link ICryptoProvider.verifyHmacSha256}\n * for constant-time verification of the output.\n * @param key - An HMAC `CryptoKey` with `'sign'` usage.\n * @param data - The bytes to authenticate.\n * @returns `Success` with the 32-byte MAC, or `Failure` with error context.\n */\n hmacSha256(key: CryptoKey, data: Uint8Array): Promise<Result<Uint8Array>>;\n\n /**\n * Verifies an HMAC-SHA256 authentication code in constant time.\n *\n * Computes the expected MAC over `data` with `key`, then compares it to\n * `signature` using {@link ICryptoProvider.timingSafeEqual} so that\n * mismatches do not leak information through timing.\n * @param key - An HMAC `CryptoKey` with `'sign'` usage.\n * @param signature - The MAC bytes to verify (typically 32 bytes).\n * @param data - The original data that was authenticated.\n * @returns `Success` with `true` if the MAC is valid, `false` if it is not,\n * or `Failure` with error context if the MAC computation itself failed.\n */\n verifyHmacSha256(key: CryptoKey, signature: Uint8Array, data: Uint8Array): Promise<Result<boolean>>;\n}\n\n// ============================================================================\n// Encryption Provider Interface\n// ============================================================================\n\n/**\n * High-level interface for encrypting JSON content by secret name.\n *\n * This abstraction unifies two common encryption workflows:\n * - **KeyStore**: looks up the named secret and crypto provider from the vault\n * - **DirectEncryptionProvider**: uses a pre-supplied key and crypto provider,\n * optionally bound to a specific secret name for safety\n *\n * Callers that need to encrypt (e.g. `EditableCollection.save()`) depend on\n * this interface rather than on `KeyStore` directly, allowing mix-and-match.\n *\n * @public\n */\nexport interface IEncryptionProvider {\n /**\n * Encrypts JSON content under a named secret.\n *\n * @param secretName - Name of the secret to encrypt with\n * @param content - JSON-safe content to encrypt\n * @param metadata - Optional unencrypted metadata to include in the encrypted file\n * @returns Success with encrypted file structure, or Failure with error context\n */\n encryptByName<TMetadata = JsonValue>(\n secretName: string,\n content: JsonValue,\n metadata?: TMetadata\n ): Promise<Result<IEncryptedFile<TMetadata>>>;\n}\n\n// ============================================================================\n// Encryption Configuration\n// ============================================================================\n\n/**\n * Behavior when an encrypted file cannot be decrypted.\n * @public\n */\nexport type EncryptedFileErrorMode =\n | 'fail' // Return failure, abort loading\n | 'skip' // Skip file silently, continue loading others\n | 'warn'; // Log warning, skip file, continue loading\n\n/**\n * Function type for dynamic secret retrieval.\n * @public\n */\nexport type SecretProvider = (secretName: string) => Promise<Result<Uint8Array>>;\n\n/**\n * Configuration for encrypted file handling during loading.\n * @public\n */\nexport interface IEncryptionConfig {\n /**\n * Named secrets available for decryption.\n */\n readonly secrets?: ReadonlyArray<INamedSecret>;\n\n /**\n * Alternative: dynamic secret provider function.\n * Called when a secret is not found in the secrets array.\n */\n readonly secretProvider?: SecretProvider;\n\n /**\n * Crypto provider implementation (Node.js or browser).\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * Behavior when decryption key is missing (default: 'fail').\n */\n readonly onMissingKey?: EncryptedFileErrorMode;\n\n /**\n * Behavior when decryption fails (default: 'fail').\n */\n readonly onDecryptionError?: EncryptedFileErrorMode;\n}\n\n// ============================================================================\n// Detection Helper\n// ============================================================================\n\n/**\n * Checks if a JSON object appears to be an encrypted file.\n * Uses the format field as a discriminator.\n * @param json - JSON object to check\n * @returns true if the object has the encrypted file format field\n * @public\n */\nexport function isEncryptedFile(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) {\n return false;\n }\n const obj = json as Record<string, unknown>;\n return obj.format === Constants.ENCRYPTED_FILE_FORMAT;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Result, Uuid } from '@fgv/ts-utils';
|
|
2
|
-
import { ICryptoProvider, IEncryptionResult, IWrapBytesOptions, IWrappedBytes, KeyPairAlgorithm } from './model';
|
|
2
|
+
import { ICryptoProvider, IEncryptBytesResult, IEncryptionResult, IWrapBytesOptions, IWrappedBytes, KeyPairAlgorithm } from './model';
|
|
3
3
|
/**
|
|
4
4
|
* Node.js implementation of {@link CryptoUtils.ICryptoProvider} using the built-in crypto module.
|
|
5
5
|
* Uses AES-256-GCM for authenticated encryption.
|
|
@@ -22,6 +22,30 @@ export declare class NodeCryptoProvider implements ICryptoProvider {
|
|
|
22
22
|
* @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.
|
|
23
23
|
*/
|
|
24
24
|
decrypt(encryptedData: Uint8Array, key: Uint8Array, iv: Uint8Array, authTag: Uint8Array): Promise<Result<string>>;
|
|
25
|
+
/**
|
|
26
|
+
* Encrypts raw bytes using AES-256-GCM with a caller-supplied nonce and
|
|
27
|
+
* optional AAD. See {@link CryptoUtils.ICryptoProvider.encryptBytes | ICryptoProvider.encryptBytes}
|
|
28
|
+
* — in particular the caller's responsibility to use a unique `nonce` per
|
|
29
|
+
* message under a given `key`.
|
|
30
|
+
* @param key - 32-byte AES-256 key.
|
|
31
|
+
* @param nonce - 12-byte GCM nonce (must be unique per message under `key`).
|
|
32
|
+
* @param plaintext - The bytes to encrypt (empty permitted).
|
|
33
|
+
* @param aad - Optional additional authenticated data bound into the tag.
|
|
34
|
+
* @returns `Success` with the ciphertext and 16-byte auth tag, or `Failure` with an error.
|
|
35
|
+
*/
|
|
36
|
+
encryptBytes(key: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array, aad?: Uint8Array): Promise<Result<IEncryptBytesResult>>;
|
|
37
|
+
/**
|
|
38
|
+
* Decrypts raw bytes produced by {@link NodeCryptoProvider.encryptBytes} using
|
|
39
|
+
* AES-256-GCM. See {@link CryptoUtils.ICryptoProvider.decryptBytes | ICryptoProvider.decryptBytes}.
|
|
40
|
+
* Fails (never throws) on any authentication failure, including a mismatched `aad`.
|
|
41
|
+
* @param key - 32-byte AES-256 key.
|
|
42
|
+
* @param nonce - 12-byte GCM nonce (the same one used to encrypt).
|
|
43
|
+
* @param ciphertext - The ciphertext from the `encryptBytes` result.
|
|
44
|
+
* @param authTag - The 16-byte GCM auth tag from the `encryptBytes` result.
|
|
45
|
+
* @param aad - The identical AAD supplied at encrypt time (or absent).
|
|
46
|
+
* @returns `Success` with the decrypted plaintext bytes, or `Failure` with an error.
|
|
47
|
+
*/
|
|
48
|
+
decryptBytes(key: Uint8Array, nonce: Uint8Array, ciphertext: Uint8Array, authTag: Uint8Array, aad?: Uint8Array): Promise<Result<Uint8Array>>;
|
|
25
49
|
/**
|
|
26
50
|
* Generates a random 32-byte key suitable for AES-256.
|
|
27
51
|
* @returns `Success` with generated key, or `Failure` with an error.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nodeCryptoProvider.d.ts","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/nodeCryptoProvider.ts"],"names":[],"mappings":"AAqBA,OAAO,EAML,MAAM,EAGN,IAAI,EACL,MAAM,eAAe,CAAC;AAGvB,OAAO,EACL,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,aAAa,EACb,gBAAgB,EACjB,MAAM,SAAS,CAAC;AAEjB;;;;GAIG;AACH,qBAAa,kBAAmB,YAAW,eAAe;IACxD;;;;;OAKG;IACU,OAAO,CAA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D;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,kBAA6C,CAAC"}
|
|
1
|
+
{"version":3,"file":"nodeCryptoProvider.d.ts","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/nodeCryptoProvider.ts"],"names":[],"mappings":"AAqBA,OAAO,EAML,MAAM,EAGN,IAAI,EACL,MAAM,eAAe,CAAC;AAGvB,OAAO,EACL,eAAe,EACf,mBAAmB,EACnB,iBAAiB,EACjB,iBAAiB,EACjB,aAAa,EACb,gBAAgB,EACjB,MAAM,SAAS,CAAC;AAEjB;;;;GAIG;AACH,qBAAa,kBAAmB,YAAW,eAAe;IACxD;;;;;OAKG;IACU,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;IA0B5F;;;;;;;OAOG;IACU,OAAO,CAClB,aAAa,EAAE,UAAU,EACzB,GAAG,EAAE,UAAU,EACf,EAAE,EAAE,UAAU,EACd,OAAO,EAAE,UAAU,GAClB,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAyB1B;;;;;;;;;;OAUG;IACU,YAAY,CACvB,GAAG,EAAE,UAAU,EACf,KAAK,EAAE,UAAU,EACjB,SAAS,EAAE,UAAU,EACrB,GAAG,CAAC,EAAE,UAAU,GACf,OAAO,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC;IAwBvC;;;;;;;;;;OAUG;IACU,YAAY,CACvB,GAAG,EAAE,UAAU,EACf,KAAK,EAAE,UAAU,EACjB,UAAU,EAAE,UAAU,EACtB,OAAO,EAAE,UAAU,EACnB,GAAG,CAAC,EAAE,UAAU,GACf,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IA0B9B;;;OAGG;IACU,WAAW,IAAI,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAOvD;;;;;;OAMG;IACU,SAAS,CACpB,QAAQ,EAAE,MAAM,EAChB,IAAI,E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ACjB,SAAS,EAAE,SAAS,EACpB,SAAS,EAAE,UAAU,EACrB,IAAI,EAAE,UAAU,GACf,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAQ3B;;;;;;;OAOG;IACI,eAAe,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,GAAG,OAAO;IAK7D;;;;;OAKG;IACU,UAAU,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAOtF;;;;;;OAMG;IACU,gBAAgB,CAC3B,GAAG,EAAE,SAAS,EACd,SAAS,EAAE,UAAU,EACrB,IAAI,EAAE,UAAU,GACf,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAM3B;;;;;;;;OAQG;IACU,SAAS,CACpB,SAAS,EAAE,UAAU,EACrB,kBAAkB,EAAE,SAAS,EAC7B,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAoCjC;;;;;;;OAOG;IACU,WAAW,CACtB,OAAO,EAAE,aAAa,EACtB,mBAAmB,EAAE,SAAS,EAC9B,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;CAuD/B;AA2CD;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,kBAA6C,CAAC"}
|
|
@@ -117,6 +117,72 @@ class NodeCryptoProvider {
|
|
|
117
117
|
return decrypted.toString('utf8');
|
|
118
118
|
}).withErrorFormat((e) => `Decryption failed: ${e}`);
|
|
119
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Encrypts raw bytes using AES-256-GCM with a caller-supplied nonce and
|
|
122
|
+
* optional AAD. See {@link CryptoUtils.ICryptoProvider.encryptBytes | ICryptoProvider.encryptBytes}
|
|
123
|
+
* — in particular the caller's responsibility to use a unique `nonce` per
|
|
124
|
+
* message under a given `key`.
|
|
125
|
+
* @param key - 32-byte AES-256 key.
|
|
126
|
+
* @param nonce - 12-byte GCM nonce (must be unique per message under `key`).
|
|
127
|
+
* @param plaintext - The bytes to encrypt (empty permitted).
|
|
128
|
+
* @param aad - Optional additional authenticated data bound into the tag.
|
|
129
|
+
* @returns `Success` with the ciphertext and 16-byte auth tag, or `Failure` with an error.
|
|
130
|
+
*/
|
|
131
|
+
async encryptBytes(key, nonce, plaintext, aad) {
|
|
132
|
+
if (key.length !== Constants.AES_256_KEY_SIZE) {
|
|
133
|
+
return (0, ts_utils_1.fail)(`encryptBytes: key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);
|
|
134
|
+
}
|
|
135
|
+
if (nonce.length !== Constants.GCM_IV_SIZE) {
|
|
136
|
+
return (0, ts_utils_1.fail)(`encryptBytes: nonce must be ${Constants.GCM_IV_SIZE} bytes, got ${nonce.length}`);
|
|
137
|
+
}
|
|
138
|
+
return (0, ts_utils_1.captureResult)(() => {
|
|
139
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', Buffer.from(key), Buffer.from(nonce), {
|
|
140
|
+
authTagLength: Constants.GCM_AUTH_TAG_SIZE
|
|
141
|
+
});
|
|
142
|
+
if (aad !== undefined) {
|
|
143
|
+
cipher.setAAD(Buffer.from(aad));
|
|
144
|
+
}
|
|
145
|
+
const encrypted = Buffer.concat([cipher.update(Buffer.from(plaintext)), cipher.final()]);
|
|
146
|
+
const authTag = cipher.getAuthTag();
|
|
147
|
+
return {
|
|
148
|
+
ciphertext: new Uint8Array(encrypted),
|
|
149
|
+
authTag: new Uint8Array(authTag)
|
|
150
|
+
};
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Decrypts raw bytes produced by {@link NodeCryptoProvider.encryptBytes} using
|
|
155
|
+
* AES-256-GCM. See {@link CryptoUtils.ICryptoProvider.decryptBytes | ICryptoProvider.decryptBytes}.
|
|
156
|
+
* Fails (never throws) on any authentication failure, including a mismatched `aad`.
|
|
157
|
+
* @param key - 32-byte AES-256 key.
|
|
158
|
+
* @param nonce - 12-byte GCM nonce (the same one used to encrypt).
|
|
159
|
+
* @param ciphertext - The ciphertext from the `encryptBytes` result.
|
|
160
|
+
* @param authTag - The 16-byte GCM auth tag from the `encryptBytes` result.
|
|
161
|
+
* @param aad - The identical AAD supplied at encrypt time (or absent).
|
|
162
|
+
* @returns `Success` with the decrypted plaintext bytes, or `Failure` with an error.
|
|
163
|
+
*/
|
|
164
|
+
async decryptBytes(key, nonce, ciphertext, authTag, aad) {
|
|
165
|
+
if (key.length !== Constants.AES_256_KEY_SIZE) {
|
|
166
|
+
return (0, ts_utils_1.fail)(`decryptBytes: key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);
|
|
167
|
+
}
|
|
168
|
+
if (nonce.length !== Constants.GCM_IV_SIZE) {
|
|
169
|
+
return (0, ts_utils_1.fail)(`decryptBytes: nonce must be ${Constants.GCM_IV_SIZE} bytes, got ${nonce.length}`);
|
|
170
|
+
}
|
|
171
|
+
if (authTag.length !== Constants.GCM_AUTH_TAG_SIZE) {
|
|
172
|
+
return (0, ts_utils_1.fail)(`decryptBytes: auth tag must be ${Constants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`);
|
|
173
|
+
}
|
|
174
|
+
return (0, ts_utils_1.captureResult)(() => {
|
|
175
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(key), Buffer.from(nonce), {
|
|
176
|
+
authTagLength: Constants.GCM_AUTH_TAG_SIZE
|
|
177
|
+
});
|
|
178
|
+
if (aad !== undefined) {
|
|
179
|
+
decipher.setAAD(Buffer.from(aad));
|
|
180
|
+
}
|
|
181
|
+
decipher.setAuthTag(Buffer.from(authTag));
|
|
182
|
+
const decrypted = Buffer.concat([decipher.update(Buffer.from(ciphertext)), decipher.final()]);
|
|
183
|
+
return new Uint8Array(decrypted);
|
|
184
|
+
}).withErrorFormat((e) => `decryptBytes failed: ${e}`);
|
|
185
|
+
}
|
|
120
186
|
/**
|
|
121
187
|
* Generates a random 32-byte key suitable for AES-256.
|
|
122
188
|
* @returns `Success` with generated key, or `Failure` with an error.
|