@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
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ## 📦 Core Cryptographic Primitives
2
2
 
3
- Core primitives for the Me2em authorization protocol: hierarchical
3
+ Core primitives for the Me2eM authorization protocol: hierarchical
4
4
  deterministic identities (`Identity` → `Handle` → `SubHandle`), stateless
5
5
  signed sessions, and parent-signed **attestation chains** for delegatable,
6
6
  externally verifiable authorization — all on Ed25519.
@@ -57,7 +57,7 @@ different lenses:
57
57
  | **E2EE Messaging** (UC-6) | The user's messaging identity | An optional device identity |
58
58
 
59
59
  Full glossary (including Channel and material-class terms):
60
- see the [root README](../../README.md).
60
+ see the root [GLOSSARY.md](../../GLOSSARY.md).
61
61
 
62
62
  ---
63
63
 
@@ -84,8 +84,8 @@ pnpm add @me2em/core
84
84
  ```typescript
85
85
  import { Identity, Session } from '@me2em/core';
86
86
 
87
- // 1. Create an Identity from a 32-byte seed
88
- const seed = new Uint8Array(32).fill(42); // use a CSPRNG in production
87
+ // 1. Create an Identity from a 64-byte seed
88
+ const seed = new Uint8Array(64).fill(42); // use a CSPRNG in production
89
89
  const identity = await Identity.fromSeed(seed);
90
90
 
91
91
  // 2. Derive a contextual Handle
@@ -115,19 +115,19 @@ console.log(session.token); // base64url(payload).base64url(signature)
115
115
  ```typescript
116
116
  import {
117
117
  Identity, generateSeedPhrase,
118
- get32ByteSeedFromMnemonic, validateSeedPhrase,
118
+ get64ByteSeedFromMnemonic, validateSeedPhrase,
119
119
  } from '@me2em/core';
120
120
 
121
121
  const phrase = generateSeedPhrase(128); // 12 words (256 → 24 words)
122
122
  const check = validateSeedPhrase(phrase);
123
123
  if (!check.isValid) throw new Error(check.error);
124
124
 
125
- const seedBytes = await get32ByteSeedFromMnemonic(phrase);
125
+ const seedBytes = await get64ByteSeedFromMnemonic(phrase); // full 64-byte BIP39 seed
126
126
  const identity = await Identity.fromSeed(seedBytes);
127
127
  ```
128
128
 
129
129
  > ⚠️ Passphrases (BIP39 "25th word") ARE supported:
130
- > `get32ByteSeedFromMnemonic(words, passphrase)`. The passphrase is
130
+ > `get64ByteSeedFromMnemonic(words, passphrase)`. The passphrase is
131
131
  > case-sensitive, not recoverable, and silently derives a different
132
132
  > identity if mistyped. Store it with the same care as the words.
133
133
 
@@ -199,19 +199,25 @@ try {
199
199
  ### Error model
200
200
 
201
201
  All failures throw `AttestationError` with `code` and `level`
202
- (`ROOT | HANDLE_ATTESTATION | SUB_ATTESTATION | SESSION | FORMAT`):
202
+ (`ROOT | HANDLE_ATTESTATION | SUB_ATTESTATION | SESSION | FORMAT`) —
203
+ including token parsing, `Session.verifyStateless` and session-creation
204
+ constraint checks (PR-7). Match on `code`/`level`, never on messages:
203
205
 
204
206
  | code | levels |
205
207
  |---|---|
206
- | `MALFORMED`, `CHAIN_INCOMPLETE` | FORMAT |
208
+ | `MALFORMED`, `CHAIN_INCOMPLETE`, `MAX_DEPTH_EXCEEDED`, `DISPOSED` | FORMAT |
207
209
  | `BAD_SIGNATURE` | ROOT, HANDLE_ATTESTATION, SESSION |
208
210
  | `EXPIRED`, `NOT_YET_VALID`, `REVOKED` | ROOT, HANDLE_ATTESTATION, SESSION |
209
211
  | `PATH_MISMATCH` | ROOT, HANDLE_ATTESTATION, SESSION |
210
- | `NAME_NOT_PERMITTED`, `SCOPE_EXCEEDED`, `TTL_EXCEEDED` | ROOT |
212
+ | `NAME_NOT_PERMITTED`, `SCOPE_EXCEEDED`, `TTL_EXCEEDED` | ROOT, SESSION |
211
213
  | `SCOPE_EXCEEDED`, `TTL_EXCEEDED`, `AUDIENCE_NOT_PERMITTED`, `SESSION_OUTLIVES_ATTESTATION` | SESSION |
212
- | `SUBJECT_MISMATCH` | ROOT, SUB_ATTESTATION |
214
+ | `SUBJECT_MISMATCH` | ROOT, SUB_ATTESTATION, SESSION |
213
215
 
214
- "Note on error types. Failures detected during token parsing — wrong shape, invalid Base64URL, payload over 4096 bytes, non-JSON payload, missing required fields — throw a plain `Error`, before any attestation layer is consulted. Every failure **after** parsing throws an `AttestationError`. Integration code should handle both."
216
+ `MAX_DEPTH_EXCEEDED` signals the derivation-tree limit (a leaf `SubHandle`
217
+ cannot derive children); `DISPOSED` signals a capability call on a disposed
218
+ `Identity`/`Handle` — `DisposedError` is an `AttestationError` subclass
219
+ carrying that code, so `e.name === 'DisposedError'` still works for targeted
220
+ handling.
215
221
 
216
222
  ### Verification modes
217
223
 
@@ -269,13 +275,15 @@ external access granted via Mode 2 — see
269
275
 
270
276
  ```typescript
