@me2em/core 0.4.1-alpha.1 → 0.4.2-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.
- package/README.md +197 -383
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/seed.d.ts +24 -0
- package/dist/seed.d.ts.map +1 -0
- package/dist/seed.js +55 -0
- package/dist/seed.js.map +1 -0
- package/package.json +5 -2
- package/src/index.ts +10 -1
- package/src/seed.ts +65 -0
package/README.md
CHANGED
|
@@ -1,37 +1,63 @@
|
|
|
1
|
-
|
|
1
|
+
Отлично! Сейчас создам детальный `packages/core/README.md` — это будет профессиональная документация API для npm-пакета `@me2em/core`.
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Замените содержимое файла `packages/core/README.md` на этот код:
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
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.
|
|
9
|
+
|
|
10
|
+
[](https://www.npmjs.com/package/@me2em/core)
|
|
11
|
+
[](https://github.com/me2em-org/me2em-protocol/blob/main/LICENSE)
|
|
7
12
|
[](https://docs.me2em.com)
|
|
8
13
|
|
|
9
14
|
---
|
|
10
15
|
|
|
11
|
-
## 🎯
|
|
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
|
|
12
28
|
|
|
13
29
|
```bash
|
|
14
|
-
npm install @me2em
|
|
30
|
+
npm install @me2em/core
|
|
15
31
|
# or
|
|
16
|
-
pnpm add @me2em
|
|
32
|
+
pnpm add @me2em/core
|
|
17
33
|
# or
|
|
18
|
-
yarn add @me2em
|
|
34
|
+
yarn add @me2em/core
|
|
19
35
|
```
|
|
20
36
|
|
|
37
|
+
**Dependencies:**
|
|
38
|
+
- `@noble/ed25519` — Ed25519 signatures
|
|
39
|
+
- `@noble/hashes` — HKDF, SHA-256
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## 🚀 Quick Start
|
|
44
|
+
|
|
45
|
+
### Basic Usage
|
|
46
|
+
|
|
21
47
|
```typescript
|
|
22
|
-
import { Identity, Handle } from '@me2em
|
|
48
|
+
import { Identity, Handle } from '@me2em/core';
|
|
23
49
|
|
|
24
|
-
// 1. Create
|
|
25
|
-
const seed =
|
|
50
|
+
// 1. Create Identity from seed (32 bytes)
|
|
51
|
+
const seed = new Uint8Array(32).fill(42); // Replace with your secure seed
|
|
26
52
|
const identity = await Identity.fromSeed(seed);
|
|
27
53
|
|
|
28
|
-
// 2. Derive a contextual
|
|
54
|
+
// 2. Derive a contextual Handle
|
|
29
55
|
const workHandle = await identity.deriveHandle('work', {
|
|
30
56
|
displayName: 'Alice @ Work',
|
|
31
57
|
avatar: 'https://example.com/avatar.png'
|
|
32
58
|
});
|
|
33
59
|
|
|
34
|
-
// 3. Use
|
|
60
|
+
// 3. Use Handle for cryptographic operations
|
|
35
61
|
const message = new TextEncoder().encode('Hello, world!');
|
|
36
62
|
const signature = await workHandle.sign(message);
|
|
37
63
|
const isValid = await Handle.verify(signature, message, workHandle.getPublicKey());
|
|
@@ -40,77 +66,34 @@ console.log('Handle ID:', workHandle.getId()); // base64url(publicKey)
|
|
|
40
66
|
console.log('Signature valid:', isValid); // true
|
|
41
67
|
```
|
|
42
68
|
|
|
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
|
|
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
|
-
└─────────────────┘
|
|
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
|
|
69
|
+
### Integration with BIP39 (Recommended)
|
|
82
70
|
|
|
83
|
-
|
|
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.
|
|
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.
|
|
101
72
|
|
|
102
73
|
```typescript
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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);
|
|
108
92
|
```
|
|
109
93
|
|
|
110
|
-
**
|
|
111
|
-
-
|
|
112
|
-
|
|
113
|
-
- 🌐 **Stateless verification**: Servers verify signatures using Handle public key — no database lookup required
|
|
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.
|
|
96
|
+
|
|
114
97
|
|
|
115
98
|
---
|
|
116
99
|
|
|
@@ -118,10 +101,12 @@ interface SessionOptions {
|
|
|
118
101
|
|
|
119
102
|
### `Identity` Class
|
|
120
103
|
|
|
104
|
+
The root cryptographic identity, derived from a seed phrase.
|
|
105
|
+
|
|
121
106
|
```typescript
|
|
122
107
|
class Identity {
|
|
123
|
-
// Create Identity from seed (32-byte Uint8Array
|
|
124
|
-
static fromSeed(seed: Uint8Array
|
|
108
|
+
// Create Identity from seed (32-byte Uint8Array)
|
|
109
|
+
static fromSeed(seed: Uint8Array): Promise<Identity>;
|
|
125
110
|
|
|
126
111
|
// Derive a new Handle with optional metadata
|
|
127
112
|
deriveHandle(name: string, metadata?: HandleMetadata): Promise<Handle>;
|
|
@@ -133,36 +118,66 @@ class Identity {
|
|
|
133
118
|
|
|
134
119
|
#### `Identity.fromSeed(seed)`
|
|
135
120
|
|
|
136
|
-
|
|
137
|
-
// From hex string (64 chars = 32 bytes)
|
|
138
|
-
const identity = await Identity.fromSeed('a1b2c3...');
|
|
121
|
+
Creates an Identity from a 32-byte seed.
|
|
139
122
|
|
|
140
|
-
|
|
141
|
-
const
|
|
142
|
-
|
|
123
|
+
```typescript
|
|
124
|
+
const seed = new Uint8Array(32);
|
|
125
|
+
crypto.getRandomValues(seed); // Generate secure random seed
|
|
126
|
+
const identity = await Identity.fromSeed(seed);
|
|
143
127
|
```
|
|
144
128
|
|
|
145
|
-
|
|
129
|
+
**Security:** The seed must be kept secret. Never log, transmit, or store it in plaintext.
|
|
146
130
|
|
|
147
131
|
#### `Identity.deriveHandle(name, metadata?)`
|
|
148
132
|
|
|
133
|
+
Derives a new Handle deterministically from the Identity.
|
|
134
|
+
|
|
149
135
|
```typescript
|
|
150
|
-
const handle = await identity.deriveHandle('
|
|
151
|
-
displayName: 'Alice
|
|
152
|
-
avatar: 'https://example.com/alice.png'
|
|
153
|
-
org: 'Acme Corp'
|
|
136
|
+
const handle = await identity.deriveHandle('google', {
|
|
137
|
+
displayName: 'Alice Personal',
|
|
138
|
+
avatar: 'https://example.com/alice.png'
|
|
154
139
|
});
|
|
155
140
|
```
|
|
156
141
|
|
|
157
|
-
|
|
158
|
-
- `
|
|
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
|
+
```
|
|
159
172
|
|
|
160
|
-
|
|
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.
|
|
161
174
|
|
|
162
175
|
---
|
|
163
176
|
|
|
164
177
|
### `Handle` Class
|
|
165
178
|
|
|
179
|
+
A derived Ed25519 keypair representing a specific context (work, personal, IoT device).
|
|
180
|
+
|
|
166
181
|
```typescript
|
|
167
182
|
class Handle {
|
|
168
183
|
// Get public identifier (safe to share)
|
|
@@ -177,7 +192,7 @@ class Handle {
|
|
|
177
192
|
// Deterministically derive a password/secret for a specific context
|
|
178
193
|
derivePassword(context: string, length?: number): string;
|
|
179
194
|
|
|
180
|
-
// Derive a symmetric
|
|
195
|
+
// Derive a symmetric channel key for encrypted communication
|
|
181
196
|
deriveChannelKey(context: string): Uint8Array;
|
|
182
197
|
|
|
183
198
|
// Accessors
|
|
@@ -236,7 +251,7 @@ if (!isValid) throw new Error('Invalid signature');
|
|
|
236
251
|
|
|
237
252
|
#### `Handle.derivePassword(context, length?)`
|
|
238
253
|
|
|
239
|
-
|
|
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.
|
|
240
255
|
|
|
241
256
|
```typescript
|
|
242
257
|
// Derive a password for a specific service
|
|
@@ -247,7 +262,15 @@ const googlePassword = workHandle.derivePassword('google');
|
|
|
247
262
|
const apiKey = workHandle.derivePassword('aws-api', 32);
|
|
248
263
|
```
|
|
249
264
|
|
|
250
|
-
|
|
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.
|
|
251
274
|
|
|
252
275
|
#### `Handle.deriveChannelKey(context)`
|
|
253
276
|
|
|
@@ -264,138 +287,20 @@ const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
|
|
|
264
287
|
// Identical key, derived independently
|
|
265
288
|
```
|
|
266
289
|
|
|
267
|
-
|
|
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
|
-
---
|
|
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.
|
|
272
292
|
|
|
273
|
-
|
|
293
|
+
**Returns:** 32-byte `Uint8Array` suitable for AES-256-GCM encryption.
|
|
274
294
|
|
|
275
|
-
|
|
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.
|
|
276
296
|
|
|
277
|
-
|
|
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
|
-
```
|
|
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.
|
|
290
298
|
|
|
291
299
|
---
|
|
292
300
|
|
|
293
301
|
## 🎯 Use Cases
|
|
294
302
|
|
|
295
|
-
### 1.
|
|
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)
|
|
303
|
+
### 1. Deterministic Password Manager (Access Key Keeper)
|
|
399
304
|
|
|
400
305
|
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
306
|
|
|
@@ -416,9 +321,11 @@ console.log('Login:', 'alice@example.com');
|
|
|
416
321
|
console.log('Password:', password); // Always the same for this seed + handle + context
|
|
417
322
|
```
|
|
418
323
|
|
|
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'
|
|
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
|
+
---
|
|
420
327
|
|
|
421
|
-
###
|
|
328
|
+
### 2. IoT Fleet with Encrypted Channels
|
|
422
329
|
|
|
423
330
|
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.
|
|
424
331
|
|
|
@@ -485,7 +392,7 @@ async function sendTelemetry(telemetry: object) {
|
|
|
485
392
|
|
|
486
393
|
---
|
|
487
394
|
|
|
488
|
-
###
|
|
395
|
+
### 3. Stateless Multi-Device Synchronization
|
|
489
396
|
|
|
490
397
|
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.
|
|
491
398
|
|
|
@@ -507,7 +414,7 @@ const handleId = messengerHandle.getId(); // Identical handleId!
|
|
|
507
414
|
|
|
508
415
|
---
|
|
509
416
|
|
|
510
|
-
###
|
|
417
|
+
### 4. Break-Glass Recovery and Inheritance
|
|
511
418
|
|
|
512
419
|
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.
|
|
513
420
|
|
|
@@ -534,7 +441,7 @@ const messengerChannelKey = messengerHandle.deriveChannelKey('session-2026');
|
|
|
534
441
|
|
|
535
442
|
---
|
|
536
443
|
|
|
537
|
-
###
|
|
444
|
+
### 5. Ephemeral Delegated Access
|
|
538
445
|
|
|
539
446
|
Grant time-limited access to a contractor or temporary service by deriving a Handle with a time-bound name.
|
|
540
447
|
|
|
@@ -557,9 +464,11 @@ const contractorHandle = await identity.deriveHandle('contractor-acme-2026-12-31
|
|
|
557
464
|
|
|
558
465
|
✅ **Benefit**: Clean delegation without polluting the permanent identity. Expired Handles become inert cryptographic artifacts.
|
|
559
466
|
|
|
467
|
+
---
|
|
468
|
+
|
|
560
469
|
## 🔐 Cryptographic Details
|
|
561
470
|
|
|
562
|
-
###
|
|
471
|
+
### Handle Derivation Algorithm
|
|
563
472
|
|
|
564
473
|
Handles are derived using **HKDF-SHA256** with domain separation:
|
|
565
474
|
|
|
@@ -579,6 +488,25 @@ HandleId = Base64Url(HandlePublicKey)
|
|
|
579
488
|
- 🔒 **One-way**: Cannot derive Identity key from Handle key
|
|
580
489
|
- 🧩 **Isolated**: Each Handle uses independent Ed25519 keypair
|
|
581
490
|
|
|
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
|
+
|
|
582
510
|
### Channel Key Derivation
|
|
583
511
|
|
|
584
512
|
Channel keys are derived using **HKDF-SHA256** with the Handle's private key as input key material:
|
|
@@ -592,7 +520,7 @@ ChannelKey = HKDF-SHA256(
|
|
|
592
520
|
)
|
|
593
521
|
```
|
|
594
522
|
|
|
595
|
-
**Properties
|
|
523
|
+
**Properties:**
|
|
596
524
|
- 🔁 **Deterministic**: Same Handle + same context → same 32-byte key
|
|
597
525
|
- 🔐 **Encapsulated**: Private key never leaves the Handle instance
|
|
598
526
|
- 🧩 **Domain-separated**: Different contexts produce different keys (e.g., `'telemetry-v1'` vs `'command-v1'`)
|
|
@@ -604,91 +532,6 @@ ChannelKey = HKDF-SHA256(
|
|
|
604
532
|
- **Hash**: SHA-512 (via `@noble/ed25519`)
|
|
605
533
|
- **Encoding**: Raw bytes → base64url for transport
|
|
606
534
|
|
|
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-org/protocol-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
|
-
|
|
692
535
|
---
|
|
693
536
|
|
|
694
537
|
## 🛡️ Security Best Practices
|
|
@@ -699,7 +542,7 @@ async function loadIdentity(pin: string) {
|
|
|
699
542
|
- **Clear memory**: Zero out seed/private key buffers after use (`buffer.fill(0)`)
|
|
700
543
|
- **Use short TTLs**: Rotate session tokens frequently (≤1 hour recommended)
|
|
701
544
|
- **Validate metadata server-side**: Never trust client-provided Handle metadata without verification
|
|
702
|
-
- **Pin dependencies**: Lock `@me2em
|
|
545
|
+
- **Pin dependencies**: Lock `@me2em/core` to specific version in `package.json`
|
|
703
546
|
|
|
704
547
|
### ❌ Don't
|
|
705
548
|
|
|
@@ -720,7 +563,7 @@ async function loadIdentity(pin: string) {
|
|
|
720
563
|
[Derive Handle(s) as needed]
|
|
721
564
|
│
|
|
722
565
|
▼
|
|
723
|
-
[Sign challenge / data]
|
|
566
|
+
[Sign challenge / data / derive password / derive channel key]
|
|
724
567
|
│
|
|
725
568
|
▼
|
|
726
569
|
[Zero out private key buffers] ← Critical!
|
|
@@ -736,19 +579,21 @@ async function loadIdentity(pin: string) {
|
|
|
736
579
|
### Unit Tests
|
|
737
580
|
|
|
738
581
|
```bash
|
|
739
|
-
cd packages/
|
|
582
|
+
cd packages/core
|
|
740
583
|
pnpm test
|
|
741
584
|
```
|
|
742
585
|
|
|
743
586
|
Tests cover:
|
|
744
587
|
- ✅ Deterministic derivation (same seed + name → same HandleId)
|
|
745
588
|
- ✅ Signature generation and verification
|
|
589
|
+
- ✅ Password derivation (same Handle + context → same password)
|
|
590
|
+
- ✅ Channel key derivation (same Handle + context → same key)
|
|
746
591
|
- ✅ Edge cases (empty metadata, long names, unicode)
|
|
747
592
|
|
|
748
593
|
### Integration Test Example
|
|
749
594
|
|
|
750
595
|
```typescript
|
|
751
|
-
import { Identity } from '@me2em
|
|
596
|
+
import { Identity } from '@me2em/core';
|
|
752
597
|
|
|
753
598
|
test('full auth flow', async () => {
|
|
754
599
|
// Client side
|
|
@@ -768,65 +613,14 @@ test('full auth flow', async () => {
|
|
|
768
613
|
});
|
|
769
614
|
```
|
|
770
615
|
|
|
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-org/protocol-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
|
-
|
|
822
616
|
---
|
|
823
617
|
|
|
824
618
|
## 📦 Package Info
|
|
825
619
|
|
|
826
620
|
```json
|
|
827
621
|
{
|
|
828
|
-
"name": "@me2em
|
|
829
|
-
"version": "0.
|
|
622
|
+
"name": "@me2em/core",
|
|
623
|
+
"version": "0.4.2-alpha.1",
|
|
830
624
|
"type": "module",
|
|
831
625
|
"main": "./dist/index.js",
|
|
832
626
|
"types": "./dist/index.d.ts",
|
|
@@ -839,7 +633,8 @@ pnpm -r lint
|
|
|
839
633
|
},
|
|
840
634
|
"dependencies": {
|
|
841
635
|
"@noble/ed25519": "^3.1.0",
|
|
842
|
-
"@noble/hashes": "^2.2.0"
|
|
636
|
+
"@noble/hashes": "^2.2.0",
|
|
637
|
+
"@scure/bip39": "^1.3.0"
|
|
843
638
|
},
|
|
844
639
|
"engines": {
|
|
845
640
|
"node": ">=18.0.0"
|
|
@@ -849,18 +644,13 @@ pnpm -r lint
|
|
|
849
644
|
|
|
850
645
|
---
|
|
851
646
|
|
|
852
|
-
##
|
|
853
|
-
|
|
854
|
-
This package is part of the Me2em ecosystem:
|
|
647
|
+
## 🤝 Contributing
|
|
855
648
|
|
|
856
|
-
|
|
857
|
-
|---------|---------|
|
|
858
|
-
| `@me2em-org/protocol-core` | ✅ Core cryptography (this package) |
|
|
859
|
-
| `@me2em-org/sdk-js` | 🔄 Browser-friendly wrapper (planned) |
|
|
860
|
-
| `@me2em-org/auth-middleware` | 🔄 NestJS/Express auth middleware (planned) |
|
|
861
|
-
| `me2em-protocol/specs` | 📄 Protocol specification and test vectors |
|
|
649
|
+
We welcome contributions! See:
|
|
862
650
|
|
|
863
|
-
|
|
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
|
|
864
654
|
|
|
865
655
|
---
|
|
866
656
|
|
|
@@ -868,4 +658,28 @@ This package is part of the Me2em ecosystem:
|
|
|
868
658
|
|
|
869
659
|
Apache License 2.0 — see [LICENSE](../../LICENSE) for details.
|
|
870
660
|
|
|
871
|
-
© 2026 Me2em Organization. Built for privacy, openness, and user sovereignty.
|
|
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`.
|
package/dist/index.d.ts
CHANGED
|
@@ -2,5 +2,6 @@ export { Identity } from './identity.js';
|
|
|
2
2
|
export { Handle, type HandleMetadata } from './handle.js';
|
|
3
3
|
export { Session, type SessionOptions, type SessionToken } from './session.js';
|
|
4
4
|
export * as crypto from './crypto/index.js';
|
|
5
|
-
export
|
|
5
|
+
export { generateSeedPhrase, normalizeSeedPhrase, validateSeedPhrase, get32ByteSeedFromMnemonic, type SeedStrength } from './seed.js';
|
|
6
|
+
export declare const PROTOCOL_VERSION = "0.4.1-alpha.1";
|
|
6
7
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,KAAK,cAAc,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,KAAK,cAAc,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAC;AAG5C,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,kBAAkB,EAClB,yBAAyB,EACzB,KAAK,YAAY,EAClB,MAAM,WAAW,CAAC;AAEnB,eAAO,MAAM,gBAAgB,kBAAkB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -2,5 +2,7 @@ export { Identity } from './identity.js';
|
|
|
2
2
|
export { Handle } from './handle.js';
|
|
3
3
|
export { Session } from './session.js';
|
|
4
4
|
export * as crypto from './crypto/index.js';
|
|
5
|
-
|
|
5
|
+
// Seed utilities for human-friendly key generation
|
|
6
|
+
export { generateSeedPhrase, normalizeSeedPhrase, validateSeedPhrase, get32ByteSeedFromMnemonic } from './seed.js';
|
|
7
|
+
export const PROTOCOL_VERSION = '0.4.1-alpha.1';
|
|
6
8
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAuB,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,OAAO,EAA0C,MAAM,cAAc,CAAC;AAC/E,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAC;AAE5C,MAAM,CAAC,MAAM,gBAAgB,GAAG,eAAe,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAuB,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,OAAO,EAA0C,MAAM,cAAc,CAAC;AAC/E,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAC;AAE5C,mDAAmD;AACnD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,kBAAkB,EAClB,yBAAyB,EAE1B,MAAM,WAAW,CAAC;AAEnB,MAAM,CAAC,MAAM,gBAAgB,GAAG,eAAe,CAAC"}
|
package/dist/seed.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export type SeedStrength = 128 | 256;
|
|
2
|
+
/**
|
|
3
|
+
* Generates a BIP39 mnemonic phrase.
|
|
4
|
+
* @param strength - 128 for 12 words (default), 256 for 24 words.
|
|
5
|
+
* @returns Array of words.
|
|
6
|
+
*/
|
|
7
|
+
export declare function generateSeedPhrase(strength?: SeedStrength): string[];
|
|
8
|
+
/**
|
|
9
|
+
* Normalizes a seed phrase (lowercase, trimmed, removes extra spaces).
|
|
10
|
+
*/
|
|
11
|
+
export declare function normalizeSeedPhrase(seedPhrase: string | string[]): string[];
|
|
12
|
+
/**
|
|
13
|
+
* Validates a BIP39 seed phrase.
|
|
14
|
+
*/
|
|
15
|
+
export declare function validateSeedPhrase(words: string[]): {
|
|
16
|
+
isValid: boolean;
|
|
17
|
+
error?: string;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Converts a BIP39 mnemonic phrase into a 32-byte Uint8Array suitable for Ed25519.
|
|
21
|
+
* BIP39 produces a 64-byte seed. We hash it with SHA-256 to get exactly 32 bytes deterministically.
|
|
22
|
+
*/
|
|
23
|
+
export declare function get32ByteSeedFromMnemonic(seedPhrase: string | string[]): Promise<Uint8Array>;
|
|
24
|
+
//# sourceMappingURL=seed.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"seed.d.ts","sourceRoot":"","sources":["../src/seed.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,YAAY,GAAG,GAAG,GAAG,GAAG,CAAC;AAErC;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,GAAE,YAAkB,GAAG,MAAM,EAAE,CAMzE;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,CAG3E;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAexF;AAED;;;GAGG;AACH,wBAAsB,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,UAAU,CAAC,CAalG"}
|
package/dist/seed.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { generateMnemonic, mnemonicToSeed, validateMnemonic } from '@scure/bip39';
|
|
2
|
+
import { wordlist } from '@scure/bip39/wordlists/english';
|
|
3
|
+
import { sha256 } from './crypto/hkdf.js';
|
|
4
|
+
/**
|
|
5
|
+
* Generates a BIP39 mnemonic phrase.
|
|
6
|
+
* @param strength - 128 for 12 words (default), 256 for 24 words.
|
|
7
|
+
* @returns Array of words.
|
|
8
|
+
*/
|
|
9
|
+
export function generateSeedPhrase(strength = 128) {
|
|
10
|
+
if (strength !== 128 && strength !== 256) {
|
|
11
|
+
throw new Error('Seed strength must be 128 (12 words) or 256 (24 words)');
|
|
12
|
+
}
|
|
13
|
+
const mnemonic = generateMnemonic(wordlist, strength);
|
|
14
|
+
return mnemonic.split(' ');
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Normalizes a seed phrase (lowercase, trimmed, removes extra spaces).
|
|
18
|
+
*/
|
|
19
|
+
export function normalizeSeedPhrase(seedPhrase) {
|
|
20
|
+
const words = Array.isArray(seedPhrase) ? seedPhrase : seedPhrase.trim().split(/\s+/);
|
|
21
|
+
return words.map(word => word.toLowerCase().trim()).filter(word => word.length > 0);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Validates a BIP39 seed phrase.
|
|
25
|
+
*/
|
|
26
|
+
export function validateSeedPhrase(words) {
|
|
27
|
+
const wordCount = words.length;
|
|
28
|
+
if (wordCount !== 12 && wordCount !== 24) {
|
|
29
|
+
return { isValid: false, error: `Seed phrase must be 12 or 24 words, got ${wordCount}` };
|
|
30
|
+
}
|
|
31
|
+
const normalized = normalizeSeedPhrase(words);
|
|
32
|
+
for (const word of normalized) {
|
|
33
|
+
if (!wordlist.includes(word)) {
|
|
34
|
+
return { isValid: false, error: `Invalid word: ${word}` };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const isValid = validateMnemonic(normalized.join(' '), wordlist);
|
|
38
|
+
return { isValid, error: isValid ? undefined : 'Invalid seed phrase checksum' };
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Converts a BIP39 mnemonic phrase into a 32-byte Uint8Array suitable for Ed25519.
|
|
42
|
+
* BIP39 produces a 64-byte seed. We hash it with SHA-256 to get exactly 32 bytes deterministically.
|
|
43
|
+
*/
|
|
44
|
+
export async function get32ByteSeedFromMnemonic(seedPhrase) {
|
|
45
|
+
const words = normalizeSeedPhrase(seedPhrase);
|
|
46
|
+
const validation = validateSeedPhrase(words);
|
|
47
|
+
if (!validation.isValid) {
|
|
48
|
+
throw new Error(`Invalid seed phrase: ${validation.error}`);
|
|
49
|
+
}
|
|
50
|
+
const mnemonic = words.join(' ');
|
|
51
|
+
const seed64 = await mnemonicToSeed(mnemonic);
|
|
52
|
+
// Hash the 64-byte seed to get a deterministic 32-byte seed for Ed25519
|
|
53
|
+
return sha256(seed64);
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=seed.js.map
|
package/dist/seed.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"seed.js","sourceRoot":"","sources":["../src/seed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAClF,OAAO,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAI1C;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,WAAyB,GAAG;IAC7D,IAAI,QAAQ,KAAK,GAAG,IAAI,QAAQ,KAAK,GAAG,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IAC5E,CAAC;IACD,MAAM,QAAQ,GAAG,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACtD,OAAO,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,UAA6B;IAC/D,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACtF,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACtF,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,kBAAkB,CAAC,KAAe;IAChD,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC;IAC/B,IAAI,SAAS,KAAK,EAAE,IAAI,SAAS,KAAK,EAAE,EAAE,CAAC;QACzC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,2CAA2C,SAAS,EAAE,EAAE,CAAC;IAC3F,CAAC;IAED,MAAM,UAAU,GAAG,mBAAmB,CAAC,KAAK,CAAC,CAAC;IAC9C,KAAK,MAAM,IAAI,IAAI,UAAU,EAAE,CAAC;QAC9B,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YAC7B,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,iBAAiB,IAAI,EAAE,EAAE,CAAC;QAC5D,CAAC;IACH,CAAC;IAED,MAAM,OAAO,GAAG,gBAAgB,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC;IACjE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,8BAA8B,EAAE,CAAC;AAClF,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,UAA6B;IAC3E,MAAM,KAAK,GAAG,mBAAmB,CAAC,UAAU,CAAC,CAAC;IAC9C,MAAM,UAAU,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAE7C,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,wBAAwB,UAAU,CAAC,KAAK,EAAE,CAAC,CAAC;IAC9D,CAAC;IAED,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACjC,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,QAAQ,CAAC,CAAC;IAE9C,wEAAwE;IACxE,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC;AACxB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@me2em/core",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.2-alpha.1",
|
|
4
4
|
"description": "Core primitives for the Me2em authorization protocol: Identity, Handle, and Session",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -24,10 +24,12 @@
|
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
26
|
"@noble/ed25519": "^3.1.0",
|
|
27
|
-
"@noble/hashes": "^2.2.0"
|
|
27
|
+
"@noble/hashes": "^2.2.0",
|
|
28
|
+
"@scure/bip39": "^1.3.0"
|
|
28
29
|
},
|
|
29
30
|
"devDependencies": {
|
|
30
31
|
"@types/node": "^25.9.1",
|
|
32
|
+
"@vitest/coverage-v8": "^4.1.11",
|
|
31
33
|
"eslint": "^10.4.1",
|
|
32
34
|
"typescript": "^6.0.3",
|
|
33
35
|
"vitest": "^4.1.7"
|
|
@@ -35,6 +37,7 @@
|
|
|
35
37
|
"scripts": {
|
|
36
38
|
"build": "tsc -p tsconfig.json",
|
|
37
39
|
"test": "vitest run",
|
|
40
|
+
"test:coverage": "vitest run --coverage",
|
|
38
41
|
"lint": "eslint src",
|
|
39
42
|
"typecheck": "tsc --noEmit"
|
|
40
43
|
}
|
package/src/index.ts
CHANGED
|
@@ -3,4 +3,13 @@ export { Handle, type HandleMetadata } from './handle.js';
|
|
|
3
3
|
export { Session, type SessionOptions, type SessionToken } from './session.js';
|
|
4
4
|
export * as crypto from './crypto/index.js';
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
// Seed utilities for human-friendly key generation
|
|
7
|
+
export {
|
|
8
|
+
generateSeedPhrase,
|
|
9
|
+
normalizeSeedPhrase,
|
|
10
|
+
validateSeedPhrase,
|
|
11
|
+
get32ByteSeedFromMnemonic,
|
|
12
|
+
type SeedStrength
|
|
13
|
+
} from './seed.js';
|
|
14
|
+
|
|
15
|
+
export const PROTOCOL_VERSION = '0.4.1-alpha.1';
|
package/src/seed.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { generateMnemonic, mnemonicToSeed, validateMnemonic } from '@scure/bip39';
|
|
2
|
+
import { wordlist } from '@scure/bip39/wordlists/english';
|
|
3
|
+
import { sha256 } from './crypto/hkdf.js';
|
|
4
|
+
|
|
5
|
+
export type SeedStrength = 128 | 256; // 128 bits = 12 words, 256 bits = 24 words
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Generates a BIP39 mnemonic phrase.
|
|
9
|
+
* @param strength - 128 for 12 words (default), 256 for 24 words.
|
|
10
|
+
* @returns Array of words.
|
|
11
|
+
*/
|
|
12
|
+
export function generateSeedPhrase(strength: SeedStrength = 128): string[] {
|
|
13
|
+
if (strength !== 128 && strength !== 256) {
|
|
14
|
+
throw new Error('Seed strength must be 128 (12 words) or 256 (24 words)');
|
|
15
|
+
}
|
|
16
|
+
const mnemonic = generateMnemonic(wordlist, strength);
|
|
17
|
+
return mnemonic.split(' ');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Normalizes a seed phrase (lowercase, trimmed, removes extra spaces).
|
|
22
|
+
*/
|
|
23
|
+
export function normalizeSeedPhrase(seedPhrase: string | string[]): string[] {
|
|
24
|
+
const words = Array.isArray(seedPhrase) ? seedPhrase : seedPhrase.trim().split(/\s+/);
|
|
25
|
+
return words.map(word => word.toLowerCase().trim()).filter(word => word.length > 0);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Validates a BIP39 seed phrase.
|
|
30
|
+
*/
|
|
31
|
+
export function validateSeedPhrase(words: string[]): { isValid: boolean; error?: string } {
|
|
32
|
+
const wordCount = words.length;
|
|
33
|
+
if (wordCount !== 12 && wordCount !== 24) {
|
|
34
|
+
return { isValid: false, error: `Seed phrase must be 12 or 24 words, got ${wordCount}` };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const normalized = normalizeSeedPhrase(words);
|
|
38
|
+
for (const word of normalized) {
|
|
39
|
+
if (!wordlist.includes(word)) {
|
|
40
|
+
return { isValid: false, error: `Invalid word: ${word}` };
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const isValid = validateMnemonic(normalized.join(' '), wordlist);
|
|
45
|
+
return { isValid, error: isValid ? undefined : 'Invalid seed phrase checksum' };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Converts a BIP39 mnemonic phrase into a 32-byte Uint8Array suitable for Ed25519.
|
|
50
|
+
* BIP39 produces a 64-byte seed. We hash it with SHA-256 to get exactly 32 bytes deterministically.
|
|
51
|
+
*/
|
|
52
|
+
export async function get32ByteSeedFromMnemonic(seedPhrase: string | string[]): Promise<Uint8Array> {
|
|
53
|
+
const words = normalizeSeedPhrase(seedPhrase);
|
|
54
|
+
const validation = validateSeedPhrase(words);
|
|
55
|
+
|
|
56
|
+
if (!validation.isValid) {
|
|
57
|
+
throw new Error(`Invalid seed phrase: ${validation.error}`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const mnemonic = words.join(' ');
|
|
61
|
+
const seed64 = await mnemonicToSeed(mnemonic);
|
|
62
|
+
|
|
63
|
+
// Hash the 64-byte seed to get a deterministic 32-byte seed for Ed25519
|
|
64
|
+
return sha256(seed64);
|
|
65
|
+
}
|