@me2em/core 0.4.4-alpha.2 → 0.7.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +294 -546
  2. package/dist/attestation.d.ts +151 -0
  3. package/dist/attestation.d.ts.map +1 -0
  4. package/dist/attestation.js +279 -0
  5. package/dist/attestation.js.map +1 -0
  6. package/dist/canonical-name.d.ts +3 -0
  7. package/dist/canonical-name.d.ts.map +1 -0
  8. package/dist/canonical-name.js +12 -0
  9. package/dist/canonical-name.js.map +1 -0
  10. package/dist/crypto/derivation-paths.d.ts +41 -0
  11. package/dist/crypto/derivation-paths.d.ts.map +1 -0
  12. package/dist/crypto/derivation-paths.js +50 -0
  13. package/dist/crypto/derivation-paths.js.map +1 -0
  14. package/dist/crypto/ed25519.d.ts +48 -8
  15. package/dist/crypto/ed25519.d.ts.map +1 -1
  16. package/dist/crypto/ed25519.js +63 -8
  17. package/dist/crypto/ed25519.js.map +1 -1
  18. package/dist/crypto/hkdf.d.ts.map +1 -1
  19. package/dist/crypto/hkdf.js +1 -0
  20. package/dist/crypto/hkdf.js.map +1 -1
  21. package/dist/crypto/index.d.ts +1 -0
  22. package/dist/crypto/index.d.ts.map +1 -1
  23. package/dist/crypto/index.js +2 -0
  24. package/dist/crypto/index.js.map +1 -1
  25. package/dist/crypto/init.d.ts.map +1 -1
  26. package/dist/crypto/init.js +1 -0
  27. package/dist/crypto/init.js.map +1 -1
  28. package/dist/handle.d.ts +149 -35
  29. package/dist/handle.d.ts.map +1 -1
  30. package/dist/handle.js +180 -40
  31. package/dist/handle.js.map +1 -1
  32. package/dist/identity.d.ts +99 -19
  33. package/dist/identity.d.ts.map +1 -1
  34. package/dist/identity.js +128 -32
  35. package/dist/identity.js.map +1 -1
  36. package/dist/index.d.ts +5 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +4 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/seed.d.ts +38 -39
  41. package/dist/seed.d.ts.map +1 -1
  42. package/dist/seed.js +36 -41
  43. package/dist/seed.js.map +1 -1
  44. package/dist/session.d.ts +207 -17
  45. package/dist/session.d.ts.map +1 -1
  46. package/dist/session.js +428 -11
  47. package/dist/session.js.map +1 -1
  48. package/dist/subhandle.d.ts +126 -0
  49. package/dist/subhandle.d.ts.map +1 -0
  50. package/dist/subhandle.js +182 -0
  51. package/dist/subhandle.js.map +1 -0
  52. package/dist/util.d.ts +9 -0
  53. package/dist/util.d.ts.map +1 -0
  54. package/dist/util.js +34 -0
  55. package/dist/util.js.map +1 -0
  56. package/package.json +3 -3
  57. package/src/attestation.ts +364 -0
  58. package/src/canonical-name.ts +12 -0
  59. package/src/crypto/derivation-paths.ts +56 -0
  60. package/src/crypto/ed25519.ts +82 -8
  61. package/src/crypto/hkdf.ts +2 -0
  62. package/src/crypto/index.ts +3 -1
  63. package/src/crypto/init.ts +1 -0
  64. package/src/handle.ts +227 -42
  65. package/src/identity.ts +164 -35
  66. package/src/index.ts +5 -1
  67. package/src/seed.ts +59 -59
  68. package/src/session.ts +637 -24
  69. package/src/subhandle.ts +254 -0
  70. package/src/util.ts +35 -0
