@me2em/core 0.4.4-alpha.1 → 0.6.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +299 -766
  2. package/dist/attestation.d.ts +151 -0
  3. package/dist/attestation.d.ts.map +1 -0
  4. package/dist/attestation.js +279 -0
  5. package/dist/attestation.js.map +1 -0
  6. package/dist/canonical-name.d.ts +3 -0
  7. package/dist/canonical-name.d.ts.map +1 -0
  8. package/dist/canonical-name.js +12 -0
  9. package/dist/canonical-name.js.map +1 -0
  10. package/dist/crypto/derivation-paths.d.ts +41 -0
  11. package/dist/crypto/derivation-paths.d.ts.map +1 -0
  12. package/dist/crypto/derivation-paths.js +50 -0
  13. package/dist/crypto/derivation-paths.js.map +1 -0
  14. package/dist/crypto/ed25519.d.ts +52 -0
  15. package/dist/crypto/ed25519.d.ts.map +1 -0
  16. package/dist/crypto/ed25519.js +67 -0
  17. package/dist/crypto/ed25519.js.map +1 -0
  18. package/dist/crypto/hkdf.d.ts +13 -0
  19. package/dist/crypto/hkdf.d.ts.map +1 -0
  20. package/dist/crypto/hkdf.js +17 -0
  21. package/dist/crypto/hkdf.js.map +1 -0
  22. package/dist/crypto/index.d.ts +4 -0
  23. package/dist/crypto/index.d.ts.map +1 -0
  24. package/dist/crypto/index.js +5 -0
  25. package/dist/crypto/index.js.map +1 -0
  26. package/dist/crypto/init.d.ts +9 -0
  27. package/dist/crypto/init.d.ts.map +1 -0
  28. package/dist/crypto/init.js +17 -0
  29. package/dist/crypto/init.js.map +1 -0
  30. package/dist/handle.d.ts +206 -0
  31. package/dist/handle.d.ts.map +1 -0
  32. package/dist/handle.js +258 -0
  33. package/dist/handle.js.map +1 -0
  34. package/dist/identity.d.ts +123 -0
  35. package/dist/identity.d.ts.map +1 -0
  36. package/dist/identity.js +167 -0
  37. package/dist/identity.js.map +1 -0
  38. package/dist/index.d.ts +33 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +33 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/seed.d.ts +83 -0
  43. package/dist/seed.d.ts.map +1 -0
  44. package/dist/seed.js +117 -0
  45. package/dist/seed.js.map +1 -0
  46. package/dist/session.d.ts +231 -0
  47. package/dist/session.d.ts.map +1 -0
  48. package/dist/session.js +454 -0
  49. package/dist/session.js.map +1 -0
  50. package/dist/subhandle.d.ts +126 -0
  51. package/dist/subhandle.d.ts.map +1 -0
  52. package/dist/subhandle.js +158 -0
  53. package/dist/subhandle.js.map +1 -0
  54. package/dist/util.d.ts +9 -0
  55. package/dist/util.d.ts.map +1 -0
  56. package/dist/util.js +34 -0
  57. package/dist/util.js.map +1 -0
  58. package/package.json +36 -12
  59. package/src/attestation.ts +364 -0
  60. package/src/canonical-name.ts +12 -0
  61. package/src/crypto/derivation-paths.ts +56 -0
  62. package/src/crypto/ed25519.ts +86 -0
  63. package/{packages/core/src → src}/crypto/hkdf.ts +2 -0
  64. package/src/crypto/index.ts +4 -0
  65. package/{packages/core/src → src}/crypto/init.ts +1 -0
  66. package/src/handle.ts +320 -0
  67. package/src/identity.ts +218 -0
  68. package/{packages/core/src → src}/index.ts +5 -1
  69. package/{packages/core/src → src}/seed.ts +41 -54
  70. package/src/session.ts +660 -0
  71. package/src/subhandle.ts +230 -0
  72. package/src/util.ts +35 -0
  73. package/.github/workflows/ci.yml +0 -0
  74. package/CODE_OF_CONDUCT.md +0 -73
  75. package/CONTRIBUTING.md +0 -145
  76. package/GOVERNANCE.md +0 -132
  77. package/SECURITY.md +0 -70
  78. package/packages/core/README.md +0 -656
  79. package/packages/core/package.json +0 -44
  80. package/packages/core/src/crypto/ed25519.ts +0 -12
  81. package/packages/core/src/crypto/index.ts +0 -2
  82. package/packages/core/src/handle.ts +0 -130
  83. package/packages/core/src/identity.ts +0 -89
  84. package/packages/core/src/session.ts +0 -47
  85. package/packages/core/test/derivation.spec.ts +0 -117
  86. package/packages/core/tsconfig.json +0 -9
  87. package/pnpm-workspace.yaml +0 -2
  88. package/specs/core.md +0 -44
  89. package/specs/openapi/server-ref.yaml +0 -10
  90. package/specs/test-vectors.json +0 -13
  91. package/tsconfig.base.json +0 -20
  92. package/typedoc.json +0 -18
