@me2em/core 0.4.4-alpha.1 → 0.6.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 (92) hide show
  1. package/README.md +299 -766
  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 +52 -0
  15. package/dist/crypto/ed25519.d.ts.map +1 -0
  16. package/dist/crypto/ed25519.js +67 -0
  17. package/dist/crypto/ed25519.js.map +1 -0
  18. package/dist/crypto/hkdf.d.ts +13 -0
  19. package/dist/crypto/hkdf.d.ts.map +1 -0
  20. package/dist/crypto/hkdf.js +17 -0
  21. package/dist/crypto/hkdf.js.map +1 -0
  22. package/dist/crypto/index.d.ts +4 -0
  23. package/dist/crypto/index.d.ts.map +1 -0
  24. package/dist/crypto/index.js +5 -0
  25. package/dist/crypto/index.js.map +1 -0
  26. package/dist/crypto/init.d.ts +9 -0
  27. package/dist/crypto/init.d.ts.map +1 -0
  28. package/dist/crypto/init.js +17 -0
  29. package/dist/crypto/init.js.map +1 -0
  30. package/dist/handle.d.ts +206 -0
  31. package/dist/handle.d.ts.map +1 -0
  32. package/dist/handle.js +258 -0
  33. package/dist/handle.js.map +1 -0
  34. package/dist/identity.d.ts +123 -0
  35. package/dist/identity.d.ts.map +1 -0
  36. package/dist/identity.js +167 -0
  37. package/dist/identity.js.map +1 -0
  38. package/dist/index.d.ts +33 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +33 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/seed.d.ts +83 -0
  43. package/dist/seed.d.ts.map +1 -0
  44. package/dist/seed.js +117 -0
  45. package/dist/seed.js.map +1 -0
  46. package/dist/session.d.ts +231 -0
  47. package/dist/session.d.ts.map +1 -0
  48. package/dist/session.js +454 -0
  49. package/dist/session.js.map +1 -0
  50. package/dist/subhandle.d.ts +126 -0
  51. package/dist/subhandle.d.ts.map +1 -0
  52. package/dist/subhandle.js +158 -0
  53. package/dist/subhandle.js.map +1 -0
  54. package/dist/util.d.ts +9 -0
  55. package/dist/util.d.ts.map +1 -0
  56. package/dist/util.js +34 -0
  57. package/dist/util.js.map +1 -0
  58. package/package.json +36 -12
  59. package/src/attestation.ts +364 -0
  60. package/src/canonical-name.ts +12 -0
  61. package/src/crypto/derivation-paths.ts +56 -0
  62. package/src/crypto/ed25519.ts +86 -0
  63. package/{packages/core/src → src}/crypto/hkdf.ts +2 -0
  64. package/src/crypto/index.ts +4 -0
  65. package/{packages/core/src → src}/crypto/init.ts +1 -0
  66. package/src/handle.ts +320 -0
  67. package/src/identity.ts +218 -0
  68. package/{packages/core/src → src}/index.ts +5 -1
  69. package/{packages/core/src → src}/seed.ts +41 -54
  70. package/src/session.ts +660 -0
  71. package/src/subhandle.ts +230 -0
  72. package/src/util.ts +35 -0
  73. package/.github/workflows/ci.yml +0 -0
  74. package/CODE_OF_CONDUCT.md +0 -73
  75. package/CONTRIBUTING.md +0 -145
  76. package/GOVERNANCE.md +0 -132
  77. package/SECURITY.md +0 -70
  78. package/packages/core/README.md +0 -656
  79. package/packages/core/package.json +0 -44
  80. package/packages/core/src/crypto/ed25519.ts +0 -12
  81. package/packages/core/src/crypto/index.ts +0 -2
  82. package/packages/core/src/handle.ts +0 -130
  83. package/packages/core/src/identity.ts +0 -89
  84. package/packages/core/src/session.ts +0 -47
  85. package/packages/core/test/derivation.spec.ts +0 -117
  86. package/packages/core/tsconfig.json +0 -9
  87. package/pnpm-workspace.yaml +0 -2
  88. package/specs/core.md +0 -44
  89. package/specs/openapi/server-ref.yaml +0 -10
  90. package/specs/test-vectors.json +0 -13
  91. package/tsconfig.base.json +0 -20
  92. package/typedoc.json +0 -18
