@me2em/core 0.7.0-alpha.2 → 1.0.0-rc.1
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 +179 -32
- package/dist/attestation.d.ts +26 -17
- package/dist/attestation.d.ts.map +1 -1
- package/dist/attestation.js +76 -29
- package/dist/attestation.js.map +1 -1
- package/dist/canonical-name.d.ts +18 -0
- package/dist/canonical-name.d.ts.map +1 -1
- package/dist/canonical-name.js +28 -1
- package/dist/canonical-name.js.map +1 -1
- package/dist/crypto/derivation-paths.d.ts +33 -2
- package/dist/crypto/derivation-paths.d.ts.map +1 -1
- package/dist/crypto/derivation-paths.js +33 -2
- package/dist/crypto/derivation-paths.js.map +1 -1
- package/dist/crypto/derivation.d.ts +47 -0
- package/dist/crypto/derivation.d.ts.map +1 -0
- package/dist/crypto/derivation.js +68 -0
- package/dist/crypto/derivation.js.map +1 -0
- package/dist/crypto/ecdh.d.ts +19 -0
- package/dist/crypto/ecdh.d.ts.map +1 -0
- package/dist/crypto/ecdh.js +33 -0
- package/dist/crypto/ecdh.js.map +1 -0
- package/dist/crypto/ed25519.d.ts +24 -3
- package/dist/crypto/ed25519.d.ts.map +1 -1
- package/dist/crypto/ed25519.js +39 -6
- package/dist/crypto/ed25519.js.map +1 -1
- package/dist/crypto/hkdf.d.ts +10 -1
- package/dist/crypto/hkdf.d.ts.map +1 -1
- package/dist/crypto/hkdf.js +10 -1
- package/dist/crypto/hkdf.js.map +1 -1
- package/dist/crypto/index.d.ts +25 -0
- package/dist/crypto/index.d.ts.map +1 -1
- package/dist/crypto/index.js +25 -0
- package/dist/crypto/index.js.map +1 -1
- package/dist/disposed-error.d.ts +24 -0
- package/dist/disposed-error.d.ts.map +1 -0
- package/dist/disposed-error.js +39 -0
- package/dist/disposed-error.js.map +1 -0
- package/dist/errors.d.ts +67 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +54 -0
- package/dist/errors.js.map +1 -0
- package/dist/handle.d.ts +300 -14
- package/dist/handle.d.ts.map +1 -1
- package/dist/handle.js +463 -54
- package/dist/handle.js.map +1 -1
- package/dist/identity.d.ts +55 -11
- package/dist/identity.d.ts.map +1 -1
- package/dist/identity.js +105 -35
- package/dist/identity.js.map +1 -1
- package/dist/index.d.ts +9 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -4
- package/dist/index.js.map +1 -1
- package/dist/seed.d.ts +15 -11
- package/dist/seed.d.ts.map +1 -1
- package/dist/seed.js +23 -17
- package/dist/seed.js.map +1 -1
- package/dist/session.d.ts +42 -5
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +248 -117
- package/dist/session.js.map +1 -1
- package/dist/subhandle.d.ts +1 -125
- package/dist/subhandle.d.ts.map +1 -1
- package/dist/subhandle.js +12 -179
- package/dist/subhandle.js.map +1 -1
- package/dist/types.d.ts +22 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/util.d.ts +47 -0
- package/dist/util.d.ts.map +1 -1
- package/dist/util.js +72 -20
- package/dist/util.js.map +1 -1
- package/package.json +10 -4
- package/src/attestation.ts +88 -38
- package/src/canonical-name.ts +33 -1
- package/src/crypto/derivation-paths.ts +37 -2
- package/src/crypto/derivation.ts +90 -0
- package/src/crypto/ecdh.ts +37 -0
- package/src/crypto/ed25519.ts +39 -6
- package/src/crypto/hkdf.ts +10 -1
- package/src/crypto/index.ts +28 -1
- package/src/disposed-error.ts +45 -0
- package/src/errors.ts +88 -0
- package/src/handle.ts +630 -65
- package/src/identity.ts +111 -64
- package/src/index.ts +10 -6
- package/src/seed.ts +27 -17
- package/src/session.ts +336 -132
- package/src/subhandle.ts +12 -251
- package/src/types.ts +26 -0
- package/src/util.ts +78 -20
package/src/handle.ts
CHANGED
|
@@ -1,12 +1,33 @@
|
|
|
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 '
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { normalizeName } from './canonical-name.js';
|
|
7
|
-
import type { SubHandleMetadata, SubHandle } from './subhandle.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';
|
|
8
25
|
import { DERIVATION_PATHS } from './crypto/derivation-paths.js';
|
|
9
26
|
import { Attestation, type AttestationGrant } from './attestation.js';
|
|
27
|
+
import { DisposedError } from './disposed-error.js';
|
|
28
|
+
import { AttestationError } from './errors.js';
|
|
29
|
+
import type { Signer } from './types.js';
|
|
30
|
+
import { base64urlEncode, INSPECT_SYMBOL } from './util.js';
|
|
10
31
|
|
|
11
32
|
/**
|
|
12
33
|
* Metadata associated with a {@link Handle}.
|
|
@@ -26,6 +47,109 @@ export interface HandleMetadata {
|
|
|
26
47
|
[key: string]: unknown;
|
|
27
48
|
}
|
|
28
49
|
|
|
50
|
+
/**
|
|
51
|
+
* Options for {@link Handle.derivePassword}.
|
|
52
|
+
*
|
|
53
|
+
* All fields are optional; the defaults reproduce the frozen v1.0
|
|
54
|
+
* derivation exactly (specs/v1.0.md §3).
|
|
55
|
+
*
|
|
56
|
+
* @category Types
|
|
57
|
+
*/
|
|
58
|
+
export interface DerivePasswordOptions {
|
|
59
|
+
/**
|
|
60
|
+
* Positive integer revision of the secret (default `1`).
|
|
61
|
+
*
|
|
62
|
+
* Revision `1` — the initial secret — is byte-identical to the
|
|
63
|
+
* pre-revision derivation. Revision `N ≥ 2` derives a secret that is
|
|
64
|
+
* cryptographically independent of revision 1 for the same context:
|
|
65
|
+
* the sanctioned rotation path when a credential leaks, without
|
|
66
|
+
* changing the context string.
|
|
67
|
+
*
|
|
68
|
+
* Canonical by construction: NFKC normalization applies to the string
|
|
69
|
+
* `context` only. Integers have no Unicode representation, so no
|
|
70
|
+
* normalization is needed or performed on `revision`.
|
|
71
|
+
*/
|
|
72
|
+
revision?: number;
|
|
73
|
+
/**
|
|
74
|
+
* Length of the derived raw bytes in `[1, 8160]` (default `16` —
|
|
75
|
+
* ≈ 22 base64url chars). Upper bound is the RFC 5869 HKDF-SHA256
|
|
76
|
+
* limit (`255 × 32`); note the output is prefix-stable, so the first
|
|
77
|
+
* `n` bytes of a longer derivation equal the `n`-byte derivation.
|
|
78
|
+
*/
|
|
79
|
+
byteLength?: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Options for {@link Handle.deriveChannelKey}.
|
|
84
|
+
*
|
|
85
|
+
* All fields are optional; the defaults reproduce the frozen v1.0
|
|
86
|
+
* derivation exactly (specs/v1.0.md §3).
|
|
87
|
+
*
|
|
88
|
+
* @category Types
|
|
89
|
+
*/
|
|
90
|
+
export interface DeriveChannelKeyOptions {
|
|
91
|
+
/**
|
|
92
|
+
* Positive integer revision of the channel key (default `1`).
|
|
93
|
+
*
|
|
94
|
+
* Revision `N ≥ 2` derives a key that is independent of revision 1 for
|
|
95
|
+
* the same context — rotate a compromised channel by bumping the
|
|
96
|
+
* revision on **both** peers in lockstep.
|
|
97
|
+
*
|
|
98
|
+
* Canonical by construction: NFKC normalization applies to the string
|
|
99
|
+
* `context` only. Integers have no Unicode representation, so no
|
|
100
|
+
* normalization is needed or performed on `revision`.
|
|
101
|
+
*/
|
|
102
|
+
revision?: number;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Default {@link Handle.derivePassword} output length (bytes). */
|
|
106
|
+
const DEFAULT_PASSWORD_BYTES = 16;
|
|
107
|
+
|
|
108
|
+
/** Upper HKDF-SHA256 output bound per RFC 5869: 255 × 32 bytes. */
|
|
109
|
+
const MAX_HKDF_BYTES = 255 * 32;
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Revision-domain guard shared by {@link Handle.derivePassword} and
|
|
113
|
+
* {@link Handle.deriveChannelKey}. An omitted revision is the default
|
|
114
|
+
* (`1`); anything that is not a positive integer is rejected as
|
|
115
|
+
* `MALFORMED`/`FORMAT` (same pattern as `Session.create` ttl).
|
|
116
|
+
*/
|
|
117
|
+
function assertRevision(revision: number | undefined): void {
|
|
118
|
+
if (
|
|
119
|
+
revision !== undefined &&
|
|
120
|
+
(typeof revision !== 'number' ||
|
|
121
|
+
!Number.isInteger(revision) ||
|
|
122
|
+
revision < 1)
|
|
123
|
+
) {
|
|
124
|
+
throw new AttestationError(
|
|
125
|
+
'MALFORMED',
|
|
126
|
+
'FORMAT',
|
|
127
|
+
`revision must be a positive integer, got: ${String(revision)}`
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Output-length guard for {@link Handle.derivePassword}: an integer in
|
|
134
|
+
* `[1, 8160]`. Pre-checking here keeps the failure an
|
|
135
|
+
* {@link AttestationError} instead of the raw `Error` @noble/hashes
|
|
136
|
+
* would throw beyond the RFC 5869 bound.
|
|
137
|
+
*/
|
|
138
|
+
function assertByteLength(byteLength: number): void {
|
|
139
|
+
if (
|
|
140
|
+
typeof byteLength !== 'number' ||
|
|
141
|
+
!Number.isInteger(byteLength) ||
|
|
142
|
+
byteLength < 1 ||
|
|
143
|
+
byteLength > MAX_HKDF_BYTES
|
|
144
|
+
) {
|
|
145
|
+
throw new AttestationError(
|
|
146
|
+
'MALFORMED',
|
|
147
|
+
'FORMAT',
|
|
148
|
+
`byteLength must be an integer in [1, ${MAX_HKDF_BYTES}] (RFC 5869: 255 × SHA-256 output), got: ${String(byteLength)}`
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
29
153
|
/**
|
|
30
154
|
* Represents a context-specific cryptographic handle derived from an {@link Identity}.
|
|
31
155
|
*
|
|
@@ -38,13 +162,19 @@ export interface HandleMetadata {
|
|
|
38
162
|
* (e.g., an IoT device deriving keys for its components). The private key
|
|
39
163
|
* **never leaves the Handle** — derivation is performed internally using HKDF.
|
|
40
164
|
*
|
|
165
|
+
* Handles own their lifecycle: {@link Handle.dispose} zeroizes the private
|
|
166
|
+
* key, after which every capability method throws a {@link DisposedError}.
|
|
167
|
+
* Serialization (`JSON.stringify`, console inspection) is redacted and never
|
|
168
|
+
* emits key material.
|
|
169
|
+
*
|
|
41
170
|
* @category Core Primitives
|
|
42
171
|
*/
|
|
43
|
-
export class Handle {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
172
|
+
export class Handle implements Signer {
|
|
173
|
+
#privateKey: Uint8Array;
|
|
174
|
+
#publicKey: Uint8Array;
|
|
175
|
+
#name: string;
|
|
176
|
+
#metadata: HandleMetadata | undefined;
|
|
177
|
+
#disposed = false;
|
|
48
178
|
|
|
49
179
|
/**
|
|
50
180
|
* Creates a new Handle instance.
|
|
@@ -53,14 +183,18 @@ export class Handle {
|
|
|
53
183
|
* {@link Handle.deriveSubHandle}. Direct construction is discouraged.
|
|
54
184
|
*
|
|
55
185
|
* @param privateKey - The 32-byte Ed25519 private key for this handle.
|
|
186
|
+
* Copied on input — later mutation of the caller's buffer has no effect.
|
|
56
187
|
* @param name - The context name this handle represents.
|
|
57
188
|
* @param metadata - Optional metadata associated with this handle.
|
|
189
|
+
* Custom metadata is deep-copied (JSON-safe structures up to depth 8);
|
|
190
|
+
* non-plain values (Date, Map, functions) remain shared by reference —
|
|
191
|
+
* same caveats as `getSubMetadata()`.
|
|
58
192
|
*/
|
|
59
193
|
constructor(privateKey: Uint8Array, name: string, metadata?: HandleMetadata) {
|
|
60
|
-
this
|
|
61
|
-
this
|
|
62
|
-
this
|
|
63
|
-
this
|
|
194
|
+
this.#privateKey = new Uint8Array(privateKey);
|
|
195
|
+
this.#publicKey = ed.getPublicKey(this.#privateKey);
|
|
196
|
+
this.#name = name;
|
|
197
|
+
this.#metadata = metadata ? deepCloneJsonValue(metadata) as HandleMetadata : undefined;
|
|
64
198
|
}
|
|
65
199
|
|
|
66
200
|
/**
|
|
@@ -70,25 +204,30 @@ export class Handle {
|
|
|
70
204
|
* @returns A unique, URL-safe string identifier.
|
|
71
205
|
*/
|
|
72
206
|
getId(): string {
|
|
73
|
-
return
|
|
74
|
-
.replace(/\+/g, '-')
|
|
75
|
-
.replace(/\//g, '_')
|
|
76
|
-
.replace(/=+$/, '');
|
|
207
|
+
return base64urlEncode(this.#publicKey);
|
|
77
208
|
}
|
|
78
209
|
|
|
79
210
|
/**
|
|
80
|
-
* Cryptographically signs arbitrary data using the Handle's private key
|
|
211
|
+
* Cryptographically signs arbitrary data using the Handle's private key
|
|
212
|
+
* (implements {@link Signer} — a `Handle` is acceptable as the `signer`
|
|
213
|
+
* argument of {@link Attestation.issue}).
|
|
81
214
|
*
|
|
82
215
|
* @param data - The data to be signed, as a Uint8Array.
|
|
83
216
|
* @returns A Promise resolving to the Ed25519 signature as a Uint8Array.
|
|
217
|
+
* @throws {DisposedError} If the Handle has been disposed.
|
|
84
218
|
*/
|
|
85
219
|
async sign(data: Uint8Array): Promise<Uint8Array> {
|
|
86
|
-
|
|
220
|
+
this.#assertNotDisposed();
|
|
221
|
+
return ed.sign(data, this.#privateKey);
|
|
87
222
|
}
|
|
88
223
|
|
|
89
224
|
/**
|
|
90
225
|
* Verifies an Ed25519 signature against the provided data and public key.
|
|
91
226
|
*
|
|
227
|
+
* A signature whose length differs from the 64-byte Ed25519 size is
|
|
228
|
+
* rejected with `false` before any crypto runs (PR-7 pre-check) — the
|
|
229
|
+
* method therefore never throws for short/long signatures.
|
|
230
|
+
*
|
|
92
231
|
* @param signature - The signature to verify (Uint8Array).
|
|
93
232
|
* @param data - The original data that was signed (Uint8Array).
|
|
94
233
|
* @param publicKey - The public key to verify against (Uint8Array).
|
|
@@ -99,22 +238,34 @@ export class Handle {
|
|
|
99
238
|
data: Uint8Array,
|
|
100
239
|
publicKey: Uint8Array
|
|
101
240
|
): Promise<boolean> {
|
|
241
|
+
if (signature.length !== 64) {
|
|
242
|
+
return false;
|
|
243
|
+
}
|
|
102
244
|
return ed.verify(signature, data, publicKey);
|
|
103
245
|
}
|
|
104
246
|
|
|
105
247
|
/** @returns The context name associated with this Handle. */
|
|
106
248
|
getName(): string {
|
|
107
|
-
return this
|
|
249
|
+
return this.#name;
|
|
108
250
|
}
|
|
109
251
|
|
|
110
|
-
/**
|
|
252
|
+
/**
|
|
253
|
+
* @returns A deep copy of the metadata object associated with this
|
|
254
|
+
* Handle — mutating the returned object does not affect the Handle.
|
|
255
|
+
* Custom metadata is deep-copied (JSON-safe structures up to depth 8);
|
|
256
|
+
* non-plain values (Date, Map, functions) remain shared by reference —
|
|
257
|
+
* same caveats as `getSubMetadata()`.
|
|
258
|
+
*/
|
|
111
259
|
getMetadata(): HandleMetadata | undefined {
|
|
112
|
-
return this
|
|
260
|
+
return this.#metadata ? deepCloneJsonValue(this.#metadata) as HandleMetadata : undefined;
|
|
113
261
|
}
|
|
114
262
|
|
|
115
|
-
/**
|
|
263
|
+
/**
|
|
264
|
+
* @returns A copy of the 32-byte Ed25519 public key — mutating the
|
|
265
|
+
* returned array does not affect the Handle.
|
|
266
|
+
*/
|
|
116
267
|
getPublicKey(): Uint8Array {
|
|
117
|
-
return this
|
|
268
|
+
return new Uint8Array(this.#publicKey);
|
|
118
269
|
}
|
|
119
270
|
|
|
120
271
|
/** @returns The derivation path, or undefined for Handle (only SubHandle has a path). */
|
|
@@ -155,21 +306,14 @@ export class Handle {
|
|
|
155
306
|
* ```
|
|
156
307
|
*/
|
|
157
308
|
async deriveSubHandle(name: string, metadata?: SubHandleMetadata): Promise<SubHandle> {
|
|
309
|
+
this.#assertNotDisposed();
|
|
158
310
|
const normalizedName = normalizeName(name);
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
this.privateKey,
|
|
166
|
-
new Uint8Array(0),
|
|
167
|
-
info,
|
|
168
|
-
32
|
|
169
|
-
);
|
|
170
|
-
const path = [this._name, normalizedName];
|
|
171
|
-
const { SubHandle: SubHandleClass } = await import('./subhandle.js');
|
|
172
|
-
return new SubHandleClass(subKey, normalizedName, path, metadata);
|
|
311
|
+
// Single shared derivation (PR-10, 5.3.3): byte-identical to the
|
|
312
|
+
// atomic Identity.deriveSubHandle path by construction — both entry
|
|
313
|
+
// points call crypto/derivation.ts#deriveSubHandleKey.
|
|
314
|
+
const subKey = deriveSubHandleKey(this.#privateKey, this.#name, normalizedName);
|
|
315
|
+
const path = [this.#name, normalizedName];
|
|
316
|
+
return new SubHandle(subKey, normalizedName, path, metadata);
|
|
173
317
|
}
|
|
174
318
|
|
|
175
319
|
/**
|
|
@@ -201,12 +345,17 @@ export class Handle {
|
|
|
201
345
|
grant: AttestationGrant,
|
|
202
346
|
opts?: { ttlSeconds?: number; expiresAt?: number; jti?: string; now?: number }
|
|
203
347
|
): Promise<Attestation> {
|
|
204
|
-
|
|
205
|
-
|
|
348
|
+
this.#assertNotDisposed();
|
|
349
|
+
// Single normalization (PR-11, 3.6): deriveSubHandle canonicalizes
|
|
350
|
+
// the subName (NFKC → lowercase → trim) and the returned SubHandle
|
|
351
|
+
// carries the canonical name — pre-normalizing here ran the same
|
|
352
|
+
// name through normalizeName twice. Attestation.issue applies its
|
|
353
|
+
// own defensive canonicalization on top (its public contract).
|
|
354
|
+
const sub = await this.deriveSubHandle(subName);
|
|
206
355
|
return Attestation.issue(
|
|
207
|
-
this
|
|
356
|
+
this,
|
|
208
357
|
sub.getPublicKey(),
|
|
209
|
-
|
|
358
|
+
sub.getName(),
|
|
210
359
|
grant,
|
|
211
360
|
opts ?? {}
|
|
212
361
|
);
|
|
@@ -218,23 +367,42 @@ export class Handle {
|
|
|
218
367
|
*
|
|
219
368
|
* The private key **never leaves this class**, ensuring maximum security.
|
|
220
369
|
*
|
|
370
|
+
* The `context` is canonicalized NFKC → lowercase → trim before use
|
|
371
|
+
* (`' GitHub '`, `'github'` and `'GitHub'` yield the same secret).
|
|
372
|
+
* NFKC applies to the string `context` only — `options.revision` is
|
|
373
|
+
* an integer and is canonical by construction (no normalization).
|
|
374
|
+
*
|
|
375
|
+
* **Revision model (since 0.8.0, D3):** `options.revision` (positive
|
|
376
|
+
* integer, default `1`) selects an independent secret for the same
|
|
377
|
+
* context — revision 1 is the initial secret, revision 2, 3, … are for
|
|
378
|
+
* rotation (e.g. after a breach). Revision 1 is byte-identical to the
|
|
379
|
+
* pre-revision v1.0 derivation.
|
|
380
|
+
*
|
|
221
381
|
* @param context - A unique identifier for the service (e.g., `'google'`, `'github'`).
|
|
222
|
-
* @param
|
|
382
|
+
* @param options - Derivation options.
|
|
223
383
|
* @returns A URL-safe base64 string suitable for use as a strong password.
|
|
384
|
+
* @throws AttestationError `MALFORMED`/`FORMAT` if `revision` is not a
|
|
385
|
+
* positive integer, `byteLength` is not an integer in `[1, 8160]`, or
|
|
386
|
+
* the context is empty after canonicalization.
|
|
224
387
|
*
|
|
225
388
|
* @example
|
|
226
389
|
* ```ts
|
|
227
|
-
* const githubPassword = handle.derivePassword('github', 20);
|
|
390
|
+
* const githubPassword = handle.derivePassword('github', { byteLength: 20 });
|
|
391
|
+
* // after rotating the GitHub credential:
|
|
392
|
+
* const rotated = handle.derivePassword('github', { revision: 2 });
|
|
228
393
|
* ```
|
|
229
394
|
*/
|
|
230
|
-
derivePassword(context: string,
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
const
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
395
|
+
derivePassword(context: string, options: DerivePasswordOptions = {}): string {
|
|
396
|
+
this.#assertNotDisposed();
|
|
397
|
+
assertRevision(options.revision);
|
|
398
|
+
const byteLength = options.byteLength ?? DEFAULT_PASSWORD_BYTES;
|
|
399
|
+
assertByteLength(byteLength);
|
|
400
|
+
const canonical = normalizeContext(context);
|
|
401
|
+
const salt = new TextEncoder().encode(`me2em/secret/${canonical}`);
|
|
402
|
+
const info = new TextEncoder().encode(DERIVATION_PATHS.password(options.revision ?? 1));
|
|
403
|
+
const secretBytes = hkdf(this.#privateKey, salt, info, byteLength);
|
|
404
|
+
// Audited @scure/base codec (A3) — no hand-rolled btoa alphabet math.
|
|
405
|
+
return base64urlEncode(secretBytes);
|
|
238
406
|
}
|
|
239
407
|
|
|
240
408
|
/**
|
|
@@ -247,21 +415,39 @@ export class Handle {
|
|
|
247
415
|
*
|
|
248
416
|
* This enables zero-knowledge encrypted channels without key exchange protocols.
|
|
249
417
|
*
|
|
418
|
+
* The `context` is canonicalized NFKC → lowercase → trim before use.
|
|
419
|
+
* NFKC applies to the string `context` only — `options.revision` is
|
|
420
|
+
* an integer and is canonical by construction (no normalization).
|
|
421
|
+
*
|
|
422
|
+
* **Revision model (since 0.8.0, D3):** `options.revision` (positive
|
|
423
|
+
* integer, default `1`) selects an independent 32-byte key for the same
|
|
424
|
+
* context — the sanctioned rotation path for a compromised channel
|
|
425
|
+
* without changing the context string. Revision 1 is byte-identical to
|
|
426
|
+
* the pre-revision v1.0 derivation.
|
|
427
|
+
*
|
|
250
428
|
* @param context - Channel identifier for domain separation (e.g., `'drone-001'`).
|
|
251
|
-
* Both parties **MUST** use the same context.
|
|
429
|
+
* Both parties **MUST** use the same context **and** the same revision.
|
|
430
|
+
* @param options - Derivation options.
|
|
252
431
|
* @returns A 32-byte Uint8Array suitable for AES-256-GCM encryption.
|
|
432
|
+
* @throws AttestationError `MALFORMED`/`FORMAT` if `revision` is not a
|
|
433
|
+
* positive integer or the context is empty after canonicalization.
|
|
253
434
|
*
|
|
254
435
|
* @example
|
|
255
436
|
* ```ts
|
|
256
437
|
* // AES-GCM helpers are application-side; the protocol provides
|
|
257
438
|
* // only the key:
|
|
258
439
|
* const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
|
|
440
|
+
* // after rotating the channel (both sides migrate in lockstep):
|
|
441
|
+
* const rotatedKey = droneHandle.deriveChannelKey('telemetry-v1', { revision: 2 });
|
|
259
442
|
* ```
|
|
260
443
|
*/
|
|
261
|
-
deriveChannelKey(context: string): Uint8Array {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
444
|
+
deriveChannelKey(context: string, options: DeriveChannelKeyOptions = {}): Uint8Array {
|
|
445
|
+
this.#assertNotDisposed();
|
|
446
|
+
assertRevision(options.revision);
|
|
447
|
+
const canonical = normalizeContext(context);
|
|
448
|
+
const salt = new TextEncoder().encode(`me2em/channel/${canonical}`);
|
|
449
|
+
const info = new TextEncoder().encode(DERIVATION_PATHS.channel(options.revision ?? 1));
|
|
450
|
+
return hkdf(this.#privateKey, salt, info, 32);
|
|
265
451
|
}
|
|
266
452
|
|
|
267
453
|
/**
|
|
@@ -281,19 +467,21 @@ export class Handle {
|
|
|
281
467
|
* ```
|
|
282
468
|
*/
|
|
283
469
|
async deriveSharedSecret(otherPublicKey: Uint8Array): Promise<Uint8Array> {
|
|
284
|
-
|
|
470
|
+
this.#assertNotDisposed();
|
|
471
|
+
const myPrivBytes = this.#privateKey;
|
|
285
472
|
const otherPubBytes = otherPublicKey;
|
|
286
473
|
|
|
474
|
+
/* v8 ignore start -- defensive: the constructor already validates the
|
|
475
|
+
key length implicitly (ed25519.getPublicKey throws RangeError). */
|
|
287
476
|
if (myPrivBytes.length !== 32) {
|
|
288
|
-
throw new
|
|
477
|
+
throw new AttestationError('MALFORMED', 'FORMAT', 'Handle private key must be 32 bytes');
|
|
289
478
|
}
|
|
479
|
+
/* v8 ignore stop */
|
|
290
480
|
if (otherPubBytes.length !== 32) {
|
|
291
|
-
throw new
|
|
481
|
+
throw new AttestationError('MALFORMED', 'FORMAT', 'Public key must be 32 bytes');
|
|
292
482
|
}
|
|
293
483
|
|
|
294
|
-
const
|
|
295
|
-
const x25519Pub = ed25519.utils.toMontgomery(otherPubBytes);
|
|
296
|
-
const rawSharedSecret = x25519.getSharedSecret(x25519Priv, x25519Pub);
|
|
484
|
+
const rawSharedSecret = rawX25519SharedSecret(this.#privateKey, otherPubBytes);
|
|
297
485
|
|
|
298
486
|
// Canonical, order-independent binding of both peers' public keys.
|
|
299
487
|
const myPub = this.getPublicKey();
|
|
@@ -310,6 +498,383 @@ export class Handle {
|
|
|
310
498
|
const info = new TextEncoder().encode(
|
|
311
499
|
DERIVATION_PATHS.p2pChannelV2
|
|
312
500
|
);
|
|
313
|
-
return hkdf(
|
|
501
|
+
return hkdf(rawSharedSecret, bound, info, 32);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Permanently destroys this Handle's key material.
|
|
506
|
+
*
|
|
507
|
+
* The private key bytes are zeroized; afterwards every capability method
|
|
508
|
+
* ({@link sign}, {@link deriveSubHandle}, {@link attestSubHandle},
|
|
509
|
+
* {@link derivePassword}, {@link deriveChannelKey},
|
|
510
|
+
* {@link deriveSharedSecret}) throws a {@link DisposedError}.
|
|
511
|
+
* Informational getters ({@link getName}, {@link getId},
|
|
512
|
+
* {@link getPublicKey}, {@link getMetadata}) keep working — they never
|
|
513
|
+
* touch key material.
|
|
514
|
+
*
|
|
515
|
+
* SubHandles inherit `dispose()`. Calling it more than once is a no-op
|
|
516
|
+
* (idempotent).
|
|
517
|
+
*/
|
|
518
|
+
dispose(): void {
|
|
519
|
+
if (this.#disposed) return;
|
|
520
|
+
this.#privateKey.fill(0);
|
|
521
|
+
this.#disposed = true;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
#assertNotDisposed(): void {
|
|
525
|
+
if (this.#disposed) throw new DisposedError('Handle');
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* Redacted serialization contract: `JSON.stringify(handle)` exposes only
|
|
530
|
+
* the object kind, the public identifier and the context name — never
|
|
531
|
+
* key material or metadata.
|
|
532
|
+
*/
|
|
533
|
+
toJSON(): { kind: string; id: string; name: string } {
|
|
534
|
+
return {
|
|
535
|
+
kind: 'Handle',
|
|
536
|
+
id: base64urlEncode(this.#publicKey),
|
|
537
|
+
name: this.#name,
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
[INSPECT_SYMBOL](): string {
|
|
542
|
+
return `Handle(id=${base64urlEncode(this.#publicKey).slice(0, 8)}…, name=${JSON.stringify(this.#name)})`;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// ---------------------------------------------------------------------------
|
|
547
|
+
// SubHandle (co-located with Handle — see the module comment at the top)
|
|
548
|
+
// ---------------------------------------------------------------------------
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* Metadata for a {@link SubHandle}, extending {@link HandleMetadata} with
|
|
552
|
+
* constraints that govern session creation.
|
|
553
|
+
*
|
|
554
|
+
* All constraint fields are optional. When present, they are enforced by
|
|
555
|
+
* {@link SubHandle.validateSessionOptions} at session creation time.
|
|
556
|
+
*
|
|
557
|
+
* @category Types
|
|
558
|
+
*/
|
|
559
|
+
export interface SubHandleMetadata extends HandleMetadata {
|
|
560
|
+
/**
|
|
561
|
+
* Restricts the set of audiences this SubHandle may create sessions for.
|
|
562
|
+
* `undefined` = unrestricted; `[]` = deny all.
|
|
563
|
+
*/
|
|
564
|
+
allowedAudiences?: string[];
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Restricts the set of scopes this SubHandle may request in sessions.
|
|
568
|
+
* `undefined` = unrestricted; `[]` = deny all.
|
|
569
|
+
*/
|
|
570
|
+
allowedScopes?: string[];
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Maximum allowed TTL (in seconds) for sessions created by this SubHandle.
|
|
574
|
+
* Attempts to create a session with a larger TTL will be rejected.
|
|
575
|
+
*/
|
|
576
|
+
maxSessionTtl?: number;
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* Unix timestamp (in seconds) at which this SubHandle itself expires.
|
|
580
|
+
* After this time, any attempt to create a session will fail.
|
|
581
|
+
* Useful for temporary access grants (e.g., contractor access for 2 weeks).
|
|
582
|
+
*/
|
|
583
|
+
expiresAt?: number;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Extracts only display-safe fields for the base Handle metadata.
|
|
588
|
+
* Constraint fields stay in SubHandle's own storage and must never
|
|
589
|
+
* leak through Handle.getMetadata().
|
|
590
|
+
*/
|
|
591
|
+
function extractDisplayFields(
|
|
592
|
+
meta?: SubHandleMetadata
|
|
593
|
+
): HandleMetadata | undefined {
|
|
594
|
+
if (!meta) return undefined;
|
|
595
|
+
const display: HandleMetadata = {};
|
|
596
|
+
if (meta.displayName !== undefined) display.displayName = meta.displayName;
|
|
597
|
+
if (meta.avatar !== undefined) display.avatar = meta.avatar;
|
|
598
|
+
// copy any other custom fields, but never the constraint ones
|
|
599
|
+
const CONSTRAINT_KEYS = new Set([
|
|
600
|
+
'allowedAudiences', 'allowedScopes', 'maxSessionTtl', 'expiresAt',
|
|
601
|
+
]);
|
|
602
|
+
for (const [k, v] of Object.entries(meta)) {
|
|
603
|
+
if (!CONSTRAINT_KEYS.has(k)) {
|
|
604
|
+
(display as Record<string, unknown>)[k] = v;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
return display;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Deep copy of Handle metadata for the {@link Handle.getMetadata} and
|
|
612
|
+
* {@link SubHandle.getSubMetadata} getters (PR-7; extended to the Handle
|
|
613
|
+
* constructor/getter for symmetry): JSON-safe values (plain objects and
|
|
614
|
+
* arrays, including nested ones) are duplicated so no caller mutation can
|
|
615
|
+
* reach the stored metadata or the enforced constraints. Non-plain values
|
|
616
|
+
* (Date, Map, class instances) are shared by reference at depth > 8 and
|
|
617
|
+
* documented as such.
|
|
618
|
+
*/
|
|
619
|
+
function deepCloneJsonValue(value: unknown, depth = 0): unknown {
|
|
620
|
+
if (depth > 8 || value === null || typeof value !== 'object') return value;
|
|
621
|
+
if (Array.isArray(value)) {
|
|
622
|
+
return value.map((v) => deepCloneJsonValue(v, depth + 1));
|
|
623
|
+
}
|
|
624
|
+
const proto = Object.getPrototypeOf(value);
|
|
625
|
+
if (proto !== Object.prototype && proto !== null) return value; // non-plain: share
|
|
626
|
+
const out: Record<string, unknown> = {};
|
|
627
|
+
for (const [k, v] of Object.entries(value)) {
|
|
628
|
+
out[k] = deepCloneJsonValue(v, depth + 1);
|
|
629
|
+
}
|
|
630
|
+
return out;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Deep-ish copy of SubHandle metadata: constraint arrays (the
|
|
635
|
+
* security-relevant part) are duplicated so the caller cannot mutate
|
|
636
|
+
* the enforced constraints after construction. Custom fields are
|
|
637
|
+
* shallow-copied (nested objects are not cloned).
|
|
638
|
+
*/
|
|
639
|
+
function copySubMetadata(meta?: SubHandleMetadata): SubHandleMetadata {
|
|
640
|
+
const out: SubHandleMetadata = { ...(meta ?? {}) };
|
|
641
|
+
if (out.allowedAudiences !== undefined) out.allowedAudiences = [...out.allowedAudiences];
|
|
642
|
+
if (out.allowedScopes !== undefined) out.allowedScopes = [...out.allowedScopes];
|
|
643
|
+
return out;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* Represents a context-isolated child Handle in the Me2eM hierarchy.
|
|
648
|
+
*
|
|
649
|
+
* A SubHandle is always derived from a parent {@link Handle} and represents
|
|
650
|
+
* a leaf node in the derivation tree (MAX_DEPTH = 2). It inherits all
|
|
651
|
+
* cryptographic capabilities of Handle (signing, key derivation, etc.) but
|
|
652
|
+
* adds:
|
|
653
|
+
*
|
|
654
|
+
* - A **derivation path** (`[handleName, subName]`) carried in session tokens.
|
|
655
|
+
* - **Constraint enforcement** on audience, scopes, and TTL at session creation.
|
|
656
|
+
* - An optional **expiration timestamp** for temporary access grants.
|
|
657
|
+
*
|
|
658
|
+
* SubHandle is used for polymorphism in {@link Session}: both Handle and
|
|
659
|
+
* SubHandle can create and verify sessions, but SubHandle sessions carry
|
|
660
|
+
* the additional `hPath` field for hierarchical auditing.
|
|
661
|
+
*
|
|
662
|
+
* The class is defined in the same module as {@link Handle} on purpose
|
|
663
|
+
* (D4, PR-10): `SubHandle extends Handle` plus a static import of the
|
|
664
|
+
* subclass from `handle.ts` would form an ESM module cycle that crashes
|
|
665
|
+
* at import time depending on the graph root; co-location keeps the
|
|
666
|
+
* graph acyclic. `subhandle.ts` re-exports this class unchanged, so the
|
|
667
|
+
* public import paths are unaffected.
|
|
668
|
+
*
|
|
669
|
+
* @category Core Primitives
|
|
670
|
+
*/
|
|
671
|
+
export class SubHandle extends Handle implements Signer {
|
|
672
|
+
#path: string[];
|
|
673
|
+
#subMetadata: SubHandleMetadata;
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* Creates a new SubHandle instance.
|
|
677
|
+
*
|
|
678
|
+
* @internal Typically created via {@link Handle.deriveSubHandle} or
|
|
679
|
+
* {@link Identity.deriveSubHandle}. Direct construction is discouraged.
|
|
680
|
+
*
|
|
681
|
+
* @param privateKey - The 32-byte Ed25519 private key for this SubHandle.
|
|
682
|
+
* Copied on input by the Handle constructor.
|
|
683
|
+
* @param name - The SubHandle name.
|
|
684
|
+
* @param path - The derivation path, must have exactly 2 elements: `[handleName, subName]`.
|
|
685
|
+
* Copied on input — later mutation of the caller's array has no effect.
|
|
686
|
+
* @param subMetadata - Optional constraints and metadata.
|
|
687
|
+
* Copied on input (constraint arrays are duplicated).
|
|
688
|
+
* @throws {Error} If the path does not have exactly 2 elements.
|
|
689
|
+
*/
|
|
690
|
+
constructor(
|
|
691
|
+
privateKey: Uint8Array,
|
|
692
|
+
name: string,
|
|
693
|
+
path: string[],
|
|
694
|
+
subMetadata?: SubHandleMetadata
|
|
695
|
+
) {
|
|
696
|
+
super(privateKey, name, extractDisplayFields(subMetadata));
|
|
697
|
+
|
|
698
|
+
if (path.length !== 2) {
|
|
699
|
+
throw new AttestationError(
|
|
700
|
+
'MALFORMED',
|
|
701
|
+
'FORMAT',
|
|
702
|
+
`SubHandle path must have exactly 2 elements: [handleName, subName]. Got ${path.length}.`
|
|
703
|
+
);
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
const normalizedName = normalizeName(name);
|
|
707
|
+
if (path[1] !== normalizedName) {
|
|
708
|
+
throw new AttestationError(
|
|
709
|
+
'MALFORMED',
|
|
710
|
+
'FORMAT',
|
|
711
|
+
`path[1] must equal normalized name: path[1]=${JSON.stringify(path[1])}, name=${JSON.stringify(normalizedName)}`
|
|
712
|
+
);
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// Defensive copies: the caller keeps no live reference into this leaf.
|
|
716
|
+
this.#path = [...path];
|
|
717
|
+
this.#subMetadata = copySubMetadata(subMetadata);
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* Returns the full derivation path of this SubHandle.
|
|
722
|
+
*
|
|
723
|
+
* @returns A copy of the path array, e.g. `["station-001", "connector-1"]`.
|
|
724
|
+
*/
|
|
725
|
+
getPath(): string[] {
|
|
726
|
+
return [...this.#path];
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* Returns the derivation path as a slash-separated string.
|
|
731
|
+
*
|
|
732
|
+
* @returns The path string, e.g. `"station-001/connector-1"`.
|
|
733
|
+
*/
|
|
734
|
+
getPathString(): string {
|
|
735
|
+
return this.#path.join('/');
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* Returns the depth of this SubHandle in the derivation hierarchy.
|
|
740
|
+
*
|
|
741
|
+
* With MAX_DEPTH = 2, this is always `2` (Identity = 0, Handle = 1, SubHandle = 2).
|
|
742
|
+
*
|
|
743
|
+
* @returns The depth, always `2`.
|
|
744
|
+
*/
|
|
745
|
+
getDepth(): number {
|
|
746
|
+
return 2;
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* Returns whether this SubHandle is a leaf node.
|
|
751
|
+
*
|
|
752
|
+
* With MAX_DEPTH = 2, a SubHandle is **always** a leaf and cannot derive children.
|
|
753
|
+
*
|
|
754
|
+
* @returns Always `true`.
|
|
755
|
+
*/
|
|
756
|
+
isLeaf(): boolean {
|
|
757
|
+
return true;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* SubHandle is a leaf node (depth = 2) and cannot derive children.
|
|
762
|
+
* Overrides the inherited `Handle.deriveSubHandle` to throw
|
|
763
|
+
* `AttestationError` `MAX_DEPTH_EXCEEDED`/`FORMAT`.
|
|
764
|
+
*/
|
|
765
|
+
override async deriveSubHandle(): Promise<never> {
|
|
766
|
+
throw new AttestationError(
|
|
767
|
+
'MAX_DEPTH_EXCEEDED',
|
|
768
|
+
'FORMAT',
|
|
769
|
+
'Cannot derive child: maximum depth (2) reached or this SubHandle is marked as leaf'
|
|
770
|
+
);
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/**
|
|
774
|
+
* Returns the SubHandle-specific metadata (constraints).
|
|
775
|
+
*
|
|
776
|
+
* The returned object is a **deep copy** (PR-7): JSON-safe nested
|
|
777
|
+
* structures (plain objects, arrays) are fully duplicated, so mutating
|
|
778
|
+
* the result — at any depth — cannot alter the constraints this
|
|
779
|
+
* SubHandle enforces. Non-plain values (Date, Map, class instances)
|
|
780
|
+
* are shared by reference; functions abort the deep copy and fall
|
|
781
|
+
* back to the shallow constraint-array-duplicating copy.
|
|
782
|
+
*
|
|
783
|
+
* @returns A deep copy of the SubHandleMetadata object.
|
|
784
|
+
*/
|
|
785
|
+
getSubMetadata(): SubHandleMetadata {
|
|
786
|
+
for (const value of Object.values(this.#subMetadata)) {
|
|
787
|
+
// A function anywhere in the metadata cannot be deep-cloned by the
|
|
788
|
+
// generic copier — fall back to the shallow, array-duplicating copy.
|
|
789
|
+
if (typeof value === 'function') return copySubMetadata(this.#subMetadata);
|
|
790
|
+
}
|
|
791
|
+
return deepCloneJsonValue(this.#subMetadata) as SubHandleMetadata;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* Validates session options against this SubHandle's constraints.
|
|
796
|
+
*
|
|
797
|
+
* Called internally by {@link Session.create} before signing. Throws if
|
|
798
|
+
* any constraint is violated:
|
|
799
|
+
* - `audience` not in `allowedAudiences`
|
|
800
|
+
* - any `scope` not in `allowedScopes`
|
|
801
|
+
* - `ttl` exceeds `maxSessionTtl`
|
|
802
|
+
* - current time is past `expiresAt`
|
|
803
|
+
*
|
|
804
|
+
* @param options - The session options to validate.
|
|
805
|
+
* @throws {Error} If any constraint is violated.
|
|
806
|
+
*/
|
|
807
|
+
validateSessionOptions(options: {
|
|
808
|
+
audience: string;
|
|
809
|
+
scopes: string[];
|
|
810
|
+
ttl: number;
|
|
811
|
+
}): void {
|
|
812
|
+
// Audience check: undefined = unrestricted, [] = deny all
|
|
813
|
+
if (this.#subMetadata.allowedAudiences !== undefined) {
|
|
814
|
+
if (!this.#subMetadata.allowedAudiences.includes(options.audience)) {
|
|
815
|
+
throw new AttestationError(
|
|
816
|
+
'AUDIENCE_NOT_PERMITTED',
|
|
817
|
+
'SESSION',
|
|
818
|
+
`Audience "${options.audience}" not allowed for this SubHandle. ` +
|
|
819
|
+
`Allowed: ${this.#subMetadata.allowedAudiences.length === 0
|
|
820
|
+
? '(none — empty list denies all)'
|
|
821
|
+
: this.#subMetadata.allowedAudiences.join(', ')}`
|
|
822
|
+
);
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// Scopes check: undefined = unrestricted, [] = deny all
|
|
827
|
+
if (this.#subMetadata.allowedScopes !== undefined) {
|
|
828
|
+
const forbidden = options.scopes.filter(
|
|
829
|
+
s => !this.#subMetadata.allowedScopes!.includes(s)
|
|
830
|
+
);
|
|
831
|
+
// An empty allow-list denies every requested scope.
|
|
832
|
+
if (forbidden.length > 0) {
|
|
833
|
+
throw new AttestationError(
|
|
834
|
+
'SCOPE_EXCEEDED',
|
|
835
|
+
'SESSION',
|
|
836
|
+
`Scopes not allowed for this SubHandle: ${forbidden.join(', ')}`
|
|
837
|
+
);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// TTL check
|
|
842
|
+
if (
|
|
843
|
+
this.#subMetadata.maxSessionTtl !== undefined &&
|
|
844
|
+
options.ttl > this.#subMetadata.maxSessionTtl
|
|
845
|
+
) {
|
|
846
|
+
throw new AttestationError(
|
|
847
|
+
'TTL_EXCEEDED',
|
|
848
|
+
'SESSION',
|
|
849
|
+
`TTL ${options.ttl}s exceeds max allowed ` +
|
|
850
|
+
`${this.#subMetadata.maxSessionTtl}s for this SubHandle`
|
|
851
|
+
);
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
// SubHandle expiration check
|
|
855
|
+
if (this.#subMetadata.expiresAt !== undefined) {
|
|
856
|
+
const now = Math.floor(Date.now() / 1000);
|
|
857
|
+
if (now >= this.#subMetadata.expiresAt) {
|
|
858
|
+
throw new AttestationError('EXPIRED', 'SESSION', 'SubHandle has expired');
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* Redacted serialization contract: `JSON.stringify(sub)` exposes only the
|
|
865
|
+
* object kind, the public identifier, the name and the derivation path —
|
|
866
|
+
* never key material or constraint metadata.
|
|
867
|
+
*/
|
|
868
|
+
override toJSON(): { kind: string; id: string; name: string; path: string[] } {
|
|
869
|
+
return {
|
|
870
|
+
kind: 'SubHandle',
|
|
871
|
+
id: base64urlEncode(this.getPublicKey()),
|
|
872
|
+
name: this.getName(),
|
|
873
|
+
path: [...this.#path],
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
override [INSPECT_SYMBOL](): string {
|
|
878
|
+
return `SubHandle(id=${base64urlEncode(this.getPublicKey()).slice(0, 8)}…, path=${this.#path.join('/')})`;
|
|
314
879
|
}
|
|
315
880
|
}
|