@me2em/core 0.4.4-alpha.1 → 0.6.0-alpha.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 +299 -766
  2. package/dist/attestation.d.ts +151 -0
  3. package/dist/attestation.d.ts.map +1 -0
  4. package/dist/attestation.js +279 -0
  5. package/dist/attestation.js.map +1 -0
  6. package/dist/canonical-name.d.ts +3 -0
  7. package/dist/canonical-name.d.ts.map +1 -0
  8. package/dist/canonical-name.js +12 -0
  9. package/dist/canonical-name.js.map +1 -0
  10. package/dist/crypto/derivation-paths.d.ts +41 -0
  11. package/dist/crypto/derivation-paths.d.ts.map +1 -0
  12. package/dist/crypto/derivation-paths.js +50 -0
  13. package/dist/crypto/derivation-paths.js.map +1 -0
  14. package/dist/crypto/ed25519.d.ts +52 -0
  15. package/dist/crypto/ed25519.d.ts.map +1 -0
  16. package/dist/crypto/ed25519.js +67 -0
  17. package/dist/crypto/ed25519.js.map +1 -0
  18. package/dist/crypto/hkdf.d.ts +13 -0
  19. package/dist/crypto/hkdf.d.ts.map +1 -0
  20. package/dist/crypto/hkdf.js +17 -0
  21. package/dist/crypto/hkdf.js.map +1 -0
  22. package/dist/crypto/index.d.ts +4 -0
  23. package/dist/crypto/index.d.ts.map +1 -0
  24. package/dist/crypto/index.js +5 -0
  25. package/dist/crypto/index.js.map +1 -0
  26. package/dist/crypto/init.d.ts +9 -0
  27. package/dist/crypto/init.d.ts.map +1 -0
  28. package/dist/crypto/init.js +17 -0
  29. package/dist/crypto/init.js.map +1 -0
  30. package/dist/handle.d.ts +206 -0
  31. package/dist/handle.d.ts.map +1 -0
  32. package/dist/handle.js +258 -0
  33. package/dist/handle.js.map +1 -0
  34. package/dist/identity.d.ts +123 -0
  35. package/dist/identity.d.ts.map +1 -0
  36. package/dist/identity.js +167 -0
  37. package/dist/identity.js.map +1 -0
  38. package/dist/index.d.ts +33 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +33 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/seed.d.ts +83 -0
  43. package/dist/seed.d.ts.map +1 -0
  44. package/dist/seed.js +117 -0
  45. package/dist/seed.js.map +1 -0
  46. package/dist/session.d.ts +231 -0
  47. package/dist/session.d.ts.map +1 -0
  48. package/dist/session.js +454 -0
  49. package/dist/session.js.map +1 -0
  50. package/dist/subhandle.d.ts +126 -0
  51. package/dist/subhandle.d.ts.map +1 -0
  52. package/dist/subhandle.js +158 -0
  53. package/dist/subhandle.js.map +1 -0
  54. package/dist/util.d.ts +9 -0
  55. package/dist/util.d.ts.map +1 -0
  56. package/dist/util.js +34 -0
  57. package/dist/util.js.map +1 -0
  58. package/package.json +36 -12
  59. package/src/attestation.ts +364 -0
  60. package/src/canonical-name.ts +12 -0
  61. package/src/crypto/derivation-paths.ts +56 -0
  62. package/src/crypto/ed25519.ts +86 -0
  63. package/{packages/core/src → src}/crypto/hkdf.ts +2 -0
  64. package/src/crypto/index.ts +4 -0
  65. package/{packages/core/src → src}/crypto/init.ts +1 -0
  66. package/src/handle.ts +320 -0
  67. package/src/identity.ts +218 -0
  68. package/{packages/core/src → src}/index.ts +5 -1
  69. package/{packages/core/src → src}/seed.ts +41 -54
  70. package/src/session.ts +660 -0
  71. package/src/subhandle.ts +230 -0
  72. package/src/util.ts +35 -0
  73. package/.github/workflows/ci.yml +0 -0
  74. package/CODE_OF_CONDUCT.md +0 -73
  75. package/CONTRIBUTING.md +0 -145
  76. package/GOVERNANCE.md +0 -132
  77. package/SECURITY.md +0 -70
  78. package/packages/core/README.md +0 -656
  79. package/packages/core/package.json +0 -44
  80. package/packages/core/src/crypto/ed25519.ts +0 -12
  81. package/packages/core/src/crypto/index.ts +0 -2
  82. package/packages/core/src/handle.ts +0 -130
  83. package/packages/core/src/identity.ts +0 -89
  84. package/packages/core/src/session.ts +0 -47
  85. package/packages/core/test/derivation.spec.ts +0 -117
  86. package/packages/core/tsconfig.json +0 -9
  87. package/pnpm-workspace.yaml +0 -2
  88. package/specs/core.md +0 -44
  89. package/specs/openapi/server-ref.yaml +0 -10
  90. package/specs/test-vectors.json +0 -13
  91. package/tsconfig.base.json +0 -20
  92. package/typedoc.json +0 -18
package/README.md CHANGED
@@ -1,870 +1,403 @@
1
- # 📦 `@me2em/core` — Developer Documentation
1
+ # 📦 `@me2em/core` — Core Cryptographic Primitives
2
2
 
3
- > Core primitives for the Me2em authorization protocol: `Identity`, `Handle`, and `Session` management with Ed25519 cryptography.
3
+ Core primitives for the Me2em authorization protocol: hierarchical
4
+ deterministic identities (`Identity` → `Handle` → `SubHandle`), stateless
5
+ signed sessions, and parent-signed **attestation chains** for delegatable,
6
+ externally verifiable authorization — all on Ed25519.
4
7
 