package/src/handle.ts ADDED
@@ -0,0 +1,320 @@
1
+ // handle.ts
2
+ import { ed } from './crypto/init.js';
3
+ import { hkdf } from '@noble/hashes/hkdf.js';
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 type { SubHandleMetadata, SubHandle } from './subhandle.js';
8
+ import { DERIVATION_PATHS } from './crypto/derivation-paths.js';
9
+ import { Attestation, type AttestationGrant } from './attestation.js';
10
+
11
+ /**
12
+ * Metadata associated with a {@link Handle}.
13
+ *
14
+ * All fields are optional and application-defined. The protocol does not
15
+ * interpret metadata; it is carried for convenience and may be serialized
16
+ * into tokens or stored by the application.
17
+ *
18
+ * @category Types
19
+ */
20
+ export interface HandleMetadata {
21
+ /** Human-readable display name. */
22
+ displayName?: string;
23
+ /** URL or data-URI of an avatar image. */
24
+ avatar?: string;
25
+ /** Arbitrary additional fields. */
26
+ [key: string]: unknown;
27
+ }
28
+
29
+ /**
30
+ * Represents a context-specific cryptographic handle derived from an {@link Identity}.
31
+ *
32
+ * A Handle encapsulates a private key tied to a specific name (context).
33
+ * It provides methods for signing data, verifying signatures, and deriving
34
+ * secondary secrets (passwords, channel keys, shared secrets) without ever
35
+ * exposing the underlying private key.
36
+ *
37
+ * A Handle can also derive {@link SubHandle}s for hierarchical access control
38
+ * (e.g., an IoT device deriving keys for its components). The private key
39
+ * **never leaves the Handle** — derivation is performed internally using HKDF.
40
+ *
41
+ * @category Core Primitives
42
+ */
43
+ export class Handle {
44
+ private readonly privateKey: Uint8Array;
45
+ private readonly publicKey: Uint8Array;
46
+ private readonly _name: string;
47
+ private readonly _metadata?: HandleMetadata;
48
+
49
+ /**
50
+ * Creates a new Handle instance.
51
+ *
52
+ * @internal Typically created via {@link Identity.deriveHandle} or
53
+ * {@link Handle.deriveSubHandle}. Direct construction is discouraged.
54
+ *
55
+ * @param privateKey - The 32-byte Ed25519 private key for this handle.
56
+ * @param name - The context name this handle represents.
57
+ * @param metadata - Optional metadata associated with this handle.
58
+ */
59
+ constructor(privateKey: Uint8Array, name: string, metadata?: HandleMetadata) {
60
+ this.privateKey = privateKey;
61
+ this.publicKey = ed.getPublicKey(privateKey);
62
+ this._name = name;
63
+ this._metadata = metadata;
64
+ }
65
+
66
+ /**
67
+ * Returns a URL-safe Base64-encoded identifier for this Handle,
68
+ * derived from its public key.
69
+ *
70
+ * @returns A unique, URL-safe string identifier.
71
+ */
72
+ getId(): string {
73
+ return btoa(String.fromCharCode(...this.publicKey))
74
+ .replace(/\+/g, '-')
75
+ .replace(/\//g, '_')
76
+ .replace(/=+$/, '');
77
+ }
78
+
79
+ /**
80
+ * Cryptographically signs arbitrary data using the Handle's private key.
81
+ *
82
+ * @param data - The data to be signed, as a Uint8Array.
83
+ * @returns A Promise resolving to the Ed25519 signature as a Uint8Array.
84
+ */
85
+ async sign(data: Uint8Array): Promise<Uint8Array> {
86
+ return ed.sign(data, this.privateKey);
87
+ }
88
+
89
+ /**
90
+ * Verifies an Ed25519 signature against the provided data and public key.
91
+ *
92
+ * @param signature - The signature to verify (Uint8Array).
93
+ * @param data - The original data that was signed (Uint8Array).
94
+ * @param publicKey - The public key to verify against (Uint8Array).
95
+ * @returns A Promise resolving to `true` if the signature is valid, `false` otherwise.
96
+ */
97
+ static async verify(
98
+ signature: Uint8Array,
99
+ data: Uint8Array,
100
+ publicKey: Uint8Array
101
+ ): Promise<boolean> {
102
+ return ed.verify(signature, data, publicKey);
103
+ }
104
+
105
+ /** @returns The context name associated with this Handle. */
106
+ getName(): string {
107
+ return this._name;
108
+ }
109
+
110
+ /** @returns The metadata object associated with this Handle. */
111
+ getMetadata(): HandleMetadata | undefined {
112
+ return this._metadata;
113
+ }
114
+
115
+ /** @returns A Uint8Array containing the 32-byte Ed25519 public key. */
116
+ getPublicKey(): Uint8Array {
117
+ return this.publicKey;
118
+ }
119
+
120
+ /** @returns The derivation path, or undefined for Handle (only SubHandle has a path). */
121
+ getPath(): string[] | undefined {
122
+ return undefined;
123
+ }
124
+
125
+ /**
126
+ * Validates session options against this Handle's constraints.
127
+ * Handle has no constraints.
128
+ */
129
+ validateSessionOptions(_options: {
130
+ audience: string; scopes: string[]; ttl: number;
131
+ }): void { /* Handle has no constraints */ }
132
+
133
+ /**
134
+ * Derives a {@link SubHandle} from this Handle.
135
+ *
136
+ * This is the **autonomous entry point** for IoT devices and other contexts
137
+ * where the Identity is not available locally. The Handle uses its own
138
+ * private key internally (it never leaves the class) to derive a child key
139
+ * via HKDF-SHA256.
140
+ *
141
+ * The resulting SubHandle is cryptographically identical to the one produced
142
+ * by `Identity.deriveSubHandle(this.name, subName)`.
143
+ *
144
+ * @param name - The SubHandle name (will be normalized).
145
+ * @param metadata - Optional SubHandle metadata with constraints.
146
+ * @returns A Promise resolving to the derived SubHandle with path `[this.name, name]`.
147
+ *
148
+ * @example
149
+ * ```ts
150
+ * // On an IoT device (no Identity available)
151
+ * const connector = await stationHandle.deriveSubHandle('connector-1', {
152
+ * allowedScopes: ['charge:start'],
153
+ * maxSessionTtl: 3600
154
+ * });
155
+ * ```
156
+ */
157
+ async deriveSubHandle(name: string, metadata?: SubHandleMetadata): Promise<SubHandle> {
158
+ const normalizedName = normalizeName(name);
159
+ const info = new TextEncoder().encode(
160
+ DERIVATION_PATHS.subhandle(this._name, normalizedName)
161
+ );
162
+ // The private key is used internally and never leaves this class.
163
+ const subKey = hkdf(
164
+ sha256,
165
+ this.privateKey,
166
+ new Uint8Array(0),
167
+ info,
168
+ 32
169
+ );
170
+ const path = [this._name, normalizedName];
171
+ const { SubHandle: SubHandleClass } = await import('./subhandle.js');
172
+ return new SubHandleClass(subKey, normalizedName, path, metadata);
173
+ }
174
+
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(
200
+ subName: string,
201
+ grant: AttestationGrant,
202
+ opts?: { ttlSeconds?: number; expiresAt?: number; jti?: string; now?: number }
203
+ ): Promise<Attestation> {
204
+ const normalized = normalizeName(subName);
205
+ const sub = await this.deriveSubHandle(normalized);
206
+ return Attestation.issue(
207
+ this.privateKey,
208
+ sub.getPublicKey(),
209
+ normalized,
210
+ grant,
211
+ opts ?? {}
212
+ );
213
+ }
214
+
215
+ /**
216
+ * Deterministically derives a secret (e.g., a password or API key) for a
217
+ * specific service context.
218
+ *
219
+ * The private key **never leaves this class**, ensuring maximum security.
220
+ *
221
+ * @param context - A unique identifier for the service (e.g., `'google'`, `'github'`).
222
+ * @param length - Length of the derived raw bytes (default: 16 bytes ≈ 22 chars base64url).
223
+ * @returns A URL-safe base64 string suitable for use as a strong password.
224
+ *
225
+ * @example
226
+ * ```ts
227
+ * const githubPassword = handle.derivePassword('github', 20);
228
+ * ```
229
+ */
230
+ derivePassword(context: string, length: number = 16): string {
231
+ const salt = new TextEncoder().encode(`me2em/secret/${context.toLowerCase().trim()}`);
232
+ const info = new TextEncoder().encode('me2em/secret/v1');
233
+ const secretBytes = hkdf(sha256, this.privateKey, salt, info, length);
234
+ return btoa(String.fromCharCode(...secretBytes))
235
+ .replace(/\+/g, '-')
236
+ .replace(/\//g, '_')
237
+ .replace(/=+$/, '');
238
+ }
239
+
240
+ /**
241
+ * Derives a symmetric 256-bit channel key for secure communication between
242
+ * the Identity (controller) and this Handle (device/context).
243
+ *
244
+ * Both parties can independently compute this key because:
245
+ * - The Handle possesses its own private key directly.
246
+ * - The Identity can derive the same private key via `identity.deriveHandle(name)`.
247
+ *
248
+ * This enables zero-knowledge encrypted channels without key exchange protocols.
249
+ *
250
+ * @param context - Channel identifier for domain separation (e.g., `'drone-001'`).
251
+ * Both parties **MUST** use the same context.
252
+ * @returns A 32-byte Uint8Array suitable for AES-256-GCM encryption.
253
+ *
254
+ * @example
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');
262
+ * const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
263
+ * const decrypted = await decryptAESGCM(encrypted, channelKey);
264
+ * ```
265
+ */
266
+ deriveChannelKey(context: string): Uint8Array {
267
+ const salt = new TextEncoder().encode(`me2em/channel/${context.toLowerCase().trim()}`);
268
+ const info = new TextEncoder().encode('me2em/channel/v1');
269
+ return hkdf(sha256, this.privateKey, salt, info, 32);
270
+ }
271
+
272
+ /**
273
+ * Derives a shared secret using ECDH (X25519) for P2P key exchange.
274
+ *
275
+ * Converts the Ed25519 keypair to X25519 for Diffie-Hellman key agreement,
276
+ * then applies HKDF-SHA256 to produce a clean 32-byte channel key.
277
+ *
278
+ * @param otherPublicKey - The Ed25519 public key of the other party (32 bytes).
279
+ * @returns A Promise resolving to a 32-byte shared secret suitable for AES-256-GCM.
280
+ *
281
+ * @example
282
+ * ```ts
283
+ * const aliceShared = await aliceHandle.deriveSharedSecret(bobHandle.getPublicKey());
284
+ * const bobShared = await bobHandle.deriveSharedSecret(aliceHandle.getPublicKey());
285
+ * // aliceShared === bobShared
286
+ * ```
287
+ */
288
+ async deriveSharedSecret(otherPublicKey: Uint8Array): Promise<Uint8Array> {
289
+ const myPrivBytes = this.privateKey;
290
+ const otherPubBytes = otherPublicKey;
291
+
292
+ if (myPrivBytes.length !== 32) {
293
+ throw new Error('Handle private key must be 32 bytes');
294
+ }
295
+ if (otherPubBytes.length !== 32) {
296
+ throw new Error('Public key must be 32 bytes');
297
+ }
298
+
299
+ const x25519Priv = ed25519.utils.toMontgomerySecret(myPrivBytes);
300
+ const x25519Pub = ed25519.utils.toMontgomery(otherPubBytes);
301
+ const rawSharedSecret = x25519.getSharedSecret(x25519Priv, x25519Pub);
302
+
303
+ // Canonical, order-independent binding of both peers' public keys.
304
+ const myPub = this.getPublicKey();
305
+ const peers = [myPub, otherPubBytes].sort((a, b) => {
306
+ for (let i = 0; i < 32; i++) {
307
+ if (a[i] !== b[i]) return a[i] - b[i];
308
+ }
309
+ return 0;
310
+ });
311
+ const bound = new Uint8Array(64);
312
+ bound.set(peers[0], 0);
313
+ bound.set(peers[1], 32);
314
+
315
+ const info = new TextEncoder().encode(
316
+ DERIVATION_PATHS.p2pChannelV2
317
+ );
318
+ return hkdf(sha256, rawSharedSecret, bound, info, 32);
319
+ }
320
+ }
@@ -0,0 +1,218 @@
1
+ // identity.ts
2
+ import { ed } from './crypto/init.js';
3
+ import { hkdf } from '@noble/hashes/hkdf.js';
4
+ import { sha256 } from '@noble/hashes/sha2.js';
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';
10
+
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
+ }
19
+
20
+ /**
21
+ * Represents the root cryptographic identity derived from a seed phrase.
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
+ *
34
+ * @category Core Primitives
35
+ */
36
+ export class Identity {
37
+ private readonly privateKey: Uint8Array;
38
+ private readonly publicKey: Uint8Array;
39
+
40
+ private constructor(privateKey: Uint8Array) {
41
+ this.privateKey = privateKey;
42
+ this.publicKey = ed.getPublicKey(privateKey);
43
+ }
44
+
45
+ /**
46
+ * Initializes a new Identity from a BIP39 mnemonic seed phrase or raw seed bytes.
47
+ *
48
+ * @param seed - A 32-byte raw Uint8Array seed, or a hex-encoded string of 32 bytes.
49
+ * @returns A Promise resolving to a new Identity instance.
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
+ * ```
57
+ */
58
+ static async fromSeed(seed: Uint8Array | string): Promise<Identity> {
59
+ const seedBytes = typeof seed === 'string'
60
+ ? parseHexSeed(seed)
61
+ : seed;
62
+
63
+ if (seedBytes.length !== 32) {
64
+ throw new Error('Invalid seed: must be 32 bytes');
65
+ }
66
+
67
+ const key = hkdf(
68
+ sha256,
69
+ seedBytes,
70
+ new Uint8Array(0),
71
+ new TextEncoder().encode(DERIVATION_PATHS.identity),
72
+ 32
73
+ );
74
+ return new Identity(key);
75
+ }
76
+
77
+ /**
78
+ * Derives a new, cryptographically isolated {@link Handle} for a specific context.
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'`).
85
+ * @param metadata - Optional metadata to associate with this Handle.
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
+ * ```
94
+ */
95
+ async deriveHandle(name: string, metadata?: HandleMetadata): Promise<Handle> {
96
+ name = normalizeName(name);
97
+ const info = new TextEncoder().encode(DERIVATION_PATHS.handle(name));
98
+ const handleKey = hkdf(
99
+ sha256,
100
+ this.privateKey,
101
+ new Uint8Array(0),
102
+ info,
103
+ 32
104
+ );
105
+ return new Handle(handleKey, name, metadata);
106
+ }
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
+
210
+ /**
211
+ * Retrieves the public key of the root Identity.
212
+ *
213
+ * @returns A Uint8Array containing the 32-byte Ed25519 public key.
214
+ */
215
+ getPublicKey(): Uint8Array {
216
+ return this.publicKey;
217
+ }
218
+ }
@@ -1,6 +1,8 @@
1
1
  export { Identity } from './identity.js';
2
2
  export { Handle, type HandleMetadata } from './handle.js';
3
- export { Session, type SessionOptions, type SessionToken } from './session.js';
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