@sess.si/sdk 0.0.0-stage → 0.1.0-rc.4

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 (95) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +9 -0
  4. package/README.md +136 -2
  5. package/dist/client.d.ts +12 -0
  6. package/dist/client.d.ts.map +1 -0
  7. package/dist/client.js +34 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/errors.d.ts +40 -0
  10. package/dist/errors.d.ts.map +1 -0
  11. package/dist/errors.js +52 -0
  12. package/dist/errors.js.map +1 -0
  13. package/dist/generated/openapi.d.ts +2462 -0
  14. package/dist/generated/openapi.d.ts.map +1 -0
  15. package/dist/generated/openapi.js +2 -0
  16. package/dist/generated/openapi.js.map +1 -0
  17. package/dist/index.d.ts +5 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +4 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/internal/decode.d.ts +21 -0
  22. package/dist/internal/decode.d.ts.map +1 -0
  23. package/dist/internal/decode.js +333 -0
  24. package/dist/internal/decode.js.map +1 -0
  25. package/dist/internal/json.d.ts +4 -0
  26. package/dist/internal/json.d.ts.map +1 -0
  27. package/dist/internal/json.js +75 -0
  28. package/dist/internal/json.js.map +1 -0
  29. package/dist/internal/time.d.ts +11 -0
  30. package/dist/internal/time.d.ts.map +1 -0
  31. package/dist/internal/time.js +71 -0
  32. package/dist/internal/time.js.map +1 -0
  33. package/dist/polling.d.ts +3 -0
  34. package/dist/polling.d.ts.map +1 -0
  35. package/dist/polling.js +61 -0
  36. package/dist/polling.js.map +1 -0
  37. package/dist/receipts/index.d.ts +5 -0
  38. package/dist/receipts/index.d.ts.map +1 -0
  39. package/dist/receipts/index.js +2 -0
  40. package/dist/receipts/index.js.map +1 -0
  41. package/dist/receipts/json.d.ts +22 -0
  42. package/dist/receipts/json.d.ts.map +1 -0
  43. package/dist/receipts/json.js +152 -0
  44. package/dist/receipts/json.js.map +1 -0
  45. package/dist/receipts/key-cache.d.ts +28 -0
  46. package/dist/receipts/key-cache.d.ts.map +1 -0
  47. package/dist/receipts/key-cache.js +110 -0
  48. package/dist/receipts/key-cache.js.map +1 -0
  49. package/dist/receipts/resource.d.ts +39 -0
  50. package/dist/receipts/resource.d.ts.map +1 -0
  51. package/dist/receipts/resource.js +119 -0
  52. package/dist/receipts/resource.js.map +1 -0
  53. package/dist/receipts/verify.d.ts +90 -0
  54. package/dist/receipts/verify.d.ts.map +1 -0
  55. package/dist/receipts/verify.js +294 -0
  56. package/dist/receipts/verify.js.map +1 -0
  57. package/dist/sessions.d.ts +19 -0
  58. package/dist/sessions.d.ts.map +1 -0
  59. package/dist/sessions.js +145 -0
  60. package/dist/sessions.js.map +1 -0
  61. package/dist/transport.d.ts +29 -0
  62. package/dist/transport.d.ts.map +1 -0
  63. package/dist/transport.js +447 -0
  64. package/dist/transport.js.map +1 -0
  65. package/dist/types.d.ts +149 -0
  66. package/dist/types.d.ts.map +1 -0
  67. package/dist/types.js +9 -0
  68. package/dist/types.js.map +1 -0
  69. package/dist/webhook-resource.d.ts +13 -0
  70. package/dist/webhook-resource.d.ts.map +1 -0
  71. package/dist/webhook-resource.js +52 -0
  72. package/dist/webhook-resource.js.map +1 -0
  73. package/dist/webhooks/index.d.ts +22 -0
  74. package/dist/webhooks/index.d.ts.map +1 -0
  75. package/dist/webhooks/index.js +184 -0
  76. package/dist/webhooks/index.js.map +1 -0
  77. package/package.json +74 -4
  78. package/src/client.ts +41 -0
  79. package/src/errors.ts +96 -0
  80. package/src/generated/openapi.ts +2578 -0
  81. package/src/index.ts +4 -0
  82. package/src/internal/decode.ts +317 -0
  83. package/src/internal/json.ts +64 -0
  84. package/src/internal/time.ts +85 -0
  85. package/src/polling.ts +77 -0
  86. package/src/receipts/index.ts +16 -0
  87. package/src/receipts/json.ts +168 -0
  88. package/src/receipts/key-cache.ts +143 -0
  89. package/src/receipts/resource.ts +227 -0
  90. package/src/receipts/verify.ts +468 -0
  91. package/src/sessions.ts +227 -0
  92. package/src/transport.ts +524 -0
  93. package/src/types.ts +135 -0
  94. package/src/webhook-resource.ts +81 -0
  95. package/src/webhooks/index.ts +246 -0
