@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
package/README.md CHANGED
@@ -1,30 +1,14 @@
1
- Отлично! Сейчас создам детальный `packages/core/README.md` — это будет профессиональная документация API для npm-пакета `@me2em/core`.
1
+ # 📦 `@me2em/core` — Developer Documentation
2
2
 
3
- Замените содержимое файла `packages/core/README.md` на этот код:
4
-
5
- ```markdown
6
- # 📦 `@me2em/core` — Core Cryptographic Primitives
7
-
8
- > Core primitives for the Me2em authorization protocol: `Identity`, `Handle`, and secure channel derivation with Ed25519 cryptography.
3
+ > Core primitives for the Me2em authorization protocol: `Identity`, `Handle`, and `Session` management with Ed25519 cryptography.
9
4
 
10
5
  [![npm version](https://img.shields.io/npm/v/@me2em/core.svg)](https://www.npmjs.com/package/@me2em/core)
11
- [![License](https://img.shields.io/npm/l/@me2em/core.svg)](https://github.com/me2em-org/me2em-protocol/blob/main/LICENSE)
6
+ [![License](https://img.shields.io/npm/l/@me2em/core)](https://github.com/me2em-org/me2em-protocol/blob/main/LICENSE)
12
7
  [![Docs](https://img.shields.io/badge/docs-docs.me2em.com-blue)](https://docs.me2em.com)
13
8
 
14
9
  ---
15
10
 
16
- ## 🎯 Overview
17
-
18
- `@me2em/core` provides the cryptographic foundation for the Me2em protocol — a decentralized multi-context identity system. It enables:
19
-
20
- - **Hierarchical Deterministic Identities**: One seed → multiple isolated Handles
21
- - **Zero-Knowledge Password Management**: Deterministic password derivation without storage
22
- - **Secure Channel Communication**: Encrypted channels between Identity and Handles without key exchange
23
- - **Stateless Authentication**: Cryptographic proof without server-side session storage
24
-
25
- ---
26
-
27
- ## 📦 Installation
11
+ ## 🎯 Quick Start
28
12
 
29
13
  ```bash
30
14
  npm install @me2em/core
@@ -34,30 +18,20 @@ pnpm add @me2em/core
34
18
  yarn add @me2em/core
35
19
  ```
36
20
 
37
- **Dependencies:**
38
- - `@noble/ed25519` — Ed25519 signatures
39
- - `@noble/hashes` — HKDF, SHA-256
40
-
41
- ---
42
-
43
- ## 🚀 Quick Start
44
-
45
- ### Basic Usage
46
-
47
21
  ```typescript
48
22
  import { Identity, Handle } from '@me2em/core';
49
23
 
50
- // 1. Create Identity from seed (32 bytes)
51
- const seed = new Uint8Array(32).fill(42); // Replace with your secure seed
24
+ // 1. Create or restore identity from seed
25
+ const seed = 'your-32-byte-hex-seed-or-24-words';
52
26
  const identity = await Identity.fromSeed(seed);
53
27
 
54
- // 2. Derive a contextual Handle
28
+ // 2. Derive a contextual handle
55
29
  const workHandle = await identity.deriveHandle('work', {
56
30
  displayName: 'Alice @ Work',
57
31
  avatar: 'https://example.com/avatar.png'
58
32
  });
59
33
 
60
- // 3. Use Handle for cryptographic operations
34
+ // 3. Use handle for cryptographic operations
61
35
  const message = new TextEncoder().encode('Hello, world!');
62
36
  const signature = await workHandle.sign(message);
63
37
  const isValid = await Handle.verify(signature, message, workHandle.getPublicKey());
@@ -66,34 +40,77 @@ console.log('Handle ID:', workHandle.getId()); // base64url(publicKey)
66
40
  console.log('Signature valid:', isValid); // true
