@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.
Files changed (70) hide show
  1. package/README.md +294 -546
  2. package/dist/attestation.d.ts +151 -0
  3. package/dist/attestation.d.ts.map +1 -0
  4. package/dist/attestation.js +279 -0
  5. package/dist/attestation.js.map +1 -0
  6. package/dist/canonical-name.d.ts +3 -0
  7. package/dist/canonical-name.d.ts.map +1 -0
  8. package/dist/canonical-name.js +12 -0
  9. package/dist/canonical-name.js.map +1 -0
  10. package/dist/crypto/derivation-paths.d.ts +41 -0
  11. package/dist/crypto/derivation-paths.d.ts.map +1 -0
  12. package/dist/crypto/derivation-paths.js +50 -0
  13. package/dist/crypto/derivation-paths.js.map +1 -0
  14. package/dist/crypto/ed25519.d.ts +48 -8
  15. package/dist/crypto/ed25519.d.ts.map +1 -1
  16. package/dist/crypto/ed25519.js +63 -8
  17. package/dist/crypto/ed25519.js.map +1 -1
  18. package/dist/crypto/hkdf.d.ts.map +1 -1
  19. package/dist/crypto/hkdf.js +1 -0
  20. package/dist/crypto/hkdf.js.map +1 -1
  21. package/dist/crypto/index.d.ts +1 -0
  22. package/dist/crypto/index.d.ts.map +1 -1
  23. package/dist/crypto/index.js +2 -0
  24. package/dist/crypto/index.js.map +1 -1
  25. package/dist/crypto/init.d.ts.map +1 -1
  26. package/dist/crypto/init.js +1 -0
  27. package/dist/crypto/init.js.map +1 -1
  28. package/dist/handle.d.ts +149 -35
  29. package/dist/handle.d.ts.map +1 -1
  30. package/dist/handle.js +180 -40
  31. package/dist/handle.js.map +1 -1
  32. package/dist/identity.d.ts +99 -19
  33. package/dist/identity.d.ts.map +1 -1
  34. package/dist/identity.js +128 -32
  35. package/dist/identity.js.map +1 -1
  36. package/dist/index.d.ts +5 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +4 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/seed.d.ts +38 -39
  41. package/dist/seed.d.ts.map +1 -1
  42. package/dist/seed.js +36 -41
  43. package/dist/seed.js.map +1 -1
  44. package/dist/session.d.ts +207 -17
  45. package/dist/session.d.ts.map +1 -1
  46. package/dist/session.js +428 -11
  47. package/dist/session.js.map +1 -1
  48. package/dist/subhandle.d.ts +126 -0
  49. package/dist/subhandle.d.ts.map +1 -0
  50. package/dist/subhandle.js +182 -0
  51. package/dist/subhandle.js.map +1 -0
  52. package/dist/util.d.ts +9 -0
  53. package/dist/util.d.ts.map +1 -0
  54. package/dist/util.js +34 -0
  55. package/dist/util.js.map +1 -0
  56. package/package.json +3 -3
  57. package/src/attestation.ts +364 -0
  58. package/src/canonical-name.ts +12 -0
  59. package/src/crypto/derivation-paths.ts +56 -0
  60. package/src/crypto/ed25519.ts +82 -8
  61. package/src/crypto/hkdf.ts +2 -0
  62. package/src/crypto/index.ts +3 -1
  63. package/src/crypto/init.ts +1 -0
  64. package/src/handle.ts +227 -42
  65. package/src/identity.ts +164 -35
  66. package/src/index.ts +5 -1
  67. package/src/seed.ts +59 -59
  68. package/src/session.ts +637 -24
  69. package/src/subhandle.ts +254 -0
  70. package/src/util.ts +35 -0
package/dist/handle.js CHANGED
@@ -1,13 +1,22 @@
1
+ // handle.ts
1
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';
5
+ import { ed25519, x25519 } from '@noble/curves/ed25519.js';
6
+ import { normalizeName } from './canonical-name.js';
7
+ import { DERIVATION_PATHS } from './crypto/derivation-paths.js';
8
+ import { Attestation } from './attestation.js';
4
9
  /**
5
10
  * Represents a context-specific cryptographic handle derived from an {@link Identity}.
6
11
  *
7
12
  * A Handle encapsulates a private key tied to a specific name (context).
8
13
  * It provides methods for signing data, verifying signatures, and deriving
9
- * secondary secrets (like passwords or channel keys) without ever exposing
10
- * the underlying private key.
14
+ * secondary secrets (passwords, channel keys, shared secrets) without ever
15
+ * exposing the underlying private key.
16
+ *
17
+ * A Handle can also derive {@link SubHandle}s for hierarchical access control
18
+ * (e.g., an IoT device deriving keys for its components). The private key
19
+ * **never leaves the Handle** — derivation is performed internally using HKDF.
11
20
  *
12
21
  * @category Core Primitives
13
22
  */