271
277
  class Identity {
272
- static fromSeed(seed: Uint8Array | string): Promise<Identity>; // 32 bytes or 64-char hex
278
+ static fromSeed(seed: Uint8Array | string): Promise<Identity>; // 64 bytes or 128-char hex
273
279
  deriveHandle(name: string, metadata?: HandleMetadata): Promise<Handle>;
274
280
  deriveSubHandle(handleName: string, subName: string,
275
281
  metadata?: SubHandleMetadata): Promise<SubHandle>; // atomic, for verification
282
+ sign(data: Uint8Array): Promise<Uint8Array>; // implements Signer (root key)
276
283
  attestHandle(name: string, grant: AttestationGrant,
277
284
  opts?: { ttlSeconds?, expiresAt?, jti?, now? }): Promise<Attestation>;
278
285
  getPublicKey(): Uint8Array;
286
+ dispose(): void; // zeroize key; capability methods throw DisposedError
279
287
  }
280
288
  ```
281
289
 
@@ -285,18 +293,19 @@ class Identity {
285
293
  class Handle {
286
294
  getId(): string; // base64url of the public key
287
295
  getName(): string; // canonical (normalized) name
288
- getMetadata(): HandleMetadata | undefined;
289
- getPublicKey(): Uint8Array;
296
+ getMetadata(): HandleMetadata | undefined; // defensive copy
297
+ getPublicKey(): Uint8Array; // defensive copy
290
298
  getPath(): string[] | undefined; // undefined for Handle, path for SubHandle
291
299
  sign(data: Uint8Array): Promise<Uint8Array>;
292
300
  static verify(sig: Uint8Array, data: Uint8Array, pub: Uint8Array): Promise<boolean>;
293
- derivePassword(context: string, length?: number): string; // base64url secret
294
- deriveChannelKey(context: string): Uint8Array; // 32-byte AES key
301
+ derivePassword(context: string, options?: { revision?: number; byteLength?: number }): string; // base64url secret
302
+ deriveChannelKey(context: string, options?: { revision?: number }): Uint8Array; // 32-byte AES key
295
303
  deriveSharedSecret(otherPublicKey: Uint8Array): Promise<Uint8Array>; // X25519 + HKDF
296
304
  deriveSubHandle(name: string, metadata?: SubHandleMetadata): Promise<SubHandle>;
297
305
  attestSubHandle(subName: string, grant: AttestationGrant,
298
306
  opts?: { ttlSeconds?, expiresAt?, jti?, now? }): Promise<Attestation>;
299
307
  validateSessionOptions(options: { audience: string; scopes: string[]; ttl: number }): void;
308
+ dispose(): void; // zeroize key; capability methods throw DisposedError
300
309
  }
301
310
  ```
302
311
 
