@me2em/core 0.7.0-alpha.2 → 1.0.0-rc.2

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.
Files changed (92) hide show
  1. package/README.md +179 -32
  2. package/dist/attestation.d.ts +26 -17
  3. package/dist/attestation.d.ts.map +1 -1
  4. package/dist/attestation.js +76 -29
  5. package/dist/attestation.js.map +1 -1
  6. package/dist/canonical-name.d.ts +18 -0
  7. package/dist/canonical-name.d.ts.map +1 -1
  8. package/dist/canonical-name.js +28 -1
  9. package/dist/canonical-name.js.map +1 -1
  10. package/dist/crypto/derivation-paths.d.ts +33 -2
  11. package/dist/crypto/derivation-paths.d.ts.map +1 -1
  12. package/dist/crypto/derivation-paths.js +33 -2
  13. package/dist/crypto/derivation-paths.js.map +1 -1
  14. package/dist/crypto/derivation.d.ts +47 -0
  15. package/dist/crypto/derivation.d.ts.map +1 -0
  16. package/dist/crypto/derivation.js +68 -0
  17. package/dist/crypto/derivation.js.map +1 -0
  18. package/dist/crypto/ecdh.d.ts +19 -0
  19. package/dist/crypto/ecdh.d.ts.map +1 -0
  20. package/dist/crypto/ecdh.js +33 -0
  21. package/dist/crypto/ecdh.js.map +1 -0
  22. package/dist/crypto/ed25519.d.ts +24 -3
  23. package/dist/crypto/ed25519.d.ts.map +1 -1
  24. package/dist/crypto/ed25519.js +39 -6
  25. package/dist/crypto/ed25519.js.map +1 -1
  26. package/dist/crypto/hkdf.d.ts +10 -1
  27. package/dist/crypto/hkdf.d.ts.map +1 -1
  28. package/dist/crypto/hkdf.js +10 -1
  29. package/dist/crypto/hkdf.js.map +1 -1
  30. package/dist/crypto/index.d.ts +25 -0
  31. package/dist/crypto/index.d.ts.map +1 -1
  32. package/dist/crypto/index.js +25 -0
  33. package/dist/crypto/index.js.map +1 -1
  34. package/dist/disposed-error.d.ts +24 -0
  35. package/dist/disposed-error.d.ts.map +1 -0
  36. package/dist/disposed-error.js +39 -0
  37. package/dist/disposed-error.js.map +1 -0
  38. package/dist/errors.d.ts +67 -0
  39. package/dist/errors.d.ts.map +1 -0
  40. package/dist/errors.js +54 -0
  41. package/dist/errors.js.map +1 -0
  42. package/dist/handle.d.ts +300 -14
  43. package/dist/handle.d.ts.map +1 -1
  44. package/dist/handle.js +463 -54
  45. package/dist/handle.js.map +1 -1
  46. package/dist/identity.d.ts +55 -11
  47. package/dist/identity.d.ts.map +1 -1
  48. package/dist/identity.js +105 -35
  49. package/dist/identity.js.map +1 -1
  50. package/dist/index.d.ts +10 -5
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +8 -4
  53. package/dist/index.js.map +1 -1
  54. package/dist/seed.d.ts +15 -11
  55. package/dist/seed.d.ts.map +1 -1
  56. package/dist/seed.js +23 -17
  57. package/dist/seed.js.map +1 -1
  58. package/dist/session.d.ts +42 -5
  59. package/dist/session.d.ts.map +1 -1
  60. package/dist/session.js +248 -117
  61. package/dist/session.js.map +1 -1
  62. package/dist/subhandle.d.ts +1 -125
  63. package/dist/subhandle.d.ts.map +1 -1
  64. package/dist/subhandle.js +12 -179
  65. package/dist/subhandle.js.map +1 -1
  66. package/dist/types.d.ts +22 -0
  67. package/dist/types.d.ts.map +1 -0
  68. package/dist/types.js +6 -0
  69. package/dist/types.js.map +1 -0
  70. package/dist/util.d.ts +47 -0
  71. package/dist/util.d.ts.map +1 -1
  72. package/dist/util.js +72 -20
  73. package/dist/util.js.map +1 -1
  74. package/package.json +10 -4
  75. package/src/attestation.ts +88 -38
  76. package/src/canonical-name.ts +33 -1
  77. package/src/crypto/derivation-paths.ts +37 -2
  78. package/src/crypto/derivation.ts +90 -0
  79. package/src/crypto/ecdh.ts +37 -0
  80. package/src/crypto/ed25519.ts +39 -6
  81. package/src/crypto/hkdf.ts +10 -1
  82. package/src/crypto/index.ts +28 -1
  83. package/src/disposed-error.ts +45 -0
  84. package/src/errors.ts +88 -0
  85. package/src/handle.ts +630 -65
  86. package/src/identity.ts +111 -64
  87. package/src/index.ts +11 -6
  88. package/src/seed.ts +27 -17
  89. package/src/session.ts +336 -132
  90. package/src/subhandle.ts +12 -251
  91. package/src/types.ts +26 -0
  92. package/src/util.ts +78 -20
