@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
@@ -0,0 +1,56 @@
1
+ // packages/core/src/crypto/derivation-paths.ts
2
+ //
3
+ // Single source of truth for HKDF info strings used across the protocol.
4
+ // All derivation functions (Identity, Handle, SubHandle) MUST import their
5
+ // info strings from this module to guarantee cryptographic consistency.
6
+ //
7
+ // Changing any of these strings is a BREAKING CHANGE and requires a new
8
+ // protocol version.
9
+
10
+ import { normalizeName } from '../canonical-name.js';
11
+
12
+ /**
13
+ * Deterministic derivation paths for the Me2em protocol.
14
+ *
15
+ * All HKDF info strings used to derive Identity, Handle, and SubHandle keys
16
+ * are centralized here. This guarantees that:
17
+ * - `Identity.deriveHandle(name)` and `Handle.deriveSubHandle(subName)`
18
+ * produce the same key as `Identity.deriveSubHandle(name, subName)`.
19
+ * - Any future change to derivation paths is a single-line edit.
20
+ *
21
+ * @category Cryptographic Constants
22
+ */
23
+ export const DERIVATION_PATHS = {
24
+ /**
25
+ * Info string for deriving the root Identity key from the seed.
26
+ * Constant value: `"me2em/identity/v1/root"`.
27
+ */
28
+ identity: 'me2em/identity/v1/root',
29
+
30
+ /**
31
+ * Builds the info string for deriving a Handle from an Identity.
32
+ *
33
+ * @param name - The Handle name (will be normalized).
34
+ * @returns The info string, e.g. `"me2em/handle/v1/station-001"`.
35
+ */
36
+ handle: (name: string): string =>
37
+ `me2em/handle/v1/${normalizeName(name)}`,
38
+
39
+ /**
40
+ * Builds the info string for deriving a SubHandle from a Handle.
41
+ *
42
+ * @param handleName - The parent Handle name (will be normalized).
43
+ * @param subName - The SubHandle name (will be normalized).
44
+ * @returns The info string, e.g. `"me2em/subhandle/v1/station-001/connector-1"`.
45
+ */
46
+ subhandle: (handleName: string, subName: string): string =>
47
+ `me2em/subhandle/v1/${normalizeName(handleName)}/${normalizeName(subName)}`,
48
+
49
+ /**
50
+ * Versioned info string for peer-to-peer channel key derivation.
51
+ * v2 binds both peers' public keys into the derivation, preventing
52
+ * unknown key-share attacks. The peer keys are appended in sorted
53
+ * order so both parties derive the identical string.
54
+ */
55
+ p2pChannelV2: 'me2em/p2p-channel/v2',
56
+ } as const;
@@ -1,12 +1,86 @@
1
+ // packages/core/src/crypto/ed25519.ts
2
+ //
3
+ // Documented wrappers around the @noble/ed25519 primitives used by the
4
+ // protocol. These are real functions rather than alias re-exports, so
5
+ // generated documentation is fully owned by this package and never
6
+ // inherits comments (or broken links) from the upstream library.
7
+
1
8
  import { ed } from './init.js';
2
9
 
