@me2em/core 0.7.0-alpha.1 → 1.0.0-rc.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.
- package/README.md +242 -47
- package/dist/attestation.d.ts +26 -17
- package/dist/attestation.d.ts.map +1 -1
- package/dist/attestation.js +76 -29
- package/dist/attestation.js.map +1 -1
- package/dist/canonical-name.d.ts +18 -0
- package/dist/canonical-name.d.ts.map +1 -1
- package/dist/canonical-name.js +28 -1
- package/dist/canonical-name.js.map +1 -1
- package/dist/crypto/derivation-paths.d.ts +33 -2
- package/dist/crypto/derivation-paths.d.ts.map +1 -1
- package/dist/crypto/derivation-paths.js +33 -2
- package/dist/crypto/derivation-paths.js.map +1 -1
- package/dist/crypto/derivation.d.ts +47 -0
- package/dist/crypto/derivation.d.ts.map +1 -0
- package/dist/crypto/derivation.js +68 -0
- package/dist/crypto/derivation.js.map +1 -0
- package/dist/crypto/ecdh.d.ts +19 -0
- package/dist/crypto/ecdh.d.ts.map +1 -0
- package/dist/crypto/ecdh.js +33 -0
- package/dist/crypto/ecdh.js.map +1 -0
- package/dist/crypto/ed25519.d.ts +24 -3
- package/dist/crypto/ed25519.d.ts.map +1 -1
- package/dist/crypto/ed25519.js +39 -6
- package/dist/crypto/ed25519.js.map +1 -1
- package/dist/crypto/hkdf.d.ts +11 -2
- package/dist/crypto/hkdf.d.ts.map +1 -1
- package/dist/crypto/hkdf.js +13 -1
- package/dist/crypto/hkdf.js.map +1 -1
- package/dist/crypto/index.d.ts +25 -0
- package/dist/crypto/index.d.ts.map +1 -1
- package/dist/crypto/index.js +25 -0
- package/dist/crypto/index.js.map +1 -1
- package/dist/disposed-error.d.ts +24 -0
- package/dist/disposed-error.d.ts.map +1 -0
- package/dist/disposed-error.js +39 -0
- package/dist/disposed-error.js.map +1 -0
- package/dist/errors.d.ts +67 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +54 -0
- package/dist/errors.js.map +1 -0
- package/dist/handle.d.ts +300 -14
- package/dist/handle.d.ts.map +1 -1
- package/dist/handle.js +463 -54
- package/dist/handle.js.map +1 -1
- package/dist/identity.d.ts +55 -11
- package/dist/identity.d.ts.map +1 -1
- package/dist/identity.js +105 -35
- package/dist/identity.js.map +1 -1
- package/dist/index.d.ts +10 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -4
- package/dist/index.js.map +1 -1
- package/dist/seed.d.ts +33 -22
- package/dist/seed.d.ts.map +1 -1
- package/dist/seed.js +59 -31
- package/dist/seed.js.map +1 -1
- package/dist/session.d.ts +42 -5
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +248 -117
- package/dist/session.js.map +1 -1
- package/dist/subhandle.d.ts +1 -125
- package/dist/subhandle.d.ts.map +1 -1
- package/dist/subhandle.js +12 -179
- package/dist/subhandle.js.map +1 -1
- package/dist/types.d.ts +22 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/util.d.ts +47 -0
- package/dist/util.d.ts.map +1 -1
- package/dist/util.js +72 -20
- package/dist/util.js.map +1 -1
- package/package.json +12 -5
- package/src/attestation.ts +88 -38
- package/src/canonical-name.ts +33 -1
- package/src/crypto/derivation-paths.ts +37 -2
- package/src/crypto/derivation.ts +90 -0
- package/src/crypto/ecdh.ts +37 -0
- package/src/crypto/ed25519.ts +39 -6
- package/src/crypto/hkdf.ts +13 -1
- package/src/crypto/index.ts +28 -1
- package/src/disposed-error.ts +45 -0
- package/src/errors.ts +88 -0
- package/src/handle.ts +630 -65
- package/src/identity.ts +111 -64
- package/src/index.ts +13 -7
- package/src/seed.ts +75 -32
- package/src/session.ts +336 -132
- package/src/subhandle.ts +12 -251
- package/src/types.ts +26 -0
- package/src/util.ts +78 -20
package/src/attestation.ts
CHANGED
|
@@ -1,15 +1,22 @@
|
|
|
1
1
|
// attestation.ts
|
|
2
2
|
//
|
|
3
3
|
// Attestation module: cryptographically signed, self-contained
|
|
4
|
-
// authorization attestations for the
|
|
4
|
+
// authorization attestations for the Me2eM protocol.
|
|
5
5
|
|
|
6
6
|
import { normalizeName } from './canonical-name.js';
|
|
7
|
-
import { base64urlEncode, base64urlDecode } from './util.js';
|
|
7
|
+
import { base64urlEncode, base64urlDecode, randomUUID, safeJsonParse } from './util.js';
|
|
8
8
|
import { ed } from './crypto/init.js';
|
|
9
|
+
import type { Signer } from './types.js';
|
|
10
|
+
import { AttestationError, type AttestationErrorCode } from './errors.js';
|
|
11
|
+
|
|
12
|
+
export { AttestationError, type AttestationErrorCode, type AttestationLevel } from './errors.js';
|
|
9
13
|
|
|
10
14
|
export const ATTESTATION_TYPE = 'me2em/attestation/v1';
|
|
11
15
|
export const ATTESTATION_MAX_PAYLOAD = 2048;
|
|
12
16
|
|
|
17
|
+
/** Maximum accepted length of an attestation `jti` (hardening, PR-7). */
|
|
18
|
+
const MAX_JTI_LENGTH = 256;
|
|
19
|
+
|
|
13
20
|
export interface AttestationGrant {
|
|
14
21
|
/**
|
|
15
22
|
* Audiences the subject may create sessions for.
|
|
@@ -45,23 +52,6 @@ export interface AttestationPayload {
|
|
|
45
52
|
jti: string;
|
|
46
53
|
}
|
|
47
54
|
|
|
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
55
|
function throwFormat(code: AttestationErrorCode, msg: string): never {
|
|
66
56
|
throw new AttestationError(code, 'FORMAT', msg);
|
|
67
57
|
}
|
|
@@ -89,7 +79,12 @@ function parseToken(token: string): ParseResult {
|
|
|
89
79
|
throwFormat('MALFORMED', 'Payload and signature must be valid Base64URL');
|
|
90
80
|
}
|
|
91
81
|
|
|
92
|
-
|
|
82
|
+
let payloadBytes: Uint8Array;
|
|
83
|
+
try {
|
|
84
|
+
payloadBytes = base64urlDecode(payloadB64);
|
|
85
|
+
} catch {
|
|
86
|
+
throwFormat('MALFORMED', 'Payload and signature must be valid Base64URL');
|
|
87
|
+
}
|
|
93
88
|
if (payloadBytes.length > ATTESTATION_MAX_PAYLOAD) {
|
|
94
89
|
throwFormat('MALFORMED', `Payload exceeds maximum size of ${ATTESTATION_MAX_PAYLOAD} bytes`);
|
|
95
90
|
}
|
|
@@ -97,12 +92,22 @@ function parseToken(token: string): ParseResult {
|
|
|
97
92
|
let payload: AttestationPayload;
|
|
98
93
|
try {
|
|
99
94
|
const jsonString = new TextDecoder().decode(payloadBytes);
|
|
100
|
-
payload =
|
|
101
|
-
} catch {
|
|
102
|
-
throwFormat(
|
|
95
|
+
payload = safeJsonParse(jsonString) as AttestationPayload;
|
|
96
|
+
} catch (e) {
|
|
97
|
+
throwFormat(
|
|
98
|
+
'MALFORMED',
|
|
99
|
+
e instanceof SyntaxError && e.message.includes('__proto__')
|
|
100
|
+
? `Payload is not valid JSON — ${e.message}`
|
|
101
|
+
: 'Payload is not valid JSON'
|
|
102
|
+
);
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
-
|
|
105
|
+
let signatureBytes: Uint8Array;
|
|
106
|
+
try {
|
|
107
|
+
signatureBytes = base64urlDecode(signatureB64);
|
|
108
|
+
} catch {
|
|
109
|
+
throwFormat('MALFORMED', 'Payload and signature must be valid Base64URL');
|
|
110
|
+
}
|
|
106
111
|
|
|
107
112
|
return { payloadBytes, signatureBytes, payload };
|
|
108
113
|
}
|
|
@@ -121,22 +126,20 @@ function parseToken(token: string): ParseResult {
|
|
|
121
126
|
* ```ts
|
|
122
127
|
* import { ed25519 } from '@noble/curves/ed25519.js';
|
|
123
128
|
*
|
|
124
|
-
* //
|
|
125
|
-
* const
|
|
126
|
-
* const signerPub = ed25519.getPublicKey(signerPriv);
|
|
129
|
+
* // Issuer (a Signer — Identity/Handle qualify) and subject public key:
|
|
130
|
+
* const identity = await Identity.fromSeed(seed);
|
|
127
131
|
* const childPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());
|
|
128
132
|
*
|
|
129
|
-
* const A = await Attestation.issue(
|
|
133
|
+
* const A = await Attestation.issue(identity, childPub, 'station-001', {
|
|
130
134
|
* audiences: ['ev-app.com'],
|
|
131
135
|
* scopes: ['charge:start', 'charge:stop'],
|
|
132
136
|
* maxSessionTtl: 7200,
|
|
133
137
|
* subNamePatterns: ['connector-*'],
|
|
134
138
|
* });
|
|
135
139
|
*
|
|
136
|
-
* const ok = await Attestation.verifySignature(A.token,
|
|
140
|
+
* const ok = await Attestation.verifySignature(A.token, identity.getPublicKey()); // true
|
|
137
141
|
* const payload = Attestation.decode(A.token); // structure only — no sig, no time
|
|
138
|
-
*
|
|
139
|
-
* ```
|
|
142
|
+
* ```
|
|
140
143
|
*
|
|
141
144
|
* @category Core Primitives
|
|
142
145
|
*/
|
|
@@ -219,9 +222,20 @@ export class Attestation {
|
|
|
219
222
|
if (typeof payload.exp !== 'number') {
|
|
220
223
|
throwFormat('MALFORMED', 'Missing required field: exp');
|
|
221
224
|
}
|
|
222
|
-
|
|
225
|
+
// Non-finite numbers survive JSON.parse only as `Infinity` (e.g. 1e999);
|
|
226
|
+
// unchecked, `now > exp + skew` would be false forever — fail-open expiry.
|
|
227
|
+
if (!Number.isFinite(payload.iat) || !Number.isFinite(payload.exp)) {
|
|
228
|
+
throwFormat('MALFORMED', 'iat/exp must be finite numbers');
|
|
229
|
+
}
|
|
230
|
+
if (payload.exp <= payload.iat) {
|
|
231
|
+
throwFormat('MALFORMED', 'exp must be greater than iat');
|
|
232
|
+
}
|
|
233
|
+
if (typeof payload.jti !== 'string' || payload.jti.length === 0) {
|
|
223
234
|
throwFormat('MALFORMED', 'Missing required field: jti');
|
|
224
235
|
}
|
|
236
|
+
if (payload.jti.length > MAX_JTI_LENGTH) {
|
|
237
|
+
throwFormat('MALFORMED', `jti exceeds the maximum length of ${MAX_JTI_LENGTH} characters`);
|
|
238
|
+
}
|
|
225
239
|
|
|
226
240
|
return payload;
|
|
227
241
|
}
|
|
@@ -229,6 +243,10 @@ export class Attestation {
|
|
|
229
243
|
/**
|
|
230
244
|
* Verifies the token signature against a public key.
|
|
231
245
|
*
|
|
246
|
+
* A signature whose length differs from the 64-byte Ed25519 size is
|
|
247
|
+
* rejected with `false` before any crypto runs (PR-7 pre-check) —
|
|
248
|
+
* the method therefore never throws for short/long signatures.
|
|
249
|
+
*
|
|
232
250
|
* @returns `false` for a bad signature or a wrong key. Returns
|
|
233
251
|
* `false` for any invalid signature, including malformed lengths.
|
|
234
252
|
* It still throws `AttestationError` `MALFORMED`/`FORMAT` for
|
|
@@ -236,6 +254,11 @@ export class Attestation {
|
|
|
236
254
|
*/
|
|
237
255
|
static async verifySignature(token: string, signerPublicKey: Uint8Array): Promise<boolean> {
|
|
238
256
|
const { signatureBytes, payloadBytes } = parseToken(token);
|
|
257
|
+
// Ed25519 signatures are exactly 64 bytes — reject other lengths
|
|
258
|
+
// before the curve math (the underlying library throws RangeError).
|
|
259
|
+
if (signatureBytes.length !== 64) {
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
239
262
|
try {
|
|
240
263
|
return ed.verify(signatureBytes, payloadBytes, signerPublicKey);
|
|
241
264
|
} catch {
|
|
@@ -276,7 +299,16 @@ export class Attestation {
|
|
|
276
299
|
* `undefined` grant fields are omitted from the JSON entirely
|
|
277
300
|
* (distinguishable from `[]`).
|
|
278
301
|
*
|
|
279
|
-
*
|
|
302
|
+
* The `signer` is a {@link Signer} — typically the issuing
|
|
303
|
+
* {@link Identity} (root attestations) or {@link Handle} (SubHandle
|
|
304
|
+
* attestations). Raw private keys never cross a trust boundary as
|
|
305
|
+
* function arguments (D2): the key material stays encapsulated in the
|
|
306
|
+
* signer object.
|
|
307
|
+
*
|
|
308
|
+
* @param signer - Object producing the Ed25519 signature via
|
|
309
|
+
* `sign(data)`. `Identity` and `Handle` implement `Signer`; custom
|
|
310
|
+
* implementations (remote/HSM-backed signing) are accepted
|
|
311
|
+
* structurally.
|
|
280
312
|
* @param subjectPublicKey - 32-byte Ed25519 public key being attested.
|
|
281
313
|
* @param subjectName - Child name; canonicalized before signing.
|
|
282
314
|
* @param grant - Constraints enforced by verifiers (Mode 2).
|
|
@@ -287,25 +319,43 @@ export class Attestation {
|
|
|
287
319
|
* @throws {AttestationError} `MALFORMED`/`FORMAT` if the grant is
|
|
288
320
|
* structurally invalid (bad scopes/TTL/audiences or a wildcard
|
|
289
321
|
* not at the end of a `subNamePatterns` entry).
|
|
322
|
+
* @throws {TypeError} If `signer` has no callable `sign` method — e.g.
|
|
323
|
+
* when a raw private key is passed (the pre-v1.0 form is no longer
|
|
324
|
+
* accepted).
|
|
290
325
|
* @throws {Error} If `subjectPublicKey` is not 32 bytes.
|
|
291
326
|
*
|
|
292
327
|
* @example
|
|
293
328
|
* ```ts
|
|
294
|
-
* const att = await Attestation.issue(
|
|
329
|
+
* const att = await Attestation.issue(rootIdentity, childPub, 'Station-1',
|
|
295
330
|
* { scopes: ['read'], maxSessionTtl: 3600 }, { ttlSeconds: 600 });
|
|
296
331
|
* ```
|
|
297
332
|
*/
|
|
298
333
|
static async issue(
|
|
299
|
-
|
|
334
|
+
signer: Signer,
|
|
300
335
|
subjectPublicKey: Uint8Array,
|
|
301
336
|
subjectName: string,
|
|
302
337
|
grant: AttestationGrant,
|
|
303
338
|
opts?: { ttlSeconds?: number; expiresAt?: number; jti?: string; now?: number }
|
|
304
339
|
): Promise<Attestation> {
|
|
340
|
+
if (typeof (signer as Signer | undefined)?.sign !== 'function') {
|
|
341
|
+
throw new TypeError(
|
|
342
|
+
'Attestation.issue requires a Signer — an object with a sign(data) ' +
|
|
343
|
+
'method (Identity or Handle). Raw private keys are no longer accepted.'
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
|
|
305
347
|
const name = normalizeName(subjectName);
|
|
306
348
|
|
|
307
349
|
if (subjectPublicKey.length !== 32) {
|
|
308
|
-
|
|
350
|
+
throwFormat('MALFORMED', 'subject public key must be 32 bytes');
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (opts?.jti !== undefined &&
|
|
354
|
+
(typeof opts.jti !== 'string' || opts.jti.length === 0 || opts.jti.length > MAX_JTI_LENGTH)) {
|
|
355
|
+
throwFormat(
|
|
356
|
+
'MALFORMED',
|
|
357
|
+
`opts.jti must be a non-empty string of at most ${MAX_JTI_LENGTH} characters`
|
|
358
|
+
);
|
|
309
359
|
}
|
|
310
360
|
|
|
311
361
|
// Validate grant
|
|
@@ -334,7 +384,7 @@ export class Attestation {
|
|
|
334
384
|
|
|
335
385
|
const now = opts?.now ?? Math.floor(Date.now() / 1000);
|
|
336
386
|
const exp = opts?.expiresAt ?? (now + (opts?.ttlSeconds ?? 31536000));
|
|
337
|
-
const jti = opts?.jti ??
|
|
387
|
+
const jti = opts?.jti ?? randomUUID();
|
|
338
388
|
|
|
339
389
|
const grantJson: Record<string, unknown> = {};
|
|
340
390
|
if (grant.audiences !== undefined) grantJson.audiences = [...grant.audiences];
|
|
@@ -354,7 +404,7 @@ export class Attestation {
|
|
|
354
404
|
};
|
|
355
405
|
|
|
356
406
|
const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
|
|
357
|
-
const signature = await
|
|
407
|
+
const signature = await signer.sign(payloadBytes);
|
|
358
408
|
const payloadB64 = base64urlEncode(payloadBytes);
|
|
359
409
|
const signatureB64 = base64urlEncode(signature);
|
|
360
410
|
const token = `${payloadB64}.${signatureB64}`;
|
package/src/canonical-name.ts
CHANGED
|
@@ -1,12 +1,44 @@
|
|
|
1
1
|
// canonical-name.ts
|
|
2
2
|
|
|
3
|
+
import { AttestationError } from './errors.js';
|
|
4
|
+
|
|
3
5
|
export const NAME_PATTERN = /^[a-z0-9][a-z0-9._@-]{0,62}$/;
|
|
4
6
|
|
|
5
7
|
export function normalizeName(raw: string): string {
|
|
6
8
|
if (typeof raw !== 'string') throw new TypeError('Name must be a string');
|
|
7
9
|
const name = raw.normalize('NFKC').toLowerCase().trim();
|
|
8
10
|
if (!NAME_PATTERN.test(name)) {
|
|
9
|
-
throw new
|
|
11
|
+
throw new AttestationError('MALFORMED', 'FORMAT', `Invalid name: ${JSON.stringify(raw)}`);
|
|
10
12
|
}
|
|
11
13
|
return name;
|
|
12
14
|
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Canonicalizes a password/channel context: NFKC → lowercase → trim.
|
|
18
|
+
*
|
|
19
|
+
* Same canonical form as {@link normalizeName} names use, minus the
|
|
20
|
+
* character-set pattern — a context is a caller-defined HKDF label, not
|
|
21
|
+
* a wire identifier. The canonical context is embedded verbatim into the
|
|
22
|
+
* derivation salt (`me2em/secret/{context}`, `me2em/channel/{context}`),
|
|
23
|
+
* so `' GitHub '`, `'github'` and the fullwidth `'GitHub'` all map to
|
|
24
|
+
* the same secret (specs/v1.0.md §1, since the revisions PR-8; the
|
|
25
|
+
* pre-revision rule was lowercase → trim without NFKC).
|
|
26
|
+
*
|
|
27
|
+
* @param raw - Caller-defined context, e.g. `'github'`, `'telemetry-v1'`.
|
|
28
|
+
* @returns The canonical context.
|
|
29
|
+
* @throws TypeError if `raw` is not a string (API misuse).
|
|
30
|
+
* @throws AttestationError `MALFORMED`/`FORMAT` if the context is empty
|
|
31
|
+
* after canonicalization.
|
|
32
|
+
*/
|
|
33
|
+
export function normalizeContext(raw: string): string {
|
|
34
|
+
if (typeof raw !== 'string') throw new TypeError('Context must be a string');
|
|
35
|
+
const ctx = raw.normalize('NFKC').toLowerCase().trim();
|
|
36
|
+
if (ctx.length === 0) {
|
|
37
|
+
throw new AttestationError(
|
|
38
|
+
'MALFORMED',
|
|
39
|
+
'FORMAT',
|
|
40
|
+
`Context must not be empty after canonicalization: ${JSON.stringify(raw)}`
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
return ctx;
|
|
44
|
+
}
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
import { normalizeName } from '../canonical-name.js';
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
|
-
* Deterministic derivation paths for the
|
|
13
|
+
* Deterministic derivation paths for the Me2eM protocol.
|
|
14
14
|
*
|
|
15
15
|
* All HKDF info strings used to derive Identity, Handle, and SubHandle keys
|
|
16
16
|
* are centralized here. This guarantees that:
|
|
@@ -47,10 +47,45 @@ export const DERIVATION_PATHS = {
|
|
|
47
47
|
`me2em/subhandle/v1/${normalizeName(handleName)}/${normalizeName(subName)}`,
|
|
48
48
|
|
|
49
49
|
/**
|
|
50
|
-
*
|
|
50
|
+
* Info string for peer-to-peer channel key derivation.
|
|
51
51
|
* v2 binds both peers' public keys into the derivation, preventing
|
|
52
52
|
* unknown key-share attacks. The peer keys are appended in sorted
|
|
53
53
|
* order so both parties derive the identical string.
|
|
54
54
|
*/
|
|
55
55
|
p2pChannelV2: 'me2em/p2p-channel/v2',
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Builds the info string for password (secret) derivation.
|
|
59
|
+
*
|
|
60
|
+
* Revision model (PR-8, D3): revision `1` — the initial revision — and
|
|
61
|
+
* an omitted revision both yield the frozen v1 info string, so the
|
|
62
|
+
* default derivation is byte-identical to the pre-revision protocol.
|
|
63
|
+
* Revision `N ≥ 2` appends a `/rN` path segment and derives a secret
|
|
64
|
+
* that is cryptographically independent of revision 1 for the same
|
|
65
|
+
* context — the sanctioned rotation path (specs/v1.0.md §3, PLAN-LTS
|
|
66
|
+
* §4 derivation-freeze rule).
|
|
67
|
+
*
|
|
68
|
+
* @param revision - Positive integer revision; default `1`.
|
|
69
|
+
* @returns The info string, e.g. `"me2em/secret/v1"` or `"me2em/secret/v1/r2"`.
|
|
70
|
+
*
|
|
71
|
+
* @since 0.8.0
|
|
72
|
+
*/
|
|
73
|
+
password: (revision: number = 1): string =>
|
|
74
|
+
revision === 1 ? 'me2em/secret/v1' : `me2em/secret/v1/r${revision}`,
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Builds the info string for channel-key derivation.
|
|
78
|
+
*
|
|
79
|
+
* Same revision model as {@link DERIVATION_PATHS.password}: revision
|
|
80
|
+
* `1`/omitted yields the frozen `"me2em/channel/v1"`; revision
|
|
81
|
+
* `N ≥ 2` yields `"me2em/channel/v1/rN"` — an independent key for
|
|
82
|
+
* rotating a compromised channel without changing the context.
|
|
83
|
+
*
|
|
84
|
+
* @param revision - Positive integer revision; default `1`.
|
|
85
|
+
* @returns The info string, e.g. `"me2em/channel/v1"` or `"me2em/channel/v1/r2"`.
|
|
86
|
+
*
|
|
87
|
+
* @since 0.8.0
|
|
88
|
+
*/
|
|
89
|
+
channel: (revision: number = 1): string =>
|
|
90
|
+
revision === 1 ? 'me2em/channel/v1' : `me2em/channel/v1/r${revision}`,
|
|
56
91
|
} as const;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// packages/core/src/crypto/derivation.ts
|
|
2
|
+
//
|
|
3
|
+
// Key-derivation helpers shared by every derivation entry point
|
|
4
|
+
// (PR-10, tasks 3.2/5.3.3). `Identity.fromSeed`, `Identity.deriveHandle`,
|
|
5
|
+
// `Identity.deriveSubHandle` and `Handle.deriveSubHandle` all route
|
|
6
|
+
// through these functions, which is what guarantees the byte-parity the
|
|
7
|
+
// spec pins (specs/v1.0.md §3): the two-step derivation
|
|
8
|
+
// (`handle.deriveSubHandle`) and the atomic derivation
|
|
9
|
+
// (`identity.deriveSubHandle`) MUST produce the same SubHandle key.
|
|
10
|
+
//
|
|
11
|
+
// All functions derive with HKDF-SHA256 (RFC 5869), salt = "" (zero
|
|
12
|
+
// length), 32-byte output — see specs/v1.0.md §3. The info strings come
|
|
13
|
+
// exclusively from {@link DERIVATION_PATHS} (single source of truth).
|
|
14
|
+
|
|
15
|
+
import { hkdf } from './hkdf.js';
|
|
16
|
+
import { DERIVATION_PATHS } from './derivation-paths.js';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Derives the root Identity key from the 64-byte seed.
|
|
20
|
+
*
|
|
21
|
+
* `HKDF-SHA256(seed, salt = "", info = "me2em/identity/v1/root", 32)`
|
|
22
|
+
* (specs/v1.0.md §2–§3). This is the exact computation
|
|
23
|
+
* `Identity.fromSeed` performs; exposed so advanced callers can
|
|
24
|
+
* reproduce or audit the derivation without holding an Identity
|
|
25
|
+
* instance.
|
|
26
|
+
*
|
|
27
|
+
* @param seed - The 64-byte BIP39 seed (specs/v1.0.md §2).
|
|
28
|
+
* @returns The 32-byte Ed25519 root private key.
|
|
29
|
+
* @since 0.8.0
|
|
30
|
+
*/
|
|
31
|
+
export function deriveRootKey(seed: Uint8Array): Uint8Array {
|
|
32
|
+
return hkdf(
|
|
33
|
+
seed,
|
|
34
|
+
new Uint8Array(0),
|
|
35
|
+
new TextEncoder().encode(DERIVATION_PATHS.identity),
|
|
36
|
+
32
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Derives a Handle key from the root Identity key.
|
|
42
|
+
*
|
|
43
|
+
* `HKDF-SHA256(rootKey, salt = "", info = "me2em/handle/v1/{name}", 32)`.
|
|
44
|
+
* `name` is canonicalized (NFKC → lowercase → trim) by
|
|
45
|
+
* {@link DERIVATION_PATHS.handle}.
|
|
46
|
+
*
|
|
47
|
+
* @param rootKey - The 32-byte root private key (see {@link deriveRootKey}).
|
|
48
|
+
* @param name - The Handle name.
|
|
49
|
+
* @returns The 32-byte Ed25519 Handle private key.
|
|
50
|
+
* @since 0.8.0
|
|
51
|
+
*/
|
|
52
|
+
export function deriveHandleKey(rootKey: Uint8Array, name: string): Uint8Array {
|
|
53
|
+
return hkdf(
|
|
54
|
+
rootKey,
|
|
55
|
+
new Uint8Array(0),
|
|
56
|
+
new TextEncoder().encode(DERIVATION_PATHS.handle(name)),
|
|
57
|
+
32
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Derives a SubHandle key from its parent Handle key — the single
|
|
63
|
+
* implementation shared by `Handle.deriveSubHandle` (autonomous,
|
|
64
|
+
* two-step from the Handle) and `Identity.deriveSubHandle` (atomic,
|
|
65
|
+
* from the Identity). Byte-parity of both entry points is pinned by
|
|
66
|
+
* test 5.3.3 (`derivation.spec.ts`) and by the golden vectors.
|
|
67
|
+
*
|
|
68
|
+
* `HKDF-SHA256(handleKey, salt = "",
|
|
69
|
+
* info = "me2em/subhandle/v1/{handleName}/{subName}", 32)`. Both names
|
|
70
|
+
* are canonicalized (NFKC → lowercase → trim) by
|
|
71
|
+
* {@link DERIVATION_PATHS.subhandle}.
|
|
72
|
+
*
|
|
73
|
+
* @param handleKey - The 32-byte parent Handle private key.
|
|
74
|
+
* @param handleName - The parent Handle name.
|
|
75
|
+
* @param subName - The SubHandle name.
|
|
76
|
+
* @returns The 32-byte Ed25519 SubHandle private key.
|
|
77
|
+
* @since 0.8.0
|
|
78
|
+
*/
|
|
79
|
+
export function deriveSubHandleKey(
|
|
80
|
+
handleKey: Uint8Array,
|
|
81
|
+
handleName: string,
|
|
82
|
+
subName: string
|
|
83
|
+
): Uint8Array {
|
|
84
|
+
return hkdf(
|
|
85
|
+
handleKey,
|
|
86
|
+
new Uint8Array(0),
|
|
87
|
+
new TextEncoder().encode(DERIVATION_PATHS.subhandle(handleName, subName)),
|
|
88
|
+
32
|
|
89
|
+
);
|
|
90
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// packages/core/src/crypto/ecdh.ts
|
|
2
|
+
//
|
|
3
|
+
// X25519 (Montgomery) ECDH step of the P2P shared-secret derivation
|
|
4
|
+
// (specs/v1.0.md §3 "P2P"): both Ed25519 keypairs are converted to the
|
|
5
|
+
// Montgomery form (RFC 7748) and the raw X25519 output becomes the HKDF
|
|
6
|
+
// IKM. Isolated here (PR-10, task 3.3.1) so that no protocol module
|
|
7
|
+
// imports `@noble/curves` directly — every crypto primitive lives
|
|
8
|
+
// under `crypto/` and reaches the rest of the codebase through
|
|
9
|
+
// documented wrappers.
|
|
10
|
+
|
|
11
|
+
import { ed25519, x25519 } from '@noble/curves/ed25519.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Computes the raw X25519 shared secret between this party's Ed25519
|
|
15
|
+
* private key and the peer's Ed25519 public key (both converted to the
|
|
16
|
+
* Montgomery form, RFC 7748). ECDH is symmetric, so the result is
|
|
17
|
+
* order-independent — and byte-identical on both peers.
|
|
18
|
+
*
|
|
19
|
+
* This is only the raw ECDH output. The protocol derivation
|
|
20
|
+
* ({@link Handle.deriveSharedSecret}) additionally binds both peers'
|
|
21
|
+
* public keys into the HKDF salt and expands with the P2P info string;
|
|
22
|
+
* never encrypt with the raw output alone.
|
|
23
|
+
*
|
|
24
|
+
* @param myPrivateKey - This party's 32-byte Ed25519 private key.
|
|
25
|
+
* @param otherPublicKey - The peer's 32-byte Ed25519 public key.
|
|
26
|
+
* @returns The 32-byte raw ECDH output — the HKDF IKM of the P2P
|
|
27
|
+
* derivation.
|
|
28
|
+
* @since 0.8.0
|
|
29
|
+
*/
|
|
30
|
+
export function rawX25519SharedSecret(
|
|
31
|
+
myPrivateKey: Uint8Array,
|
|
32
|
+
otherPublicKey: Uint8Array
|
|
33
|
+
): Uint8Array {
|
|
34
|
+
const montgomerySecret = ed25519.utils.toMontgomerySecret(myPrivateKey);
|
|
35
|
+
const montgomeryPeer = ed25519.utils.toMontgomery(otherPublicKey);
|
|
36
|
+
return x25519.getSharedSecret(montgomerySecret, montgomeryPeer);
|
|
37
|
+
}
|
package/src/crypto/ed25519.ts
CHANGED
|
@@ -1,9 +1,21 @@
|
|
|
1
1
|
// packages/core/src/crypto/ed25519.ts
|
|
2
2
|
//
|
|
3
3
|
// Documented wrappers around the @noble/ed25519 primitives used by the
|
|
4
|
-
// protocol. These are real functions rather than alias re-exports,
|
|
5
|
-
//
|
|
6
|
-
//
|
|
4
|
+
// protocol. These are real functions rather than alias re-exports, for
|
|
5
|
+
// two stable reasons (see also the BACKLOG.md house rule):
|
|
6
|
+
//
|
|
7
|
+
// 1. Documentation ownership — generated documentation is fully owned
|
|
8
|
+
// by this package and never inherits comments (or broken links)
|
|
9
|
+
// from the upstream library; TypeDoc renders these TSDoc blocks
|
|
10
|
+
// verbatim on the docs site (TSDoc is the source of truth).
|
|
11
|
+
// 2. Typing isolation — the upstream `ed` entity's typing produces
|
|
12
|
+
// TypeDoc warnings that fail the `treatWarningsAsErrors: true`
|
|
13
|
+
// docs build; local wrappers keep the public surface clean.
|
|
14
|
+
//
|
|
15
|
+
// The wrappers are public API surface (the `crypto` namespace,
|
|
16
|
+
// specs/v1.0.md §12) and are pinned by test/arch-cycle.spec.ts parity
|
|
17
|
+
// tests. Removing them is a breaking 2.0.0 decision — do not propose
|
|
18
|
+
// (PLAN amendment A5).
|
|
7
19
|
|
|
8
20
|
import { ed } from './init.js';
|
|
9
21
|
|
|
@@ -57,24 +69,45 @@ export function verify(
|
|
|
57
69
|
}
|
|
58
70
|
|
|
59
71
|
/**
|
|
60
|
-
*
|
|
72
|
+
* Derives the Ed25519 public key for a private key (asynchronous
|
|
73
|
+
* variant of {@link getPublicKey}; same contract).
|
|
74
|
+
*
|
|
75
|
+
* @param privateKey - 32-byte Ed25519 private key.
|
|
76
|
+
* @returns A Promise resolving to the 32-byte public key.
|
|
77
|
+
* @throws `TypeError` if the key length is invalid.
|
|
78
|
+
* @throws `RangeError` if the key length is invalid.
|
|
61
79
|
*/
|
|
62
80
|
export async function getPublicKeyAsync(privateKey: Uint8Array): Promise<Uint8Array> {
|
|
63
81
|
return ed.getPublicKeyAsync(privateKey);
|
|
64
82
|
}
|
|
65
83
|
|
|
66
84
|
/**
|
|
67
|
-
*
|
|
85
|
+
* Signs a message with an Ed25519 private key (asynchronous variant of
|
|
86
|
+
* {@link sign}; same contract).
|
|
87
|
+
*
|
|
88
|
+
* @param message - The bytes to sign.
|
|
89
|
+
* @param privateKey - 32-byte Ed25519 private key.
|
|
90
|
+
* @returns A Promise resolving to the 64-byte signature.
|
|
91
|
+
* @throws `TypeError` if an input length is invalid.
|
|
92
|
+
* @throws `RangeError` if an input length is invalid.
|
|
68
93
|
*/
|
|
69
94
|
export async function signAsync(message: Uint8Array, privateKey: Uint8Array): Promise<Uint8Array> {
|
|
70
95
|
return ed.signAsync(message, privateKey);
|
|
71
96
|
}
|
|
72
97
|
|
|
73
98
|
/**
|
|
74
|
-
*
|
|
99
|
+
* Verifies an Ed25519 signature (asynchronous variant of
|
|
100
|
+
* {@link verify}; same contract).
|
|
75
101
|
*
|
|
102
|
+
* @param signature - The 64-byte signature.
|
|
103
|
+
* @param message - The signed message bytes.
|
|
104
|
+
* @param publicKey - The 32-byte signer public key.
|
|
76
105
|
* @param opts - Optional verification options, forwarded to the
|
|
77
106
|
* underlying implementation.
|
|
107
|
+
* @returns A Promise resolving to `true` if the signature is valid,
|
|
108
|
+
* `false` otherwise.
|
|
109
|
+
* @throws `TypeError` if an input length is invalid.
|
|
110
|
+
* @throws `RangeError` if an input length is invalid.
|
|
78
111
|
*/
|
|
79
112
|
export async function verifyAsync(
|
|
80
113
|
signature: Uint8Array,
|
package/src/crypto/hkdf.ts
CHANGED
|
@@ -21,4 +21,16 @@ export function hkdf(
|
|
|
21
21
|
return nobleHkdf(nobleSha256, ikm, salt, info, length);
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
/**
|
|
25
|
+
* SHA-256 hash function (wrapper over `@noble/hashes/sha2`).
|
|
26
|
+
*
|
|
27
|
+
* Exposed as a building block for application-side tooling that needs
|
|
28
|
+
* the same hash the protocol's derivation uses; the derivation module
|
|
29
|
+
* consumes it internally.
|
|
30
|
+
*
|
|
31
|
+
* @param input - The bytes to hash.
|
|
32
|
+
* @returns The 32-byte SHA-256 digest.
|
|
33
|
+
*/
|
|
34
|
+
export function sha256(input: Uint8Array): Uint8Array {
|
|
35
|
+
return nobleSha256(input);
|
|
36
|
+
}
|
package/src/crypto/index.ts
CHANGED
|
@@ -1,4 +1,31 @@
|
|
|
1
1
|
// packages/core/src/crypto/index.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The `crypto` namespace: low-level cryptographic primitives and the
|
|
5
|
+
* derivation module of the protocol.
|
|
6
|
+
*
|
|
7
|
+
* Two groups live here:
|
|
8
|
+
*
|
|
9
|
+
* - **Derivation (HKDF-SHA256, RFC 5869):** `deriveRootKey`,
|
|
10
|
+
* `deriveHandleKey`, `deriveSubHandleKey`, `rawX25519SharedSecret`,
|
|
11
|
+
* plus the frozen {@link DERIVATION_PATHS} info-string registry.
|
|
12
|
+
* These are the derivation functions of specs/v1.0.md §3 —
|
|
13
|
+
* deterministic, versioned, byte-pinned by the golden vectors.
|
|
14
|
+
* - **Raw primitives (Ed25519, RFC 8032):** `getPublicKey`, `sign`,
|
|
15
|
+
* `verify` and their `*Async` variants, plus the `hkdf` / `sha256`
|
|
16
|
+
* helpers — documented wrappers around the configured `@noble`
|
|
17
|
+
* backend (see the ed25519 module header for why they exist as real
|
|
18
|
+
* functions). Building blocks for tooling outside the token flow;
|
|
19
|
+
* the protocol itself signs through `Identity` / `Handle` /
|
|
20
|
+
* `SubHandle`, which implement `Signer`.
|
|
21
|
+
*
|
|
22
|
+
* The namespace is part of the frozen public API (specs/v1.0.md §12).
|
|
23
|
+
* Note: `derivePassword` and `deriveChannelKey` are `Handle` methods,
|
|
24
|
+
* not namespace members.
|
|
25
|
+
*/
|
|
26
|
+
|
|
2
27
|
export * from './ed25519.js';
|
|
3
28
|
export * from './hkdf.js';
|
|
4
|
-
export * from './derivation-paths.js';
|
|
29
|
+
export * from './derivation-paths.js';
|
|
30
|
+
export * from './derivation.js';
|
|
31
|
+
export * from './ecdh.js';
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// disposed-error.ts
|
|
2
|
+
//
|
|
3
|
+
// Thrown by Identity/Handle/SubHandle methods that require key material
|
|
4
|
+
// after the object has been disposed. Informational getters (name, path,
|
|
5
|
+
// public key, metadata) deliberately keep working after dispose() — only
|
|
6
|
+
// capabilities are revoked.
|
|
7
|
+
//
|
|
8
|
+
// Since PR-7 the class extends {@link AttestationError} with the
|
|
9
|
+
// `DISPOSED` code (level `FORMAT`), so the whole package surface is
|
|
10
|
+
// catchable as a single error type while `instanceof DisposedError`
|
|
11
|
+
// keeps working for targeted handling.
|
|
12
|
+
|
|
13
|
+
import { AttestationError } from './errors.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Thrown when a method that requires key material is called on an
|
|
17
|
+
* {@link Identity} or a {@link Handle}/{@link SubHandle} that has been
|
|
18
|
+
* disposed via {@link Identity.dispose} / {@link Handle.dispose}.
|
|
19
|
+
*
|
|
20
|
+
* The private key bytes are zeroized by `dispose()`; calling a capability
|
|
21
|
+
* method afterwards is always a programming error, never a recoverable
|
|
22
|
+
* state — match on `e.name === 'DisposedError'` (or `instanceof`).
|
|
23
|
+
* As an {@link AttestationError} subclass it carries `code === 'DISPOSED'`
|
|
24
|
+
* and `level === 'FORMAT'`.
|
|
25
|
+
*
|
|
26
|
+
* @category Errors
|
|
27
|
+
*/
|
|
28
|
+
export class DisposedError extends AttestationError {
|
|
29
|
+
/** Name of the disposed class, e.g. `'Identity'`, `'Handle'`, `'SubHandle'`. */
|
|
30
|
+
public readonly className: string;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param className - Name of the disposed class, used in the message and
|
|
34
|
+
* exposed as {@link DisposedError.className}.
|
|
35
|
+
*/
|
|
36
|
+
constructor(className: string) {
|
|
37
|
+
super(
|
|
38
|
+
'DISPOSED',
|
|
39
|
+
'FORMAT',
|
|
40
|
+
`${className} has been disposed; its key material has been zeroized`
|
|
41
|
+
);
|
|
42
|
+
this.name = 'DisposedError';
|
|
43
|
+
this.className = className;
|
|
44
|
+
}
|
|
45
|
+
}
|