@me2em/core 0.4.4-alpha.2 → 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 (70) hide show
  1. package/README.md +293 -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 +147 -28
  29. package/dist/handle.d.ts.map +1 -1
  30. package/dist/handle.js +178 -33
  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 +22 -35
  41. package/dist/seed.d.ts.map +1 -1
  42. package/dist/seed.js +26 -36
  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 +158 -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 +226 -36
  65. package/src/identity.ts +164 -35
  66. package/src/index.ts +5 -1
  67. package/src/seed.ts +41 -54
  68. package/src/session.ts +637 -24
  69. package/src/subhandle.ts +230 -0
  70. package/src/util.ts +35 -0
@@ -0,0 +1,151 @@
1
+ export declare const ATTESTATION_TYPE = "me2em/attestation/v1";
2
+ export declare const ATTESTATION_MAX_PAYLOAD = 2048;
3
+ export interface AttestationGrant {
4
+ /**
5
+ * Audiences the subject may create sessions for.
6
+ * `undefined` = unrestricted; `[]` = deny all (fail-closed).
7
+ */
8
+ audiences?: string[];
9
+ /**
10
+ * Exact scope strings the subject may request. Wildcards are NOT
11
+ * supported here — only `subNamePatterns` supports wildcards.
12
+ */
13
+ scopes: string[];
14
+ /**
15
+ * Maximum session TTL (seconds) the subject may create. Must be a
16
+ * finite positive number.
17
+ */
18
+ maxSessionTtl: number;
19
+ /**
20
+ * Permitted child (SubHandle) names. Only meaningful on
21
+ * Identity→Handle attestations. Each pattern is either an exact name
22
+ * or ends with a single trailing `*` (prefix match); a lone `*`
23
+ * matches everything. Patterns like `a*b` are rejected at issue time.
24
+ */
25
+ subNamePatterns?: string[];
26
+ }
27
+ export interface AttestationPayload {
28
+ typ: typeof ATTESTATION_TYPE;
29
+ subjectName: string;
30
+ subjectId: string;
31
+ grant: AttestationGrant;
32
+ iat: number;
33
+ exp: number;
34
+ jti: string;
35
+ }
36
+ export type AttestationErrorCode = 'MALFORMED' | 'BAD_SIGNATURE' | 'EXPIRED' | 'NOT_YET_VALID' | 'REVOKED' | 'PATH_MISMATCH' | 'NAME_NOT_PERMITTED' | 'SCOPE_EXCEEDED' | 'AUDIENCE_NOT_PERMITTED' | 'TTL_EXCEEDED' | 'CHAIN_INCOMPLETE' | 'SUBJECT_MISMATCH' | 'SESSION_OUTLIVES_ATTESTATION';
37
+ export type AttestationLevel = 'ROOT' | 'HANDLE_ATTESTATION' | 'SUB_ATTESTATION' | 'SESSION' | 'FORMAT';
38
+ export declare class AttestationError extends Error {
39
+ readonly code: AttestationErrorCode;
40
+ readonly level: AttestationLevel;
41
+ constructor(code: AttestationErrorCode, level: AttestationLevel, msg: string);
42
+ }
43
+ /**
44
+ * A parent-signed statement binding a derived child key to a name and a
45
+ * grant. Chains of attestations (`Identity → Handle → SubHandle`) allow
46
+ * any third party to verify sessions offline using only the root public
47
+ * key, with grant constraints enforced at verification time.
48
+ *
49
+ * Tokens have the form `base64url(payload).base64url(signature)` and are
50
+ * deterministic: the same inputs (including `jti` and `now`) always
51
+ * produce byte-identical tokens.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * import { ed25519 } from '@noble/curves/ed25519.js';
56
+ *
57
+ * // Parent (signer) and child (subject) keys — use a CSPRNG in practice:
58
+ * const signerPriv = ed25519.utils.randomPrivateKey();
59
+ * const signerPub = ed25519.getPublicKey(signerPriv);
60
+ * const childPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());
61
+ *
62
+ * const A = await Attestation.issue(signerPriv, childPub, 'station-001', {
63
+ * audiences: ['ev-app.com'],
64
+ * scopes: ['charge:start', 'charge:stop'],
65
+ * maxSessionTtl: 7200,
66
+ * subNamePatterns: ['connector-*'],
67
+ * });
68
+ *
69
+ * const ok = await Attestation.verifySignature(A.token, signerPub); // true
70
+ * const payload = Attestation.decode(A.token); // structure only — no sig, no time
71
+ *
72
+ * ```
73
+ *
74
+ * @category Core Primitives
75
+ */
76
+ export declare class Attestation {
77
+ private readonly _payload;
78
+ private readonly _token;
79
+ private constructor();
80
+ get payload(): AttestationPayload;
81
+ get token(): string;
82
+ get jti(): string;
83
+ /**
84
+ * Parses a token and validates its structure WITHOUT checking the
85
+ * signature or any timestamps. Use {@link verifySignature} for the
86
+ * signature; expiration is checked by `Session.verifyAttested`.
87
+ *
88
+ * @throws {AttestationError} `MALFORMED`/`FORMAT` on any structural
89
+ * problem: wrong shape, invalid Base64URL, size over
90
+ * {@link ATTESTATION_MAX_PAYLOAD}, non-JSON payload, wrong `typ`,
91
+ * missing/ill-typed fields, or a non-positive/NaN `maxSessionTtl`.
92
+ */
93
+ static decode(token: string): AttestationPayload;
94
+ /**
95
+ * Verifies the token signature against a public key.
96
+ *
97
+ * @returns `false` for a bad signature or a wrong key. Returns
98
+ * `false` for any invalid signature, including malformed lengths.
99
+ * It still throws `AttestationError` `MALFORMED`/`FORMAT` for
100
+ * structurally invalid tokens (see {@link decode}).
101
+ */
102
+ static verifySignature(token: string, signerPublicKey: Uint8Array): Promise<boolean>;
103
+ /**
104
+ * Wildcard name matching used for `subNamePatterns`.
105
+ * A pattern matches if it equals `name`, or ends with `*` and `name`
106
+ * starts with the pattern's prefix. A lone `*` matches everything.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * Attestation.matchNamePattern('connector-1', ['connector-*']); // true
111
+ * Attestation.matchNamePattern('meter-1', ['connector-*']); // false
112
+ * Attestation.matchNamePattern('anything', ['*']); // true
113
+ * ```
114
+ */
115
+ static matchNamePattern(name: string, patterns: string[]): boolean;
116
+ /**
117
+ * Creates and signs a new attestation.
118
+ *
119
+ * The subject name is canonicalized (NFKC → lowercase → trim) before
120
+ * signing; the subject public key must be exactly 32 bytes. Serialization is
121
+ * deterministic: fields are emitted in a fixed order and
122
+ * `undefined` grant fields are omitted from the JSON entirely
123
+ * (distinguishable from `[]`).
124
+ *
125
+ * @param signerPrivateKey - 32-byte Ed25519 private key of the parent.
126
+ * @param subjectPublicKey - 32-byte Ed25519 public key being attested.
127
+ * @param subjectName - Child name; canonicalized before signing.
128
+ * @param grant - Constraints enforced by verifiers (Mode 2).
129
+ * @param opts - Lifetime control: `ttlSeconds` (default one year),
130
+ * `expiresAt` (overrides `ttlSeconds`), `jti` (default random UUID),
131
+ * `now` (fixed clock for deterministic tests).
132
+ * @returns The attestation with `payload`, `token` and `jti` accessors.
133
+ * @throws {AttestationError} `MALFORMED`/`FORMAT` if the grant is
134
+ * structurally invalid (bad scopes/TTL/audiences or a wildcard
135
+ * not at the end of a `subNamePatterns` entry).
136
+ * @throws {Error} If `subjectPublicKey` is not 32 bytes.
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * const att = await Attestation.issue(rootPriv, childPub, 'Station-1',
141
+ * { scopes: ['read'], maxSessionTtl: 3600 }, { ttlSeconds: 600 });
142
+ * ```
143
+ */
144
+ static issue(signerPrivateKey: Uint8Array, subjectPublicKey: Uint8Array, subjectName: string, grant: AttestationGrant, opts?: {
145
+ ttlSeconds?: number;
146
+ expiresAt?: number;
147
+ jti?: string;
148
+ now?: number;
149
+ }): Promise<Attestation>;
150
+ }
151
+ //# sourceMappingURL=attestation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attestation.d.ts","sourceRoot":"","sources":["../src/attestation.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,gBAAgB,yBAAyB,CAAC;AACvD,eAAO,MAAM,uBAAuB,OAAO,CAAC;AAE5C,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB;;;OAGG;IACH,MAAM,EAAE,MAA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;;;;;QAOI;WACU,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC;IAS3F;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,OAAO;IAYlE;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;WACU,KAAK,CAChB,gBAAgB,EAAE,UAAU,EAC5B,gBAAgB,EAAE,UAAU,EAC5B,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE,gBAAgB,EACvB,IAAI,CAAC,EAAE;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,GAC7E,OAAO,CAAC,WAAW,CAAC;CA4DxB"}
@@ -0,0 +1,279 @@
1
+ // attestation.ts
2
+ //
3
+ // Attestation module: cryptographically signed, self-contained
4
+ // authorization attestations for the Me2em protocol.
5
+ import { normalizeName } from './canonical-name.js';
6
+ import { base64urlEncode, base64urlDecode } from './util.js';
7
+ import { ed } from './crypto/init.js';
8
+ export const ATTESTATION_TYPE = 'me2em/attestation/v1';
9
+ export const ATTESTATION_MAX_PAYLOAD = 2048;
10
+ export class AttestationError extends Error {
11
+ code;
12
+ level;
13
+ constructor(code, level, msg) {
14
+ super(`[${level}/${code}] ${msg}`);
15
+ this.code = code;
16
+ this.level = level;
17
+ }
18
+ }
19
+ function throwFormat(code, msg) {
20
+ throw new AttestationError(code, 'FORMAT', msg);
21
+ }
22
+ function parseToken(token) {
23
+ if (typeof token !== 'string') {
24
+ throwFormat('MALFORMED', 'Token must be a string');
25
+ }
26
+ const parts = token.split('.');
27
+ if (parts.length !== 2) {
28
+ throwFormat('MALFORMED', 'Token must have exactly two parts separated by "."');
29
+ }
30
+ const [payloadB64, signatureB64] = parts;
31
+ const b64urlRegex = /^[A-Za-z0-9_-]+$/;
32
+ if (!b64urlRegex.test(payloadB64) || !b64urlRegex.test(signatureB64)) {
33
+ throwFormat('MALFORMED', 'Payload and signature must be valid Base64URL');
34
+ }
35
+ const payloadBytes = base64urlDecode(payloadB64);
36
+ if (payloadBytes.length > ATTESTATION_MAX_PAYLOAD) {
37
+ throwFormat('MALFORMED', `Payload exceeds maximum size of ${ATTESTATION_MAX_PAYLOAD} bytes`);
38
+ }
39
+ let payload;
40
+ try {
41
+ const jsonString = new TextDecoder().decode(payloadBytes);
42
+ payload = JSON.parse(jsonString);
43
+ }
44
+ catch {
45
+ throwFormat('MALFORMED', 'Payload is not valid JSON');
46
+ }
47
+ const signatureBytes = base64urlDecode(signatureB64);
48
+ return { payloadBytes, signatureBytes, payload };
49
+ }
50
+ /**
51
+ * A parent-signed statement binding a derived child key to a name and a
52
+ * grant. Chains of attestations (`Identity → Handle → SubHandle`) allow
53
+ * any third party to verify sessions offline using only the root public
54
+ * key, with grant constraints enforced at verification time.
55
+ *
56
+ * Tokens have the form `base64url(payload).base64url(signature)` and are
57
+ * deterministic: the same inputs (including `jti` and `now`) always
58
+ * produce byte-identical tokens.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * import { ed25519 } from '@noble/curves/ed25519.js';
63
+ *
64
+ * // Parent (signer) and child (subject) keys — use a CSPRNG in practice:
65
+ * const signerPriv = ed25519.utils.randomPrivateKey();
66
+ * const signerPub = ed25519.getPublicKey(signerPriv);
67
+ * const childPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());
68
+ *
69
+ * const A = await Attestation.issue(signerPriv, childPub, 'station-001', {
70
+ * audiences: ['ev-app.com'],
71
+ * scopes: ['charge:start', 'charge:stop'],
72
+ * maxSessionTtl: 7200,
73
+ * subNamePatterns: ['connector-*'],
74
+ * });
75
+ *
76
+ * const ok = await Attestation.verifySignature(A.token, signerPub); // true
77
+ * const payload = Attestation.decode(A.token); // structure only — no sig, no time
78
+ *
79
+ * ```
80
+ *
81
+ * @category Core Primitives
82
+ */
83
+ export class Attestation {
84
+ _payload;
85
+ _token;
86
+ constructor(payload, token) {
87
+ this._payload = payload;
88
+ this._token = token;
89
+ }
90
+ get payload() {
91
+ return this._payload;
92
+ }
93
+ get token() {
94
+ return this._token;
95
+ }
96
+ get jti() {
97
+ return this._payload.jti;
98
+ }
99
+ /**
100
+ * Parses a token and validates its structure WITHOUT checking the
101
+ * signature or any timestamps. Use {@link verifySignature} for the
102
+ * signature; expiration is checked by `Session.verifyAttested`.
103
+ *
104
+ * @throws {AttestationError} `MALFORMED`/`FORMAT` on any structural
105
+ * problem: wrong shape, invalid Base64URL, size over
106
+ * {@link ATTESTATION_MAX_PAYLOAD}, non-JSON payload, wrong `typ`,
107
+ * missing/ill-typed fields, or a non-positive/NaN `maxSessionTtl`.
108
+ */
109
+ static decode(token) {
110
+ const { payload } = parseToken(token);
111
+ if (payload.typ !== ATTESTATION_TYPE) {
112
+ throwFormat('MALFORMED', `Invalid typ: expected "${ATTESTATION_TYPE}"`);
113
+ }
114
+ if (typeof payload.subjectName !== 'string') {
115
+ throwFormat('MALFORMED', 'Missing required field: subjectName');
116
+ }
117
+ if (typeof payload.subjectId !== 'string') {
118
+ throwFormat('MALFORMED', 'Missing required field: subjectId');
119
+ }
120
+ if (typeof payload.grant !== 'object' ||
121
+ payload.grant === null ||
122
+ Array.isArray(payload.grant)) {
123
+ throwFormat('MALFORMED', 'Invalid field: grant');
124
+ }
125
+ if (!Array.isArray(payload.grant.scopes) || !payload.grant.scopes.every((s) => typeof s === 'string')) {
126
+ throwFormat('MALFORMED', 'Invalid field: grant.scopes');
127
+ }
128
+ if (typeof payload.grant.maxSessionTtl !== 'number' || !Number.isFinite(payload.grant.maxSessionTtl) || payload.grant.maxSessionTtl <= 0) {
129
+ throwFormat('MALFORMED', 'Invalid field: grant.maxSessionTtl');
130
+ }
131
+ if (payload.grant.audiences !== undefined) {
132
+ if (!Array.isArray(payload.grant.audiences) || !payload.grant.audiences.every((a) => typeof a === 'string')) {
133
+ throwFormat('MALFORMED', 'Invalid field: grant.audiences');
134
+ }
135
+ }
136
+ if (payload.grant.subNamePatterns !== undefined) {
137
+ if (!Array.isArray(payload.grant.subNamePatterns) || !payload.grant.subNamePatterns.every((p) => typeof p === 'string')) {
138
+ throwFormat('MALFORMED', 'Invalid field: grant.subNamePatterns');
139
+ }
140
+ }
141
+ if (typeof payload.iat !== 'number') {
142
+ throwFormat('MALFORMED', 'Missing required field: iat');
143
+ }
144
+ if (typeof payload.exp !== 'number') {
145
+ throwFormat('MALFORMED', 'Missing required field: exp');
146
+ }
147
+ if (typeof payload.jti !== 'string') {
148
+ throwFormat('MALFORMED', 'Missing required field: jti');
149
+ }
150
+ return payload;
151
+ }
152
+ /**
153
+ * Verifies the token signature against a public key.
154
+ *
155
+ * @returns `false` for a bad signature or a wrong key. Returns
156
+ * `false` for any invalid signature, including malformed lengths.
157
+ * It still throws `AttestationError` `MALFORMED`/`FORMAT` for
158
+ * structurally invalid tokens (see {@link decode}).
159
+ */
160
+ static async verifySignature(token, signerPublicKey) {
161
+ const { signatureBytes, payloadBytes } = parseToken(token);
162
+ try {
163
+ return ed.verify(signatureBytes, payloadBytes, signerPublicKey);
164
+ }
165
+ catch {
166
+ return false;
167
+ }
168
+ }
169
+ /**
170
+ * Wildcard name matching used for `subNamePatterns`.
171
+ * A pattern matches if it equals `name`, or ends with `*` and `name`
172
+ * starts with the pattern's prefix. A lone `*` matches everything.
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * Attestation.matchNamePattern('connector-1', ['connector-*']); // true
177
+ * Attestation.matchNamePattern('meter-1', ['connector-*']); // false
178
+ * Attestation.matchNamePattern('anything', ['*']); // true
179
+ * ```
180
+ */
181
+ static matchNamePattern(name, patterns) {
182
+ for (const pattern of patterns) {
183
+ if (pattern === '*')
184
+ return true;
185
+ if (pattern.endsWith('*')) {
186
+ if (name.startsWith(pattern.slice(0, -1)))
187
+ return true;
188
+ }
189
+ else {
190
+ if (pattern === name)
191
+ return true;
192
+ }
193
+ }
194
+ return false;
195
+ }
196
+ /**
197
+ * Creates and signs a new attestation.
198
+ *
199
+ * The subject name is canonicalized (NFKC → lowercase → trim) before
200
+ * signing; the subject public key must be exactly 32 bytes. Serialization is
201
+ * deterministic: fields are emitted in a fixed order and
202
+ * `undefined` grant fields are omitted from the JSON entirely
203
+ * (distinguishable from `[]`).
204
+ *
205
+ * @param signerPrivateKey - 32-byte Ed25519 private key of the parent.
206
+ * @param subjectPublicKey - 32-byte Ed25519 public key being attested.
207
+ * @param subjectName - Child name; canonicalized before signing.
208
+ * @param grant - Constraints enforced by verifiers (Mode 2).
209
+ * @param opts - Lifetime control: `ttlSeconds` (default one year),
210
+ * `expiresAt` (overrides `ttlSeconds`), `jti` (default random UUID),
211
+ * `now` (fixed clock for deterministic tests).
212
+ * @returns The attestation with `payload`, `token` and `jti` accessors.
213
+ * @throws {AttestationError} `MALFORMED`/`FORMAT` if the grant is
214
+ * structurally invalid (bad scopes/TTL/audiences or a wildcard
215
+ * not at the end of a `subNamePatterns` entry).
216
+ * @throws {Error} If `subjectPublicKey` is not 32 bytes.
217
+ *
218
+ * @example
219
+ * ```ts
220
+ * const att = await Attestation.issue(rootPriv, childPub, 'Station-1',
221
+ * { scopes: ['read'], maxSessionTtl: 3600 }, { ttlSeconds: 600 });
222
+ * ```
223
+ */
224
+ static async issue(signerPrivateKey, subjectPublicKey, subjectName, grant, opts) {
225
+ const name = normalizeName(subjectName);
226
+ if (subjectPublicKey.length !== 32) {
227
+ throw new Error('subject public key must be 32 bytes');
228
+ }
229
+ // Validate grant
230
+ if (!Array.isArray(grant.scopes) || !grant.scopes.every((s) => typeof s === 'string')) {
231
+ throwFormat('MALFORMED', 'grant.scopes must be an array of strings');
232
+ }
233
+ if (typeof grant.maxSessionTtl !== 'number' || !Number.isFinite(grant.maxSessionTtl) || grant.maxSessionTtl <= 0) {
234
+ throwFormat('MALFORMED', 'grant.maxSessionTtl must be a finite positive number');
235
+ }
236
+ if (grant.audiences !== undefined) {
237
+ if (!Array.isArray(grant.audiences) || !grant.audiences.every((a) => typeof a === 'string')) {
238
+ throwFormat('MALFORMED', 'grant.audiences must be an array of strings');
239
+ }
240
+ }
241
+ if (grant.subNamePatterns !== undefined) {
242
+ if (!Array.isArray(grant.subNamePatterns) || !grant.subNamePatterns.every((p) => typeof p === 'string')) {
243
+ throwFormat('MALFORMED', 'grant.subNamePatterns must be an array of strings');
244
+ }
245
+ for (const pattern of grant.subNamePatterns) {
246
+ const starIndex = pattern.indexOf('*');
247
+ if (starIndex !== -1 && starIndex !== pattern.length - 1) {
248
+ throwFormat('MALFORMED', `Invalid pattern: ${JSON.stringify(pattern)} — '*' only allowed at end`);
249
+ }
250
+ }
251
+ }
252
+ const now = opts?.now ?? Math.floor(Date.now() / 1000);
253
+ const exp = opts?.expiresAt ?? (now + (opts?.ttlSeconds ?? 31536000));
254
+ const jti = opts?.jti ?? crypto.randomUUID();
255
+ const grantJson = {};
256
+ if (grant.audiences !== undefined)
257
+ grantJson.audiences = [...grant.audiences];
258
+ grantJson.scopes = [...grant.scopes];
259
+ grantJson.maxSessionTtl = grant.maxSessionTtl;
260
+ if (grant.subNamePatterns !== undefined)
261
+ grantJson.subNamePatterns = [...grant.subNamePatterns];
262
+ const payload = {
263
+ typ: ATTESTATION_TYPE,
264
+ subjectName: name,
265
+ subjectId: base64urlEncode(subjectPublicKey),
266
+ grant: grantJson,
267
+ iat: now,
268
+ exp,
269
+ jti,
270
+ };
271
+ const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
272
+ const signature = await ed.sign(payloadBytes, signerPrivateKey);
273
+ const payloadB64 = base64urlEncode(payloadBytes);
274
+ const signatureB64 = base64urlEncode(signature);
275
+ const token = `${payloadB64}.${signatureB64}`;
276
+ return new Attestation(payload, token);
277
+ }
278
+ }
279
+ //# sourceMappingURL=attestation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attestation.js","sourceRoot":"","s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YAAY,EAAE,CAAC;QAE9C,OAAO,IAAI,WAAW,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACzC,CAAC;CACF"}
@@ -0,0 +1,3 @@
1
+ export declare const NAME_PATTERN: RegExp;
2
+ export declare function normalizeName(raw: string): string;
3
+ //# sourceMappingURL=canonical-name.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canonical-name.d.ts","sourceRoot":"","sources":["../src/canonical-name.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,YAAY,QAAiC,CAAC;AAE3D,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAOjD"}
@@ -0,0 +1,12 @@
1
+ // canonical-name.ts
2
+ export const NAME_PATTERN = /^[a-z0-9][a-z0-9._@-]{0,62}$/;
3
+ export function normalizeName(raw) {
4
+ if (typeof raw !== 'string')
5
+ throw new TypeError('Name must be a string');
6
+ const name = raw.normalize('NFKC').toLowerCase().trim();
7
+ if (!NAME_PATTERN.test(name)) {
8
+ throw new Error(`Invalid name: ${JSON.stringify(raw)}`);
9
+ }
10
+ return name;
11
+ }
12
+ //# sourceMappingURL=canonical-name.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canonical-name.js","sourceRoot":"","sources":["../src/canonical-name.ts"],"names":[],"mappings":"AAAA,oBAAoB;AAEpB,MAAM,CAAC,MAAM,YAAY,GAAG,8BAA8B,CAAC;AAE3D,MAAM,UAAU,aAAa,CAAC,GAAW;IACvC,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,MAAM,IAAI,SAAS,CAAC,uBAAuB,CAAC,CAAC;IAC1E,MAAM,IAAI,GAAG,GAAG,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC;IACxD,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7B,MAAM,IAAI,KAAK,CAAC,iBAAiB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAC1D,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Deterministic derivation paths for the Me2em protocol.
3
+ *
4
+ * All HKDF info strings used to derive Identity, Handle, and SubHandle keys
5
+ * are centralized here. This guarantees that:
6
+ * - `Identity.deriveHandle(name)` and `Handle.deriveSubHandle(subName)`
7
+ * produce the same key as `Identity.deriveSubHandle(name, subName)`.
8
+ * - Any future change to derivation paths is a single-line edit.
9
+ *
10
+ * @category Cryptographic Constants
11
+ */
12
+ export declare const DERIVATION_PATHS: {
13
+ /**
14
+ * Info string for deriving the root Identity key from the seed.
15
+ * Constant value: `"me2em/identity/v1/root"`.
16
+ */
17
+ readonly identity: "me2em/identity/v1/root";
18
+ /**
19
+ * Builds the info string for deriving a Handle from an Identity.
20
+ *
21
+ * @param name - The Handle name (will be normalized).
22
+ * @returns The info string, e.g. `"me2em/handle/v1/station-001"`.
23
+ */
24
+ readonly handle: (name: string) => string;
25
+ /**
26
+ * Builds the info string for deriving a SubHandle from a Handle.
27
+ *
28
+ * @param handleName - The parent Handle name (will be normalized).
29
+ * @param subName - The SubHandle name (will be normalized).
30
+ * @returns The info string, e.g. `"me2em/subhandle/v1/station-001/connector-1"`.
31
+ */
32
+ readonly subhandle: (handleName: string, subName: string) => string;
33
+ /**
34
+ * Versioned info string for peer-to-peer channel key derivation.
35
+ * v2 binds both peers' public keys into the derivation, preventing
36
+ * unknown key-share attacks. The peer keys are appended in sorted
37
+ * order so both parties derive the identical string.
38
+ */
39
+ readonly p2pChannelV2: "me2em/p2p-channel/v2";
40
+ };
41
+ //# sourceMappingURL=derivation-paths.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"derivation-paths.d.ts","sourceRoot":"","sources":["../../src/crypto/derivation-paths.ts"],"names":[],"mappings":"AAWA;;;;;;;;;;GAUG;AACH,eAAO,MAAM,gBAAgB;IAC3B;;;OAGG;;IAGH;;;;;OAKG;4BACY,MAAM,KAAG,MAAM;IAG9B;;;;;;OAMG;qCACqB,MAAM,WAAW,MAAM,KAAG,MAAM;IAGxD;;;;;OAKG;;CAEK,CAAC"}
@@ -0,0 +1,50 @@
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
+ import { normalizeName } from '../canonical-name.js';
10
+ /**
11
+ * Deterministic derivation paths for the Me2em protocol.
12
+ *
13
+ * All HKDF info strings used to derive Identity, Handle, and SubHandle keys
14
+ * are centralized here. This guarantees that:
15
+ * - `Identity.deriveHandle(name)` and `Handle.deriveSubHandle(subName)`
16
+ * produce the same key as `Identity.deriveSubHandle(name, subName)`.
17
+ * - Any future change to derivation paths is a single-line edit.
18
+ *
19
+ * @category Cryptographic Constants
20
+ */
21
+ export const DERIVATION_PATHS = {
22
+ /**
23
+ * Info string for deriving the root Identity key from the seed.
24
+ * Constant value: `"me2em/identity/v1/root"`.
25
+ */
26
+ identity: 'me2em/identity/v1/root',
27
+ /**
28
+ * Builds the info string for deriving a Handle from an Identity.
29
+ *
30
+ * @param name - The Handle name (will be normalized).
31
+ * @returns The info string, e.g. `"me2em/handle/v1/station-001"`.
32
+ */
33
+ handle: (name) => `me2em/handle/v1/${normalizeName(name)}`,
34
+ /**
35
+ * Builds the info string for deriving a SubHandle from a Handle.
36
+ *
37
+ * @param handleName - The parent Handle name (will be normalized).
38
+ * @param subName - The SubHandle name (will be normalized).
39
+ * @returns The info string, e.g. `"me2em/subhandle/v1/station-001/connector-1"`.
40
+ */
41
+ subhandle: (handleName, subName) => `me2em/subhandle/v1/${normalizeName(handleName)}/${normalizeName(subName)}`,
42
+ /**
43
+ * Versioned info string for peer-to-peer channel key derivation.
44
+ * v2 binds both peers' public keys into the derivation, preventing
45
+ * unknown key-share attacks. The peer keys are appended in sorted
46
+ * order so both parties derive the identical string.
47
+ */
48
+ p2pChannelV2: 'me2em/p2p-channel/v2',
49
+ };
50
+ //# sourceMappingURL=derivation-paths.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"derivation-paths.js","sourceRoot":"","sources":["../../src/crypto/derivation-paths.ts"],"names":[],"mappings":"AAAA,+CAA+C;AAC/C,EAAE;AACF,yEAAyE;AACzE,2EAA2E;AAC3E,wEAAwE;AACxE,EAAE;AACF,wEAAwE;AACxE,oBAAoB;AAEpB,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B;;;OAGG;IACH,QAAQ,EAAE,wBAAwB;IAElC;;;;;OAKG;IACH,MAAM,EAAE,CAAC,IAAY,EAAU,EAAE,CAC/B,mBAAmB,aAAa,CAAC,IAAI,CAAC,EAAE;IAE1C;;;;;;OAMG;IACH,SAAS,EAAE,CAAC,UAAkB,EAAE,OAAe,EAAU,EAAE,CACzD,sBAAsB,aAAa,CAAC,UAAU,CAAC,IAAI,aAAa,CAAC,OAAO,CAAC,EAAE;IAE7E;;;;;OAKG;IACH,YAAY,EAAE,sBAAsB;CAC5B,CAAC"}
@@ -1,12 +1,52 @@
1
1
  import { ed } from './init.js';
