@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/README.md CHANGED
@@ -1,13 +1,13 @@
1
- # πŸ“¦ `@me2em/core` β€” Core Cryptographic Primitives
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.
7
7
 
8
8
  [![npm version](https://img.shields.io/npm/v/@me2em/core.svg)](https://www.npmjs.com/package/@me2em/core)
9
- [![License](https://img.shields.io/npm/l/@me2em/core.svg)](https://github.com/me2em/core/blob/main/LICENSE)
10
- [![Docs](https://img.shields.io/badge/docs-docs.me2em.com-blue)](https://docs.me2em.com)
9
+ [![License](https://img.shields.io/npm/l/@me2em/core.svg)](./LICENSE)
10
+ [![Docs](https://img.shields.io/badge/docs-core.me2em.com-blue)](https://core.me2em.com)
11
11
 
12
12
  ## 🎯 Overview
13
13
 
@@ -23,6 +23,43 @@ externally verifiable authorization β€” all on Ed25519.
23
23
  derivation without storage.
24
24
  - **Secure Channels** β€” symmetric channel keys and X25519 shared
25
25
  secrets derived without key exchange.
26
+ - **BIP39 Passphrase** β€” optional "25th word" support: the
27
+ passphrase silently derives a different identity if changed.
28
+ - **UKS-Safe ECDH** β€” `deriveSharedSecret` binds both peers'
29
+ public keys into the KDF (`p2p-channel/v2`), preventing
30
+ unknown key-share attacks.
31
+
32
+ ---
33
+
34
+ ## πŸ“– Terminology
35
+
36
+ Protocol terms are **domain-neutral** β€” each use case assigns them
37
+ its own meaning. The five terms most relevant to this package:
38
+
39
+ | Term | Definition |
40
+ |------|------------|
41
+ | **Identity** | Root cryptographic identity derived from a seed phrase. Constant forever. |
42
+ | **Handle** | A derived, attested, named key representing a distinct identity context. |
43
+ | **SubHandle** | A leaf child of a Handle (MAX_DEPTH = 2). |
44
+ | **Attestation** | A parent-signed statement binding a child key to a name and a grant. |
45
+ | **Session** | A stateless signed authorization token. |
46
+
47
+ **Domain interpretations** β€” the same primitives, read through
48
+ different lenses:
49
+
50
+ | Use case | Handle is… | SubHandle is… |
51
+ |----------|------------|----------------|
52
+ | **AI Agent Delegation** (UC-1) | An AI agent acting on behalf of a user | β€” (the agent signs sessions directly) |
53
+ | **IoT Device Hierarchy** (UC-2) | A physical device | A component of that device |
54
+ | **Multi-Context Identity** (UC-3) | A user persona (work, personal) | Delegated access within a persona |
55
+ | **Multi-App SSO** (UC-4) | A per-app persona of the user | β€” |
56
+ | **Deterministic Password Manager** (UC-5) | A service context | β€” |
57
+ | **E2EE Messaging** (UC-6) | The user's messaging identity | An optional device identity |
58
+
59
+ Full glossary (including Channel and material-class terms):
60
+ see the root [GLOSSARY.md](../../GLOSSARY.md).
61
+
62
+ ---
26
63
 
27
64
  ## πŸ“¦ Installation
28
65
 
@@ -35,13 +72,20 @@ pnpm add @me2em/core
35
72
  **Dependencies:** `@noble/curves` (Ed25519/X25519), `@noble/ed25519`,
36
73
  `@noble/hashes` (HKDF, SHA-256), `@scure/bip39` (mnemonic handling).
37
74
 
75
+ > πŸ’‘ This package is self-contained. For E2EE channels, X3DH key
76
+ > agreement, and Argon2id use [`@me2em/crypto`](../crypto/README.md).
77
+ > For React hooks and seed phrase UX components use
78
+ > [`@me2em/react`](../react/README.md). The three packages are
79
+ > designed to work together β€” see the root
80
+ > [README](../../README.md) for the full package map.
81
+
38
82
  ## πŸš€ Quick Start
39
83
 
40
84
  ```typescript
41
85
  import { Identity, Session } from '@me2em/core';
42
86
 
43
- // 1. Create an Identity from a 32-byte seed
44
- 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
45
89
  const identity = await Identity.fromSeed(seed);
46
90
 
47
91
  // 2. Derive a contextual Handle
@@ -71,19 +115,19 @@ console.log(session.token); // base64url(payload).base64url(signature)
71
115
  ```typescript
72
116
  import {
73
117
  Identity, generateSeedPhrase,
74
- get32ByteSeedFromMnemonic, validateSeedPhrase,
118
+ get64ByteSeedFromMnemonic, validateSeedPhrase,
75
119
  } from '@me2em/core';
76
120
 
77
121
  const phrase = generateSeedPhrase(128); // 12 words (256 β†’ 24 words)
78
122
  const check = validateSeedPhrase(phrase);
79
123
  if (!check.isValid) throw new Error(check.error);
80
124
 
81
- const seedBytes = await get32ByteSeedFromMnemonic(phrase);
125
+ const seedBytes = await get64ByteSeedFromMnemonic(phrase); // full 64-byte BIP39 seed
82
126
  const identity = await Identity.fromSeed(seedBytes);
83
127
  ```
84
128
 
85
129
  > ⚠️ Passphrases (BIP39 "25th word") ARE supported:
86
- > `get32ByteSeedFromMnemonic(words, passphrase)`. The passphrase is
130
+ > `get64ByteSeedFromMnemonic(words, passphrase)`. The passphrase is
87
131
  > case-sensitive, not recoverable, and silently derives a different
88
132
  > identity if mistyped. Store it with the same care as the words.
89
133
 
@@ -155,19 +199,25 @@ try {
155
199
  ### Error model
156
200
 
157
201
  All failures throw `AttestationError` with `code` and `level`
158
- (`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:
159
205
 
160
206
  | code | levels |
161
207
  |---|---|
162
- | `MALFORMED`, `CHAIN_INCOMPLETE` | FORMAT |
208
+ | `MALFORMED`, `CHAIN_INCOMPLETE`, `MAX_DEPTH_EXCEEDED`, `DISPOSED` | FORMAT |
163
209
  | `BAD_SIGNATURE` | ROOT, HANDLE_ATTESTATION, SESSION |
164
210
  | `EXPIRED`, `NOT_YET_VALID`, `REVOKED` | ROOT, HANDLE_ATTESTATION, SESSION |
165
211
  | `PATH_MISMATCH` | ROOT, HANDLE_ATTESTATION, SESSION |
166
- | `NAME_NOT_PERMITTED`, `SCOPE_EXCEEDED`, `TTL_EXCEEDED` | ROOT |
212
+ | `NAME_NOT_PERMITTED`, `SCOPE_EXCEEDED`, `TTL_EXCEEDED` | ROOT, SESSION |
167
213
  | `SCOPE_EXCEEDED`, `TTL_EXCEEDED`, `AUDIENCE_NOT_PERMITTED`, `SESSION_OUTLIVES_ATTESTATION` | SESSION |
168
- | `SUBJECT_MISMATCH` | ROOT, SUB_ATTESTATION |
214
+ | `SUBJECT_MISMATCH` | ROOT, SUB_ATTESTATION, SESSION |
169
215
 
170
- "Note on error types. Failures detected during token parsing β€” wrongshape, invalid Base64URL, payload over 4096 bytes, non-JSON payload,missing required fields β€” throw a plain Error, before any attestationlayer is consulted. Every failure after parsing throwsAttestationError. 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.
171
221
 
172
222
  ### Verification modes
173
223
 
@@ -217,8 +267,7 @@ entire branch: current **and** future sessions under it.
217
267
 
218
268
  The modes coexist naturally: internal telemetry verified with Mode 1,
219
269
  external access granted via Mode 2 β€” see
220
- [USE_CASES.md](./USE_CASES.md) for full production scenarios (EV
221
- charging, drone fleets, corporate messenger).
270
+ [USE_CASES.md](./USE_CASES.md) for all nine production scenarios.
222
271
 
223
272
  ## πŸ“– API Reference
224
273
 
@@ -226,13 +275,15 @@ charging, drone fleets, corporate messenger).
226
275
 
227
276
  ```typescript
228
277
  class Identity {
229
- 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
230
279
  deriveHandle(name: string, metadata?: HandleMetadata): Promise<Handle>;
231
280
  deriveSubHandle(handleName: string, subName: string,
232
281
  metadata?: SubHandleMetadata): Promise<SubHandle>; // atomic, for verification
282
+ sign(data: Uint8Array): Promise<Uint8Array>; // implements Signer (root key)
233
283
  attestHandle(name: string, grant: AttestationGrant,
234
284
  opts?: { ttlSeconds?, expiresAt?, jti?, now? }): Promise<Attestation>;
235
285
  getPublicKey(): Uint8Array;
286
+ dispose(): void; // zeroize key; capability methods throw DisposedError
236
287
  }
237
288
  ```
238
289
 
@@ -242,18 +293,19 @@ class Identity {
242
293
  class Handle {
243
294
  getId(): string; // base64url of the public key
244
295
  getName(): string; // canonical (normalized) name
245
- getMetadata(): HandleMetadata | undefined;
246
- getPublicKey(): Uint8Array;
296
+ getMetadata(): HandleMetadata | undefined; // defensive copy
297
+ getPublicKey(): Uint8Array; // defensive copy
247
298
  getPath(): string[] | undefined; // undefined for Handle, path for SubHandle
248
299
  sign(data: Uint8Array): Promise<Uint8Array>;
249
300
  static verify(sig: Uint8Array, data: Uint8Array, pub: Uint8Array): Promise<boolean>;
250
- derivePassword(context: string, length?: number): string; // base64url secret
251
- 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
252
303
  deriveSharedSecret(otherPublicKey: Uint8Array): Promise<Uint8Array>; // X25519 + HKDF
253
304
  deriveSubHandle(name: string, metadata?: SubHandleMetadata): Promise<SubHandle>;
254
305
  attestSubHandle(subName: string, grant: AttestationGrant,
255
306
  opts?: { ttlSeconds?, expiresAt?, jti?, now? }): Promise<Attestation>;
256
307
  validateSessionOptions(options: { audience: string; scopes: string[]; ttl: number }): void;
308
+ dispose(): void; // zeroize key; capability methods throw DisposedError
257
309
  }
258
310
  ```
259
311
 
@@ -261,16 +313,37 @@ class Handle {
261
313
 
262
314
  ```typescript
263
315
  class SubHandle extends Handle {
264
- getPath(): string[]; // ['station-001', 'connector-ccs']
316
+ getPath(): string[]; // ['station-001', 'connector-ccs'] β€” a copy
265
317
  getPathString(): string; // 'station-001/connector-ccs'
266
318
  getDepth(): number; // always 2
267
319
  isLeaf(): boolean; // always true
268
- getSubMetadata(): SubHandleMetadata;
320
+ getSubMetadata(): SubHandleMetadata; // defensive copy of constraints
269
321
  validateSessionOptions(options: { audience: string; scopes: string[]; ttl: number }): void;
270
322
  // deriveSubHandle is overridden and ALWAYS throws (leaf node)
271
323
  }
272
324
  ```
273
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
+
274
347
  ### `Session`
275
348
 
276
349
  ```typescript
@@ -304,7 +377,7 @@ interface RevocationChecker {
304
377
 
305
378
  ```typescript
306
379
  class Attestation {
307
- static issue(signerPrivateKey: Uint8Array, subjectPublicKey: Uint8Array,
380
+ static issue(signer: Signer, subjectPublicKey: Uint8Array,
308
381
  subjectName: string, grant: AttestationGrant,
309
382
  opts?: { ttlSeconds?, expiresAt?, jti?, now? }): Promise<Attestation>;
310
383
  static decode(token: string): AttestationPayload; // structure only β€” no sig, no time
@@ -315,6 +388,13 @@ class Attestation {
315
388
  get jti(): string;
316
389
  }
317
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
+
318
398
  interface AttestationGrant {
319
399
  audiences?: string[]; // undefined = unrestricted; [] = deny all
320
400
  scopes: string[]; // exact strings, no wildcards
@@ -330,22 +410,68 @@ class AttestationError extends Error {
330
410
 
331
411
  ### Name normalization
332
412
 
333
- All derivation inputs are canonicalized: `NFKC β†’ lowercase β†’ trim`,
334
- then validated against `/^[a-z0-9][a-z0-9._@-]{0,62}$/`. Names with `/`,
335
- non-ASCII letters, or > 64 chars **throw**. Identical inputs always
336
- 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.
337
460
 
338
461
  ## 🎯 Core Use Cases
339
462
 
340
- 1. **Deterministic password manager** β€” derive secrets per service, store nothing.
341
- 2. **IoT fleets with encrypted channels** β€” devices operate fully offline.
342
- 3. **Stateless multi-device sync** β€” same seed β†’ same handles everywhere.
343
- 4. **Delegatable access control** β€” attestation chains grant scope- and
344
- time-limited access to components, verifiable by external parties.
463
+ Mapped to the official registry β€” see [USE_CASES.md](./USE_CASES.md):
464
+
465
+ - **UC-5 β€” Deterministic password manager** β€” derive secrets per service, store nothing.
466
+ - **UC-2 β€” IoT fleets with encrypted channels** β€” devices operate fully offline.
467
+ - **Stateless multi-device sync** β€” same seed β†’ same handles everywhere (spans UC-3/UC-4).
468
+ - **UC-1 / UC-2 β€” Delegatable access control** β€” attestation chains grant scope- and
469
+ time-limited access, verifiable by external parties.
345
470
 
346
- πŸ‘‰ **[USE_CASES.md](./USE_CASES.md)** β€” EV charging stations, drone fleet
347
- access marketplace, corporate messenger, and a production Redis
348
- `RevocationChecker`.
471
+ πŸ‘‰ **[USE_CASES.md](./USE_CASES.md)** β€” nine scenarios: AI agents, satellite capacity
472
+ marketplace, drone fleet management, multi-app SSO, multi-context identity, EV
473
+ charging, corporate messenger, password manager, E2EE messenger β€” plus a production
474
+ Redis `RevocationChecker`.
349
475
 
350
476
  ## πŸ” Cryptographic Details
351
477
 
@@ -355,6 +481,67 @@ access marketplace, corporate messenger, and a production Redis
355
481
  - **Signatures:** Ed25519 (RFC 8032); tokens are `base64url(payload).base64url(signature)`
356
482
  - **Attestation payload limit:** 2048 bytes; **session payload limit:** 4096 bytes
357
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).
358
545
 
359
546
  ## πŸ›‘οΈ Security Best Practices
360
547
 
@@ -374,7 +561,7 @@ access marketplace, corporate messenger, and a production Redis
374
561
  - Don't reuse Handles across unrelated contexts.
375
562
  - Don't log private keys or seed phrases.
376
563
  - Don't rely on zeroing buffers as a hard guarantee β€” GC/JIT may retain
377
- copies (tracked in [BACKLOG](./BACKLOG.md) BL-07).
564
+ copies (tracked in [BACKLOG](../../BACKLOG.md) BL-07).
378
565
 
379
566
  ## πŸ§ͺ Testing
380
567
 
@@ -382,23 +569,31 @@ access marketplace, corporate messenger, and a production Redis
382
569
  cd packages/core && pnpm test
383
570
  ```
384
571
 
385
- 166 tests cover: deterministic derivation and cross-entry-point key
386
- 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,
387
575
  tamper, expiry, iat), revocation, SubHandle constraint enforcement,
388
576
  MAX_DEPTH leaf enforcement, attestation issue/decode/signature
389
- determinism and validation, and the full `verifyAttested` chain
390
- (20+ cases including nesting, wildcard permitting, revocation at every
391
- level, and signature robustness).
577
+ determinism and validation, the full `verifyAttested` chain
578
+ (28 cases including nesting, wildcard permitting, revocation at every
579
+ level, signature robustness, BIP39 passphrase derivation, and wordlist
580
+ validation), module-structure and crypto-boundary pins, and parser fuzz
581
+ (~1 050 rounds).
392
582
 
393
583
  ## πŸ—ΊοΈ Roadmap
394
584
 
395
- Recommendations for further development β€” including BIP39 passphrase
396
- support, revocation lineage (`sid`), key zeroing, and attestation
397
- reference compression β€” live in [BACKLOG.md](./BACKLOG.md).
398
- The backlog is advisory and not part of the shipped API contract.
585
+ Passphrase support and `dispose()` zeroization have shipped. Remaining
586
+ recommendations β€” session lineage (`sid`), zeroization hardening
587
+ (BL-07), attestation reference compression,
588
+ and the full package strategy (`@me2em/crypto`, `@me2em/messenger`,
589
+ `@me2em/iot`) β€” live in [BACKLOG.md](../../BACKLOG.md). The backlog is
590
+ advisory and not part of the shipped API contract.
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.
399
594
 
400
595
  ## πŸ“œ License
401
596
 
402
597
  Apache License 2.0 β€” see [LICENSE](../../LICENSE).
403
598
 
404
- Β© 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,gB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