@@ -0,0 +1,182 @@
1
+ // subhandle.ts
2
+ //
3
+ // SubHandle is a leaf node in the Me2em derivation tree.
4
+ // With MAX_DEPTH = 2, a SubHandle CANNOT derive children.
5
+ // It inherits from Handle for polymorphism in Session handling.
6
+ import { Handle } from './handle.js';
7
+ import { normalizeName } from './canonical-name.js';
8
+ /**
9
+ * Extracts only display-safe fields for the base Handle metadata.
10
+ * Constraint fields stay in SubHandle's own storage and must never
11
+ * leak through Handle.getMetadata().
12
+ */
13
+ function extractDisplayFields(meta) {
14
+ if (!meta)
15
+ return undefined;
16
+ const display = {};
17
+ if (meta.displayName !== undefined)
18
+ display.displayName = meta.displayName;
19
+ if (meta.avatar !== undefined)
20
+ display.avatar = meta.avatar;
21
+ // copy any other custom fields, but never the constraint ones
22
+ const CONSTRAINT_KEYS = new Set([
23
+ 'allowedAudiences', 'allowedScopes', 'maxSessionTtl', 'expiresAt',
24
+ ]);
25
+ for (const [k, v] of Object.entries(meta)) {
26
+ if (!CONSTRAINT_KEYS.has(k)) {
27
+ display[k] = v;
28
+ }
29
+ }
30
+ return display;
31
+ }
32
+ /**
33
+ * Represents a context-isolated child Handle in the Me2em hierarchy.
34
+ *
35
+ * A SubHandle is always derived from a parent {@link Handle} and represents
36
+ * a leaf node in the derivation tree (MAX_DEPTH = 2). It inherits all
37
+ * cryptographic capabilities of Handle (signing, key derivation, etc.) but
38
+ * adds:
39
+ *
40
+ * - A **derivation path** (`[handleName, subName]`) carried in session tokens.
41
+ * - **Constraint enforcement** on audience, scopes, and TTL at session creation.
42
+ * - An optional **expiration timestamp** for temporary access grants.
43
+ *
44
+ * SubHandle is used for polymorphism in {@link Session}: both Handle and
45
+ * SubHandle can create and verify sessions, but SubHandle sessions carry
46
+ * the additional `hPath` field for hierarchical auditing.
47
+ *
48
+ * @category Core Primitives
49
+ */
50
+ export class SubHandle extends Handle {
51
+ _path;
52
+ _subMetadata;
53
+ /**
54
+ * Creates a new SubHandle instance.
55
+ *
56
+ * @internal Typically created via {@link Handle.deriveSubHandle} or
57
+ * {@link Identity.deriveSubHandle}. Direct construction is discouraged.
58
+ *
59
+ * @param privateKey - The 32-byte Ed25519 private key for this SubHandle.
60
+ * @param name - The SubHandle name.
61
+ * @param path - The derivation path, must have exactly 2 elements: `[handleName, subName]`.
62
+ * @param subMetadata - Optional constraints and metadata.
63
+ * @throws {Error} If the path does not have exactly 2 elements.
64
+ */
65
+ constructor(privateKey, name, path, subMetadata) {
66
+ super(privateKey, name, extractDisplayFields(subMetadata));
67
+ if (path.length !== 2) {
68
+ throw new Error(`SubHandle path must have exactly 2 elements: [handleName, subName]. Got ${path.length}.`);
69
+ }
70
+ const normalizedName = normalizeName(name);
71
+ if (path[1] !== normalizedName) {
72
+ throw new Error(`path[1] must equal normalized name: path[1]=${JSON.stringify(path[1])}, name=${JSON.stringify(normalizedName)}`);
73
+ }
74
+ this._path = path;
75
+ this._subMetadata = subMetadata ?? {};
76
+ }
77
+ /**
78
+ * Returns the full derivation path of this SubHandle.
79
+ *
80
+ * @returns A copy of the path array, e.g. `["station-001", "connector-1"]`.
81
+ */
82
+ getPath() {
83
+ return [...this._path];
84
+ }
85
+ /**
86
+ * Returns the derivation path as a slash-separated string.
87
+ *
88
+ * @returns The path string, e.g. `"station-001/connector-1"`.
89
+ */
90
+ getPathString() {
91
+ return this._path.join('/');
92
+ }
93
+ /**
94
+ * Returns the depth of this SubHandle in the derivation hierarchy.
95
+ *
96
+ * With MAX_DEPTH = 2, this is always `2` (Identity = 0, Handle = 1, SubHandle = 2).
97
+ *
98
+ * @returns The depth, always `2`.
99
+ */
100
+ getDepth() {
101
+ return 2;
102
+ }
103
+ /**
104
+ * Returns whether this SubHandle is a leaf node.
105
+ *
106
+ * With MAX_DEPTH = 2, a SubHandle is **always** a leaf and cannot derive children.
107
+ *
108
+ * @returns Always `true`.
109
+ */
110
+ isLeaf() {
111
+ return true;
112
+ }
113
+ /**
114
+ * SubHandle is a leaf node (depth = 2) and cannot derive children.
115
+ * Overrides the inherited `Handle.deriveSubHandle` to throw an error.
116
+ */
117
+ async deriveSubHandle() {
118
+ throw new Error('Cannot derive child: maximum depth (2) reached or this SubHandle is marked as leaf');
119
+ }
120
+ /**
121
+ * Returns the SubHandle-specific metadata (constraints).
122
+ *
123
+ * @returns The SubHandleMetadata object.
124
+ */
125
+ getSubMetadata() {
126
+ return {
127
+ ...this._subMetadata,
128
+ allowedAudiences: this._subMetadata.allowedAudiences !== undefined
129
+ ? [...this._subMetadata.allowedAudiences]
130
+ : undefined,
131
+ allowedScopes: this._subMetadata.allowedScopes !== undefined
132
+ ? [...this._subMetadata.allowedScopes]
133
+ : undefined,
134
+ };
135
+ }
136
+ /**
137
+ * Validates session options against this SubHandle's constraints.
138
+ *
139
+ * Called internally by {@link Session.create} before signing. Throws if
140
+ * any constraint is violated:
141
+ * - `audience` not in `allowedAudiences`
142
+ * - any `scope` not in `allowedScopes`
143
+ * - `ttl` exceeds `maxSessionTtl`
144
+ * - current time is past `expiresAt`
145
+ *
146
+ * @param options - The session options to validate.
147
+ * @throws {Error} If any constraint is violated.
148
+ */
149
+ validateSessionOptions(options) {
150
+ // Audience check: undefined = unrestricted, [] = deny all
151
+ if (this._subMetadata.allowedAudiences !== undefined) {
152
+ if (!this._subMetadata.allowedAudiences.includes(options.audience)) {
153
+ throw new Error(`Audience "${options.audience}" not allowed for this SubHandle. ` +
154
+ `Allowed: ${this._subMetadata.allowedAudiences.length === 0
155
+ ? '(none — empty list denies all)'
156
+ : this._subMetadata.allowedAudiences.join(', ')}`);
157
+ }
158
+ }
159
+ // Scopes check: undefined = unrestricted, [] = deny all
160
+ if (this._subMetadata.allowedScopes !== undefined) {
161
+ const forbidden = options.scopes.filter(s => !this._subMetadata.allowedScopes.includes(s));
162
+ // An empty allow-list denies every requested scope.
163
+ if (forbidden.length > 0) {
164
+ throw new Error(`Scopes not allowed for this SubHandle: ${forbidden.join(', ')}`);
165
+ }
166
+ }
167
+ // TTL check
168
+ if (this._subMetadata.maxSessionTtl !== undefined &&
169
+ options.ttl > this._subMetadata.maxSessionTtl) {
170
+ throw new Error(`TTL ${options.ttl}s exceeds max allowed ` +
171
+ `${this._subMetadata.maxSessionTtl}s for this SubHandle`);
172
+ }
173
+ // SubHandle expiration check
174
+ if (this._subMetadata.expiresAt !== undefined) {
175
+ const now = Math.floor(Date.now() / 1000);
176
+ if (now >= this._subMetadata.expiresAt) {
177
+ throw new Error('SubHandle has expired');
178
+ }
179
+ }
180
+ }
181
+ }
182
+ //# sourceMappingURL=subhandle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subhandle.js","sourceRoot":"","sources":["../src/subhandle.ts"],"names":[],"mappings":"AAAA,eAAe;AACf,EAAE;AACF,yDAAyD;AACzD,0DAA0D;AAC1D,gEAAgE;AAEhE,OAAO,EAAE,MAAM,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AY,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;YAC9C,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;YAC1C,IAAI,GAAG,IAAI,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE,CAAC;gBACvC,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;IACH,CAAC;CACF"}
package/dist/util.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Encodes a Uint8Array to a URL-safe Base64 string (no padding).
3
+ */
4
+ export declare function base64urlEncode(bytes: Uint8Array): string;
5
+ /**
6
+ * Decodes a URL-safe Base64 string to a Uint8Array.
7
+ */
8
+ export declare function base64urlDecode(input: string): Uint8Array;
9
+ //# sourceMappingURL=util.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAIA;;GAEG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CASzD;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAazD"}
package/dist/util.js ADDED
@@ -0,0 +1,34 @@
1
+ // util.ts
2
+ //
3
+ // Shared utility functions for the Me2em protocol.
4
+ /**
5
+ * Encodes a Uint8Array to a URL-safe Base64 string (no padding).
6
+ */
7
+ export function base64urlEncode(bytes) {
8
+ let binary = '';
9
+ for (const byte of bytes) {
10
+ binary += String.fromCharCode(byte);
11
+ }
12
+ return btoa(binary)
13
+ .replace(/\+/g, '-')
14
+ .replace(/\//g, '_')
15
+ .replace(/=+$/, '');
16
+ }
17
+ /**
18
+ * Decodes a URL-safe Base64 string to a Uint8Array.
19
+ */
20
+ export function base64urlDecode(input) {
21
+ let base64 = input
22
+ .replace(/-/g, '+')
23
+ .replace(/_/g, '/');
24
+ while (base64.length % 4 !== 0) {
25
+ base64 += '=';
26
+ }
27
+ const binary = atob(base64);
28
+ const bytes = new Uint8Array(binary.length);
29
+ for (let i = 0; i < binary.length; i++) {
30
+ bytes[i] = binary.charCodeAt(i);
31
+ }
32
+ return bytes;
33
+ }
34
+ //# sourceMappingURL=util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAAA,UAAU;AACV,EAAE;AACF,mDAAmD;AAEnD;;GAEG;AACH,MAAM,UAAU,eAAe,CAAC,KAAiB;IAC/C,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IACtC,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,CAAC;SAChB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACxB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,eAAe,CAAC,KAAa;IAC3C,IAAI,MAAM,GAAG,KAAK;SACf,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC;SAClB,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IACtB,OAAO,MAAM,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;QAC/B,MAAM,IAAI,GAAG,CAAC;IAChB,CAAC;IACD,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;IAC5B,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC5C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACvC,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAClC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@me2em/core",
3
- "version": "0.4.4-alpha.2",
3
+ "version": "0.7.0-alpha.1",
4
4
  "description": "Core primitives for the Me2em authorization protocol: Identity, Handle, and Session",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -8,8 +8,7 @@
8
8
  "exports": {
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js",
12
- "require": "./dist/index.cjs"
11
+ "import": "./dist/index.js"
13
12
  }
14
13
  },
15
14
  "files": [
@@ -23,6 +22,7 @@
23
22
  "access": "public"
24
23
  },
25
24
  "dependencies": {
25
+ "@noble/curves": "^1.8.1",
26
26
  "@noble/ed25519": "^3.1.0",
27
27
  "@noble/hashes": "^2.2.0",
28
28
  "@scure/bip39": "^1.3.0"
@@ -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
+ }