@@ -17,20 +26,27 @@ export class Handle {
17
26
  _name;
18
27
  _metadata;
19
28
  /**
20
- * Creates a new Handle instance.
21
- * @internal Typically created via {@link Identity.deriveHandle}.
22
- *
23
- * @param privateKey - The 32-byte Ed25519 private key for this handle.
24
- * @param name - The context name this handle represents.
25
- * @param metadata - Optional metadata associated with this handle.
26
- */
29
+ * Creates a new Handle instance.
30
+ *
31
+ * @internal Typically created via {@link Identity.deriveHandle} or
32
+ * {@link Handle.deriveSubHandle}. Direct construction is discouraged.
33
+ *
34
+ * @param privateKey - The 32-byte Ed25519 private key for this handle.
35
+ * @param name - The context name this handle represents.
36
+ * @param metadata - Optional metadata associated with this handle.
37
+ */
27
38
  constructor(privateKey, name, metadata) {
28
39
  this.privateKey = privateKey;
29
40
  this.publicKey = ed.getPublicKey(privateKey);
30
41
  this._name = name;
31
42
  this._metadata = metadata;
32
43
  }
33
- /** @returns The unique context identifier for this Handle. */
44
+ /**
45
+ * Returns a URL-safe Base64-encoded identifier for this Handle,
46
+ * derived from its public key.
47
+ *
48
+ * @returns A unique, URL-safe string identifier.
49
+ */
34
50
  getId() {
35
51
  return btoa(String.fromCharCode(...this.publicKey))
36
52
  .replace(/\+/g, '-')
@@ -38,43 +54,127 @@ export class Handle {
38
54
  .replace(/=+$/, '');
39
55
  }
40
56
  /**
41
- * Cryptographically signs arbitrary data using the Handle's private key.
42
- * @param data - The data to be signed, as a Uint8Array.
43
- * @returns A Promise resolving to the Ed25519 signature as a Uint8Array.
44
- */
57
+ * Cryptographically signs arbitrary data using the Handle's private key.
58
+ *
59
+ * @param data - The data to be signed, as a Uint8Array.
60
+ * @returns A Promise resolving to the Ed25519 signature as a Uint8Array.
61
+ */
45
62
  async sign(data) {
46
63
  return ed.sign(data, this.privateKey);
47
64
  }
48
65
  /**
49
- * Verifies an Ed25519 signature against the provided data and public key.
50
- * @param signature - The signature to verify (Uint8Array).
51
- * @param data - The original data that was signed (Uint8Array).
52
- * @param publicKey - The public key to verify against (Uint8Array).
53
- * @returns A Promise resolving to true if the signature is valid, false otherwise.
54
- */
66
+ * Verifies an Ed25519 signature against the provided data and public key.
67
+ *
68
+ * @param signature - The signature to verify (Uint8Array).
69
+ * @param data - The original data that was signed (Uint8Array).
70
+ * @param publicKey - The public key to verify against (Uint8Array).
71
+ * @returns A Promise resolving to `true` if the signature is valid, `false` otherwise.
72
+ */
55
73
  static async verify(signature, data, publicKey) {
56
74
  return ed.verify(signature, data, publicKey);
57
75
  }
58
76
  /** @returns The context name associated with this Handle. */
59
- getName() { return this._name; }
77
+ getName() {
78
+ return this._name;
79
+ }
60
80
  /** @returns The metadata object associated with this Handle. */
61
- getMetadata() { return this._metadata; }
81
+ getMetadata() {
82
+ return this._metadata;
83
+ }
62
84
  /** @returns A Uint8Array containing the 32-byte Ed25519 public key. */
63
- getPublicKey() { return this.publicKey; }
85
+ getPublicKey() {
86
+ return this.publicKey;
87
+ }
88
+ /** @returns The derivation path, or undefined for Handle (only SubHandle has a path). */
89
+ getPath() {
90
+ return undefined;
91
+ }
92
+ /**
93
+ * Validates session options against this Handle's constraints.
94
+ * Handle has no constraints.
95
+ */
96
+ validateSessionOptions(_options) { }
64
97
  /**
65
- * Deterministically derives a secret (e.g., a password or API key) for a specific service context.
66
- * The private key NEVER leaves this class, ensuring maximum security.
98
+ * Derives a {@link SubHandle} from this Handle.
99
+ *
100
+ * This is the **autonomous entry point** for IoT devices and other contexts
101
+ * where the Identity is not available locally. The Handle uses its own
102
+ * private key internally (it never leaves the class) to derive a child key
103
+ * via HKDF-SHA256.
104
+ *
105
+ * The resulting SubHandle is cryptographically identical to the one produced
106
+ * by `Identity.deriveSubHandle(this.name, subName)`.
67
107
  *
68
- * @param context - A unique identifier for the service (e.g., 'google', 'github', 'wifi-router').
69
- * @param length - Length of the derived raw bytes (default: 16 bytes = ~22 chars base64url).
108
+ * @param name - The SubHandle name (will be normalized).
109
+ * @param metadata - Optional SubHandle metadata with constraints.
110
+ * @returns A Promise resolving to the derived SubHandle with path `[this.name, name]`.
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * // On an IoT device (no Identity available)
115
+ * const connector = await stationHandle.deriveSubHandle('connector-1', {
116
+ * allowedScopes: ['charge:start'],
117
+ * maxSessionTtl: 3600
118
+ * });
119
+ * ```
120
+ */
121
+ async deriveSubHandle(name, metadata) {
122
+ const normalizedName = normalizeName(name);
123
+ const info = new TextEncoder().encode(DERIVATION_PATHS.subhandle(this._name, normalizedName));
124
+ // The private key is used internally and never leaves this class.
125
+ const subKey = hkdf(sha256, this.privateKey, new Uint8Array(0), info, 32);
126
+ const path = [this._name, normalizedName];
127
+ const { SubHandle: SubHandleClass } = await import('./subhandle.js');
128
+ return new SubHandleClass(subKey, normalizedName, path, metadata);
129
+ }
130
+ /**
131
+ * Issues an attestation for a derived SubHandle, binding its
132
+ * derived key to the name and grant. Autonomous: requires only
133
+ * this Handle's own key, no Identity and no network.
134
+ *
135
+ * The child key is derived internally, so the attestation's
136
+ * `subjectId` always equals the key produced by
137
+ * `identity.deriveSubHandle(this.name, subName)`.
138
+ *
139
+ * Note: this method does not check this Handle's own grant — it may
140
+ * not have one (Mode 1). Nesting is enforced by verifiers in
141
+ * `Session.verifyAttested` (a child grant exceeding the parent's is
142
+ * rejected with `SCOPE_EXCEEDED`/`TTL_EXCEEDED` at level ROOT).
143
+ *
144
+ * @example
145
+ * ```ts
146
+ * const B = await station.attestSubHandle('connector-ccs', {
147
+ * audiences: ['ev-app.com'],
148
+ * scopes: ['charge:start', 'charge:stop'],
149
+ * maxSessionTtl: 7200,
150
+ * }, { ttlSeconds: 1800 });
151
+ * // Ship [A.token, B.token] together with the session token.
152
+ * ```
153
+ */
154
+ async attestSubHandle(subName, grant, opts) {
155
+ const normalized = normalizeName(subName);
156
+ const sub = await this.deriveSubHandle(normalized);
157
+ return Attestation.issue(this.privateKey, sub.getPublicKey(), normalized, grant, opts ?? {});
158
+ }
159
+ /**
160
+ * Deterministically derives a secret (e.g., a password or API key) for a
161
+ * specific service context.
162
+ *
163
+ * The private key **never leaves this class**, ensuring maximum security.
164
+ *
165
+ * @param context - A unique identifier for the service (e.g., `'google'`, `'github'`).
166
+ * @param length - Length of the derived raw bytes (default: 16 bytes ≈ 22 chars base64url).
70
167
  * @returns A URL-safe base64 string suitable for use as a strong password.
168
+ *
169
+ * @example
170
+ * ```ts
171
+ * const githubPassword = handle.derivePassword('github', 20);
172
+ * ```
71
173
  */
72
174
  derivePassword(context, length = 16) {
73
175
  const salt = new TextEncoder().encode(`me2em/secret/${context.toLowerCase().trim()}`);
74
176
  const info = new TextEncoder().encode('me2em/secret/v1');
75
- // HKDF использует this.privateKey напрямую, не экспортируя его
76
177
  const secretBytes = hkdf(sha256, this.privateKey, salt, info, length);
77
- // Конвертация в URL-safe base64 (аналогично getId)
78
178
  return btoa(String.fromCharCode(...secretBytes))
79
179
  .replace(/\+/g, '-')
80
180
  .replace(/\//g, '_')
@@ -85,23 +185,20 @@ export class Handle {
85
185
  * the Identity (controller) and this Handle (device/context).
86
186
  *
87
187
  * Both parties can independently compute this key because:
88
- * 1. The Handle possesses its own private key directly.
89
- * 2. The Identity can derive the same private key via `identity.deriveHandle(name)`.
188
+ * - The Handle possesses its own private key directly.
189
+ * - The Identity can derive the same private key via `identity.deriveHandle(name)`.
90
190
  *
91
191
  * This enables zero-knowledge encrypted channels without key exchange protocols.
92
192
  *
93
- * @param context - Channel identifier for domain separation (e.g., 'drone-001', 'session-abc'). Both parties MUST use the same context.
193
+ * @param context - Channel identifier for domain separation (e.g., `'drone-001'`).
194
+ * Both parties **MUST** use the same context.
94
195
  * @returns A 32-byte Uint8Array suitable for AES-256-GCM encryption.
95
- * @example
96
- * ```typescript
97
- * // On the drone (Handle side):
98
- * const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
99
- * const encrypted = await encryptAESGCM(telemetry, channelKey);
100
196
  *
101
- * // On the control center (Identity side):
102
- * const droneHandle = await centerIdentity.deriveHandle('drone-001');
197
+ * @example
198
+ * ```ts
199
+ * // AES-GCM helpers are application-side; the protocol provides
200
+ * // only the key:
103
201
  * const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
104
- * const decrypted = await decryptAESGCM(encrypted, channelKey);
105
202
  * ```
106
203
  */
107
204
  deriveChannelKey(context) {
@@ -109,5 +206,48 @@ export class Handle {
109
206
  const info = new TextEncoder().encode('me2em/channel/v1');
110
207
  return hkdf(sha256, this.privateKey, salt, info, 32);
111
208
  }
209
+ /**
210
+ * Derives a shared secret using ECDH (X25519) for P2P key exchange.
211
+ *
212
+ * Converts the Ed25519 keypair to X25519 for Diffie-Hellman key agreement,
213
+ * then applies HKDF-SHA256 to produce a clean 32-byte channel key.
214
+ *
215
+ * @param otherPublicKey - The Ed25519 public key of the other party (32 bytes).
216
+ * @returns A Promise resolving to a 32-byte shared secret suitable for AES-256-GCM.
217
+ *
218
+ * @example
219
+ * ```ts
220
+ * const aliceShared = await aliceHandle.deriveSharedSecret(bobHandle.getPublicKey());
221
+ * const bobShared = await bobHandle.deriveSharedSecret(aliceHandle.getPublicKey());
222
+ * // aliceShared === bobShared
223
+ * ```
224
+ */
225
+ async deriveSharedSecret(otherPublicKey) {
226
+ const myPrivBytes = this.privateKey;
227
+ const otherPubBytes = otherPublicKey;
228
+ if (myPrivBytes.length !== 32) {
229
+ throw new Error('Handle private key must be 32 bytes');
230
+ }
231
+ if (otherPubBytes.length !== 32) {
232
+ throw new Error('Public key must be 32 bytes');
233
+ }
234
+ const x25519Priv = ed25519.utils.toMontgomerySecret(myPrivBytes);
235
+ const x25519Pub = ed25519.utils.toMontgomery(otherPubBytes);
236
+ const rawSharedSecret = x25519.getSharedSecret(x25519Priv, x25519Pub);
237
+ // Canonical, order-independent binding of both peers' public keys.
238
+ const myPub = this.getPublicKey();
239
+ const peers = [myPub, otherPubBytes].sort((a, b) => {
240
+ for (let i = 0; i < 32; i++) {
241
+ if (a[i] !== b[i])
242
+ return a[i] - b[i];
243
+ }
244
+ return 0;
245
+ });
246
+ const bound = new Uint8Array(64);
247
+ bound.set(peers[0], 0);
248
+ bound.set(peers[1], 32);
249
+ const info = new TextEncoder().encode(DERIVATION_PATHS.p2pChannelV2);
250
+ return hkdf(sha256, rawSharedSecret, bound, info, 32);
251
+ }
112
252
  }
113
253
  //# sourceMappingURL=handle.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"handle.js","sourceRoot":"","sources":["../src/handle.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAQ/C;;;;;;;;;GASG;AACH,MAAM,OAAO,MAAM;IACA,UAAU,CAAa;IACvB,SAAS,CAAa;IACtB,KAAK,CAAS;IACd,SAAS,CAAkB;IAE1C;;;;;;;KAOC;IACH,YAAY,UAAsB,EAAE,IAAY,EAAE,QAAyB;QACzE,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC;QAC7C,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;IAC5B,CAAC;IAED,8DAA8D;IAC9D,KAAK;QACH,OAAO,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC;aAChD,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;aACnB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;aACnB,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACxB,CAAC;IAEC;;;;KAIC;IACH,K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C,EAAE,CAAC,EAAE,EAAE;YACjD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC;gBAC5B,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;oBAAE,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACxC,CAAC;YACD,OAAO,CAAC,CAAC;QACX,CAAC,CAAC,CAAC;QACH,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;QACjC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACvB,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAExB,MAAM,IAAI,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CACnC,gBAAgB,CAAC,YAAY,CAC9B,CAAC;QACF,OAAO,IAAI,CAAC,MAAM,EAAE,eAAe,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;IACxD,CAAC;CACF"}
@@ -1,11 +1,19 @@
1
1
  import { Handle, type HandleMetadata } from './handle.js';
2
+ import { SubHandle, type SubHandleMetadata } from './subhandle.js';
3
+ import { Attestation, type AttestationGrant } from './attestation.js';
2
4
  /**
3
5
  * Represents the root cryptographic identity derived from a seed phrase.
4
6
  *
5
7
  * An Identity is the foundation of the Me2em protocol. It allows for the
6
- * hierarchical derivation of isolated {@link Handle}s for different contexts
7
- * (e.g., email, social, specific devices) from a single master seed,
8
- * ensuring zero cross-contamination of cryptographic material.
8
+ * hierarchical derivation of isolated {@link Handle}s and {@link SubHandle}s
9
+ * for different contexts (e.g., email, social, specific devices) from a
10
+ * single master seed, ensuring zero cross-contamination of cryptographic material.
11
+ *
12
+ * The Identity provides two derivation entry points:
13
+ * - {@link Identity.deriveHandle} — derives a top-level Handle.
14
+ * - {@link Identity.deriveSubHandle} — atomically derives a SubHandle by its
15
+ * full path (Handle name + SubHandle name). Used primarily for stateless
16
+ * session verification on the server side.
9
17
  *
10
18
  * @category Core Primitives
11
19
  */
@@ -14,25 +22,97 @@ export declare class Identity {
14
22
  private readonly publicKey;
15
23
  private constructor();
16
24
  /**
17
- * Initializes a new Identity from a BIP39 mnemonic seed phrase or raw seed bytes.
18
- *
19
- * @param seed - A 12 or 24-word BIP39 mnemonic string, or a raw Uint8Array seed.
20
- * @returns A Promise resolving to a new Identity instance.
21
- * @throws {Error} If the provided seed is invalid or cannot be processed.
22
- */
25
+ * Initializes a new Identity from a BIP39 mnemonic seed phrase or raw seed bytes.
26
+ *
27
+ * @param seed - A 32-byte raw Uint8Array seed, or a hex-encoded string of 32 bytes.
28
+ * @returns A Promise resolving to a new Identity instance.
29
+ * @throws {Error} If the provided seed is not exactly 32 bytes.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * const seed = await get32ByteSeedFromMnemonic('abandon abandon ... art');
34
+ * const identity = await Identity.fromSeed(seed);
35
+ * ```
36
+ */
23
37
  static fromSeed(seed: Uint8Array | string): Promise<Identity>;
24
38
  /**
25
- * Derives a new, cryptographically isolated {@link Handle} for a specific context.
26
- *
27
- * Each Handle is derived deterministically. The same name and metadata will
28
- * always produce the same Handle from the same Identity, but different names
29
- * produce completely unrelated keys.
30
- *
31
- * @param name - The context identifier (e.g., 'alice@example.com', 'device-1').
32
- * @param metadata - Optional metadata to associate with this Handle.
33
- * @returns A Promise resolving to the derived Handle.
34
- */
39
+ * Derives a new, cryptographically isolated {@link Handle} for a specific context.
40
+ *
41
+ * Each Handle is derived deterministically. The same name will always produce
42
+ * the same Handle from the same Identity, but different names produce
43
+ * completely unrelated keys.
44
+ *
45
+ * @param name - The context identifier (e.g., `'alice@example.com'`, `'station-001'`).
46
+ * @param metadata - Optional metadata to associate with this Handle.
47
+ * @returns A Promise resolving to the derived Handle.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * const handle = await identity.deriveHandle('station-001', {
52
+ * displayName: 'Berlin Station #001'
53
+ * });
54
+ * ```
55
+ */
35
56
  deriveHandle(name: string, metadata?: HandleMetadata): Promise<Handle>;
57
+ /**
58
+ * Atomically derives a {@link SubHandle} from this Identity by its full path.
59
+ *
60
+ * This method performs the equivalent of:
61
+ * ```ts
62
+ * const handle = await identity.deriveHandle(handleName);
63
+ * const sub = await handle.deriveSubHandle(subName);
64
+ * ```
65
+ * but in a single call, without exposing the intermediate Handle.
66
+ *
67
+ * It is the **recommended entry point for stateless session verification**,
68
+ * because the server only needs the Identity and the path from the token.
69
+ *
70
+ * The resulting SubHandle is cryptographically identical to the one produced
71
+ * by `Handle.deriveSubHandle(subName)` on the same Identity.
72
+ *
73
+ * @param handleName - The parent Handle name.
74
+ * @param subName - The SubHandle name.
75
+ * @param metadata - Optional SubHandle metadata with constraints.
76
+ * @returns A Promise resolving to the derived SubHandle with path `[handleName, subName]`.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * // Server-side stateless verification
81
+ * const sub = await identity.deriveSubHandle('station-001', 'connector-1');
82
+ * const publicKey = sub.getPublicKey();
83
+ * ```
84
+ */
85
+ deriveSubHandle(handleName: string, subName: string, metadata?: SubHandleMetadata): Promise<SubHandle>;
86
+ /**
87
+ * Issues an attestation binding a derived Handle key to its name
88
+ * and grant. The subject public key is always derived internally —
89
+ * it is impossible to attest a foreign key, and the resulting
90
+ * `subjectId` always matches the handle reconstructed via
91
+ * {@link Identity.deriveSubHandle}.
92
+ *
93
+ * @param grant - Constraints verifiers will enforce for this handle
94
+ * and (via `subNamePatterns`) for the SubHandles it may attest.
95
+ * @returns An attestation signed by the Identity root key. Store it
96
+ * with the Handle — it is a public artifact, not a secret.
97
+ * @throws {Error} If the name is not canonicalizable.
98
+ * @throws {AttestationError} If the grant is invalid.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const A = await identity.attestHandle('station-001', {
103
+ * audiences: ['ev-app.com'],
104
+ * scopes: ['charge:start', 'charge:stop', 'charge:status'],
105
+ * maxSessionTtl: 7200,
106
+ * subNamePatterns: ['connector-*', 'meter-*'],
107
+ * });
108
+ * ```
109
+ */
110
+ attestHandle(name: string, grant: AttestationGrant, opts?: {
111
+ ttlSeconds?: number;
112
+ expiresAt?: number;
113
+ jti?: string;
114
+ now?: number;
115
+ }): Promise<Attestation>;
36
116
  /**
37
117
  * Retrieves the public key of the root Identity.
38
118
  *
@@ -1 +1 @@
1
- {"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAE,KAAK,cAAc,EAAE,MAAM,aAAa,CAAC;AAI1D;;;;;;;;;GASG;AACH,qBAAa,QAAQ;IACnB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAa;IACxC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAa;IAEvC,OAAO;IAKL;;;;;;KAMC;WACU,QAAQ,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;IAoBjE;;;;;;;;;;KAUC;IACG,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAgB5E;;;;OAIG;IACH,YAAY,IAAI,UAAU;CAG3B"}
1
+ {"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,MAAM,EAAE,KAAK,cAAc,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,KAAK,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAGnE,OAAO,EAAE,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAWtE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,QAAQ;IACnB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAa;IACxC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAa;IAEvC,OAAO;IAKP;;;;;;;;;;;;OAYG;WACU,QAAQ,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;IAmBnE;;;;;;;;;;;;;;;;;OAiBG;IACG,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAa5E;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACG,eAAe,CACnB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,EACf,QAAQ,CAAC,EAAE,iBAAiB,GAC3B,OAAO,CAAC,SAAS,CAAC;IA8BrB;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACG,YAAY,CAChB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,gBAAgB,EACvB,IAAI,CAAC,EAAE;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,GAC7E,OAAO,CAAC,WAAW,CAAC;IAYvB;;;;OAIG;IACH,YAAY,IAAI,UAAU;CAG3B"}
package/dist/identity.js CHANGED
@@ -1,15 +1,34 @@
1
- import { ed } from './crypto/init.js'; // ← sha512 теперь импортируется из init
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 } from './handle.js';
5
- const ME2EM_HKDF_INFO_PREFIX = 'me2em/handle/v1/';
6
+ import { SubHandle } from './subhandle.js';
7
+ import { DERIVATION_PATHS } from './crypto/derivation-paths.js';
8
+ import { normalizeName } from './canonical-name.js';
9
+ import { Attestation } from './attestation.js';
10
+ function parseHexSeed(hex) {
11
+ if (!/^[0-9a-fA-F]{64}$/.test(hex)) {
12
+ throw new Error('Seed string must be 64 hex characters');
13
+ }
14
+ const out = new Uint8Array(32);
15
+ for (let i = 0; i < 32; i++)
16
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
17
+ return out;
18
+ }
6
19
  /**
7
20
  * Represents the root cryptographic identity derived from a seed phrase.
8
21
  *
9
22
  * An Identity is the foundation of the Me2em protocol. It allows for the
10
- * hierarchical derivation of isolated {@link Handle}s for different contexts
11
- * (e.g., email, social, specific devices) from a single master seed,
12
- * ensuring zero cross-contamination of cryptographic material.
23
+ * hierarchical derivation of isolated {@link Handle}s and {@link SubHandle}s
24
+ * for different contexts (e.g., email, social, specific devices) from a
25
+ * single master seed, ensuring zero cross-contamination of cryptographic material.
26
+ *
27
+ * The Identity provides two derivation entry points:
28
+ * - {@link Identity.deriveHandle} — derives a top-level Handle.
29
+ * - {@link Identity.deriveSubHandle} — atomically derives a SubHandle by its
30
+ * full path (Handle name + SubHandle name). Used primarily for stateless
31
+ * session verification on the server side.
13
32
  *
14
33
  * @category Core Primitives
15
34
  */
@@ -18,47 +37,124 @@ export class Identity {
18
37
  publicKey;
19
38
  constructor(privateKey) {
20
39
  this.privateKey = privateKey;
21
- this.publicKey = ed.getPublicKey(privateKey); // Теперь работает синхронно
40
+ this.publicKey = ed.getPublicKey(privateKey);
22
41
  }
23
42
  /**
24
- * Initializes a new Identity from a BIP39 mnemonic seed phrase or raw seed bytes.
25
- *
26
- * @param seed - A 12 or 24-word BIP39 mnemonic string, or a raw Uint8Array seed.
27
- * @returns A Promise resolving to a new Identity instance.
28
- * @throws {Error} If the provided seed is invalid or cannot be processed.
29
- */
43
+ * Initializes a new Identity from a BIP39 mnemonic seed phrase or raw seed bytes.
44
+ *
45
+ * @param seed - A 32-byte raw Uint8Array seed, or a hex-encoded string of 32 bytes.
46
+ * @returns A Promise resolving to a new Identity instance.
47
+ * @throws {Error} If the provided seed is not exactly 32 bytes.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * const seed = await get32ByteSeedFromMnemonic('abandon abandon ... art');
52
+ * const identity = await Identity.fromSeed(seed);
53
+ * ```
54
+ */
30
55
  static async fromSeed(seed) {
31
56
  const seedBytes = typeof seed === 'string'
32
- ? Uint8Array.from(Buffer.from(seed, 'hex'))
57
+ ? parseHexSeed(seed)
33
58
  : seed;
34
59
  if (seedBytes.length !== 32) {
35
60
  throw new Error('Invalid seed: must be 32 bytes');
36
61
  }
37
- const key = hkdf(sha256, seedBytes, new Uint8Array(0), // salt
38
- new TextEncoder().encode('me2em/identity/v1/root'), // info
39
- 32 // length
40
- );
62
+ const key = hkdf(sha256, seedBytes, new Uint8Array(0), new TextEncoder().encode(DERIVATION_PATHS.identity), 32);
41
63
  return new Identity(key);
42
64
  }
43
65
  /**
44
- * Derives a new, cryptographically isolated {@link Handle} for a specific context.
45
- *
46
- * Each Handle is derived deterministically. The same name and metadata will
47
- * always produce the same Handle from the same Identity, but different names
48
- * produce completely unrelated keys.
49
- *
50
- * @param name - The context identifier (e.g., 'alice@example.com', 'device-1').
51
- * @param metadata - Optional metadata to associate with this Handle.
52
- * @returns A Promise resolving to the derived Handle.
53
- */
66
+ * Derives a new, cryptographically isolated {@link Handle} for a specific context.
67
+ *
68
+ * Each Handle is derived deterministically. The same name will always produce
69
+ * the same Handle from the same Identity, but different names produce
70
+ * completely unrelated keys.
71
+ *
72
+ * @param name - The context identifier (e.g., `'alice@example.com'`, `'station-001'`).
73
+ * @param metadata - Optional metadata to associate with this Handle.
74
+ * @returns A Promise resolving to the derived Handle.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * const handle = await identity.deriveHandle('station-001', {
79
+ * displayName: 'Berlin Station #001'
80
+ * });
81
+ * ```
82
+ */
54
83
  async deriveHandle(name, metadata) {
55
- const info = new TextEncoder().encode(ME2EM_HKDF_INFO_PREFIX + name.toLowerCase().trim());
56
- // Используем sha256 для единообразия (или sha512, если нужно)
57
- // Важно: используем тот же хэш, что и в спецификации
58
- const handleKey = hkdf(sha256, // ← Используем sha256 для совместимости с Identity деривацией
59
- this.privateKey, new Uint8Array(0), info, 32);
84
+ name = normalizeName(name);
85
+ const info = new TextEncoder().encode(DERIVATION_PATHS.handle(name));
86
+ const handleKey = hkdf(sha256, this.privateKey, new Uint8Array(0), info, 32);
60
87
  return new Handle(handleKey, name, metadata);
61
88
  }
89
+ /**
90
+ * Atomically derives a {@link SubHandle} from this Identity by its full path.
91
+ *
92
+ * This method performs the equivalent of:
93
+ * ```ts
94
+ * const handle = await identity.deriveHandle(handleName);
95
+ * const sub = await handle.deriveSubHandle(subName);
96
+ * ```
97
+ * but in a single call, without exposing the intermediate Handle.
98
+ *
99
+ * It is the **recommended entry point for stateless session verification**,
100
+ * because the server only needs the Identity and the path from the token.
101
+ *
102
+ * The resulting SubHandle is cryptographically identical to the one produced
103
+ * by `Handle.deriveSubHandle(subName)` on the same Identity.
104
+ *
105
+ * @param handleName - The parent Handle name.
106
+ * @param subName - The SubHandle name.
107
+ * @param metadata - Optional SubHandle metadata with constraints.
108
+ * @returns A Promise resolving to the derived SubHandle with path `[handleName, subName]`.
109
+ *
110
+ * @example
111
+ * ```ts
112
+ * // Server-side stateless verification
113
+ * const sub = await identity.deriveSubHandle('station-001', 'connector-1');
114
+ * const publicKey = sub.getPublicKey();
115
+ * ```
116
+ */
117
+ async deriveSubHandle(handleName, subName, metadata) {
118
+ handleName = normalizeName(handleName);
119
+ const subNameNorm = normalizeName(subName);
120
+ // Step 1: derive the intermediate Handle key (never exposed)
121
+ const handleInfo = new TextEncoder().encode(DERIVATION_PATHS.handle(handleName));
122
+ const handleKey = hkdf(sha256, this.privateKey, new Uint8Array(0), handleInfo, 32);
123
+ // Step 2: derive the SubHandle key from the Handle key
124
+ const subInfo = new TextEncoder().encode(DERIVATION_PATHS.subhandle(handleName, subNameNorm));
125
+ const subKey = hkdf(sha256, handleKey, new Uint8Array(0), subInfo, 32);
126
+ const path = [handleName, subNameNorm];
127
+ return new SubHandle(subKey, subNameNorm, path, metadata);
128
+ }
129
+ /**
130
+ * Issues an attestation binding a derived Handle key to its name
131
+ * and grant. The subject public key is always derived internally —
132
+ * it is impossible to attest a foreign key, and the resulting
133
+ * `subjectId` always matches the handle reconstructed via
134
+ * {@link Identity.deriveSubHandle}.
135
+ *
136
+ * @param grant - Constraints verifiers will enforce for this handle
137
+ * and (via `subNamePatterns`) for the SubHandles it may attest.
138
+ * @returns An attestation signed by the Identity root key. Store it
139
+ * with the Handle — it is a public artifact, not a secret.
140
+ * @throws {Error} If the name is not canonicalizable.
141
+ * @throws {AttestationError} If the grant is invalid.
142
+ *
143
+ * @example
144
+ * ```ts
145
+ * const A = await identity.attestHandle('station-001', {
146
+ * audiences: ['ev-app.com'],
147
+ * scopes: ['charge:start', 'charge:stop', 'charge:status'],
148
+ * maxSessionTtl: 7200,
149
+ * subNamePatterns: ['connector-*', 'meter-*'],
150
+ * });
151
+ * ```
152
+ */
153
+ async attestHandle(name, grant, opts) {
154
+ const normalized = normalizeName(name);
155
+ const handle = await this.deriveHandle(normalized);
156
+ return Attestation.issue(this.privateKey, handle.getPublicKey(), normalized, grant, opts ?? {});
157
+ }
62
158
  /**
63
159
  * Retrieves the public key of the root Identity.
64
160
  *