67
41
  ```
68
42
 
69
- ### Integration with BIP39 (Recommended)
43
+ ---
70
44
 
71
- 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.
45
+ ## 📚 Table of Contents
72
46
 
73
- ```typescript
74
- import {
75
- Identity,
76
- generateSeedPhrase,
77
- get32ByteSeedFromMnemonic,
78
- validateSeedPhrase
79
- } from '@me2em/core';
80
-
81
- // 1. Generate a 12-word phrase (use 256 for 24 words)
82
- const phrase = generateSeedPhrase(128);
83
- console.log('Your seed:', phrase.join(' '));
84
-
85
- // 2. (Optional) Validate a user-provided phrase
86
- const validation = validateSeedPhrase(phrase);
87
- if (!validation.isValid) throw new Error(validation.error);
88
-
89
- // 3. Convert to 32-byte seed and create Identity
90
- const seedBytes = await get32ByteSeedFromMnemonic(phrase);
91
- const identity = await Identity.fromSeed(seedBytes);
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
61
+
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
+ └─────────────────┘
92
74
  ```
93
75
 
94
- **Why is this better?**
95
- 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.
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
96
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.
101
+
102
+ ```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
+ ```
109
+
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
97
114
 
98
115
  ---
99
116
 
@@ -101,12 +118,10 @@ BIP39 produces a 64-byte seed, but Ed25519 requires exactly 32 bytes. The `get32
101
118
 
102
119
  ### `Identity` Class
103
120
 
104
- The root cryptographic identity, derived from a seed phrase.
105
-
106
121
  ```typescript
107
122
  class Identity {
108
- // Create Identity from seed (32-byte Uint8Array)
109
- static fromSeed(seed: Uint8Array): Promise<Identity>;
123
+ // Create Identity from seed (32-byte Uint8Array or hex string)
124
+ static fromSeed(seed: Uint8Array | string): Promise<Identity>;
110
125
 
111
126
  // Derive a new Handle with optional metadata
112
127
  deriveHandle(name: string, metadata?: HandleMetadata): Promise<Handle>;
@@ -118,66 +133,36 @@ class Identity {
118
133
 
119
134
  #### `Identity.fromSeed(seed)`
120
135
 
121
- Creates an Identity from a 32-byte seed.
122
-
123
136
  ```typescript
124
- const seed = new Uint8Array(32);
125
- crypto.getRandomValues(seed); // Generate secure random seed
126
- const identity = await Identity.fromSeed(seed);
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);
127
143
  ```
128
144
 
129
- **Security:** The seed must be kept secret. Never log, transmit, or store it in plaintext.
145
+ ⚠️ **Security**: The seed must be kept secret. Never log, transmit, or store it in plaintext.
130
146
 
131
147
  #### `Identity.deriveHandle(name, metadata?)`
132
148
 
133
- Derives a new Handle deterministically from the Identity.
134
-
135
149
  ```typescript
