@me2em/core 0.4.2-alpha.1 → 0.4.4-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 (65) hide show
  1. package/.github/workflows/ci.yml +0 -0
  2. package/CODE_OF_CONDUCT.md +73 -0
  3. package/CONTRIBUTING.md +145 -0
  4. package/GOVERNANCE.md +132 -0
  5. package/README.md +374 -189
  6. package/SECURITY.md +70 -0
  7. package/package.json +12 -36
  8. package/packages/core/README.md +656 -0
  9. package/packages/core/package.json +44 -0
  10. package/{src → packages/core/src}/crypto/ed25519.ts +4 -0
  11. package/{src → packages/core/src}/handle.ts +42 -6
  12. package/{src → packages/core/src}/identity.ts +33 -0
  13. package/packages/core/src/index.ts +35 -0
  14. package/packages/core/src/seed.ts +138 -0
  15. package/packages/core/src/session.ts +47 -0
  16. package/packages/core/test/derivation.spec.ts +117 -0
  17. package/packages/core/tsconfig.json +9 -0
  18. package/pnpm-workspace.yaml +2 -0
  19. package/specs/core.md +44 -0
  20. package/specs/openapi/server-ref.yaml +10 -0
  21. package/specs/test-vectors.json +13 -0
  22. package/tsconfig.base.json +20 -0
  23. package/typedoc.json +18 -0
  24. package/dist/crypto/ed25519.d.ts +0 -8
  25. package/dist/crypto/ed25519.d.ts.map +0 -1
  26. package/dist/crypto/ed25519.js +0 -8
  27. package/dist/crypto/ed25519.js.map +0 -1
  28. package/dist/crypto/hkdf.d.ts +0 -13
  29. package/dist/crypto/hkdf.d.ts.map +0 -1
  30. package/dist/crypto/hkdf.js +0 -16
  31. package/dist/crypto/hkdf.js.map +0 -1
  32. package/dist/crypto/index.d.ts +0 -3
  33. package/dist/crypto/index.d.ts.map +0 -1
  34. package/dist/crypto/index.js +0 -3
  35. package/dist/crypto/index.js.map +0 -1
  36. package/dist/crypto/init.d.ts +0 -9
  37. package/dist/crypto/init.d.ts.map +0 -1
  38. package/dist/crypto/init.js +0 -16
  39. package/dist/crypto/init.js.map +0 -1
  40. package/dist/handle.d.ts +0 -53
  41. package/dist/handle.d.ts.map +0 -1
  42. package/dist/handle.js +0 -79
  43. package/dist/handle.js.map +0 -1
  44. package/dist/identity.d.ts +0 -10
  45. package/dist/identity.d.ts.map +0 -1
  46. package/dist/identity.js +0 -38
  47. package/dist/identity.js.map +0 -1
  48. package/dist/index.d.ts +0 -7
  49. package/dist/index.d.ts.map +0 -1
  50. package/dist/index.js +0 -8
  51. package/dist/index.js.map +0 -1
  52. package/dist/seed.d.ts +0 -24
  53. package/dist/seed.d.ts.map +0 -1
  54. package/dist/seed.js +0 -55
  55. package/dist/seed.js.map +0 -1
  56. package/dist/session.d.ts +0 -20
  57. package/dist/session.d.ts.map +0 -1
  58. package/dist/session.js +0 -16
  59. package/dist/session.js.map +0 -1
  60. package/src/index.ts +0 -15
  61. package/src/seed.ts +0 -65
  62. package/src/session.ts +0 -25
  63. /package/{src → packages/core/src}/crypto/hkdf.ts +0 -0
  64. /package/{src → packages/core/src}/crypto/index.ts +0 -0
  65. /package/{src → packages/core/src}/crypto/init.ts +0 -0
