@fgv/ts-extras 5.1.0-2 → 5.1.0-20
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/index.browser.js +2 -1
- package/dist/index.browser.js.map +1 -0
- package/dist/index.js.map +1 -0
- package/dist/packlets/ai-assist/apiClient.js +792 -57
- package/dist/packlets/ai-assist/apiClient.js.map +1 -0
- package/dist/packlets/ai-assist/chatRequestBuilders.js +180 -0
- package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -0
- package/dist/packlets/ai-assist/converters.js.map +1 -0
- package/dist/packlets/ai-assist/index.js +4 -3
- package/dist/packlets/ai-assist/index.js.map +1 -0
- package/dist/packlets/ai-assist/model.js +20 -3
- package/dist/packlets/ai-assist/model.js.map +1 -0
- package/dist/packlets/ai-assist/registry.js +111 -10
- package/dist/packlets/ai-assist/registry.js.map +1 -0
- package/dist/packlets/ai-assist/sseParser.js +122 -0
- package/dist/packlets/ai-assist/sseParser.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +192 -0
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/common.js +77 -0
- package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js +160 -0
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +149 -0
- package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +163 -0
- package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/proxy.js +157 -0
- package/dist/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -0
- package/dist/packlets/ai-assist/streamingClient.js +88 -0
- package/dist/packlets/ai-assist/streamingClient.js.map +1 -0
- package/dist/packlets/ai-assist/toolFormats.js.map +1 -0
- package/dist/packlets/conversion/converters.js +34 -1
- package/dist/packlets/conversion/converters.js.map +1 -0
- package/dist/packlets/conversion/index.js.map +1 -0
- package/dist/packlets/crypto-utils/constants.js.map +1 -0
- package/dist/packlets/crypto-utils/converters.js.map +1 -0
- package/dist/packlets/crypto-utils/directEncryptionProvider.js.map +1 -0
- package/dist/packlets/crypto-utils/encryptedFile.js.map +1 -0
- package/dist/packlets/crypto-utils/index.browser.js +2 -0
- package/dist/packlets/crypto-utils/index.browser.js.map +1 -0
- package/dist/packlets/crypto-utils/index.js +2 -0
- package/dist/packlets/crypto-utils/index.js.map +1 -0
- package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js +57 -0
- package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/converters.js +101 -9
- package/dist/packlets/crypto-utils/keystore/converters.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/index.js +1 -0
- package/dist/packlets/crypto-utils/keystore/index.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/keyStore.js +431 -118
- package/dist/packlets/crypto-utils/keystore/keyStore.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/model.js +22 -1
- package/dist/packlets/crypto-utils/keystore/model.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/privateKeyStorage.js +21 -0
- package/dist/packlets/crypto-utils/keystore/privateKeyStorage.js.map +1 -0
- package/dist/packlets/crypto-utils/model.js +9 -0
- package/dist/packlets/crypto-utils/model.js.map +1 -0
- package/dist/packlets/crypto-utils/nodeCryptoProvider.js +152 -1
- package/dist/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -0
- package/dist/packlets/csv/csvFileHelpers.js.map +1 -0
- package/dist/packlets/csv/csvHelpers.js.map +1 -0
- package/dist/packlets/csv/index.browser.js.map +1 -0
- package/dist/packlets/csv/index.js.map +1 -0
- package/dist/packlets/experimental/extendedArray.js.map +1 -0
- package/dist/packlets/experimental/formatter.js.map +1 -0
- package/dist/packlets/experimental/index.js.map +1 -0
- package/dist/packlets/experimental/rangeOf.js.map +1 -0
- package/dist/packlets/hash/index.browser.js.map +1 -0
- package/dist/packlets/hash/index.js.map +1 -0
- package/dist/packlets/hash/index.node.js.map +1 -0
- package/dist/packlets/hash/md5Normalizer.browser.js.map +1 -0
- package/dist/packlets/hash/md5Normalizer.js.map +1 -0
- package/dist/packlets/mustache/index.js.map +1 -0
- package/dist/packlets/mustache/interfaces.js.map +1 -0
- package/dist/packlets/mustache/mustacheTemplate.js.map +1 -0
- package/dist/packlets/record-jar/index.browser.js.map +1 -0
- package/dist/packlets/record-jar/index.js.map +1 -0
- package/dist/packlets/record-jar/recordJarFileHelpers.js.map +1 -0
- package/dist/packlets/record-jar/recordJarHelpers.js.map +1 -0
- package/dist/packlets/yaml/converters.js.map +1 -0
- package/dist/packlets/yaml/index.js +1 -0
- package/dist/packlets/yaml/index.js.map +1 -0
- package/dist/packlets/yaml/serializers.js +48 -0
- package/dist/packlets/yaml/serializers.js.map +1 -0
- package/dist/packlets/zip-file-tree/index.js.map +1 -0
- package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
- package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -0
- package/dist/packlets/zip-file-tree/zipFileTreeWriter.js.map +1 -0
- package/dist/ts-extras.d.ts +1442 -45
- package/dist/tsdoc-metadata.json +1 -1
- package/lib/index.browser.d.ts +2 -1
- package/lib/index.browser.d.ts.map +1 -0
- package/lib/index.browser.js +3 -1
- package/lib/index.browser.js.map +1 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js.map +1 -0
- package/lib/packlets/ai-assist/apiClient.d.ts +111 -1
- package/lib/packlets/ai-assist/apiClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/apiClient.js +795 -56
- package/lib/packlets/ai-assist/apiClient.js.map +1 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +89 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.js +189 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -0
- package/lib/packlets/ai-assist/converters.d.ts.map +1 -0
- package/lib/packlets/ai-assist/converters.js.map +1 -0
- package/lib/packlets/ai-assist/index.d.ts +4 -3
- package/lib/packlets/ai-assist/index.d.ts.map +1 -0
- package/lib/packlets/ai-assist/index.js +12 -1
- package/lib/packlets/ai-assist/index.js.map +1 -0
- package/lib/packlets/ai-assist/model.d.ts +332 -2
- package/lib/packlets/ai-assist/model.d.ts.map +1 -0
- package/lib/packlets/ai-assist/model.js +21 -3
- package/lib/packlets/ai-assist/model.js.map +1 -0
- package/lib/packlets/ai-assist/registry.d.ts +34 -1
- package/lib/packlets/ai-assist/registry.d.ts.map +1 -0
- package/lib/packlets/ai-assist/registry.js +114 -11
- package/lib/packlets/ai-assist/registry.js.map +1 -0
- package/lib/packlets/ai-assist/sseParser.d.ts +45 -0
- package/lib/packlets/ai-assist/sseParser.d.ts.map +1 -0
- package/lib/packlets/ai-assist/sseParser.js +127 -0
- package/lib/packlets/ai-assist/sseParser.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +18 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +195 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +71 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.js +81 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts +19 -0
- package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js +163 -0
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +18 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +152 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +19 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +166 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts +34 -0
- package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/proxy.js +160 -0
- package/lib/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -0
- package/lib/packlets/ai-assist/streamingClient.d.ts +33 -0
- package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingClient.js +93 -0
- package/lib/packlets/ai-assist/streamingClient.js.map +1 -0
- package/lib/packlets/ai-assist/toolFormats.d.ts.map +1 -0
- package/lib/packlets/ai-assist/toolFormats.js.map +1 -0
- package/lib/packlets/conversion/converters.d.ts +8 -1
- package/lib/packlets/conversion/converters.d.ts.map +1 -0
- package/lib/packlets/conversion/converters.js +35 -2
- package/lib/packlets/conversion/converters.js.map +1 -0
- package/lib/packlets/conversion/index.d.ts.map +1 -0
- package/lib/packlets/conversion/index.js.map +1 -0
- package/lib/packlets/crypto-utils/constants.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/constants.js.map +1 -0
- package/lib/packlets/crypto-utils/converters.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/converters.js.map +1 -0
- package/lib/packlets/crypto-utils/directEncryptionProvider.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/directEncryptionProvider.js.map +1 -0
- package/lib/packlets/crypto-utils/encryptedFile.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/encryptedFile.js.map +1 -0
- package/lib/packlets/crypto-utils/index.browser.d.ts +1 -0
- package/lib/packlets/crypto-utils/index.browser.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/index.browser.js +4 -1
- package/lib/packlets/crypto-utils/index.browser.js.map +1 -0
- package/lib/packlets/crypto-utils/index.d.ts +1 -0
- package/lib/packlets/crypto-utils/index.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/index.js +4 -1
- package/lib/packlets/crypto-utils/index.js.map +1 -0
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts +39 -0
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js +60 -0
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/converters.d.ts +68 -6
- package/lib/packlets/crypto-utils/keystore/converters.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/converters.js +100 -8
- package/lib/packlets/crypto-utils/keystore/converters.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/index.d.ts +1 -0
- package/lib/packlets/crypto-utils/keystore/index.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/index.js +1 -0
- package/lib/packlets/crypto-utils/keystore/index.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/keyStore.d.ts +125 -12
- package/lib/packlets/crypto-utils/keystore/keyStore.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/keyStore.js +431 -118
- package/lib/packlets/crypto-utils/keystore/keyStore.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/model.d.ts +248 -17
- package/lib/packlets/crypto-utils/keystore/model.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/model.js +24 -2
- package/lib/packlets/crypto-utils/keystore/model.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/privateKeyStorage.d.ts +50 -0
- package/lib/packlets/crypto-utils/keystore/privateKeyStorage.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/privateKeyStorage.js +22 -0
- package/lib/packlets/crypto-utils/keystore/privateKeyStorage.js.map +1 -0
- package/lib/packlets/crypto-utils/model.d.ts +140 -0
- package/lib/packlets/crypto-utils/model.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/model.js +10 -1
- package/lib/packlets/crypto-utils/model.js.map +1 -0
- package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts +51 -1
- package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/nodeCryptoProvider.js +151 -0
- package/lib/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -0
- package/lib/packlets/csv/csvFileHelpers.d.ts.map +1 -0
- package/lib/packlets/csv/csvFileHelpers.js.map +1 -0
- package/lib/packlets/csv/csvHelpers.d.ts.map +1 -0
- package/lib/packlets/csv/csvHelpers.js.map +1 -0
- package/lib/packlets/csv/index.browser.d.ts.map +1 -0
- package/lib/packlets/csv/index.browser.js.map +1 -0
- package/lib/packlets/csv/index.d.ts.map +1 -0
- package/lib/packlets/csv/index.js.map +1 -0
- package/lib/packlets/experimental/extendedArray.d.ts.map +1 -0
- package/lib/packlets/experimental/extendedArray.js.map +1 -0
- package/lib/packlets/experimental/formatter.d.ts.map +1 -0
- package/lib/packlets/experimental/formatter.js.map +1 -0
- package/lib/packlets/experimental/index.d.ts.map +1 -0
- package/lib/packlets/experimental/index.js.map +1 -0
- package/lib/packlets/experimental/rangeOf.d.ts.map +1 -0
- package/lib/packlets/experimental/rangeOf.js.map +1 -0
- package/lib/packlets/hash/index.browser.d.ts.map +1 -0
- package/lib/packlets/hash/index.browser.js.map +1 -0
- package/lib/packlets/hash/index.d.ts.map +1 -0
- package/lib/packlets/hash/index.js.map +1 -0
- package/lib/packlets/hash/index.node.d.ts.map +1 -0
- package/lib/packlets/hash/index.node.js.map +1 -0
- package/lib/packlets/hash/md5Normalizer.browser.d.ts.map +1 -0
- package/lib/packlets/hash/md5Normalizer.browser.js.map +1 -0
- package/lib/packlets/hash/md5Normalizer.d.ts.map +1 -0
- package/lib/packlets/hash/md5Normalizer.js.map +1 -0
- package/lib/packlets/mustache/index.d.ts.map +1 -0
- package/lib/packlets/mustache/index.js.map +1 -0
- package/lib/packlets/mustache/interfaces.d.ts.map +1 -0
- package/lib/packlets/mustache/interfaces.js.map +1 -0
- package/lib/packlets/mustache/mustacheTemplate.d.ts.map +1 -0
- package/lib/packlets/mustache/mustacheTemplate.js.map +1 -0
- package/lib/packlets/record-jar/index.browser.d.ts.map +1 -0
- package/lib/packlets/record-jar/index.browser.js.map +1 -0
- package/lib/packlets/record-jar/index.d.ts.map +1 -0
- package/lib/packlets/record-jar/index.js.map +1 -0
- package/lib/packlets/record-jar/recordJarFileHelpers.d.ts.map +1 -0
- package/lib/packlets/record-jar/recordJarFileHelpers.js.map +1 -0
- package/lib/packlets/record-jar/recordJarHelpers.d.ts.map +1 -0
- package/lib/packlets/record-jar/recordJarHelpers.js.map +1 -0
- package/lib/packlets/yaml/converters.d.ts.map +1 -0
- package/lib/packlets/yaml/converters.js.map +1 -0
- package/lib/packlets/yaml/index.d.ts +1 -0
- package/lib/packlets/yaml/index.d.ts.map +1 -0
- package/lib/packlets/yaml/index.js +1 -0
- package/lib/packlets/yaml/index.js.map +1 -0
- package/lib/packlets/yaml/serializers.d.ts +45 -0
- package/lib/packlets/yaml/serializers.d.ts.map +1 -0
- package/lib/packlets/yaml/serializers.js +84 -0
- package/lib/packlets/yaml/serializers.js.map +1 -0
- package/lib/packlets/zip-file-tree/index.d.ts.map +1 -0
- package/lib/packlets/zip-file-tree/index.js.map +1 -0
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts +2 -2
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts.map +1 -0
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -0
- package/lib/packlets/zip-file-tree/zipFileTreeWriter.d.ts.map +1 -0
- package/lib/packlets/zip-file-tree/zipFileTreeWriter.js.map +1 -0
- package/package.json +24 -23
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { Result } from '@fgv/ts-utils';
|
|
2
|
+
/**
|
|
3
|
+
* Pluggable backend that persists raw asymmetric private keys outside of the
|
|
4
|
+
* encrypted keystore vault. Concrete implementations live in platform-specific
|
|
5
|
+
* packages (e.g. an IndexedDB-backed implementation in `@fgv/ts-web-extras` or
|
|
6
|
+
* an encrypted-file implementation in `@fgv/ts-chocolate`).
|
|
7
|
+
*
|
|
8
|
+
* The keystore writes storage-first: a private key is always stored here
|
|
9
|
+
* before the corresponding public-key vault entry is committed. Conversely,
|
|
10
|
+
* deletes hit the vault first and then this storage best-effort. As a result,
|
|
11
|
+
* crashes or skipped saves can leave orphaned blobs here; callers are expected
|
|
12
|
+
* to reconcile via {@link CryptoUtils.KeyStore.IPrivateKeyStorage.list} cross-referenced
|
|
13
|
+
* against the keystore's asymmetric entries.
|
|
14
|
+
*
|
|
15
|
+
* @public
|
|
16
|
+
*/
|
|
17
|
+
export interface IPrivateKeyStorage {
|
|
18
|
+
/**
|
|
19
|
+
* Whether keys generated for this backend may be marked
|
|
20
|
+
* `extractable: false`. `true` on backends that store `CryptoKey`
|
|
21
|
+
* objects directly (e.g. IndexedDB). `false` on backends that must
|
|
22
|
+
* round-trip via JWK (e.g. encrypted-file backends).
|
|
23
|
+
*/
|
|
24
|
+
readonly supportsNonExtractable: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Stores `key` under `id`. Returns the stored `id` on success so the
|
|
27
|
+
* call can compose into a Result chain.
|
|
28
|
+
* @param id - Storage handle to write under.
|
|
29
|
+
* @param key - The private `CryptoKey` to persist.
|
|
30
|
+
*/
|
|
31
|
+
store(id: string, key: CryptoKey): Promise<Result<string>>;
|
|
32
|
+
/**
|
|
33
|
+
* Loads the private key previously stored under `id`.
|
|
34
|
+
* @param id - Storage handle to look up.
|
|
35
|
+
*/
|
|
36
|
+
load(id: string): Promise<Result<CryptoKey>>;
|
|
37
|
+
/**
|
|
38
|
+
* Deletes the entry stored under `id`. Returns the deleted `id` on
|
|
39
|
+
* success so the call can compose into a Result chain.
|
|
40
|
+
* @param id - Storage handle to remove.
|
|
41
|
+
*/
|
|
42
|
+
delete(id: string): Promise<Result<string>>;
|
|
43
|
+
/**
|
|
44
|
+
* Lists every `id` currently held by the backend. Used by consumers to
|
|
45
|
+
* garbage-collect orphans left by crashes or aborted sessions; the
|
|
46
|
+
* keystore itself does not invoke this automatically.
|
|
47
|
+
*/
|
|
48
|
+
list(): Promise<Result<readonly string[]>>;
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=privateKeyStorage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"privateKeyStorage.d.ts","sourceRoot":"","sources":["../../../../src/packlets/crypto-utils/keystore/privateKeyStorage.ts"],"names":[],"mappings":"AAoBA,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAEvC;;;;;;;;;;;;;;GAcG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;;OAKG;IACH,QAAQ,CAAC,sBAAsB,EAAE,OAAO,CAAC;IAEzC;;;;;OAKG;IACH,KAAK,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;IAE3D;;;OAGG;IACH,IAAI,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;IAE7C;;;;OAIG;IACH,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;IAE5C;;;;OAIG;IACH,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC,SAAS,MAAM,EAAE,CAAC,CAAC,CAAC;CAC5C"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Copyright (c) 2026 Erik Fortune
|
|
3
|
+
//
|
|
4
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
// in the Software without restriction, including without limitation the rights
|
|
7
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
// furnished to do so, subject to the following conditions:
|
|
10
|
+
//
|
|
11
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
// copies or substantial portions of the Software.
|
|
13
|
+
//
|
|
14
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
// SOFTWARE.
|
|
21
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
//# sourceMappingURL=privateKeyStorage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"privateKeyStorage.js","sourceRoot":"","sources":["../../../../src/packlets/crypto-utils/keystore/privateKeyStorage.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","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 { Result } from '@fgv/ts-utils';\n\n/**\n * Pluggable backend that persists raw asymmetric private keys outside of the\n * encrypted keystore vault. Concrete implementations live in platform-specific\n * packages (e.g. an IndexedDB-backed implementation in `@fgv/ts-web-extras` or\n * an encrypted-file implementation in `@fgv/ts-chocolate`).\n *\n * The keystore writes storage-first: a private key is always stored here\n * before the corresponding public-key vault entry is committed. Conversely,\n * deletes hit the vault first and then this storage best-effort. As a result,\n * crashes or skipped saves can leave orphaned blobs here; callers are expected\n * to reconcile via {@link CryptoUtils.KeyStore.IPrivateKeyStorage.list} cross-referenced\n * against the keystore's asymmetric entries.\n *\n * @public\n */\nexport interface IPrivateKeyStorage {\n /**\n * Whether keys generated for this backend may be marked\n * `extractable: false`. `true` on backends that store `CryptoKey`\n * objects directly (e.g. IndexedDB). `false` on backends that must\n * round-trip via JWK (e.g. encrypted-file backends).\n */\n readonly supportsNonExtractable: boolean;\n\n /**\n * Stores `key` under `id`. Returns the stored `id` on success so the\n * call can compose into a Result chain.\n * @param id - Storage handle to write under.\n * @param key - The private `CryptoKey` to persist.\n */\n store(id: string, key: CryptoKey): Promise<Result<string>>;\n\n /**\n * Loads the private key previously stored under `id`.\n * @param id - Storage handle to look up.\n */\n load(id: string): Promise<Result<CryptoKey>>;\n\n /**\n * Deletes the entry stored under `id`. Returns the deleted `id` on\n * success so the call can compose into a Result chain.\n * @param id - Storage handle to remove.\n */\n delete(id: string): Promise<Result<string>>;\n\n /**\n * Lists every `id` currently held by the backend. Used by consumers to\n * garbage-collect orphans left by crashes or aborted sessions; the\n * keystore itself does not invoke this automatically.\n */\n list(): Promise<Result<readonly string[]>>;\n}\n"]}
|
|
@@ -44,6 +44,73 @@ export interface IEncryptionResult {
|
|
|
44
44
|
*/
|
|
45
45
|
readonly encryptedData: Uint8Array;
|
|
46
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Asymmetric keypair algorithms supported by the crypto provider.
|
|
49
|
+
* - `'ecdsa-p256'`: ECDSA over the P-256 curve, for signing.
|
|
50
|
+
* - `'rsa-oaep-2048'`: RSA-OAEP, 2048-bit modulus with SHA-256, for encryption.
|
|
51
|
+
* - `'ecdh-p256'`: ECDH over the P-256 curve, for key agreement
|
|
52
|
+
* (e.g. as the recipient keypair in
|
|
53
|
+
* {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes} /
|
|
54
|
+
* {@link CryptoUtils.ICryptoProvider.unwrapBytes | unwrapBytes}).
|
|
55
|
+
* @public
|
|
56
|
+
*/
|
|
57
|
+
export type KeyPairAlgorithm = 'ecdsa-p256' | 'rsa-oaep-2048' | 'ecdh-p256';
|
|
58
|
+
/**
|
|
59
|
+
* Caller-supplied HKDF parameters that domain-separate one
|
|
60
|
+
* {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes} call from another.
|
|
61
|
+
* Two wraps that share recipient but differ on `salt` or `info` derive distinct
|
|
62
|
+
* wrap keys, so callers should pick values that bind the wrap to its
|
|
63
|
+
* application context (e.g. a content hash for `salt` and a secret name for
|
|
64
|
+
* `info`).
|
|
65
|
+
*
|
|
66
|
+
* Both fields are required; pass an empty `Uint8Array` if the caller has no
|
|
67
|
+
* value to bind on a given axis. Silent defaulting would hide protocol
|
|
68
|
+
* mistakes, so the API does not pick defaults.
|
|
69
|
+
* @public
|
|
70
|
+
*/
|
|
71
|
+
export interface IWrapBytesOptions {
|
|
72
|
+
/**
|
|
73
|
+
* HKDF salt. Domain-separates this wrap from others in different contexts.
|
|
74
|
+
* Caller picks; common choices include a content hash, document id, channel
|
|
75
|
+
* id, etc.
|
|
76
|
+
*/
|
|
77
|
+
readonly salt: Uint8Array;
|
|
78
|
+
/**
|
|
79
|
+
* HKDF info. Further binds the derived key to a specific use within the
|
|
80
|
+
* calling application. Caller picks; common choices include a secret name,
|
|
81
|
+
* message type, or version tag.
|
|
82
|
+
*/
|
|
83
|
+
readonly info: Uint8Array;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Output of {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes}. The
|
|
87
|
+
* shape is JSON-serializable so it can travel directly over the wire or be
|
|
88
|
+
* persisted as-is.
|
|
89
|
+
* @public
|
|
90
|
+
*/
|
|
91
|
+
export interface IWrappedBytes {
|
|
92
|
+
/**
|
|
93
|
+
* Sender's ephemeral ECDH P-256 public key as a JSON Web Key. The matching
|
|
94
|
+
* ephemeral private key is dropped after the shared-secret derive.
|
|
95
|
+
*/
|
|
96
|
+
readonly ephemeralPublicKey: JsonWebKey;
|
|
97
|
+
/**
|
|
98
|
+
* AES-GCM nonce, base64-encoded. 12 bytes (96 bits) — the standard AES-GCM
|
|
99
|
+
* nonce length.
|
|
100
|
+
*/
|
|
101
|
+
readonly nonce: string;
|
|
102
|
+
/**
|
|
103
|
+
* AES-GCM ciphertext concatenated with the 16-byte authentication tag,
|
|
104
|
+
* base64-encoded. Tampering with either the nonce or the ciphertext causes
|
|
105
|
+
* unwrap to fail GCM authentication.
|
|
106
|
+
*/
|
|
107
|
+
readonly ciphertext: string;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* All valid key pair algorithms.
|
|
111
|
+
* @public
|
|
112
|
+
*/
|
|
113
|
+
export declare const allKeyPairAlgorithms: ReadonlyArray<KeyPairAlgorithm>;
|
|
47
114
|
/**
|
|
48
115
|
* Supported key derivation functions.
|
|
49
116
|
* @public
|
|
@@ -145,6 +212,12 @@ export interface ICryptoProvider {
|
|
|
145
212
|
* @returns Success with derived 32-byte key, or Failure with error
|
|
146
213
|
*/
|
|
147
214
|
deriveKey(password: string, salt: Uint8Array, iterations: number): Promise<Result<Uint8Array>>;
|
|
215
|
+
/**
|
|
216
|
+
* Computes a SHA-256 hash of the given data.
|
|
217
|
+
* @param data - UTF-8 string to hash
|
|
218
|
+
* @returns Success with hex-encoded hash string, or Failure with error
|
|
219
|
+
*/
|
|
220
|
+
sha256(data: string): Promise<Result<string>>;
|
|
148
221
|
/**
|
|
149
222
|
* Generates cryptographically secure random bytes.
|
|
150
223
|
* @param length - Number of bytes to generate
|
|
@@ -163,6 +236,73 @@ export interface ICryptoProvider {
|
|
|
163
236
|
* @returns Success with decoded bytes, or Failure if invalid base64
|
|
164
237
|
*/
|
|
165
238
|
fromBase64(base64: string): Result<Uint8Array>;
|
|
239
|
+
/**
|
|
240
|
+
* Generates a new asymmetric keypair for the requested algorithm.
|
|
241
|
+
* @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} to use.
|
|
242
|
+
* @param extractable - Whether the resulting `CryptoKey` objects may be exported.
|
|
243
|
+
* Set `false` on backends that store `CryptoKey` references directly (e.g.
|
|
244
|
+
* IndexedDB). Set `true` when the private key must round-trip through JWK or
|
|
245
|
+
* PKCS#8 (e.g. encrypted-file backends).
|
|
246
|
+
* @returns Success with the generated `CryptoKeyPair`, or Failure with error context.
|
|
247
|
+
*/
|
|
248
|
+
generateKeyPair(algorithm: KeyPairAlgorithm, extractable: boolean): Promise<Result<CryptoKeyPair>>;
|
|
249
|
+
/**
|
|
250
|
+
* Exports the public half of a keypair as a JSON Web Key.
|
|
251
|
+
* @param publicKey - The public `CryptoKey` to export. Must be an `extractable`
|
|
252
|
+
* key generated for an asymmetric algorithm.
|
|
253
|
+
* @returns Success with the JWK, or Failure with error context.
|
|
254
|
+
*/
|
|
255
|
+
exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>>;
|
|
256
|
+
/**
|
|
257
|
+
* Re-imports a public-key JWK as a `CryptoKey` usable for verification or
|
|
258
|
+
* encryption (depending on algorithm).
|
|
259
|
+
* @param jwk - The JSON Web Key produced by {@link CryptoUtils.ICryptoProvider.exportPublicKeyJwk | exportPublicKeyJwk}.
|
|
260
|
+
* @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} the
|
|
261
|
+
* key was generated for. Determines the import parameters and key usages.
|
|
262
|
+
* @returns Success with the imported public `CryptoKey`, or Failure with error context.
|
|
263
|
+
*/
|
|
264
|
+
importPublicKeyJwk(jwk: JsonWebKey, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>>;
|
|
265
|
+
/**
|
|
266
|
+
* Wraps `plaintext` for delivery to the holder of the private key paired
|
|
267
|
+
* with `recipientPublicKey`. Uses ECIES with ECDH P-256, HKDF-SHA256, and
|
|
268
|
+
* AES-GCM-256.
|
|
269
|
+
*
|
|
270
|
+
* Generates a fresh ephemeral keypair per call; the ephemeral private key
|
|
271
|
+
* is discarded after the shared-secret derive. Only the recipient (with the
|
|
272
|
+
* matching private key) and the same HKDF parameters can recover
|
|
273
|
+
* `plaintext`.
|
|
274
|
+
*
|
|
275
|
+
* Empty `plaintext` is permitted; the resulting wrap contains only the
|
|
276
|
+
* 16-byte GCM authentication tag and round-trips back to an empty
|
|
277
|
+
* `Uint8Array`.
|
|
278
|
+
* @param plaintext - The bytes to wrap. Any length supported by AES-GCM
|
|
279
|
+
* (in practice, well below 2^39 - 256 bits).
|
|
280
|
+
* @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.
|
|
281
|
+
* Must have algorithm name `'ECDH'` and named curve `'P-256'`; mismatched
|
|
282
|
+
* algorithm or curve yields a `Failure` with error context.
|
|
283
|
+
* @param options - HKDF parameters; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.
|
|
284
|
+
* @returns `Success` with the wrapped payload, or `Failure` with error context.
|
|
285
|
+
*/
|
|
286
|
+
wrapBytes(plaintext: Uint8Array, recipientPublicKey: CryptoKey, options: IWrapBytesOptions): Promise<Result<IWrappedBytes>>;
|
|
287
|
+
/**
|
|
288
|
+
* Inverse of {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes}.
|
|
289
|
+
* Recovers the original `plaintext` from a wrapped payload using the
|
|
290
|
+
* recipient's private key.
|
|
291
|
+
*
|
|
292
|
+
* Returns a `Failure` (never throws) on any of:
|
|
293
|
+
* - Tampered nonce or ciphertext (AES-GCM authentication fails)
|
|
294
|
+
* - Wrong private key (different shared secret derives a different wrap key)
|
|
295
|
+
* - Wrong HKDF parameters (different wrap key)
|
|
296
|
+
* - Malformed `ephemeralPublicKey` JWK
|
|
297
|
+
* - Malformed base64 in `nonce` or `ciphertext`
|
|
298
|
+
* @param wrapped - The wrapped payload produced by `wrapBytes`.
|
|
299
|
+
* @param recipientPrivateKey - The recipient's ECDH P-256 private
|
|
300
|
+
* `CryptoKey`. Must have algorithm name `'ECDH'` and named curve `'P-256'`,
|
|
301
|
+
* and key usages including `'deriveKey'` or `'deriveBits'`.
|
|
302
|
+
* @param options - The same HKDF parameters used at wrap time.
|
|
303
|
+
* @returns `Success` with the original `plaintext`, or `Failure` with error context.
|
|
304
|
+
*/
|
|
305
|
+
unwrapBytes(wrapped: IWrappedBytes, recipientPrivateKey: CryptoKey, options: IWrapBytesOptions): Promise<Result<Uint8Array>>;
|
|
166
306
|
}
|
|
167
307
|
/**
|
|
168
308
|
* High-level interface for encrypting JSON content by secret name.
|
|
@@ -0,0 +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,MAAM,EAAE,MAAM,eAAe,CAAC;AAEvC,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,CAAC;AAMrB;;;GAGG;AACH,MAAM,MAAM,mBAAmB,GAAG,OAAO,SAAS,CAAC,iBAAiB,CAAC;AAErE;;;GAGG;AACH,MAAM,MAAM,mBAAmB,GAAG,OAAO,SAAS,CAAC,qBAAqB,CAAC;AAEzE;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB;;OAEG;IACH,QAAQ,CAAC,GAAG,EAAE,UAAU,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,UAAU,CAAC;IAExB;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,UAAU,CAAC;IAE7B;;OAEG;IACH,QAAQ,CAAC,aAAa,EAAE,UAAU,CAAC;CACpC;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,gBAAgB,GAAG,YAAY,GAAG,eAAe,GAAG,WAAW,CAAC;AAE5E;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,QAAQ,CAAC,IAAI,EAAE,UA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AAC,EAAE,sBAAsB,CAAC;CACrD;AAMD;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAMtD"}
|
|
@@ -52,10 +52,19 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
52
52
|
};
|
|
53
53
|
})();
|
|
54
54
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
55
|
-
exports.Constants = void 0;
|
|
55
|
+
exports.allKeyPairAlgorithms = exports.Constants = void 0;
|
|
56
56
|
exports.isEncryptedFile = isEncryptedFile;
|
|
57
57
|
const Constants = __importStar(require("./constants"));
|
|
58
58
|
exports.Constants = Constants;
|
|
59
|
+
/**
|
|
60
|
+
* All valid key pair algorithms.
|
|
61
|
+
* @public
|
|
62
|
+
*/
|
|
63
|
+
exports.allKeyPairAlgorithms = [
|
|
64
|
+
'ecdsa-p256',
|
|
65
|
+
'rsa-oaep-2048',
|
|
66
|
+
'ecdh-p256'
|
|
67
|
+
];
|
|
59
68
|
// ============================================================================
|
|
60
69
|
// Detection Helper
|
|
61
70
|
// ============================================================================
|
|
@@ -0,0 +1 @@
|
|
|
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6dZ,0CAMC;AA9dD,uDAAyC;AAChC,8BAAS;AA2HlB;;;GAGG;AACU,QAAA,oBAAoB,GAAoC;IACnE,YAAY;IACZ,eAAe;IACf,WAAW;CACZ,CAAC;AAyUF,+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 { Result } from '@fgv/ts-utils';\n\nimport * as Constants from './constants';\nexport { Constants };\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 * @public\n */\nexport type KeyPairAlgorithm = 'ecdsa-p256' | 'rsa-oaep-2048' | 'ecdh-p256';\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];\n\n/**\n * Supported key derivation functions.\n * @public\n */\nexport type KeyDerivationFunction = 'pbkdf2';\n\n/**\n * Key derivation parameters stored in encrypted files.\n * Allows decryption with password without needing to know the original salt/iterations.\n * @public\n */\nexport interface IKeyDerivationParams {\n /**\n * Key derivation function used.\n */\n readonly kdf: KeyDerivationFunction;\n\n /**\n * Base64-encoded salt used for key derivation.\n */\n readonly salt: string;\n\n /**\n * Number of iterations used for key derivation.\n */\n readonly iterations: number;\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 * 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 * 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// ============================================================================\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 } from '@fgv/ts-utils';
|
|
2
|
-
import { ICryptoProvider, IEncryptionResult } from './model';
|
|
2
|
+
import { ICryptoProvider, 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.
|
|
@@ -35,6 +35,12 @@ export declare class NodeCryptoProvider implements ICryptoProvider {
|
|
|
35
35
|
* @returns `Success` with derived 32-byte key, or `Failure` with an error.
|
|
36
36
|
*/
|
|
37
37
|
deriveKey(password: string, salt: Uint8Array, iterations: number): Promise<Result<Uint8Array>>;
|
|
38
|
+
/**
|
|
39
|
+
* Computes a SHA-256 hash of the given data.
|
|
40
|
+
* @param data - UTF-8 string to hash
|
|
41
|
+
* @returns `Success` with hex-encoded hash string, or `Failure` with an error.
|
|
42
|
+
*/
|
|
43
|
+
sha256(data: string): Promise<Result<string>>;
|
|
38
44
|
/**
|
|
39
45
|
* Generates cryptographically secure random bytes.
|
|
40
46
|
* @param length - Number of bytes to generate
|
|
@@ -53,6 +59,50 @@ export declare class NodeCryptoProvider implements ICryptoProvider {
|
|
|
53
59
|
* @returns Success with decoded bytes, or Failure if invalid base64
|
|
54
60
|
*/
|
|
55
61
|
fromBase64(base64: string): Result<Uint8Array>;
|
|
62
|
+
/**
|
|
63
|
+
* Generates a new asymmetric keypair using Node's WebCrypto.
|
|
64
|
+
* @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} to use.
|
|
65
|
+
* @param extractable - Whether the resulting keys may be exported.
|
|
66
|
+
* @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.
|
|
67
|
+
*/
|
|
68
|
+
generateKeyPair(algorithm: KeyPairAlgorithm, extractable: boolean): Promise<Result<CryptoKeyPair>>;
|
|
69
|
+
/**
|
|
70
|
+
* Exports a public `CryptoKey` as a JSON Web Key.
|
|
71
|
+
* @remarks
|
|
72
|
+
* Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`
|
|
73
|
+
* does not enforce public-vs-private; without this guard a caller that
|
|
74
|
+
* passed an extractable private key would receive its private fields
|
|
75
|
+
* (`d`, `p`, `q`, ...) as JWK, defeating the method's name.
|
|
76
|
+
* @param publicKey - Extractable public key to export.
|
|
77
|
+
* @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.
|
|
78
|
+
*/
|
|
79
|
+
exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>>;
|
|
80
|
+
/**
|
|
81
|
+
* Imports a public-key JWK as a `CryptoKey` for the requested algorithm.
|
|
82
|
+
* @param jwk - The JSON Web Key produced by a prior export.
|
|
83
|
+
* @param algorithm - The algorithm the key was generated for.
|
|
84
|
+
* @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.
|
|
85
|
+
*/
|
|
86
|
+
importPublicKeyJwk(jwk: JsonWebKey, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>>;
|
|
87
|
+
/**
|
|
88
|
+
* Wraps `plaintext` for the holder of `recipientPublicKey` using
|
|
89
|
+
* ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See
|
|
90
|
+
* {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.
|
|
91
|
+
* @param plaintext - The bytes to wrap.
|
|
92
|
+
* @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.
|
|
93
|
+
* @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.
|
|
94
|
+
* @returns `Success` with the wrapped payload, or `Failure` with an error.
|
|
95
|
+
*/
|
|
96
|
+
wrapBytes(plaintext: Uint8Array, recipientPublicKey: CryptoKey, options: IWrapBytesOptions): Promise<Result<IWrappedBytes>>;
|
|
97
|
+
/**
|
|
98
|
+
* Unwraps a payload produced by `wrapBytes` using the recipient's private
|
|
99
|
+
* key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.
|
|
100
|
+
* @param wrapped - The wrapped payload.
|
|
101
|
+
* @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.
|
|
102
|
+
* @param options - HKDF salt and info matching the wrap call.
|
|
103
|
+
* @returns `Success` with the original `plaintext`, or `Failure` with an error.
|
|
104
|
+
*/
|
|
105
|
+
unwrapBytes(wrapped: IWrappedBytes, recipientPrivateKey: CryptoKey, options: IWrapBytesOptions): Promise<Result<Uint8Array>>;
|
|
56
106
|
}
|
|
57
107
|
/**
|
|
58
108
|
* Singleton instance of {@link CryptoUtils.NodeCryptoProvider}.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nodeCryptoProvider.d.ts","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/nodeCryptoProvider.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAoD,MAAM,EAAoB,MAAM,eAAe,CAAC;AAG3G,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,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,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AE,aAAa,EACtB,mBAAmB,EAAE,SAAS,EAC9B,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;CAuD/B;AA8BD;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,kBAA6C,CAAC"}
|
|
@@ -56,6 +56,7 @@ exports.nodeCryptoProvider = exports.NodeCryptoProvider = void 0;
|
|
|
56
56
|
const crypto = __importStar(require("crypto"));
|
|
57
57
|
const ts_utils_1 = require("@fgv/ts-utils");
|
|
58
58
|
const Constants = __importStar(require("./constants"));
|
|
59
|
+
const keyPairAlgorithmParams_1 = require("./keyPairAlgorithmParams");
|
|
59
60
|
/**
|
|
60
61
|
* Node.js implementation of {@link CryptoUtils.ICryptoProvider} using the built-in crypto module.
|
|
61
62
|
* Uses AES-256-GCM for authenticated encryption.
|
|
@@ -152,6 +153,18 @@ class NodeCryptoProvider {
|
|
|
152
153
|
});
|
|
153
154
|
});
|
|
154
155
|
}
|
|
156
|
+
/**
|
|
157
|
+
* Computes a SHA-256 hash of the given data.
|
|
158
|
+
* @param data - UTF-8 string to hash
|
|
159
|
+
* @returns `Success` with hex-encoded hash string, or `Failure` with an error.
|
|
160
|
+
*/
|
|
161
|
+
async sha256(data) {
|
|
162
|
+
return (0, ts_utils_1.captureResult)(() => {
|
|
163
|
+
const hash = crypto.createHash('sha256');
|
|
164
|
+
hash.update(data, 'utf8');
|
|
165
|
+
return hash.digest('hex');
|
|
166
|
+
});
|
|
167
|
+
}
|
|
155
168
|
// ============================================================================
|
|
156
169
|
// Platform Utility Methods
|
|
157
170
|
// ============================================================================
|
|
@@ -186,8 +199,146 @@ class NodeCryptoProvider {
|
|
|
186
199
|
}
|
|
187
200
|
return ts_utils_1.Success.with(new Uint8Array(Buffer.from(base64, 'base64')));
|
|
188
201
|
}
|
|
202
|
+
// ============================================================================
|
|
203
|
+
// Asymmetric Key Operations
|
|
204
|
+
// ============================================================================
|
|
205
|
+
/**
|
|
206
|
+
* Generates a new asymmetric keypair using Node's WebCrypto.
|
|
207
|
+
* @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} to use.
|
|
208
|
+
* @param extractable - Whether the resulting keys may be exported.
|
|
209
|
+
* @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.
|
|
210
|
+
*/
|
|
211
|
+
async generateKeyPair(algorithm, extractable) {
|
|
212
|
+
const params = keyPairAlgorithmParams_1.keyPairAlgorithmParams[algorithm];
|
|
213
|
+
const result = await (0, ts_utils_1.captureAsyncResult)(() => crypto.webcrypto.subtle.generateKey(params.generateKey, extractable, params.keyPairUsages));
|
|
214
|
+
return result.withErrorFormat((e) => `Failed to generate ${algorithm} keypair: ${e}`);
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Exports a public `CryptoKey` as a JSON Web Key.
|
|
218
|
+
* @remarks
|
|
219
|
+
* Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`
|
|
220
|
+
* does not enforce public-vs-private; without this guard a caller that
|
|
221
|
+
* passed an extractable private key would receive its private fields
|
|
222
|
+
* (`d`, `p`, `q`, ...) as JWK, defeating the method's name.
|
|
223
|
+
* @param publicKey - Extractable public key to export.
|
|
224
|
+
* @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.
|
|
225
|
+
*/
|
|
226
|
+
async exportPublicKeyJwk(publicKey) {
|
|
227
|
+
if (publicKey.type !== 'public') {
|
|
228
|
+
return (0, ts_utils_1.fail)(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);
|
|
229
|
+
}
|
|
230
|
+
const result = await (0, ts_utils_1.captureAsyncResult)(() => crypto.webcrypto.subtle.exportKey('jwk', publicKey));
|
|
231
|
+
return result.withErrorFormat((e) => `Failed to export public key as JWK: ${e}`);
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Imports a public-key JWK as a `CryptoKey` for the requested algorithm.
|
|
235
|
+
* @param jwk - The JSON Web Key produced by a prior export.
|
|
236
|
+
* @param algorithm - The algorithm the key was generated for.
|
|
237
|
+
* @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.
|
|
238
|
+
*/
|
|
239
|
+
async importPublicKeyJwk(jwk, algorithm) {
|
|
240
|
+
const params = keyPairAlgorithmParams_1.keyPairAlgorithmParams[algorithm];
|
|
241
|
+
const result = await (0, ts_utils_1.captureAsyncResult)(() => crypto.webcrypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, params.publicKeyUsages));
|
|
242
|
+
return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Wraps `plaintext` for the holder of `recipientPublicKey` using
|
|
246
|
+
* ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See
|
|
247
|
+
* {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.
|
|
248
|
+
* @param plaintext - The bytes to wrap.
|
|
249
|
+
* @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.
|
|
250
|
+
* @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.
|
|
251
|
+
* @returns `Success` with the wrapped payload, or `Failure` with an error.
|
|
252
|
+
*/
|
|
253
|
+
async wrapBytes(plaintext, recipientPublicKey, options) {
|
|
254
|
+
const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');
|
|
255
|
+
if (recipientCheck.isFailure()) {
|
|
256
|
+
return (0, ts_utils_1.fail)(`wrapBytes failed: ${recipientCheck.message}`);
|
|
257
|
+
}
|
|
258
|
+
const subtle = crypto.webcrypto.subtle;
|
|
259
|
+
const result = await (0, ts_utils_1.captureAsyncResult)(async () => {
|
|
260
|
+
const ephemeral = (await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [
|
|
261
|
+
'deriveKey'
|
|
262
|
+
]));
|
|
263
|
+
const hkdfBase = await subtle.deriveKey({ name: 'ECDH', public: recipientPublicKey }, ephemeral.privateKey, { name: 'HKDF' }, false, ['deriveKey']);
|
|
264
|
+
const wrapKey = await subtle.deriveKey({ name: 'HKDF', salt: options.salt, info: options.info, hash: 'SHA-256' }, hkdfBase, { name: 'AES-GCM', length: 256 }, false, ['encrypt']);
|
|
265
|
+
const nonce = crypto.randomBytes(Constants.GCM_IV_SIZE);
|
|
266
|
+
const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, plaintext);
|
|
267
|
+
const ephemeralPublicKey = await subtle.exportKey('jwk', ephemeral.publicKey);
|
|
268
|
+
return {
|
|
269
|
+
ephemeralPublicKey,
|
|
270
|
+
nonce: this.toBase64(nonce),
|
|
271
|
+
ciphertext: this.toBase64(new Uint8Array(ctBuf))
|
|
272
|
+
};
|
|
273
|
+
});
|
|
274
|
+
return result.withErrorFormat((e) => `wrapBytes failed: ${e}`);
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Unwraps a payload produced by `wrapBytes` using the recipient's private
|
|
278
|
+
* key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.
|
|
279
|
+
* @param wrapped - The wrapped payload.
|
|
280
|
+
* @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.
|
|
281
|
+
* @param options - HKDF salt and info matching the wrap call.
|
|
282
|
+
* @returns `Success` with the original `plaintext`, or `Failure` with an error.
|
|
283
|
+
*/
|
|
284
|
+
async unwrapBytes(wrapped, recipientPrivateKey, options) {
|
|
285
|
+
const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');
|
|
286
|
+
if (recipientCheck.isFailure()) {
|
|
287
|
+
return (0, ts_utils_1.fail)(`unwrapBytes failed: ${recipientCheck.message}`);
|
|
288
|
+
}
|
|
289
|
+
const nonceResult = this.fromBase64(wrapped.nonce);
|
|
290
|
+
if (nonceResult.isFailure()) {
|
|
291
|
+
return (0, ts_utils_1.fail)(`unwrapBytes failed: nonce: ${nonceResult.message}`);
|
|
292
|
+
}
|
|
293
|
+
if (nonceResult.value.length !== Constants.GCM_IV_SIZE) {
|
|
294
|
+
return (0, ts_utils_1.fail)(`unwrapBytes failed: nonce must be ${Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`);
|
|
295
|
+
}
|
|
296
|
+
const ciphertextResult = this.fromBase64(wrapped.ciphertext);
|
|
297
|
+
if (ciphertextResult.isFailure()) {
|
|
298
|
+
return (0, ts_utils_1.fail)(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);
|
|
299
|
+
}
|
|
300
|
+
if (ciphertextResult.value.length < Constants.GCM_AUTH_TAG_SIZE) {
|
|
301
|
+
return (0, ts_utils_1.fail)(`unwrapBytes failed: ciphertext must be at least ${Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`);
|
|
302
|
+
}
|
|
303
|
+
const subtle = crypto.webcrypto.subtle;
|
|
304
|
+
const result = await (0, ts_utils_1.captureAsyncResult)(async () => {
|
|
305
|
+
const ephemeralPub = await subtle.importKey('jwk', wrapped.ephemeralPublicKey, { name: 'ECDH', namedCurve: 'P-256' }, false, []);
|
|
306
|
+
const hkdfBase = await subtle.deriveKey({ name: 'ECDH', public: ephemeralPub }, recipientPrivateKey, { name: 'HKDF' }, false, ['deriveKey']);
|
|
307
|
+
const wrapKey = await subtle.deriveKey({ name: 'HKDF', salt: options.salt, info: options.info, hash: 'SHA-256' }, hkdfBase, { name: 'AES-GCM', length: 256 }, false, ['decrypt']);
|
|
308
|
+
const ptBuf = await subtle.decrypt({ name: 'AES-GCM', iv: nonceResult.value }, wrapKey, ciphertextResult.value);
|
|
309
|
+
return new Uint8Array(ptBuf);
|
|
310
|
+
});
|
|
311
|
+
return result.withErrorFormat((e) => `unwrapBytes failed: ${e}`);
|
|
312
|
+
}
|
|
189
313
|
}
|
|
190
314
|
exports.NodeCryptoProvider = NodeCryptoProvider;
|
|
315
|
+
/**
|
|
316
|
+
* Verifies that `key` is an ECDH P-256 `CryptoKey` of the expected `keyType`
|
|
317
|
+
* (public or private). Used by the wrap/unwrap methods to surface a clean
|
|
318
|
+
* `Failure` instead of letting the WebCrypto deriveKey call throw a less
|
|
319
|
+
* informative error later in the pipeline. Key usages are intentionally not
|
|
320
|
+
* checked here: WebCrypto already produces a specific error if `deriveKey` is
|
|
321
|
+
* not in `usages`, and `deriveBits` is an equally valid alternative usage that
|
|
322
|
+
* an explicit check would have to track.
|
|
323
|
+
* @param key - The CryptoKey to validate.
|
|
324
|
+
* @param keyType - The required `key.type` ('public' for wrap, 'private' for unwrap).
|
|
325
|
+
* @param label - Human-readable role label included in the failure message.
|
|
326
|
+
* @returns `Success` with the key (unchanged) when the algorithm, curve, and
|
|
327
|
+
* type all match; otherwise `Failure` with `<label> must be ECDH P-256 (...)`.
|
|
328
|
+
*/
|
|
329
|
+
function checkEcdhP256(key, keyType, label) {
|
|
330
|
+
if (key.algorithm.name !== 'ECDH') {
|
|
331
|
+
return (0, ts_utils_1.fail)(`${label} must be ECDH P-256 (got algorithm '${key.algorithm.name}')`);
|
|
332
|
+
}
|
|
333
|
+
const namedCurve = key.algorithm.namedCurve;
|
|
334
|
+
if (namedCurve !== 'P-256') {
|
|
335
|
+
return (0, ts_utils_1.fail)(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);
|
|
336
|
+
}
|
|
337
|
+
if (key.type !== keyType) {
|
|
338
|
+
return (0, ts_utils_1.fail)(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);
|
|
339
|
+
}
|
|
340
|
+
return (0, ts_utils_1.succeed)(key);
|
|
341
|
+
}
|
|
191
342
|
/**
|
|
192
343
|
* Singleton instance of {@link CryptoUtils.NodeCryptoProvider}.
|
|
193
344
|
* @public
|