136
- const handle = await identity.deriveHandle('google', {
137
- displayName: 'Alice Personal',
138
- avatar: 'https://example.com/alice.png'
150
+ const handle = await identity.deriveHandle('work', {
151
+ displayName: 'Alice Developer',
152
+ avatar: 'https://example.com/alice.png',
153
+ org: 'Acme Corp'
139
154
  });
140
155
  ```
141
156
 
142
- **Parameters:**
143
- - `name`: Unique identifier for this Handle (case-insensitive, trimmed)
144
- - `metadata`: Optional public data attached to the Handle
145
-
146
- **Returns:** A `Handle` instance with its own keypair, derived deterministically from the Identity.
147
-
148
- **Key Properties:**
149
- - 🔁 **Deterministic**: Same seed + same name → same Handle (always)
150
- - 🔗 **Isolated**: Each Handle has its own keypair; compromise of one does not affect others
151
- - 🔒 **One-way**: Cannot derive Identity key from Handle key
152
-
153
- ---
154
-
155
- ### Seed Utilities
156
-
157
- Built-in helpers for human-friendly key generation and validation.
158
-
159
- ```typescript
160
- // Generate a new phrase (128 bits = 12 words, 256 bits = 24 words)
161
- function generateSeedPhrase(strength: 128 | 256 = 128): string[];
162
-
163
- // Normalize input (handles extra spaces, lowercase)
164
- function normalizeSeedPhrase(input: string | string[]): string[];
165
-
166
- // Validate word count, wordlist, and BIP39 checksum
167
- function validateSeedPhrase(words: string[]): { isValid: boolean; error?: string };
168
-
169
- // Convert validated mnemonic to a secure 32-byte Uint8Array for Ed25519
170
- async function get32ByteSeedFromMnemonic(phrase: string | string[]): Promise<Uint8Array>;
171
- ```
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)
172
159
 
173
- ✅ **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.
160
+ Returns a `Handle` instance with its own keypair, derived deterministically from the Identity.
174
161
 
175
162
  ---
176
163
 
177
164
  ### `Handle` Class
178
165
 
179
- A derived Ed25519 keypair representing a specific context (work, personal, IoT device).
180
-
181
166
  ```typescript
182
167
  class Handle {
183
168
  // Get public identifier (safe to share)
@@ -192,7 +177,7 @@ class Handle {
192
177
  // Deterministically derive a password/secret for a specific context
193
178
  derivePassword(context: string, length?: number): string;
194
179
 
195
- // Derive a symmetric channel key for encrypted communication
180
+ // Derive a symmetric 256-bit channel key for encrypted communication
196
181
  deriveChannelKey(context: string): Uint8Array;
197
182
 
198
183
  // Accessors
@@ -251,7 +236,7 @@ if (!isValid) throw new Error('Invalid signature');
251
236
 
252
237
  #### `Handle.derivePassword(context, length?)`
253
238
 
254
- 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.
239
+ Generates a deterministic, cryptographically strong secret (e.g., a password) for a specific service, without ever exposing the private key.
255
240
 
256
241
  ```typescript
257
242
  // Derive a password for a specific service
@@ -262,15 +247,7 @@ const googlePassword = workHandle.derivePassword('google');
262
247
  const apiKey = workHandle.derivePassword('aws-api', 32);
263
248
  ```
264
249
 
265
- **Parameters:**
266
- - `context`: A unique identifier for the service (e.g., `'google'`, `'github'`, `'wifi-router'`)
267
- - `length`: Length of the derived raw bytes (default: 16 bytes = ~22 chars base64url)
268
-
269
- **Returns:** A URL-safe base64 string suitable for use as a strong password.
270
-
271
- **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.
272
-
273
- **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.
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.
274
251
 
275
252
  #### `Handle.deriveChannelKey(context)`
276
253
 
@@ -287,20 +264,138 @@ const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
287
264
  // Identical key, derived independently
288
265
  ```
289
266
 
290
- **Parameters:**
291
- - `context`: Channel identifier for domain separation (e.g., `'drone-001'`, `'session-abc'`). Both parties **must** use the same context to derive the same key.
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
+ ---
292
272
 
293
- **Returns:** 32-byte `Uint8Array` suitable for AES-256-GCM encryption.
273
+ ### `Session` Class (Planned)
294
274
 
295
- **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.
275
+ > ⚠️ Session management is planned for v0.2. Current implementations should use custom token logic with Handle signatures.
296
276
 
297
- **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.
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
283
+ });
284
+
285
+ // Use token
286
+ fetch('https://api.myapp.com/me', {
287
+ headers: { Authorization: `Bearer ${session.token}` }
288
+ });
289
+ ```
298
290
 
299
291
  ---
300
292
 
301
293
  ## 🎯 Use Cases
302
294
 
303
- ### 1. Deterministic Password Manager (Access Key Keeper)
295
+ ### 1. Multi-Context User Authentication
296
+
297
+ ```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
310
+
311
+ // Later, derive personal handle for social app
312
+ const personalHandle = await identity.deriveHandle('personal', {
313
+ displayName: 'Alice',
314
+ interests: ['hiking', 'photography']
315
+ });
316
+
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
320
+ ```
321
+
322
+ ✅ **Benefit**: One seed, multiple isolated identities. Apps see only the Handle they interact with.
323
+
324
+ ---
325
+
326
+ ### 2. IoT Device Hierarchy
327
+
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
+ });
337
+
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
+ });
343
+
344
+ const sensor2 = await fleetIdentity.deriveHandle('gateway-001/sensor-humidity', {
345
+ type: 'humidity',
346
+ unit: 'percent'
347
+ });
348
+ ```
349
+
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
355
+
356
+ ```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
365
+ });
366
+
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)
304
399
 
305
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.
306
401
 
@@ -321,11 +416,9 @@ console.log('Login:', 'alice@example.com');
321
416
  console.log('Password:', password); // Always the same for this seed + handle + context