10
+ /** Verification options, forwarded to the underlying implementation. */
11
+ type VerifyOpts = Parameters<typeof ed.verify>[3];
12
+
13
+ /**
14
+ * Derives the Ed25519 public key for a private key (synchronous).
15
+ *
16
+ * @param privateKey - 32-byte Ed25519 private key.
17
+ * @returns The 32-byte public key.
18
+ * @throws `TypeError` if the key length is invalid.
19
+ * @throws `RangeError` if the key length is invalid.
20
+ */
21
+ export function getPublicKey(privateKey: Uint8Array): Uint8Array {
22
+ return ed.getPublicKey(privateKey);
23
+ }
24
+
25
+ /**
26
+ * Signs a message with an Ed25519 private key (synchronous).
27
+ *
28
+ * @param message - The bytes to sign.
29
+ * @param privateKey - 32-byte Ed25519 private key.
30
+ * @returns The 64-byte signature.
31
+ * @throws `TypeError` if an input length is invalid.
32
+ * @throws `RangeError` if an input length is invalid.
33
+ */
34
+ export function sign(message: Uint8Array, privateKey: Uint8Array): Uint8Array {
35
+ return ed.sign(message, privateKey);
36
+ }
37
+
38
+ /**
39
+ * Verifies an Ed25519 signature (synchronous).
40
+ *
41
+ * @param signature - The 64-byte signature.
42
+ * @param message - The signed message bytes.
43
+ * @param publicKey - The 32-byte signer public key.
44
+ * @param opts - Optional verification options, forwarded to the
45
+ * underlying implementation.
46
+ * @returns `true` if the signature is valid, `false` otherwise.
47
+ * @throws `TypeError` if an input length is invalid.
48
+ * @throws `RangeError` if an input length is invalid.
49
+ */
50
+ export function verify(
51
+ signature: Uint8Array,
52
+ message: Uint8Array,
53
+ publicKey: Uint8Array,
54
+ opts?: VerifyOpts
55
+ ): boolean {
56
+ return ed.verify(signature, message, publicKey, opts);
57
+ }
58
+
59
+ /**
60
+ * Asynchronous variant of {@link getPublicKey}; same contract.
61
+ */
62
+ export async function getPublicKeyAsync(privateKey: Uint8Array): Promise<Uint8Array> {
63
+ return ed.getPublicKeyAsync(privateKey);
64
+ }
65
+
66
+ /**
67
+ * Asynchronous variant of {@link sign}; same contract.
68
+ */
69
+ export async function signAsync(message: Uint8Array, privateKey: Uint8Array): Promise<Uint8Array> {
70
+ return ed.signAsync(message, privateKey);
71
+ }
72
+
3
73
  /**
4
- * @internal
5
- * Low-level Ed25519 implementation wrapper.
74
+ * Asynchronous variant of {@link verify}; same contract.
75
+ *
76
+ * @param opts - Optional verification options, forwarded to the
77
+ * underlying implementation.
6
78
  */
7
- export const getPublicKey = ed.getPublicKey;
8
- export const sign = ed.sign;
9
- export const verify = ed.verify;
10
- export const getPublicKeyAsync = ed.getPublicKeyAsync;
11
- export const signAsync = ed.signAsync;
12
- export const verifyAsync = ed.verifyAsync;
79
+ export async function verifyAsync(
80
+ signature: Uint8Array,
81
+ message: Uint8Array,
82
+ publicKey: Uint8Array,
83
+ opts?: Parameters<typeof ed.verifyAsync>[3]
84
+ ): Promise<boolean> {
85
+ return ed.verifyAsync(signature, message, publicKey, opts);
86
+ }
@@ -1,3 +1,5 @@
1
+ // packages/core/src/crypto/hkdf.ts
2
+
1
3
  import { hkdf as nobleHkdf } from '@noble/hashes/hkdf.js';
2
4
  import { sha256 as nobleSha256 } from '@noble/hashes/sha2.js';
3
5
 
@@ -1,2 +1,4 @@
1
+ // packages/core/src/crypto/index.ts
1
2
  export * from './ed25519.js';
2
- export * from './hkdf.js';
3
+ export * from './hkdf.js';
4
+ export * from './derivation-paths.js';
@@ -1,3 +1,4 @@
1
+ // packages/core/src/crypto/init.ts
1
2
  import * as ed from '@noble/ed25519';
2
3
  import { sha512 } from '@noble/hashes/sha2.js';
3
4
 
package/src/handle.ts CHANGED
@@ -1,21 +1,43 @@
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 type { SubHandleMetadata, SubHandle } from './subhandle.js';
8
+ import { DERIVATION_PATHS } from './crypto/derivation-paths.js';
9
+ import { Attestation, type AttestationGrant } from './attestation.js';
4
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
+ */
5
20
  export interface HandleMetadata {
21
+ /** Human-readable display name. */
6
22
  displayName?: string;
23
+ /** URL or data-URI of an avatar image. */
7
24
  avatar?: string;
25
+ /** Arbitrary additional fields. */
8
26
  [key: string]: unknown;
9
27
  }
10
28
 
11
29
  /**
12
30
  * Represents a context-specific cryptographic handle derived from an {@link Identity}.
13
- *
14
- * A Handle encapsulates a private key tied to a specific name (context).
15
- * It provides methods for signing data, verifying signatures, and deriving
16
- * secondary secrets (like passwords or channel keys) without ever exposing
17
- * the underlying private key.
18
- *
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
+ *
19
41
  * @category Core Primitives
20
42
  */
