@me2em/core 0.4.4-alpha.2 → 0.7.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +294 -546
- package/dist/attestation.d.ts +151 -0
- package/dist/attestation.d.ts.map +1 -0
- package/dist/attestation.js +279 -0
- package/dist/attestation.js.map +1 -0
- package/dist/canonical-name.d.ts +3 -0
- package/dist/canonical-name.d.ts.map +1 -0
- package/dist/canonical-name.js +12 -0
- package/dist/canonical-name.js.map +1 -0
- package/dist/crypto/derivation-paths.d.ts +41 -0
- package/dist/crypto/derivation-paths.d.ts.map +1 -0
- package/dist/crypto/derivation-paths.js +50 -0
- package/dist/crypto/derivation-paths.js.map +1 -0
- package/dist/crypto/ed25519.d.ts +48 -8
- package/dist/crypto/ed25519.d.ts.map +1 -1
- package/dist/crypto/ed25519.js +63 -8
- package/dist/crypto/ed25519.js.map +1 -1
- package/dist/crypto/hkdf.d.ts.map +1 -1
- package/dist/crypto/hkdf.js +1 -0
- package/dist/crypto/hkdf.js.map +1 -1
- package/dist/crypto/index.d.ts +1 -0
- package/dist/crypto/index.d.ts.map +1 -1
- package/dist/crypto/index.js +2 -0
- package/dist/crypto/index.js.map +1 -1
- package/dist/crypto/init.d.ts.map +1 -1
- package/dist/crypto/init.js +1 -0
- package/dist/crypto/init.js.map +1 -1
- package/dist/handle.d.ts +149 -35
- package/dist/handle.d.ts.map +1 -1
- package/dist/handle.js +180 -40
- package/dist/handle.js.map +1 -1
- package/dist/identity.d.ts +99 -19
- package/dist/identity.d.ts.map +1 -1
- package/dist/identity.js +128 -32
- package/dist/identity.js.map +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/seed.d.ts +38 -39
- package/dist/seed.d.ts.map +1 -1
- package/dist/seed.js +36 -41
- package/dist/seed.js.map +1 -1
- package/dist/session.d.ts +207 -17
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +428 -11
- package/dist/session.js.map +1 -1
- package/dist/subhandle.d.ts +126 -0
- package/dist/subhandle.d.ts.map +1 -0
- package/dist/subhandle.js +182 -0
- package/dist/subhandle.js.map +1 -0
- package/dist/util.d.ts +9 -0
- package/dist/util.d.ts.map +1 -0
- package/dist/util.js +34 -0
- package/dist/util.js.map +1 -0
- package/package.json +3 -3
- package/src/attestation.ts +364 -0
- package/src/canonical-name.ts +12 -0
- package/src/crypto/derivation-paths.ts +56 -0
- package/src/crypto/ed25519.ts +82 -8
- package/src/crypto/hkdf.ts +2 -0
- package/src/crypto/index.ts +3 -1
- package/src/crypto/init.ts +1 -0
- package/src/handle.ts +227 -42
- package/src/identity.ts +164 -35
- package/src/index.ts +5 -1
- package/src/seed.ts +59 -59
- package/src/session.ts +637 -24
- package/src/subhandle.ts +254 -0
- package/src/util.ts +35 -0
package/src/identity.ts
CHANGED
|
@@ -1,18 +1,36 @@
|
|
|
1
|
-
|
|
1
|
+
// identity.ts
|
|
2
|
+
import { ed } from './crypto/init.js';
|
|
2
3
|
import { hkdf } from '@noble/hashes/hkdf.js';
|
|
3
4
|
import { sha256 } from '@noble/hashes/sha2.js';
|
|
4
5
|
import { Handle, type HandleMetadata } from './handle.js';
|
|
6
|
+
import { SubHandle, type SubHandleMetadata } from './subhandle.js';
|
|
7
|
+
import { DERIVATION_PATHS } from './crypto/derivation-paths.js';
|
|
8
|
+
import { normalizeName } from './canonical-name.js';
|
|
9
|
+
import { Attestation, type AttestationGrant } from './attestation.js';
|
|
5
10
|
|
|
6
|
-
|
|
11
|
+
function parseHexSeed(hex: string): Uint8Array {
|
|
12
|
+
if (!/^[0-9a-fA-F]{64}$/.test(hex)) {
|
|
13
|
+
throw new Error('Seed string must be 64 hex characters');
|
|
14
|
+
}
|
|
15
|
+
const out = new Uint8Array(32);
|
|
16
|
+
for (let i = 0; i < 32; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
17
|
+
return out;
|
|
18
|
+
}
|
|
7
19
|
|
|
8
20
|
/**
|
|
9
21
|
* Represents the root cryptographic identity derived from a seed phrase.
|
|
10
|
-
*
|
|
11
|
-
* An Identity is the foundation of the Me2em protocol. It allows for the
|
|
12
|
-
* hierarchical derivation of isolated {@link Handle}s
|
|
13
|
-
* (e.g., email, social, specific devices) from a
|
|
14
|
-
* ensuring zero cross-contamination of cryptographic material.
|
|
15
|
-
*
|
|
22
|
+
*
|
|
23
|
+
* An Identity is the foundation of the Me2em protocol. It allows for the
|
|
24
|
+
* hierarchical derivation of isolated {@link Handle}s and {@link SubHandle}s
|
|
25
|
+
* for different contexts (e.g., email, social, specific devices) from a
|
|
26
|
+
* single master seed, ensuring zero cross-contamination of cryptographic material.
|
|
27
|
+
*
|
|
28
|
+
* The Identity provides two derivation entry points:
|
|
29
|
+
* - {@link Identity.deriveHandle} — derives a top-level Handle.
|
|
30
|
+
* - {@link Identity.deriveSubHandle} — atomically derives a SubHandle by its
|
|
31
|
+
* full path (Handle name + SubHandle name). Used primarily for stateless
|
|
32
|
+
* session verification on the server side.
|
|
33
|
+
*
|
|
16
34
|
* @category Core Primitives
|
|
17
35
|
*/
|
|
18
36
|
export class Identity {
|
|
@@ -21,21 +39,27 @@ export class Identity {
|
|
|
21
39
|
|
|
22
40
|
private constructor(privateKey: Uint8Array) {
|
|
23
41
|
this.privateKey = privateKey;
|
|
24
|
-
this.publicKey = ed.getPublicKey(privateKey);
|
|
42
|
+
this.publicKey = ed.getPublicKey(privateKey);
|
|
25
43
|
}
|
|
26
44
|
|
|
27
|
-
|
|
45
|
+
/**
|
|
28
46
|
* Initializes a new Identity from a BIP39 mnemonic seed phrase or raw seed bytes.
|
|
29
|
-
*
|
|
30
|
-
* @param seed - A
|
|
47
|
+
*
|
|
48
|
+
* @param seed - A 32-byte raw Uint8Array seed, or a hex-encoded string of 32 bytes.
|
|
31
49
|
* @returns A Promise resolving to a new Identity instance.
|
|
32
|
-
* @throws {Error} If the provided seed is
|
|
50
|
+
* @throws {Error} If the provided seed is not exactly 32 bytes.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```ts
|
|
54
|
+
* const seed = await get32ByteSeedFromMnemonic('abandon abandon ... art');
|
|
55
|
+
* const identity = await Identity.fromSeed(seed);
|
|
56
|
+
* ```
|
|
33
57
|
*/
|
|
34
58
|
static async fromSeed(seed: Uint8Array | string): Promise<Identity> {
|
|
35
|
-
const seedBytes = typeof seed === 'string'
|
|
36
|
-
?
|
|
59
|
+
const seedBytes = typeof seed === 'string'
|
|
60
|
+
? parseHexSeed(seed)
|
|
37
61
|
: seed;
|
|
38
|
-
|
|
62
|
+
|
|
39
63
|
if (seedBytes.length !== 32) {
|
|
40
64
|
throw new Error('Invalid seed: must be 32 bytes');
|
|
41
65
|
}
|
|
@@ -43,47 +67,152 @@ export class Identity {
|
|
|
43
67
|
const key = hkdf(
|
|
44
68
|
sha256,
|
|
45
69
|
seedBytes,
|
|
46
|
-
new Uint8Array(0),
|
|
47
|
-
new TextEncoder().encode(
|
|
48
|
-
32
|
|
70
|
+
new Uint8Array(0),
|
|
71
|
+
new TextEncoder().encode(DERIVATION_PATHS.identity),
|
|
72
|
+
32
|
|
49
73
|
);
|
|
50
|
-
|
|
51
74
|
return new Identity(key);
|
|
52
75
|
}
|
|
53
76
|
|
|
54
|
-
|
|
77
|
+
/**
|
|
55
78
|
* Derives a new, cryptographically isolated {@link Handle} for a specific context.
|
|
56
|
-
*
|
|
57
|
-
* Each Handle is derived deterministically. The same name
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
* @param name - The context identifier (e.g., 'alice@example.com'
|
|
79
|
+
*
|
|
80
|
+
* Each Handle is derived deterministically. The same name will always produce
|
|
81
|
+
* the same Handle from the same Identity, but different names produce
|
|
82
|
+
* completely unrelated keys.
|
|
83
|
+
*
|
|
84
|
+
* @param name - The context identifier (e.g., `'alice@example.com'`, `'station-001'`).
|
|
62
85
|
* @param metadata - Optional metadata to associate with this Handle.
|
|
63
86
|
* @returns A Promise resolving to the derived Handle.
|
|
87
|
+
*
|
|
88
|
+
* @example
|
|
89
|
+
* ```ts
|
|
90
|
+
* const handle = await identity.deriveHandle('station-001', {
|
|
91
|
+
* displayName: 'Berlin Station #001'
|
|
92
|
+
* });
|
|
93
|
+
* ```
|
|
64
94
|
*/
|
|
65
95
|
async deriveHandle(name: string, metadata?: HandleMetadata): Promise<Handle> {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
// Используем sha256 для единообразия (или sha512, если нужно)
|
|
69
|
-
// Важно: используем тот же хэш, что и в спецификации
|
|
96
|
+
name = normalizeName(name);
|
|
97
|
+
const info = new TextEncoder().encode(DERIVATION_PATHS.handle(name));
|
|
70
98
|
const handleKey = hkdf(
|
|
71
|
-
sha256,
|
|
99
|
+
sha256,
|
|
72
100
|
this.privateKey,
|
|
73
101
|
new Uint8Array(0),
|
|
74
102
|
info,
|
|
75
103
|
32
|
|
76
104
|
);
|
|
77
|
-
|
|
78
105
|
return new Handle(handleKey, name, metadata);
|
|
79
106
|
}
|
|
80
107
|
|
|
108
|
+
/**
|
|
109
|
+
* Atomically derives a {@link SubHandle} from this Identity by its full path.
|
|
110
|
+
*
|
|
111
|
+
* This method performs the equivalent of:
|
|
112
|
+
* ```ts
|
|
113
|
+
* const handle = await identity.deriveHandle(handleName);
|
|
114
|
+
* const sub = await handle.deriveSubHandle(subName);
|
|
115
|
+
* ```
|
|
116
|
+
* but in a single call, without exposing the intermediate Handle.
|
|
117
|
+
*
|
|
118
|
+
* It is the **recommended entry point for stateless session verification**,
|
|
119
|
+
* because the server only needs the Identity and the path from the token.
|
|
120
|
+
*
|
|
121
|
+
* The resulting SubHandle is cryptographically identical to the one produced
|
|
122
|
+
* by `Handle.deriveSubHandle(subName)` on the same Identity.
|
|
123
|
+
*
|
|
124
|
+
* @param handleName - The parent Handle name.
|
|
125
|
+
* @param subName - The SubHandle name.
|
|
126
|
+
* @param metadata - Optional SubHandle metadata with constraints.
|
|
127
|
+
* @returns A Promise resolving to the derived SubHandle with path `[handleName, subName]`.
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```ts
|
|
131
|
+
* // Server-side stateless verification
|
|
132
|
+
* const sub = await identity.deriveSubHandle('station-001', 'connector-1');
|
|
133
|
+
* const publicKey = sub.getPublicKey();
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
async deriveSubHandle(
|
|
137
|
+
handleName: string,
|
|
138
|
+
subName: string,
|
|
139
|
+
metadata?: SubHandleMetadata
|
|
140
|
+
): Promise<SubHandle> {
|
|
141
|
+
handleName = normalizeName(handleName);
|
|
142
|
+
const subNameNorm = normalizeName(subName);
|
|
143
|
+
|
|
144
|
+
// Step 1: derive the intermediate Handle key (never exposed)
|
|
145
|
+
const handleInfo = new TextEncoder().encode(DERIVATION_PATHS.handle(handleName));
|
|
146
|
+
const handleKey = hkdf(
|
|
147
|
+
sha256,
|
|
148
|
+
this.privateKey,
|
|
149
|
+
new Uint8Array(0),
|
|
150
|
+
handleInfo,
|
|
151
|
+
32
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
// Step 2: derive the SubHandle key from the Handle key
|
|
155
|
+
const subInfo = new TextEncoder().encode(
|
|
156
|
+
DERIVATION_PATHS.subhandle(handleName, subNameNorm)
|
|
157
|
+
);
|
|
158
|
+
const subKey = hkdf(
|
|
159
|
+
sha256,
|
|
160
|
+
handleKey,
|
|
161
|
+
new Uint8Array(0),
|
|
162
|
+
subInfo,
|
|
163
|
+
32
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
const path = [handleName, subNameNorm];
|
|
167
|
+
return new SubHandle(subKey, subNameNorm, path, metadata);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Issues an attestation binding a derived Handle key to its name
|
|
172
|
+
* and grant. The subject public key is always derived internally —
|
|
173
|
+
* it is impossible to attest a foreign key, and the resulting
|
|
174
|
+
* `subjectId` always matches the handle reconstructed via
|
|
175
|
+
* {@link Identity.deriveSubHandle}.
|
|
176
|
+
*
|
|
177
|
+
* @param grant - Constraints verifiers will enforce for this handle
|
|
178
|
+
* and (via `subNamePatterns`) for the SubHandles it may attest.
|
|
179
|
+
* @returns An attestation signed by the Identity root key. Store it
|
|
180
|
+
* with the Handle — it is a public artifact, not a secret.
|
|
181
|
+
* @throws {Error} If the name is not canonicalizable.
|
|
182
|
+
* @throws {AttestationError} If the grant is invalid.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* ```ts
|
|
186
|
+
* const A = await identity.attestHandle('station-001', {
|
|
187
|
+
* audiences: ['ev-app.com'],
|
|
188
|
+
* scopes: ['charge:start', 'charge:stop', 'charge:status'],
|
|
189
|
+
* maxSessionTtl: 7200,
|
|
190
|
+
* subNamePatterns: ['connector-*', 'meter-*'],
|
|
191
|
+
* });
|
|
192
|
+
* ```
|
|
193
|
+
*/
|
|
194
|
+
async attestHandle(
|
|
195
|
+
name: string,
|
|
196
|
+
grant: AttestationGrant,
|
|
197
|
+
opts?: { ttlSeconds?: number; expiresAt?: number; jti?: string; now?: number }
|
|
198
|
+
): Promise<Attestation> {
|
|
199
|
+
const normalized = normalizeName(name);
|
|
200
|
+
const handle = await this.deriveHandle(normalized);
|
|
201
|
+
return Attestation.issue(
|
|
202
|
+
this.privateKey,
|
|
203
|
+
handle.getPublicKey(),
|
|
204
|
+
normalized,
|
|
205
|
+
grant,
|
|
206
|
+
opts ?? {}
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
|
|
81
210
|
/**
|
|
82
211
|
* Retrieves the public key of the root Identity.
|
|
83
|
-
*
|
|
212
|
+
*
|
|
84
213
|
* @returns A Uint8Array containing the 32-byte Ed25519 public key.
|
|
85
214
|
*/
|
|
86
215
|
getPublicKey(): Uint8Array {
|
|
87
216
|
return this.publicKey;
|
|
88
217
|
}
|
|
89
|
-
}
|
|
218
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
export { Identity } from './identity.js';
|
|
2
2
|
export { Handle, type HandleMetadata } from './handle.js';
|
|
3
|
-
export {
|
|
3
|
+
export { SubHandle, type SubHandleMetadata } from './subhandle.js';
|
|
4
|
+
export { Session, type SessionOptions, type SessionPayload, type RevocationChecker } from './session.js';
|
|
5
|
+
export { Attestation, AttestationError, ATTESTATION_TYPE, ATTESTATION_MAX_PAYLOAD, type AttestationGrant, type AttestationPayload, type AttestationErrorCode, type AttestationLevel } from './attestation.js';
|
|
4
6
|
export * as crypto from './crypto/index.js';
|
|
5
7
|
|
|
6
8
|
/**
|
|
@@ -14,8 +16,10 @@ export * as crypto from './crypto/index.js';
|
|
|
14
16
|
*
|
|
15
17
|
* ## Key Features
|
|
16
18
|
* - **Hierarchical Identities**: Derive multiple isolated {@link Handle}s from a single seed.
|
|
19
|
+
* - **SubHandle Leaf Nodes**: Hierarchical access control with MAX_DEPTH = 2.
|
|
17
20
|
* - **Stateless Auth**: Cryptographic proof without server-side session storage via {@link Session}.
|
|
18
21
|
* - **Zero-Knowledge Secrets**: Deterministic password derivation without storage.
|
|
22
|
+
* - **Revocation Support**: Optional {@link RevocationChecker} interface for session invalidation.
|
|
19
23
|
*
|
|
20
24
|
* @example Basic usage
|
|
21
25
|
* ```typescript
|
package/src/seed.ts
CHANGED
|
@@ -1,38 +1,41 @@
|
|
|
1
|
+
// seed.ts
|
|
1
2
|
import { generateMnemonic, mnemonicToSeed, validateMnemonic } from '@scure/bip39';
|
|
2
3
|
import { wordlist } from '@scure/bip39/wordlists/english';
|
|
3
4
|
import { sha256 } from './crypto/hkdf.js';
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
/**
|
|
7
|
+
* Seed strength in bits. 128 bits → 12 words, 256 bits → 24 words.
|
|
8
|
+
* Intermediate strengths (160/192/224 → 15/18/21 words) are valid
|
|
9
|
+
* BIP39 strengths but intentionally NOT exposed by this API; extend
|
|
10
|
+
* the union deliberately if ever needed (BREAKING for exhaustiveness
|
|
11
|
+
* checks).
|
|
12
|
+
*/
|
|
13
|
+
export type SeedStrength = 128 | 256;
|
|
6
14
|
|
|
7
15
|
/**
|
|
8
16
|
* Utilities for BIP39 mnemonic seed phrase generation and validation.
|
|
9
|
-
*
|
|
10
17
|
* These functions provide secure, deterministic seed phrase handling
|
|
11
18
|
* compatible with the BIP39 standard.
|
|
12
|
-
*
|
|
19
|
+
*
|
|
13
20
|
* @category Seed Utilities
|
|
14
21
|
* @packageDocumentation
|
|
15
22
|
*/
|
|
16
23
|
|
|
17
24
|
/**
|
|
18
25
|
* Generates a cryptographically secure random mnemonic seed phrase.
|
|
19
|
-
*
|
|
20
|
-
* @param strength - The entropy strength in bits.
|
|
26
|
+
*
|
|
27
|
+
* @param strength - The entropy strength in bits.
|
|
21
28
|
* - 128 bits = 12 words (standard security)
|
|
22
|
-
* - 160 bits = 15 words
|
|
23
|
-
* - 192 bits = 18 words
|
|
24
|
-
* - 224 bits = 21 words
|
|
25
29
|
* - 256 bits = 24 words (maximum security)
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
30
|
+
* @returns A space-separated mnemonic string split into an array of words.
|
|
31
|
+
*
|
|
29
32
|
* @example
|
|
30
|
-
* ```
|
|
31
|
-
* const mnemonic12 =
|
|
32
|
-
* // "abandon abandon
|
|
33
|
-
*
|
|
34
|
-
* const mnemonic24 =
|
|
35
|
-
* // "abandon abandon
|
|
33
|
+
* ```ts
|
|
34
|
+
* const mnemonic12 = generateSeedPhrase(128);
|
|
35
|
+
* // ["abandon", "abandon", ..., "art"]
|
|
36
|
+
*
|
|
37
|
+
* const mnemonic24 = generateSeedPhrase(256);
|
|
38
|
+
* // ["abandon", "abandon", ..., "zoo"] (24 words)
|
|
36
39
|
* ```
|
|
37
40
|
*/
|
|
38
41
|
export function generateSeedPhrase(strength: SeedStrength = 128): string[] {
|
|
@@ -45,42 +48,38 @@ export function generateSeedPhrase(strength: SeedStrength = 128): string[] {
|
|
|
45
48
|
|
|
46
49
|
/**
|
|
47
50
|
* Normalizes a mnemonic seed phrase by trimming whitespace and converting to lowercase.
|
|
48
|
-
*
|
|
49
|
-
* @param
|
|
50
|
-
* @returns A normalized
|
|
51
|
-
*
|
|
51
|
+
*
|
|
52
|
+
* @param seedPhrase - The mnemonic phrase to normalize (string or array of words).
|
|
53
|
+
* @returns A normalized array of lowercase words.
|
|
54
|
+
*
|
|
52
55
|
* @example
|
|
53
|
-
* ```
|
|
56
|
+
* ```ts
|
|
54
57
|
* const normalized = normalizeSeedPhrase(' ABANDON abandon ART ');
|
|
55
|
-
* // "abandon abandon art"
|
|
56
|
-
*
|
|
57
|
-
* const normalized2 = normalizeSeedPhrase(['abandon', ' ART ', 'zoo']);
|
|
58
|
-
* // "abandon art zoo"
|
|
58
|
+
* // ["abandon", "abandon", "art"]
|
|
59
59
|
* ```
|
|
60
60
|
*/
|
|
61
61
|
export function normalizeSeedPhrase(seedPhrase: string | string[]): string[] {
|
|
62
|
-
const words = Array.isArray(seedPhrase)
|
|
62
|
+
const words = Array.isArray(seedPhrase)
|
|
63
|
+
? seedPhrase
|
|
64
|
+
: seedPhrase.trim().split(/\s+/);
|
|
63
65
|
return words.map(word => word.toLowerCase().trim()).filter(word => word.length > 0);
|
|
64
66
|
}
|
|
65
67
|
|
|
66
68
|
/**
|
|
67
69
|
* Validates a mnemonic seed phrase against the BIP39 standard.
|
|
68
|
-
*
|
|
70
|
+
*
|
|
69
71
|
* Checks:
|
|
70
|
-
* - Correct word count (12
|
|
72
|
+
* - Correct word count (12 or 24 words)
|
|
71
73
|
* - All words exist in the BIP39 wordlist
|
|
72
74
|
* - Valid checksum
|
|
73
|
-
*
|
|
74
|
-
* @param
|
|
75
|
-
* @returns `
|
|
76
|
-
*
|
|
75
|
+
*
|
|
76
|
+
* @param words - The mnemonic phrase to validate.
|
|
77
|
+
* @returns An object with `isValid` flag and optional `error` message.
|
|
78
|
+
*
|
|
77
79
|
* @example
|
|
78
|
-
* ```
|
|
79
|
-
* const
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
* const isInvalid = await validateSeedPhrase('invalid word list ...');
|
|
83
|
-
* // false
|
|
80
|
+
* ```ts
|
|
81
|
+
* const result = validateSeedPhrase(['abandon', 'abandon', ..., 'art']);
|
|
82
|
+
* if (!result.isValid) console.error(result.error);
|
|
84
83
|
* ```
|
|
85
84
|
*/
|
|
86
85
|
export function validateSeedPhrase(words: string[]): { isValid: boolean; error?: string } {
|
|
@@ -88,51 +87,52 @@ export function validateSeedPhrase(words: string[]): { isValid: boolean; error?:
|
|
|
88
87
|
if (wordCount !== 12 && wordCount !== 24) {
|
|
89
88
|
return { isValid: false, error: `Seed phrase must be 12 or 24 words, got ${wordCount}` };
|
|
90
89
|
}
|
|
91
|
-
|
|
92
90
|
const normalized = normalizeSeedPhrase(words);
|
|
93
91
|
for (const word of normalized) {
|
|
94
92
|
if (!wordlist.includes(word)) {
|
|
95
93
|
return { isValid: false, error: `Invalid word: ${word}` };
|
|
96
94
|
}
|
|
97
95
|
}
|
|
98
|
-
|
|
99
96
|
const isValid = validateMnemonic(normalized.join(' '), wordlist);
|
|
100
97
|
return { isValid, error: isValid ? undefined : 'Invalid seed phrase checksum' };
|
|
101
98
|
}
|
|
102
99
|
|
|
103
100
|
/**
|
|
104
101
|
* Derives a 32-byte cryptographic seed from a BIP39 mnemonic phrase using PBKDF2.
|
|
105
|
-
*
|
|
106
102
|
* This is the standard BIP39 derivation function that converts a human-readable
|
|
107
|
-
* mnemonic into a binary seed suitable for key generation.
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
103
|
+
* mnemonic into a binary seed suitable for Ed25519 key generation.
|
|
104
|
+
*
|
|
105
|
+
* The resulting 64-byte BIP39 seed is hashed with SHA-256 to produce a
|
|
106
|
+
* deterministic 32-byte seed, as required by Ed25519.
|
|
107
|
+
*
|
|
108
|
+
* @param seedPhrase - The BIP39 mnemonic phrase (string or array of words).
|
|
109
|
+
* @param passphrase - Optional BIP39 passphrase ("25th word").
|
|
110
|
+
* Normalized via NFKC before use. An empty string (default)
|
|
111
|
+
* matches phrases without a passphrase. WARNING: the passphrase
|
|
112
|
+
* is NOT recoverable — a different passphrase silently derives a
|
|
113
|
+
* completely different seed with no error indication. Store it
|
|
114
|
+
* as carefully as the mnemonic itself.
|
|
111
115
|
* @returns A Promise resolving to a 32-byte Uint8Array seed.
|
|
112
|
-
*
|
|
116
|
+
*
|
|
113
117
|
* @example
|
|
114
|
-
* ```
|
|
118
|
+
* ```ts
|
|
115
119
|
* const seed = await get32ByteSeedFromMnemonic('abandon abandon ... art');
|
|
116
120
|
* // Uint8Array(32) [123, 45, 67, ...]
|
|
117
|
-
*
|
|
118
|
-
* const seedWithPassphrase = await get32ByteSeedFromMnemonic(
|
|
119
|
-
* 'abandon abandon ... art',
|
|
120
|
-
* 'mySecretPassphrase'
|
|
121
|
-
* );
|
|
122
|
-
* // Different seed even with same mnemonic
|
|
121
|
+
*
|
|
122
|
+
* const seedWithPassphrase = await get32ByteSeedFromMnemonic(words, 'my secret 25th word');
|
|
123
123
|
* ```
|
|
124
124
|
*/
|
|
125
|
-
export async function get32ByteSeedFromMnemonic(
|
|
125
|
+
export async function get32ByteSeedFromMnemonic(
|
|
126
|
+
seedPhrase: string | string[],
|
|
127
|
+
passphrase: string = ''
|
|
128
|
+
): Promise<Uint8Array> {
|
|
126
129
|
const words = normalizeSeedPhrase(seedPhrase);
|
|
127
130
|
const validation = validateSeedPhrase(words);
|
|
128
|
-
|
|
129
131
|
if (!validation.isValid) {
|
|
130
132
|
throw new Error(`Invalid seed phrase: ${validation.error}`);
|
|
131
133
|
}
|
|
132
|
-
|
|
133
134
|
const mnemonic = words.join(' ');
|
|
134
|
-
const seed64 = await mnemonicToSeed(mnemonic);
|
|
135
|
-
|
|
135
|
+
const seed64 = await mnemonicToSeed(mnemonic, passphrase.normalize('NFKC'));
|
|
136
136
|
// Hash the 64-byte seed to get a deterministic 32-byte seed for Ed25519
|
|
137
137
|
return sha256(seed64);
|
|
138
138
|
}
|