322
417
  ```
323
418
 
324
- ✅ **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')`).
325
-
326
- ---
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)`).
327
420
 
328
- ### 2. IoT Fleet with Encrypted Channels
421
+ ### 6. IoT Fleet with Encrypted Channels
329
422
 
330
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.
331
424
 
@@ -392,7 +485,7 @@ async function sendTelemetry(telemetry: object) {
392
485
 
393
486
  ---
394
487
 
395
- ### 3. Stateless Multi-Device Synchronization
488
+ ### 7. Stateless Multi-Device Synchronization
396
489
 
397
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.
398
491
 
@@ -414,7 +507,7 @@ const handleId = messengerHandle.getId(); // Identical handleId!
414
507
 
415
508
  ---
416
509
 
417
- ### 4. Break-Glass Recovery and Inheritance
510
+ ### 8. Break-Glass Recovery and Inheritance
418
511
 
419
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.
420
513
 
@@ -441,7 +534,7 @@ const messengerChannelKey = messengerHandle.deriveChannelKey('session-2026');
441
534
 
442
535
  ---
443
536
 
444
- ### 5. Ephemeral Delegated Access
537
+ ### 9. Ephemeral Delegated Access
445
538
 
446
539
  Grant time-limited access to a contractor or temporary service by deriving a Handle with a time-bound name.
447
540
 
@@ -464,11 +557,9 @@ const contractorHandle = await identity.deriveHandle('contractor-acme-2026-12-31
464
557
 
465
558
  ✅ **Benefit**: Clean delegation without polluting the permanent identity. Expired Handles become inert cryptographic artifacts.
466
559
 
467
- ---
468
-
469
560
  ## 🔐 Cryptographic Details
470
561
 
471
- ### Handle Derivation Algorithm
562
+ ### Key Derivation Algorithm
472
563
 
473
564
  Handles are derived using **HKDF-SHA256** with domain separation:
474
565
 
@@ -488,25 +579,6 @@ HandleId = Base64Url(HandlePublicKey)
488
579
  - 🔒 **One-way**: Cannot derive Identity key from Handle key
489
580
  - 🧩 **Isolated**: Each Handle uses independent Ed25519 keypair
490
581
 
491
- ### Password Derivation Algorithm
492
-
493
- Passwords are derived using **HKDF-SHA256** with the Handle's private key as input key material:
494
-
495
- ```
496
- PasswordBytes = HKDF-SHA256(
497
- inputKeyMaterial = HandlePrivateKey,
498
- salt = "me2em/secret/" + lowercase(context),
499
- info = "me2em/secret/v1",
500
- length = 16 (default)
501
- )
502
- Password = Base64Url(PasswordBytes)
503
- ```
504
-
505
- **Properties:**
506
- - 🔁 **Deterministic**: Same Handle + same context → same password
507
- - 🔐 **Encapsulated**: Private key never leaves the Handle instance
508
- - 🧩 **Domain-separated**: Different contexts produce different passwords
509
-
510
582
  ### Channel Key Derivation
511
583
 
512
584
  Channel keys are derived using **HKDF-SHA256** with the Handle's private key as input key material:
@@ -520,7 +592,7 @@ ChannelKey = HKDF-SHA256(
520
592
  )
521
593
  ```
522
594
 
523
- **Properties:**
595
+ **Properties**:
524
596
  - 🔁 **Deterministic**: Same Handle + same context → same 32-byte key
525
597
  - 🔐 **Encapsulated**: Private key never leaves the Handle instance
526
598
  - 🧩 **Domain-separated**: Different contexts produce different keys (e.g., `'telemetry-v1'` vs `'command-v1'`)
@@ -532,6 +604,91 @@ ChannelKey = HKDF-SHA256(
532
604
  - **Hash**: SHA-512 (via `@noble/ed25519`)
533
605
  - **Encoding**: Raw bytes → base64url for transport
534
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"
618
+ }
619
+ ```
620
+
621
+ ---
622
+
623
+ ## 🔌 Integration Guide
624
+
625
+ ### Backend Verification (Node.js Example)
626
+
627
+ ```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);
635
+
636
+ if (!handleId || !signature) {
637
+ return res.status(401).json({ error: 'Missing authentication headers' });
638
+ }
639
+
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
+ }
656
+ }
657
+
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));
662
+ }
663
+ ```
664
+
665
+ ### Frontend Secure Key Handling
666
+
667
+ ```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
+ });
678
+ }
679
+
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);
687
+ }
688
+ ```
689
+
690
+ ✅ **Best practice**: Use Web Crypto API or secure enclave for PIN/biometric decryption.
691
+
535
692
  ---
536
693
 
537
694
  ## 🛡️ Security Best Practices
@@ -563,7 +720,7 @@ ChannelKey = HKDF-SHA256(
563
720
  [Derive Handle(s) as needed]
564
721
  │
565
722
  ▼
566
- [Sign challenge / data / derive password / derive channel key]
723
+ [Sign challenge / data]
567
724
  │
568
725
  ▼
569
726
  [Zero out private key buffers] ← Critical!
@@ -579,15 +736,13 @@ ChannelKey = HKDF-SHA256(
579
736
  ### Unit Tests
580
737
 
581
738
  ```bash