5
8
  [![npm version](https://img.shields.io/npm/v/@me2em/core.svg)](https://www.npmjs.com/package/@me2em/core)
6
- [![License](https://img.shields.io/npm/l/@me2em/core)](https://github.com/me2em-org/me2em-protocol/blob/main/LICENSE)
9
+ [![License](https://img.shields.io/npm/l/@me2em/core.svg)](https://github.com/me2em/core/blob/main/LICENSE)
7
10
  [![Docs](https://img.shields.io/badge/docs-docs.me2em.com-blue)](https://docs.me2em.com)
8
11
 
9
- ---
12
+ ## 🎯 Overview
10
13
 
11
- ## 🎯 Quick Start
14
+ - **Hierarchical Deterministic Identities** — one seed → isolated
15
+ `Handle`s and `SubHandle`s (MAX_DEPTH = 2), derived offline via HKDF.
16
+ - **Stateless Authentication** — self-contained signed session tokens,
17
+ verified without server-side storage, with optional revocation.
18
+ - **Attestations** — a parent cryptographically binds a child key to a
19
+ name and a grant (audiences, scopes, TTL caps, name patterns). Chains
20
+ are verified **offline by third parties using only the root public
21
+ key** — the root private key never leaves its owner.
22
+ - **Zero-Knowledge Password Management** — deterministic password
23
+ derivation without storage.
24
+ - **Secure Channels** — symmetric channel keys and X25519 shared
25
+ secrets derived without key exchange.
26
+
27
+ ## 📦 Installation
12
28
 
13
29
  ```bash
14
30
  npm install @me2em/core
15
31
  # or
16
32
  pnpm add @me2em/core
17
- # or
18
- yarn add @me2em/core
19
- ```
20
-
21
- ```typescript
22
- import { Identity, Handle } from '@me2em/core';
23
-
24
- // 1. Create or restore identity from seed
25
- const seed = 'your-32-byte-hex-seed-or-24-words';
26
- const identity = await Identity.fromSeed(seed);
27
-
28
- // 2. Derive a contextual handle
29
- const workHandle = await identity.deriveHandle('work', {
30
- displayName: 'Alice @ Work',
31
- avatar: 'https://example.com/avatar.png'
32
- });
33
-
34
- // 3. Use handle for cryptographic operations
35
- const message = new TextEncoder().encode('Hello, world!');
36
- const signature = await workHandle.sign(message);
37
- const isValid = await Handle.verify(signature, message, workHandle.getPublicKey());
38
-
39
- console.log('Handle ID:', workHandle.getId()); // base64url(publicKey)
40
- console.log('Signature valid:', isValid); // true
41
33
  ```
42
34
 
43
- ---
44
-
45
- ## 📚 Table of Contents
46
-
47
- 1. [Core Concepts](#-core-concepts)
48
- 2. [API Reference](#-api-reference)
49
- 3. [Use Cases](#-use-cases)
50
- 4. [Cryptographic Details](#-cryptographic-details)
51
- 5. [Integration Guide](#-integration-guide)
52
- 6. [Security Best Practices](#-security-best-practices)
53
- 7. [Testing](#-testing)
54
- 8. [Contributing](#-contributing)
55
-
56
- ---
57
-
58
- ## 🔑 Core Concepts
59
-
60
- ### Identity — Cryptographic Root
35
+ **Dependencies:** `@noble/curves` (Ed25519/X25519), `@noble/ed25519`,
36
+ `@noble/hashes` (HKDF, SHA-256), `@scure/bip39` (mnemonic handling).
61
37
 
62
- `Identity` represents the root cryptographic identity derived from a seed phrase.
63
-
64
- ```
65
- Seed (32 bytes / 24 words)
66
- │
67
- ▼
68
- ┌─────────────────┐
69
- │ Identity │
70
- │ • Ed25519 key │
71
- │ • Deterministic │
72
- │ • Client-only │
73
- └─────────────────┘
74
- ```
75
-
76
- **Key properties:**
77
- - 🔐 **Never transmitted**: The root private key never leaves the client device
78
- - 🔄 **Deterministic**: Same seed → same Identity → same derived Handles
79
- - 🧩 **Stateless**: No server storage required for cryptographic operations
80
-
81
- ### Handle — Contextual Profile
82
-
83
- `Handle` is a derived Ed25519 keypair representing a specific context (work, personal, IoT device).
84
-
85
- ```
86
- Identity
87
- │
88
- ├─ deriveHandle('work') → Handle(@alice_work)
89
- ├─ deriveHandle('private') → Handle(@alice_private)
90
- └─ deriveHandle('iot-device-001') → Handle(@device_001)
91
- ```
92
-
93
- **Key properties:**
94
- - 🔗 **Cryptographically isolated**: Each Handle has its own keypair; compromise of one does not affect others
95
- - 🏷️ **Public identifier**: `Handle.getId()` returns `base64url(publicKey)` — safe to share
96
- - 📦 **Metadata support**: Attach public metadata (displayName, avatar) without revealing Identity
97
-
98
- ### Session — Scoped Access Token
99
-
100
- `Session` represents a time-limited, scoped authorization token for accessing a specific application.
38
+ ## 🚀 Quick Start
101
39
 
102
40
  ```typescript
103
- interface SessionOptions {
104
- audience: string; // e.g., 'https://api.myapp.com'
105
- scopes: string[]; // e.g., ['read:profile', 'write:messages']
106
- ttl?: number; // seconds until expiration (default: 3600)
107
- }
108
- ```
41
+ import { Identity, Session } from '@me2em/core';
109
42
 
110
- **Key properties:**
111
- - ⏱️ **Short-lived**: Tokens expire automatically; refresh via Handle re-authentication
112
- - 🔐 **Scoped**: Each token grants only specified permissions
113
- - 🌐 **Stateless verification**: Servers verify signatures using Handle public key — no database lookup required
114
-
115
- ---
116
-
117
- ## 📖 API Reference
118
-
119
- ### `Identity` Class
120
-
121
- ```typescript
122
- class Identity {
123
- // Create Identity from seed (32-byte Uint8Array or hex string)
124
- static fromSeed(seed: Uint8Array | string): Promise<Identity>;
125
-
126
- // Derive a new Handle with optional metadata
127
- deriveHandle(name: string, metadata?: HandleMetadata): Promise<Handle>;
128
-
129
- // Get root public key (for verification, never share private key)
130
- getPublicKey(): Uint8Array;
131
- }
132
- ```
133
-
134
- #### `Identity.fromSeed(seed)`
135
-
136
- ```typescript
137
- // From hex string (64 chars = 32 bytes)
138
- const identity = await Identity.fromSeed('a1b2c3...');
139
-
140
- // From Uint8Array
141
- const seedBytes = new Uint8Array(32).fill(42);
142
- const identity = await Identity.fromSeed(seedBytes);
143
- ```
144
-
145
- ⚠️ **Security**: The seed must be kept secret. Never log, transmit, or store it in plaintext.
146
-
147
- #### `Identity.deriveHandle(name, metadata?)`
43
+ // 1. Create an Identity from a 32-byte seed
44
+ const seed = new Uint8Array(32).fill(42); // use a CSPRNG in production
45
+ const identity = await Identity.fromSeed(seed);
148
46
 
149
- ```typescript
150
- const handle = await identity.deriveHandle('work', {
151
- displayName: 'Alice Developer',
152
- avatar: 'https://example.com/alice.png',
153
- org: 'Acme Corp'
47
+ // 2. Derive a contextual Handle
48
+ const station = await identity.deriveHandle('station-001', {
49
+ displayName: 'Station Berlin #001',
154
50
  });
155
- ```
156
-
157
- - `name`: Unique identifier for this Handle within the Identity (case-insensitive, trimmed)
158
- - `metadata`: Arbitrary public data attached to the Handle (visible to servers/other users)
159
-
160
- Returns a `Handle` instance with its own keypair, derived deterministically from the Identity.
161
-
162
- ---
163
51
 
164
- ### `Handle` Class
165
-
166
- ```typescript
167
- class Handle {
168
- // Get public identifier (safe to share)
169
- getId(): string; // base64url-encoded public key
170
-
171
- // Sign arbitrary data with Handle's private key
172
- sign(data: Uint8Array): Promise<Uint8Array>;
173
-
174
- // Verify a signature using a public key (static method)
175
- static verify(signature: Uint8Array, data: Uint8Array, publicKey: Uint8Array): Promise<boolean>;
176
-
177
- // Deterministically derive a password/secret for a specific context
178
- derivePassword(context: string, length?: number): string;
179
-
180
- // Derive a symmetric 256-bit channel key for encrypted communication
181
- deriveChannelKey(context: string): Uint8Array;
182
-
183
- // Accessors
184
- getName(): string;
185
- getMetadata(): HandleMetadata | undefined;
186
- getPublicKey(): Uint8Array;
187
- }
188
- ```
189
-
190
- #### `Handle.getId()`
191
-
192
- Returns a URL-safe base64 string representing the Handle's public key:
193
-
194
- ```typescript
195
- const handleId = handle.getId();
196
- // Example: "pK7xJ2mN8vQ3rL5wY9zB1cD4eF6gH8iJ0kL2mN4oP6qR8sT0uV2wX4yZ6aB8cD0"
197
- ```
198
-
199
- This is the identifier you send to servers for authentication and routing.
200
-
201
- #### `Handle.sign(data)`
202
-
203
- Signs arbitrary binary data using Ed25519:
204
-
205
- ```typescript
206
- const payload = new TextEncoder().encode('{"action":"post","content":"Hello"}');
207
- const signature = await handle.sign(payload);
208
-
209
- // Send to server:
210
- fetch('https://api.example.com/endpoint', {
211
- method: 'POST',
212
- headers: {
213
- 'X-Handle-ID': handle.getId(),
214
- 'Content-Type': 'application/json'
215
- },
216
- body: JSON.stringify({
217
- payload: btoa(String.fromCharCode(...payload)),
218
- signature: btoa(String.fromCharCode(...signature))
219
- })
52
+ // 3. Derive a SubHandle with constraints
53
+ const connector = await station.deriveSubHandle('connector-ccs', {
54
+ allowedAudiences: ['ev-app.com'],
55
+ allowedScopes: ['charge:start', 'charge:stop'],
56
+ maxSessionTtl: 7200,
220
57
  });
221
- ```
222
-
223
- #### `Handle.verify(signature, data, publicKey)`
224
-
225
- Static method for server-side signature verification:
226
-
227
- ```typescript
228
- // Server receives: handleId, signature, payload
229
- const publicKey = Uint8Array.from(atob(handleId), c => c.charCodeAt(0));
230
- const data = Uint8Array.from(atob(payload), c => c.charCodeAt(0));
231
- const sig = Uint8Array.from(atob(signature), c => c.charCodeAt(0));
232
-
233
- const isValid = await Handle.verify(sig, data, publicKey);
234
- if (!isValid) throw new Error('Invalid signature');
235
- ```
236
-
237
- #### `Handle.derivePassword(context, length?)`
238
-
239
- Generates a deterministic, cryptographically strong secret (e.g., a password) for a specific service, without ever exposing the private key.
240
-
241
- ```typescript
242
- // Derive a password for a specific service
243
- const googlePassword = workHandle.derivePassword('google');
244
- // Example output: "xK9mP2qL5wY9zB1cD4eF6g"
245
-
246
- // Derive a longer secret (e.g., 32 bytes for an API key)
247
- const apiKey = workHandle.derivePassword('aws-api', 32);
248
- ```
249
-
250
- ✅ **Security Benefit**: The `privateKey` remains strictly encapsulated within the `Handle` instance. It is used internally by HKDF-SHA256 and is never returned, logged, or serialized.
251
58
 
252
- #### `Handle.deriveChannelKey(context)`
253
-
254
- Derives a symmetric 256-bit key for establishing a secure, encrypted communication channel between the Identity (controller) and this Handle (device/context). Both parties can independently compute this key without any key exchange protocol, because they both have access to the Handle's private key.
255
-
256
- ```typescript
257
- // On the device (Handle side):
258
- const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
259
- // channelKey is a 32-byte Uint8Array, ready for AES-256-GCM
260
-
261
- // On the controller (Identity side):
262
- const droneHandle = await centerIdentity.deriveHandle('drone-001');
263
- const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
264
- // Identical key, derived independently
265
- ```
266
-
267
- ✅ **Security Benefit**: The `privateKey` remains strictly encapsulated within the `Handle` instance. No key exchange protocol (ECDH, etc.) is needed — both parties derive the same key independently from the shared Handle private key.
268
-
269
- ⚠️ **Note**: This method returns raw bytes (Uint8Array), unlike `derivePassword` which returns a base64url string. Use the returned bytes directly with AES-256-GCM via Web Crypto API or similar.
270
-
271
- ---
272
-
273
- ### `Session` Class (Planned)
274
-
275
- > ⚠️ Session management is planned for v0.2. Current implementations should use custom token logic with Handle signatures.
276
-
277
- ```typescript
278
- // Future API (not yet implemented)
279
- const session = await handle.requestSession({
280
- audience: 'https://api.myapp.com',
281
- scopes: ['read:profile', 'write:messages'],
282
- ttl: 3600
59
+ // 4. Create a stateless session (signed by the SubHandle)
60
+ const session = await Session.create(connector, {
61
+ audience: 'ev-app.com',
62
+ scopes: ['charge:start'],
63
+ ttl: 1800,
283
64
  });
284
65
 
285
- // Use token
286
- fetch('https://api.myapp.com/me', {
287
- headers: { Authorization: `Bearer ${session.token}` }
288
- });
66
+ console.log(session.token); // base64url(payload).base64url(signature)
289
67
  ```
290
68
 
291
- ---
292
-
293
- ## 🎯 Use Cases
294
-
295
- ### 1. Multi-Context User Authentication
69
+ ### Integration with BIP39 (recommended)
296
70
 
297
71
  ```typescript
298
- // User logs in with seed
299
- const identity = await Identity.fromSeed(userSeed);
300
-
301
- // Derive work handle
302
- const workHandle = await identity.deriveHandle('work', {
303
- displayName: 'Alice @ Acme',
304
- role: 'engineer'
305
- });
306
-
307
- // Authenticate to work app
308
- const workSig = await workHandle.sign(challenge);
309
- // Send workHandle.getId() + workSig to https://work.acme.com/auth
72
+ import {
73
+ Identity, generateSeedPhrase,
74
+ get32ByteSeedFromMnemonic, validateSeedPhrase,
75
+ } from '@me2em/core';
310
76
 
311
- // Later, derive personal handle for social app
312
- const personalHandle = await identity.deriveHandle('personal', {
313
- displayName: 'Alice',
314
- interests: ['hiking', 'photography']
315
- });
77
+ const phrase = generateSeedPhrase(128); // 12 words (256 → 24 words)
78
+ const check = validateSeedPhrase(phrase);
79
+ if (!check.isValid) throw new Error(check.error);
316
80
 
317
- // Authenticate to social app with different handle
318
- const socialSig = await personalHandle.sign(challenge);
319
- // Send personalHandle.getId() + socialSig to https://social.app/auth
81
+ const seedBytes = await get32ByteSeedFromMnemonic(phrase);
82
+ const identity = await Identity.fromSeed(seedBytes);
320
83
  ```
321
84
 
322
- ✅ **Benefit**: One seed, multiple isolated identities. Apps see only the Handle they interact with.
85
+ > ⚠️ Passphrases (BIP39 "25th word") are not yet supported — see
86
+ > [BACKLOG](./BACKLOG.md) (BL-04). Importing a phrase that was
87
+ > created with a passphrase will silently derive a *different* identity.
323
88
 
324
- ---
89
+ ## 🔗 Attestations (verifiable delegation)
325
90
 
326
- ### 2. IoT Device Hierarchy
91
+ An **attestation** is a parent-signed statement:
327
92
 
328
- ```typescript
329
- // Root identity for device fleet
330
- const fleetIdentity = await Identity.fromSeed(fleetSeed);
331
-
332
- // Derive handle for gateway
333
- const gateway = await fleetIdentity.deriveHandle('gateway-001', {
334
- type: 'gateway',
335
- location: 'warehouse-a'
336
- });
93
+ > "the public key `K` belongs to the name `N` and is valid within grant `G`".
337
94
 
338
- // Derive child handles for sensors (using name prefix for hierarchy)
339
- const sensor1 = await fleetIdentity.deriveHandle('gateway-001/sensor-temp', {
340
- type: 'temperature',
341
- unit: 'celsius'
342
- });
95
+ Chains (`root → handle → subhandle → session`) let **third parties verify
96
+ sessions offline using only the root *public* key** — with grant
97
+ constraints enforced at verification time, not just at creation.
343
98
 
344
- const sensor2 = await fleetIdentity.deriveHandle('gateway-001/sensor-humidity', {
345
- type: 'humidity',
346
- unit: 'percent'
347
- });
99
+ ```text
100
+ Identity ──attestHandle──▶ Handle (e.g. a charging station, issued once)
101
+ │ offline, no Identity, no network:
102
+ ├─ deriveSubHandle('connector-ccs')
103
+ ├─ attestSubHandle('connector-ccs', grant)
104
+ └─ Session.create(subHandle, ...)
105
+ ▼
106
+ third-party verifier: verifyAttested(token, rootPublicKey, [A, B], audience)
348
107
  ```
349
108
 
350
- ✅ **Benefit**: Compromise of `sensor-temp` does not expose `gateway-001` or other sensors. Each device has isolated credentials.
351
-
352
- ---
353
-
354
- ### 3. Anonymous Guest Access
109
+ ### Issuing
355
110
 
356
111
  ```typescript
357
- // Generate ephemeral seed for guest session
358
- const guestSeed = crypto.getRandomValues(new Uint8Array(32));
359
- const guestIdentity = await Identity.fromSeed(guestSeed);
360
-
361
- // Create anonymous handle
362
- const guestHandle = await guestIdentity.deriveHandle('guest', {
363
- displayName: 'Anonymous User',
364
- ephemeral: true
112
+ // Root owner (once per handle lifetime):
113
+ const A = await identity.attestHandle('station-001', {
114
+ audiences: ['ev-app.com'],
115
+ scopes: ['charge:start', 'charge:stop', 'charge:status'],
116
+ maxSessionTtl: 7200,
117
+ subNamePatterns: ['connector-*', 'meter-*'], // wildcard: trailing '*' only
365
118
  });
366
119
 
367
- // Use for limited-scope access
368
- const guestSig = await guestHandle.sign(challenge);
369
- // Send to server with scope: ['read:public-content']
370
- ```
371
-
372
- ✅ **Benefit**: No email, no phone, no tracking. Guest access with cryptographic accountability.
373
-
374
- ---
375
-
376
- ### 4. Cross-App Single Sign-On (SSO)
377
-
378
- ```typescript
379
- // User authenticates once with Identity
380
- const identity = await Identity.fromSeed(seed);
381
-
382
- // App A requests session for 'app-a.example.com'
383
- const handleA = await identity.deriveHandle('app-a', { app: 'example-a' });
384
- const sessionA = { /* custom token logic */ };
385
-
386
- // App B requests session for 'app-b.example.com'
387
- const handleB = await identity.deriveHandle('app-b', { app: 'example-b' });
388
- const sessionB = { /* custom token logic */ };
389
-
390
- // User switches between apps without re-entering seed
391
- // Each app sees only its Handle, not the others
392
- ```
393
-
394
- ✅ **Benefit**: Seamless SSO with privacy isolation — apps cannot correlate user activity across services.
395
-
396
- ---
397
-
398
- ### 5. Deterministic Password Manager (Access Key Keeper)
399
-
400
- Instead of storing passwords in a database, derive them deterministically from the Handle. The user only needs to remember their root Seed and the service name.
401
-
402
- ```typescript
403
- // 1. User restores Identity from Seed (e.g., after entering a PIN)
404
- const identity = await Identity.fromSeed(userSeed);
405
-
406
- // 2. Derive the specific service Handle
407
- const googleHandle = await identity.deriveHandle('google', {
408
- displayName: 'Alice Personal'
120
+ // Handle (autonomous, offline, per subhandle):
121
+ const B = await station.attestSubHandle('connector-ccs', {
122
+ audiences: ['ev-app.com'],
123
+ scopes: ['charge:start', 'charge:stop'],
124
+ maxSessionTtl: 7200,
409
125
  });
410
-
411
- // 3. Deterministically generate the password on the fly
412
- const password = googleHandle.derivePassword('google');
413
-
414
- // 4. Auto-fill the login form
415
- console.log('Login:', 'alice@example.com');
416
- console.log('Password:', password); // Always the same for this seed + handle + context
417
126
  ```
418
127
 
419
- ✅ **Benefit**: Zero-knowledge password management. No database of passwords is required on the server. If a service forces a password change, the user simply derives a new handle (e.g., `'google-v2'`) or adds a version suffix to the context (e.g., `derivePassword('google', 16, 2)`).
420
-
421
- ### 6. IoT Fleet with Encrypted Channels
128
+ The attested public key is always **derived internally** — a parent
129
+ cannot attest a foreign key, and `B.subjectId` always equals the key
130
+ reconstructed via `identity.deriveSubHandle('station-001', 'connector-ccs')`.
422
131
 
423
- Control a fleet of devices (drones, sensors, robots) with zero-knowledge encrypted communication. The control center derives a channel key for each device, and the device independently derives the same key — no key exchange protocol required.
132
+ ### Verifying (on any third-party server)
424
133
 
425
134
  ```typescript
426
- // === CONTROL CENTER (Identity) ===
427
- const centerIdentity = await Identity.fromSeed(centerSeed);
428
-
429
- // Minimal registry: just device names (no public keys stored!)
430
- const allowedDevices = ['drone-001', 'drone-002', 'sensor-warehouse-a'];
431
-
432
- // Receiving telemetry from a drone
433
- async function receiveTelemetry(message: { name: string, signature: Uint8Array, encrypted: Uint8Array }) {
434
- // 1. Check if device is in registry
435
- if (!allowedDevices.includes(message.name)) {
436
- throw new Error('Unknown device');
437
- }
438
-
439
- // 2. Derive the Handle (deterministic, no DB lookup)
440
- const deviceHandle = await centerIdentity.deriveHandle(message.name);
441
-
442
- // 3. Verify signature (proves device owns the private key)
443
- const dataToVerify = concatBytes(
444
- new TextEncoder().encode(message.name),
445
- message.encrypted
135
+ import { Session, AttestationError } from '@me2em/core';
136
+
137
+ try {
138
+ const s = await Session.verifyAttested(
139
+ session.token,
140
+ rootPublicKey, // Uint8Array — public key only
141
+ [A.token, B.token], // chain, root first; length 1 for handle sessions
142
+ 'ev-app.com',
143
+ revocationChecker?, // optional; checks attestation and session jti
446
144
  );
447
- const isValid = await Handle.verify(message.signature, dataToVerify, deviceHandle.getPublicKey());
448
- if (!isValid) throw new Error('Invalid signature');
449
-
450
- // 4. Derive the SAME channel key the device used for encryption
451
- const channelKey = deviceHandle.deriveChannelKey('telemetry-v1');
452
-
453
- // 5. Decrypt the message
454
- const telemetry = await decryptAESGCM(message.encrypted, channelKey);
455
- return telemetry;
456
- }
457
-
458
- // === DRONE (Handle, provisioned at factory) ===
459
- // Drone is provisioned with its Handle's private key and name
460
- async function sendTelemetry(telemetry: object) {
461
- const name = 'drone-001';
462
- const privateKey = /* loaded from secure enclave */;
463
- const droneHandle = new Handle(privateKey, name);
464
-
465
- // 1. Derive the SAME channel key the center will use for decryption
466
- const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
467
-
468
- // 2. Encrypt telemetry
469
- const telemetryBytes = new TextEncoder().encode(JSON.stringify(telemetry));
470
- const encrypted = await encryptAESGCM(telemetryBytes, channelKey);
471
-
472
- // 3. Sign (name + encrypted data)
473
- const dataToSign = concatBytes(new TextEncoder().encode(name), encrypted);
474
- const signature = await droneHandle.sign(dataToSign);
475
-
476
- return { name, signature, encrypted };
145
+ await startCharging(s.path![1]);
146
+ } catch (e) {
147
+ if (e instanceof AttestationError) {
148
+ console.error(e.code, e.level); // e.g. SCOPE_EXCEEDED / SESSION
149
+ }
150
+ throw new Error('Unauthorized');
477
151
  }
478
152
  ```
479
153
 
480
- ✅ **Benefits**:
481
- - **Minimal registry**: Control center stores only device names (strings), not public keys
482
- - **No key exchange**: Both parties derive the same key independently
483
- - **Stateless verification**: Signature check proves device authenticity
484
- - **Isolation**: Compromise of one device doesn't affect others (different Handles → different channel keys)
154
+ ### Error model
155
+
156
+ All failures throw `AttestationError` with `code` and `level`
157
+ (`ROOT | HANDLE_ATTESTATION | SUB_ATTESTATION | SESSION | FORMAT`):
158
+
159
+ | code | levels |
160
+ |---|---|
161
+ | `MALFORMED`, `CHAIN_INCOMPLETE` | FORMAT |
162
+ | `BAD_SIGNATURE` | ROOT, HANDLE_ATTESTATION, SESSION |
163
+ | `EXPIRED`, `NOT_YET_VALID`, `REVOKED` | ROOT, HANDLE_ATTESTATION, SESSION |
164
+ | `PATH_MISMATCH` | ROOT, HANDLE_ATTESTATION, SESSION |
165
+ | `NAME_NOT_PERMITTED`, `SCOPE_EXCEEDED`, `TTL_EXCEEDED` | ROOT |
166
+ | `SCOPE_EXCEEDED`, `TTL_EXCEEDED`, `AUDIENCE_NOT_PERMITTED`, `SESSION_OUTLIVES_ATTESTATION` | SESSION |
167
+ | `SUBJECT_MISMATCH` | ROOT, SUB_ATTESTATION |
168
+
169
+ "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."
170
+
171
+ ### Verification modes
172
+
173
+ The library provides two ways to verify a session token. Both answer the
174
+ same question — *"is this signature valid, unexpired, unrevoked, and what
175
+ does it allow?"* — but they differ in **who is able to verify** and in
176
+ **what is actually enforced**.
177
+
178
+ **Mode 1 — `Session.verifyStateless` (direct verification).**
179
+ The verifier re-derives the signer's public key from the token's
180
+ `hNm`/`hPath` using an `Identity` instance and checks the signature.
181
+ Re-derivation requires the **private root key**, so Mode 1 is only
182
+ available to the key holder itself or to backend infrastructure trusted
183
+ with the root. Scopes, audience, TTL and revocation are checked from the
184
+ token itself — but SubHandle *constraints* (`allowedScopes`,
185
+ `maxSessionTtl`, …) are enforced only at session **creation**. A party
186
+ that has obtained a SubHandle private key can sign a session with any
187
+ scopes and TTL, and Mode 1 verification will accept it.
188
+
189
+ **Mode 2 — `Session.verifyAttested` (attestation-chain verification).**
190
+ The verifier checks the session signature against the key bound by a
191
+ parent-signed attestation, and each attestation against its parent's
192
+ signature, up to the root **public** key. Because every chain link
193
+ carries a signed grant, the verifier **enforces grants at verification
194
+ time**: session scopes must fit the grant, TTL caps and audiences hold,
195
+ and child grants must nest inside parent grants. This makes delegation
196
+ externally verifiable — a partner service verifies sessions with the
197
+ root public key only — and revoking an attestation `jti` disables the
198
+ entire branch: current **and** future sessions under it.
199
+
200
+ **Which mode should I use?**
201
+
202
+ | Situation | Mode |
203
+ |---|---|
204
+ | Verifier is your own trusted backend that already holds the root key | Mode 1 |
205
+ | Verifier is a third party / partner / customer who must not receive the root private key | Mode 2 |
206
+ | You need branch revocation (disable a device, an employee, a sold deal entirely) | Mode 2 |
207
+ | SubHandle constraints must be *enforced*, not just advisory | Mode 2 |
208
+
209
+ | | `Session.verifyStateless` (Mode 1) | `Session.verifyAttested` (Mode 2) |
210
+ |---|---|---|
211
+ | Verifier needs | `Identity` (**private** root) | root **public** key + chain |
212
+ | Trust model | verifier is the root owner | any third party |
213
+ | SubHandle constraints | enforced at creation only | **enforced at verification** |
214
+ | Revoke a handle/branch | per-session `jti` only | revoke attestation `jti` |
215
+ | Use when | closed perimeter, own services | external audiences, delegation, selling access |
216
+
217
+ The modes coexist naturally: internal telemetry verified with Mode 1,
218
+ external access granted via Mode 2 — see
219
+ [USE_CASES.md](./USE_CASES.md) for full production scenarios (EV
220
+ charging, drone fleets, corporate messenger).
485
221
 
486
- ---
487
-
488
- ### 7. Stateless Multi-Device Synchronization
222
+ ## 📖 API Reference
489
223
 
490
- A user with the same Identity on multiple devices (phone, laptop, tablet) can derive identical Handles and secrets on each device without any synchronization protocol.
224
+ ### `Identity`
491
225
 
492
226
  ```typescript
493
- // On the phone:
494
- const identity = await Identity.fromSeed(userSeed);
495
- const messengerHandle = await identity.deriveHandle('messenger-main');
496
- const handleId = messengerHandle.getId();
497
- // Send handleId to server for registration
498
-
499
- // On the laptop (later, no sync needed):
500
- const identity = await Identity.fromSeed(userSeed); // Same seed
501
- const messengerHandle = await identity.deriveHandle('messenger-main'); // Same name
502
- const handleId = messengerHandle.getId(); // Identical handleId!
503
- // Server recognizes the same user automatically
227
+ class Identity {
228
+ static fromSeed(seed: Uint8Array | string): Promise<Identity>; // 32 bytes or 64-char hex
229
+ deriveHandle(name: string, metadata?: HandleMetadata): Promise<Handle>;
230
+ deriveSubHandle(handleName: string, subName: string,
231
+ metadata?: SubHandleMetadata): Promise<SubHandle>; // atomic, for verification
232
+ attestHandle(name: string, grant: AttestationGrant,
233
+ opts?: { ttlSeconds?, expiresAt?, jti?, now? }): Promise<Attestation>;
234
+ getPublicKey(): Uint8Array;
235
+ }
504
236
  ```
505
237
 
506
- ✅ **Benefit**: Zero-knowledge multi-device support. No QR codes, no server-side key sync, no backup servers. The mathematics guarantees identity across devices.
507
-
508
- ---
509
-
510
- ### 8. Break-Glass Recovery and Inheritance
511
-
512
- A user's entire digital identity can be recovered from a single seed phrase, even years later, on any device, without contacting any service provider.
238
+ ### `Handle`
513
239
 
514
240
  ```typescript
515
- // User stores seed phrase in a physical safe (or via Shamir's Secret Sharing with trusted heirs)
516
-
517
- // Years later, on a new device:
518
- const identity = await Identity.fromSeed(recoveredSeed);
519
-
520
- // All handles are instantly recoverable:
521
- const googleHandle = await identity.deriveHandle('google');
522
- const bankHandle = await identity.deriveHandle('bank');
523
- const messengerHandle = await identity.deriveHandle('messenger-main');
524
-
525
- // All passwords are instantly recoverable:
526
- const googlePassword = googleHandle.derivePassword('google');
527
- const bankPassword = bankHandle.derivePassword('bank');
528
-
529
- // All channel keys are instantly recoverable:
530
- const messengerChannelKey = messengerHandle.deriveChannelKey('session-2026');
241
+ class Handle {
242
+ getId(): string; // base64url of the public key
243
+ getName(): string; // canonical (normalized) name
244
+ getMetadata(): HandleMetadata | undefined;
245
+ getPublicKey(): Uint8Array;
246
+ getPath(): string[] | undefined; // undefined for Handle, path for SubHandle
247
+ sign(data: Uint8Array): Promise<Uint8Array>;
248
+ static verify(sig: Uint8Array, data: Uint8Array, pub: Uint8Array): Promise<boolean>;
249
+ derivePassword(context: string, length?: number): string; // base64url secret
250
+ deriveChannelKey(context: string): Uint8Array; // 32-byte AES key
251
+ deriveSharedSecret(otherPublicKey: Uint8Array): Promise<Uint8Array>; // X25519 + HKDF
252
+ deriveSubHandle(name: string, metadata?: SubHandleMetadata): Promise<SubHandle>;
253
+ attestSubHandle(subName: string, grant: AttestationGrant,
254
+ opts?: { ttlSeconds?, expiresAt?, jti?, now? }): Promise<Attestation>;
255
+ validateSessionOptions(options: { audience: string; scopes: string[]; ttl: number }): void;
256
+ }
531
257
  ```
532
258
 
533
- ✅ **Benefit**: True self-sovereignty. No company can lock you out of your identity. Recovery is a mathematical certainty, not a customer support ticket.
534
-
535
- ---
536
-
537
- ### 9. Ephemeral Delegated Access
538
-
539
- Grant time-limited access to a contractor or temporary service by deriving a Handle with a time-bound name.
259
+ ### `SubHandle` (leaf, MAX_DEPTH = 2)
540
260
 
541
261
  ```typescript
542
- // Grant access to contractor until 2026-12-31
543
- const contractorHandle = await identity.deriveHandle('contractor-acme-2026-12-31', {
544
- displayName: 'ACME Corp Contractor',
545
- role: 'auditor',
546
- expiresAt: '2026-12-31T23:59:59Z'
547
- });
548
-
549
- // Share the Handle ID with the contractor's system
550
- // Contractor uses this Handle for authenticated access
551
-
552
- // After expiration:
553
- // - Server rejects requests (checks expiresAt metadata)
554
- // - User simply stops using this Handle
555
- // - No cleanup needed — the Handle is just a name in the derivation tree
556
- ```
557
-
558
- ✅ **Benefit**: Clean delegation without polluting the permanent identity. Expired Handles become inert cryptographic artifacts.
559
-
560
- ## 🔐 Cryptographic Details
561
-
562
- ### Key Derivation Algorithm
563
-
564
- Handles are derived using **HKDF-SHA256** with domain separation:
565
-
566
- ```
567
- HandlePrivateKey = HKDF-SHA256(
568
- inputKeyMaterial = IdentityPrivateKey,
569
- salt = empty,
570
- info = "me2em/handle/v1/" + lowercase(name),
571
- length = 32
572
- )
573
- HandlePublicKey = Ed25519.PublicKey(HandlePrivateKey)
574
- HandleId = Base64Url(HandlePublicKey)
575
- ```
576
-
577
- **Properties:**
578
- - 🔁 **Deterministic**: Same inputs → same output across all implementations
579
- - 🔒 **One-way**: Cannot derive Identity key from Handle key
580
- - 🧩 **Isolated**: Each Handle uses independent Ed25519 keypair
581
-
582
- ### Channel Key Derivation
583
-
584
- Channel keys are derived using **HKDF-SHA256** with the Handle's private key as input key material:
585
-
586
- ```
587
- ChannelKey = HKDF-SHA256(
588
- inputKeyMaterial = HandlePrivateKey,
589
- salt = "me2em/channel/" + lowercase(context),
590
- info = "me2em/channel/v1",
591
- length = 32
592
- )
593
- ```
594
-
595
- **Properties**:
596
- - 🔁 **Deterministic**: Same Handle + same context → same 32-byte key
597
- - 🔐 **Encapsulated**: Private key never leaves the Handle instance
598
- - 🧩 **Domain-separated**: Different contexts produce different keys (e.g., `'telemetry-v1'` vs `'command-v1'`)
599
- - ⚡ **No key exchange**: Both parties derive the key independently, no ECDH needed
600
-
601
- ### Signature Scheme
602
-
603
- - **Algorithm**: Ed25519 (RFC 8032)
604
- - **Hash**: SHA-512 (via `@noble/ed25519`)
605
- - **Encoding**: Raw bytes → base64url for transport
606
-
607
- ### Test Vectors
608
-
609
- See [`specs/test-vectors.json`](../../specs/test-vectors.json) for canonical derivation examples to ensure cross-implementation compatibility.
610
-
611
- Example vector:
612
- ```json
613
- {
614
- "seed_hex": "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a",
615
- "handle_name": "work",
616
- "expected_handle_id": "pK7xJ2mN8vQ3rL5wY9zB1cD4eF6gH8iJ0kL2mN4oP6qR8sT0uV2wX4yZ6aB8cD0",
617
- "expected_public_key_hex": "a4b5c6d7e8f90123456789abcdef0123456789abcdef0123456789abcdef0123"
262
+ class SubHandle extends Handle {
263
+ getPath(): string[]; // ['station-001', 'connector-ccs']
264
+ getPathString(): string; // 'station-001/connector-ccs'
265
+ getDepth(): number; // always 2
266
+ isLeaf(): boolean; // always true
267
+ getSubMetadata(): SubHandleMetadata;
268
+ validateSessionOptions(options: { audience: string; scopes: string[]; ttl: number }): void;
269
+ // deriveSubHandle is overridden and ALWAYS throws (leaf node)
618
270
  }
619
271
  ```
620
272
 
621
- ---
622
-
623
- ## 🔌 Integration Guide
624
-
625
- ### Backend Verification (Node.js Example)
273
+ ### `Session`
626
274
 
627
275
  ```typescript
628
- import { Handle } from '@me2em/core';
629
-
630
- // Middleware to verify Handle-signed requests
631
- export async function me2emAuthMiddleware(req: Request, res: Response, next: NextFunction) {
632
- const handleId = req.headers['x-handle-id'] as string;
633
- const signature = req.headers['x-signature'] as string;
634
- const payload = JSON.stringify(req.body);
276
+ class Session {
277
+ static create(handle: Handle | SubHandle, options: SessionOptions): Promise<Session>;
278
+ static verifyStateless(token: string, companyIdentity: Identity,
279
+ expectedAudience: string,
280
+ revocationChecker?: RevocationChecker): Promise<Session>;
281
+ static verifyAttested(token: string, rootPublicKey: Uint8Array,
282
+ attestationChain: string[], expectedAudience: string,
283
+ revocationChecker?: RevocationChecker): Promise<Session>;
284
+ isExpired(): boolean;
285
+ readonly handleId, handleName, audience, scopes, expiresAt, token, path, sessionId;
286
+ }
635
287
 
636
- if (!handleId || !signature) {
637
- return res.status(401).json({ error: 'Missing authentication headers' });
638
- }
288
+ interface SessionOptions {
289
+ audience: string; scopes: string[]; ttl: number; sessionId?: string;
290
+ }
639
291
 
640
- try {
641
- // Decode base64url to Uint8Array
642
- const publicKey = base64urlToBytes(handleId);
643
- const sig = base64urlToBytes(signature);
644
- const data = new TextEncoder().encode(payload);
645
-
646
- // Verify signature
647
- const isValid = await Handle.verify(sig, data, publicKey);
648
- if (!isValid) throw new Error('Invalid signature');
649
-
650
- // Attach handle info to request for downstream use
651
- req.me2em = { handleId, publicKey };
652
- next();
653
- } catch (err) {
654
- res.status(401).json({ error: 'Authentication failed' });
655
- }
292
+ interface SessionPayload { // signed token contents
293
+ hId: string; hNm: string; hPath?: string[];
294
+ aud: string; scp: string[]; exp: number; iat: number; jti: string;
656
295
  }
657
296
 
658
- function base64urlToBytes(str: string): Uint8Array {
659
- const padding = '='.repeat((4 - (str.length % 4)) % 4);
660
- const base64 = str.replace(/-/g, '+').replace(/_/g, '/') + padding;
661
- return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
297
+ interface RevocationChecker {
298
+ isRevoked(jti: string): Promise<boolean>;
662
299
  }
663
300
  ```
664
301
 
665
- ### Frontend Secure Key Handling
302
+ ### `Attestation`
666
303
 
667
304
  ```typescript
668
- // Store encrypted seed in IndexedDB (never plaintext)
669
- import { encryptWithPin } from './crypto/local';
670
-
671
- async function saveIdentity(seed: string, pin: string) {
672
- const encrypted = await encryptWithPin(seed, pin);
673
- await db.identities.add({
674
- id: 'current',
675
- encryptedSeed: encrypted,
676
- // seed is NEVER stored in plaintext
677
- });
305
+ class Attestation {
306
+ static issue(signerPrivateKey: Uint8Array, subjectPublicKey: Uint8Array,
307
+ subjectName: string, grant: AttestationGrant,
308
+ opts?: { ttlSeconds?, expiresAt?, jti?, now? }): Promise<Attestation>;
309
+ static decode(token: string): AttestationPayload; // structure only — no sig, no time
310
+ static verifySignature(token: string, signerPublicKey: Uint8Array): Promise<boolean>;
311
+ static matchNamePattern(name: string, patterns: string[]): boolean;
312
+ get payload(): AttestationPayload;
313
+ get token(): string;
314
+ get jti(): string;
678
315
  }
679
316
 
680
- // Load and decrypt on login
681
- async function loadIdentity(pin: string) {
682
- const record = await db.identities.get('current');
683
- if (!record) throw new Error('No identity found');
684
-
685
- const seed = await decryptWithPin(record.encryptedSeed, pin);
686
- return Identity.fromSeed(seed);
317
+ interface AttestationGrant {
318
+ audiences?: string[]; // undefined = unrestricted; [] = deny all
319
+ scopes: string[]; // exact strings, no wildcards
320
+ maxSessionTtl: number; // seconds, > 0
321
+ subNamePatterns?: string[]; // root→handle only; trailing '*' only
687
322
  }
688
- ```
689
-
690
- ✅ **Best practice**: Use Web Crypto API or secure enclave for PIN/biometric decryption.
691
-
692
- ---
693
-
694
- ## 🛡️ Security Best Practices
695
-
696
- ### ✅ Do
697
-
698
- - **Store seeds encrypted**: Use PIN/biometric + AES-GCM before persisting to IndexedDB
699
- - **Clear memory**: Zero out seed/private key buffers after use (`buffer.fill(0)`)
700
- - **Use short TTLs**: Rotate session tokens frequently (≤1 hour recommended)
701
- - **Validate metadata server-side**: Never trust client-provided Handle metadata without verification
702
- - **Pin dependencies**: Lock `@me2em/core` to specific version in `package.json`
703
-
704
- ### ❌ Don't
705
-
706
- - **Never transmit seeds**: The seed is the root of trust — keep it client-side only
707
- - **Don't reuse Handles across contexts**: Derive separate Handles for different apps/services
708
- - **Don't log private keys**: Ensure debugging output never includes key material
709
- - **Don't disable signature verification**: Always verify Ed25519 signatures server-side
710
-
711
- ### Key Lifecycle
712
323
 
713
- ```
714
- [User enters seed]
715
- │
716
- ▼
717
- [Derive Identity in RAM]
718
- │
719
- ▼
720
- [Derive Handle(s) as needed]
721
- │
722
- ▼
723
- [Sign challenge / data]
724
- │
725
- ▼
726
- [Zero out private key buffers] ← Critical!
727
- │
728
- ▼
729
- [Keep only public HandleId for future use]
730
- ```
731
-
732
- ---
733
-
734
- ## 🧪 Testing
735
-
736
- ### Unit Tests
737
-
738
- ```bash
739
- cd packages/protocol-core
740
- pnpm test
324
+ class AttestationError extends Error {
325
+ readonly code: AttestationErrorCode;
326
+ readonly level: AttestationLevel;
327
+ }
741
328
  ```
742
329
 
743
- Tests cover:
744
- - ✅ Deterministic derivation (same seed + name → same HandleId)
745
- - ✅ Signature generation and verification
746
- - ✅ Edge cases (empty metadata, long names, unicode)
330
+ ### Name normalization
747
331
 
748
- ### Integration Test Example
332
+ All derivation inputs are canonicalized: `NFKC → lowercase → trim`,
333
+ then validated against `/^[a-z0-9][a-z0-9._@-]{0,62}$/`. Names with `/`,
334
+ non-ASCII letters, or > 64 chars **throw**. Identical inputs always
335
+ produce identical keys across platforms and entry points.
749
336
 
750
- ```typescript
751
- import { Identity } from '@me2em/core';
752
-
753
- test('full auth flow', async () => {
754
- // Client side
755
- const identity = await Identity.fromSeed(testSeed);
756
- const handle = await identity.deriveHandle('test');
757
- const challenge = new TextEncoder().encode('nonce-123');
758
- const signature = await handle.sign(challenge);
759
-
760
- // Server side
761
- const isValid = await Handle.verify(
762
- signature,
763
- challenge,
764
- handle.getPublicKey()
765
- );
766
- expect(isValid).toBe(true);
767
- expect(handle.getId()).toMatch(/^[A-Za-z0-9_-]{43}$/);
768
- });
769
- ```
770
-
771
- ### Cross-Implementation Testing
337
+ ## 🎯 Core Use Cases
772
338
 
773
- Use [`specs/test-vectors.json`](../../specs/test-vectors.json) to verify your implementation matches the reference:
339
+ 1. **Deterministic password manager** — derive secrets per service, store nothing.
340
+ 2. **IoT fleets with encrypted channels** — devices operate fully offline.
341
+ 3. **Stateless multi-device sync** — same seed → same handles everywhere.
342
+ 4. **Delegatable access control** — attestation chains grant scope- and
343
+ time-limited access to components, verifiable by external parties.
774
344
 
775
- ```typescript
776
- import vectors from '@me2em/core/specs/test-vectors.json';
777
-
778
- for (const vector of vectors) {
779
- const identity = await Identity.fromSeed(vector.seed_hex);
780
- const handle = await identity.deriveHandle(vector.handle_name);
781
-
782
- expect(handle.getId()).toBe(vector.expected_handle_id);
783
- expect(bytesToHex(handle.getPublicKey())).toBe(vector.expected_public_key_hex);
784
- }
785
- ```
345
+ 👉 **[USE_CASES.md](./USE_CASES.md)** — EV charging stations, drone fleet
346
+ access marketplace, corporate messenger, and a production Redis
347
+ `RevocationChecker`.
786
348
 
787
- ---
349
+ ## 🔐 Cryptographic Details
788
350
 
789
- ## 🤝 Contributing
351
+ - **Identity:** `Ed25519 key = HKDF-SHA256(seed, salt="", info="me2em/identity/v1/root", 32)`
352
+ - **Handle:** `HKDF-SHA256(identityKey, salt="", info="me2em/handle/v1/{name}", 32)`
353
+ - **SubHandle:** `HKDF-SHA256(handleKey, salt="", info="me2em/subhandle/v1/{handle}/{sub}", 32)`
354
+ - **Signatures:** Ed25519 (RFC 8032); tokens are `base64url(payload).base64url(signature)`
355
+ - **Attestation payload limit:** 2048 bytes; **session payload limit:** 4096 bytes
356
+ - **Clock skew tolerance:** ±30 seconds on all time checks
790
357
 
791
- We welcome contributions! See:
358
+ ## 🛡️ Security Best Practices
792
359
 
793
- - 📄 [CONTRIBUTING.md](../../CONTRIBUTING.md) — How to contribute code/docs
794
- - 🗳️ [GOVERNANCE.md](../../GOVERNANCE.md) — Project decision-making process
795
- - 🔐 [SECURITY.md](../../SECURITY.md) — Responsible disclosure policy
360
+ ✅ **Do**:
361
+ - Store seeds encrypted (PIN/biometric + AES-GCM); keep the root offline
362
+ except for issuance ceremonies.
363
+ - Use short session TTLs (≤ 1 hour recommended).
364
+ - Implement a `RevocationChecker` (e.g., Redis SET) — it is consulted for
365
+ attestation **and** session `jti` in `verifyAttested`.
366
+ - Prefer `verifyAttested` for any external audience; reserve
367
+ `verifyStateless` for infrastructure you fully control.
368
+ - Scope `subNamePatterns` as narrowly as possible — a holder can do
369
+ everything *inside* its wildcard.
370
+
371
+ ❌ **Don't**:
372
+ - Never transmit seeds; keep derivation client-side.
373
+ - Don't reuse Handles across unrelated contexts.
374
+ - Don't log private keys or seed phrases.
375
+ - Don't rely on zeroing buffers as a hard guarantee — GC/JIT may retain
376
+ copies (tracked in [BACKLOG](./BACKLOG.md) BL-07).
796
377
 
797
- ### Quick Start for Contributors
378
+ ## 🧪 Testing
798
379
 
799
380
  ```bash
800
- git clone https://github.com/me2em-org/me2em-protocol.git
801
- cd me2em-protocol
802
- pnpm install
803
-
804
- # Run tests
805
- pnpm -r test
806
-
807
- # Build all packages
808
- pnpm -r build
809
-
810
- # Lint
811
- pnpm -r lint
381
+ cd packages/core && pnpm test
812
382
  ```
813
383
 
814
- ### Adding a New Feature
815
-
816
- 1. Open a [Discussion](https://github.com/me2em-org/me2em-protocol/discussions) to propose the change
817
- 2. Implement in a feature branch
818
- 3. Add tests covering new functionality
819
- 4. Update `specs/core.md` if protocol behavior changes
820
- 5. Submit PR with clear description and test results
821
-
822
- ---
823
-
824
- ## 📦 Package Info
825
-
826
- ```json
827
- {
828
- "name": "@me2em/core",
829
- "version": "0.3.0-alpha.1",
830
- "type": "module",
831
- "main": "./dist/index.js",
832
- "types": "./dist/index.d.ts",
833
- "exports": {
834
- ".": {
835
- "types": "./dist/index.d.ts",
836
- "import": "./dist/index.js",
837
- "require": "./dist/index.cjs"
838
- }
839
- },
840
- "dependencies": {
841
- "@noble/ed25519": "^3.1.0",
842
- "@noble/hashes": "^2.2.0"
843
- },
844
- "engines": {
845
- "node": ">=18.0.0"
846
- }
847
- }
848
- ```
849
-
850
- ---
851
-
852
- ## 🌐 Ecosystem
853
-
854
- This package is part of the Me2em ecosystem:
855
-
856
- @me2em/core ← криптография (Identity, Handle, derivePassword, deriveChannelKey)
857
- @me2em/sdk ← browser wrapper (IndexedDB, PIN, biometric, session management)
858
- @me2em/react ← UI компоненты (SeedDisplay, SeedVerification, HandleManager)
859
- @me2em/auth-middleware ← NestJS/Express middleware для Handle.verify()
860
- @me2em/server ← (опционально) готовый NestJS backend из Phase 1
384
+ 166 tests cover: deterministic derivation and cross-entry-point key
385
+ consistency, name canonicalization, session lifecycle (create, verify,
386
+ tamper, expiry, iat), revocation, SubHandle constraint enforcement,
387
+ MAX_DEPTH leaf enforcement, attestation issue/decode/signature
388
+ determinism and validation, and the full `verifyAttested` chain
389
+ (20+ cases including nesting, wildcard permitting, revocation at every
390
+ level, and signature robustness).
861
391
 
862
- 🔗 Learn more: [github.com/me2em-org](https://github.com/me2em-org) | [docs.me2em.com](https://docs.me2em.com)
392
+ ## 🗺️ Roadmap
863
393
 
864
- ---
394
+ Recommendations for further development — including BIP39 passphrase
395
+ support, revocation lineage (`sid`), key zeroing, and attestation
396
+ reference compression — live in [BACKLOG.md](./BACKLOG.md).
397
+ The backlog is advisory and not part of the shipped API contract.
865
398
 
866
399
  ## 📜 License
867
400
 
868
- Apache License 2.0 — see [LICENSE](../../LICENSE) for details.
401
+ Apache License 2.0 — see [LICENSE](../../LICENSE).
869
402
 
870
- © 2026 Me2em Organization. Built for privacy, openness, and user sovereignty.
403
+ © 2026 Me2em Organization. Built for privacy, openness, and user sovereignty.