@@ -1 +1 @@
1
- {"version":3,"file":"handle.d.ts","sourceRoot":"","sources":["../src/handle.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEnE,OAAO,EAAE,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEtE;;;;;;;;GAQG;AACH,MAAM,WAAW,cAAc;IAC7B,mCAAmC;IACnC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,0CAA0C;IAC1C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,mCAAmC;IACnC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,MAAM;IACjB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAa;IACxC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAa;IACvC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAiB;IAE5C;;;;;;;;;OASG;gBACS,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,cAAc;IAO3E;;;;;OAKG;IACH,KAAK,IAAI,MAAM;IAOf;;;;;OAKG;IACG,IAAI,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;IAIjD;;;;;;;OAOG;WACU,MAAM,CACjB,SAAS,EAAE,UAAU,EACrB,IAAI,EAAE,UAAU,EAChB,SAAS,EAAE,UAAU,GACpB,OAAO,CAAC,OAAO,CAAC;IAInB,6DAA6D;IAC7D,OAAO,IAAI,MAAM;IAIjB,gEAAgE;IAChE,WAAW,IAAI,cAAc,GAAG,SAAS;IAIzC,uEAAu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EAAE,CAAC;IAE1B;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AA8DD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,qBAAa,SAAU,SAAQ,MAAO,YAAW,MAAM;;IAIrD;;;;;;;;;;;;;;OAcG;gBAED,UAAU,EAAE,UAAU,EACtB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EAAE,EACd,WAAW,CAAC,EAAE,iBAAiB;IA0BjC;;;;OAIG;IACH,OAAO,IAAI,MAAM,EAAE;IAInB;;;;OAIG;IACH,aAAa,IAAI,MAAM;IAIvB;;;;;;OAMG;IACH,QAAQ,IAAI,MAAM;IAIlB;;;;;;OAMG;IACH,MAAM,IAAI,OAAO;IAIjB;;;;OAIG;IACY,eAAe,IAAI,OAAO,CAAC,KAAK,CAAC;IAQhD;;;;;;;;;;;OAWG;IACH,cAAc,IAAI,iBAAiB;IASnC;;;;;;;;;;;;OAYG;IACH,sBAAsB,CAAC,OAAO,EAAE;QAC9B,QAAQ,EAAE,MAAM,CAAC;QACjB,MAAM,EAAE,MAAM,EAAE,CAAC;QACjB,GAAG,EAAE,MAAM,CAAC;KACb,GAAG,IAAI;IAoDR;;;;OAIG;IACM,MAAM,IAAI;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,EAAE,CAAA;KAAE;IASpE,CAAC,cAAc,CAAC,IAAI,MAAM;CAGpC"}
package/dist/handle.js CHANGED
@@ -1,11 +1,64 @@
1
1
  // handle.ts
2
+ //
3
+ // Handle AND SubHandle deliberately live in this one module (D4, PR-10):
4
+ // `SubHandle extends Handle`, and a cross-file static `import { SubHandle }
5
+ // from './subhandle.js'` here would create an ESM module cycle whose
6
+ // evaluation order is illegal — when the graph is rooted at this file the
7
+ // `class SubHandle extends Handle` statement runs before the `Handle` class
8
+ // declaration and dies with "ReferenceError: Cannot access 'Handle' before
9
+ // initialization" (reproduced on Node 24). The pre-PR-10 code dodged this
10
+ // with a dynamic `import('./subhandle.js')` inside `deriveSubHandle` — the
11
+ // smell the audit flagged. Co-locating the class pair keeps the module graph
12
+ // acyclic and 100% static; `subhandle.ts` remains a pure re-export facade
13
+ // preserving the public import path.
14
+ //
15
+ // All crypto primitives are reached through the `crypto/` wrappers
16
+ // (PR-10, 3.3.1): hkdf/sha256 via `crypto/hkdf.ts`, `ed` via
17
+ // `crypto/init.ts`, the X25519 Montgomery step via `crypto/ecdh.ts`, the
18
+ // SubHandle derivation via `crypto/derivation.ts`. No @noble import
19
+ // outside `crypto/`.
2
20
  import { ed } from './crypto/init.js';
3
- import { hkdf } from '@noble/hashes/hkdf.js';
4
- import { sha256 } from '@noble/hashes/sha2.js';
5
- import { ed25519, x25519 } from '@noble/curves/ed25519.js';
6
- import { normalizeName } from './canonical-name.js';
21
+ import { hkdf } from './crypto/hkdf.js';
22
+ import { deriveSubHandleKey } from './crypto/derivation.js';
23
+ import { rawX25519SharedSecret } from './crypto/ecdh.js';
24
+ import { normalizeName, normalizeContext } from './canonical-name.js';
7
25
  import { DERIVATION_PATHS } from './crypto/derivation-paths.js';
8
26
  import { Attestation } from './attestation.js';
27
+ import { DisposedError } from './disposed-error.js';
28
+ import { AttestationError } from './errors.js';
29
+ import { base64urlEncode, INSPECT_SYMBOL } from './util.js';
30
+ /** Default {@link Handle.derivePassword} output length (bytes). */
31
+ const DEFAULT_PASSWORD_BYTES = 16;
32
+ /** Upper HKDF-SHA256 output bound per RFC 5869: 255 × 32 bytes. */
33
+ const MAX_HKDF_BYTES = 255 * 32;
34
+ /**
35
+ * Revision-domain guard shared by {@link Handle.derivePassword} and
36
+ * {@link Handle.deriveChannelKey}. An omitted revision is the default
37
+ * (`1`); anything that is not a positive integer is rejected as
38
+ * `MALFORMED`/`FORMAT` (same pattern as `Session.create` ttl).
39
+ */
40
+ function assertRevision(revision) {
41
+ if (revision !== undefined &&
42
+ (typeof revision !== 'number' ||
43
+ !Number.isInteger(revision) ||
44
+ revision < 1)) {
45
+ throw new AttestationError('MALFORMED', 'FORMAT', `revision must be a positive integer, got: ${String(revision)}`);
46
+ }
47
+ }
48
+ /**
49
+ * Output-length guard for {@link Handle.derivePassword}: an integer in
50
+ * `[1, 8160]`. Pre-checking here keeps the failure an
51
+ * {@link AttestationError} instead of the raw `Error` @noble/hashes
52
+ * would throw beyond the RFC 5869 bound.
53
+ */
54
+ function assertByteLength(byteLength) {
55
+ if (typeof byteLength !== 'number' ||
56
+ !Number.isInteger(byteLength) ||
57
+ byteLength < 1 ||
58
+ byteLength > MAX_HKDF_BYTES) {
59
+ throw new AttestationError('MALFORMED', 'FORMAT', `byteLength must be an integer in [1, ${MAX_HKDF_BYTES}] (RFC 5869: 255 × SHA-256 output), got: ${String(byteLength)}`);
60
+ }
61
+ }
9
62
  /**
10
63
  * Represents a context-specific cryptographic handle derived from an {@link Identity}.
11
64
  *
@@ -18,13 +71,19 @@ import { Attestation } from './attestation.js';
18
71
  * (e.g., an IoT device deriving keys for its components). The private key
19
72
  * **never leaves the Handle** — derivation is performed internally using HKDF.
20
73
  *
74
+ * Handles own their lifecycle: {@link Handle.dispose} zeroizes the private
75
+ * key, after which every capability method throws a {@link DisposedError}.
76
+ * Serialization (`JSON.stringify`, console inspection) is redacted and never
77
+ * emits key material.
78
+ *
21
79
  * @category Core Primitives
22
80
  */
23
81
  export class Handle {
24
- privateKey;
25
- publicKey;
26
- _name;
27
- _metadata;
82
+ #privateKey;
83
+ #publicKey;
84
+ #name;
85
+ #metadata;
86
+ #disposed = false;
28
87
  /**
29
88
  * Creates a new Handle instance.
30
89
  *
@@ -32,14 +91,18 @@ export class Handle {
32
91
  * {@link Handle.deriveSubHandle}. Direct construction is discouraged.
33
92
  *
34
93
  * @param privateKey - The 32-byte Ed25519 private key for this handle.
94
+ * Copied on input — later mutation of the caller's buffer has no effect.
35
95
  * @param name - The context name this handle represents.
36
96
  * @param metadata - Optional metadata associated with this handle.
97
+ * Custom metadata is deep-copied (JSON-safe structures up to depth 8);
98
+ * non-plain values (Date, Map, functions) remain shared by reference —
99
+ * same caveats as `getSubMetadata()`.
37
100
  */
38
101
  constructor(privateKey, name, metadata) {
39
- this.privateKey = privateKey;
40
- this.publicKey = ed.getPublicKey(privateKey);
41
- this._name = name;
42
- this._metadata = metadata;
102
+ this.#privateKey = new Uint8Array(privateKey);
103
+ this.#publicKey = ed.getPublicKey(this.#privateKey);
104
+ this.#name = name;
105
+ this.#metadata = metadata ? deepCloneJsonValue(metadata) : undefined;
43
106
  }
44
107
  /**
45
108
  * Returns a URL-safe Base64-encoded identifier for this Handle,
@@ -48,42 +111,59 @@ export class Handle {
48
111
  * @returns A unique, URL-safe string identifier.
49
112
  */
50
113
  getId() {
51
- return btoa(String.fromCharCode(...this.publicKey))
52
- .replace(/\+/g, '-')
53
- .replace(/\//g, '_')
54
- .replace(/=+$/, '');
114
+ return base64urlEncode(this.#publicKey);
55
115
  }
56
116
  /**
57
- * Cryptographically signs arbitrary data using the Handle's private key.
117
+ * Cryptographically signs arbitrary data using the Handle's private key
118
+ * (implements {@link Signer} — a `Handle` is acceptable as the `signer`
119
+ * argument of {@link Attestation.issue}).
58
120
  *
59
121
  * @param data - The data to be signed, as a Uint8Array.
60
122
  * @returns A Promise resolving to the Ed25519 signature as a Uint8Array.
123
+ * @throws {DisposedError} If the Handle has been disposed.
61
124
  */
62
125
  async sign(data) {
63
- return ed.sign(data, this.privateKey);
126
+ this.#assertNotDisposed();
127
+ return ed.sign(data, this.#privateKey);
64
128
  }
65
129
  /**
66
130
  * Verifies an Ed25519 signature against the provided data and public key.
67
131
  *
132
+ * A signature whose length differs from the 64-byte Ed25519 size is
133
+ * rejected with `false` before any crypto runs (PR-7 pre-check) — the
134
+ * method therefore never throws for short/long signatures.
135
+ *
68
136
  * @param signature - The signature to verify (Uint8Array).
69
137
  * @param data - The original data that was signed (Uint8Array).
70
138
  * @param publicKey - The public key to verify against (Uint8Array).
71
139
  * @returns A Promise resolving to `true` if the signature is valid, `false` otherwise.
72
140
  */
73
141
  static async verify(signature, data, publicKey) {
142
+ if (signature.length !== 64) {
143
+ return false;
144
+ }
74
145
  return ed.verify(signature, data, publicKey);
75
146
  }
76
147
  /** @returns The context name associated with this Handle. */
77
148
  getName() {
78
- return this._name;
149
+ return this.#name;
79
150
  }
80
- /** @returns The metadata object associated with this Handle. */
151
+ /**
152
+ * @returns A deep copy of the metadata object associated with this
153
+ * Handle — mutating the returned object does not affect the Handle.
154
+ * Custom metadata is deep-copied (JSON-safe structures up to depth 8);
155
+ * non-plain values (Date, Map, functions) remain shared by reference —
156
+ * same caveats as `getSubMetadata()`.
157
+ */
81
158
  getMetadata() {
82
- return this._metadata;
159
+ return this.#metadata ? deepCloneJsonValue(this.#metadata) : undefined;
83
160
  }
84
- /** @returns A Uint8Array containing the 32-byte Ed25519 public key. */
161
+ /**
162
+ * @returns A copy of the 32-byte Ed25519 public key — mutating the
163
+ * returned array does not affect the Handle.
164
+ */
85
165
  getPublicKey() {
86
- return this.publicKey;
166
+ return new Uint8Array(this.#publicKey);
87
167
  }
88
168
  /** @returns The derivation path, or undefined for Handle (only SubHandle has a path). */
89
169
  getPath() {
@@ -119,13 +199,14 @@ export class Handle {
119
199
  * ```
120
200
  */
121
201
  async deriveSubHandle(name, metadata) {
202
+ this.#assertNotDisposed();
122
203
  const normalizedName = normalizeName(name);
123
- const info = new TextEncoder().encode(DERIVATION_PATHS.subhandle(this._name, normalizedName));
124
- // The private key is used internally and never leaves this class.
125
- const subKey = hkdf(sha256, this.privateKey, new Uint8Array(0), info, 32);
126
- const path = [this._name, normalizedName];
127
- const { SubHandle: SubHandleClass } = await import('./subhandle.js');
128
- return new SubHandleClass(subKey, normalizedName, path, metadata);
204
+ // Single shared derivation (PR-10, 5.3.3): byte-identical to the
205
+ // atomic Identity.deriveSubHandle path by construction — both entry
206
+ // points call crypto/derivation.ts#deriveSubHandleKey.
207
+ const subKey = deriveSubHandleKey(this.#privateKey, this.#name, normalizedName);
208
+ const path = [this.#name, normalizedName];
209
+ return new SubHandle(subKey, normalizedName, path, metadata);
129
210
  }
130
211
  /**
131
212
  * Issues an attestation for a derived SubHandle, binding its
@@ -152,9 +233,14 @@ export class Handle {
152
233
  * ```
153
234
  */
154
235
  async attestSubHandle(subName, grant, opts) {
155
- const normalized = normalizeName(subName);
156
- const sub = await this.deriveSubHandle(normalized);
157
- return Attestation.issue(this.privateKey, sub.getPublicKey(), normalized, grant, opts ?? {});
236
+ this.#assertNotDisposed();
237
+ // Single normalization (PR-11, 3.6): deriveSubHandle canonicalizes
238
+ // the subName (NFKC → lowercase → trim) and the returned SubHandle
239
+ // carries the canonical name — pre-normalizing here ran the same
240
+ // name through normalizeName twice. Attestation.issue applies its
241
+ // own defensive canonicalization on top (its public contract).
242
+ const sub = await this.deriveSubHandle(subName);
243
+ return Attestation.issue(this, sub.getPublicKey(), sub.getName(), grant, opts ?? {});
158
244
  }
159
245
  /**
160
246
  * Deterministically derives a secret (e.g., a password or API key) for a
@@ -162,23 +248,42 @@ export class Handle {
162
248
  *
163
249
  * The private key **never leaves this class**, ensuring maximum security.
164
250
  *
251
+ * The `context` is canonicalized NFKC → lowercase → trim before use
252
+ * (`' GitHub '`, `'github'` and `'GitHub'` yield the same secret).
253
+ * NFKC applies to the string `context` only — `options.revision` is
254
+ * an integer and is canonical by construction (no normalization).
255
+ *
256
+ * **Revision model (since 0.8.0, D3):** `options.revision` (positive
257
+ * integer, default `1`) selects an independent secret for the same
258
+ * context — revision 1 is the initial secret, revision 2, 3, … are for
259
+ * rotation (e.g. after a breach). Revision 1 is byte-identical to the
260
+ * pre-revision v1.0 derivation.
261
+ *
165
262
  * @param context - A unique identifier for the service (e.g., `'google'`, `'github'`).
166
- * @param length - Length of the derived raw bytes (default: 16 bytes ≈ 22 chars base64url).
263
+ * @param options - Derivation options.
167
264
  * @returns A URL-safe base64 string suitable for use as a strong password.
265
+ * @throws AttestationError `MALFORMED`/`FORMAT` if `revision` is not a
266
+ * positive integer, `byteLength` is not an integer in `[1, 8160]`, or
267
+ * the context is empty after canonicalization.
168
268
  *
169
269
  * @example
170
270
  * ```ts
171
- * const githubPassword = handle.derivePassword('github', 20);
271
+ * const githubPassword = handle.derivePassword('github', { byteLength: 20 });
272
+ * // after rotating the GitHub credential:
273
+ * const rotated = handle.derivePassword('github', { revision: 2 });
172
274
  * ```
173
275
  */
174
- derivePassword(context, length = 16) {
175
- const salt = new TextEncoder().encode(`me2em/secret/${context.toLowerCase().trim()}`);
176
- const info = new TextEncoder().encode('me2em/secret/v1');
177
- const secretBytes = hkdf(sha256, this.privateKey, salt, info, length);
178
- return btoa(String.fromCharCode(...secretBytes))
179
- .replace(/\+/g, '-')
180
- .replace(/\//g, '_')
181
- .replace(/=+$/, '');
276
+ derivePassword(context, options = {}) {
277
+ this.#assertNotDisposed();
278
+ assertRevision(options.revision);
279
+ const byteLength = options.byteLength ?? DEFAULT_PASSWORD_BYTES;
280
+ assertByteLength(byteLength);
281
+ const canonical = normalizeContext(context);
282
+ const salt = new TextEncoder().encode(`me2em/secret/${canonical}`);
283
+ const info = new TextEncoder().encode(DERIVATION_PATHS.password(options.revision ?? 1));
284
+ const secretBytes = hkdf(this.#privateKey, salt, info, byteLength);
285
+ // Audited @scure/base codec (A3) — no hand-rolled btoa alphabet math.
286
+ return base64urlEncode(secretBytes);
182
287
  }
183
288
  /**
184
289
  * Derives a symmetric 256-bit channel key for secure communication between
@@ -190,21 +295,39 @@ export class Handle {
190
295
  *
191
296
  * This enables zero-knowledge encrypted channels without key exchange protocols.
192
297
  *
298
+ * The `context` is canonicalized NFKC → lowercase → trim before use.
299
+ * NFKC applies to the string `context` only — `options.revision` is
300
+ * an integer and is canonical by construction (no normalization).
301
+ *
302
+ * **Revision model (since 0.8.0, D3):** `options.revision` (positive
303
+ * integer, default `1`) selects an independent 32-byte key for the same
304
+ * context — the sanctioned rotation path for a compromised channel
305
+ * without changing the context string. Revision 1 is byte-identical to
306
+ * the pre-revision v1.0 derivation.
307
+ *
193
308
  * @param context - Channel identifier for domain separation (e.g., `'drone-001'`).
194
- * Both parties **MUST** use the same context.
309
+ * Both parties **MUST** use the same context **and** the same revision.
310
+ * @param options - Derivation options.
195
311
  * @returns A 32-byte Uint8Array suitable for AES-256-GCM encryption.
312
+ * @throws AttestationError `MALFORMED`/`FORMAT` if `revision` is not a
313
+ * positive integer or the context is empty after canonicalization.
196
314
  *
197
315
  * @example
198
316
  * ```ts
199
317
  * // AES-GCM helpers are application-side; the protocol provides
200
318
  * // only the key:
201
319
  * const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
320
+ * // after rotating the channel (both sides migrate in lockstep):
321
+ * const rotatedKey = droneHandle.deriveChannelKey('telemetry-v1', { revision: 2 });
202
322
  * ```
203
323
  */
204
- deriveChannelKey(context) {
205
- const salt = new TextEncoder().encode(`me2em/channel/${context.toLowerCase().trim()}`);
206
- const info = new TextEncoder().encode('me2em/channel/v1');
207
- return hkdf(sha256, this.privateKey, salt, info, 32);
324
+ deriveChannelKey(context, options = {}) {
325
+ this.#assertNotDisposed();
326
+ assertRevision(options.revision);
327
+ const canonical = normalizeContext(context);
328
+ const salt = new TextEncoder().encode(`me2em/channel/${canonical}`);
329
+ const info = new TextEncoder().encode(DERIVATION_PATHS.channel(options.revision ?? 1));
330
+ return hkdf(this.#privateKey, salt, info, 32);
208
331
  }
209
332
  /**
210
333
  * Derives a shared secret using ECDH (X25519) for P2P key exchange.
@@ -223,17 +346,19 @@ export class Handle {
223
346
  * ```
224
347
  */
225
348
  async deriveSharedSecret(otherPublicKey) {
226
- const myPrivBytes = this.privateKey;
349
+ this.#assertNotDisposed();
350
+ const myPrivBytes = this.#privateKey;
227
351
  const otherPubBytes = otherPublicKey;
352
+ /* v8 ignore start -- defensive: the constructor already validates the
353
+ key length implicitly (ed25519.getPublicKey throws RangeError). */
228
354
  if (myPrivBytes.length !== 32) {
229
- throw new Error('Handle private key must be 32 bytes');
355
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Handle private key must be 32 bytes');
230
356
  }
357
+ /* v8 ignore stop */
231
358
  if (otherPubBytes.length !== 32) {
232
- throw new Error('Public key must be 32 bytes');
359
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Public key must be 32 bytes');
233
360
  }
234
- const x25519Priv = ed25519.utils.toMontgomerySecret(myPrivBytes);
235
- const x25519Pub = ed25519.utils.toMontgomery(otherPubBytes);
236
- const rawSharedSecret = x25519.getSharedSecret(x25519Priv, x25519Pub);
361
+ const rawSharedSecret = rawX25519SharedSecret(this.#privateKey, otherPubBytes);
237
362
  // Canonical, order-independent binding of both peers' public keys.
238
363
  const myPub = this.getPublicKey();
239
364
  const peers = [myPub, otherPubBytes].sort((a, b) => {
@@ -247,7 +372,291 @@ export class Handle {
247
372
  bound.set(peers[0], 0);
248
373
  bound.set(peers[1], 32);
249
374
  const info = new TextEncoder().encode(DERIVATION_PATHS.p2pChannelV2);
250
- return hkdf(sha256, rawSharedSecret, bound, info, 32);
375
+ return hkdf(rawSharedSecret, bound, info, 32);
376
+ }
377
+ /**
378
+ * Permanently destroys this Handle's key material.
379
+ *
380
+ * The private key bytes are zeroized; afterwards every capability method
381
+ * ({@link sign}, {@link deriveSubHandle}, {@link attestSubHandle},
382
+ * {@link derivePassword}, {@link deriveChannelKey},
383
+ * {@link deriveSharedSecret}) throws a {@link DisposedError}.
384
+ * Informational getters ({@link getName}, {@link getId},
385
+ * {@link getPublicKey}, {@link getMetadata}) keep working — they never
386
+ * touch key material.
387
+ *
388
+ * SubHandles inherit `dispose()`. Calling it more than once is a no-op
389
+ * (idempotent).
390
+ */
391
+ dispose() {
392
+ if (this.#disposed)
393
+ return;
394
+ this.#privateKey.fill(0);
395
+ this.#disposed = true;
396
+ }
397
+ #assertNotDisposed() {
398
+ if (this.#disposed)
399
+ throw new DisposedError('Handle');
400
+ }
401
+ /**
402
+ * Redacted serialization contract: `JSON.stringify(handle)` exposes only
403
+ * the object kind, the public identifier and the context name — never
404
+ * key material or metadata.
405
+ */
406
+ toJSON() {
407
+ return {
408
+ kind: 'Handle',
409
+ id: base64urlEncode(this.#publicKey),
410
+ name: this.#name,
411
+ };
412
+ }
413
+ [INSPECT_SYMBOL]() {
414
+ return `Handle(id=${base64urlEncode(this.#publicKey).slice(0, 8)}…, name=${JSON.stringify(this.#name)})`;
415
+ }
416
+ }
417
+ /**
418
+ * Extracts only display-safe fields for the base Handle metadata.
419
+ * Constraint fields stay in SubHandle's own storage and must never
420
+ * leak through Handle.getMetadata().
421
+ */
422
+ function extractDisplayFields(meta) {
423
+ if (!meta)
424
+ return undefined;
425
+ const display = {};
426
+ if (meta.displayName !== undefined)
427
+ display.displayName = meta.displayName;
428
+ if (meta.avatar !== undefined)
429
+ display.avatar = meta.avatar;
430
+ // copy any other custom fields, but never the constraint ones
431
+ const CONSTRAINT_KEYS = new Set([
432
+ 'allowedAudiences', 'allowedScopes', 'maxSessionTtl', 'expiresAt',
433
+ ]);
434
+ for (const [k, v] of Object.entries(meta)) {
435
+ if (!CONSTRAINT_KEYS.has(k)) {
436
+ display[k] = v;
437
+ }
438
+ }
439
+ return display;
440
+ }
441
+ /**
442
+ * Deep copy of Handle metadata for the {@link Handle.getMetadata} and
443
+ * {@link SubHandle.getSubMetadata} getters (PR-7; extended to the Handle
444
+ * constructor/getter for symmetry): JSON-safe values (plain objects and
445
+ * arrays, including nested ones) are duplicated so no caller mutation can
446
+ * reach the stored metadata or the enforced constraints. Non-plain values
447
+ * (Date, Map, class instances) are shared by reference at depth > 8 and
448
+ * documented as such.
449
+ */
450
+ function deepCloneJsonValue(value, depth = 0) {
451
+ if (depth > 8 || value === null || typeof value !== 'object')
452
+ return value;
453
+ if (Array.isArray(value)) {
454
+ return value.map((v) => deepCloneJsonValue(v, depth + 1));
455
+ }
456
+ const proto = Object.getPrototypeOf(value);
457
+ if (proto !== Object.prototype && proto !== null)
458
+ return value; // non-plain: share
459
+ const out = {};
460
+ for (const [k, v] of Object.entries(value)) {
461
+ out[k] = deepCloneJsonValue(v, depth + 1);
462
+ }
463
+ return out;
464
+ }
465
+ /**
466
+ * Deep-ish copy of SubHandle metadata: constraint arrays (the
467
+ * security-relevant part) are duplicated so the caller cannot mutate
468
+ * the enforced constraints after construction. Custom fields are
469
+ * shallow-copied (nested objects are not cloned).
470
+ */
471
+ function copySubMetadata(meta) {
472
+ const out = { ...(meta ?? {}) };
473
+ if (out.allowedAudiences !== undefined)
474
+ out.allowedAudiences = [...out.allowedAudiences];
475
+ if (out.allowedScopes !== undefined)
476
+ out.allowedScopes = [...out.allowedScopes];
477
+ return out;
478
+ }
479
+ /**
480
+ * Represents a context-isolated child Handle in the Me2eM hierarchy.
481
+ *
482
+ * A SubHandle is always derived from a parent {@link Handle} and represents
483
+ * a leaf node in the derivation tree (MAX_DEPTH = 2). It inherits all
484
+ * cryptographic capabilities of Handle (signing, key derivation, etc.) but
485
+ * adds:
486
+ *
487
+ * - A **derivation path** (`[handleName, subName]`) carried in session tokens.
488
+ * - **Constraint enforcement** on audience, scopes, and TTL at session creation.
489
+ * - An optional **expiration timestamp** for temporary access grants.
490
+ *
491
+ * SubHandle is used for polymorphism in {@link Session}: both Handle and
492
+ * SubHandle can create and verify sessions, but SubHandle sessions carry
493
+ * the additional `hPath` field for hierarchical auditing.
494
+ *
495
+ * The class is defined in the same module as {@link Handle} on purpose
496
+ * (D4, PR-10): `SubHandle extends Handle` plus a static import of the
497
+ * subclass from `handle.ts` would form an ESM module cycle that crashes
498
+ * at import time depending on the graph root; co-location keeps the
499
+ * graph acyclic. `subhandle.ts` re-exports this class unchanged, so the
500
+ * public import paths are unaffected.
501
+ *
502
+ * @category Core Primitives
503
+ */
504
+ export class SubHandle extends Handle {
505
+ #path;
506
+ #subMetadata;
507
+ /**
508
+ * Creates a new SubHandle instance.
509
+ *
510
+ * @internal Typically created via {@link Handle.deriveSubHandle} or
511
+ * {@link Identity.deriveSubHandle}. Direct construction is discouraged.
512
+ *
513
+ * @param privateKey - The 32-byte Ed25519 private key for this SubHandle.
514
+ * Copied on input by the Handle constructor.
515
+ * @param name - The SubHandle name.
516
+ * @param path - The derivation path, must have exactly 2 elements: `[handleName, subName]`.
517
+ * Copied on input — later mutation of the caller's array has no effect.
518
+ * @param subMetadata - Optional constraints and metadata.
519
+ * Copied on input (constraint arrays are duplicated).
520
+ * @throws {Error} If the path does not have exactly 2 elements.
521
+ */
522
+ constructor(privateKey, name, path, subMetadata) {
523
+ super(privateKey, name, extractDisplayFields(subMetadata));
524
+ if (path.length !== 2) {
525
+ throw new AttestationError('MALFORMED', 'FORMAT', `SubHandle path must have exactly 2 elements: [handleName, subName]. Got ${path.length}.`);
526
+ }
527
+ const normalizedName = normalizeName(name);
528
+ if (path[1] !== normalizedName) {
529
+ throw new AttestationError('MALFORMED', 'FORMAT', `path[1] must equal normalized name: path[1]=${JSON.stringify(path[1])}, name=${JSON.stringify(normalizedName)}`);
530
+ }
531
+ // Defensive copies: the caller keeps no live reference into this leaf.
532
+ this.#path = [...path];
533
+ this.#subMetadata = copySubMetadata(subMetadata);
534
+ }
535
+ /**
536
+ * Returns the full derivation path of this SubHandle.
537
+ *
538
+ * @returns A copy of the path array, e.g. `["station-001", "connector-1"]`.
539
+ */
540
+ getPath() {
541
+ return [...this.#path];
542
+ }
543
+ /**
544
+ * Returns the derivation path as a slash-separated string.
545
+ *
546
+ * @returns The path string, e.g. `"station-001/connector-1"`.
547
+ */
548
+ getPathString() {
549
+ return this.#path.join('/');
550
+ }
551
+ /**
552
+ * Returns the depth of this SubHandle in the derivation hierarchy.
553
+ *
554
+ * With MAX_DEPTH = 2, this is always `2` (Identity = 0, Handle = 1, SubHandle = 2).
555
+ *
556
+ * @returns The depth, always `2`.
557
+ */
558
+ getDepth() {
559
+ return 2;
560
+ }
561
+ /**
562
+ * Returns whether this SubHandle is a leaf node.
563
+ *
564
+ * With MAX_DEPTH = 2, a SubHandle is **always** a leaf and cannot derive children.
565
+ *
566
+ * @returns Always `true`.
567
+ */
568
+ isLeaf() {
569
+ return true;
570
+ }
571
+ /**
572
+ * SubHandle is a leaf node (depth = 2) and cannot derive children.
573
+ * Overrides the inherited `Handle.deriveSubHandle` to throw
574
+ * `AttestationError` `MAX_DEPTH_EXCEEDED`/`FORMAT`.
575
+ */
576
+ async deriveSubHandle() {
577
+ throw new AttestationError('MAX_DEPTH_EXCEEDED', 'FORMAT', 'Cannot derive child: maximum depth (2) reached or this SubHandle is marked as leaf');
578
+ }
579
+ /**
580
+ * Returns the SubHandle-specific metadata (constraints).
581
+ *
582
+ * The returned object is a **deep copy** (PR-7): JSON-safe nested
583
+ * structures (plain objects, arrays) are fully duplicated, so mutating
584
+ * the result — at any depth — cannot alter the constraints this
585
+ * SubHandle enforces. Non-plain values (Date, Map, class instances)
586
+ * are shared by reference; functions abort the deep copy and fall
587
+ * back to the shallow constraint-array-duplicating copy.
588
+ *
589
+ * @returns A deep copy of the SubHandleMetadata object.
590
+ */
591
+ getSubMetadata() {
592
+ for (const value of Object.values(this.#subMetadata)) {
593
+ // A function anywhere in the metadata cannot be deep-cloned by the
594
+ // generic copier — fall back to the shallow, array-duplicating copy.
595
+ if (typeof value === 'function')
596
+ return copySubMetadata(this.#subMetadata);
597
+ }
598
+ return deepCloneJsonValue(this.#subMetadata);
599
+ }
600
+ /**
601
+ * Validates session options against this SubHandle's constraints.
602
+ *
603
+ * Called internally by {@link Session.create} before signing. Throws if
604
+ * any constraint is violated:
605
+ * - `audience` not in `allowedAudiences`
606
+ * - any `scope` not in `allowedScopes`
607
+ * - `ttl` exceeds `maxSessionTtl`
608
+ * - current time is past `expiresAt`
609
+ *
610
+ * @param options - The session options to validate.
611
+ * @throws {Error} If any constraint is violated.
612
+ */
613
+ validateSessionOptions(options) {
614
+ // Audience check: undefined = unrestricted, [] = deny all
615
+ if (this.#subMetadata.allowedAudiences !== undefined) {
616
+ if (!this.#subMetadata.allowedAudiences.includes(options.audience)) {
617
+ throw new AttestationError('AUDIENCE_NOT_PERMITTED', 'SESSION', `Audience "${options.audience}" not allowed for this SubHandle. ` +
618
+ `Allowed: ${this.#subMetadata.allowedAudiences.length === 0
619
+ ? '(none — empty list denies all)'
620
+ : this.#subMetadata.allowedAudiences.join(', ')}`);
621
+ }
622
+ }
623
+ // Scopes check: undefined = unrestricted, [] = deny all
624
+ if (this.#subMetadata.allowedScopes !== undefined) {
625
+ const forbidden = options.scopes.filter(s => !this.#subMetadata.allowedScopes.includes(s));
626
+ // An empty allow-list denies every requested scope.
627
+ if (forbidden.length > 0) {
628
+ throw new AttestationError('SCOPE_EXCEEDED', 'SESSION', `Scopes not allowed for this SubHandle: ${forbidden.join(', ')}`);
629
+ }
630
+ }
631
+ // TTL check
632
+ if (this.#subMetadata.maxSessionTtl !== undefined &&
633
+ options.ttl > this.#subMetadata.maxSessionTtl) {
634
+ throw new AttestationError('TTL_EXCEEDED', 'SESSION', `TTL ${options.ttl}s exceeds max allowed ` +
635
+ `${this.#subMetadata.maxSessionTtl}s for this SubHandle`);
636
+ }
637
+ // SubHandle expiration check
638
+ if (this.#subMetadata.expiresAt !== undefined) {
639
+ const now = Math.floor(Date.now() / 1000);
640
+ if (now >= this.#subMetadata.expiresAt) {
641
+ throw new AttestationError('EXPIRED', 'SESSION', 'SubHandle has expired');
642
+ }
643
+ }
644
+ }
645
+ /**
646
+ * Redacted serialization contract: `JSON.stringify(sub)` exposes only the
647
+ * object kind, the public identifier, the name and the derivation path —
648
+ * never key material or constraint metadata.
649
+ */
650
+ toJSON() {
651
+ return {
652
+ kind: 'SubHandle',
653
+ id: base64urlEncode(this.getPublicKey()),
654
+ name: this.getName(),
655
+ path: [...this.#path],
656
+ };
657
+ }
658
+ [INSPECT_SYMBOL]() {
659
+ return `SubHandle(id=${base64urlEncode(this.getPublicKey()).slice(0, 8)}…, path=${this.#path.join('/')})`;
251
660
  }
252
661
  }
253
662
  //# sourceMappingURL=handle.js.map