582
- cd packages/core
739
+ cd packages/protocol-core
583
740
  pnpm test
584
741
  ```
585
742
 
586
743
  Tests cover:
587
744
  - ✅ Deterministic derivation (same seed + name → same HandleId)
588
745
  - ✅ Signature generation and verification
589
- - ✅ Password derivation (same Handle + context → same password)
590
- - ✅ Channel key derivation (same Handle + context → same key)
591
746
  - ✅ Edge cases (empty metadata, long names, unicode)
592
747
 
593
748
  ### Integration Test Example
@@ -613,6 +768,57 @@ test('full auth flow', async () => {
613
768
  });
614
769
  ```
615
770
 
771
+ ### Cross-Implementation Testing
772
+
773
+ Use [`specs/test-vectors.json`](../../specs/test-vectors.json) to verify your implementation matches the reference:
774
+
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
+ ```
786
+
787
+ ---
788
+
789
+ ## 🤝 Contributing
790
+
791
+ We welcome contributions! See:
792
+
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
796
+
797
+ ### Quick Start for Contributors
798
+
799
+ ```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
812
+ ```
813
+
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
+
616
822
  ---
617
823
 
618
824
  ## 📦 Package Info
@@ -620,7 +826,7 @@ test('full auth flow', async () => {
620
826
  ```json
621
827
  {
622
828
  "name": "@me2em/core",
623
- "version": "0.4.2-alpha.1",
829
+ "version": "0.3.0-alpha.1",
624
830
  "type": "module",
625
831
  "main": "./dist/index.js",
626
832
  "types": "./dist/index.d.ts",
@@ -633,8 +839,7 @@ test('full auth flow', async () => {
633
839
  },
634
840
  "dependencies": {
635
841
  "@noble/ed25519": "^3.1.0",
636
- "@noble/hashes": "^2.2.0",
637
- "@scure/bip39": "^1.3.0"
842
+ "@noble/hashes": "^2.2.0"
638
843
  },
639
844
  "engines": {
640
845
  "node": ">=18.0.0"
@@ -644,13 +849,17 @@ test('full auth flow', async () => {
644
849
 
645
850
  ---
646
851
 
647
- ## 🤝 Contributing
852
+ ## 🌐 Ecosystem
648
853
 
649
- We welcome contributions! See:
854
+ This package is part of the Me2em ecosystem:
650
855
 
651
- - 📄 [CONTRIBUTING.md](../../CONTRIBUTING.md) — How to contribute code/docs
652
- - 🗳️ [GOVERNANCE.md](../../GOVERNANCE.md) — Project decision-making process
653
- - 🔐 [SECURITY.md](../../SECURITY.md) — Responsible disclosure policy
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
861
+
862
+ 🔗 Learn more: [github.com/me2em-org](https://github.com/me2em-org) | [docs.me2em.com](https://docs.me2em.com)
654
863
 
655
864
  ---
656
865
 
@@ -658,28 +867,4 @@ We welcome contributions! See:
658
867
 
659
868
  Apache License 2.0 — see [LICENSE](../../LICENSE) for details.
660
869
 
661
- © 2026 Me2em Organization. Built for privacy, openness, and user sovereignty.
662
- ```
663
-
664
- ---
665
-
666
- ## ✅ Что сделано
667
-
668
- Этот `README.md` теперь:
669
-
670
- 1. **Профессиональный API-документ** для npm-пакета `@me2em/core`
671
- 2. **Quick Start** с интеграцией BIP39 (как в BeSafeChat)
672
- 3. **Полный API Reference** для `Identity` и `Handle`
673
- 4. **Детальное описание** новых методов:
674
- - `derivePassword()` — для Password Manager
675
- - `deriveChannelKey()` — для IoT Fleet
676
- 5. **6 Use Cases** с реальными примерами кода:
677
- - Password Manager
678
- - IoT Fleet with Encrypted Channels
679
- - Multi-Device Sync
680
- - Break-Glass Recovery
681
- - Ephemeral Delegated Access
682
- 6. **Cryptographic Details** — описание алгоритмов деривации
683
- 7. **Security Best Practices** — рекомендации по безопасному использованию
684
-
685
- Этот README будет отображаться на странице npm-пакета и станет основным источником документации для разработчиков, использующих `@me2em/core`.
870
+ © 2026 Me2em Organization. Built for privacy, openness, and user sovereignty.