@@ -0,0 +1,656 @@
1
+ # 📦 `@me2em/core` — Core Cryptographic Primitives
2
+
3
+ > Core primitives for the Me2em authorization protocol: `Identity`, `Handle`, and secure channel derivation with Ed25519 cryptography.
4
+
5
+ [![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.svg)](https://github.com/me2em-org/me2em-protocol/blob/main/LICENSE)
7
+ [![Docs](https://img.shields.io/badge/docs-docs.me2em.com-blue)](https://docs.me2em.com)
8
+
9
+ ---
10
+
11
+ ## 🎯 Overview
12
+
13
+ `@me2em/core` provides the cryptographic foundation for the Me2em protocol — a decentralized multi-context identity system. It enables:
14
+
15
+ - **Hierarchical Deterministic Identities**: One seed → multiple isolated Handles
16
+ - **Zero-Knowledge Password Management**: Deterministic password derivation without storage
17
+ - **Secure Channel Communication**: Encrypted channels between Identity and Handles without key exchange
18
+ - **Stateless Authentication**: Cryptographic proof without server-side session storage
19
+
20
+ ---
21
+
22
+ ## 📦 Installation
23
+
24
+ ```bash
25
+ npm install @me2em/core
26
+ # or
27
+ pnpm add @me2em/core
28
+ # or
29
+ yarn add @me2em/core
30
+ ```
31
+
32
+ **Dependencies:**
33
+ - `@noble/ed25519` — Ed25519 signatures
34
+ - `@noble/hashes` — HKDF, SHA-256
35
+
36
+ ---
37
+
38
+ ## 🚀 Quick Start
39
+
40
+ ### Basic Usage
41
+
42
+ ```typescript
43
+ import { Identity, Handle } from '@me2em/core';
44
+
45
+ // 1. Create Identity from seed (32 bytes)
46
+ const seed = new Uint8Array(32).fill(42); // Replace with your secure seed
47
+ const identity = await Identity.fromSeed(seed);
48
+
49
+ // 2. Derive a contextual Handle
50
+ const workHandle = await identity.deriveHandle('work', {
51
+ displayName: 'Alice @ Work',
52
+ avatar: 'https://example.com/avatar.png'
53
+ });
54
+
55
+ // 3. Use Handle for cryptographic operations
56
+ const message = new TextEncoder().encode('Hello, world!');
57
+ const signature = await workHandle.sign(message);
58
+ const isValid = await Handle.verify(signature, message, workHandle.getPublicKey());
59
+
60
+ console.log('Handle ID:', workHandle.getId()); // base64url(publicKey)
61
+ console.log('Signature valid:', isValid); // true
62
+ ```
63
+
64
+ ### Integration with BIP39 (Recommended)
65
+
66
+ For production applications, use BIP39 mnemonic phrases. `@me2em/core` provides built-in utilities to handle generation, validation, and conversion to the required 32-byte Ed25519 seed.
67
+
68
+ ```typescript
69
+ import {
70
+ Identity,
71
+ generateSeedPhrase,
72
+ get32ByteSeedFromMnemonic,
73
+ validateSeedPhrase
74
+ } from '@me2em/core';
75
+
76
+ // 1. Generate a 12-word phrase (use 256 for 24 words)
77
+ const phrase = generateSeedPhrase(128);
78
+ console.log('Your seed:', phrase.join(' '));
79
+
80
+ // 2. (Optional) Validate a user-provided phrase
81
+ const validation = validateSeedPhrase(phrase);
82
+ if (!validation.isValid) throw new Error(validation.error);
83
+
84
+ // 3. Convert to 32-byte seed and create Identity
85
+ const seedBytes = await get32ByteSeedFromMnemonic(phrase);
86
+ const identity = await Identity.fromSeed(seedBytes);
87
+ ```
88
+
89
+ **Why is this better?**
90
+ BIP39 produces a 64-byte seed, but Ed25519 requires exactly 32 bytes. The `get32ByteSeedFromMnemonic` utility handles the SHA-256 hashing deterministically and safely, so you don't have to write boilerplate crypto code.
91
+
92
+
93
+ ---
94
+
95
+ ## 📖 API Reference
96
+
97
+ ### `Identity` Class
98
+
99
+ The root cryptographic identity, derived from a seed phrase.
100
+
101
+ ```typescript
102
+ class Identity {
103
+ // Create Identity from seed (32-byte Uint8Array)
104
+ static fromSeed(seed: Uint8Array): Promise<Identity>;
105
+
106
+ // Derive a new Handle with optional metadata
107
+ deriveHandle(name: string, metadata?: HandleMetadata): Promise<Handle>;
108
+
109
+ // Get root public key (for verification, never share private key)
110
+ getPublicKey(): Uint8Array;
111
+ }
112
+ ```
113
+
114
+ #### `Identity.fromSeed(seed)`
115
+
116
+ Creates an Identity from a 32-byte seed.
117
+
118
+ ```typescript
119
+ const seed = new Uint8Array(32);
120
+ crypto.getRandomValues(seed); // Generate secure random seed
121
+ const identity = await Identity.fromSeed(seed);
122
+ ```
123
+
124
+ **Security:** The seed must be kept secret. Never log, transmit, or store it in plaintext.
125
+
126
+ #### `Identity.deriveHandle(name, metadata?)`
127
+
128
+ Derives a new Handle deterministically from the Identity.
129
+
130
+ ```typescript
131
+ const handle = await identity.deriveHandle('google', {
132
+ displayName: 'Alice Personal',
133
+ avatar: 'https://example.com/alice.png'
134
+ });
135
+ ```
136
+
137
+ **Parameters:**
138
+ - `name`: Unique identifier for this Handle (case-insensitive, trimmed)
139
+ - `metadata`: Optional public data attached to the Handle
140
+
141
+ **Returns:** A `Handle` instance with its own keypair, derived deterministically from the Identity.
142
+
143
+ **Key Properties:**
144
+ - 🔁 **Deterministic**: Same seed + same name → same Handle (always)
145
+ - 🔗 **Isolated**: Each Handle has its own keypair; compromise of one does not affect others
146
+ - 🔒 **One-way**: Cannot derive Identity key from Handle key
147
+
148
+ ---
149
+
150
+ ### Seed Utilities
151
+
152
+ Built-in helpers for human-friendly key generation and validation.
153
+
154
+ ```typescript
155
+ // Generate a new phrase (128 bits = 12 words, 256 bits = 24 words)
156
+ function generateSeedPhrase(strength: 128 | 256 = 128): string[];
157
+
158
+ // Normalize input (handles extra spaces, lowercase)
159
+ function normalizeSeedPhrase(input: string | string[]): string[];
160
+
161
+ // Validate word count, wordlist, and BIP39 checksum
162
+ function validateSeedPhrase(words: string[]): { isValid: boolean; error?: string };
163
+
164
+ // Convert validated mnemonic to a secure 32-byte Uint8Array for Ed25519
165
+ async function get32ByteSeedFromMnemonic(phrase: string | string[]): Promise<Uint8Array>;
166
+ ```
167
+
168
+ ✅ **Benefit**: Developers don't need to manually manage `@scure/bip39` imports or remember to hash the 64-byte output. Everything is handled securely within the protocol.
169
+
170
+ ---
171
+
172
+ ### `Handle` Class
173
+
174
+ A derived Ed25519 keypair representing a specific context (work, personal, IoT device).
175
+
176
+ ```typescript
177
+ class Handle {
178
+ // Get public identifier (safe to share)
179
+ getId(): string; // base64url-encoded public key
180
+
181
+ // Sign arbitrary data with Handle's private key
182
+ sign(data: Uint8Array): Promise<Uint8Array>;
183
+
184
+ // Verify a signature using a public key (static method)
185
+ static verify(signature: Uint8Array, data: Uint8Array, publicKey: Uint8Array): Promise<boolean>;
186
+
187
+ // Deterministically derive a password/secret for a specific context
188
+ derivePassword(context: string, length?: number): string;
189
+
190
+ // Derive a symmetric channel key for encrypted communication
191
+ deriveChannelKey(context: string): Uint8Array;
192
+
193
+ // Accessors
194
+ getName(): string;
195
+ getMetadata(): HandleMetadata | undefined;
196
+ getPublicKey(): Uint8Array;
197
+ }
198
+ ```
199
+
200
+ #### `Handle.getId()`
201
+
202
+ Returns a URL-safe base64 string representing the Handle's public key:
203
+
204
+ ```typescript
205
+ const handleId = handle.getId();
206
+ // Example: "pK7xJ2mN8vQ3rL5wY9zB1cD4eF6gH8iJ0kL2mN4oP6qR8sT0uV2wX4yZ6aB8cD0"
207
+ ```
208
+
209
+ This is the identifier you send to servers for authentication and routing.
210
+
211
+ #### `Handle.sign(data)`
212
+
213
+ Signs arbitrary binary data using Ed25519:
214
+
215
+ ```typescript
216
+ const payload = new TextEncoder().encode('{"action":"post","content":"Hello"}');
217
+ const signature = await handle.sign(payload);
218
+
219
+ // Send to server:
220
+ fetch('https://api.example.com/endpoint', {
221
+ method: 'POST',
222
+ headers: {
223
+ 'X-Handle-ID': handle.getId(),
224
+ 'Content-Type': 'application/json'
225
+ },
226
+ body: JSON.stringify({
227
+ payload: btoa(String.fromCharCode(...payload)),
228
+ signature: btoa(String.fromCharCode(...signature))
229
+ })
230
+ });
231
+ ```
232
+
233
+ #### `Handle.verify(signature, data, publicKey)`
234
+
235
+ Static method for server-side signature verification:
236
+
237
+ ```typescript
238
+ // Server receives: handleId, signature, payload
239
+ const publicKey = Uint8Array.from(atob(handleId), c => c.charCodeAt(0));
240
+ const data = Uint8Array.from(atob(payload), c => c.charCodeAt(0));
241
+ const sig = Uint8Array.from(atob(signature), c => c.charCodeAt(0));
242
+
243
+ const isValid = await Handle.verify(sig, data, publicKey);
244
+ if (!isValid) throw new Error('Invalid signature');
245
+ ```
246
+
247
+ #### `Handle.derivePassword(context, length?)`
248
+
249
+ Deterministically derives a secret (e.g., a password or API key) for a specific service context. The private key **never leaves this class**, ensuring maximum security.
250
+
251
+ ```typescript
252
+ // Derive a password for a specific service
253
+ const googlePassword = workHandle.derivePassword('google');
254
+ // Example output: "xK9mP2qL5wY9zB1cD4eF6g"
255
+
256
+ // Derive a longer secret (e.g., 32 bytes for an API key)
257
+ const apiKey = workHandle.derivePassword('aws-api', 32);
258
+ ```
259
+
260
+ **Parameters:**
261
+ - `context`: A unique identifier for the service (e.g., `'google'`, `'github'`, `'wifi-router'`)
262
+ - `length`: Length of the derived raw bytes (default: 16 bytes = ~22 chars base64url)
263
+
264
+ **Returns:** A URL-safe base64 string suitable for use as a strong password.
265
+
266
+ **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.
267
+
268
+ **Use Case:** 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.
269
+
270
+ #### `Handle.deriveChannelKey(context)`
271
+
272
+ 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.
273
+
274
+ ```typescript
275
+ // On the device (Handle side):
276
+ const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
277
+ // channelKey is a 32-byte Uint8Array, ready for AES-256-GCM
278
+
279
+ // On the controller (Identity side):
280
+ const droneHandle = await centerIdentity.deriveHandle('drone-001');
281
+ const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
282
+ // Identical key, derived independently
283
+ ```
284
+
285
+ **Parameters:**
286
+ - `context`: Channel identifier for domain separation (e.g., `'drone-001'`, `'session-abc'`). Both parties **must** use the same context to derive the same key.
287
+
288
+ **Returns:** 32-byte `Uint8Array` suitable for AES-256-GCM encryption.
289
+
290
+ **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.
291
+
292
+ **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.
293
+
294
+ ---
295
+
296
+ ## 🎯 Use Cases
297
+
298
+ ### 1. Deterministic Password Manager (Access Key Keeper)
299
+
300
+ 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.
301
+
302
+ ```typescript
303
+ // 1. User restores Identity from Seed (e.g., after entering a PIN)
304
+ const identity = await Identity.fromSeed(userSeed);
305
+
306
+ // 2. Derive the specific service Handle
307
+ const googleHandle = await identity.deriveHandle('google', {
308
+ displayName: 'Alice Personal'
309
+ });
310
+
311
+ // 3. Deterministically generate the password on the fly
312
+ const password = googleHandle.derivePassword('google');
313
+
314
+ // 4. Auto-fill the login form
315
+ console.log('Login:', 'alice@example.com');
316
+ console.log('Password:', password); // Always the same for this seed + handle + context
317
+ ```
318
+
319
+ ✅ **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-v2')`).
320
+
321
+ ---
322
+
323
+ ### 2. IoT Fleet with Encrypted Channels
324
+
325
+ 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.
326
+
327
+ ```typescript
328
+ // === CONTROL CENTER (Identity) ===
329
+ const centerIdentity = await Identity.fromSeed(centerSeed);
330
+
331
+ // Minimal registry: just device names (no public keys stored!)
332
+ const allowedDevices = ['drone-001', 'drone-002', 'sensor-warehouse-a'];
333
+
334
+ // Receiving telemetry from a drone
335
+ async function receiveTelemetry(message: { name: string, signature: Uint8Array, encrypted: Uint8Array }) {
336
+ // 1. Check if device is in registry
337
+ if (!allowedDevices.includes(message.name)) {
338
+ throw new Error('Unknown device');
339
+ }
340
+
341
+ // 2. Derive the Handle (deterministic, no DB lookup)
342
+ const deviceHandle = await centerIdentity.deriveHandle(message.name);
343
+
344
+ // 3. Verify signature (proves device owns the private key)
345
+ const dataToVerify = concatBytes(
346
+ new TextEncoder().encode(message.name),
347
+ message.encrypted
348
+ );
349
+ const isValid = await Handle.verify(message.signature, dataToVerify, deviceHandle.getPublicKey());
350
+ if (!isValid) throw new Error('Invalid signature');
351
+
352
+ // 4. Derive the SAME channel key the device used for encryption
353
+ const channelKey = deviceHandle.deriveChannelKey('telemetry-v1');
354
+
355
+ // 5. Decrypt the message
356
+ const telemetry = await decryptAESGCM(message.encrypted, channelKey);
357
+ return telemetry;
358
+ }
359
+
360
+ // === DRONE (Handle, provisioned at factory) ===
361
+ // Drone is provisioned with its Handle's private key and name
362
+ async function sendTelemetry(telemetry: object) {
363
+ const name = 'drone-001';
364
+ const privateKey = /* loaded from secure enclave */;
365
+ const droneHandle = new Handle(privateKey, name);
366
+
367
+ // 1. Derive the SAME channel key the center will use for decryption
368
+ const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
369
+
370
+ // 2. Encrypt telemetry
371
+ const telemetryBytes = new TextEncoder().encode(JSON.stringify(telemetry));
372
+ const encrypted = await encryptAESGCM(telemetryBytes, channelKey);
373
+
374
+ // 3. Sign (name + encrypted data)
375
+ const dataToSign = concatBytes(new TextEncoder().encode(name), encrypted);
376
+ const signature = await droneHandle.sign(dataToSign);
377
+
378
+ return { name, signature, encrypted };
379
+ }
380
+ ```
381
+
382
+ ✅ **Benefits**:
383
+ - **Minimal registry**: Control center stores only device names (strings), not public keys
384
+ - **No key exchange**: Both parties derive the same key independently
385
+ - **Stateless verification**: Signature check proves device authenticity
386
+ - **Isolation**: Compromise of one device doesn't affect others (different Handles → different channel keys)
387
+
388
+ ---
389
+
390
+ ### 3. Stateless Multi-Device Synchronization
391
+
392
+ 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.
393
+
394
+ ```typescript
395
+ // On the phone:
396
+ const identity = await Identity.fromSeed(userSeed);
397
+ const messengerHandle = await identity.deriveHandle('messenger-main');
398
+ const handleId = messengerHandle.getId();
399
+ // Send handleId to server for registration
400
+
401
+ // On the laptop (later, no sync needed):
402
+ const identity = await Identity.fromSeed(userSeed); // Same seed
403
+ const messengerHandle = await identity.deriveHandle('messenger-main'); // Same name
404
+ const handleId = messengerHandle.getId(); // Identical handleId!
405
+ // Server recognizes the same user automatically
406
+ ```
407
+
408
+ ✅ **Benefit**: Zero-knowledge multi-device support. No QR codes, no server-side key sync, no backup servers. The mathematics guarantees identity across devices.
409
+
410
+ ---
411
+
412
+ ### 4. Break-Glass Recovery and Inheritance
413
+
414
+ 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.
415
+
416
+ ```typescript
417
+ // User stores seed phrase in a physical safe (or via Shamir's Secret Sharing with trusted heirs)
418
+
419
+ // Years later, on a new device:
420
+ const identity = await Identity.fromSeed(recoveredSeed);
421
+
422
+ // All handles are instantly recoverable:
423
+ const googleHandle = await identity.deriveHandle('google');
424
+ const bankHandle = await identity.deriveHandle('bank');
425
+ const messengerHandle = await identity.deriveHandle('messenger-main');
426
+
427
+ // All passwords are instantly recoverable:
428
+ const googlePassword = googleHandle.derivePassword('google');
429
+ const bankPassword = bankHandle.derivePassword('bank');
430
+
431
+ // All channel keys are instantly recoverable:
432
+ const messengerChannelKey = messengerHandle.deriveChannelKey('session-2026');
433
+ ```
434
+
435
+ ✅ **Benefit**: True self-sovereignty. No company can lock you out of your identity. Recovery is a mathematical certainty, not a customer support ticket.
436
+
437
+ ---
438
+
439
+ ### 5. Ephemeral Delegated Access
440
+
441
+ Grant time-limited access to a contractor or temporary service by deriving a Handle with a time-bound name.
442
+
443
+ ```typescript
444
+ // Grant access to contractor until 2026-12-31
445
+ const contractorHandle = await identity.deriveHandle('contractor-acme-2026-12-31', {
446
+ displayName: 'ACME Corp Contractor',
447
+ role: 'auditor',
448
+ expiresAt: '2026-12-31T23:59:59Z'
449
+ });
450
+
451
+ // Share the Handle ID with the contractor's system
452
+ // Contractor uses this Handle for authenticated access
453
+
454
+ // After expiration:
455
+ // - Server rejects requests (checks expiresAt metadata)
456
+ // - User simply stops using this Handle
457
+ // - No cleanup needed — the Handle is just a name in the derivation tree
458
+ ```
459
+
460
+ ✅ **Benefit**: Clean delegation without polluting the permanent identity. Expired Handles become inert cryptographic artifacts.
461
+
462
+ ---
463
+
464
+ ## 🔐 Cryptographic Details
465
+
466
+ ### Handle Derivation Algorithm
467
+
468
+ Handles are derived using **HKDF-SHA256** with domain separation:
469
+
470
+ ```
471
+ HandlePrivateKey = HKDF-SHA256(
472
+ inputKeyMaterial = IdentityPrivateKey,
473
+ salt = empty,
474
+ info = "me2em/handle/v1/" + lowercase(name),
475
+ length = 32
476
+ )
477
+ HandlePublicKey = Ed25519.PublicKey(HandlePrivateKey)
478
+ HandleId = Base64Url(HandlePublicKey)
479
+ ```
480
+
481
+ **Properties:**
482
+ - 🔁 **Deterministic**: Same inputs → same output across all implementations
483
+ - 🔒 **One-way**: Cannot derive Identity key from Handle key
484
+ - 🧩 **Isolated**: Each Handle uses independent Ed25519 keypair
485
+
486
+ ### Password Derivation Algorithm
487
+
488
+ Passwords are derived using **HKDF-SHA256** with the Handle's private key as input key material:
489
+
490
+ ```
491
+ PasswordBytes = HKDF-SHA256(
492
+ inputKeyMaterial = HandlePrivateKey,
493
+ salt = "me2em/secret/" + lowercase(context),
494
+ info = "me2em/secret/v1",
495
+ length = 16 (default)
496
+ )
497
+ Password = Base64Url(PasswordBytes)
498
+ ```
499
+
500
+ **Properties:**
501
+ - 🔁 **Deterministic**: Same Handle + same context → same password
502
+ - 🔐 **Encapsulated**: Private key never leaves the Handle instance
503
+ - 🧩 **Domain-separated**: Different contexts produce different passwords
504
+
505
+ ### Channel Key Derivation
506
+
507
+ Channel keys are derived using **HKDF-SHA256** with the Handle's private key as input key material:
508
+
509
+ ```
510
+ ChannelKey = HKDF-SHA256(
511
+ inputKeyMaterial = HandlePrivateKey,
512
+ salt = "me2em/channel/" + lowercase(context),
513
+ info = "me2em/channel/v1",
514
+ length = 32
515
+ )
516
+ ```
517
+
518
+ **Properties:**
519
+ - 🔁 **Deterministic**: Same Handle + same context → same 32-byte key
520
+ - 🔐 **Encapsulated**: Private key never leaves the Handle instance
521
+ - 🧩 **Domain-separated**: Different contexts produce different keys (e.g., `'telemetry-v1'` vs `'command-v1'`)
522
+ - ⚡ **No key exchange**: Both parties derive the key independently, no ECDH needed
523
+
524
+ ### Signature Scheme
525
+
526
+ - **Algorithm**: Ed25519 (RFC 8032)
527
+ - **Hash**: SHA-512 (via `@noble/ed25519`)
528
+ - **Encoding**: Raw bytes → base64url for transport
529
+
530
+ ---
531
+
532
+ ## 🛡️ Security Best Practices
533
+
534
+ ### ✅ Do
535
+
536
+ - **Store seeds encrypted**: Use PIN/biometric + AES-GCM before persisting to IndexedDB
537
+ - **Clear memory**: Zero out seed/private key buffers after use (`buffer.fill(0)`)
538
+ - **Use short TTLs**: Rotate session tokens frequently (≤1 hour recommended)
539
+ - **Validate metadata server-side**: Never trust client-provided Handle metadata without verification
540
+ - **Pin dependencies**: Lock `@me2em/core` to specific version in `package.json`
541
+
542
+ ### ❌ Don't
543
+
544
+ - **Never transmit seeds**: The seed is the root of trust — keep it client-side only
545
+ - **Don't reuse Handles across contexts**: Derive separate Handles for different apps/services
546
+ - **Don't log private keys**: Ensure debugging output never includes key material
547
+ - **Don't disable signature verification**: Always verify Ed25519 signatures server-side
548
+
549
+ ### Key Lifecycle
550
+
551
+ ```
552
+ [User enters seed]
553
+ │
554
+ ▼
555
+ [Derive Identity in RAM]
556
+ │
557
+ ▼
558
+ [Derive Handle(s) as needed]
559
+ │
560
+ ▼
561
+ [Sign challenge / data / derive password / derive channel key]
562
+ │
563
+ ▼
564
+ [Zero out private key buffers] ← Critical!
565
+ │
566
+ ▼
567
+ [Keep only public HandleId for future use]
568
+ ```
569
+
570
+ ---
571
+
572
+ ## 🧪 Testing
573
+
574
+ ### Unit Tests
575
+
576
+ ```bash
577
+ cd packages/core
578
+ pnpm test
579
+ ```
580
+
581
+ Tests cover:
582
+ - ✅ Deterministic derivation (same seed + name → same HandleId)
583
+ - ✅ Signature generation and verification
584
+ - ✅ Password derivation (same Handle + context → same password)
585
+ - ✅ Channel key derivation (same Handle + context → same key)
586
+ - ✅ Edge cases (empty metadata, long names, unicode)
587
+
588
+ ### Integration Test Example
589
+
590
+ ```typescript
591
+ import { Identity } from '@me2em/core';
592
+
593
+ test('full auth flow', async () => {
594
+ // Client side
595
+ const identity = await Identity.fromSeed(testSeed);
596
+ const handle = await identity.deriveHandle('test');
597
+ const challenge = new TextEncoder().encode('nonce-123');
598
+ const signature = await handle.sign(challenge);
599
+
600
+ // Server side
601
+ const isValid = await Handle.verify(
602
+ signature,
603
+ challenge,
604
+ handle.getPublicKey()
605
+ );
606
+ expect(isValid).toBe(true);
607
+ expect(handle.getId()).toMatch(/^[A-Za-z0-9_-]{43}$/);
608
+ });
609
+ ```
610
+
611
+ ---
612
+
613
+ ## 📦 Package Info
614
+
615
+ ```json
616
+ {
617
+ "name": "@me2em/core",
618
+ "version": "0.4.2-alpha.1",
619
+ "type": "module",
620
+ "main": "./dist/index.js",
621
+ "types": "./dist/index.d.ts",
622
+ "exports": {
623
+ ".": {
624
+ "types": "./dist/index.d.ts",
625
+ "import": "./dist/index.js",
626
+ "require": "./dist/index.cjs"
627
+ }
628
+ },
629
+ "dependencies": {
630
+ "@noble/ed25519": "^3.1.0",
631
+ "@noble/hashes": "^2.2.0",
632
+ "@scure/bip39": "^1.3.0"
633
+ },
634
+ "engines": {
635
+ "node": ">=18.0.0"
636
+ }
637
+ }
638
+ ```
639
+
640
+ ---
641
+
642
+ ## 🤝 Contributing
643
+
644
+ We welcome contributions! See:
645
+
646
+ - 📄 [CONTRIBUTING.md](../../CONTRIBUTING.md) — How to contribute code/docs
647
+ - 🗳️ [GOVERNANCE.md](../../GOVERNANCE.md) — Project decision-making process
648
+ - 🔐 [SECURITY.md](../../SECURITY.md) — Responsible disclosure policy
649
+
650
+ ---
651
+
652
+ ## 📜 License
653
+
654
+ Apache License 2.0 — see [LICENSE](../../LICENSE) for details.
655
+
656
+ © 2026 Me2em Organization. Built for privacy, openness, and user sovereignty.
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@me2em/core",
3
+ "version": "0.4.4-alpha.1",
4
+ "description": "Core primitives for the Me2em authorization protocol: Identity, Handle, and Session",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "require": "./dist/index.cjs"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "src",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "scripts": {
22
+ "build": "tsc -p tsconfig.json",
23
+ "test": "vitest run",
24
+ "test:coverage": "vitest run --coverage",
25
+ "lint": "eslint src",
26
+ "typecheck": "tsc --noEmit"
27
+ },
28
+ "license": "Apache-2.0",
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "dependencies": {
33
+ "@noble/ed25519": "^3.1.0",
34
+ "@noble/hashes": "^2.2.0",
35
+ "@scure/bip39": "^1.3.0"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^25.9.1",
39
+ "@vitest/coverage-v8": "^4.1.11",
40
+ "eslint": "^10.4.1",
41
+ "typescript": "^6.0.3",
42
+ "vitest": "^4.1.7"
43
+ }
44
+ }