@@ -0,0 +1,468 @@
1
+ import { compactVerify, importJWK } from 'jose';
2
+ import type { InteractiveSurfaceRevision } from '../types.js';
3
+ import {
4
+ abortError,
5
+ canonicalJson,
6
+ checkedInstant,
7
+ deepFreeze,
8
+ exactKeys,
9
+ isRecord,
10
+ jsonDigest,
11
+ snapshotJson,
12
+ verificationError,
13
+ waitWithSignal,
14
+ type DeepReadonly,
15
+ } from './json.js';
16
+
17
+ export const MAX_RECEIPT_BYTES = 64 * 1024;
18
+ export const MAX_RECEIPT_KEY_SET_BYTES = 256 * 1024;
19
+ const MAX_KEYS = 64;
20
+ const KID = /^[A-Za-z0-9._-]{1,64}$/;
21
+ const SESSION_ID = /^ses_[0-9A-HJKMNP-TV-Z]{26}$/;
22
+ const EVENT_ID = /^evt_[0-9A-HJKMNP-TV-Z]{26}$/;
23
+ const ACTION_ID = /^[a-z][a-z0-9_]{0,31}$/;
24
+ const DIGEST = /^sha256:[0-9a-f]{64}$/;
25
+
26
+ /** Public Ed25519 verification material; private JWK parameters are refused. */
27
+ export interface ReceiptPublicKey {
28
+ kty: 'OKP';
29
+ crv: 'Ed25519';
30
+ x: string;
31
+ kid: string;
32
+ alg?: 'EdDSA';
33
+ use?: 'sig';
34
+ key_ops?: readonly 'verify'[];
35
+ ext?: boolean;
36
+ }
37
+
38
+ export interface ReceiptKeySet {
39
+ keys: readonly ReceiptPublicKey[];
40
+ }
41
+
42
+ /** A resolver is explicitly trusted application configuration, never JWT URL discovery. */
43
+ export type ReceiptKeyResolver = (context: {
44
+ readonly kid: string;
45
+ readonly issuer: string;
46
+ readonly signal?: AbortSignal;
47
+ }) => ReceiptKeySet | Promise<ReceiptKeySet>;
48
+
49
+ export interface ReceiptClaims {
50
+ sess_receipt: 1;
51
+ iss: string;
52
+ aud: string;
53
+ jti: string;
54
+ iat: number;
55
+ exp: number;
56
+ accepted_at: string;
57
+ workspace_id: string;
58
+ session_id: string;
59
+ step_id: string;
60
+ event_id: string;
61
+ surface: { revision: number; hash: string; renderer_version: 'sess-html-form-1' };
62
+ action: { id: string; label: string; summary: string };
63
+ input_hash: string;
64
+ actor: { assurance: 'link_holder'; subject: string };
65
+ return_binding: { recipient: string; return_channel_id: null };
66
+ }
67
+
68
+ export interface VerifyDecisionReceiptInput {
69
+ receipt: string | null;
70
+ /** Trusted protocol identity, independently configured. */
71
+ issuer: string;
72
+ /** Trusted resource workspace, never read from an unverified receipt. */
73
+ audience: string;
74
+ expected: {
75
+ sessionId: string;
76
+ eventId: string;
77
+ revision: number;
78
+ actionId: string;
79
+ acceptedAt: string;
80
+ };
81
+ input: Record<string, unknown>;
82
+ /** The complete normalized `interaction` from the immutable Surface endpoint. */
83
+ interaction: InteractiveSurfaceRevision['interaction'];
84
+ keys?: ReceiptKeySet;
85
+ keyResolver?: ReceiptKeyResolver;
86
+ }
87
+
88
+ export interface VerifyDecisionReceiptOptions {
89
+ /** An explicit verification instant, useful for deliberate archival verification/tests. */
90
+ now?: Date;
91
+ /** Issued-time tolerance only, 0–60 seconds. Expiry never receives a grace interval. */
92
+ issuedAtToleranceSeconds?: number;
93
+ signal?: AbortSignal;
94
+ }
95
+
96
+ function identifier(value: unknown): value is string {
97
+ return (
98
+ typeof value === 'string' &&
99
+ value.length > 0 &&
100
+ value.length <= 200 &&
101
+ !/[\s\u0000-\u001f\u007f-\u009f]/.test(value)
102
+ );
103
+ }
104
+
105
+ /** Validates and copies the whole set, not merely the key selected by the token. */
106
+ export function validateKeySet(raw: unknown): ReceiptKeySet {
107
+ const value = snapshotJson(raw);
108
+ if (
109
+ !isRecord(value) ||
110
+ !exactKeys(value, ['keys']) ||
111
+ !Array.isArray(value.keys) ||
112
+ value.keys.length === 0 ||
113
+ value.keys.length > MAX_KEYS ||
114
+ Buffer.byteLength(canonicalJson(value), 'utf8') > MAX_RECEIPT_KEY_SET_BYTES
115
+ ) {
116
+ throw verificationError(
117
+ 'INVALID_KEY_SET',
118
+ 'The trusted receipt key set is malformed or exceeds its safety limit.',
119
+ );
120
+ }
121
+ const seen = new Set<string>();
122
+ for (const key of value.keys) {
123
+ if (
124
+ !isRecord(key) ||
125
+ Object.keys(key).some(
126
+ (name) => !['kty', 'crv', 'x', 'kid', 'alg', 'use', 'key_ops', 'ext'].includes(name),
127
+ ) ||
128
+ key.kty !== 'OKP' ||
129
+ key.crv !== 'Ed25519' ||
130
+ typeof key.kid !== 'string' ||
131
+ !KID.test(key.kid) ||
132
+ typeof key.x !== 'string' ||
133
+ !/^[A-Za-z0-9_-]{43}$/.test(key.x) ||
134
+ Buffer.from(key.x, 'base64url').length !== 32 ||
135
+ Buffer.from(key.x, 'base64url').toString('base64url') !== key.x ||
136
+ (key.alg !== undefined && key.alg !== 'EdDSA') ||
137
+ (key.use !== undefined && key.use !== 'sig') ||
138
+ (key.key_ops !== undefined &&
139
+ (!Array.isArray(key.key_ops) || key.key_ops.length !== 1 || key.key_ops[0] !== 'verify')) ||
140
+ (key.ext !== undefined && typeof key.ext !== 'boolean')
141
+ ) {
142
+ throw verificationError(
143
+ 'INVALID_PUBLIC_KEY',
144
+ 'Receipt keys must be unambiguous public Ed25519 verification keys.',
145
+ );
146
+ }
147
+ if (seen.has(key.kid))
148
+ throw verificationError('DUPLICATE_KEY_ID', 'The trusted key set contains duplicate key IDs.');
149
+ seen.add(key.kid);
150
+ }
151
+ return deepFreeze(value) as unknown as ReceiptKeySet;
152
+ }
153
+
154
+ function decodeSegment(segment: string): string {
155
+ const bytes = Buffer.from(segment, 'base64url');
156
+ if (bytes.toString('base64url') !== segment)
157
+ throw verificationError('MALFORMED_RECEIPT', 'The receipt is not canonical base64url.');
158
+ try {
159
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
160
+ } catch {
161
+ throw verificationError('MALFORMED_RECEIPT', 'The receipt does not contain valid UTF-8 JSON.');
162
+ }
163
+ }
164
+
165
+ /** Header fields have only string values; reject duplicate names before JOSE parsing. */
166
+ function headerOf(encoded: string): { alg: string; kid: string; typ: string } {
167
+ let parsed: unknown;
168
+ const text = decodeSegment(encoded);
169
+ try {
170
+ parsed = JSON.parse(text);
171
+ } catch {
172
+ throw verificationError('MALFORMED_RECEIPT', 'The receipt protected header is not JSON.');
173
+ }
174
+ if (
175
+ !isRecord(parsed) ||
176
+ !exactKeys(parsed, ['alg', 'kid', 'typ']) ||
177
+ typeof parsed.alg !== 'string' ||
178
+ typeof parsed.typ !== 'string' ||
179
+ typeof parsed.kid !== 'string' ||
180
+ !KID.test(parsed.kid)
181
+ ) {
182
+ throw verificationError(
183
+ 'UNSUPPORTED_HEADER',
184
+ 'The receipt protected header has missing or unsupported fields.',
185
+ );
186
+ }
187
+ // Tokenize JSON strings, punctuation and whitespace. The exact shape above allows only
188
+ // {string:string,...}; six string tokens means precisely three names and three values.
189
+ const strings = text.match(/"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/g);
190
+ if (strings?.length !== 6)
191
+ throw verificationError('UNSUPPORTED_HEADER', 'Duplicate receipt header fields are not supported.');
192
+ if (parsed.alg !== 'EdDSA')
193
+ throw verificationError('UNSUPPORTED_ALGORITHM', 'The receipt must use the supported EdDSA algorithm.');
194
+ if (parsed.typ !== 'sess-receipt+jwt')
195
+ throw verificationError('UNSUPPORTED_TYPE', 'The receipt has an unsupported protected type.');
196
+ return parsed as { alg: string; kid: string; typ: string };
197
+ }
198
+
199
+ function claimsOf(raw: unknown): ReceiptClaims {
200
+ if (!isRecord(raw) || raw.sess_receipt !== 1) {
201
+ throw verificationError('UNSUPPORTED_RECEIPT_VERSION', 'Only receipt format version 1 is supported.');
202
+ }
203
+ const top = [
204
+ 'sess_receipt',
205
+ 'iss',
206
+ 'aud',
207
+ 'jti',
208
+ 'iat',
209
+ 'exp',
210
+ 'accepted_at',
211
+ 'workspace_id',
212
+ 'session_id',
213
+ 'step_id',
214
+ 'event_id',
215
+ 'surface',
216
+ 'action',
217
+ 'input_hash',
218
+ 'actor',
219
+ 'return_binding',
220
+ ];
221
+ const surface = raw.surface;
222
+ const action = raw.action;
223
+ const actor = raw.actor;
224
+ const binding = raw.return_binding;
225
+ if (
226
+ !exactKeys(raw, top) ||
227
+ ![raw.iss, raw.aud, raw.jti, raw.workspace_id, raw.session_id, raw.step_id, raw.event_id].every(
228
+ identifier,
229
+ ) ||
230
+ !Number.isSafeInteger(raw.iat) ||
231
+ !Number.isSafeInteger(raw.exp) ||
232
+ (raw.iat as number) < 0 ||
233
+ (raw.exp as number) <= (raw.iat as number) ||
234
+ checkedInstant(raw.accepted_at) === undefined ||
235
+ !isRecord(surface) ||
236
+ !exactKeys(surface, ['revision', 'hash', 'renderer_version']) ||
237
+ !Number.isSafeInteger(surface.revision) ||
238
+ (surface.revision as number) < 1 ||
239
+ typeof surface.hash !== 'string' ||
240
+ !DIGEST.test(surface.hash) ||
241
+ !isRecord(action) ||
242
+ !exactKeys(action, ['id', 'label', 'summary']) ||
243
+ !identifier(action.id) ||
244
+ typeof action.label !== 'string' ||
245
+ action.label.length === 0 ||
246
+ typeof action.summary !== 'string' ||
247
+ typeof raw.input_hash !== 'string' ||
248
+ !DIGEST.test(raw.input_hash) ||
249
+ !isRecord(actor) ||
250
+ !exactKeys(actor, ['assurance', 'subject']) ||
251
+ !isRecord(binding) ||
252
+ !exactKeys(binding, ['recipient', 'return_channel_id'])
253
+ ) {
254
+ throw verificationError('INVALID_CLAIMS', 'The receipt claims do not match the supported format.');
255
+ }
256
+ if (surface.renderer_version !== 'sess-html-form-1') {
257
+ throw verificationError('UNSUPPORTED_RENDERER', 'The receipt names an unsupported renderer version.');
258
+ }
259
+ if (actor.assurance !== 'link_holder' || !identifier(actor.subject)) {
260
+ throw verificationError('UNSUPPORTED_ACTOR', 'The receipt actor assurance or subject is unsupported.');
261
+ }
262
+ if (!identifier(binding.recipient) || binding.return_channel_id !== null) {
263
+ throw verificationError('RETURN_BINDING_MISMATCH', 'The receipt return binding is unsupported.');
264
+ }
265
+ return raw as unknown as ReceiptClaims;
266
+ }
267
+
268
+ /**
269
+ * Fully verifies a version-1 receipt and its exact accepted record. Explicit keys make this
270
+ * function entirely offline. A valid receipt attests the accepted record, not business authority.
271
+ */
272
+ export async function verifyDecisionReceipt(
273
+ input: VerifyDecisionReceiptInput,
274
+ options: VerifyDecisionReceiptOptions = {},
275
+ ): Promise<DeepReadonly<ReceiptClaims>> {
276
+ // Capture all caller-owned data and options before a resolver can yield control.
277
+ if (input?.receipt === null)
278
+ throw verificationError(
279
+ 'LEGACY_RECEIPT_UNAVAILABLE',
280
+ 'This accepted response has no verifiable receipt.',
281
+ );
282
+ if (
283
+ typeof input?.receipt !== 'string' ||
284
+ input.receipt.length > MAX_RECEIPT_BYTES ||
285
+ !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(input.receipt)
286
+ ) {
287
+ throw verificationError(
288
+ 'MALFORMED_RECEIPT',
289
+ 'The receipt is malformed or exceeds the 64 KiB safety limit.',
290
+ );
291
+ }
292
+ const receipt = input.receipt;
293
+ const issuer = input.issuer;
294
+ const audience = input.audience;
295
+ if (!identifier(issuer) || !identifier(audience)) {
296
+ throw verificationError(
297
+ 'VERIFICATION_CONTEXT_MISSING',
298
+ 'A trusted issuer and expected resource workspace are required.',
299
+ );
300
+ }
301
+ const expected = snapshotJson(input.expected);
302
+ const acceptedInput = snapshotJson(input.input);
303
+ const interaction = snapshotJson(input.interaction);
304
+ const resolver = input.keyResolver;
305
+ const keys = input.keys === undefined ? undefined : validateKeySet(input.keys);
306
+ if (
307
+ (keys === undefined) === (resolver === undefined) ||
308
+ (resolver !== undefined && typeof resolver !== 'function')
309
+ ) {
310
+ throw verificationError(
311
+ 'VERIFICATION_CONTEXT_MISSING',
312
+ 'Provide exactly one trusted public key set or key resolver.',
313
+ );
314
+ }
315
+ const signal = options.signal;
316
+ const now =
317
+ options.now === undefined ? Date.now() : options.now instanceof Date ? options.now.getTime() : NaN;
318
+ const tolerance = options.issuedAtToleranceSeconds ?? 60;
319
+ if (!Number.isFinite(now) || !Number.isFinite(tolerance) || tolerance < 0 || tolerance > 60) {
320
+ throw verificationError(
321
+ 'INVALID_VERIFICATION_OPTIONS',
322
+ 'Use a valid verification time and issued-time tolerance between 0 and 60 seconds.',
323
+ );
324
+ }
325
+ if (signal?.aborted) throw abortError(signal);
326
+ if (
327
+ !isRecord(expected) ||
328
+ !SESSION_ID.test(expected.sessionId) ||
329
+ !EVENT_ID.test(expected.eventId) ||
330
+ !Number.isSafeInteger(expected.revision) ||
331
+ expected.revision < 1 ||
332
+ !ACTION_ID.test(expected.actionId) ||
333
+ checkedInstant(expected.acceptedAt) === undefined ||
334
+ !isRecord(acceptedInput) ||
335
+ !isRecord(interaction) ||
336
+ interaction.mode !== 'interactive' ||
337
+ interaction.response_policy !== 'first' ||
338
+ !Array.isArray(interaction.actions) ||
339
+ !isRecord(interaction.source) ||
340
+ interaction.source.kind !== 'sess_surface' ||
341
+ !Array.isArray(interaction.source.components)
342
+ ) {
343
+ throw verificationError(
344
+ 'INVALID_VERIFICATION_INPUT',
345
+ 'Verification requires an accepted record and its complete normalized immutable interaction.',
346
+ );
347
+ }
348
+ const parts = receipt.split('.') as [string, string, string];
349
+ const header = headerOf(parts[0]);
350
+ let raw: unknown;
351
+ const payloadText = decodeSegment(parts[1]);
352
+ try {
353
+ raw = JSON.parse(payloadText);
354
+ } catch {
355
+ throw verificationError('MALFORMED_RECEIPT', 'The receipt payload is not JSON.');
356
+ }
357
+ const claims = claimsOf(snapshotJson(raw));
358
+ if (canonicalJson(claims) !== payloadText) {
359
+ throw verificationError(
360
+ 'NON_CANONICAL_PAYLOAD',
361
+ 'The signed receipt payload must be RFC 8785 canonical JSON.',
362
+ );
363
+ }
364
+ if (claims.iss !== issuer)
365
+ throw verificationError('ISSUER_MISMATCH', 'The receipt issuer does not match the trusted issuer.');
366
+ if (
367
+ claims.aud !== audience ||
368
+ claims.workspace_id !== audience ||
369
+ claims.return_binding.recipient !== audience
370
+ ) {
371
+ throw verificationError(
372
+ 'AUDIENCE_MISMATCH',
373
+ 'The receipt does not belong to the expected resource workspace.',
374
+ );
375
+ }
376
+ if (
377
+ claims.session_id !== expected.sessionId ||
378
+ claims.event_id !== expected.eventId ||
379
+ claims.jti !== expected.eventId ||
380
+ claims.step_id !== `rev_${expected.revision}` ||
381
+ claims.surface.revision !== expected.revision
382
+ ) {
383
+ throw verificationError(
384
+ 'RECORD_BINDING_MISMATCH',
385
+ 'The receipt does not bind the expected Session, event and revision.',
386
+ );
387
+ }
388
+ if (claims.actor.subject !== `${audience}:human_link:${expected.sessionId}`) {
389
+ throw verificationError(
390
+ 'ACTOR_BINDING_MISMATCH',
391
+ 'The receipt actor is not bound to this resource workspace and Session.',
392
+ );
393
+ }
394
+ const acceptedAt = checkedInstant(claims.accepted_at) as number;
395
+ if (claims.accepted_at !== expected.acceptedAt || Math.floor(acceptedAt / 1000) !== claims.iat) {
396
+ throw verificationError(
397
+ 'ACCEPTED_TIME_MISMATCH',
398
+ 'The receipt acceptance time does not match the accepted record.',
399
+ );
400
+ }
401
+ if (claims.exp * 1000 <= now)
402
+ throw verificationError('RECEIPT_EXPIRED', 'The receipt has expired at the verification time.');
403
+ if (acceptedAt > now + tolerance * 1000 || claims.iat * 1000 > now + tolerance * 1000) {
404
+ throw verificationError(
405
+ 'RECEIPT_FROM_FUTURE',
406
+ 'The receipt was issued after the allowed clock tolerance.',
407
+ );
408
+ }
409
+ const actions = interaction.actions.filter((action) => isRecord(action) && action.id === expected.actionId);
410
+ const action = actions[0];
411
+ if (
412
+ actions.length !== 1 ||
413
+ !action ||
414
+ claims.action.id !== expected.actionId ||
415
+ claims.action.label !== action.label ||
416
+ claims.action.summary !== (action.intent ?? '')
417
+ ) {
418
+ throw verificationError(
419
+ 'ACTION_BINDING_MISMATCH',
420
+ 'The receipt action does not match its immutable Surface action.',
421
+ );
422
+ }
423
+ if (claims.surface.hash !== jsonDigest(interaction)) {
424
+ throw verificationError(
425
+ 'SURFACE_HASH_MISMATCH',
426
+ 'The receipt does not bind the complete immutable interaction.',
427
+ );
428
+ }
429
+ if (claims.input_hash !== jsonDigest(acceptedInput)) {
430
+ throw verificationError('INPUT_HASH_MISMATCH', 'The receipt does not bind the accepted typed input.');
431
+ }
432
+ let trustedKeys = keys;
433
+ if (!trustedKeys && resolver) {
434
+ let resolved: ReceiptKeySet;
435
+ try {
436
+ resolved = await waitWithSignal(
437
+ Promise.resolve(resolver(Object.freeze({ kid: header.kid, issuer, ...(signal ? { signal } : {}) }))),
438
+ signal,
439
+ );
440
+ } catch {
441
+ if (signal?.aborted) throw abortError(signal);
442
+ // Callback failures may contain arbitrary application or upstream material,
443
+ // including caller-created SessError instances. Do not forward their fields.
444
+ throw verificationError(
445
+ 'KEY_RESOLUTION_FAILED',
446
+ 'The trusted receipt key resolver could not supply verification keys.',
447
+ );
448
+ }
449
+ trustedKeys = validateKeySet(resolved);
450
+ }
451
+ const publicKey = trustedKeys?.keys.find((key) => key.kid === header.kid);
452
+ if (!publicKey)
453
+ throw verificationError('UNKNOWN_KEY_ID', 'The receipt signing key is not in the trusted key set.');
454
+ try {
455
+ const key = await waitWithSignal(
456
+ importJWK({ ...publicKey, key_ops: ['verify'], ext: false }, 'EdDSA'),
457
+ signal,
458
+ );
459
+ await waitWithSignal(compactVerify(receipt, key, { algorithms: ['EdDSA'] }), signal);
460
+ } catch {
461
+ if (signal?.aborted) throw abortError(signal);
462
+ throw verificationError(
463
+ 'INVALID_SIGNATURE',
464
+ 'The receipt signature did not verify with the trusted Ed25519 key.',
465
+ );
466
+ }
467
+ return deepFreeze(claims);
468
+ }
@@ -0,0 +1,227 @@
1
+ import { SessError } from './errors.js';
2
+ import { Transport, pathSegment } from './transport.js';
3
+ import {
4
+ decodeCreate,
5
+ decodeDeliveries,
6
+ decodeEvents,
7
+ decodeSession,
8
+ decodeSurface,
9
+ decodeRedelivery,
10
+ } from './internal/decode.js';
11
+ import { boundedNumber } from './internal/time.js';
12
+ import { waitForResponse } from './polling.js';
13
+ import type {
14
+ ApiResult,
15
+ CreateSessionRequest,
16
+ CreateSessionResponse,
17
+ Deliveries,
18
+ InteractiveSession,
19
+ MutationOptions,
20
+ PublishSessionRequest,
21
+ RequestOptions,
22
+ Session,
23
+ SessionEvents,
24
+ SurfaceRevision,
25
+ VersionedResult,
26
+ WaitOptions,
27
+ WaitResult,
28
+ RedeliverResponse,
29
+ } from './types.js';
30
+
31
+ function mutationIdentity(options: MutationOptions): {
32
+ ifMatch: string;
33
+ idempotencyKey?: string;
34
+ requestOptions: RequestOptions;
35
+ } {
36
+ const source = options ?? ({} as MutationOptions);
37
+ if (typeof source !== 'object' || Array.isArray(source))
38
+ throw new SessError('configuration', 'Mutation options must be an object.', { outcome: 'not_sent' });
39
+ // Inspect the two replay identity fields before spreading/accessing caller options.
40
+ // Accessor or inherited identities are not immutable primitive options.
41
+ for (const name of ['ifMatch', 'idempotencyKey'] as const) {
42
+ const descriptor = Object.getOwnPropertyDescriptor(source, name);
43
+ if (
44
+ (name in source && !descriptor) ||
45
+ (descriptor && !('value' in descriptor)) ||
46
+ (name === 'idempotencyKey' && descriptor && typeof descriptor.value !== 'string')
47
+ )
48
+ throw new SessError(
49
+ 'configuration',
50
+ 'Mutation identity options must be primitive string data properties.',
51
+ { outcome: 'not_sent' },
52
+ );
53
+ }
54
+ const { ifMatch, idempotencyKey, ...requestOptions } = source;
55
+ return { ifMatch, idempotencyKey, requestOptions };
56
+ }
57
+
58
+ export class Sessions {
59
+ #transport: Transport;
60
+ constructor(transport: Transport) {
61
+ this.#transport = transport;
62
+ }
63
+
64
+ /** Creates once. A lost reply may mean creation succeeded; no retry is safe. */
65
+ create(
66
+ body: CreateSessionRequest,
67
+ options: RequestOptions = {},
68
+ ): Promise<VersionedResult<CreateSessionResponse>> {
69
+ if ('idempotencyKey' in options || 'ifMatch' in options)
70
+ return Promise.reject(
71
+ new SessError('configuration', 'Session creation does not support idempotency keys or If-Match.', {
72
+ outcome: 'not_sent',
73
+ }),
74
+ );
75
+ return this.#transport.request(
76
+ {
77
+ name: 'sessions.create',
78
+ method: 'POST',
79
+ path: '/v1/sessions',
80
+ body,
81
+ status: 201,
82
+ versioned: true,
83
+ retry: 'never',
84
+ parse: (value) => decodeCreate(value, this.#transport.allowInsecureLocalhost),
85
+ },
86
+ options,
87
+ ) as Promise<VersionedResult<CreateSessionResponse>>;
88
+ }
89
+ retrieve(id: string, options?: RequestOptions): Promise<VersionedResult<Session>> {
90
+ return this.#transport.request(
91
+ {
92
+ name: 'sessions.retrieve',
93
+ method: 'GET',
94
+ path: `/v1/sessions/${pathSegment(id)}`,
95
+ status: 200,
96
+ versioned: true,
97
+ retry: 'safe',
98
+ parse: (value) => decodeSession(value, id),
99
+ },
100
+ options,
101
+ ) as Promise<VersionedResult<Session>>;
102
+ }
103
+ /** Full next interaction, with the original concurrency and replay identity. */
104
+ async publish(
105
+ id: string,
106
+ body: PublishSessionRequest,
107
+ options: MutationOptions,
108
+ ): Promise<VersionedResult<InteractiveSession>> {
109
+ const { ifMatch, idempotencyKey, requestOptions } = mutationIdentity(options);
110
+ return this.#transport.request(
111
+ {
112
+ name: 'sessions.publish',
113
+ method: 'PATCH',
114
+ path: `/v1/sessions/${pathSegment(id)}`,
115
+ body,
116
+ ifMatch,
117
+ idempotencyKey,
118
+ status: 200,
119
+ versioned: true,
120
+ retry: 'mutation',
121
+ parse: (value) => {
122
+ const session = decodeSession(value, id);
123
+ if (!('status' in session) || session.status !== 'active')
124
+ throw new SessError('protocol', 'Publish did not return an active interactive Session.', {
125
+ code: 'INVALID_RESPONSE',
126
+ });
127
+ return session;
128
+ },
129
+ },
130
+ requestOptions,
131
+ ) as Promise<VersionedResult<InteractiveSession>>;
132
+ }
133
+ async complete(id: string, options: MutationOptions): Promise<VersionedResult<InteractiveSession>> {
134
+ const { ifMatch, idempotencyKey, requestOptions } = mutationIdentity(options);
135
+ return this.#transport.request(
136
+ {
137
+ name: 'sessions.complete',
138
+ method: 'POST',
139
+ path: `/v1/sessions/${pathSegment(id)}/complete`,
140
+ ifMatch,
141
+ idempotencyKey,
142
+ status: 200,
143
+ versioned: true,
144
+ retry: 'mutation',
145
+ parse: (value) => {
146
+ const session = decodeSession(value, id);
147
+ if (!('status' in session) || session.status !== 'completed')
148
+ throw new SessError('protocol', 'Complete did not return a completed interactive Session.', {
149
+ code: 'INVALID_RESPONSE',
150
+ });
151
+ return session;
152
+ },
153
+ },
154
+ requestOptions,
155
+ ) as Promise<VersionedResult<InteractiveSession>>;
156
+ }
157
+ listEvents(id: string, options?: RequestOptions): Promise<ApiResult<SessionEvents>> {
158
+ return this.#transport.request(
159
+ {
160
+ name: 'sessions.listEvents',
161
+ method: 'GET',
162
+ path: `/v1/sessions/${pathSegment(id)}/events`,
163
+ status: 200,
164
+ retry: 'safe',
165
+ parse: (value) => decodeEvents(value, id),
166
+ },
167
+ options,
168
+ );
169
+ }
170
+ retrieveSurface(
171
+ id: string,
172
+ revision: number,
173
+ options?: RequestOptions,
174
+ ): Promise<ApiResult<SurfaceRevision>> {
175
+ boundedNumber(revision, 0, 'revision');
176
+ return this.#transport.request(
177
+ {
178
+ name: 'sessions.retrieveSurface',
179
+ method: 'GET',
180
+ path: `/v1/sessions/${pathSegment(id)}/surfaces/${revision}`,
181
+ status: 200,
182
+ retry: 'safe',
183
+ parse: (value) => decodeSurface(value, id, revision),
184
+ },
185
+ options,
186
+ );
187
+ }
188
+ listDeliveries(id: string, options?: RequestOptions): Promise<ApiResult<Deliveries>> {
189
+ return this.#transport.request(
190
+ {
191
+ name: 'sessions.listDeliveries',
192
+ method: 'GET',
193
+ path: `/v1/sessions/${pathSegment(id)}/deliveries`,
194
+ status: 200,
195
+ retry: 'safe',
196
+ parse: (value) => decodeDeliveries(value, id),
197
+ },
198
+ options,
199
+ );
200
+ }
201
+ redeliverEvent(
202
+ id: string,
203
+ eventId: string,
204
+ options?: RequestOptions,
205
+ ): Promise<ApiResult<RedeliverResponse>> {
206
+ return this.#transport.request(
207
+ {
208
+ name: 'sessions.redeliverEvent',
209
+ method: 'POST',
210
+ path: `/v1/sessions/${pathSegment(id)}/events/${pathSegment(eventId)}/redeliver`,
211
+ status: 202,
212
+ retry: 'never',
213
+ parse: (value) => decodeRedelivery(value, eventId),
214
+ },
215
+ options,
216
+ );
217
+ }
218
+ /** Read-only, restartable wait for exactly one immutable revision. */
219
+ waitForResponse(id: string, options: WaitOptions): Promise<WaitResult> {
220
+ return waitForResponse(
221
+ (requestOptions) => this.retrieve(id, requestOptions),
222
+ id,
223
+ options,
224
+ this.#transport.operationTimeoutMs,
225
+ );
226
+ }
227
+ }