@smartledger/keys 3.1.0 → 4.0.0

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/README.md CHANGED
@@ -6,8 +6,10 @@ supplies ML-DSA-44/65/87 (FIPS 204, via `@noble/post-quantum`) and ECDSA
6
6
  secp256k1 (via `@noble/secp256k1`).
7
7
 
8
8
  **Read [Limits](#limits) before depending on it.** The only storage backend
9
- shipped is in-memory, and ML-DSA signatures are made over a digest rather than
10
- the message.
9
+ shipped is in-memory.
10
+
11
+ **Upgrading from 3.x:** 4.0 changes what an ML-DSA key signs. See
12
+ [What a key signs](#what-a-key-signs).
11
13
 
12
14
  ## Installation
13
15
 
@@ -48,6 +50,39 @@ console.log(result.allValid); // true
48
50
  | `ml-dsa-87` | 5 | 2,592 B | 4,627 B |
49
51
  | `bsv-ecdsa-secp256k1` | not post-quantum | 33 B | 64 B (compact `r‖s`, low S) |
50
52
 
53
+ ## What a key signs
54
+
55
+ | Suite | Signs | Verify it elsewhere with |
56
+ |---|---|---|
57
+ | `ml-dsa-44/65/87` | the message itself, FIPS 204 pure mode (`ML-DSA.Sign`), hedged, under a context string | any FIPS 204 verifier, given the message and the context |
58
+ | `bsv-ecdsa-secp256k1` | `SHA-256(message)`, RFC 6979 | any secp256k1 ECDSA verifier over that digest |
59
+
60
+ The context string is `@smartledger/keys/4` unless you set one:
61
+
62
+ ```typescript
63
+ const sdk = createKeySDK({ signingContext: 'example.org/payments' }); // 1 to 255 bytes
64
+ ```
65
+
66
+ An ML-DSA signature verifies only under the context it was made with, so
67
+ ML-DSA signatures cannot be replayed between deployments that use different
68
+ contexts. A verifier has to be told the context; it is not carried in the
69
+ signature. **The context does not enter an ECDSA signature**: ECDSA has none,
70
+ so the same ECDSA key and message verify in any deployment. Where that
71
+ matters, put the deployment or purpose in the message.
72
+
73
+ **From 3.x.** Until 4.0 an ML-DSA key signed `SHA3-256(message)` with the
74
+ empty context. That capped collision resistance at about 128 bits whatever
75
+ the ML-DSA level, and a standard verifier had to be handed the digest, not the
76
+ message. Signatures made by 3.x do not verify under 4.0's default. To verify
77
+ one:
78
+
79
+ ```typescript
80
+ await sdk.verifySignature(keyId, message, signature, { scheme: 'v3-digest' });
81
+ await sdk.verifyWithSuites(agentId, message, signatures, { scheme: 'v3-digest', requiredSuites });
82
+ ```
83
+
84
+ 4.0 never signs in the old scheme. ECDSA signatures are unchanged.
85
+
51
86
  ## Verifying a hybrid signature
52
87
 
53
88
  `verifyWithSuites(agentId, message, signatures, options?)` returns
@@ -170,17 +205,15 @@ sighash preimage, which this SDK does not build.
170
205
  - **Private keys are reachable.** `signWithKey` keeps them out of the common
171
206
  path, but anyone holding the `KeyRegistry` can call `getKey`. This is an API
172
207
  convenience, not an isolation boundary.
173
- - **ML-DSA signs a digest.** The SDK signs `SHA3-256(message)` with pure
174
- ML-DSA and an empty context string (and ECDSA signs `SHA-256(message)`).
175
- A standard FIPS 204 verifier must therefore be given the 32-byte digest as
176
- its message. The 256-bit digest also bounds collision resistance at about
177
- 128 bits whatever the ML-DSA level, which matters where an attacker can
178
- choose the messages that get signed. Signing the message directly (or
179
- HashML-DSA with a context string) is planned for the next major version,
180
- because it changes every signature.
181
- - **No domain separation between uses.** A key that signs for several purposes
182
- can have a signature replayed from one to another. Put the purpose in the
183
- message.
208
+ - **Hybrid signatures here are separable.** `signWithSuites` makes one
209
+ independent signature per key over the same message. Each is also a valid
210
+ single-key signature; what makes a set "hybrid" is the verifier requiring
211
+ every suite (`verifyWithSuites` with `requiredSuites`). A construction where
212
+ each half commits to the whole signer set is not provided by this package.
213
+ - **ECDSA has no domain separation.** An ML-DSA signature is bound to the
214
+ SDK's context string; an ECDSA signature is over `SHA-256(message)` and
215
+ nothing else. A key that signs for several purposes can have an ECDSA
216
+ signature replayed from one to another. Put the purpose in the message.
184
217
  - **`getOrCreateKey` across instances.** Two SDK instances or processes on one
185
218
  backend can each create a key; this needs a lock in the backend.
186
219
  - **Dependencies.** `@noble/post-quantum` is pre-1.0 and, unlike the other
package/dist/cjs/sdk.d.ts CHANGED
@@ -14,7 +14,18 @@ export interface KeySDKConfig {
14
14
  keyRegistry: KeyRegistry;
15
15
  /** Signature suite registry instance */
16
16
  suiteRegistry: SignatureSuiteRegistry;
17
+ /**
18
+ * Context string for ML-DSA signatures (FIPS 204), 1 to 255 bytes. An
19
+ * ML-DSA signature verifies only under the context it was made with, so
20
+ * two deployments with different contexts cannot have ML-DSA signatures
21
+ * replayed between them. It does NOT enter an ECDSA signature: ECDSA has
22
+ * no context, and the same ECDSA key and message verify in any deployment.
23
+ * Default: `@smartledger/keys/4`.
24
+ */
25
+ signingContext?: string | Uint8Array;
17
26
  }
27
+ /** The default ML-DSA context string of this major version. */
28
+ export declare const DEFAULT_SIGNING_CONTEXT = "@smartledger/keys/4";
18
29
  export { agentIdOfKey };
19
30
  /**
20
31
  * Default KeySDK implementation.
@@ -28,6 +39,7 @@ export declare class DefaultKeySDK implements KeySDK {
28
39
  private counterInitialized;
29
40
  private counterInitPromises;
30
41
  private getOrCreateInFlight;
42
+ private signingContext;
31
43
  constructor(config: KeySDKConfig);
32
44
  /**
33
45
  * Create a new key for an agent.
@@ -44,6 +56,19 @@ export declare class DefaultKeySDK implements KeySDK {
44
56
  * registered for signing
45
57
  */
46
58
  signWithKey(keyId: string, message: Uint8Array): Promise<Uint8Array>;
59
+ /**
60
+ * What a key of `suiteId` signs for `message` under a scheme.
61
+ *
62
+ * v4: ML-DSA signs the message itself in FIPS 204 pure mode with this SDK's
63
+ * context string, so a standard verifier needs only the message and the
64
+ * context, and the signature is not limited by an outside digest. ECDSA
65
+ * signs SHA-256(message): ECDSA signs a digest by definition and has no
66
+ * context, so callers who need domain separation for it put the purpose in
67
+ * the message.
68
+ *
69
+ * v3-digest: what 3.x signed — SHA3-256(message) for ML-DSA, empty context.
70
+ */
71
+ private signingInput;
47
72
  /**
48
73
  * Verify a signature.
49
74
  *
@@ -194,10 +219,6 @@ export declare class DefaultKeySDK implements KeySDK {
194
219
  * @returns KeyRecord with Bitcoin-compatible key
195
220
  */
196
221
  createBitcoinWalletKey(agentId: string, mnemonic: string, accountIndex?: number, addressIndex?: number, isChange?: boolean, options?: CreateKeyOptions): Promise<KeyRecord>;
197
- /**
198
- * Helper: Get hash algorithm for a suite.
199
- */
200
- private getHashAlgorithm;
201
222
  /**
202
223
  * Helper: register a key under the agent's next free key ID.
203
224
  *
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/sdk.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,WAAW,EACX,sBAAsB,EAGtB,aAAa,EAKb,YAAY,EAQb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,MAAM,EACN,SAAS,EACT,gBAAgB,EAEhB,oBAAoB,EACpB,uBAAuB,EACvB,cAAc,EAGd,sBAAsB,EACtB,uBAAuB,EACvB,sBAAsB,EACtB,aAAa,EACd,MAAM,YAAY,CAAC;AAEpB;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,4BAA4B;IAC5B,WAAW,EAAE,WAAW,CAAC;IAEzB,wCAAwC;IACxC,aAAa,EAAE,sBAAsB,CAAC;CACvC;AAED,OAAO,EAAE,YAAY,EAAE,CAAC;AAuBxB;;;;GAIG;AACH,qBAAa,aAAc,YAAW,MAAM;IAC1C,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,aAAa,CAAyB;IAC9C,OAAO,CAAC,UAAU,CAA6B;IAC/C,OAAO,CAAC,kBAAkB,CAAqB;IAC/C,OAAO,CAAC,mBAAmB,CAAoC;IAC/D,OAAO,CAAC,mBAAmB,CAAyC;gBAExD,MAAM,EAAE,YAAY;IAKhC;;OAEG;IACG,SAAS,CACb,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,aAAa,EACtB,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,SAAS,CAAC;IA4CrB;;OAEG;IACG,MAAM,CAAC,KAAK,EAAE,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AM,EACf,QAAQ,EAAE,MAAM,EAChB,YAAY,GAAE,MAAU,EACxB,YAAY,GAAE,MAAU,EACxB,QAAQ,GAAE,OAAe,EACzB,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,SAAS,CAAC;IAarB;;;;;;;;OAQG;YACW,oBAAoB;IAyBlC;;OAEG;YACW,cAAc;IAoC5B;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAW3B,OAAO,CAAC,gBAAgB;CAKzB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,YAAY,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,GAAG,MAAM,CAuBnE"}
package/dist/cjs/sdk.js CHANGED
@@ -6,10 +6,12 @@
6
6
  * a clean, high-level API for key operations.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.DefaultKeySDK = exports.agentIdOfKey = void 0;
9
+ exports.DefaultKeySDK = exports.agentIdOfKey = exports.DEFAULT_SIGNING_CONTEXT = void 0;
10
10
  exports.createKeySDK = createKeySDK;
11
11
  const crypto_1 = require("@smartledger/crypto");
12
12
  Object.defineProperty(exports, "agentIdOfKey", { enumerable: true, get: function () { return crypto_1.agentIdOfKey; } });
13
+ /** The default ML-DSA context string of this major version. */
14
+ exports.DEFAULT_SIGNING_CONTEXT = '@smartledger/keys/4';
13
15
  const COUNTER_SUFFIX = /^pk-[^:-]+-(\d+)$/;
14
16
  const MAX_KEY_ID_ATTEMPTS = 8;
15
17
  function assertAgentId(agentId) {
@@ -42,6 +44,12 @@ class DefaultKeySDK {
42
44
  this.getOrCreateInFlight = new Map();
43
45
  this.keyRegistry = config.keyRegistry;
44
46
  this.suiteRegistry = config.suiteRegistry;
47
+ const context = config.signingContext ?? exports.DEFAULT_SIGNING_CONTEXT;
48
+ const bytes = typeof context === 'string' ? new TextEncoder().encode(context) : Uint8Array.from(context);
49
+ if (bytes.length < 1 || bytes.length > 255) {
50
+ throw new Error('signingContext must be 1 to 255 bytes');
51
+ }
52
+ this.signingContext = bytes;
45
53
  }
46
54
  /**
47
55
  * Create a new key for an agent.
@@ -113,10 +121,31 @@ class DefaultKeySDK {
113
121
  }
114
122
  // Get suite and sign
115
123
  const suite = this.suiteRegistry.getSuite(result.meta.suiteId);
116
- // Hash the message (consistent with signAgentResponse)
117
- const hashAlg = this.getHashAlgorithm(result.meta.suiteId);
118
- const messageHash = await (0, crypto_1.hashBytes)(message, hashAlg);
119
- return await suite.sign(result.keypair.privateKey, messageHash);
124
+ const { input, options } = await this.signingInput(result.meta.suiteId, message, 'v4');
125
+ return await suite.sign(result.keypair.privateKey, input, options);
126
+ }
127
+ /**
128
+ * What a key of `suiteId` signs for `message` under a scheme.
129
+ *
130
+ * v4: ML-DSA signs the message itself in FIPS 204 pure mode with this SDK's
131
+ * context string, so a standard verifier needs only the message and the
132
+ * context, and the signature is not limited by an outside digest. ECDSA
133
+ * signs SHA-256(message): ECDSA signs a digest by definition and has no
134
+ * context, so callers who need domain separation for it put the purpose in
135
+ * the message.
136
+ *
137
+ * v3-digest: what 3.x signed — SHA3-256(message) for ML-DSA, empty context.
138
+ */
139
+ async signingInput(suiteId, message, scheme) {
140
+ if (scheme !== 'v4' && scheme !== 'v3-digest') {
141
+ throw new Error(`Unknown signature scheme: ${String(scheme)}`);
142
+ }
143
+ if (suiteId.startsWith('ml-dsa')) {
144
+ return scheme === 'v4'
145
+ ? { input: message, options: { context: this.signingContext } }
146
+ : { input: await (0, crypto_1.hashBytes)(message, 'sha3-256') };
147
+ }
148
+ return { input: await (0, crypto_1.hashBytes)(message, 'sha256') };
120
149
  }
121
150
  /**
122
151
  * Verify a signature.
@@ -134,15 +163,14 @@ class DefaultKeySDK {
134
163
  if (!statusAllows(result.meta, options.keyStatus ?? 'any')) {
135
164
  return false;
136
165
  }
137
- return this.verifyAgainst(result.meta, result.publicKey, message, signature);
166
+ return this.verifyAgainst(result.meta, result.publicKey, message, signature, options.scheme ?? 'v4');
138
167
  }
139
168
  /** The cryptographic check alone. Anything but a strict `true` is a failure. */
140
- async verifyAgainst(meta, publicKey, message, signature) {
169
+ async verifyAgainst(meta, publicKey, message, signature, scheme = 'v4') {
141
170
  try {
142
171
  const suite = this.suiteRegistry.getSuite(meta.suiteId);
143
- const hashAlg = this.getHashAlgorithm(meta.suiteId);
144
- const messageHash = await (0, crypto_1.hashBytes)(message, hashAlg);
145
- return (await suite.verify(publicKey, messageHash, signature)) === true;
172
+ const { input, options } = await this.signingInput(meta.suiteId, message, scheme);
173
+ return (await suite.verify(publicKey, input, signature, options)) === true;
146
174
  }
147
175
  catch {
148
176
  return false;
@@ -392,7 +420,7 @@ class DefaultKeySDK {
392
420
  fail('Signature must be a Uint8Array');
393
421
  continue;
394
422
  }
395
- const valid = await this.verifyAgainst(key.meta, key.publicKey, message, entry.signature);
423
+ const valid = await this.verifyAgainst(key.meta, key.publicKey, message, entry.signature, options.scheme ?? 'v4');
396
424
  if (valid) {
397
425
  results.push({ suiteId, keyId, valid: true });
398
426
  }
@@ -536,15 +564,6 @@ class DefaultKeySDK {
536
564
  const path = crypto_1.BIP32Derivation.bitcoinPath(accountIndex, isChange ? 1 : 0, addressIndex);
537
565
  return this.createKeyFromMnemonic(agentId, { primarySignatureSuite: 'bsv-ecdsa-secp256k1' }, mnemonic, path, undefined, options);
538
566
  }
539
- /**
540
- * Helper: Get hash algorithm for a suite.
541
- */
542
- getHashAlgorithm(suiteId) {
543
- if (suiteId.startsWith('ml-dsa')) {
544
- return 'sha3-256';
545
- }
546
- return 'sha256';
547
- }
548
567
  /**
549
568
  * Helper: register a key under the agent's next free key ID.
550
569
  *
@@ -669,6 +688,7 @@ function createKeySDK(config) {
669
688
  return new DefaultKeySDK({
670
689
  keyRegistry,
671
690
  suiteRegistry,
691
+ signingContext: config?.signingContext,
672
692
  });
673
693
  }
674
694
  //# sourceMappingURL=sdk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/sdk.ts"],"names":[],"mappings":";AA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7C,CAAC;IAED,OAAO,IAAI,aAAa,CAAC;QACvB,WAAW;QACX,aAAa;KACd,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Default implementation of KeySDK.\n * \n * Integrates KeyRegistry and SignatureSuiteRegistry to provide\n * a clean, high-level API for key operations.\n */\n\nimport {\n KeyRegistry,\n SignatureSuiteRegistry,\n KeyMeta,\n Keypair,\n CryptoProfile,\n hashBytes,\n assertKeyUsable,\n isKeyUsable,\n cloneKeyMeta,\n agentIdOfKey,\n KeyAlreadyExistsError,\n BIP32Derivation,\n InMemoryKeyStorage,\n BsvEcdsaSuite,\n MlDsa44Suite,\n MlDsa65Suite,\n MlDsa87Suite,\n} from '@smartledger/crypto';\nimport {\n KeySDK,\n KeyRecord,\n CreateKeyOptions,\n AgentKeyConfig,\n MultiSignatureResult,\n MultiVerificationResult,\n SuiteSignature,\n SuiteVerificationResult,\n KeyStatusPolicy,\n VerifySignatureOptions,\n VerifyWithSuitesOptions,\n RotateAgentKeysOptions,\n WalletKeyPath,\n} from './types.js';\n\n/**\n * Configuration for DefaultKeySDK.\n */\nexport interface KeySDKConfig {\n /** Key registry instance */\n keyRegistry: KeyRegistry;\n \n /** Signature suite registry instance */\n suiteRegistry: SignatureSuiteRegistry;\n}\n\nexport { agentIdOfKey };\n\nconst COUNTER_SUFFIX = /^pk-[^:-]+-(\\d+)$/;\nconst MAX_KEY_ID_ATTEMPTS = 8;\n\nfunction assertAgentId(agentId: unknown): asserts agentId is string {\n if (typeof agentId !== 'string' || agentId.length === 0) {\n throw new Error('agentId must be a non-empty string');\n }\n}\n\nfunction toRecord(meta: KeyMeta, publicKey: Uint8Array): KeyRecord {\n // Copies, so a caller cannot reach registry state through a KeyRecord even\n // when a custom storage backend hands out its own objects.\n return { meta: cloneKeyMeta(meta), publicKey: Uint8Array.from(publicKey) };\n}\n\nfunction statusAllows(meta: KeyMeta, policy: KeyStatusPolicy): boolean {\n if (policy === 'any') return true;\n if (policy === 'not-revoked') return meta.status !== 'revoked';\n return isKeyUsable(meta);\n}\n\n/**\n * Default KeySDK implementation.\n * \n * Provides a simple, safe API for key operations while hiding complexity.\n */\nexport class DefaultKeySDK implements KeySDK {\n private keyRegistry: KeyRegistry;\n private suiteRegistry: SignatureSuiteRegistry;\n private keyCounter = new Map<string, number>(); // agentId -> counter\n private counterInitialized = new Set<string>();\n private counterInitPromises = new Map<string, Promise<void>>();\n private getOrCreateInFlight = new Map<string, Promise<KeyRecord>>();\n \n constructor(config: KeySDKConfig) {\n this.keyRegistry = config.keyRegistry;\n this.suiteRegistry = config.suiteRegistry;\n }\n \n /**\n * Create a new key for an agent.\n */\n async createKey(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n assertAgentId(agentId);\n\n // Get suite\n const suite = this.suiteRegistry.getSuite(profile.primarySignatureSuite);\n \n // Generate keypair (with optional derivation)\n let keypair;\n \n if (options.derivationContext) {\n // Check if suite supports derivation\n if (!suite.capabilities?.derivation) {\n const available = this.getSuitesWithCapability('derivation');\n throw new Error(\n `Suite '${suite.suiteId}' does not support key derivation.\\n` +\n (available.length > 0\n ? `Suites with derivation capability: ${available.join(', ')}\\n` +\n `Consider using one of these suites or remove the derivationContext option.`\n : `No suites currently support derivation. Remove the derivationContext option.`)\n );\n }\n \n // Use derivation capability\n keypair = await suite.capabilities.derivation.deriveKeypair(options.derivationContext);\n } else {\n // Standard random key generation\n keypair = await suite.generateKeypair();\n }\n \n const meta = await this.registerUnderFreshId(agentId, profile.primarySignatureSuite, keyId =>\n this.keyRegistry.registerKey(keyId, keypair, profile.primarySignatureSuite, {\n expiresAt: options.expiresAt,\n usage: options.usage || ['signing'],\n cryptoProfileVersion: options.cryptoProfileVersion || '1.0.0',\n // Record that (and where) the key was derived. Never the seed.\n derivation: options.derivationContext\n ? { path: options.derivationContext.path ?? '' }\n : undefined,\n })\n );\n \n return toRecord(meta, keypair.publicKey);\n }\n \n /**\n * Get an existing key.\n */\n async getKey(keyId: string): Promise<KeyRecord | null> {\n const result = await this.keyRegistry.getPublicKey(keyId);\n \n if (!result) {\n return null;\n }\n \n return toRecord(result.meta, result.publicKey);\n }\n \n /**\n * Sign with a key (private key never exposed).\n *\n * @throws if the key is unknown, not active, past its `expiresAt`, or not\n * registered for signing\n */\n async signWithKey(\n keyId: string,\n message: Uint8Array\n ): Promise<Uint8Array> {\n // Get full keypair (private access)\n const result = await this.keyRegistry.getKey(keyId);\n \n if (!result) {\n throw new Error(`Key not found: ${keyId}`);\n }\n \n if (result.meta.status && result.meta.status !== 'active') {\n throw new Error(`Key is not active: ${keyId} (status: ${result.meta.status})`);\n }\n // Status alone is not enough: an expired key keeps status 'active' until\n // markExpiredKeys() runs, and used to go on signing in the meantime.\n assertKeyUsable(result.meta);\n\n if (!result.meta.usage.some(u => u === 'signing' || u === 'both')) {\n throw new Error(\n `Key is not registered for signing: ${keyId} (usage: ${result.meta.usage.join(', ')})`\n );\n }\n \n // Get suite and sign\n const suite = this.suiteRegistry.getSuite(result.meta.suiteId);\n \n // Hash the message (consistent with signAgentResponse)\n const hashAlg = this.getHashAlgorithm(result.meta.suiteId);\n const messageHash = await hashBytes(message, hashAlg);\n \n return await suite.sign(result.keypair.privateKey, messageHash);\n }\n \n /**\n * Verify a signature.\n *\n * By default this is the cryptographic check only: a signature made by a\n * key that has since been rotated, expired or revoked still verifies, which\n * is what verifying a historical signature needs. Pass `keyStatus` to also\n * require something of the key's state now.\n */\n async verifySignature(\n keyId: string,\n message: Uint8Array,\n signature: Uint8Array,\n options: VerifySignatureOptions = {}\n ): Promise<boolean> {\n const result = await this.keyRegistry.getPublicKey(keyId);\n \n if (!result) {\n return false;\n }\n\n if (!statusAllows(result.meta, options.keyStatus ?? 'any')) {\n return false;\n }\n \n return this.verifyAgainst(result.meta, result.publicKey, message, signature);\n }\n\n /** The cryptographic check alone. Anything but a strict `true` is a failure. */\n private async verifyAgainst(\n meta: KeyMeta,\n publicKey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array\n ): Promise<boolean> {\n try {\n const suite = this.suiteRegistry.getSuite(meta.suiteId);\n const hashAlg = this.getHashAlgorithm(meta.suiteId);\n const messageHash = await hashBytes(message, hashAlg);\n return (await suite.verify(publicKey, messageHash, signature)) === true;\n } catch {\n return false;\n }\n }\n \n /**\n * List keys for an agent.\n */\n async listKeysForAgent(\n agentId: string,\n activeOnly: boolean = true\n ): Promise<KeyRecord[]> {\n assertAgentId(agentId);\n\n const keys = activeOnly\n ? await this.keyRegistry.listActiveKeys()\n : await this.keyRegistry.listKeys();\n \n // Exact ownership, not a prefix match (see agentIdOfKey)\n const agentKeys = keys.filter(meta => agentIdOfKey(meta.keyId) === agentId);\n \n // Convert to KeyRecords\n const records: KeyRecord[] = [];\n \n for (const meta of agentKeys) {\n const result = await this.keyRegistry.getPublicKey(meta.keyId);\n if (result) {\n records.push(toRecord(result.meta, result.publicKey));\n }\n }\n \n return records;\n }\n \n /**\n * Get active crypto profile for an agent.\n */\n async getActiveCryptoProfile(agentId: string): Promise<CryptoProfile | null> {\n const keys = await this.listKeysForAgent(agentId, true);\n \n if (keys.length === 0) {\n return null;\n }\n \n // Group by suite\n const sorted = this.sortKeysByCreatedAt(keys);\n const suites = new Set(sorted.map(k => k.meta.suiteId));\n const suiteArray = Array.from(suites);\n \n // Assume first is primary, second is secondary\n return {\n primarySignatureSuite: suiteArray[0],\n secondarySignatureSuite: suiteArray[1],\n };\n }\n \n /**\n * Rotate all keys for an agent.\n *\n * Each replacement gets its predecessor's lifetime again, counted from now\n * (or `options.expiresAt`); it does not inherit the old expiry instant.\n *\n * A key derived from a seed cannot be re-derived here, because the SDK does\n * not keep seeds. By default the call refuses, before changing anything,\n * rather than silently swapping a recoverable key for a random one. See\n * {@link RotateAgentKeysOptions.derivedKeys}.\n */\n async rotateAgentKeys(\n agentId: string,\n options: RotateAgentKeysOptions = {}\n ): Promise<KeyRecord[]> {\n const derivedPolicy = options.derivedKeys ?? 'error';\n const activeKeys = await this.listKeysForAgent(agentId, true);\n\n // Decide everything before changing anything.\n const toRotate: KeyRecord[] = [];\n for (const keyRecord of activeKeys) {\n // Resolves the suite now, so an unknown suite fails before any rotation.\n this.suiteRegistry.getSuite(keyRecord.meta.suiteId);\n if (keyRecord.meta.derivation) {\n if (derivedPolicy === 'error') {\n throw new Error(\n `Key ${keyRecord.meta.keyId} was derived from a seed ` +\n `(path ${keyRecord.meta.derivation.path || 'unknown'}). Rotating it here would ` +\n `replace it with a random key that the mnemonic cannot recover. Derive the ` +\n `successor yourself with createKeyFromMnemonic at a new path, or pass ` +\n `{ derivedKeys: 'skip' } or { derivedKeys: 'randomize' }. No keys were rotated.`\n );\n }\n if (derivedPolicy === 'skip') continue;\n }\n toRotate.push(keyRecord);\n }\n\n // Generate every replacement before committing any, so a failing suite\n // cannot leave the agent half rotated. The commits below are then one\n // registry rotation per key; they are not a single transaction, so a\n // storage failure part-way through leaves the earlier keys rotated.\n const replacements: Keypair[] = [];\n for (const keyRecord of toRotate) {\n const suite = this.suiteRegistry.getSuite(keyRecord.meta.suiteId);\n replacements.push(await suite.generateKeypair());\n }\n\n const newKeys: KeyRecord[] = [];\n \n for (const [i, keyRecord] of toRotate.entries()) {\n const newKeypair = replacements[i];\n \n const newMeta = await this.registerUnderFreshId(agentId, keyRecord.meta.suiteId, newKeyId =>\n this.keyRegistry.rotateKey(keyRecord.meta.keyId, newKeyId, newKeypair, {\n expiresAt: options.expiresAt,\n })\n );\n \n newKeys.push(toRecord(newMeta, newKeypair.publicKey));\n }\n \n return newKeys;\n }\n \n /**\n * Get or create key (idempotent).\n *\n * Concurrent calls on this SDK instance for the same agent and suite share\n * one creation. Two SDK instances (or processes) on one storage backend can\n * still each create a key; that needs a lock in the backend.\n */\n async getOrCreateKey(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n assertAgentId(agentId);\n const slot = JSON.stringify([agentId, profile.primarySignatureSuite]);\n\n const pending = this.getOrCreateInFlight.get(slot);\n if (pending) {\n const record = await pending;\n return toRecord(record.meta, record.publicKey);\n }\n\n const work = (async () => {\n // Check if key exists\n const existingKeys = await this.listKeysForAgent(agentId, true);\n const primaryKey = existingKeys.find(\n k => k.meta.suiteId === profile.primarySignatureSuite\n );\n \n if (primaryKey) {\n return primaryKey;\n }\n \n // Create new key\n return await this.createKey(agentId, profile, options);\n })();\n\n this.getOrCreateInFlight.set(slot, work);\n try {\n return await work;\n } finally {\n this.getOrCreateInFlight.delete(slot);\n }\n }\n\n /**\n * Create both primary and secondary keys for an agent.\n */\n async createDualSignatureKeys(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<{ primaryKey: KeyRecord; secondaryKey: KeyRecord }> {\n if (!profile.secondarySignatureSuite) {\n throw new Error('secondarySignatureSuite is required to create dual signature keys');\n }\n this.assertDualProfile(profile);\n\n const primaryKey = await this.createKey(agentId, {\n primarySignatureSuite: profile.primarySignatureSuite,\n }, options);\n\n const secondaryKey = await this.createKey(agentId, {\n primarySignatureSuite: profile.secondarySignatureSuite,\n }, options);\n\n return { primaryKey, secondaryKey };\n }\n\n /**\n * Idempotent creation of both primary and secondary keys.\n */\n async getOrCreateDualSignatureKeys(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<{ primaryKey: KeyRecord; secondaryKey: KeyRecord }> {\n if (!profile.secondarySignatureSuite) {\n throw new Error('secondarySignatureSuite is required to create dual signature keys');\n }\n this.assertDualProfile(profile);\n\n const primaryKey = await this.getOrCreateKey(agentId, {\n primarySignatureSuite: profile.primarySignatureSuite,\n }, options);\n\n const secondaryKey = await this.getOrCreateKey(agentId, {\n primarySignatureSuite: profile.secondarySignatureSuite,\n }, options);\n\n return { primaryKey, secondaryKey };\n }\n\n /**\n * Fail before creating either key if the pair could not be a hybrid pair:\n * an unknown suite, or the same suite twice (two ECDSA keys are not a\n * classical + post-quantum pair, whatever the profile calls them).\n */\n private assertDualProfile(profile: CryptoProfile): void {\n this.suiteRegistry.getSuite(profile.primarySignatureSuite);\n this.suiteRegistry.getSuite(profile.secondarySignatureSuite!);\n if (profile.primarySignatureSuite === profile.secondarySignatureSuite) {\n throw new Error(\n `Dual signature keys need two different suites; both are ${profile.primarySignatureSuite}`\n );\n }\n }\n\n /**\n * Sign with one or more suites for an agent.\n */\n async signWithSuites(\n agentId: string,\n message: Uint8Array,\n suites?: string[]\n ): Promise<MultiSignatureResult> {\n const activeKeys = this.sortKeysByCreatedAt(await this.listKeysForAgent(agentId, true));\n\n if (activeKeys.length === 0) {\n throw new Error(`No active keys found for agent: ${agentId}`);\n }\n\n const suitesToUse = Array.from(\n new Set(suites?.length ? suites : activeKeys.map(k => k.meta.suiteId))\n );\n const signatures: SuiteSignature[] = [];\n\n for (const suiteId of suitesToUse) {\n const key = activeKeys.find(k => k.meta.suiteId === suiteId);\n if (!key) {\n throw new Error(`No active key for suite '${suiteId}' and agent '${agentId}'`);\n }\n\n const signature = await this.signWithKey(key.meta.keyId, message);\n signatures.push({ suiteId, keyId: key.meta.keyId, signature });\n }\n\n return { signatures };\n }\n\n /**\n * Verify a set of signatures as a hybrid (multi-suite) signature by `agentId`.\n *\n * `allValid` is true only when ALL of these hold:\n * - at least one signature was supplied;\n * - every supplied signature is by a key that belongs to `agentId`, names\n * that key's real suite, passes the key-status policy, and verifies;\n * - every REQUIRED suite has such a signature.\n *\n * The required suites come from the verifier: `options.requiredSuites`, or\n * by default the suites of the agent's currently usable keys in this SDK's\n * registry. They are never read from `signatures`. The check walks the\n * required suites and looks each one up among the valid signatures, so an\n * empty list, or one that merely omits the post-quantum signature, is\n * refused instead of passing because everything in it happens to be valid.\n */\n async verifyWithSuites(\n agentId: string,\n message: Uint8Array,\n signatures: SuiteSignature[],\n options: VerifyWithSuitesOptions = {}\n ): Promise<MultiVerificationResult> {\n assertAgentId(agentId);\n const keyStatus = options.keyStatus ?? 'not-revoked';\n\n const requiredSuites = Array.from(\n new Set(\n options.requiredSuites ??\n (await this.listKeysForAgent(agentId, true)).map(k => k.meta.suiteId)\n )\n );\n\n const refuse = (error: string, results: SuiteVerificationResult[] = []): MultiVerificationResult => ({\n results,\n allValid: false,\n requiredSuites,\n missingSuites: requiredSuites.filter(s => !results.some(r => r.valid && r.suiteId === s)),\n error,\n });\n\n if (!Array.isArray(signatures)) {\n return refuse('signatures must be an array');\n }\n\n const results: SuiteVerificationResult[] = [];\n\n for (const entry of signatures) {\n const suiteId = String(entry?.suiteId);\n const keyId = String(entry?.keyId);\n const fail = (error: string) => results.push({ suiteId, keyId, valid: false, error });\n\n try {\n if (agentIdOfKey(keyId) !== agentId) {\n fail(`Key does not belong to agent '${agentId}'`);\n continue;\n }\n const key = await this.keyRegistry.getPublicKey(keyId);\n if (!key) {\n fail('Key not found');\n continue;\n }\n if (key.meta.suiteId !== suiteId) {\n fail(`Suite mismatch: key is ${key.meta.suiteId}, signature claims ${suiteId}`);\n continue;\n }\n if (!statusAllows(key.meta, keyStatus)) {\n fail(`Key status not accepted (status: ${key.meta.status ?? 'active'}, policy: ${keyStatus})`);\n continue;\n }\n if (!(entry.signature instanceof Uint8Array)) {\n fail('Signature must be a Uint8Array');\n continue;\n }\n const valid = await this.verifyAgainst(key.meta, key.publicKey, message, entry.signature);\n if (valid) {\n results.push({ suiteId, keyId, valid: true });\n } else {\n fail('Signature verification failed');\n }\n } catch (error) {\n fail(error instanceof Error ? error.message : String(error));\n }\n }\n\n if (requiredSuites.length === 0) {\n return refuse(\n `No required suites: agent '${agentId}' has no usable keys and options.requiredSuites was not given`,\n results\n );\n }\n if (results.length === 0) {\n return refuse('No signatures supplied', results);\n }\n\n // Walk the REQUIRED suites and look each up among the valid signatures.\n const missingSuites = requiredSuites.filter(\n required => !results.some(r => r.valid && r.suiteId === required)\n );\n const everySuppliedValid = results.every(r => r.valid === true);\n\n return {\n results,\n allValid: everySuppliedValid && missingSuites.length === 0,\n requiredSuites,\n missingSuites,\n ...(missingSuites.length > 0\n ? { error: `No valid signature for required suite(s): ${missingSuites.join(', ')}` }\n : {}),\n };\n }\n \n /**\n * Generate a new BIP39 mnemonic phrase.\n * \n * @param strength 128 (12 words) or 256 (24 words)\n * @returns Mnemonic phrase\n */\n generateMnemonic(strength: 128 | 256 = 256): string {\n const bip32 = new BIP32Derivation();\n return bip32.generateMnemonic(strength);\n }\n \n /**\n * Create a key from a BIP39 mnemonic using HD derivation.\n * \n * Only works with suites that support BIP32 derivation (e.g., bsv-ecdsa-secp256k1).\n * \n * @param agentId Agent identifier\n * @param profile Crypto profile (must use derivation-capable suite)\n * @param mnemonic BIP39 mnemonic phrase (words and checksum are validated)\n * @param path BIP32 derivation path (default: \"m/44'/0'/0'/0/0\")\n * @param passphrase Optional BIP39 passphrase\n * @param options Additional key creation options\n * @returns KeyRecord with derived key\n * @throws if the mnemonic has an unknown word, a wrong word count or a bad checksum\n */\n async createKeyFromMnemonic(\n agentId: string,\n profile: CryptoProfile,\n mnemonic: string,\n path: string = BIP32Derivation.bitcoinPath(0, 0, 0),\n passphrase?: string,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n const bip32 = new BIP32Derivation();\n const seed = bip32.mnemonicToSeed(mnemonic, passphrase);\n \n try {\n return await this.createKey(agentId, profile, {\n ...options,\n derivationContext: {\n seed,\n path,\n },\n });\n } finally {\n // The seed is the root of every key in the wallet; do not leave it behind.\n seed.fill(0);\n }\n }\n \n /**\n * Get available capabilities for a specific suite.\n * \n * @param suiteId Suite identifier\n * @returns Array of capability names\n */\n getCapabilities(suiteId: string): string[] {\n const suite = this.suiteRegistry.getSuite(suiteId);\n const caps: string[] = [];\n \n if (suite.capabilities?.derivation) caps.push('derivation');\n if ((suite.capabilities as any)?.encryption) caps.push('encryption');\n if ((suite.capabilities as any)?.threshold) caps.push('threshold');\n \n return caps;\n }\n \n /**\n * Get all suite IDs that support a specific capability.\n * \n * @param capability Capability name\n * @returns Array of suite IDs\n */\n getSuitesWithCapability(capability: 'derivation' | 'encryption' | 'threshold'): string[] {\n const allSuites = this.suiteRegistry.getAllSuites();\n return allSuites\n .filter(suite => !!(suite.capabilities as any)?.[capability])\n .map(suite => suite.suiteId);\n }\n\n /**\n * Create a wallet key from a mnemonic at an explicit BIP44 coin type:\n * `m/44'/coinType'/account'/change/index`.\n *\n * The coin type is required and has no default. It decides which wallets\n * will find the key again: Bitcoin (BTC) is 0, Bitcoin SV is 236.\n *\n * @param agentId Agent identifier\n * @param mnemonic BIP39 mnemonic phrase (words and checksum are validated)\n * @param path Coin type and position in the BIP44 tree\n * @param options Additional key creation options\n * @returns KeyRecord with the derived secp256k1 key\n */\n async createWalletKey(\n agentId: string,\n mnemonic: string,\n path: WalletKeyPath,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n if (!path || typeof path.coinType !== 'number') {\n throw new Error(\n 'createWalletKey requires path.coinType (SLIP-44: Bitcoin is 0, Bitcoin SV is 236)'\n );\n }\n const derivationPath = BIP32Derivation.bip44Path(\n path.coinType,\n path.account ?? 0,\n path.change ? 1 : 0,\n path.index ?? 0\n );\n return this.createKeyFromMnemonic(\n agentId,\n { primarySignatureSuite: 'bsv-ecdsa-secp256k1' },\n mnemonic,\n derivationPath,\n path.passphrase,\n options\n );\n }\n \n /**\n * Create a wallet key from mnemonic at the Bitcoin (BTC) BIP44 path:\n * m/44'/0'/account'/change/addressIndex\n *\n * NOTE: coin type 0 is BTC. A Bitcoin SV wallet restoring the same mnemonic\n * looks under coin type 236 and will not find this key. The path is left\n * as it is because changing it would move every key already created with\n * this method. For new code use {@link createWalletKey}, which makes the\n * coin type explicit.\n * \n * @deprecated Use createWalletKey(agentId, mnemonic, { coinType, ... }).\n * @param agentId Agent identifier\n * @param mnemonic BIP39 mnemonic phrase\n * @param accountIndex Account index (default: 0)\n * @param addressIndex Address index (default: 0)\n * @param isChange Use change address path (default: false)\n * @param options Additional key creation options\n * @returns KeyRecord with Bitcoin-compatible key\n */\n async createBitcoinWalletKey(\n agentId: string,\n mnemonic: string,\n accountIndex: number = 0,\n addressIndex: number = 0,\n isChange: boolean = false,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n const path = BIP32Derivation.bitcoinPath(accountIndex, isChange ? 1 : 0, addressIndex);\n \n return this.createKeyFromMnemonic(\n agentId,\n { primarySignatureSuite: 'bsv-ecdsa-secp256k1' },\n mnemonic,\n path,\n undefined,\n options\n );\n }\n \n /**\n * Helper: Get hash algorithm for a suite.\n */\n private getHashAlgorithm(suiteId: string): 'sha256' | 'sha3-256' | 'sha512' {\n if (suiteId.startsWith('ml-dsa')) {\n return 'sha3-256';\n }\n return 'sha256';\n }\n\n /**\n * Helper: register a key under the agent's next free key ID.\n *\n * The counter is cached per SDK instance, so another instance (or process)\n * on the same storage can have taken the ID already. The registry refuses\n * to overwrite; on that refusal the counter is re-read from storage and the\n * next ID is tried. Before, the second writer silently replaced the first\n * writer's private key.\n */\n private async registerUnderFreshId(\n agentId: string,\n suiteId: string,\n register: (keyId: string) => Promise<KeyMeta>\n ): Promise<KeyMeta> {\n // 'ml' for every ml-dsa suite, 'bsv' for bsv-ecdsa-secp256k1\n const suiteName = suiteId.split('-')[0].replace(/[^A-Za-z0-9]/g, '') || 'key';\n\n for (let attempt = 0; attempt < MAX_KEY_ID_ATTEMPTS; attempt++) {\n const counter = await this.getNextCounter(agentId);\n const keyId = `${agentId}:pk-${suiteName}-${counter}`;\n try {\n return await register(keyId);\n } catch (error) {\n if (!(error instanceof KeyAlreadyExistsError)) throw error;\n // Someone else holds that ID: forget the cached counter and re-read.\n this.counterInitialized.delete(agentId);\n this.keyCounter.delete(agentId);\n }\n }\n throw new Error(\n `Could not allocate a key ID for agent '${agentId}' after ${MAX_KEY_ID_ATTEMPTS} attempts`\n );\n }\n \n /**\n * Helper: Get next counter for an agent.\n */\n private async getNextCounter(agentId: string): Promise<number> {\n if (!this.counterInitialized.has(agentId)) {\n if (!this.counterInitPromises.has(agentId)) {\n const initPromise = (async () => {\n try {\n const existing = await this.keyRegistry.listKeys();\n const max = existing.reduce((acc, meta) => {\n if (agentIdOfKey(meta.keyId) !== agentId) return acc;\n const local = meta.keyId.slice(agentId.length + 1);\n const match = COUNTER_SUFFIX.exec(local);\n if (!match) return acc;\n const num = parseInt(match[1], 10);\n return Number.isSafeInteger(num) ? Math.max(acc, num) : acc;\n }, 0);\n // A counter handed out while this scan ran must not be reused.\n this.keyCounter.set(agentId, Math.max(max, this.keyCounter.get(agentId) || 0));\n this.counterInitialized.add(agentId);\n } finally {\n this.counterInitPromises.delete(agentId);\n }\n })();\n this.counterInitPromises.set(agentId, initPromise);\n }\n\n const pendingInit = this.counterInitPromises.get(agentId);\n if (pendingInit) {\n await pendingInit;\n }\n }\n\n const current = this.keyCounter.get(agentId) || 0;\n const next = current + 1;\n this.keyCounter.set(agentId, next);\n return next;\n }\n\n /**\n * Helper: sort keys deterministically by createdAt then keyId.\n */\n private sortKeysByCreatedAt(keys: KeyRecord[]): KeyRecord[] {\n return [...keys].sort((a, b) => {\n const aTime = new Date(a.meta.createdAt).getTime();\n const bTime = new Date(b.meta.createdAt).getTime();\n if (aTime !== bTime) return aTime - bTime;\n const priorityDiff = this.getSuitePriority(a.meta.suiteId) - this.getSuitePriority(b.meta.suiteId);\n if (priorityDiff !== 0) return priorityDiff;\n return a.meta.keyId.localeCompare(b.meta.keyId);\n });\n }\n\n private getSuitePriority(suiteId: string): number {\n if (suiteId.startsWith('ml-dsa')) return 0;\n if (suiteId.includes('ecdsa')) return 1;\n return 2;\n }\n}\n\n/**\n * Create a KeySDK instance with default configuration\n * \n * Uses in-memory storage and registers both ECDSA and ML-DSA suites.\n * For custom storage or different suites, instantiate DefaultKeySDK directly.\n * \n * @example\n * ```typescript\n * import { createKeySDK } from '@smartledger/keys';\n * \n * const sdk = createKeySDK();\n * const key = await sdk.createKey('my-agent', { primarySignatureSuite: 'ml-dsa-87' });\n * ```\n */\nexport function createKeySDK(config?: Partial<KeySDKConfig>): KeySDK {\n const keyRegistry = config?.keyRegistry || new KeyRegistry(new InMemoryKeyStorage());\n const suiteRegistry = config?.suiteRegistry || new SignatureSuiteRegistry();\n \n // Register default suites if not provided.\n //\n // All three ML-DSA levels are registered, not just 87. The README documents\n // ml-dsa-65 as the recommended default and ml-dsa-44 for constrained\n // devices; registering only 87 made every one of those examples throw\n // `Unknown signature suite` at runtime, with no way for a caller to fix it\n // -- SignatureSuiteRegistry is not re-exported from this package.\n if (!config?.suiteRegistry) {\n suiteRegistry.register(new BsvEcdsaSuite());\n suiteRegistry.register(new MlDsa44Suite());\n suiteRegistry.register(new MlDsa65Suite());\n suiteRegistry.register(new MlDsa87Suite());\n }\n \n return new DefaultKeySDK({\n keyRegistry,\n suiteRegistry,\n });\n}\n"]}
1
+ {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/sdk.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAo5BH,oCAuBC;AAz6BD,gDAkB6B;AA0CpB,6FAlDP,qBAAY,OAkDO;AAHrB,+DAA+D;AAClD,QAAA,uBAAuB,GAAG,qBAAqB,CAAC;AAI7D,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAC3C,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAE9B,SAAS,aAAa,CAAC,OAAgB;IACrC,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxD,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IACxD,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,IAAa,EAAE,SAAqB;IACpD,2EAA2E;IAC3E,2DAA2D;IAC3D,OAAO,EAAE,IAAI,EAAE,IAAA,qBAAY,EAAC,IAAI,CAAC,EAAE,SAAS,EAAE,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;AAC7E,CAAC;AAED,SAAS,YAAY,CAAC,IAAa,EAAE,MAAuB;IAC1D,IAAI,MAAM,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAClC,IAAI,MAAM,KAAK,aAAa;QAA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EAAE,CAAC;QAC3B,aAAa,CAAC,QAAQ,CAAC,IAAI,sBAAa,EAAE,CAAC,CAAC;QAC5C,aAAa,CAAC,QAAQ,CAAC,IAAI,qBAAY,EAAE,CAAC,CAAC;QAC3C,aAAa,CAAC,QAAQ,CAAC,IAAI,qBAAY,EAAE,CAAC,CAAC;QAC3C,aAAa,CAAC,QAAQ,CAAC,IAAI,qBAAY,EAAE,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,IAAI,aAAa,CAAC;QACvB,WAAW;QACX,aAAa;QACb,cAAc,EAAE,MAAM,EAAE,cAAc;KACvC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Default implementation of KeySDK.\n * \n * Integrates KeyRegistry and SignatureSuiteRegistry to provide\n * a clean, high-level API for key operations.\n */\n\nimport {\n KeyRegistry,\n SignatureSuiteRegistry,\n KeyMeta,\n Keypair,\n CryptoProfile,\n hashBytes,\n assertKeyUsable,\n isKeyUsable,\n cloneKeyMeta,\n agentIdOfKey,\n KeyAlreadyExistsError,\n BIP32Derivation,\n InMemoryKeyStorage,\n BsvEcdsaSuite,\n MlDsa44Suite,\n MlDsa65Suite,\n MlDsa87Suite,\n} from '@smartledger/crypto';\nimport {\n KeySDK,\n KeyRecord,\n CreateKeyOptions,\n AgentKeyConfig,\n MultiSignatureResult,\n MultiVerificationResult,\n SuiteSignature,\n SuiteVerificationResult,\n KeyStatusPolicy,\n VerifySignatureOptions,\n VerifyWithSuitesOptions,\n SignatureScheme,\n RotateAgentKeysOptions,\n WalletKeyPath,\n} from './types.js';\n\n/**\n * Configuration for DefaultKeySDK.\n */\nexport interface KeySDKConfig {\n /** Key registry instance */\n keyRegistry: KeyRegistry;\n \n /** Signature suite registry instance */\n suiteRegistry: SignatureSuiteRegistry;\n\n /**\n * Context string for ML-DSA signatures (FIPS 204), 1 to 255 bytes. An\n * ML-DSA signature verifies only under the context it was made with, so\n * two deployments with different contexts cannot have ML-DSA signatures\n * replayed between them. It does NOT enter an ECDSA signature: ECDSA has\n * no context, and the same ECDSA key and message verify in any deployment.\n * Default: `@smartledger/keys/4`.\n */\n signingContext?: string | Uint8Array;\n}\n\n/** The default ML-DSA context string of this major version. */\nexport const DEFAULT_SIGNING_CONTEXT = '@smartledger/keys/4';\n\nexport { agentIdOfKey };\n\nconst COUNTER_SUFFIX = /^pk-[^:-]+-(\\d+)$/;\nconst MAX_KEY_ID_ATTEMPTS = 8;\n\nfunction assertAgentId(agentId: unknown): asserts agentId is string {\n if (typeof agentId !== 'string' || agentId.length === 0) {\n throw new Error('agentId must be a non-empty string');\n }\n}\n\nfunction toRecord(meta: KeyMeta, publicKey: Uint8Array): KeyRecord {\n // Copies, so a caller cannot reach registry state through a KeyRecord even\n // when a custom storage backend hands out its own objects.\n return { meta: cloneKeyMeta(meta), publicKey: Uint8Array.from(publicKey) };\n}\n\nfunction statusAllows(meta: KeyMeta, policy: KeyStatusPolicy): boolean {\n if (policy === 'any') return true;\n if (policy === 'not-revoked') return meta.status !== 'revoked';\n return isKeyUsable(meta);\n}\n\n/**\n * Default KeySDK implementation.\n * \n * Provides a simple, safe API for key operations while hiding complexity.\n */\nexport class DefaultKeySDK implements KeySDK {\n private keyRegistry: KeyRegistry;\n private suiteRegistry: SignatureSuiteRegistry;\n private keyCounter = new Map<string, number>(); // agentId -> counter\n private counterInitialized = new Set<string>();\n private counterInitPromises = new Map<string, Promise<void>>();\n private getOrCreateInFlight = new Map<string, Promise<KeyRecord>>();\n \n private signingContext: Uint8Array;\n\n constructor(config: KeySDKConfig) {\n this.keyRegistry = config.keyRegistry;\n this.suiteRegistry = config.suiteRegistry;\n const context = config.signingContext ?? DEFAULT_SIGNING_CONTEXT;\n const bytes = typeof context === 'string' ? new TextEncoder().encode(context) : Uint8Array.from(context);\n if (bytes.length < 1 || bytes.length > 255) {\n throw new Error('signingContext must be 1 to 255 bytes');\n }\n this.signingContext = bytes;\n }\n \n /**\n * Create a new key for an agent.\n */\n async createKey(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n assertAgentId(agentId);\n\n // Get suite\n const suite = this.suiteRegistry.getSuite(profile.primarySignatureSuite);\n \n // Generate keypair (with optional derivation)\n let keypair;\n \n if (options.derivationContext) {\n // Check if suite supports derivation\n if (!suite.capabilities?.derivation) {\n const available = this.getSuitesWithCapability('derivation');\n throw new Error(\n `Suite '${suite.suiteId}' does not support key derivation.\\n` +\n (available.length > 0\n ? `Suites with derivation capability: ${available.join(', ')}\\n` +\n `Consider using one of these suites or remove the derivationContext option.`\n : `No suites currently support derivation. Remove the derivationContext option.`)\n );\n }\n \n // Use derivation capability\n keypair = await suite.capabilities.derivation.deriveKeypair(options.derivationContext);\n } else {\n // Standard random key generation\n keypair = await suite.generateKeypair();\n }\n \n const meta = await this.registerUnderFreshId(agentId, profile.primarySignatureSuite, keyId =>\n this.keyRegistry.registerKey(keyId, keypair, profile.primarySignatureSuite, {\n expiresAt: options.expiresAt,\n usage: options.usage || ['signing'],\n cryptoProfileVersion: options.cryptoProfileVersion || '1.0.0',\n // Record that (and where) the key was derived. Never the seed.\n derivation: options.derivationContext\n ? { path: options.derivationContext.path ?? '' }\n : undefined,\n })\n );\n \n return toRecord(meta, keypair.publicKey);\n }\n \n /**\n * Get an existing key.\n */\n async getKey(keyId: string): Promise<KeyRecord | null> {\n const result = await this.keyRegistry.getPublicKey(keyId);\n \n if (!result) {\n return null;\n }\n \n return toRecord(result.meta, result.publicKey);\n }\n \n /**\n * Sign with a key (private key never exposed).\n *\n * @throws if the key is unknown, not active, past its `expiresAt`, or not\n * registered for signing\n */\n async signWithKey(\n keyId: string,\n message: Uint8Array\n ): Promise<Uint8Array> {\n // Get full keypair (private access)\n const result = await this.keyRegistry.getKey(keyId);\n \n if (!result) {\n throw new Error(`Key not found: ${keyId}`);\n }\n \n if (result.meta.status && result.meta.status !== 'active') {\n throw new Error(`Key is not active: ${keyId} (status: ${result.meta.status})`);\n }\n // Status alone is not enough: an expired key keeps status 'active' until\n // markExpiredKeys() runs, and used to go on signing in the meantime.\n assertKeyUsable(result.meta);\n\n if (!result.meta.usage.some(u => u === 'signing' || u === 'both')) {\n throw new Error(\n `Key is not registered for signing: ${keyId} (usage: ${result.meta.usage.join(', ')})`\n );\n }\n \n // Get suite and sign\n const suite = this.suiteRegistry.getSuite(result.meta.suiteId);\n const { input, options } = await this.signingInput(result.meta.suiteId, message, 'v4');\n return await suite.sign(result.keypair.privateKey, input, options);\n }\n\n /**\n * What a key of `suiteId` signs for `message` under a scheme.\n *\n * v4: ML-DSA signs the message itself in FIPS 204 pure mode with this SDK's\n * context string, so a standard verifier needs only the message and the\n * context, and the signature is not limited by an outside digest. ECDSA\n * signs SHA-256(message): ECDSA signs a digest by definition and has no\n * context, so callers who need domain separation for it put the purpose in\n * the message.\n *\n * v3-digest: what 3.x signed — SHA3-256(message) for ML-DSA, empty context.\n */\n private async signingInput(\n suiteId: string,\n message: Uint8Array,\n scheme: SignatureScheme\n ): Promise<{ input: Uint8Array; options?: { context: Uint8Array } }> {\n if (scheme !== 'v4' && scheme !== 'v3-digest') {\n throw new Error(`Unknown signature scheme: ${String(scheme)}`);\n }\n if (suiteId.startsWith('ml-dsa')) {\n return scheme === 'v4'\n ? { input: message, options: { context: this.signingContext } }\n : { input: await hashBytes(message, 'sha3-256') };\n }\n return { input: await hashBytes(message, 'sha256') };\n }\n \n /**\n * Verify a signature.\n *\n * By default this is the cryptographic check only: a signature made by a\n * key that has since been rotated, expired or revoked still verifies, which\n * is what verifying a historical signature needs. Pass `keyStatus` to also\n * require something of the key's state now.\n */\n async verifySignature(\n keyId: string,\n message: Uint8Array,\n signature: Uint8Array,\n options: VerifySignatureOptions = {}\n ): Promise<boolean> {\n const result = await this.keyRegistry.getPublicKey(keyId);\n \n if (!result) {\n return false;\n }\n\n if (!statusAllows(result.meta, options.keyStatus ?? 'any')) {\n return false;\n }\n\n return this.verifyAgainst(result.meta, result.publicKey, message, signature, options.scheme ?? 'v4');\n }\n\n /** The cryptographic check alone. Anything but a strict `true` is a failure. */\n private async verifyAgainst(\n meta: KeyMeta,\n publicKey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array,\n scheme: SignatureScheme = 'v4'\n ): Promise<boolean> {\n try {\n const suite = this.suiteRegistry.getSuite(meta.suiteId);\n const { input, options } = await this.signingInput(meta.suiteId, message, scheme);\n return (await suite.verify(publicKey, input, signature, options)) === true;\n } catch {\n return false;\n }\n }\n \n /**\n * List keys for an agent.\n */\n async listKeysForAgent(\n agentId: string,\n activeOnly: boolean = true\n ): Promise<KeyRecord[]> {\n assertAgentId(agentId);\n\n const keys = activeOnly\n ? await this.keyRegistry.listActiveKeys()\n : await this.keyRegistry.listKeys();\n \n // Exact ownership, not a prefix match (see agentIdOfKey)\n const agentKeys = keys.filter(meta => agentIdOfKey(meta.keyId) === agentId);\n \n // Convert to KeyRecords\n const records: KeyRecord[] = [];\n \n for (const meta of agentKeys) {\n const result = await this.keyRegistry.getPublicKey(meta.keyId);\n if (result) {\n records.push(toRecord(result.meta, result.publicKey));\n }\n }\n \n return records;\n }\n \n /**\n * Get active crypto profile for an agent.\n */\n async getActiveCryptoProfile(agentId: string): Promise<CryptoProfile | null> {\n const keys = await this.listKeysForAgent(agentId, true);\n \n if (keys.length === 0) {\n return null;\n }\n \n // Group by suite\n const sorted = this.sortKeysByCreatedAt(keys);\n const suites = new Set(sorted.map(k => k.meta.suiteId));\n const suiteArray = Array.from(suites);\n \n // Assume first is primary, second is secondary\n return {\n primarySignatureSuite: suiteArray[0],\n secondarySignatureSuite: suiteArray[1],\n };\n }\n \n /**\n * Rotate all keys for an agent.\n *\n * Each replacement gets its predecessor's lifetime again, counted from now\n * (or `options.expiresAt`); it does not inherit the old expiry instant.\n *\n * A key derived from a seed cannot be re-derived here, because the SDK does\n * not keep seeds. By default the call refuses, before changing anything,\n * rather than silently swapping a recoverable key for a random one. See\n * {@link RotateAgentKeysOptions.derivedKeys}.\n */\n async rotateAgentKeys(\n agentId: string,\n options: RotateAgentKeysOptions = {}\n ): Promise<KeyRecord[]> {\n const derivedPolicy = options.derivedKeys ?? 'error';\n const activeKeys = await this.listKeysForAgent(agentId, true);\n\n // Decide everything before changing anything.\n const toRotate: KeyRecord[] = [];\n for (const keyRecord of activeKeys) {\n // Resolves the suite now, so an unknown suite fails before any rotation.\n this.suiteRegistry.getSuite(keyRecord.meta.suiteId);\n if (keyRecord.meta.derivation) {\n if (derivedPolicy === 'error') {\n throw new Error(\n `Key ${keyRecord.meta.keyId} was derived from a seed ` +\n `(path ${keyRecord.meta.derivation.path || 'unknown'}). Rotating it here would ` +\n `replace it with a random key that the mnemonic cannot recover. Derive the ` +\n `successor yourself with createKeyFromMnemonic at a new path, or pass ` +\n `{ derivedKeys: 'skip' } or { derivedKeys: 'randomize' }. No keys were rotated.`\n );\n }\n if (derivedPolicy === 'skip') continue;\n }\n toRotate.push(keyRecord);\n }\n\n // Generate every replacement before committing any, so a failing suite\n // cannot leave the agent half rotated. The commits below are then one\n // registry rotation per key; they are not a single transaction, so a\n // storage failure part-way through leaves the earlier keys rotated.\n const replacements: Keypair[] = [];\n for (const keyRecord of toRotate) {\n const suite = this.suiteRegistry.getSuite(keyRecord.meta.suiteId);\n replacements.push(await suite.generateKeypair());\n }\n\n const newKeys: KeyRecord[] = [];\n \n for (const [i, keyRecord] of toRotate.entries()) {\n const newKeypair = replacements[i];\n \n const newMeta = await this.registerUnderFreshId(agentId, keyRecord.meta.suiteId, newKeyId =>\n this.keyRegistry.rotateKey(keyRecord.meta.keyId, newKeyId, newKeypair, {\n expiresAt: options.expiresAt,\n })\n );\n \n newKeys.push(toRecord(newMeta, newKeypair.publicKey));\n }\n \n return newKeys;\n }\n \n /**\n * Get or create key (idempotent).\n *\n * Concurrent calls on this SDK instance for the same agent and suite share\n * one creation. Two SDK instances (or processes) on one storage backend can\n * still each create a key; that needs a lock in the backend.\n */\n async getOrCreateKey(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n assertAgentId(agentId);\n const slot = JSON.stringify([agentId, profile.primarySignatureSuite]);\n\n const pending = this.getOrCreateInFlight.get(slot);\n if (pending) {\n const record = await pending;\n return toRecord(record.meta, record.publicKey);\n }\n\n const work = (async () => {\n // Check if key exists\n const existingKeys = await this.listKeysForAgent(agentId, true);\n const primaryKey = existingKeys.find(\n k => k.meta.suiteId === profile.primarySignatureSuite\n );\n \n if (primaryKey) {\n return primaryKey;\n }\n \n // Create new key\n return await this.createKey(agentId, profile, options);\n })();\n\n this.getOrCreateInFlight.set(slot, work);\n try {\n return await work;\n } finally {\n this.getOrCreateInFlight.delete(slot);\n }\n }\n\n /**\n * Create both primary and secondary keys for an agent.\n */\n async createDualSignatureKeys(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<{ primaryKey: KeyRecord; secondaryKey: KeyRecord }> {\n if (!profile.secondarySignatureSuite) {\n throw new Error('secondarySignatureSuite is required to create dual signature keys');\n }\n this.assertDualProfile(profile);\n\n const primaryKey = await this.createKey(agentId, {\n primarySignatureSuite: profile.primarySignatureSuite,\n }, options);\n\n const secondaryKey = await this.createKey(agentId, {\n primarySignatureSuite: profile.secondarySignatureSuite,\n }, options);\n\n return { primaryKey, secondaryKey };\n }\n\n /**\n * Idempotent creation of both primary and secondary keys.\n */\n async getOrCreateDualSignatureKeys(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<{ primaryKey: KeyRecord; secondaryKey: KeyRecord }> {\n if (!profile.secondarySignatureSuite) {\n throw new Error('secondarySignatureSuite is required to create dual signature keys');\n }\n this.assertDualProfile(profile);\n\n const primaryKey = await this.getOrCreateKey(agentId, {\n primarySignatureSuite: profile.primarySignatureSuite,\n }, options);\n\n const secondaryKey = await this.getOrCreateKey(agentId, {\n primarySignatureSuite: profile.secondarySignatureSuite,\n }, options);\n\n return { primaryKey, secondaryKey };\n }\n\n /**\n * Fail before creating either key if the pair could not be a hybrid pair:\n * an unknown suite, or the same suite twice (two ECDSA keys are not a\n * classical + post-quantum pair, whatever the profile calls them).\n */\n private assertDualProfile(profile: CryptoProfile): void {\n this.suiteRegistry.getSuite(profile.primarySignatureSuite);\n this.suiteRegistry.getSuite(profile.secondarySignatureSuite!);\n if (profile.primarySignatureSuite === profile.secondarySignatureSuite) {\n throw new Error(\n `Dual signature keys need two different suites; both are ${profile.primarySignatureSuite}`\n );\n }\n }\n\n /**\n * Sign with one or more suites for an agent.\n */\n async signWithSuites(\n agentId: string,\n message: Uint8Array,\n suites?: string[]\n ): Promise<MultiSignatureResult> {\n const activeKeys = this.sortKeysByCreatedAt(await this.listKeysForAgent(agentId, true));\n\n if (activeKeys.length === 0) {\n throw new Error(`No active keys found for agent: ${agentId}`);\n }\n\n const suitesToUse = Array.from(\n new Set(suites?.length ? suites : activeKeys.map(k => k.meta.suiteId))\n );\n const signatures: SuiteSignature[] = [];\n\n for (const suiteId of suitesToUse) {\n const key = activeKeys.find(k => k.meta.suiteId === suiteId);\n if (!key) {\n throw new Error(`No active key for suite '${suiteId}' and agent '${agentId}'`);\n }\n\n const signature = await this.signWithKey(key.meta.keyId, message);\n signatures.push({ suiteId, keyId: key.meta.keyId, signature });\n }\n\n return { signatures };\n }\n\n /**\n * Verify a set of signatures as a hybrid (multi-suite) signature by `agentId`.\n *\n * `allValid` is true only when ALL of these hold:\n * - at least one signature was supplied;\n * - every supplied signature is by a key that belongs to `agentId`, names\n * that key's real suite, passes the key-status policy, and verifies;\n * - every REQUIRED suite has such a signature.\n *\n * The required suites come from the verifier: `options.requiredSuites`, or\n * by default the suites of the agent's currently usable keys in this SDK's\n * registry. They are never read from `signatures`. The check walks the\n * required suites and looks each one up among the valid signatures, so an\n * empty list, or one that merely omits the post-quantum signature, is\n * refused instead of passing because everything in it happens to be valid.\n */\n async verifyWithSuites(\n agentId: string,\n message: Uint8Array,\n signatures: SuiteSignature[],\n options: VerifyWithSuitesOptions = {}\n ): Promise<MultiVerificationResult> {\n assertAgentId(agentId);\n const keyStatus = options.keyStatus ?? 'not-revoked';\n\n const requiredSuites = Array.from(\n new Set(\n options.requiredSuites ??\n (await this.listKeysForAgent(agentId, true)).map(k => k.meta.suiteId)\n )\n );\n\n const refuse = (error: string, results: SuiteVerificationResult[] = []): MultiVerificationResult => ({\n results,\n allValid: false,\n requiredSuites,\n missingSuites: requiredSuites.filter(s => !results.some(r => r.valid && r.suiteId === s)),\n error,\n });\n\n if (!Array.isArray(signatures)) {\n return refuse('signatures must be an array');\n }\n\n const results: SuiteVerificationResult[] = [];\n\n for (const entry of signatures) {\n const suiteId = String(entry?.suiteId);\n const keyId = String(entry?.keyId);\n const fail = (error: string) => results.push({ suiteId, keyId, valid: false, error });\n\n try {\n if (agentIdOfKey(keyId) !== agentId) {\n fail(`Key does not belong to agent '${agentId}'`);\n continue;\n }\n const key = await this.keyRegistry.getPublicKey(keyId);\n if (!key) {\n fail('Key not found');\n continue;\n }\n if (key.meta.suiteId !== suiteId) {\n fail(`Suite mismatch: key is ${key.meta.suiteId}, signature claims ${suiteId}`);\n continue;\n }\n if (!statusAllows(key.meta, keyStatus)) {\n fail(`Key status not accepted (status: ${key.meta.status ?? 'active'}, policy: ${keyStatus})`);\n continue;\n }\n if (!(entry.signature instanceof Uint8Array)) {\n fail('Signature must be a Uint8Array');\n continue;\n }\n const valid = await this.verifyAgainst(key.meta, key.publicKey, message, entry.signature, options.scheme ?? 'v4');\n if (valid) {\n results.push({ suiteId, keyId, valid: true });\n } else {\n fail('Signature verification failed');\n }\n } catch (error) {\n fail(error instanceof Error ? error.message : String(error));\n }\n }\n\n if (requiredSuites.length === 0) {\n return refuse(\n `No required suites: agent '${agentId}' has no usable keys and options.requiredSuites was not given`,\n results\n );\n }\n if (results.length === 0) {\n return refuse('No signatures supplied', results);\n }\n\n // Walk the REQUIRED suites and look each up among the valid signatures.\n const missingSuites = requiredSuites.filter(\n required => !results.some(r => r.valid && r.suiteId === required)\n );\n const everySuppliedValid = results.every(r => r.valid === true);\n\n return {\n results,\n allValid: everySuppliedValid && missingSuites.length === 0,\n requiredSuites,\n missingSuites,\n ...(missingSuites.length > 0\n ? { error: `No valid signature for required suite(s): ${missingSuites.join(', ')}` }\n : {}),\n };\n }\n \n /**\n * Generate a new BIP39 mnemonic phrase.\n * \n * @param strength 128 (12 words) or 256 (24 words)\n * @returns Mnemonic phrase\n */\n generateMnemonic(strength: 128 | 256 = 256): string {\n const bip32 = new BIP32Derivation();\n return bip32.generateMnemonic(strength);\n }\n \n /**\n * Create a key from a BIP39 mnemonic using HD derivation.\n * \n * Only works with suites that support BIP32 derivation (e.g., bsv-ecdsa-secp256k1).\n * \n * @param agentId Agent identifier\n * @param profile Crypto profile (must use derivation-capable suite)\n * @param mnemonic BIP39 mnemonic phrase (words and checksum are validated)\n * @param path BIP32 derivation path (default: \"m/44'/0'/0'/0/0\")\n * @param passphrase Optional BIP39 passphrase\n * @param options Additional key creation options\n * @returns KeyRecord with derived key\n * @throws if the mnemonic has an unknown word, a wrong word count or a bad checksum\n */\n async createKeyFromMnemonic(\n agentId: string,\n profile: CryptoProfile,\n mnemonic: string,\n path: string = BIP32Derivation.bitcoinPath(0, 0, 0),\n passphrase?: string,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n const bip32 = new BIP32Derivation();\n const seed = bip32.mnemonicToSeed(mnemonic, passphrase);\n \n try {\n return await this.createKey(agentId, profile, {\n ...options,\n derivationContext: {\n seed,\n path,\n },\n });\n } finally {\n // The seed is the root of every key in the wallet; do not leave it behind.\n seed.fill(0);\n }\n }\n \n /**\n * Get available capabilities for a specific suite.\n * \n * @param suiteId Suite identifier\n * @returns Array of capability names\n */\n getCapabilities(suiteId: string): string[] {\n const suite = this.suiteRegistry.getSuite(suiteId);\n const caps: string[] = [];\n \n if (suite.capabilities?.derivation) caps.push('derivation');\n if ((suite.capabilities as any)?.encryption) caps.push('encryption');\n if ((suite.capabilities as any)?.threshold) caps.push('threshold');\n \n return caps;\n }\n \n /**\n * Get all suite IDs that support a specific capability.\n * \n * @param capability Capability name\n * @returns Array of suite IDs\n */\n getSuitesWithCapability(capability: 'derivation' | 'encryption' | 'threshold'): string[] {\n const allSuites = this.suiteRegistry.getAllSuites();\n return allSuites\n .filter(suite => !!(suite.capabilities as any)?.[capability])\n .map(suite => suite.suiteId);\n }\n\n /**\n * Create a wallet key from a mnemonic at an explicit BIP44 coin type:\n * `m/44'/coinType'/account'/change/index`.\n *\n * The coin type is required and has no default. It decides which wallets\n * will find the key again: Bitcoin (BTC) is 0, Bitcoin SV is 236.\n *\n * @param agentId Agent identifier\n * @param mnemonic BIP39 mnemonic phrase (words and checksum are validated)\n * @param path Coin type and position in the BIP44 tree\n * @param options Additional key creation options\n * @returns KeyRecord with the derived secp256k1 key\n */\n async createWalletKey(\n agentId: string,\n mnemonic: string,\n path: WalletKeyPath,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n if (!path || typeof path.coinType !== 'number') {\n throw new Error(\n 'createWalletKey requires path.coinType (SLIP-44: Bitcoin is 0, Bitcoin SV is 236)'\n );\n }\n const derivationPath = BIP32Derivation.bip44Path(\n path.coinType,\n path.account ?? 0,\n path.change ? 1 : 0,\n path.index ?? 0\n );\n return this.createKeyFromMnemonic(\n agentId,\n { primarySignatureSuite: 'bsv-ecdsa-secp256k1' },\n mnemonic,\n derivationPath,\n path.passphrase,\n options\n );\n }\n \n /**\n * Create a wallet key from mnemonic at the Bitcoin (BTC) BIP44 path:\n * m/44'/0'/account'/change/addressIndex\n *\n * NOTE: coin type 0 is BTC. A Bitcoin SV wallet restoring the same mnemonic\n * looks under coin type 236 and will not find this key. The path is left\n * as it is because changing it would move every key already created with\n * this method. For new code use {@link createWalletKey}, which makes the\n * coin type explicit.\n * \n * @deprecated Use createWalletKey(agentId, mnemonic, { coinType, ... }).\n * @param agentId Agent identifier\n * @param mnemonic BIP39 mnemonic phrase\n * @param accountIndex Account index (default: 0)\n * @param addressIndex Address index (default: 0)\n * @param isChange Use change address path (default: false)\n * @param options Additional key creation options\n * @returns KeyRecord with Bitcoin-compatible key\n */\n async createBitcoinWalletKey(\n agentId: string,\n mnemonic: string,\n accountIndex: number = 0,\n addressIndex: number = 0,\n isChange: boolean = false,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n const path = BIP32Derivation.bitcoinPath(accountIndex, isChange ? 1 : 0, addressIndex);\n \n return this.createKeyFromMnemonic(\n agentId,\n { primarySignatureSuite: 'bsv-ecdsa-secp256k1' },\n mnemonic,\n path,\n undefined,\n options\n );\n }\n \n /**\n * Helper: register a key under the agent's next free key ID.\n *\n * The counter is cached per SDK instance, so another instance (or process)\n * on the same storage can have taken the ID already. The registry refuses\n * to overwrite; on that refusal the counter is re-read from storage and the\n * next ID is tried. Before, the second writer silently replaced the first\n * writer's private key.\n */\n private async registerUnderFreshId(\n agentId: string,\n suiteId: string,\n register: (keyId: string) => Promise<KeyMeta>\n ): Promise<KeyMeta> {\n // 'ml' for every ml-dsa suite, 'bsv' for bsv-ecdsa-secp256k1\n const suiteName = suiteId.split('-')[0].replace(/[^A-Za-z0-9]/g, '') || 'key';\n\n for (let attempt = 0; attempt < MAX_KEY_ID_ATTEMPTS; attempt++) {\n const counter = await this.getNextCounter(agentId);\n const keyId = `${agentId}:pk-${suiteName}-${counter}`;\n try {\n return await register(keyId);\n } catch (error) {\n if (!(error instanceof KeyAlreadyExistsError)) throw error;\n // Someone else holds that ID: forget the cached counter and re-read.\n this.counterInitialized.delete(agentId);\n this.keyCounter.delete(agentId);\n }\n }\n throw new Error(\n `Could not allocate a key ID for agent '${agentId}' after ${MAX_KEY_ID_ATTEMPTS} attempts`\n );\n }\n \n /**\n * Helper: Get next counter for an agent.\n */\n private async getNextCounter(agentId: string): Promise<number> {\n if (!this.counterInitialized.has(agentId)) {\n if (!this.counterInitPromises.has(agentId)) {\n const initPromise = (async () => {\n try {\n const existing = await this.keyRegistry.listKeys();\n const max = existing.reduce((acc, meta) => {\n if (agentIdOfKey(meta.keyId) !== agentId) return acc;\n const local = meta.keyId.slice(agentId.length + 1);\n const match = COUNTER_SUFFIX.exec(local);\n if (!match) return acc;\n const num = parseInt(match[1], 10);\n return Number.isSafeInteger(num) ? Math.max(acc, num) : acc;\n }, 0);\n // A counter handed out while this scan ran must not be reused.\n this.keyCounter.set(agentId, Math.max(max, this.keyCounter.get(agentId) || 0));\n this.counterInitialized.add(agentId);\n } finally {\n this.counterInitPromises.delete(agentId);\n }\n })();\n this.counterInitPromises.set(agentId, initPromise);\n }\n\n const pendingInit = this.counterInitPromises.get(agentId);\n if (pendingInit) {\n await pendingInit;\n }\n }\n\n const current = this.keyCounter.get(agentId) || 0;\n const next = current + 1;\n this.keyCounter.set(agentId, next);\n return next;\n }\n\n /**\n * Helper: sort keys deterministically by createdAt then keyId.\n */\n private sortKeysByCreatedAt(keys: KeyRecord[]): KeyRecord[] {\n return [...keys].sort((a, b) => {\n const aTime = new Date(a.meta.createdAt).getTime();\n const bTime = new Date(b.meta.createdAt).getTime();\n if (aTime !== bTime) return aTime - bTime;\n const priorityDiff = this.getSuitePriority(a.meta.suiteId) - this.getSuitePriority(b.meta.suiteId);\n if (priorityDiff !== 0) return priorityDiff;\n return a.meta.keyId.localeCompare(b.meta.keyId);\n });\n }\n\n private getSuitePriority(suiteId: string): number {\n if (suiteId.startsWith('ml-dsa')) return 0;\n if (suiteId.includes('ecdsa')) return 1;\n return 2;\n }\n}\n\n/**\n * Create a KeySDK instance with default configuration\n * \n * Uses in-memory storage and registers both ECDSA and ML-DSA suites.\n * For custom storage or different suites, instantiate DefaultKeySDK directly.\n * \n * @example\n * ```typescript\n * import { createKeySDK } from '@smartledger/keys';\n * \n * const sdk = createKeySDK();\n * const key = await sdk.createKey('my-agent', { primarySignatureSuite: 'ml-dsa-87' });\n * ```\n */\nexport function createKeySDK(config?: Partial<KeySDKConfig>): KeySDK {\n const keyRegistry = config?.keyRegistry || new KeyRegistry(new InMemoryKeyStorage());\n const suiteRegistry = config?.suiteRegistry || new SignatureSuiteRegistry();\n \n // Register default suites if not provided.\n //\n // All three ML-DSA levels are registered, not just 87. The README documents\n // ml-dsa-65 as the recommended default and ml-dsa-44 for constrained\n // devices; registering only 87 made every one of those examples throw\n // `Unknown signature suite` at runtime, with no way for a caller to fix it\n // -- SignatureSuiteRegistry is not re-exported from this package.\n if (!config?.suiteRegistry) {\n suiteRegistry.register(new BsvEcdsaSuite());\n suiteRegistry.register(new MlDsa44Suite());\n suiteRegistry.register(new MlDsa65Suite());\n suiteRegistry.register(new MlDsa87Suite());\n }\n \n return new DefaultKeySDK({\n keyRegistry,\n suiteRegistry,\n signingContext: config?.signingContext,\n });\n}\n"]}
@@ -68,10 +68,21 @@ export interface MultiVerificationResult {
68
68
  * - `'usable'`: additionally require the key to be active and unexpired now.
69
69
  */
70
70
  export type KeyStatusPolicy = 'any' | 'not-revoked' | 'usable';
71
+ /**
72
+ * How a message becomes what a key signs.
73
+ * - `'v4'` (default, and the only scheme this version signs with): ML-DSA
74
+ * signs the message itself, FIPS 204 pure mode, with the SDK's context
75
+ * string; ECDSA signs `SHA-256(message)`.
76
+ * - `'v3-digest'`: what 3.x did — ML-DSA over `SHA3-256(message)` with the
77
+ * empty context. For verifying signatures made by 3.x only.
78
+ */
79
+ export type SignatureScheme = 'v4' | 'v3-digest';
71
80
  /** Options for {@link KeySDK.verifySignature}. */
72
81
  export interface VerifySignatureOptions {
73
82
  /** Default: `'any'`. */
74
83
  keyStatus?: KeyStatusPolicy;
84
+ /** Default: `'v4'`. Pass `'v3-digest'` to verify a signature made by 3.x. */
85
+ scheme?: SignatureScheme;
75
86
  }
76
87
  /** Options for {@link KeySDK.verifyWithSuites}. */
77
88
  export interface VerifyWithSuitesOptions {
@@ -86,6 +97,8 @@ export interface VerifyWithSuitesOptions {
86
97
  requiredSuites?: string[];
87
98
  /** Default: `'not-revoked'`. */
88
99
  keyStatus?: KeyStatusPolicy;
100
+ /** Default: `'v4'`. Applies to every signature in the set. */
101
+ scheme?: SignatureScheme;
89
102
  }
90
103
  /** Options for {@link KeySDK.rotateAgentKeys}. */
91
104
  export interface RotateAgentKeysOptions {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAEhF;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,OAAO,CAAC;IACd,SAAS,EAAE,UAAU,CAAC;CACvB;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,0CAA0C;IAC1C,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB,uCAAuC;IACvC,KAAK,CAAC,EAAE,KAAK,CAAC,SAAS,GAAG,YAAY,GAAG,MAAM,CAAC,CAAC;IAEjD,gDAAgD;IAChD,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAE9B,mEAAmE;IACnE,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;CACvC;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,UAAU,CAAC;CACvB;AAED,iDAAiD;AACjD,MAAM,WAAW,oBAAoB;IACnC,UAAU,EAAE,cAAc,EAAE,CAAC;CAC9B;AAED,sCAAsC;AACtC,MAAM,WAAW,uBAAuB;IACtC,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,oDAAoD;AACpD,MAAM,WAAW,uBAAuB;IACtC,OAAO,EAAE,uBAAuB,EAAE,CAAC;IACnC;;;;OAIG;IACH,QAAQ,EAAE,OAAO,CAAC;IAClB,6CAA6C;IAC7C,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,iEAAiE;IACjE,aAAa,EAAE,MAAM,EAAE,CAAC;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