@@ -0,0 +1,231 @@
1
+ import { Handle } from './handle.js';
2
+ import { SubHandle } from './subhandle.js';
3
+ import { Identity } from './identity.js';
4
+ /**
5
+ * Options for creating a new {@link Session}.
6
+ *
7
+ * @category Types
8
+ */
9
+ export interface SessionOptions {
10
+ /** The intended audience (recipient) of this session. */
11
+ audience: string;
12
+ /** Permission scopes granted in this session (e.g., `['read', 'write']`). */
13
+ scopes: string[];
14
+ /** Time-to-live in seconds. */
15
+ ttl: number;
16
+ /**
17
+ * Optional unique session identifier, used for revocation.
18
+ * If not provided, a random UUID is generated.
19
+ */
20
+ sessionId?: string;
21
+ }
22
+ /**
23
+ * The payload structure encoded inside a session token.
24
+ *
25
+ * @category Types
26
+ */
27
+ export interface SessionPayload {
28
+ /** Handle / SubHandle ID (Base64URL of public key). */
29
+ hId: string;
30
+ /** Handle / SubHandle name. */
31
+ hNm: string;
32
+ /**
33
+ * Derivation path for SubHandle sessions.
34
+ * Present only when the session was created by a SubHandle.
35
+ * Format: `[handleName, subName]`.
36
+ */
37
+ hPath?: string[];
38
+ /** Intended audience. */
39
+ aud: string;
40
+ /** Granted scopes. */
41
+ scp: string[];
42
+ /** Expiration timestamp (Unix seconds). */
43
+ exp: number;
44
+ /** Issued-at timestamp (Unix seconds). */
45
+ iat: number;
46
+ /**
47
+ * Unique session identifier, used for revocation.
48
+ * Always present (generated automatically if not provided).
49
+ */
50
+ jti: string;
51
+ }
52
+ /**
53
+ * Interface for application-side revocation checking.
54
+ *
55
+ * The Me2em protocol does not prescribe a storage backend for revocation.
56
+ * Applications implement this interface using their preferred store
57
+ * (Redis, PostgreSQL, in-memory Set, etc.) and pass it to
58
+ * {@link Session.verifyStateless}.
59
+ *
60
+ * @category Extension Points
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * // In-memory implementation (for simple cases)
65
+ * class InMemoryRevocationChecker implements RevocationChecker {
66
+ * private revoked = new Set<string>();
67
+ * async isRevoked(sessionId: string): Promise<boolean> {
68
+ * return this.revoked.has(sessionId);
69
+ * }
70
+ * revoke(sessionId: string): void {
71
+ * this.revoked.add(sessionId);
72
+ * }
73
+ * }
74
+ *
75
+ * // Redis implementation (for production)
76
+ * class RedisRevocationChecker implements RevocationChecker {
77
+ * constructor(private redis: Redis) {}
78
+ * async isRevoked(sessionId: string): Promise<boolean> {
79
+ * return (await this.redis.sismember('me2em:revoked', sessionId)) === 1;
80
+ * }
81
+ * }
82
+ * ```
83
+ */
84
+ export interface RevocationChecker {
85
+ /**
86
+ * Checks whether a session has been revoked.
87
+ *
88
+ * @param sessionId - The `jti` field from the session payload.
89
+ * @returns A Promise resolving to `true` if revoked, `false` otherwise.
90
+ */
91
+ isRevoked(sessionId: string): Promise<boolean>;
92
+ }
93
+ /**
94
+ * Represents a stateless, cryptographically verifiable session token.
95
+ *
96
+ * Instead of storing session state on the server, the Session object
97
+ * encapsulates all necessary authorization data (handle ID, scopes,
98
+ * expiration, derivation path) into a self-contained structure that can
99
+ * be verified using the Handle's or SubHandle's public key.
100
+ *
101
+ * Sessions can be created from either a {@link Handle} or a {@link SubHandle}.
102
+ * When created from a SubHandle, the token carries the derivation path
103
+ * (`hPath`) for hierarchical auditing.
104
+ *
105
+ * @category Core Primitives
106
+ */
107
+ export declare class Session {
108
+ readonly handleId: string;
109
+ readonly handleName: string;
110
+ readonly audience: string;
111
+ readonly scopes: string[];
112
+ readonly expiresAt: number;
113
+ readonly token: string;
114
+ /** Derivation path, present only for SubHandle sessions. */
115
+ readonly path?: string[];
116
+ /** Unique session identifier, used for revocation. */
117
+ readonly sessionId: string;
118
+ /**
119
+ * Creates a new Session instance.
120
+ *
121
+ * @internal Typically created via {@link Session.create} or
122
+ * {@link Session.verifyStateless}. Direct construction is discouraged.
123
+ */
124
+ constructor(handleId: string, handleName: string, audience: string, scopes: string[], expiresAt: number, token: string, path?: string[], sessionId?: string);
125
+ /**
126
+ * Checks if the session has expired based on the current time.
127
+ *
128
+ * @returns `true` if the current time is past the `expiresAt` timestamp.
129
+ */
130
+ isExpired(): boolean;
131
+ /**
132
+ * Creates a new signed session token.
133
+ *
134
+ * If the handle is a {@link SubHandle}, its constraints are validated
135
+ * before signing (audience, scopes, TTL, expiration). The derivation
136
+ * path is included in the payload as `hPath`.
137
+ *
138
+ * @param handle - The Handle or SubHandle that will sign this session.
139
+ * @param options - Session configuration including audience, scopes, TTL, and optional sessionId.
140
+ * @returns A Promise resolving to a new Session instance.
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * const session = await Session.create(handle, {
145
+ * audience: 'app.example.com',
146
+ * scopes: ['read', 'write'],
147
+ * ttl: 3600,
148
+ * sessionId: 'unique-session-id' // optional
149
+ * });
150
+ * ```
151
+ */
152
+ static create(handle: Handle | SubHandle, options: SessionOptions): Promise<Session>;
153
+ private static parseSessionToken;
154
+ /**
155
+ * Verifies a session token statelessly without server-side storage.
156
+ *
157
+ * Validates:
158
+ * - Token format (two Base64URL parts)
159
+ * - Payload size limit
160
+ * - Required fields (`hId`, `hNm`, `aud`, `scp`, `exp`, `iat`, `jti`)
161
+ * - Audience match
162
+ * - Expiration (with clock skew tolerance)
163
+ * - Signature (against the reconstructed Handle or SubHandle public key)
164
+ * - Revocation status (if a {@link RevocationChecker} is provided)
165
+ *
166
+ * For SubHandle sessions (those with `hPath`), the Handle/SubHandle is
167
+ * reconstructed atomically via {@link Identity.deriveSubHandle}.
168
+ *
169
+ * @param token - The Base64URL-encoded session token string.
170
+ * @param companyIdentity - The Identity used to reconstruct Handle/SubHandle public keys.
171
+ * @param expectedAudience - The audience that this token must be intended for.
172
+ * @param revocationChecker - Optional checker for revocation list.
173
+ * @returns A Promise resolving to a verified Session instance.
174
+ * @throws {Error} If the token is invalid, expired, tampered, audience mismatch, or revoked.
175
+ *
176
+ * @example
177
+ * ```ts
178
+ * const session = await Session.verifyStateless(
179
+ * token,
180
+ * companyIdentity,
181
+ * 'app.example.com',
182
+ * redisRevocationChecker // optional
183
+ * );
184
+ * ```
185
+ */
186
+ static verifyStateless(token: string, companyIdentity: Identity, expectedAudience: string, revocationChecker?: RevocationChecker): Promise<Session>;
187
+ /**
188
+ * Verifies a session token together with its attestation chain
189
+ * (Mode 2 - using an attestation chain) — for verifiers that hold only the root PUBLIC key.
190
+ *
191
+ * The chain contains serialized attestations, root first:
192
+ * - handle sessions: `[attestHandle_token]` (length 1)
193
+ * - subhandle sessions: `[attestHandle_token, attestSubHandle_token]`
194
+ * (length 2)
195
+ *
196
+ * Enforced, in order: token structure and required fields (including
197
+ * `iat`); audience; session time (±30 s skew); chain shape; parent
198
+ * signature against `rootPublicKey`; parent validity and revocation;
199
+ * for subhandle sessions — child signature against the parent's
200
+ * `subjectId`, child validity/revocation, name/path agreement,
201
+ * wildcard permitting, `hId == child.subjectId`, and grant nesting
202
+ * (child scopes ⊆ parent scopes, child maxTtl ≤ parent maxTtl);
203
+ * session vs the effective grant (scopes, audiences, TTL); session
204
+ * expiry against the earliest attestation expiry; session signature
205
+ * against `hId`; session revocation — last.
206
+ *
207
+ * @param attestationChain - Attestation tokens, root first; length
208
+ * must match the session kind (1 for Handle, 2 for SubHandle).
209
+ * @param revocationChecker - Optional; consulted for attestation
210
+ * `jti` values (each chain level) and the session `jti`.
211
+ * @returns The verified session.
212
+ * @throws {AttestationError} With `code` and `level` identifying the
213
+ * failed layer — integrate on these fields, not on message text.
214
+ *
215
+ * @example
216
+ * ```ts
217
+ * const A = await identity.attestHandle('station-001', grantA);
218
+ * const sub = await station.deriveSubHandle('connector-ccs');
219
+ * const B = await station.attestSubHandle('connector-ccs', grantB);
220
+ * const session = await Session.create(sub, {
221
+ * audience: 'ev-app.com', scopes: ['charge:start'], ttl: 1800,
222
+ * });
223
+ * const verified = await Session.verifyAttested(
224
+ * session.token, identity.getPublicKey(), [A.token, B.token],
225
+ * 'ev-app.com',
226
+ * );
227
+ * ```
228
+ */
229
+ static verifyAttested(token: string, rootPublicKey: Uint8Array, attestationChain: string[], expectedAudience: string, revocationChecker?: RevocationChecker): Promise<Session>;
230
+ }
231
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAWzC;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,yDAAyD;IACzD,QAAQ,EAAE,MAAM,CAAC;IACjB,6EAA6E;IAC7E,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,+BAA+B;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,uDAAuD;IACvD,GAAG,EAAE,MAAM,CAAC;IACZ,+BAA+B;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,sBAAsB;IACtB,GAAG,EAAE,MAAM,EAAE,CAAC;IACd,2CAA2C;IAC3C,GAAG,EAAE,MAAM,CAAC;IACZ,0CAA0C;IAC1C,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;;;OAKG;IACH,SAAS,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAChD;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,OAAO;IAClB,SAAgB,QAAQ,EAAE,MAAM,CAAC;IACjC,SAAgB,UAAU,EAAE,MAAM,CAAC;IACnC,SAAgB,QAAQ,EAAE,MAAM,CAAC;IACjC,SAAgB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjC,SAAgB,SAAS,EAAE,MAAM,CAAC;IAClC,SAAgB,KAAK,EAAE,MAAM,CAAC;IAC9B,4DAA4D;IAC5D,SAAgB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChC,sDAAsD;IACtD,SAAgB,SAAS,EAAE,MAAM,CAAC;IAElC;;;;;OAKG;gBAED,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EAAE,EAChB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,EACb,IAAI,CAAC,EAAE,MAAM,EAAE,EACf,SAAS,CAAC,EAAE,MAAM;IAYpB;;;;OAIG;IACH,SAAS,IAAI,OAAO;IAIpB;;;;;;;;;;;;;;;;;;;;OAoBG;WACU,MAAM,CACjB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,OAAO,CAAC;IAkDnB,OAAO,CAAC,MAAM,CAAC,iBAAiB;IAqDhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+BG;WACU,eAAe,CAC1B,KAAK,EAAE,MAAM,EACb,eAAe,EAAE,QAAQ,EACzB,gBAAgB,EAAE,MAAM,EACxB,iBAAiB,CAAC,EAAE,iBAAiB,GACpC,OAAO,CAAC,OAAO,CAAC;IAkEnB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QAyCI;WACU,cAAc,CAC1B,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,UAAU,EACzB,gBAAgB,EAAE,MAAM,EAAE,EAC1B,gBAAgB,EAAE,MAAM,EACxB,iBAAiB,CAAC,EAAE,iBAAiB,GACpC,OAAO,CAAC,OAAO,CAAC;CAsNpB"}
@@ -0,0 +1,454 @@
1
+ // session.ts
2
+ import { Handle } from './handle.js';
3
+ import { base64urlEncode, base64urlDecode } from './util.js';
4
+ import { Attestation, AttestationError, } from './attestation.js';
5
+ const MAX_PAYLOAD_SIZE = 4096;
6
+ const CLOCK_SKEW_SECONDS = 30;
7
+ /**
8
+ * Represents a stateless, cryptographically verifiable session token.
9
+ *
10
+ * Instead of storing session state on the server, the Session object
11
+ * encapsulates all necessary authorization data (handle ID, scopes,
12
+ * expiration, derivation path) into a self-contained structure that can
13
+ * be verified using the Handle's or SubHandle's public key.
14
+ *
15
+ * Sessions can be created from either a {@link Handle} or a {@link SubHandle}.
16
+ * When created from a SubHandle, the token carries the derivation path
17
+ * (`hPath`) for hierarchical auditing.
18
+ *
19
+ * @category Core Primitives
20
+ */
21
+ export class Session {
22
+ handleId;
23
+ handleName;
24
+ audience;
25
+ scopes;
26
+ expiresAt;
27
+ token;
28
+ /** Derivation path, present only for SubHandle sessions. */
29
+ path;
30
+ /** Unique session identifier, used for revocation. */
31
+ sessionId;
32
+ /**
33
+ * Creates a new Session instance.
34
+ *
35
+ * @internal Typically created via {@link Session.create} or
36
+ * {@link Session.verifyStateless}. Direct construction is discouraged.
37
+ */
38
+ constructor(handleId, handleName, audience, scopes, expiresAt, token, path, sessionId) {
39
+ this.handleId = handleId;
40
+ this.handleName = handleName;
41
+ this.audience = audience;
42
+ this.scopes = scopes;
43
+ this.expiresAt = expiresAt;
44
+ this.token = token;
45
+ this.path = path;
46
+ this.sessionId = sessionId ?? '';
47
+ }
48
+ /**
49
+ * Checks if the session has expired based on the current time.
50
+ *
51
+ * @returns `true` if the current time is past the `expiresAt` timestamp.
52
+ */
53
+ isExpired() {
54
+ return Date.now() >= this.expiresAt * 1000;
55
+ }
56
+ /**
57
+ * Creates a new signed session token.
58
+ *
59
+ * If the handle is a {@link SubHandle}, its constraints are validated
60
+ * before signing (audience, scopes, TTL, expiration). The derivation
61
+ * path is included in the payload as `hPath`.
62
+ *
63
+ * @param handle - The Handle or SubHandle that will sign this session.
64
+ * @param options - Session configuration including audience, scopes, TTL, and optional sessionId.
65
+ * @returns A Promise resolving to a new Session instance.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * const session = await Session.create(handle, {
70
+ * audience: 'app.example.com',
71
+ * scopes: ['read', 'write'],
72
+ * ttl: 3600,
73
+ * sessionId: 'unique-session-id' // optional
74
+ * });
75
+ * ```
76
+ */
77
+ static async create(handle, options) {
78
+ if (typeof options.ttl !== 'number' ||
79
+ !Number.isInteger(options.ttl) ||
80
+ options.ttl <= 0) {
81
+ throw new Error(`ttl must be a positive integer (seconds), got: ${String(options.ttl)}`);
82
+ }
83
+ handle.validateSessionOptions(options);
84
+ const now = Math.floor(Date.now() / 1000);
85
+ const expiresAt = now + options.ttl;
86
+ const sessionId = options.sessionId ?? crypto.randomUUID();
87
+ const payload = {
88
+ hId: handle.getId(),
89
+ hNm: handle.getName(),
90
+ aud: options.audience,
91
+ scp: options.scopes,
92
+ exp: expiresAt,
93
+ iat: now,
94
+ jti: sessionId,
95
+ };
96
+ // Include derivation path for SubHandle sessions
97
+ const hPath = handle.getPath();
98
+ if (hPath) {
99
+ payload.hPath = hPath;
100
+ }
101
+ const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
102
+ const signature = await handle.sign(payloadBytes);
103
+ const payloadB64 = base64urlEncode(payloadBytes);
104
+ const signatureB64 = base64urlEncode(signature);
105
+ const token = `${payloadB64}.${signatureB64}`;
106
+ return new Session(payload.hId, payload.hNm, payload.aud, payload.scp, payload.exp, token, payload.hPath, sessionId);
107
+ }
108
+ static parseSessionToken(token) {
109
+ if (typeof token !== 'string') {
110
+ throw new Error('Token must be a string');
111
+ }
112
+ const parts = token.split('.');
113
+ if (parts.length !== 2) {
114
+ throw new Error('Invalid token format: expected two Base64URL parts separated by "."');
115
+ }
116
+ const [payloadB64, signatureB64] = parts;
117
+ const b64urlRegex = /^[A-Za-z0-9_-]+$/;
118
+ if (!b64urlRegex.test(payloadB64) || !b64urlRegex.test(signatureB64)) {
119
+ throw new Error('Invalid token format: payload and signature must be valid Base64URL');
120
+ }
121
+ const payloadBytes = base64urlDecode(payloadB64);
122
+ if (payloadBytes.length > MAX_PAYLOAD_SIZE) {
123
+ throw new Error(`Payload exceeds maximum size of ${MAX_PAYLOAD_SIZE} bytes`);
124
+ }
125
+ let payload;
126
+ try {
127
+ const jsonString = new TextDecoder().decode(payloadBytes);
128
+ payload = JSON.parse(jsonString);
129
+ }
130
+ catch {
131
+ throw new Error('Invalid token format: payload is not valid JSON');
132
+ }
133
+ // Required fields validation
134
+ if (!payload.hId ||
135
+ !payload.hNm ||
136
+ !payload.aud ||
137
+ !Array.isArray(payload.scp) ||
138
+ typeof payload.exp !== 'number' ||
139
+ typeof payload.iat !== 'number' ||
140
+ typeof payload.jti !== 'string') {
141
+ throw new Error('Invalid token format: missing required fields (hId, hNm, aud, scp, exp, iat, jti)');
142
+ }
143
+ const signatureBytes = base64urlDecode(signatureB64);
144
+ return { payload, payloadBytes, signatureBytes };
145
+ }
146
+ /**
147
+ * Verifies a session token statelessly without server-side storage.
148
+ *
149
+ * Validates:
150
+ * - Token format (two Base64URL parts)
151
+ * - Payload size limit
152
+ * - Required fields (`hId`, `hNm`, `aud`, `scp`, `exp`, `iat`, `jti`)
153
+ * - Audience match
154
+ * - Expiration (with clock skew tolerance)
155
+ * - Signature (against the reconstructed Handle or SubHandle public key)
156
+ * - Revocation status (if a {@link RevocationChecker} is provided)
157
+ *
158
+ * For SubHandle sessions (those with `hPath`), the Handle/SubHandle is
159
+ * reconstructed atomically via {@link Identity.deriveSubHandle}.
160
+ *
161
+ * @param token - The Base64URL-encoded session token string.
162
+ * @param companyIdentity - The Identity used to reconstruct Handle/SubHandle public keys.
163
+ * @param expectedAudience - The audience that this token must be intended for.
164
+ * @param revocationChecker - Optional checker for revocation list.
165
+ * @returns A Promise resolving to a verified Session instance.
166
+ * @throws {Error} If the token is invalid, expired, tampered, audience mismatch, or revoked.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * const session = await Session.verifyStateless(
171
+ * token,
172
+ * companyIdentity,
173
+ * 'app.example.com',
174
+ * redisRevocationChecker // optional
175
+ * );
176
+ * ```
177
+ */
178
+ static async verifyStateless(token, companyIdentity, expectedAudience, revocationChecker) {
179
+ const { payload, payloadBytes, signatureBytes } = Session.parseSessionToken(token);
180
+ // Audience check
181
+ if (payload.aud !== expectedAudience) {
182
+ throw new Error(`Audience mismatch: expected "${expectedAudience}", got "${payload.aud}"`);
183
+ }
184
+ // Time checks
185
+ const now = Math.floor(Date.now() / 1000);
186
+ if (now > payload.exp + CLOCK_SKEW_SECONDS) {
187
+ throw new Error('Token expired');
188
+ }
189
+ if (now < payload.iat - CLOCK_SKEW_SECONDS) {
190
+ throw new Error('Token is future-dated');
191
+ }
192
+ // Reconstruct Handle or SubHandle
193
+ let handle;
194
+ if (payload.hPath && payload.hPath.length === 2) {
195
+ handle = await companyIdentity.deriveSubHandle(payload.hPath[0], payload.hPath[1]);
196
+ }
197
+ else {
198
+ handle = await companyIdentity.deriveHandle(payload.hNm);
199
+ }
200
+ // Signature verification (wrapped to catch exceptions from the crypto lib)
201
+ const publicKey = handle.getPublicKey();
202
+ let isValid = false;
203
+ try {
204
+ isValid = await Handle.verify(signatureBytes, payloadBytes, publicKey);
205
+ }
206
+ catch {
207
+ isValid = false;
208
+ }
209
+ if (!isValid) {
210
+ throw new Error('Invalid signature: token payload has been tampered with or was not signed by the claimed Handle');
211
+ }
212
+ if (handle.getId() !== payload.hId) {
213
+ throw new Error('hId mismatch');
214
+ }
215
+ // Revocation check — last, after signature is verified
216
+ if (revocationChecker) {
217
+ const isRevoked = await revocationChecker.isRevoked(payload.jti);
218
+ if (isRevoked) {
219
+ throw new Error('Session has been revoked');
220
+ }
221
+ }
222
+ return new Session(payload.hId, payload.hNm, payload.aud, payload.scp, payload.exp, token, payload.hPath, payload.jti);
223
+ }
224
+ /**
225
+ * Verifies a session token together with its attestation chain
226
+ * (Mode 2 - using an attestation chain) — for verifiers that hold only the root PUBLIC key.
227
+ *
228
+ * The chain contains serialized attestations, root first:
229
+ * - handle sessions: `[attestHandle_token]` (length 1)
230
+ * - subhandle sessions: `[attestHandle_token, attestSubHandle_token]`
231
+ * (length 2)
232
+ *
233
+ * Enforced, in order: token structure and required fields (including
234
+ * `iat`); audience; session time (±30 s skew); chain shape; parent
235
+ * signature against `rootPublicKey`; parent validity and revocation;
236
+ * for subhandle sessions — child signature against the parent's
237
+ * `subjectId`, child validity/revocation, name/path agreement,
238
+ * wildcard permitting, `hId == child.subjectId`, and grant nesting
239
+ * (child scopes ⊆ parent scopes, child maxTtl ≤ parent maxTtl);
240
+ * session vs the effective grant (scopes, audiences, TTL); session
241
+ * expiry against the earliest attestation expiry; session signature
242
+ * against `hId`; session revocation — last.
243
+ *
244
+ * @param attestationChain - Attestation tokens, root first; length
245
+ * must match the session kind (1 for Handle, 2 for SubHandle).
246
+ * @param revocationChecker - Optional; consulted for attestation
247
+ * `jti` values (each chain level) and the session `jti`.
248
+ * @returns The verified session.
249
+ * @throws {AttestationError} With `code` and `level` identifying the
250
+ * failed layer — integrate on these fields, not on message text.
251
+ *
252
+ * @example
253
+ * ```ts
254
+ * const A = await identity.attestHandle('station-001', grantA);
255
+ * const sub = await station.deriveSubHandle('connector-ccs');
256
+ * const B = await station.attestSubHandle('connector-ccs', grantB);
257
+ * const session = await Session.create(sub, {
258
+ * audience: 'ev-app.com', scopes: ['charge:start'], ttl: 1800,
259
+ * });
260
+ * const verified = await Session.verifyAttested(
261
+ * session.token, identity.getPublicKey(), [A.token, B.token],
262
+ * 'ev-app.com',
263
+ * );
264
+ * ```
265
+ */
266
+ static async verifyAttested(token, rootPublicKey, attestationChain, expectedAudience, revocationChecker) {
267
+ const { payload, payloadBytes, signatureBytes } = Session.parseSessionToken(token);
268
+ // Step 2: Audience
269
+ if (payload.aud !== expectedAudience) {
270
+ throw new AttestationError('AUDIENCE_NOT_PERMITTED', 'SESSION', `Expected audience "${expectedAudience}", got "${payload.aud}"`);
271
+ }
272
+ // Step 3: Session time
273
+ const now = Math.floor(Date.now() / 1000);
274
+ if (now > payload.exp + CLOCK_SKEW_SECONDS) {
275
+ throw new AttestationError('EXPIRED', 'SESSION', 'Session has expired');
276
+ }
277
+ if (now < payload.iat - CLOCK_SKEW_SECONDS) {
278
+ throw new AttestationError('NOT_YET_VALID', 'SESSION', 'Session is not yet valid');
279
+ }
280
+ // Step 4: Chain structure
281
+ const isSubSession = payload.hPath !== undefined;
282
+ if (isSubSession) {
283
+ if (!payload.hPath || payload.hPath.length !== 2) {
284
+ throw new AttestationError('PATH_MISMATCH', 'SESSION', 'SubHandle session requires hPath of length 2');
285
+ }
286
+ if (attestationChain.length !== 2) {
287
+ throw new AttestationError('CHAIN_INCOMPLETE', 'FORMAT', 'SubHandle session requires exactly 2 attestations');
288
+ }
289
+ }
290
+ else {
291
+ if (attestationChain.length !== 1) {
292
+ throw new AttestationError('CHAIN_INCOMPLETE', 'FORMAT', 'Handle session requires exactly 1 attestation');
293
+ }
294
+ }
295
+ // Step 5: Decode A
296
+ const A = Attestation.decode(attestationChain[0]);
297
+ // Step 6: Verify A signature against root
298
+ let sigOkA = false;
299
+ try {
300
+ sigOkA = await Attestation.verifySignature(attestationChain[0], rootPublicKey);
301
+ }
302
+ catch {
303
+ sigOkA = false;
304
+ }
305
+ if (!sigOkA) {
306
+ throw new AttestationError('BAD_SIGNATURE', 'ROOT', 'Root attestation signature is invalid');
307
+ }
308
+ // Step 7: A time
309
+ if (now > A.exp + CLOCK_SKEW_SECONDS) {
310
+ throw new AttestationError('EXPIRED', 'ROOT', 'Root attestation has expired');
311
+ }
312
+ if (now < A.iat - CLOCK_SKEW_SECONDS) {
313
+ throw new AttestationError('NOT_YET_VALID', 'ROOT', 'Root attestation is not yet valid');
314
+ }
315
+ // Step 8: A revocation
316
+ if (revocationChecker) {
317
+ const isRevoked = await revocationChecker.isRevoked(A.jti);
318
+ if (isRevoked) {
319
+ throw new AttestationError('REVOKED', 'ROOT', 'Root attestation has been revoked');
320
+ }
321
+ }
322
+ let G;
323
+ let bPayload;
324
+ if (isSubSession) {
325
+ // Step 9: SubHandle chain
326
+ const B = Attestation.decode(attestationChain[1]);
327
+ bPayload = B;
328
+ const signerPubABytes = (() => {
329
+ try {
330
+ return base64urlDecode(A.subjectId);
331
+ }
332
+ catch {
333
+ return null;
334
+ }
335
+ })();
336
+ if (!signerPubABytes) {
337
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Cannot decode root attestation subjectId');
338
+ }
339
+ let sigOkB = false;
340
+ try {
341
+ sigOkB = await Attestation.verifySignature(attestationChain[1], signerPubABytes);
342
+ }
343
+ catch {
344
+ sigOkB = false;
345
+ }
346
+ if (!sigOkB) {
347
+ throw new AttestationError('BAD_SIGNATURE', 'HANDLE_ATTESTATION', 'Handle attestation signature is invalid');
348
+ }
349
+ if (now > B.exp + CLOCK_SKEW_SECONDS) {
350
+ throw new AttestationError('EXPIRED', 'HANDLE_ATTESTATION', 'Handle attestation has expired');
351
+ }
352
+ if (now < B.iat - CLOCK_SKEW_SECONDS) {
353
+ throw new AttestationError('NOT_YET_VALID', 'HANDLE_ATTESTATION', 'Handle attestation is not yet valid');
354
+ }
355
+ if (revocationChecker) {
356
+ const isRevoked = await revocationChecker.isRevoked(B.jti);
357
+ if (isRevoked) {
358
+ throw new AttestationError('REVOKED', 'HANDLE_ATTESTATION', 'Handle attestation has been revoked');
359
+ }
360
+ }
361
+ if (B.subjectName !== payload.hPath[1]) {
362
+ throw new AttestationError('PATH_MISMATCH', 'HANDLE_ATTESTATION', `Handle attestation subject "${B.subjectName}" does not match session subName "${payload.hPath[1]}"`);
363
+ }
364
+ if (A.subjectName !== payload.hPath[0]) {
365
+ throw new AttestationError('PATH_MISMATCH', 'ROOT', `Root attestation subject "${A.subjectName}" does not match session handleName "${payload.hPath[0]}"`);
366
+ }
367
+ if (A.grant.subNamePatterns !== undefined) {
368
+ if (!Attestation.matchNamePattern(B.subjectName, A.grant.subNamePatterns)) {
369
+ throw new AttestationError('NAME_NOT_PERMITTED', 'ROOT', `SubHandle name "${B.subjectName}" not permitted by root patterns`);
370
+ }
371
+ }
372
+ if (payload.hId !== B.subjectId) {
373
+ throw new AttestationError('SUBJECT_MISMATCH', 'SUB_ATTESTATION', 'Session handleId does not match handle attestation subjectId');
374
+ }
375
+ // Nested grant check
376
+ const forbidden = B.grant.scopes.filter(s => !A.grant.scopes.includes(s));
377
+ if (forbidden.length > 0) {
378
+ throw new AttestationError('SCOPE_EXCEEDED', 'ROOT', `Handle attestation scopes not subset of root: ${forbidden.join(', ')}`);
379
+ }
380
+ if (B.grant.maxSessionTtl > A.grant.maxSessionTtl) {
381
+ throw new AttestationError('TTL_EXCEEDED', 'ROOT', 'Handle attestation maxSessionTtl exceeds root attestation');
382
+ }
383
+ G = B.grant;
384
+ }
385
+ else {
386
+ // Handle session
387
+ const subjectIdBytes = (() => {
388
+ try {
389
+ return base64urlDecode(A.subjectId);
390
+ }
391
+ catch {
392
+ return null;
393
+ }
394
+ })();
395
+ if (!subjectIdBytes) {
396
+ throw new AttestationError('MALFORMED', 'FORMAT', 'Cannot decode root attestation subjectId');
397
+ }
398
+ if (payload.hId !== A.subjectId) {
399
+ throw new AttestationError('SUBJECT_MISMATCH', 'ROOT', 'Session handleId does not match root attestation subjectId');
400
+ }
401
+ G = A.grant;
402
+ }
403
+ // Step 10: Session vs grant G
404
+ const sessionForbidden = payload.scp.filter(s => !G.scopes.includes(s));
405
+ if (sessionForbidden.length > 0) {
406
+ throw new AttestationError('SCOPE_EXCEEDED', 'SESSION', `Session scopes not permitted by grant: ${sessionForbidden.join(', ')}`);
407
+ }
408
+ if (G.audiences !== undefined && !G.audiences.includes(payload.aud)) {
409
+ throw new AttestationError('AUDIENCE_NOT_PERMITTED', 'SESSION', `Session audience "${payload.aud}" not in grant audiences`);
410
+ }
411
+ if ((payload.exp - payload.iat) > G.maxSessionTtl) {
412
+ throw new AttestationError('TTL_EXCEEDED', 'SESSION', `Session duration ${payload.exp - payload.iat}s exceeds grant maxSessionTtl ${G.maxSessionTtl}s`);
413
+ }
414
+ // Step 11: Session does not outlive attestation
415
+ const earliestAttestationExp = isSubSession
416
+ ? Math.min(A.exp, bPayload.exp)
417
+ : A.exp;
418
+ if (payload.exp > earliestAttestationExp + CLOCK_SKEW_SECONDS) {
419
+ throw new AttestationError('SESSION_OUTLIVES_ATTESTATION', 'SESSION', 'Session expires after the earliest attestation');
420
+ }
421
+ // Step 12: Session signature
422
+ const sessionPub = (() => {
423
+ try {
424
+ return base64urlDecode(payload.hId);
425
+ }
426
+ catch {
427
+ return null;
428
+ }
429
+ })();
430
+ if (!sessionPub) {
431
+ throw new AttestationError('BAD_SIGNATURE', 'SESSION', 'Cannot decode session hId');
432
+ }
433
+ let sigOk = false;
434
+ try {
435
+ sigOk = await Handle.verify(signatureBytes, payloadBytes, sessionPub);
436
+ }
437
+ catch {
438
+ sigOk = false;
439
+ }
440
+ if (!sigOk) {
441
+ throw new AttestationError('BAD_SIGNATURE', 'SESSION', 'Session signature is invalid');
442
+ }
443
+ // Step 13: Session revocation
444
+ if (revocationChecker) {
445
+ const isRevoked = await revocationChecker.isRevoked(payload.jti);
446
+ if (isRevoked) {
447
+ throw new AttestationError('REVOKED', 'SESSION', 'Session has been revoked');
448
+ }
449
+ }
450
+ // Step 14
451
+ return new Session(payload.hId, payload.hNm, payload.aud, payload.scp, payload.exp, token, payload.hPath, payload.jti);
452
+ }
453
+ }
454
+ //# sourceMappingURL=session.js.map