@@ -304,16 +313,37 @@ class Handle {
304
313
 
305
314
  ```typescript
306
315
  class SubHandle extends Handle {
307
- getPath(): string[]; // ['station-001', 'connector-ccs']
316
+ getPath(): string[]; // ['station-001', 'connector-ccs'] — a copy
308
317
  getPathString(): string; // 'station-001/connector-ccs'
309
318
  getDepth(): number; // always 2
310
319
  isLeaf(): boolean; // always true
311
- getSubMetadata(): SubHandleMetadata;
320
+ getSubMetadata(): SubHandleMetadata; // defensive copy of constraints
312
321
  validateSessionOptions(options: { audience: string; scopes: string[]; ttl: number }): void;
313
322
  // deriveSubHandle is overridden and ALWAYS throws (leaf node)
314
323
  }
315
324
  ```
316
325
 
326
+ ### Object lifecycle (`dispose()`)
327
+
328
+ `Identity` and `Handle` own true `#private` key material. `dispose()`
329
+ zeroizes the private key and permanently revokes every capability method
330
+ (`sign`, derivations, attestation issuance) — they then throw
331
+ `DisposedError`. Informational getters (`getName`, `getId`,
332
+ `getPublicKey`, metadata) keep working: public keys are not secrets.
333
+ Serialization is redacted by design — `JSON.stringify(handle)` and
334
+ `console.log(handle)` emit only `{ kind, id, name, path? }`, never key
335
+ material. Defensive copies on inputs and getters mean caller-side
336
+ mutation never reaches the stored keys.
337
+
338
+ ```typescript
339
+ const handle = await identity.deriveHandle('station-001');
340
+ try {
341
+ // ... use the handle ...
342
+ } finally {
343
+ handle.dispose(); // key material zeroized; idempotent
344
+ }
345
+ ```
346
+
317
347
  ### `Session`
318
348
 
319
349
  ```typescript
@@ -347,7 +377,7 @@ interface RevocationChecker {
347
377
 
348
378
  ```typescript
349
379
  class Attestation {
350
- static issue(signerPrivateKey: Uint8Array, subjectPublicKey: Uint8Array,
380
+ static issue(signer: Signer, subjectPublicKey: Uint8Array,
351
381
  subjectName: string, grant: AttestationGrant,
352
382
  opts?: { ttlSeconds?, expiresAt?, jti?, now? }): Promise<Attestation>;
353
383
  static decode(token: string): AttestationPayload; // structure only — no sig, no time
@@ -358,6 +388,13 @@ class Attestation {
358
388
  get jti(): string;
359
389
  }
360
390
 
391
+ interface Signer { // the issuance contract (D2)
392
+ sign(data: Uint8Array): Promise<Uint8Array>;
393
+ }
394
+ // Identity, Handle and SubHandle implement Signer; custom
395
+ // (remote/HSM-backed) signers are accepted structurally. Raw private
396
+ // keys are NOT accepted as of 1.0.0-rc.1 — the signer's key stays encapsulated.
397
+
361
398
  interface AttestationGrant {
362
399
  audiences?: string[]; // undefined = unrestricted; [] = deny all
363
400
  scopes: string[]; // exact strings, no wildcards
@@ -373,10 +410,53 @@ class AttestationError extends Error {
373
410
 
374
411
  ### Name normalization
375
412
 
376
- All derivation inputs are canonicalized: `NFKC → lowercase → trim`,
377
- then validated against `/^[a-z0-9][a-z0-9._@-]{0,62}$/`. Names with `/`,
378
- non-ASCII letters, or > 64 chars **throw**. Identical inputs always
379
- produce identical keys across platforms and entry points.
413
+ All string derivation inputs are canonicalized: `NFKC → lowercase →
414
+ trim`. NFKC applies to string inputs only — `revision` (a positive
415
+ integer) is canonical by construction and is never normalized.
416
+ Names are then validated against `/^[a-z0-9][a-z0-9._@-]{0,62}$/`; names
417
+ with `/`, non-ASCII letters, or > 64 chars **throw**. Password/channel
418
+ contexts use the same canonical form without the character-set pattern
419
+ (a context is a caller-defined label, not a wire identifier) but MUST
420
+ NOT be empty after canonicalization. Identical inputs always produce
421
+ identical keys across platforms and entry points.
422
+
423
+ ### Secret revision model (rotation)
424
+
425
+ `derivePassword` and `deriveChannelKey` take a `revision` (positive
426
+ integer, default `1`). A `revision` is a monotonic integer — canonical
427
+ by construction; the NFKC canonicalization above applies to the string
428
+ `context` only. Revision 1 is the initial secret — byte-identical
429
+ to the frozen v1.0 derivation. Revision `N ≥ 2` derives a secret that is
430
+ cryptographically independent of revision 1 for the same context: the
431
+ sanctioned rotation path when a credential leaks, without changing the
432
+ context string. Both parties of a channel MUST bump the revision in
433
+ lockstep.
434
+
435
+ ```typescript
436
+ const github = handle.derivePassword('github'); // revision 1
437
+ const rotated = handle.derivePassword('github', { revision: 2 }); // after a breach
438
+ const long = handle.derivePassword('github', { byteLength: 32 });
439
+ const channel = handle.deriveChannelKey('telemetry-v1', { revision: 2 }); // both peers!
440
+ ```
441
+
442
+ Info strings: `me2em/secret/v1` → `me2em/secret/v1/rN`,
443
+ `me2em/channel/v1` → `me2em/channel/v1/rN` (centralized in
444
+ `DERIVATION_PATHS.password(revision?)` / `.channel(revision?)`).
445
+ `byteLength` accepts an integer in `[1, 8160]` (RFC 5869 bound); the
446
+ output is prefix-stable — the first `n` bytes of a longer derivation
447
+ equal the `n`-byte derivation.
448
+
449
+ **Choosing revision values (application-level convention).** A
450
+ `revision` is an opaque positive integer — the protocol deliberately
451
+ does not assign meaning to it (mechanism, not policy). Common
452
+ app-level conventions: date-stamped rotations (`20261009` = `YYYYMMDD`,
453
+ keeps the rotation history readable), small enum-like codes for named
454
+ credential generations, or a hash of a human-readable label mapped
455
+ into the integer range — the last one reproduces the same secret from
456
+ the label across implementations without storing the mapping. The
457
+ label↔revision mapping (where one exists) is public metadata: keep it
458
+ next to the credentials it describes (e.g. in the password manager's
459
+ notes) — the secret itself is protected by the seed alone.
380
460
 
381
461
  ## 🎯 Core Use Cases
382
462
 
@@ -401,6 +481,67 @@ Redis `RevocationChecker`.
401
481
  - **Signatures:** Ed25519 (RFC 8032); tokens are `base64url(payload).base64url(signature)`
402
482
  - **Attestation payload limit:** 2048 bytes; **session payload limit:** 4096 bytes
403
483
  - **Clock skew tolerance:** ±30 seconds on all time checks
484
+ - **Derivation module:** the formulas above live in the `crypto`
485
+ namespace — `crypto.deriveRootKey`, `crypto.deriveHandleKey`,
486
+ `crypto.deriveSubHandleKey`, plus `crypto.rawX25519SharedSecret` for
487
+ the raw X25519 (Montgomery) ECDH step of the P2P derivation. Both
488
+ SubHandle entry points (`handle.deriveSubHandle` and
489
+ `identity.deriveSubHandle`) share `crypto.deriveSubHandleKey`, so
490
+ their outputs are byte-identical by construction.
491
+ - **Raw primitives in `crypto`:** besides the derivation module, the
492
+ namespace exposes documented Ed25519 wrappers (`crypto.getPublicKey`,
493
+ `crypto.sign`, `crypto.verify` and their `*Async` variants) and the
494
+ `crypto.hkdf` / `crypto.sha256` helpers — building blocks for tooling
495
+ outside the token flow (the protocol itself signs through
496
+ `Identity`/`Handle`/`SubHandle`, which implement `Signer`). The
497
+ wrappers are real functions rather than alias re-exports so TSDoc
498
+ ownership and TypeDoc typing stay in-package (`treatWarningsAsErrors`);
499
+ they are frozen public API (spec §12) — removal is a breaking 2.0.0
500
+ decision, do not propose.
501
+ - **Auto-init:** importing `@me2em/core` synchronously configures the
502
+ Ed25519 backend (sha512 wiring for `@noble/ed25519`). There is no
503
+ init call to remember and no async setup — the first sign/verify/derive
504
+ can run immediately after import. The guarantee is structural, not
505
+ conventional: the package exposes a single entry point (the `exports`
506
+ map allows only `.` — deep subpath imports such as
507
+ `@me2em/core/crypto/*` are not part of the public API), and every
508
+ module that touches Ed25519 imports the backend from
509
+ `crypto/init.ts`, which configures it on module load. Any code path
510
+ that can reach a crypto operation therefore loads the configured
511
+ backend first, in any import order (pinned by `test/arch-cycle.spec.ts`;
512
+ see specs/v1.0.md §11 for the module-structure contract).
513
+
514
+ ## ⚙️ Runtime & Limits
515
+
516
+ **Runtimes**
517
+
518
+ - **Node.js ≥ 22** (`engines.node`, A2 — Node 18/20 are EOL; CI pins
519
+ Node 22).
520
+ - Modern browsers and edge runtimes. Portability is pinned by tests:
521
+ base64url comes from `@scure/base` — `btoa`/`atob` are banned from
522
+ `src/` by a source-scan test; `jti` generation uses
523
+ `crypto.randomUUID` with a `getRandomValues`-based v4 fallback.
524
+ - The Ed25519 backend auto-initializes at import (structural guarantee —
525
+ see Cryptographic Details above); modules are side-effect-free at the
526
+ top level otherwise.
527
+
528
+ **Limits**
529
+
530
+ | Limit | Value | Enforced |
531
+ |-------|-------|----------|
532
+ | Attestation payload | ≤ 2048 bytes (`ATTESTATION_MAX_PAYLOAD`, exported) | rejected before decode |
533
+ | Session payload | ≤ 4096 bytes | rejected before decode |
534
+ | Clock-skew tolerance | ±30 seconds on all time checks | `EXPIRED` / `NOT_YET_VALID` |
535
+ | Derivation tree depth | `MAX_DEPTH = 2` — a `SubHandle` is always a leaf | `MAX_DEPTH_EXCEEDED` |
536
+ | Password `byteLength` | integer 1–8160 (RFC 5869: 255 × SHA-256), default 16 | `MALFORMED`/`FORMAT` |
537
+ | Session `ttl` | positive integer (seconds), capped by the grant's `maxSessionTtl`; the session cannot outlive the earliest attestation expiry | `MALFORMED` / `TTL_EXCEEDED` |
538
+ | `jti` length | non-empty, ≤ 256 characters | `MALFORMED` |
539
+
540
+ **Key lifecycle:** `dispose()` zeroizes the private key (`fill(0)`) and
541
+ permanently revokes all capability methods (`DisposedError`); it is
542
+ idempotent. Hard zeroization cannot be guaranteed in a JS runtime —
543
+ GC/JIT may retain copies ([BACKLOG](../../BACKLOG.md) BL-07,
544
+ [THREAT_MODEL.md](../../THREAT_MODEL.md) §5.2).
404
545
 
405
546
  ## 🛡️ Security Best Practices
406
547
 
@@ -428,25 +569,31 @@ Redis `RevocationChecker`.
428
569
  cd packages/core && pnpm test
429
570
  ```
430
571
 
431
- 186 tests cover: deterministic derivation and cross-entry-point key
432
- consistency, name canonicalization, session lifecycle (create, verify,
572
+ 350 tests cover: deterministic derivation and cross-entry-point key
573
+ consistency, name canonicalization, derivation revisions (r1 byte-parity,
574
+ r2 independence, NFKC contexts), session lifecycle (create, verify,
433
575
  tamper, expiry, iat), revocation, SubHandle constraint enforcement,
434
576
  MAX_DEPTH leaf enforcement, attestation issue/decode/signature
435
- determinism and validation, and the full `verifyAttested` chain
436
- (20+ cases including nesting, wildcard permitting, revocation at every
577
+ determinism and validation, the full `verifyAttested` chain
578
+ (28 cases including nesting, wildcard permitting, revocation at every
437
579
  level, signature robustness, BIP39 passphrase derivation, and wordlist
438
- validation).
580
+ validation), module-structure and crypto-boundary pins, and parser fuzz
581
+ (~1 050 rounds).
439
582
 
440
583
  ## 🗺️ Roadmap
441
584
 
442
- Passphrase support has shipped (0.7.0). Remaining recommendations —
443
- session lineage (`sid`), key zeroing, attestation reference compression,
585
+ Passphrase support and `dispose()` zeroization have shipped. Remaining
586
+ recommendations — session lineage (`sid`), zeroization hardening
587
+ (BL-07), attestation reference compression,
444
588
  and the full package strategy (`@me2em/crypto`, `@me2em/messenger`,
445
589
  `@me2em/iot`) — live in [BACKLOG.md](../../BACKLOG.md). The backlog is
446
590
  advisory and not part of the shipped API contract.
447
591
 
592
+ The public API is **frozen** as of `1.0.0-rc.1` — see
593
+ [specs/v1.0.md §12](../../specs/v1.0.md) for the evolution rules.
594
+
448
595
  ## 📜 License
449
596
 
450
597
  Apache License 2.0 — see [LICENSE](../../LICENSE).
451
598
 
452
- © 2026 Me2em Organization. Built for privacy, openness, and user sovereignty.
599
+ © 2026 Me2eM Organization. Built for privacy, openness, and user sovereignty.
@@ -1,3 +1,5 @@
1
+ import type { Signer } from './types.js';
2
+ export { AttestationError, type AttestationErrorCode, type AttestationLevel } from './errors.js';
1
3
  export declare const ATTESTATION_TYPE = "me2em/attestation/v1";
2
4
  export declare const ATTESTATION_MAX_PAYLOAD = 2048;
3
5
  export interface AttestationGrant {
@@ -33,13 +35,6 @@ export interface AttestationPayload {
33
35
  exp: number;
34
36
  jti: string;
35
37
  }
36
- export type AttestationErrorCode = 'MALFORMED' | 'BAD_SIGNATURE' | 'EXPIRED' | 'NOT_YET_VALID' | 'REVOKED' | 'PATH_MISMATCH' | 'NAME_NOT_PERMITTED' | 'SCOPE_EXCEEDED' | 'AUDIENCE_NOT_PERMITTED' | 'TTL_EXCEEDED' | 'CHAIN_INCOMPLETE' | 'SUBJECT_MISMATCH' | 'SESSION_OUTLIVES_ATTESTATION';
37
- export type AttestationLevel = 'ROOT' | 'HANDLE_ATTESTATION' | 'SUB_ATTESTATION' | 'SESSION' | 'FORMAT';
38
- export declare class AttestationError extends Error {
39
- readonly code: AttestationErrorCode;
40
- readonly level: AttestationLevel;
41
- constructor(code: AttestationErrorCode, level: AttestationLevel, msg: string);
42
- }
43
38
  /**
44
39
  * A parent-signed statement binding a derived child key to a name and a
45
40
  * grant. Chains of attestations (`Identity → Handle → SubHandle`) allow
@@ -54,22 +49,20 @@ export declare class AttestationError extends Error {
54
49
  * ```ts
55
50
  * import { ed25519 } from '@noble/curves/ed25519.js';
56
51
  *
57
- * // Parent (signer) and child (subject) keys — use a CSPRNG in practice:
58
- * const signerPriv = ed25519.utils.randomPrivateKey();
59
- * const signerPub = ed25519.getPublicKey(signerPriv);
52
+ * // Issuer (a Signer — Identity/Handle qualify) and subject public key:
53
+ * const identity = await Identity.fromSeed(seed);
60
54
  * const childPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());
61
55
  *
62
- * const A = await Attestation.issue(signerPriv, childPub, 'station-001', {
56
+ * const A = await Attestation.issue(identity, childPub, 'station-001', {
63
57
  * audiences: ['ev-app.com'],
64
58
  * scopes: ['charge:start', 'charge:stop'],
65
59
  * maxSessionTtl: 7200,
66
60
  * subNamePatterns: ['connector-*'],
67
61
  * });
68
62
  *
69
- * const ok = await Attestation.verifySignature(A.token, signerPub); // true
63
+ * const ok = await Attestation.verifySignature(A.token, identity.getPublicKey()); // true
70
64
  * const payload = Attestation.decode(A.token); // structure only — no sig, no time
71
- *
72
- * ```
65
+ * ```
73
66
  *
74
67
  * @category Core Primitives
75
68
  */
@@ -94,6 +87,10 @@ export declare class Attestation {
94
87
  /**
95
88
  * Verifies the token signature against a public key.
96
89
  *
90
+ * A signature whose length differs from the 64-byte Ed25519 size is
91
+ * rejected with `false` before any crypto runs (PR-7 pre-check) —
92
+ * the method therefore never throws for short/long signatures.
93
+ *
97
94
  * @returns `false` for a bad signature or a wrong key. Returns
98
95
  * `false` for any invalid signature, including malformed lengths.
99
96
  * It still throws `AttestationError` `MALFORMED`/`FORMAT` for
@@ -122,7 +119,16 @@ export declare class Attestation {
122
119
  * `undefined` grant fields are omitted from the JSON entirely
123
120
  * (distinguishable from `[]`).
124
121
  *
125
- * @param signerPrivateKey - 32-byte Ed25519 private key of the parent.
122
+ * The `signer` is a {@link Signer} — typically the issuing
123
+ * {@link Identity} (root attestations) or {@link Handle} (SubHandle
124
+ * attestations). Raw private keys never cross a trust boundary as
125
+ * function arguments (D2): the key material stays encapsulated in the
126
+ * signer object.
127
+ *
128
+ * @param signer - Object producing the Ed25519 signature via
129
+ * `sign(data)`. `Identity` and `Handle` implement `Signer`; custom
130
+ * implementations (remote/HSM-backed signing) are accepted
131
+ * structurally.
126
132
  * @param subjectPublicKey - 32-byte Ed25519 public key being attested.
127
133
  * @param subjectName - Child name; canonicalized before signing.
128
134
  * @param grant - Constraints enforced by verifiers (Mode 2).
@@ -133,15 +139,18 @@ export declare class Attestation {
133
139
  * @throws {AttestationError} `MALFORMED`/`FORMAT` if the grant is
134
140
  * structurally invalid (bad scopes/TTL/audiences or a wildcard
135
141
  * not at the end of a `subNamePatterns` entry).
142
+ * @throws {TypeError} If `signer` has no callable `sign` method — e.g.
143
+ * when a raw private key is passed (the pre-v1.0 form is no longer
144
+ * accepted).
136
145
  * @throws {Error} If `subjectPublicKey` is not 32 bytes.
137
146
  *
138
147
  * @example
139
148
  * ```ts
140
- * const att = await Attestation.issue(rootPriv, childPub, 'Station-1',
149
+ * const att = await Attestation.issue(rootIdentity, childPub, 'Station-1',
141
150
  * { scopes: ['read'], maxSessionTtl: 3600 }, { ttlSeconds: 600 });
142
151
  * ```
143
152
  */
144
- static issue(signerPrivateKey: Uint8Array, subjectPublicKey: Uint8Array, subjectName: string, grant: AttestationGrant, opts?: {
153
+ static issue(signer: Signer, subjectPublicKey: Uint8Array, subjectName: string, grant: AttestationGrant, opts?: {
145
154
  ttlSeconds?: number;
146
155
  expiresAt?: number;
147
156
  jti?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"attestation.d.ts","sourceRoot":"","sources":["../src/attestation.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,gBAAgB,yBAAyB,CAAC;AACvD,eAAO,MAAM,uBAAuB,OAAO,CAAC;AAE5C,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB;;;OAGG;IACH,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAC;IACtB;;;;;OAKG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;CAC5B;AAED,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,OAAO,gBAAgB,CAAC;IAC7B,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,gBAAgB,CAAC;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,MAAM,oBAAoB,GAC5B,WAAW,GAAG,eAAe,GAAG,SAAS,GAAG,eAAe,GAC3D,SAAS,GAAG,eAAe,GAAG,oBAAoB,GAClD,gBAAgB,GAAG,wBAAwB,GAAG,cAAc,GAC5D,kBAAkB,GAAG,kBAAkB,GAAG,8BAA8B,CAAC;AAE7E,MAAM,MAAM,gBAAgB,GACxB,MAAM,GAAG,oBAAoB,GAAG,iBAAiB,GAAG,SAAS,GAAG,QAAQ,CAAC;AAE7E,qBAAa,gBAAiB,SAAQ,KAAK;aAEvB,IAAI,EAAE,oBAAoB;aAC1B,KAAK,EAAE,gBAAgB;gBADvB,IAAI,EAAE,oBAAoB,EAC1B,KAAK,EAAE,gBAAgB,EACvC,GAAG,EAAE,MAAM;CAEd;AA+CD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqB;IAC9C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAEhC,OAAO;IAKP,IAAI,OAAO,IAAI,kBAAkB,CAEhC;IAED,IAAI,KAAK,IAAI,MAAM,CAElB;IAED,IAAI,GAAG,IAAI,MAAM,CAEhB;IAED;;;;;;;;;OASG;IACH,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,kBAAkB;IAuDhD;;;;;;;QAOI;WACU,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC;IAS3F;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,OAAO;IAYlE;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;WACU,KAAK,CAChB,gBAAgB,EAAE,UAAU,EAC5B,gBAAgB,EAAE,UAAU,EAC5B,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE,gBAAgB,EACvB,IAAI,CAAC,EAAE;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,GAC7E,OAAO,CAAC,WAAW,CAAC;CA4DxB"}
1
+ {"version":3,"file":"attestation.d.ts","sourceRoot":"","sources":["../src/attestation.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAGzC,OAAO,EAAE,gBAAgB,EAAE,KAAK,oBAAoB,EAAE,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEjG,eAAO,MAAM,gBAAgB,yBAAyB,CAAC;AACvD,eAAO,MAAM,uBAAuB,OAAO,CAAC;AAK5C,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB;;;OAGG;IACH,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAC;IACtB;;;;;OAKG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;CAC5B;AAED,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,OAAO,gBAAgB,CAAC;IAC7B,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,gBAAgB,CAAC;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;CACb;AA8DD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqB;IAC9C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAEhC,OAAO;IAKP,IAAI,OAAO,IAAI,kBAAkB,CAEhC;IAED,IAAI,KAAK,IAAI,MAAM,CAElB;IAED,IAAI,GAAG,IAAI,MAAM,CAEhB;IAED;;;;;;;;;OASG;IACH,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,kBAAkB;IAkEhD;;;;;;;;;;;QAWI;WACU,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC;IAc3F;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,OAAO;IAYlE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAuCG;WACU,KAAK,CAChB,MAAM,EAAE,MAAM,EACd,gBAAgB,EAAE,UAAU,EAC5B,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE,gBAAgB,EACvB,IAAI,CAAC,EAAE;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,GAC7E,OAAO,CAAC,WAAW,CAAC;CA2ExB"}
@@ -1,21 +1,16 @@
1
1
  // attestation.ts
2
2
  //
3
3
  // Attestation module: cryptographically signed, self-contained
4
- // authorization attestations for the Me2em protocol.
4
+ // authorization attestations for the Me2eM protocol.
5
5
  import { normalizeName } from './canonical-name.js';
6
- import { base64urlEncode, base64urlDecode } from './util.js';
6
+ import { base64urlEncode, base64urlDecode, randomUUID, safeJsonParse } from './util.js';
7
7
  import { ed } from './crypto/init.js';
8
+ import { AttestationError } from './errors.js';
9
+ export { AttestationError } from './errors.js';
8
10
  export const ATTESTATION_TYPE = 'me2em/attestation/v1';
9
11
  export const ATTESTATION_MAX_PAYLOAD = 2048;
10
- export class AttestationError extends Error {
11
- code;
12
- level;
13
- constructor(code, level, msg) {
14
- super(`[${level}/${code}] ${msg}`);
15
- this.code = code;
16
- this.level = level;
17
- }
18
- }
12
+ /** Maximum accepted length of an attestation `jti` (hardening, PR-7). */
13
+ const MAX_JTI_LENGTH = 256;
19
14
  function throwFormat(code, msg) {
20
15
  throw new AttestationError(code, 'FORMAT', msg);
21
16
  }
@@ -32,19 +27,33 @@ function parseToken(token) {
32
27
  if (!b64urlRegex.test(payloadB64) || !b64urlRegex.test(signatureB64)) {
33
28
  throwFormat('MALFORMED', 'Payload and signature must be valid Base64URL');
34
29
  }
35
- const payloadBytes = base64urlDecode(payloadB64);
30
+ let payloadBytes;
31
+ try {
32
+ payloadBytes = base64urlDecode(payloadB64);
33
+ }
34
+ catch {
35
+ throwFormat('MALFORMED', 'Payload and signature must be valid Base64URL');
36
+ }
36
37
  if (payloadBytes.length > ATTESTATION_MAX_PAYLOAD) {
37
38
  throwFormat('MALFORMED', `Payload exceeds maximum size of ${ATTESTATION_MAX_PAYLOAD} bytes`);
38
39
  }
39
40
  let payload;
40
41
  try {
41
42
  const jsonString = new TextDecoder().decode(payloadBytes);
42
- payload = JSON.parse(jsonString);
43
+ payload = safeJsonParse(jsonString);
44
+ }
45
+ catch (e) {
46
+ throwFormat('MALFORMED', e instanceof SyntaxError && e.message.includes('__proto__')
47
+ ? `Payload is not valid JSON — ${e.message}`
48
+ : 'Payload is not valid JSON');
49
+ }
50
+ let signatureBytes;
51
+ try {
52
+ signatureBytes = base64urlDecode(signatureB64);
43
53
  }
44
54
  catch {
45
- throwFormat('MALFORMED', 'Payload is not valid JSON');
55
+ throwFormat('MALFORMED', 'Payload and signature must be valid Base64URL');
46
56
  }
47
- const signatureBytes = base64urlDecode(signatureB64);
48
57
  return { payloadBytes, signatureBytes, payload };
49
58
  }
50
59
  /**
@@ -61,22 +70,20 @@ function parseToken(token) {
61
70
  * ```ts
62
71
  * import { ed25519 } from '@noble/curves/ed25519.js';
63
72
  *
64
- * // Parent (signer) and child (subject) keys — use a CSPRNG in practice:
65
- * const signerPriv = ed25519.utils.randomPrivateKey();
66
- * const signerPub = ed25519.getPublicKey(signerPriv);
73
+ * // Issuer (a Signer — Identity/Handle qualify) and subject public key:
74
+ * const identity = await Identity.fromSeed(seed);
67
75
  * const childPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());
68
76
  *
69
- * const A = await Attestation.issue(signerPriv, childPub, 'station-001', {
77
+ * const A = await Attestation.issue(identity, childPub, 'station-001', {
70
78
  * audiences: ['ev-app.com'],
71
79
  * scopes: ['charge:start', 'charge:stop'],
72
80
  * maxSessionTtl: 7200,
73
81
  * subNamePatterns: ['connector-*'],
74
82
  * });
75
83
  *
76
- * const ok = await Attestation.verifySignature(A.token, signerPub); // true
84
+ * const ok = await Attestation.verifySignature(A.token, identity.getPublicKey()); // true
77
85
  * const payload = Attestation.decode(A.token); // structure only — no sig, no time
78
- *
79
- * ```
86
+ * ```
80
87
  *
81
88
  * @category Core Primitives
82
89
  */
@@ -144,14 +151,29 @@ export class Attestation {
144
151
  if (typeof payload.exp !== 'number') {
145
152
  throwFormat('MALFORMED', 'Missing required field: exp');
146
153
  }
147
- if (typeof payload.jti !== 'string') {
154
+ // Non-finite numbers survive JSON.parse only as `Infinity` (e.g. 1e999);
155
+ // unchecked, `now > exp + skew` would be false forever — fail-open expiry.
156
+ if (!Number.isFinite(payload.iat) || !Number.isFinite(payload.exp)) {
157
+ throwFormat('MALFORMED', 'iat/exp must be finite numbers');
158
+ }
159
+ if (payload.exp <= payload.iat) {
160
+ throwFormat('MALFORMED', 'exp must be greater than iat');
161
+ }
162
+ if (typeof payload.jti !== 'string' || payload.jti.length === 0) {
148
163
  throwFormat('MALFORMED', 'Missing required field: jti');
149
164
  }
165
+ if (payload.jti.length > MAX_JTI_LENGTH) {
166
+ throwFormat('MALFORMED', `jti exceeds the maximum length of ${MAX_JTI_LENGTH} characters`);
167
+ }
150
168
  return payload;
151
169
  }
152
170
  /**
153
171
  * Verifies the token signature against a public key.
154
172
  *
173
+ * A signature whose length differs from the 64-byte Ed25519 size is
174
+ * rejected with `false` before any crypto runs (PR-7 pre-check) —
175
+ * the method therefore never throws for short/long signatures.
176
+ *
155
177
  * @returns `false` for a bad signature or a wrong key. Returns
156
178
  * `false` for any invalid signature, including malformed lengths.
157
179
  * It still throws `AttestationError` `MALFORMED`/`FORMAT` for
@@ -159,6 +181,11 @@ export class Attestation {
159
181
  */
160
182
  static async verifySignature(token, signerPublicKey) {
161
183
  const { signatureBytes, payloadBytes } = parseToken(token);
184
+ // Ed25519 signatures are exactly 64 bytes — reject other lengths
185
+ // before the curve math (the underlying library throws RangeError).
186
+ if (signatureBytes.length !== 64) {
187
+ return false;
188
+ }
162
189
  try {
163
190
  return ed.verify(signatureBytes, payloadBytes, signerPublicKey);
164
191
  }
@@ -202,7 +229,16 @@ export class Attestation {
202
229
  * `undefined` grant fields are omitted from the JSON entirely
203
230
  * (distinguishable from `[]`).
204
231
  *
205
- * @param signerPrivateKey - 32-byte Ed25519 private key of the parent.
232
+ * The `signer` is a {@link Signer} — typically the issuing
233
+ * {@link Identity} (root attestations) or {@link Handle} (SubHandle
234
+ * attestations). Raw private keys never cross a trust boundary as
235
+ * function arguments (D2): the key material stays encapsulated in the
236
+ * signer object.
237
+ *
238
+ * @param signer - Object producing the Ed25519 signature via
239
+ * `sign(data)`. `Identity` and `Handle` implement `Signer`; custom
240
+ * implementations (remote/HSM-backed signing) are accepted
241
+ * structurally.
206
242
  * @param subjectPublicKey - 32-byte Ed25519 public key being attested.
207
243
  * @param subjectName - Child name; canonicalized before signing.
208
244
  * @param grant - Constraints enforced by verifiers (Mode 2).
@@ -213,18 +249,29 @@ export class Attestation {
213
249
  * @throws {AttestationError} `MALFORMED`/`FORMAT` if the grant is
214
250
  * structurally invalid (bad scopes/TTL/audiences or a wildcard
215
251
  * not at the end of a `subNamePatterns` entry).
252
+ * @throws {TypeError} If `signer` has no callable `sign` method — e.g.
253
+ * when a raw private key is passed (the pre-v1.0 form is no longer
254
+ * accepted).
216
255
  * @throws {Error} If `subjectPublicKey` is not 32 bytes.
217
256
  *
218
257
  * @example
219
258
  * ```ts
220
- * const att = await Attestation.issue(rootPriv, childPub, 'Station-1',
259
+ * const att = await Attestation.issue(rootIdentity, childPub, 'Station-1',
221
260
  * { scopes: ['read'], maxSessionTtl: 3600 }, { ttlSeconds: 600 });
222
261
  * ```
223
262
  */
224
- static async issue(signerPrivateKey, subjectPublicKey, subjectName, grant, opts) {
263
+ static async issue(signer, subjectPublicKey, subjectName, grant, opts) {
264
+ if (typeof signer?.sign !== 'function') {
265
+ throw new TypeError('Attestation.issue requires a Signer — an object with a sign(data) ' +
266
+ 'method (Identity or Handle). Raw private keys are no longer accepted.');
267
+ }
225
268
  const name = normalizeName(subjectName);
226
269
  if (subjectPublicKey.length !== 32) {
227
- throw new Error('subject public key must be 32 bytes');
270
+ throwFormat('MALFORMED', 'subject public key must be 32 bytes');
271
+ }
272
+ if (opts?.jti !== undefined &&
273
+ (typeof opts.jti !== 'string' || opts.jti.length === 0 || opts.jti.length > MAX_JTI_LENGTH)) {
274
+ throwFormat('MALFORMED', `opts.jti must be a non-empty string of at most ${MAX_JTI_LENGTH} characters`);
228
275
  }
229
276
  // Validate grant
230
277
  if (!Array.isArray(grant.scopes) || !grant.scopes.every((s) => typeof s === 'string')) {
@@ -251,7 +298,7 @@ export class Attestation {
251
298
  }
252
299
  const now = opts?.now ?? Math.floor(Date.now() / 1000);
253
300
  const exp = opts?.expiresAt ?? (now + (opts?.ttlSeconds ?? 31536000));
254
- const jti = opts?.jti ?? crypto.randomUUID();
301
+ const jti = opts?.jti ?? randomUUID();
255
302
  const grantJson = {};
256
303
  if (grant.audiences !== undefined)
257
304
  grantJson.audiences = [...grant.audiences];
@@ -269,7 +316,7 @@ export class Attestation {
269
316
  jti,
270
317
  };
271
318
  const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
272
- const signature = await ed.sign(payloadBytes, signerPrivateKey);
319
+ const signature = await signer.sign(payloadBytes);
273
320
  const payloadB64 = base64urlEncode(payloadBytes);
274
321
  const signatureB64 = base64urlEncode(signature);
275
322
  const token = `${payloadB64}.${signatureB64}`;