@me2em/core 0.7.0-alpha.1 → 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.
Files changed (92) hide show
  1. package/README.md +242 -47
  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 +11 -2
  27. package/dist/crypto/hkdf.d.ts.map +1 -1
  28. package/dist/crypto/hkdf.js +13 -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 +33 -22
  55. package/dist/seed.d.ts.map +1 -1
  56. package/dist/seed.js +59 -31
  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 +12 -5
  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 +13 -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 +13 -7
  88. package/src/seed.ts +75 -32
  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
package/src/session.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  import { Handle } from './handle.js';
3
3
  import { SubHandle } from './subhandle.js';
4
4
  import { Identity } from './identity.js';
5
- import { base64urlEncode, base64urlDecode } from './util.js';
5
+ import { base64urlEncode, base64urlDecode, randomUUID, safeJsonParse } from './util.js';
6
6
  import {
7
7
  Attestation,
8
8
  AttestationError,
@@ -65,7 +65,7 @@ export interface SessionPayload {
65
65
  /**
66
66
  * Interface for application-side revocation checking.
67
67
  *
68
- * The Me2em protocol does not prescribe a storage backend for revocation.
68
+ * The Me2eM protocol does not prescribe a storage backend for revocation.
69
69
  * Applications implement this interface using their preferred store
70
70
  * (Redis, PostgreSQL, in-memory Set, etc.) and pass it to
71
71
  * {@link Session.verifyStateless}.
@@ -133,10 +133,14 @@ export class Session {
133
133
  /**
134
134
  * Creates a new Session instance.
135
135
  *
136
- * @internal Typically created via {@link Session.create} or
137
- * {@link Session.verifyStateless}. Direct construction is discouraged.
136
+ * @internal Construction is a library-internal step (PR-11, D6): a
137
+ * Session is either freshly issued — {@link Session.create} — or the
138
+ * result of a verified token — {@link Session.verifyStateless} /
139
+ * {@link Session.verifyAttested}. External callers cannot fabricate a
140
+ * verified-looking session object; test/tooling reconstruction goes
141
+ * through the {@link Session.fromVerified} internal factory.
138
142
  */
139
- constructor(
143
+ private constructor(
140
144
  handleId: string,
141
145
  handleName: string,
142
146
  audience: string,
@@ -156,6 +160,49 @@ export class Session {
156
160
  this.sessionId = sessionId ?? '';
157
161
  }
158
162
 
163
+ /**
164
+ * Rebuilds a Session from parts whose validity has already been
165
+ * established — the single sanctioned bypass of the private
166
+ * constructor (PR-11, D6).
167
+ *
168
+ * @internal Not public API. Production code gets sessions from
169
+ * {@link Session.create} / {@link Session.verifyStateless} /
170
+ * {@link Session.verifyAttested}; only library tests (via test-utils)
171
+ * use this factory. It performs no verification of its own — the name
172
+ * says "verified" because the CALLER asserts the parts come from a
173
+ * verification step or a fresh issuance.
174
+ *
175
+ * @param handleId - Handle / SubHandle ID (Base64URL of public key).
176
+ * @param handleName - Handle / SubHandle name.
177
+ * @param audience - Intended audience.
178
+ * @param scopes - Granted scopes.
179
+ * @param expiresAt - Expiration timestamp (Unix seconds).
180
+ * @param token - The full session token.
181
+ * @param path - Derivation path (SubHandle sessions only).
182
+ * @param sessionId - Session `jti` (revocation id).
183
+ */
184
+ static fromVerified(
185
+ handleId: string,
186
+ handleName: string,
187
+ audience: string,
188
+ scopes: string[],
189
+ expiresAt: number,
190
+ token: string,
191
+ path?: string[],
192
+ sessionId?: string
193
+ ): Session {
194
+ return new Session(
195
+ handleId,
196
+ handleName,
197
+ audience,
198
+ scopes,
199
+ expiresAt,
200
+ token,
201
+ path,
202
+ sessionId
203
+ );
204
+ }
205
+
159
206
  /**
160
207
  * Checks if the session has expired based on the current time.
161
208
  *
@@ -195,7 +242,9 @@ export class Session {
195
242
  !Number.isInteger(options.ttl) ||
196
243
  options.ttl <= 0
197
244
  ) {
198
- throw new Error(
245
+ throw new AttestationError(
246
+ 'MALFORMED',
247
+ 'FORMAT',
199
248
  `ttl must be a positive integer (seconds), got: ${String(options.ttl)}`
200
249
  );
201
250
  }
@@ -203,7 +252,7 @@ export class Session {
203
252
 
204
253
  const now = Math.floor(Date.now() / 1000);
205
254
  const expiresAt = now + options.ttl;
206
- const sessionId = options.sessionId ?? crypto.randomUUID();
255
+ const sessionId = options.sessionId ?? randomUUID();
207
256
 
208
257
  const payload: SessionPayload = {
209
258
  hId: handle.getId(),
@@ -245,49 +294,93 @@ export class Session {
245
294
  signatureBytes: Uint8Array;
246
295
  } {
247
296
  if (typeof token !== 'string') {
248
- throw new Error('Token must be a string');
297
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Token must be a string');
249
298
  }
250
299
 
251
300
  const parts = token.split('.');
252
301
  if (parts.length !== 2) {
253
- throw new Error('Invalid token format: expected two Base64URL parts separated by "."');
302
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Invalid token format: expected two Base64URL parts separated by "."');
254
303
  }
255
304
  const [payloadB64, signatureB64] = parts;
256
305
 
257
306
  const b64urlRegex = /^[A-Za-z0-9_-]+$/;
258
307
  if (!b64urlRegex.test(payloadB64) || !b64urlRegex.test(signatureB64)) {
259
- throw new Error('Invalid token format: payload and signature must be valid Base64URL');
308
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Invalid token format: payload and signature must be valid Base64URL');
260
309
  }
261
310
 
262
- const payloadBytes = base64urlDecode(payloadB64);
311
+ let payloadBytes: Uint8Array;
312
+ try {
313
+ payloadBytes = base64urlDecode(payloadB64);
314
+ } catch {
315
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Invalid token format: payload and signature must be valid Base64URL');
316
+ }
263
317
  if (payloadBytes.length > MAX_PAYLOAD_SIZE) {
264
- throw new Error(`Payload exceeds maximum size of ${MAX_PAYLOAD_SIZE} bytes`);
318
+ throw new AttestationError('MALFORMED', 'FORMAT', `Payload exceeds maximum size of ${MAX_PAYLOAD_SIZE} bytes`);
265
319
  }
266
320
 
267
321
  let payload: SessionPayload;
268
322
  try {
269
323
  const jsonString = new TextDecoder().decode(payloadBytes);
270
- payload = JSON.parse(jsonString) as SessionPayload;
271
- } catch {
272
- throw new Error('Invalid token format: payload is not valid JSON');
324
+ payload = safeJsonParse(jsonString) as SessionPayload;
325
+ } catch (e) {
326
+ throw new AttestationError(
327
+ 'MALFORMED',
328
+ 'FORMAT',
329
+ e instanceof SyntaxError && e.message.includes('__proto__')
330
+ ? `Invalid token format: payload is not valid JSON — ${e.message}`
331
+ : 'Invalid token format: payload is not valid JSON'
332
+ );
273
333
  }
274
334
 
275
- // Required fields validation
335
+ // Required fields validation (types first — a tampered token must
336
+ // never reach name derivation with a non-string hNm/hPath, PR-7)
276
337
  if (
277
- !payload.hId ||
278
- !payload.hNm ||
279
- !payload.aud ||
338
+ typeof payload.hId !== 'string' || payload.hId.length === 0 ||
339
+ typeof payload.hNm !== 'string' || payload.hNm.length === 0 ||
340
+ typeof payload.aud !== 'string' || payload.aud.length === 0 ||
280
341
  !Array.isArray(payload.scp) ||
342
+ !payload.scp.every((s: unknown) => typeof s === 'string') ||
281
343
  typeof payload.exp !== 'number' ||
282
344
  typeof payload.iat !== 'number' ||
283
- typeof payload.jti !== 'string'
345
+ typeof payload.jti !== 'string' ||
346
+ payload.jti.length === 0
284
347
  ) {
285
- throw new Error(
348
+ throw new AttestationError(
349
+ 'MALFORMED',
350
+ 'FORMAT',
286
351
  'Invalid token format: missing required fields (hId, hNm, aud, scp, exp, iat, jti)'
287
352
  );
288
353
  }
289
354
 
290
- const signatureBytes = base64urlDecode(signatureB64);
355
+ // Mirror of Attestation.decode: non-finite iat/exp and exp <= iat
356
+ // are FORMAT-layer failures, caught at parse time — not late as
357
+ // EXPIRED/NOT_YET_VALID (or never, for `exp: 1e999` → Infinity).
358
+ if (!Number.isFinite(payload.iat) || !Number.isFinite(payload.exp)) {
359
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Invalid token format: iat/exp must be finite numbers');
360
+ }
361
+ if (payload.exp <= payload.iat) {
362
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Invalid token format: exp must be greater than iat');
363
+ }
364
+
365
+ if (
366
+ payload.hPath !== undefined &&
367
+ (!Array.isArray(payload.hPath) ||
368
+ payload.hPath.length !== 2 ||
369
+ !payload.hPath.every((x: unknown) => typeof x === 'string'))
370
+ ) {
371
+ throw new AttestationError(
372
+ 'MALFORMED',
373
+ 'FORMAT',
374
+ 'Invalid token format: hPath must be an array of two strings'
375
+ );
376
+ }
377
+
378
+ let signatureBytes: Uint8Array;
379
+ try {
380
+ signatureBytes = base64urlDecode(signatureB64);
381
+ } catch {
382
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Invalid token format: payload and signature must be valid Base64URL');
383
+ }
291
384
 
292
385
  return { payload, payloadBytes, signatureBytes };
293
386
  }
@@ -312,7 +405,10 @@ export class Session {
312
405
  * @param expectedAudience - The audience that this token must be intended for.
313
406
  * @param revocationChecker - Optional checker for revocation list.
314
407
  * @returns A Promise resolving to a verified Session instance.
315
- * @throws {Error} If the token is invalid, expired, tampered, audience mismatch, or revoked.
408
+ * @throws {AttestationError} With `code`/`level` — `MALFORMED`/`FORMAT`
409
+ * for structural failures, then `AUDIENCE_NOT_PERMITTED`,
410
+ * `EXPIRED`, `NOT_YET_VALID` (session), `BAD_SIGNATURE`,
411
+ * `SUBJECT_MISMATCH`, `REVOKED` at level `SESSION`.
316
412
  *
317
413
  * @example
318
414
  * ```ts
@@ -334,16 +430,17 @@ export class Session {
334
430
 
335
431
  // Audience check
336
432
  if (payload.aud !== expectedAudience) {
337
- throw new Error(`Audience mismatch: expected "${expectedAudience}", got "${payload.aud}"`);
433
+ throw new AttestationError('AUDIENCE_NOT_PERMITTED', 'SESSION',
434
+ `Audience mismatch: expected "${expectedAudience}", got "${payload.aud}"`);
338
435
  }
339
436
 
340
437
  // Time checks
341
438
  const now = Math.floor(Date.now() / 1000);
342
439
  if (now > payload.exp + CLOCK_SKEW_SECONDS) {
343
- throw new Error('Token expired');
440
+ throw new AttestationError('EXPIRED', 'SESSION', 'Token expired');
344
441
  }
345
442
  if (now < payload.iat - CLOCK_SKEW_SECONDS) {
346
- throw new Error('Token is future-dated');
443
+ throw new AttestationError('NOT_YET_VALID', 'SESSION', 'Token is future-dated');
347
444
  }
348
445
 
349
446
  // Reconstruct Handle or SubHandle
@@ -359,31 +456,30 @@ export class Session {
359
456
 
360
457
  // Signature verification (wrapped to catch exceptions from the crypto lib)
361
458
  const publicKey = handle.getPublicKey();
362
- let isValid = false;
459
+ let isValid: boolean;
363
460
  try {
364
461
  isValid = await Handle.verify(signatureBytes, payloadBytes, publicKey);
365
462
  } catch {
366
463
  isValid = false;
367
464
  }
368
465
  if (!isValid) {
369
- throw new Error(
370
- 'Invalid signature: token payload has been tampered with or was not signed by the claimed Handle'
371
- );
466
+ throw new AttestationError('BAD_SIGNATURE', 'SESSION',
467
+ 'Invalid signature: token payload has been tampered with or was not signed by the claimed Handle');
372
468
  }
373
469
 
374
470
  if (handle.getId() !== payload.hId) {
375
- throw new Error('hId mismatch');
471
+ throw new AttestationError('SUBJECT_MISMATCH', 'SESSION', 'hId mismatch');
376
472
  }
377
473
 
378
474
  // Revocation check — last, after signature is verified
379
475
  if (revocationChecker) {
380
476
  const isRevoked = await revocationChecker.isRevoked(payload.jti);
381
477
  if (isRevoked) {
382
- throw new Error('Session has been revoked');
478
+ throw new AttestationError('REVOKED', 'SESSION', 'Session has been revoked');
383
479
  }
384
480
  }
385
481
 
386
- return new Session(
482
+ return Session.fromVerified(
387
483
  payload.hId,
388
484
  payload.hNm,
389
485
  payload.aud,
@@ -415,6 +511,13 @@ export class Session {
415
511
  * expiry against the earliest attestation expiry; session signature
416
512
  * against `hId`; session revocation — last.
417
513
  *
514
+ * Internally (PR-11, 3.4/3.6) the flow is split into five private
515
+ * stages — `#verifyChainStructure`, `#verifyRootAttestation`,
516
+ * `#verifyHandleAttestation`, `#verifySessionAgainstGrant`,
517
+ * `#verifySessionSignature` — with the check order, error codes and
518
+ * error levels byte-identical to the pre-split monolith (pinned by the
519
+ * untouched attested-session, error-table and fuzz suites).
520
+ *
418
521
  * @param attestationChain - Attestation tokens, root first; length
419
522
  * must match the session kind (1 for Handle, 2 for SubHandle).
420
523
  * @param revocationChecker - Optional; consulted for attestation
@@ -465,6 +568,86 @@ export class Session {
465
568
  }
466
569
 
467
570
  // Step 4: Chain structure
571
+ const isSubSession = Session.#verifyChainStructure(payload, attestationChain);
572
+
573
+ // Steps 5–8: root attestation (decode, signature, time, revocation)
574
+ const A = await Session.#verifyRootAttestation(
575
+ attestationChain,
576
+ rootPublicKey,
577
+ now,
578
+ revocationChecker
579
+ );
580
+
581
+ // Step 9 + effective grant G
582
+ let G: AttestationPayload['grant'];
583
+ let bPayload: AttestationPayload | undefined;
584
+
585
+ if (isSubSession) {
586
+ bPayload = await Session.#verifyHandleAttestation(
587
+ attestationChain,
588
+ A,
589
+ payload,
590
+ now,
591
+ revocationChecker
592
+ );
593
+ G = bPayload.grant;
594
+ } else {
595
+ // Handle session: the root attestation subject must decode and
596
+ // equal the session handleId (same checks, same relative order as
597
+ // the pre-split monolith).
598
+ const subjectIdBytes = (() => {
599
+ try { return base64urlDecode(A.subjectId); } catch { return null; }
600
+ })();
601
+ if (!subjectIdBytes) {
602
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Cannot decode root attestation subjectId');
603
+ }
604
+ if (payload.hId !== A.subjectId) {
605
+ throw new AttestationError('SUBJECT_MISMATCH', 'ROOT',
606
+ 'Session handleId does not match root attestation subjectId');
607
+ }
608
+ G = A.grant;
609
+ }
610
+
611
+ // Steps 10–11: session vs grant G, session does not outlive attestation
612
+ Session.#verifySessionAgainstGrant(payload, G, A, bPayload);
613
+
614
+ // Step 12: Session signature
615
+ await Session.#verifySessionSignature(signatureBytes, payloadBytes, payload);
616
+
617
+ // Step 13: Session revocation — last, after everything else
618
+ if (revocationChecker) {
619
+ const isRevoked = await revocationChecker.isRevoked(payload.jti);
620
+ if (isRevoked) {
621
+ throw new AttestationError('REVOKED', 'SESSION', 'Session has been revoked');
622
+ }
623
+ }
624
+
625
+ // Step 14
626
+ return Session.fromVerified(
627
+ payload.hId,
628
+ payload.hNm,
629
+ payload.aud,
630
+ payload.scp,
631
+ payload.exp,
632
+ token,
633
+ payload.hPath,
634
+ payload.jti
635
+ );
636
+ }
637
+
638
+ /**
639
+ * Step 4 — the chain shape must match the session kind: exactly one
640
+ * attestation for a Handle session, exactly two for a SubHandle
641
+ * session (root attestation first). `hPath` shape was already
642
+ * validated by `parseSessionToken`; the length check here is
643
+ * defense in depth.
644
+ *
645
+ * @returns Whether this is a SubHandle session (`hPath` present).
646
+ */
647
+ static #verifyChainStructure(
648
+ payload: SessionPayload,
649
+ attestationChain: string[]
650
+ ): boolean {
468
651
  const isSubSession = payload.hPath !== undefined;
469
652
  if (isSubSession) {
470
653
  if (!payload.hPath || payload.hPath.length !== 2) {
@@ -478,12 +661,26 @@ export class Session {
478
661
  throw new AttestationError('CHAIN_INCOMPLETE', 'FORMAT', 'Handle session requires exactly 1 attestation');
479
662
  }
480
663
  }
664
+ return isSubSession;
665
+ }
481
666
 
667
+ /**
668
+ * Steps 5–8 — the root attestation level: decode, signature against
669
+ * the trusted `rootPublicKey`, time window (±30 s skew), revocation.
670
+ *
671
+ * @returns The decoded root attestation payload (`A`).
672
+ */
673
+ static async #verifyRootAttestation(
674
+ attestationChain: string[],
675
+ rootPublicKey: Uint8Array,
676
+ now: number,
677
+ revocationChecker?: RevocationChecker
678
+ ): Promise<AttestationPayload> {
482
679
  // Step 5: Decode A
483
680
  const A = Attestation.decode(attestationChain[0]);
484
681
 
485
682
  // Step 6: Verify A signature against root
486
- let sigOkA = false;
683
+ let sigOkA: boolean;
487
684
  try {
488
685
  sigOkA = await Attestation.verifySignature(attestationChain[0], rootPublicKey);
489
686
  } catch {
@@ -509,93 +706,111 @@ export class Session {
509
706
  }
510
707
  }
511
708
 
512
- let G: AttestationPayload['grant'];
513
- let bPayload: AttestationPayload | undefined;
514
-
515
- if (isSubSession) {
516
- // Step 9: SubHandle chain
517
- const B = Attestation.decode(attestationChain[1]);
518
- bPayload = B;
709
+ return A;
710
+ }
519
711
 
520
- const signerPubABytes = (() => {
521
- try { return base64urlDecode(A.subjectId); } catch { return null; }
522
- })();
523
- if (!signerPubABytes) {
524
- throw new AttestationError('MALFORMED', 'FORMAT', 'Cannot decode root attestation subjectId');
525
- }
712
+ /**
713
+ * Step 9 — the SubHandle chain level: decode `B`, verify its
714
+ * signature against the root attestation's subject (the Handle key),
715
+ * time window, revocation, name/path agreement (both levels),
716
+ * wildcard permitting, session binding to the attested child key and
717
+ * grant nesting (child scopes ⊆ root scopes, child maxTtl ≤ root).
718
+ *
719
+ * @returns The decoded handle attestation payload (`B`).
720
+ */
721
+ static async #verifyHandleAttestation(
722
+ attestationChain: string[],
723
+ A: AttestationPayload,
724
+ payload: SessionPayload,
725
+ now: number,
726
+ revocationChecker?: RevocationChecker
727
+ ): Promise<AttestationPayload> {
728
+ // Decode B
729
+ const B = Attestation.decode(attestationChain[1]);
526
730
 
527
- let sigOkB = false;
528
- try {
529
- sigOkB = await Attestation.verifySignature(attestationChain[1], signerPubABytes);
530
- } catch {
531
- sigOkB = false;
532
- }
533
- if (!sigOkB) {
534
- throw new AttestationError('BAD_SIGNATURE', 'HANDLE_ATTESTATION', 'Handle attestation signature is invalid');
535
- }
731
+ // B signature against the root attestation's subject (the Handle key)
732
+ const signerPubABytes = (() => {
733
+ try { return base64urlDecode(A.subjectId); } catch { return null; }
734
+ })();
735
+ if (!signerPubABytes) {
736
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Cannot decode root attestation subjectId');
737
+ }
536
738
 
537
- if (now > B.exp + CLOCK_SKEW_SECONDS) {
538
- throw new AttestationError('EXPIRED', 'HANDLE_ATTESTATION', 'Handle attestation has expired');
539
- }
540
- if (now < B.iat - CLOCK_SKEW_SECONDS) {
541
- throw new AttestationError('NOT_YET_VALID', 'HANDLE_ATTESTATION', 'Handle attestation is not yet valid');
542
- }
739
+ let sigOkB: boolean;
740
+ try {
741
+ sigOkB = await Attestation.verifySignature(attestationChain[1], signerPubABytes);
742
+ } catch {
743
+ sigOkB = false;
744
+ }
745
+ if (!sigOkB) {
746
+ throw new AttestationError('BAD_SIGNATURE', 'HANDLE_ATTESTATION', 'Handle attestation signature is invalid');
747
+ }
543
748
 
544
- if (revocationChecker) {
545
- const isRevoked = await revocationChecker.isRevoked(B.jti);
546
- if (isRevoked) {
547
- throw new AttestationError('REVOKED', 'HANDLE_ATTESTATION', 'Handle attestation has been revoked');
548
- }
549
- }
749
+ // B time
750
+ if (now > B.exp + CLOCK_SKEW_SECONDS) {
751
+ throw new AttestationError('EXPIRED', 'HANDLE_ATTESTATION', 'Handle attestation has expired');
752
+ }
753
+ if (now < B.iat - CLOCK_SKEW_SECONDS) {
754
+ throw new AttestationError('NOT_YET_VALID', 'HANDLE_ATTESTATION', 'Handle attestation is not yet valid');
755
+ }
550
756
 
551
- if (B.subjectName !== payload.hPath![1]) {
552
- throw new AttestationError('PATH_MISMATCH', 'HANDLE_ATTESTATION',
553
- `Handle attestation subject "${B.subjectName}" does not match session subName "${payload.hPath![1]}"`);
554
- }
555
- if (A.subjectName !== payload.hPath![0]) {
556
- throw new AttestationError('PATH_MISMATCH', 'ROOT',
557
- `Root attestation subject "${A.subjectName}" does not match session handleName "${payload.hPath![0]}"`);
757
+ // B revocation
758
+ if (revocationChecker) {
759
+ const isRevoked = await revocationChecker.isRevoked(B.jti);
760
+ if (isRevoked) {
761
+ throw new AttestationError('REVOKED', 'HANDLE_ATTESTATION', 'Handle attestation has been revoked');
558
762
  }
763
+ }
559
764
 
560
- if (A.grant.subNamePatterns !== undefined) {
561
- if (!Attestation.matchNamePattern(B.subjectName, A.grant.subNamePatterns)) {
562
- throw new AttestationError('NAME_NOT_PERMITTED', 'ROOT',
563
- `SubHandle name "${B.subjectName}" not permitted by root patterns`);
564
- }
565
- }
765
+ // Name/path agreement, child then parent
766
+ if (B.subjectName !== payload.hPath![1]) {
767
+ throw new AttestationError('PATH_MISMATCH', 'HANDLE_ATTESTATION',
768
+ `Handle attestation subject "${B.subjectName}" does not match session subName "${payload.hPath![1]}"`);
769
+ }
770
+ if (A.subjectName !== payload.hPath![0]) {
771
+ throw new AttestationError('PATH_MISMATCH', 'ROOT',
772
+ `Root attestation subject "${A.subjectName}" does not match session handleName "${payload.hPath![0]}"`);
773
+ }
566
774
 
567
- if (payload.hId !== B.subjectId) {
568
- throw new AttestationError('SUBJECT_MISMATCH', 'SUB_ATTESTATION',
569
- 'Session handleId does not match handle attestation subjectId');
775
+ // Wildcard permitting
776
+ if (A.grant.subNamePatterns !== undefined) {
777
+ if (!Attestation.matchNamePattern(B.subjectName, A.grant.subNamePatterns)) {
778
+ throw new AttestationError('NAME_NOT_PERMITTED', 'ROOT',
779
+ `SubHandle name "${B.subjectName}" not permitted by root patterns`);
570
780
  }
781
+ }
571
782
 
572
- // Nested grant check
573
- const forbidden = B.grant.scopes.filter(s => !A.grant.scopes.includes(s));
574
- if (forbidden.length > 0) {
575
- throw new AttestationError('SCOPE_EXCEEDED', 'ROOT',
576
- `Handle attestation scopes not subset of root: ${forbidden.join(', ')}`);
577
- }
578
- if (B.grant.maxSessionTtl > A.grant.maxSessionTtl) {
579
- throw new AttestationError('TTL_EXCEEDED', 'ROOT',
580
- 'Handle attestation maxSessionTtl exceeds root attestation');
581
- }
783
+ // Session binds to the attested child key
784
+ if (payload.hId !== B.subjectId) {
785
+ throw new AttestationError('SUBJECT_MISMATCH', 'SUB_ATTESTATION',
786
+ 'Session handleId does not match handle attestation subjectId');
787
+ }
582
788
 
583
- G = B.grant;
584
- } else {
585
- // Handle session
586
- const subjectIdBytes = (() => {
587
- try { return base64urlDecode(A.subjectId); } catch { return null; }
588
- })();
589
- if (!subjectIdBytes) {
590
- throw new AttestationError('MALFORMED', 'FORMAT', 'Cannot decode root attestation subjectId');
591
- }
592
- if (payload.hId !== A.subjectId) {
593
- throw new AttestationError('SUBJECT_MISMATCH', 'ROOT',
594
- 'Session handleId does not match root attestation subjectId');
595
- }
596
- G = A.grant;
789
+ // Nested grant check (child ⊆ parent)
790
+ const forbidden = B.grant.scopes.filter(s => !A.grant.scopes.includes(s));
791
+ if (forbidden.length > 0) {
792
+ throw new AttestationError('SCOPE_EXCEEDED', 'ROOT',
793
+ `Handle attestation scopes not subset of root: ${forbidden.join(', ')}`);
794
+ }
795
+ if (B.grant.maxSessionTtl > A.grant.maxSessionTtl) {
796
+ throw new AttestationError('TTL_EXCEEDED', 'ROOT',
797
+ 'Handle attestation maxSessionTtl exceeds root attestation');
597
798
  }
598
799
 
800
+ return B;
801
+ }
802
+
803
+ /**
804
+ * Steps 10–11 — the session against the effective grant `G` (scopes,
805
+ * audiences, TTL) and against the earliest attestation expiry (the
806
+ * session must not outlive the chain that justifies it).
807
+ */
808
+ static #verifySessionAgainstGrant(
809
+ payload: SessionPayload,
810
+ G: AttestationPayload['grant'],
811
+ A: AttestationPayload,
812
+ bPayload?: AttestationPayload
813
+ ): void {
599
814
  // Step 10: Session vs grant G
600
815
  const sessionForbidden = payload.scp.filter(s => !G.scopes.includes(s));
601
816
  if (sessionForbidden.length > 0) {
@@ -612,22 +827,31 @@ export class Session {
612
827
  }
613
828
 
614
829
  // Step 11: Session does not outlive attestation
615
- const earliestAttestationExp = isSubSession
616
- ? Math.min(A.exp, bPayload!.exp)
830
+ const earliestAttestationExp = bPayload !== undefined
831
+ ? Math.min(A.exp, bPayload.exp)
617
832
  : A.exp;
618
833
  if (payload.exp > earliestAttestationExp + CLOCK_SKEW_SECONDS) {
619
834
  throw new AttestationError('SESSION_OUTLIVES_ATTESTATION', 'SESSION',
620
835
  'Session expires after the earliest attestation');
621
836
  }
837
+ }
622
838
 
623
- // Step 12: Session signature
839
+ /**
840
+ * Step 12 — the session signature must verify against the public key
841
+ * the session claims (`hId`, Base64URL of the signing public key).
842
+ */
843
+ static async #verifySessionSignature(
844
+ signatureBytes: Uint8Array,
845
+ payloadBytes: Uint8Array,
846
+ payload: SessionPayload
847
+ ): Promise<void> {
624
848
  const sessionPub = (() => {
625
849
  try { return base64urlDecode(payload.hId); } catch { return null; }
626
850
  })();
627
851
  if (!sessionPub) {
628
852
  throw new AttestationError('BAD_SIGNATURE', 'SESSION', 'Cannot decode session hId');
629
853
  }
630
- let sigOk = false;
854
+ let sigOk: boolean;
631
855
  try {
632
856
  sigOk = await Handle.verify(signatureBytes, payloadBytes, sessionPub);
633
857
  } catch {
@@ -636,25 +860,5 @@ export class Session {
636
860
  if (!sigOk) {
637
861
  throw new AttestationError('BAD_SIGNATURE', 'SESSION', 'Session signature is invalid');
638
862
  }
639
-
640
- // Step 13: Session revocation
641
- if (revocationChecker) {
642
- const isRevoked = await revocationChecker.isRevoked(payload.jti);
643
- if (isRevoked) {
644
- throw new AttestationError('REVOKED', 'SESSION', 'Session has been revoked');
645
- }
646
- }
647
-
648
- // Step 14
649
- return new Session(
650
- payload.hId,
651
- payload.hNm,
652
- payload.aud,
653
- payload.scp,
654
- payload.exp,
655
- token,
656
- payload.hPath,
657
- payload.jti
658
- );
659
863
  }
660
864
  }