@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
@@ -0,0 +1,364 @@
1
+ // attestation.ts
2
+ //
3
+ // Attestation module: cryptographically signed, self-contained
4
+ // authorization attestations for the Me2em protocol.
5
+
6
+ import { normalizeName } from './canonical-name.js';
7
+ import { base64urlEncode, base64urlDecode } from './util.js';
8
+ import { ed } from './crypto/init.js';
9
+
10
+ export const ATTESTATION_TYPE = 'me2em/attestation/v1';
11
+ export const ATTESTATION_MAX_PAYLOAD = 2048;
12
+
13
+ export interface AttestationGrant {
14
+ /**
15
+ * Audiences the subject may create sessions for.
16
+ * `undefined` = unrestricted; `[]` = deny all (fail-closed).
17
+ */
18
+ audiences?: string[];
19
+ /**
20
+ * Exact scope strings the subject may request. Wildcards are NOT
21
+ * supported here — only `subNamePatterns` supports wildcards.
22
+ */
23
+ scopes: string[];
24
+ /**
25
+ * Maximum session TTL (seconds) the subject may create. Must be a
26
+ * finite positive number.
27
+ */
28
+ maxSessionTtl: number;
29
+ /**
30
+ * Permitted child (SubHandle) names. Only meaningful on
31
+ * Identity→Handle attestations. Each pattern is either an exact name
32
+ * or ends with a single trailing `*` (prefix match); a lone `*`
33
+ * matches everything. Patterns like `a*b` are rejected at issue time.
34
+ */
35
+ subNamePatterns?: string[];
36
+ }
37
+
38
+ export interface AttestationPayload {
39
+ typ: typeof ATTESTATION_TYPE;
40
+ subjectName: string;
41
+ subjectId: string;
42
+ grant: AttestationGrant;
43
+ iat: number;
44
+ exp: number;
45
+ jti: string;
46
+ }
47
+
48
+ export type AttestationErrorCode =
49
+ | 'MALFORMED' | 'BAD_SIGNATURE' | 'EXPIRED' | 'NOT_YET_VALID'
50
+ | 'REVOKED' | 'PATH_MISMATCH' | 'NAME_NOT_PERMITTED'
51
+ | 'SCOPE_EXCEEDED' | 'AUDIENCE_NOT_PERMITTED' | 'TTL_EXCEEDED'
52
+ | 'CHAIN_INCOMPLETE' | 'SUBJECT_MISMATCH' | 'SESSION_OUTLIVES_ATTESTATION';
53
+
54
+ export type AttestationLevel =
55
+ | 'ROOT' | 'HANDLE_ATTESTATION' | 'SUB_ATTESTATION' | 'SESSION' | 'FORMAT';
56
+
57
+ export class AttestationError extends Error {
58
+ constructor(
59
+ public readonly code: AttestationErrorCode,
60
+ public readonly level: AttestationLevel,
61
+ msg: string
62
+ ) { super(`[${level}/${code}] ${msg}`); }
63
+ }
64
+
65
+ function throwFormat(code: AttestationErrorCode, msg: string): never {
66
+ throw new AttestationError(code, 'FORMAT', msg);
67
+ }
68
+
69
+ type ParseResult = {
70
+ payloadBytes: Uint8Array;
71
+ signatureBytes: Uint8Array;
72
+ payload: AttestationPayload;
73
+ };
74
+
75
+ function parseToken(token: string): ParseResult {
76
+ if (typeof token !== 'string') {
77
+ throwFormat('MALFORMED', 'Token must be a string');
78
+ }
79
+
80
+ const parts = token.split('.');
81
+ if (parts.length !== 2) {
82
+ throwFormat('MALFORMED', 'Token must have exactly two parts separated by "."');
83
+ }
84
+
85
+ const [payloadB64, signatureB64] = parts;
86
+
87
+ const b64urlRegex = /^[A-Za-z0-9_-]+$/;
88
+ if (!b64urlRegex.test(payloadB64) || !b64urlRegex.test(signatureB64)) {
89
+ throwFormat('MALFORMED', 'Payload and signature must be valid Base64URL');
90
+ }
91
+
92
+ const payloadBytes = base64urlDecode(payloadB64);
93
+ if (payloadBytes.length > ATTESTATION_MAX_PAYLOAD) {
94
+ throwFormat('MALFORMED', `Payload exceeds maximum size of ${ATTESTATION_MAX_PAYLOAD} bytes`);
95
+ }
96
+
97
+ let payload: AttestationPayload;
98
+ try {
99
+ const jsonString = new TextDecoder().decode(payloadBytes);
100
+ payload = JSON.parse(jsonString) as AttestationPayload;
101
+ } catch {
102
+ throwFormat('MALFORMED', 'Payload is not valid JSON');
103
+ }
104
+
105
+ const signatureBytes = base64urlDecode(signatureB64);
106
+
107
+ return { payloadBytes, signatureBytes, payload };
108
+ }
109
+
110
+ /**
111
+ * A parent-signed statement binding a derived child key to a name and a
112
+ * grant. Chains of attestations (`Identity → Handle → SubHandle`) allow
113
+ * any third party to verify sessions offline using only the root public
114
+ * key, with grant constraints enforced at verification time.
115
+ *
116
+ * Tokens have the form `base64url(payload).base64url(signature)` and are
117
+ * deterministic: the same inputs (including `jti` and `now`) always
118
+ * produce byte-identical tokens.
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * import { ed25519 } from '@noble/curves/ed25519.js';
123
+ *
124
+ * // Parent (signer) and child (subject) keys — use a CSPRNG in practice:
125
+ * const signerPriv = ed25519.utils.randomPrivateKey();
126
+ * const signerPub = ed25519.getPublicKey(signerPriv);
127
+ * const childPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());
128
+ *
129
+ * const A = await Attestation.issue(signerPriv, childPub, 'station-001', {
130
+ * audiences: ['ev-app.com'],
131
+ * scopes: ['charge:start', 'charge:stop'],
132
+ * maxSessionTtl: 7200,
133
+ * subNamePatterns: ['connector-*'],
134
+ * });
135
+ *
136
+ * const ok = await Attestation.verifySignature(A.token, signerPub); // true
137
+ * const payload = Attestation.decode(A.token); // structure only — no sig, no time
138
+ *
139
+ * ```
140
+ *
141
+ * @category Core Primitives
142
+ */
143
+ export class Attestation {
144
+ private readonly _payload: AttestationPayload;
145
+ private readonly _token: string;
146
+
147
+ private constructor(payload: AttestationPayload, token: string) {
148
+ this._payload = payload;
149
+ this._token = token;
150
+ }
151
+
152
+ get payload(): AttestationPayload {
153
+ return this._payload;
154
+ }
155
+
156
+ get token(): string {
157
+ return this._token;
158
+ }
159
+
160
+ get jti(): string {
161
+ return this._payload.jti;
162
+ }
163
+
164
+ /**
165
+ * Parses a token and validates its structure WITHOUT checking the
166
+ * signature or any timestamps. Use {@link verifySignature} for the
167
+ * signature; expiration is checked by `Session.verifyAttested`.
168
+ *
169
+ * @throws {AttestationError} `MALFORMED`/`FORMAT` on any structural
170
+ * problem: wrong shape, invalid Base64URL, size over
171
+ * {@link ATTESTATION_MAX_PAYLOAD}, non-JSON payload, wrong `typ`,
172
+ * missing/ill-typed fields, or a non-positive/NaN `maxSessionTtl`.
173
+ */
174
+ static decode(token: string): AttestationPayload {
175
+ const { payload } = parseToken(token);
176
+
177
+ if (payload.typ !== ATTESTATION_TYPE) {
178
+ throwFormat('MALFORMED', `Invalid typ: expected "${ATTESTATION_TYPE}"`);
179
+ }
180
+
181
+ if (typeof payload.subjectName !== 'string') {
182
+ throwFormat('MALFORMED', 'Missing required field: subjectName');
183
+ }
184
+ if (typeof payload.subjectId !== 'string') {
185
+ throwFormat('MALFORMED', 'Missing required field: subjectId');
186
+ }
187
+
188
+ if (
189
+ typeof payload.grant !== 'object' ||
190
+ payload.grant === null ||
191
+ Array.isArray(payload.grant)
192
+ ) {
193
+ throwFormat('MALFORMED', 'Invalid field: grant');
194
+ }
195
+
196
+ if (!Array.isArray(payload.grant.scopes) || !payload.grant.scopes.every((s: unknown) => typeof s === 'string')) {
197
+ throwFormat('MALFORMED', 'Invalid field: grant.scopes');
198
+ }
199
+
200
+ if (typeof payload.grant.maxSessionTtl !== 'number' || !Number.isFinite(payload.grant.maxSessionTtl) || payload.grant.maxSessionTtl <= 0) {
201
+ throwFormat('MALFORMED', 'Invalid field: grant.maxSessionTtl');
202
+ }
203
+
204
+ if (payload.grant.audiences !== undefined) {
205
+ if (!Array.isArray(payload.grant.audiences) || !payload.grant.audiences.every((a: unknown) => typeof a === 'string')) {
206
+ throwFormat('MALFORMED', 'Invalid field: grant.audiences');
207
+ }
208
+ }
209
+
210
+ if (payload.grant.subNamePatterns !== undefined) {
211
+ if (!Array.isArray(payload.grant.subNamePatterns) || !payload.grant.subNamePatterns.every((p: unknown) => typeof p === 'string')) {
212
+ throwFormat('MALFORMED', 'Invalid field: grant.subNamePatterns');
213
+ }
214
+ }
215
+
216
+ if (typeof payload.iat !== 'number') {
217
+ throwFormat('MALFORMED', 'Missing required field: iat');
218
+ }
219
+ if (typeof payload.exp !== 'number') {
220
+ throwFormat('MALFORMED', 'Missing required field: exp');
221
+ }
222
+ if (typeof payload.jti !== 'string') {
223
+ throwFormat('MALFORMED', 'Missing required field: jti');
224
+ }
225
+
226
+ return payload;
227
+ }
228
+
229
+ /**
230
+ * Verifies the token signature against a public key.
231
+ *
232
+ * @returns `false` for a bad signature or a wrong key. Returns
233
+ * `false` for any invalid signature, including malformed lengths.
234
+ * It still throws `AttestationError` `MALFORMED`/`FORMAT` for
235
+ * structurally invalid tokens (see {@link decode}).
236
+ */
237
+ static async verifySignature(token: string, signerPublicKey: Uint8Array): Promise<boolean> {
238
+ const { signatureBytes, payloadBytes } = parseToken(token);
239
+ try {
240
+ return ed.verify(signatureBytes, payloadBytes, signerPublicKey);
241
+ } catch {
242
+ return false;
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Wildcard name matching used for `subNamePatterns`.
248
+ * A pattern matches if it equals `name`, or ends with `*` and `name`
249
+ * starts with the pattern's prefix. A lone `*` matches everything.
250
+ *
251
+ * @example
252
+ * ```ts
253
+ * Attestation.matchNamePattern('connector-1', ['connector-*']); // true
254
+ * Attestation.matchNamePattern('meter-1', ['connector-*']); // false
255
+ * Attestation.matchNamePattern('anything', ['*']); // true
256
+ * ```
257
+ */
258
+ static matchNamePattern(name: string, patterns: string[]): boolean {
259
+ for (const pattern of patterns) {
260
+ if (pattern === '*') return true;
261
+ if (pattern.endsWith('*')) {
262
+ if (name.startsWith(pattern.slice(0, -1))) return true;
263
+ } else {
264
+ if (pattern === name) return true;
265
+ }
266
+ }
267
+ return false;
268
+ }
269
+
270
+ /**
271
+ * Creates and signs a new attestation.
272
+ *
273
+ * The subject name is canonicalized (NFKC → lowercase → trim) before
274
+ * signing; the subject public key must be exactly 32 bytes. Serialization is
275
+ * deterministic: fields are emitted in a fixed order and
276
+ * `undefined` grant fields are omitted from the JSON entirely
277
+ * (distinguishable from `[]`).
278
+ *
279
+ * @param signerPrivateKey - 32-byte Ed25519 private key of the parent.
280
+ * @param subjectPublicKey - 32-byte Ed25519 public key being attested.
281
+ * @param subjectName - Child name; canonicalized before signing.
282
+ * @param grant - Constraints enforced by verifiers (Mode 2).
283
+ * @param opts - Lifetime control: `ttlSeconds` (default one year),
284
+ * `expiresAt` (overrides `ttlSeconds`), `jti` (default random UUID),
285
+ * `now` (fixed clock for deterministic tests).
286
+ * @returns The attestation with `payload`, `token` and `jti` accessors.
287
+ * @throws {AttestationError} `MALFORMED`/`FORMAT` if the grant is
288
+ * structurally invalid (bad scopes/TTL/audiences or a wildcard
289
+ * not at the end of a `subNamePatterns` entry).
290
+ * @throws {Error} If `subjectPublicKey` is not 32 bytes.
291
+ *
292
+ * @example
293
+ * ```ts
294
+ * const att = await Attestation.issue(rootPriv, childPub, 'Station-1',
295
+ * { scopes: ['read'], maxSessionTtl: 3600 }, { ttlSeconds: 600 });
296
+ * ```
297
+ */
298
+ static async issue(
299
+ signerPrivateKey: Uint8Array,
300
+ subjectPublicKey: Uint8Array,
301
+ subjectName: string,
302
+ grant: AttestationGrant,
303
+ opts?: { ttlSeconds?: number; expiresAt?: number; jti?: string; now?: number }
304
+ ): Promise<Attestation> {
305
+ const name = normalizeName(subjectName);
306
+
307
+ if (subjectPublicKey.length !== 32) {
308
+ throw new Error('subject public key must be 32 bytes');
309
+ }
310
+
311
+ // Validate grant
312
+ if (!Array.isArray(grant.scopes) || !grant.scopes.every((s: unknown) => typeof s === 'string')) {
313
+ throwFormat('MALFORMED', 'grant.scopes must be an array of strings');
314
+ }
315
+ if (typeof grant.maxSessionTtl !== 'number' || !Number.isFinite(grant.maxSessionTtl) || grant.maxSessionTtl <= 0) {
316
+ throwFormat('MALFORMED', 'grant.maxSessionTtl must be a finite positive number');
317
+ }
318
+ if (grant.audiences !== undefined) {
319
+ if (!Array.isArray(grant.audiences) || !grant.audiences.every((a: unknown) => typeof a === 'string')) {
320
+ throwFormat('MALFORMED', 'grant.audiences must be an array of strings');
321
+ }
322
+ }
323
+ if (grant.subNamePatterns !== undefined) {
324
+ if (!Array.isArray(grant.subNamePatterns) || !grant.subNamePatterns.every((p: unknown) => typeof p === 'string')) {
325
+ throwFormat('MALFORMED', 'grant.subNamePatterns must be an array of strings');
326
+ }
327
+ for (const pattern of grant.subNamePatterns) {
328
+ const starIndex = pattern.indexOf('*');
329
+ if (starIndex !== -1 && starIndex !== pattern.length - 1) {
330
+ throwFormat('MALFORMED', `Invalid pattern: ${JSON.stringify(pattern)} — '*' only allowed at end`);
331
+ }
332
+ }
333
+ }
334
+
335
+ const now = opts?.now ?? Math.floor(Date.now() / 1000);
336
+ const exp = opts?.expiresAt ?? (now + (opts?.ttlSeconds ?? 31536000));
337
+ const jti = opts?.jti ?? crypto.randomUUID();
338
+
339
+ const grantJson: Record<string, unknown> = {};
340
+ if (grant.audiences !== undefined) grantJson.audiences = [...grant.audiences];
341
+ grantJson.scopes = [...grant.scopes];
342
+ grantJson.maxSessionTtl = grant.maxSessionTtl;
343
+ if (grant.subNamePatterns !== undefined)
344
+ grantJson.subNamePatterns = [...grant.subNamePatterns];
345
+
346
+ const payload: AttestationPayload = {
347
+ typ: ATTESTATION_TYPE,
348
+ subjectName: name,
349
+ subjectId: base64urlEncode(subjectPublicKey),
350
+ grant: grantJson as unknown as AttestationGrant,
351
+ iat: now,
352
+ exp,
353
+ jti,
354
+ };
355
+
356
+ const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
357
+ const signature = await ed.sign(payloadBytes, signerPrivateKey);
358
+ const payloadB64 = base64urlEncode(payloadBytes);
359
+ const signatureB64 = base64urlEncode(signature);
360
+ const token = `${payloadB64}.${signatureB64}`;
361
+
362
+ return new Attestation(payload, token);
363
+ }
364
+ }
@@ -0,0 +1,12 @@
1
+ // canonical-name.ts
2
+
3
+ export const NAME_PATTERN = /^[a-z0-9][a-z0-9._@-]{0,62}$/;
4
+
5
+ export function normalizeName(raw: string): string {
6
+ if (typeof raw !== 'string') throw new TypeError('Name must be a string');
7
+ const name = raw.normalize('NFKC').toLowerCase().trim();
8
+ if (!NAME_PATTERN.test(name)) {
9
+ throw new Error(`Invalid name: ${JSON.stringify(raw)}`);
10
+ }
11
+ return name;
12
+ }
@@ -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;
@@ -0,0 +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
+
8
+ import { ed } from './init.js';
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
+
73
+ /**
74
+ * Asynchronous variant of {@link verify}; same contract.
75
+ *
76
+ * @param opts - Optional verification options, forwarded to the
77
+ * underlying implementation.
78
+ */
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
 
@@ -0,0 +1,4 @@
1
+ // packages/core/src/crypto/index.ts
2
+ export * from './ed25519.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