@me2em/core 0.6.0-alpha.1 → 0.7.0-alpha.2

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/src/handle.ts CHANGED
@@ -173,30 +173,30 @@ export class Handle {
173
173
  }
174
174
 
175
175
  /**
176
- * Issues an attestation for a derived SubHandle, binding its
177
- * derived key to the name and grant. Autonomous: requires only
178
- * this Handle's own key, no Identity and no network.
179
- *
180
- * The child key is derived internally, so the attestation's
181
- * `subjectId` always equals the key produced by
182
- * `identity.deriveSubHandle(this.name, subName)`.
183
- *
184
- * Note: this method does not check this Handle's own grant — it may
185
- * not have one (Mode 1). Nesting is enforced by verifiers in
186
- * `Session.verifyAttested` (a child grant exceeding the parent's is
187
- * rejected with `SCOPE_EXCEEDED`/`TTL_EXCEEDED` at level ROOT).
188
- *
189
- * @example
190
- * ```ts
191
- * const B = await station.attestSubHandle('connector-ccs', {
192
- * audiences: ['ev-app.com'],
193
- * scopes: ['charge:start', 'charge:stop'],
194
- * maxSessionTtl: 7200,
195
- * }, { ttlSeconds: 1800 });
196
- * // Ship [A.token, B.token] together with the session token.
197
- * ```
198
- */
199
- async attestSubHandle(
176
+ * Issues an attestation for a derived SubHandle, binding its
177
+ * derived key to the name and grant. Autonomous: requires only
178
+ * this Handle's own key, no Identity and no network.
179
+ *
180
+ * The child key is derived internally, so the attestation's
181
+ * `subjectId` always equals the key produced by
182
+ * `identity.deriveSubHandle(this.name, subName)`.
183
+ *
184
+ * Note: this method does not check this Handle's own grant — it may
185
+ * not have one (Mode 1). Nesting is enforced by verifiers in
186
+ * `Session.verifyAttested` (a child grant exceeding the parent's is
187
+ * rejected with `SCOPE_EXCEEDED`/`TTL_EXCEEDED` at level ROOT).
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * const B = await station.attestSubHandle('connector-ccs', {
192
+ * audiences: ['ev-app.com'],
193
+ * scopes: ['charge:start', 'charge:stop'],
194
+ * maxSessionTtl: 7200,
195
+ * }, { ttlSeconds: 1800 });
196
+ * // Ship [A.token, B.token] together with the session token.
197
+ * ```
198
+ */
199
+ async attestSubHandle(
200
200
  subName: string,
201
201
  grant: AttestationGrant,
202
202
  opts?: { ttlSeconds?: number; expiresAt?: number; jti?: string; now?: number }
@@ -253,14 +253,9 @@ export class Handle {
253
253
  *
254
254
  * @example
255
255
  * ```ts
256
- * // On the drone (Handle side):
257
- * const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
258
- * const encrypted = await encryptAESGCM(telemetry, channelKey);
259
- *
260
- * // On the control center (Identity side):
261
- * const droneHandle = await centerIdentity.deriveHandle('drone-001');
256
+ * // AES-GCM helpers are application-side; the protocol provides
257
+ * // only the key:
262
258
  * const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
263
- * const decrypted = await decryptAESGCM(encrypted, channelKey);
264
259
  * ```
265
260
  */
266
261
  deriveChannelKey(context: string): Uint8Array {
package/src/identity.ts CHANGED
@@ -168,30 +168,30 @@ export class Identity {
168
168
  }
169
169
 
170
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(
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
195
  name: string,
196
196
  grant: AttestationGrant,
197
197
  opts?: { ttlSeconds?: number; expiresAt?: number; jti?: string; now?: number }
package/src/index.ts CHANGED
@@ -35,5 +35,7 @@ export {
35
35
  normalizeSeedPhrase,
36
36
  validateSeedPhrase,
37
37
  get32ByteSeedFromMnemonic,
38
- type SeedStrength
38
+ type SeedStrength,
39
+ type SeedValidationResult
39
40
  } from './seed.js';
41
+ export { wordlist } from '@scure/bip39/wordlists/english';
package/src/seed.ts CHANGED
@@ -1,9 +1,16 @@
1
- // seed.ts
1
+ // packages/core/src/seed.ts
2
2
  import { generateMnemonic, mnemonicToSeed, validateMnemonic } from '@scure/bip39';
3
3
  import { wordlist } from '@scure/bip39/wordlists/english';
4
4
  import { sha256 } from './crypto/hkdf.js';
5
5
 
6
- export type SeedStrength = 128 | 256; // 128 bits = 12 words, 256 bits = 24 words
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;
7
14
 
8
15
  /**
9
16
  * Utilities for BIP39 mnemonic seed phrase generation and validation.
@@ -19,9 +26,6 @@ export type SeedStrength = 128 | 256; // 128 bits = 12 words, 256 bits = 24 word
19
26
  *
20
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
30
  * @returns A space-separated mnemonic string split into an array of words.
27
31
  *
@@ -61,36 +65,69 @@ export function normalizeSeedPhrase(seedPhrase: string | string[]): string[] {
61
65
  return words.map(word => word.toLowerCase().trim()).filter(word => word.length > 0);
62
66
  }
63
67
 
68
+ export interface SeedValidationResult {
69
+ isValid: boolean;
70
+ error?: string;
71
+ wordCount: number;
72
+ invalidWords: string[];
73
+ }
74
+
64
75
  /**
65
- * Validates a mnemonic seed phrase against the BIP39 standard.
76
+ * Validates a mnemonic seed phrase against the BIP39 standard with
77
+ * detailed feedback.
66
78
  *
67
- * Checks:
68
- * - Correct word count (12 or 24 words)
69
- * - All words exist in the BIP39 wordlist
70
- * - Valid checksum
79
+ * Checks (in order):
80
+ * 1. Word count must be 12 or 24.
81
+ * 2. Each word must exist in the BIP39 English wordlist.
82
+ * 3. Checksum must be valid.
71
83
  *
72
84
  * @param words - The mnemonic phrase to validate.
73
- * @returns An object with `isValid` flag and optional `error` message.
85
+ * @returns A result object with isValid, error, wordCount, and invalidWords.
74
86
  *
75
87
  * @example
76
88
  * ```ts
77
89
  * const result = validateSeedPhrase(['abandon', 'abandon', ..., 'art']);
78
- * if (!result.isValid) console.error(result.error);
90
+ * if (!result.isValid) {
91
+ * console.error(result.error);
92
+ * console.log('Invalid words:', result.invalidWords);
93
+ * }
79
94
  * ```
80
95
  */
81
- export function validateSeedPhrase(words: string[]): { isValid: boolean; error?: string } {
82
- const wordCount = words.length;
83
- if (wordCount !== 12 && wordCount !== 24) {
84
- return { isValid: false, error: `Seed phrase must be 12 or 24 words, got ${wordCount}` };
85
- }
96
+ export function validateSeedPhrase(words: string[]): SeedValidationResult {
86
97
  const normalized = normalizeSeedPhrase(words);
98
+ const invalidWords: string[] = [];
99
+
87
100
  for (const word of normalized) {
88
101
  if (!wordlist.includes(word)) {
89
- return { isValid: false, error: `Invalid word: ${word}` };
102
+ invalidWords.push(word);
90
103
  }
91
104
  }
105
+
106
+ if (normalized.length !== 12 && normalized.length !== 24) {
107
+ return {
108
+ isValid: false,
109
+ error: `Seed phrase must be 12 or 24 words, got ${normalized.length}`,
110
+ wordCount: normalized.length,
111
+ invalidWords,
112
+ };
113
+ }
114
+
115
+ if (invalidWords.length > 0) {
116
+ return {
117
+ isValid: false,
118
+ error: `Invalid words found: ${invalidWords.join(', ')}`,
119
+ wordCount: normalized.length,
120
+ invalidWords,
121
+ };
122
+ }
123
+
92
124
  const isValid = validateMnemonic(normalized.join(' '), wordlist);
93
- return { isValid, error: isValid ? undefined : 'Invalid seed phrase checksum' };
125
+ return {
126
+ isValid,
127
+ error: isValid ? undefined : 'Invalid seed phrase checksum',
128
+ wordCount: normalized.length,
129
+ invalidWords: [],
130
+ };
94
131
  }
95
132
 
96
133
  /**
@@ -102,16 +139,25 @@ export function validateSeedPhrase(words: string[]): { isValid: boolean; error?:
102
139
  * deterministic 32-byte seed, as required by Ed25519.
103
140
  *
104
141
  * @param seedPhrase - The BIP39 mnemonic phrase (string or array of words).
142
+ * @param passphrase - Optional BIP39 passphrase ("25th word").
143
+ * Normalized via NFKC before use. An empty string (default)
144
+ * matches phrases without a passphrase. WARNING: the passphrase
145
+ * is NOT recoverable — a different passphrase silently derives a
146
+ * completely different seed with no error indication. Store it
147
+ * as carefully as the mnemonic itself.
105
148
  * @returns A Promise resolving to a 32-byte Uint8Array seed.
106
149
  *
107
150
  * @example
108
151
  * ```ts
109
152
  * const seed = await get32ByteSeedFromMnemonic('abandon abandon ... art');
110
153
  * // Uint8Array(32) [123, 45, 67, ...]
154
+ *
155
+ * const seedWithPassphrase = await get32ByteSeedFromMnemonic(words, 'my secret 25th word');
111
156
  * ```
112
157
  */
113
158
  export async function get32ByteSeedFromMnemonic(
114
- seedPhrase: string | string[]
159
+ seedPhrase: string | string[],
160
+ passphrase: string = ''
115
161
  ): Promise<Uint8Array> {
116
162
  const words = normalizeSeedPhrase(seedPhrase);
117
163
  const validation = validateSeedPhrase(words);
@@ -119,7 +165,7 @@ export async function get32ByteSeedFromMnemonic(
119
165
  throw new Error(`Invalid seed phrase: ${validation.error}`);
120
166
  }
121
167
  const mnemonic = words.join(' ');
122
- const seed64 = await mnemonicToSeed(mnemonic);
168
+ const seed64 = await mnemonicToSeed(mnemonic, passphrase.normalize('NFKC'));
123
169
  // Hash the 64-byte seed to get a deterministic 32-byte seed for Ed25519
124
170
  return sha256(seed64);
125
171
  }
package/src/session.ts CHANGED
@@ -396,48 +396,48 @@ export class Session {
396
396
  }
397
397
 
398
398
  /**
399
- * Verifies a session token together with its attestation chain
400
- * (Mode 2 - using an attestation chain) — for verifiers that hold only the root PUBLIC key.
401
- *
402
- * The chain contains serialized attestations, root first:
403
- * - handle sessions: `[attestHandle_token]` (length 1)
404
- * - subhandle sessions: `[attestHandle_token, attestSubHandle_token]`
405
- * (length 2)
406
- *
407
- * Enforced, in order: token structure and required fields (including
408
- * `iat`); audience; session time (±30 s skew); chain shape; parent
409
- * signature against `rootPublicKey`; parent validity and revocation;
410
- * for subhandle sessions — child signature against the parent's
411
- * `subjectId`, child validity/revocation, name/path agreement,
412
- * wildcard permitting, `hId == child.subjectId`, and grant nesting
413
- * (child scopes ⊆ parent scopes, child maxTtl ≤ parent maxTtl);
414
- * session vs the effective grant (scopes, audiences, TTL); session
415
- * expiry against the earliest attestation expiry; session signature
416
- * against `hId`; session revocation — last.
417
- *
418
- * @param attestationChain - Attestation tokens, root first; length
419
- * must match the session kind (1 for Handle, 2 for SubHandle).
420
- * @param revocationChecker - Optional; consulted for attestation
421
- * `jti` values (each chain level) and the session `jti`.
422
- * @returns The verified session.
423
- * @throws {AttestationError} With `code` and `level` identifying the
424
- * failed layer — integrate on these fields, not on message text.
425
- *
426
- * @example
427
- * ```ts
428
- * const A = await identity.attestHandle('station-001', grantA);
429
- * const sub = await station.deriveSubHandle('connector-ccs');
430
- * const B = await station.attestSubHandle('connector-ccs', grantB);
431
- * const session = await Session.create(sub, {
432
- * audience: 'ev-app.com', scopes: ['charge:start'], ttl: 1800,
433
- * });
434
- * const verified = await Session.verifyAttested(
435
- * session.token, identity.getPublicKey(), [A.token, B.token],
436
- * 'ev-app.com',
437
- * );
438
- * ```
439
- */
440
- static async verifyAttested(
399
+ * Verifies a session token together with its attestation chain
400
+ * (Mode 2 - using an attestation chain) — for verifiers that hold only the root PUBLIC key.
401
+ *
402
+ * The chain contains serialized attestations, root first:
403
+ * - handle sessions: `[attestHandle_token]` (length 1)
404
+ * - subhandle sessions: `[attestHandle_token, attestSubHandle_token]`
405
+ * (length 2)
406
+ *
407
+ * Enforced, in order: token structure and required fields (including
408
+ * `iat`); audience; session time (±30 s skew); chain shape; parent
409
+ * signature against `rootPublicKey`; parent validity and revocation;
410
+ * for subhandle sessions — child signature against the parent's
411
+ * `subjectId`, child validity/revocation, name/path agreement,
412
+ * wildcard permitting, `hId == child.subjectId`, and grant nesting
413
+ * (child scopes ⊆ parent scopes, child maxTtl ≤ parent maxTtl);
414
+ * session vs the effective grant (scopes, audiences, TTL); session
415
+ * expiry against the earliest attestation expiry; session signature
416
+ * against `hId`; session revocation — last.
417
+ *
418
+ * @param attestationChain - Attestation tokens, root first; length
419
+ * must match the session kind (1 for Handle, 2 for SubHandle).
420
+ * @param revocationChecker - Optional; consulted for attestation
421
+ * `jti` values (each chain level) and the session `jti`.
422
+ * @returns The verified session.
423
+ * @throws {AttestationError} With `code` and `level` identifying the
424
+ * failed layer — integrate on these fields, not on message text.
425
+ *
426
+ * @example
427
+ * ```ts
428
+ * const A = await identity.attestHandle('station-001', grantA);
429
+ * const sub = await station.deriveSubHandle('connector-ccs');
430
+ * const B = await station.attestSubHandle('connector-ccs', grantB);
431
+ * const session = await Session.create(sub, {
432
+ * audience: 'ev-app.com', scopes: ['charge:start'], ttl: 1800,
433
+ * });
434
+ * const verified = await Session.verifyAttested(
435
+ * session.token, identity.getPublicKey(), [A.token, B.token],
436
+ * 'ev-app.com',
437
+ * );
438
+ * ```
439
+ */
440
+ static async verifyAttested(
441
441
  token: string,
442
442
  rootPublicKey: Uint8Array,
443
443
  attestationChain: string[],
package/src/subhandle.ts CHANGED
@@ -43,6 +43,30 @@ export interface SubHandleMetadata extends HandleMetadata {
43
43
  expiresAt?: number;
44
44
  }
45
45
 
46
+ /**
47
+ * Extracts only display-safe fields for the base Handle metadata.
48
+ * Constraint fields stay in SubHandle's own storage and must never
49
+ * leak through Handle.getMetadata().
50
+ */
51
+ function extractDisplayFields(
52
+ meta?: SubHandleMetadata
53
+ ): HandleMetadata | undefined {
54
+ if (!meta) return undefined;
55
+ const display: HandleMetadata = {};
56
+ if (meta.displayName !== undefined) display.displayName = meta.displayName;
57
+ if (meta.avatar !== undefined) display.avatar = meta.avatar;
58
+ // copy any other custom fields, but never the constraint ones
59
+ const CONSTRAINT_KEYS = new Set([
60
+ 'allowedAudiences', 'allowedScopes', 'maxSessionTtl', 'expiresAt',
61
+ ]);
62
+ for (const [k, v] of Object.entries(meta)) {
63
+ if (!CONSTRAINT_KEYS.has(k)) {
64
+ (display as Record<string, unknown>)[k] = v;
65
+ }
66
+ }
67
+ return display;
68
+ }
69
+
46
70
  /**
47
71
  * Represents a context-isolated child Handle in the Me2em hierarchy.
48
72
  *
@@ -83,7 +107,7 @@ export class SubHandle extends Handle {
83
107
  path: string[],
84
108
  subMetadata?: SubHandleMetadata
85
109
  ) {
86
- super(privateKey, name, subMetadata);
110
+ super(privateKey, name, extractDisplayFields(subMetadata));
87
111
 
88
112
  if (path.length !== 2) {
89
113
  throw new Error(
@@ -156,10 +180,10 @@ export class SubHandle extends Handle {
156
180
  getSubMetadata(): SubHandleMetadata {
157
181
  return {
158
182
  ...this._subMetadata,
159
- allowedAudiences: this._subMetadata.allowedAudiences
183
+ allowedAudiences: this._subMetadata.allowedAudiences !== undefined
160
184
  ? [...this._subMetadata.allowedAudiences]
161
185
  : undefined,
162
- allowedScopes: this._subMetadata.allowedScopes
186
+ allowedScopes: this._subMetadata.allowedScopes !== undefined
163
187
  ? [...this._subMetadata.allowedScopes]
164
188
  : undefined,
165
189
  };