2
+ /** Verification options, forwarded to the underlying implementation. */
3
+ type VerifyOpts = Parameters<typeof ed.verify>[3];
2
4
  /**
3
- * @internal
4
- * Low-level Ed25519 implementation wrapper.
5
+ * Derives the Ed25519 public key for a private key (synchronous).
6
+ *
7
+ * @param privateKey - 32-byte Ed25519 private key.
8
+ * @returns The 32-byte public key.
9
+ * @throws `TypeError` if the key length is invalid.
10
+ * @throws `RangeError` if the key length is invalid.
5
11
  */
6
- export declare const getPublicKey: (secretKey: ed.TArg<Uint8Array>) => ed.TRet<Uint8Array>;
7
- export declare const sign: (message: ed.TArg<Uint8Array>, secretKey: ed.TArg<Uint8Array>) => ed.TRet<Uint8Array>;
8
- export declare const verify: (signature: ed.TArg<Uint8Array>, message: ed.TArg<Uint8Array>, publicKey: ed.TArg<Uint8Array>, opts?: ed.TArg<ed.EdDSAVerifyOpts>) => boolean;
9
- export declare const getPublicKeyAsync: (secretKey: ed.TArg<Uint8Array>) => Promise<ed.TRet<Uint8Array>>;
10
- export declare const signAsync: (message: ed.TArg<Uint8Array>, secretKey: ed.TArg<Uint8Array>) => Promise<ed.TRet<Uint8Array>>;
11
- export declare const verifyAsync: (signature: ed.TArg<Uint8Array>, message: ed.TArg<Uint8Array>, publicKey: ed.TArg<Uint8Array>, opts?: ed.TArg<ed.EdDSAVerifyOpts>) => Promise<boolean>;
12
+ export declare function getPublicKey(privateKey: Uint8Array): Uint8Array;
13
+ /**
14
+ * Signs a message with an Ed25519 private key (synchronous).
15
+ *
16
+ * @param message - The bytes to sign.
17
+ * @param privateKey - 32-byte Ed25519 private key.
18
+ * @returns The 64-byte signature.
19
+ * @throws `TypeError` if an input length is invalid.
20
+ * @throws `RangeError` if an input length is invalid.
21
+ */
22
+ export declare function sign(message: Uint8Array, privateKey: Uint8Array): Uint8Array;
23
+ /**
24
+ * Verifies an Ed25519 signature (synchronous).
25
+ *
26
+ * @param signature - The 64-byte signature.
27
+ * @param message - The signed message bytes.
28
+ * @param publicKey - The 32-byte signer public key.
29
+ * @param opts - Optional verification options, forwarded to the
30
+ * underlying implementation.
31
+ * @returns `true` if the signature is valid, `false` otherwise.
32
+ * @throws `TypeError` if an input length is invalid.
33
+ * @throws `RangeError` if an input length is invalid.
34
+ */
35
+ export declare function verify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array, opts?: VerifyOpts): boolean;
36
+ /**
37
+ * Asynchronous variant of {@link getPublicKey}; same contract.
38
+ */
39
+ export declare function getPublicKeyAsync(privateKey: Uint8Array): Promise<Uint8Array>;
40
+ /**
41
+ * Asynchronous variant of {@link sign}; same contract.
42
+ */
43
+ export declare function signAsync(message: Uint8Array, privateKey: Uint8Array): Promise<Uint8Array>;
44
+ /**
45
+ * Asynchronous variant of {@link verify}; same contract.
46
+ *
47
+ * @param opts - Optional verification options, forwarded to the
48
+ * underlying implementation.
49
+ */
50
+ export declare function verifyAsync(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array, opts?: Parameters<typeof ed.verifyAsync>[3]): Promise<boolean>;
51
+ export {};
12
52
  //# sourceMappingURL=ed25519.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ed25519.d.ts","sourceRoot":"","sources":["../../src/crypto/ed25519.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,WAAW,CAAC;AAE/B;;;GAGG;AACH,eAAO,MAAM,YAAY,yDAAkB,CAAC;AAC5C,eAAO,MAAM,IAAI,uFAAU,CAAC;AAC5B,eAAO,MAAM,MAAM,+IAAY,CAAC;AAChC,eAAO,MAAM,iBAAiB,kEAAuB,CAAC;AACtD,eAAO,MAAM,SAAS,gGAAe,CAAC;AACtC,eAAO,MAAM,WAAW,wJAAiB,CAAC"}
1
+ {"version":3,"file":"ed25519.d.ts","sourceRoot":"","sources":["../../src/crypto/ed25519.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,EAAE,EAAE,MAAM,WAAW,CAAC;AAE/B,wEAAwE;AACxE,KAAK,UAAU,GAAG,UAAU,CAAC,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AAElD;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,CAE/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,IAAI,CAAC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,GAAG,UAAU,CAE5E;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,MAAM,CACpB,SAAS,EAAE,UAAU,EACrB,OAAO,EAAE,UAAU,EACnB,SAAS,EAAE,UAAU,EACrB,IAAI,CAAC,EAAE,UA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