21
43
  export class Handle {
@@ -24,10 +46,12 @@ export class Handle {
24
46
  private readonly _name: string;
25
47
  private readonly _metadata?: HandleMetadata;
26
48
 
27
- /**
49
+ /**
28
50
  * Creates a new Handle instance.
29
- * @internal Typically created via {@link Identity.deriveHandle}.
30
- *
51
+ *
52
+ * @internal Typically created via {@link Identity.deriveHandle} or
53
+ * {@link Handle.deriveSubHandle}. Direct construction is discouraged.
54
+ *
31
55
  * @param privateKey - The 32-byte Ed25519 private key for this handle.
32
56
  * @param name - The context name this handle represents.
33
57
  * @param metadata - Optional metadata associated with this handle.
@@ -39,7 +63,12 @@ export class Handle {
39
63
  this._metadata = metadata;
40
64
  }
41
65
 
42
- /** @returns The unique context identifier for this Handle. */
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
+ */
43
72
  getId(): string {
44
73
  return btoa(String.fromCharCode(...this.publicKey))
45
74
  .replace(/\+/g, '-')
@@ -47,8 +76,9 @@ export class Handle {
47
76
  .replace(/=+$/, '');
48
77
  }
49
78
 
50
- /**
79
+ /**
51
80
  * Cryptographically signs arbitrary data using the Handle's private key.
81
+ *
52
82
  * @param data - The data to be signed, as a Uint8Array.
53
83
  * @returns A Promise resolving to the Ed25519 signature as a Uint8Array.
54
84
  */
@@ -56,42 +86,151 @@ export class Handle {
56
86
  return ed.sign(data, this.privateKey);
57
87
  }
58
88
 
59
- /**
89
+ /**
60
90
  * Verifies an Ed25519 signature against the provided data and public key.
91
+ *
61
92
  * @param signature - The signature to verify (Uint8Array).
62
93
  * @param data - The original data that was signed (Uint8Array).
63
94
  * @param publicKey - The public key to verify against (Uint8Array).
64
- * @returns A Promise resolving to true if the signature is valid, false otherwise.
95
+ * @returns A Promise resolving to `true` if the signature is valid, `false` otherwise.
65
96
  */
66
- static async verify(signature: Uint8Array, data: Uint8Array, publicKey: Uint8Array): Promise<boolean> {
97
+ static async verify(
98
+ signature: Uint8Array,
99
+ data: Uint8Array,
100
+ publicKey: Uint8Array
101
+ ): Promise<boolean> {
67
102
  return ed.verify(signature, data, publicKey);
68
103
  }
69
104
 
70
105
  /** @returns The context name associated with this Handle. */
71
- getName(): string { return this._name; }
106
+ getName(): string {
107
+ return this._name;
108
+ }
72
109
 
73
110
  /** @returns The metadata object associated with this Handle. */
74
- getMetadata(): HandleMetadata | undefined { return this._metadata; }
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
+ }
75
119
 
76
- /** @returns A Uint8Array containing the 32-byte Ed25519 public key. */
77
- getPublicKey(): Uint8Array { return this.publicKey; }
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
+ }
78
174
 
79
175
  /**
80
- * Deterministically derives a secret (e.g., a password or API key) for a specific service context.
81
- * The private key NEVER leaves this class, ensuring maximum security.
82
- *
83
- * @param context - A unique identifier for the service (e.g., 'google', 'github', 'wifi-router').
84
- * @param length - Length of the derived raw bytes (default: 16 bytes = ~22 chars base64url).
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).
85
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
+ * ```
86
229
  */
87
230
  derivePassword(context: string, length: number = 16): string {
88
231
  const salt = new TextEncoder().encode(`me2em/secret/${context.toLowerCase().trim()}`);
89
232
  const info = new TextEncoder().encode('me2em/secret/v1');
90
-
91
- // HKDF использует this.privateKey напрямую, не экспортируя его
92
233
  const secretBytes = hkdf(sha256, this.privateKey, salt, info, length);
93
-
94
- // Конвертация в URL-safe base64 (аналогично getId)
95
234
  return btoa(String.fromCharCode(...secretBytes))
96
235
  .replace(/\+/g, '-')
97
236
  .replace(/\//g, '_')
@@ -101,25 +240,22 @@ export class Handle {
101
240
  /**
102
241
  * Derives a symmetric 256-bit channel key for secure communication between
103
242
  * the Identity (controller) and this Handle (device/context).
104
- *
243
+ *
105
244
  * Both parties can independently compute this key because:
106
- * 1. The Handle possesses its own private key directly.
107
- * 2. The Identity can derive the same private key via `identity.deriveHandle(name)`.
108
- *
245
+ * - The Handle possesses its own private key directly.
246
+ * - The Identity can derive the same private key via `identity.deriveHandle(name)`.
247
+ *
109
248
  * This enables zero-knowledge encrypted channels without key exchange protocols.
110
- *
111
- * @param context - Channel identifier for domain separation (e.g., 'drone-001', 'session-abc'). Both parties MUST use the same context.
249
+ *
250
+ * @param context - Channel identifier for domain separation (e.g., `'drone-001'`).
251
+ * Both parties **MUST** use the same context.
112
252
  * @returns A 32-byte Uint8Array suitable for AES-256-GCM encryption.
253
+ *
113
254
  * @example
114
- * ```typescript
115
- * // On the drone (Handle side):
255
+ * ```ts
256
+ * // AES-GCM helpers are application-side; the protocol provides
257
+ * // only the key:
116
258
  * const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
117
- * const encrypted = await encryptAESGCM(telemetry, channelKey);
118
- *
119
- * // On the control center (Identity side):
120
- * const droneHandle = await centerIdentity.deriveHandle('drone-001');
121
- * const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
122
- * const decrypted = await decryptAESGCM(encrypted, channelKey);
123
259
  * ```
124
260
  */
125
261
  deriveChannelKey(context: string): Uint8Array {
@@ -127,4 +263,53 @@ export class Handle {
127
263
  const info = new TextEncoder().encode('me2em/channel/v1');
128
264
  return hkdf(sha256, this.privateKey, salt, info, 32);
129
265
  }
130
- }
266
+
267
+ /**
268
+ * Derives a shared secret using ECDH (X25519) for P2P key exchange.
269
+ *
270
+ * Converts the Ed25519 keypair to X25519 for Diffie-Hellman key agreement,
271
+ * then applies HKDF-SHA256 to produce a clean 32-byte channel key.
272
+ *
273
+ * @param otherPublicKey - The Ed25519 public key of the other party (32 bytes).
274
+ * @returns A Promise resolving to a 32-byte shared secret suitable for AES-256-GCM.
275
+ *
276
+ * @example
277
+ * ```ts
278
+ * const aliceShared = await aliceHandle.deriveSharedSecret(bobHandle.getPublicKey());
279
+ * const bobShared = await bobHandle.deriveSharedSecret(aliceHandle.getPublicKey());
280
+ * // aliceShared === bobShared
281
+ * ```
282
+ */
283
+ async deriveSharedSecret(otherPublicKey: Uint8Array): Promise<Uint8Array> {
284
+ const myPrivBytes = this.privateKey;
285
+ const otherPubBytes = otherPublicKey;
286
+
287
+ if (myPrivBytes.length !== 32) {
288
+ throw new Error('Handle private key must be 32 bytes');
289
+ }
290
+ if (otherPubBytes.length !== 32) {
291
+ throw new Error('Public key must be 32 bytes');
292
+ }
293
+
294
+ const x25519Priv = ed25519.utils.toMontgomerySecret(myPrivBytes);
295
+ const x25519Pub = ed25519.utils.toMontgomery(otherPubBytes);
296
+ const rawSharedSecret = x25519.getSharedSecret(x25519Priv, x25519Pub);
297
+
298
+ // Canonical, order-independent binding of both peers' public keys.
299
+ const myPub = this.getPublicKey();
300
+ const peers = [myPub, otherPubBytes].sort((a, b) => {
301
+ for (let i = 0; i < 32; i++) {
302
+ if (a[i] !== b[i]) return a[i] - b[i];
303
+ }
304
+ return 0;
305
+ });
306
+ const bound = new Uint8Array(64);
307
+ bound.set(peers[0], 0);
308
+ bound.set(peers[1], 32);
309
+
310
+ const info = new TextEncoder().encode(
311
+ DERIVATION_PATHS.p2pChannelV2
312
+ );
313
+ return hkdf(sha256, rawSharedSecret, bound, info, 32);
314
+ }
315
+ }