@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,168 @@
1
+ import canonicalize from 'canonicalize';
2
+ import { createHash } from 'node:crypto';
3
+ import { SessError } from '../errors.js';
4
+
5
+ /** JSON-shaped values returned by a verifier are copies, protected at every depth. */
6
+ export type DeepReadonly<T> = T extends readonly (infer U)[]
7
+ ? readonly DeepReadonly<U>[]
8
+ : T extends object
9
+ ? { readonly [P in keyof T]: DeepReadonly<T[P]> }
10
+ : T;
11
+
12
+ export function verificationError(code: string, message: string): SessError {
13
+ return new SessError('receipt_verification', message, { code });
14
+ }
15
+
16
+ export function isRecord(value: unknown): value is Record<string, unknown> {
17
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
18
+ }
19
+
20
+ export function wellFormedUnicode(value: string): boolean {
21
+ for (let index = 0; index < value.length; index += 1) {
22
+ const code = value.charCodeAt(index);
23
+ if (code >= 0xd800 && code <= 0xdbff) {
24
+ const next = value.charCodeAt(++index);
25
+ if (!(next >= 0xdc00 && next <= 0xdfff)) return false;
26
+ } else if (code >= 0xdc00 && code <= 0xdfff) return false;
27
+ }
28
+ return true;
29
+ }
30
+
31
+ export function exactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
32
+ return Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
33
+ }
34
+
35
+ /**
36
+ * Copy data without invoking accessors/toJSON or coercing non-JSON business values.
37
+ * This helper intentionally does not freeze data owned by the application.
38
+ */
39
+ export function snapshotJson<T>(input: T): T {
40
+ const ancestors = new Set<object>();
41
+ let remaining = 200_000;
42
+ const visit = (value: unknown, depth: number): unknown => {
43
+ if (--remaining < 0 || depth > 128) {
44
+ throw verificationError('INVALID_JSON', 'Verification data exceeds the supported JSON complexity.');
45
+ }
46
+ if (value === null || typeof value === 'boolean') return value;
47
+ if (typeof value === 'string') {
48
+ if (!wellFormedUnicode(value))
49
+ throw verificationError('INVALID_JSON', 'Verification data must contain well-formed Unicode.');
50
+ return value;
51
+ }
52
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
53
+ if (typeof value !== 'object' || value === null) {
54
+ throw verificationError('INVALID_JSON', 'Verification data must be JSON without coercion.');
55
+ }
56
+ if (ancestors.has(value) || Object.getOwnPropertySymbols(value).length !== 0) {
57
+ throw verificationError('INVALID_JSON', 'Verification data must be acyclic JSON.');
58
+ }
59
+ const array = Array.isArray(value);
60
+ const prototype = Object.getPrototypeOf(value);
61
+ if (array && prototype !== Array.prototype) {
62
+ throw verificationError('INVALID_JSON', 'Verification arrays must have ordinary JSON array semantics.');
63
+ }
64
+ if (!array && prototype !== Object.prototype && prototype !== null) {
65
+ throw verificationError('INVALID_JSON', 'Verification data must contain only plain JSON objects.');
66
+ }
67
+ ancestors.add(value);
68
+ try {
69
+ if (array) {
70
+ const descriptors = Object.getOwnPropertyDescriptors(value);
71
+ if (Object.keys(descriptors).some((key) => key !== 'length' && !/^(?:0|[1-9][0-9]*)$/.test(key))) {
72
+ throw verificationError('INVALID_JSON', 'Verification arrays cannot have named properties.');
73
+ }
74
+ return Array.from({ length: value.length }, (_, index) => {
75
+ const descriptor = descriptors[String(index)];
76
+ if (!descriptor || !('value' in descriptor)) {
77
+ throw verificationError(
78
+ 'INVALID_JSON',
79
+ 'Verification arrays cannot be sparse or contain accessors.',
80
+ );
81
+ }
82
+ return visit(descriptor.value, depth + 1);
83
+ });
84
+ }
85
+ const result: Record<string, unknown> = {};
86
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
87
+ if (!wellFormedUnicode(key) || !descriptor.enumerable || !('value' in descriptor)) {
88
+ throw verificationError(
89
+ 'INVALID_JSON',
90
+ 'Verification objects cannot contain accessors or hidden properties.',
91
+ );
92
+ }
93
+ Object.defineProperty(result, key, {
94
+ value: visit(descriptor.value, depth + 1),
95
+ enumerable: true,
96
+ configurable: true,
97
+ writable: true,
98
+ });
99
+ }
100
+ return result;
101
+ } finally {
102
+ ancestors.delete(value);
103
+ }
104
+ };
105
+ return visit(input, 0) as T;
106
+ }
107
+
108
+ export function deepFreeze<T>(value: T): DeepReadonly<T> {
109
+ if (value !== null && typeof value === 'object') {
110
+ for (const child of Object.values(value)) deepFreeze(child);
111
+ Object.freeze(value);
112
+ }
113
+ return value as DeepReadonly<T>;
114
+ }
115
+
116
+ export function canonicalJson(value: unknown): string {
117
+ try {
118
+ const result = canonicalize(value);
119
+ if (result !== undefined) return result;
120
+ } catch {
121
+ // Dependencies' exceptions may contain caller data; expose only a fixed explanation.
122
+ }
123
+ throw verificationError('INVALID_JSON', 'Verification data is not canonicalizable JSON.');
124
+ }
125
+
126
+ export function jsonDigest(value: unknown): string {
127
+ return `sha256:${createHash('sha256').update(canonicalJson(value), 'utf8').digest('hex')}`;
128
+ }
129
+
130
+ export function checkedInstant(value: unknown): number | undefined {
131
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value))
132
+ return undefined;
133
+ const millis = Date.parse(value);
134
+ return Number.isFinite(millis) && new Date(millis).toISOString() === value ? millis : undefined;
135
+ }
136
+
137
+ export function abortError(signal: AbortSignal): SessError {
138
+ return signal.reason instanceof SessError && signal.reason.kind === 'timeout'
139
+ ? new SessError('timeout', 'Verification exceeded its deadline.')
140
+ : new SessError('aborted', 'Verification was cancelled.');
141
+ }
142
+
143
+ /** Race a promise without cancelling shared work; always remove this waiter's listener. */
144
+ export async function waitWithSignal<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
145
+ if (!signal) return promise;
146
+ if (signal.aborted) {
147
+ void promise.catch(() => {});
148
+ throw abortError(signal);
149
+ }
150
+ return new Promise<T>((resolve, reject) => {
151
+ const aborted = () => {
152
+ cleanup();
153
+ reject(abortError(signal));
154
+ };
155
+ const cleanup = () => signal.removeEventListener('abort', aborted);
156
+ signal.addEventListener('abort', aborted, { once: true });
157
+ promise.then(
158
+ (result) => {
159
+ cleanup();
160
+ resolve(result);
161
+ },
162
+ (error: unknown) => {
163
+ cleanup();
164
+ reject(error);
165
+ },
166
+ );
167
+ });
168
+ }
@@ -0,0 +1,143 @@
1
+ import { SessError } from '../errors.js';
2
+ import { abortError, verificationError, waitWithSignal } from './json.js';
3
+ import { validateKeySet, type ReceiptKeySet } from './verify.js';
4
+
5
+ export interface ReceiptKeyCacheOptions {
6
+ issuer: string;
7
+ /** Identifies the configured trusted source. It is never derived from a receipt. */
8
+ keySource: string;
9
+ load: (options: {
10
+ signal: AbortSignal;
11
+ operationTimeoutMs: number;
12
+ timeoutMs?: number;
13
+ maxRetries?: number;
14
+ }) => Promise<unknown>;
15
+ ttlMs?: number;
16
+ refreshCooldownMs?: number;
17
+ requestTimeoutMs?: number;
18
+ }
19
+
20
+ interface Flight {
21
+ controller: AbortController;
22
+ promise: Promise<ReceiptKeySet>;
23
+ waiters: number;
24
+ }
25
+
26
+ /** One bounded, issuer/source-scoped cache per client; no global `kid` cache. */
27
+ export class ReceiptKeyCache {
28
+ readonly #issuer: string;
29
+ readonly #keySource: string;
30
+ readonly #load: ReceiptKeyCacheOptions['load'];
31
+ readonly #ttl: number;
32
+ readonly #cooldown: number;
33
+ readonly #requestTimeout: number;
34
+ #keys?: ReceiptKeySet;
35
+ #loadedAt = 0;
36
+ #attemptedAt = -Infinity;
37
+ #lastFailure?: unknown;
38
+ #flight?: Flight;
39
+
40
+ constructor(options: ReceiptKeyCacheOptions) {
41
+ this.#issuer = options.issuer;
42
+ this.#keySource = options.keySource;
43
+ this.#load = options.load;
44
+ this.#ttl = options.ttlMs ?? 5 * 60_000;
45
+ this.#cooldown = options.refreshCooldownMs ?? 10_000;
46
+ this.#requestTimeout = options.requestTimeoutMs ?? 5_000;
47
+ if (
48
+ !this.#issuer ||
49
+ !this.#keySource ||
50
+ typeof this.#load !== 'function' ||
51
+ !Number.isFinite(this.#ttl) ||
52
+ this.#ttl < 1 ||
53
+ this.#ttl > 5 * 60_000 ||
54
+ !Number.isFinite(this.#cooldown) ||
55
+ this.#cooldown < 1 ||
56
+ this.#cooldown > 60_000 ||
57
+ !Number.isFinite(this.#requestTimeout) ||
58
+ this.#requestTimeout < 1 ||
59
+ this.#requestTimeout > 10_000
60
+ ) {
61
+ throw new SessError('configuration', 'Invalid receipt key-cache configuration.');
62
+ }
63
+ }
64
+
65
+ async resolve(context: {
66
+ kid: string;
67
+ issuer: string;
68
+ signal?: AbortSignal;
69
+ timeoutMs?: number;
70
+ maxRetries?: number;
71
+ }): Promise<ReceiptKeySet> {
72
+ if (context.issuer !== this.#issuer) {
73
+ throw verificationError('ISSUER_MISMATCH', 'The key cache belongs to a different trusted issuer.');
74
+ }
75
+ if (context.signal?.aborted) throw abortError(context.signal);
76
+ const fresh = this.#keys !== undefined && Date.now() - this.#loadedAt < this.#ttl;
77
+ if (fresh && this.#keys?.keys.some((key) => key.kid === context.kid)) return this.#keys;
78
+ if (this.#flight) return this.#join(this.#flight, context.signal);
79
+ // Every unknown key can trigger at most one shared refresh in this cooldown, including
80
+ // failures. Cold-start misses use the initial fetch, never an immediate redundant fetch.
81
+ if (Date.now() - this.#attemptedAt < this.#cooldown) {
82
+ if (fresh && this.#keys) return this.#keys;
83
+ if (this.#lastFailure instanceof SessError) throw this.#lastFailure;
84
+ throw verificationError(
85
+ 'KEY_FETCH_COOLDOWN',
86
+ 'Receipt-key refresh is cooling down after a recent attempt.',
87
+ );
88
+ }
89
+ return this.#join(this.#start(context), context.signal);
90
+ }
91
+
92
+ #start(options: { timeoutMs?: number; maxRetries?: number }): Flight {
93
+ const controller = new AbortController();
94
+ this.#attemptedAt = Date.now();
95
+ const timer = setTimeout(
96
+ () => controller.abort(new SessError('timeout', 'Receipt-key retrieval exceeded its deadline.')),
97
+ this.#requestTimeout,
98
+ );
99
+ const flight: Flight = { controller, waiters: 0, promise: Promise.resolve({ keys: [] }) };
100
+ const load = Promise.resolve().then(() =>
101
+ this.#load({
102
+ signal: controller.signal,
103
+ operationTimeoutMs: this.#requestTimeout,
104
+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
105
+ ...(options.maxRetries !== undefined ? { maxRetries: options.maxRetries } : {}),
106
+ }),
107
+ );
108
+ flight.promise = waitWithSignal(load, controller.signal)
109
+ .then((raw) => {
110
+ const keys = validateKeySet(raw);
111
+ this.#keys = keys;
112
+ this.#loadedAt = Date.now();
113
+ this.#lastFailure = undefined;
114
+ return keys;
115
+ })
116
+ .catch((error: unknown) => {
117
+ if (this.#flight === flight) this.#lastFailure = error;
118
+ throw error;
119
+ })
120
+ .finally(() => {
121
+ clearTimeout(timer);
122
+ if (this.#flight === flight) this.#flight = undefined;
123
+ });
124
+ this.#flight = flight;
125
+ return flight;
126
+ }
127
+
128
+ async #join(flight: Flight, signal?: AbortSignal): Promise<ReceiptKeySet> {
129
+ flight.waiters += 1;
130
+ try {
131
+ return await waitWithSignal(flight.promise, signal);
132
+ } finally {
133
+ flight.waiters -= 1;
134
+ // One cancelled caller must not cancel another caller's shared fetch. When everyone
135
+ // leaves, release the underlying transport and its timer promptly.
136
+ if (flight.waiters === 0 && this.#flight === flight) {
137
+ this.#flight = undefined;
138
+ this.#attemptedAt = -Infinity;
139
+ flight.controller.abort(new SessError('aborted', 'Receipt-key retrieval has no remaining waiters.'));
140
+ }
141
+ }
142
+ }
143
+ }
@@ -0,0 +1,227 @@
1
+ import { SessError } from '../errors.js';
2
+ import { isInteractiveSurface } from '../types.js';
3
+ import type {
4
+ AcceptedResponse,
5
+ ApiResult,
6
+ InteractiveSurfaceRevision,
7
+ Session,
8
+ SurfaceRevision,
9
+ VersionedResult,
10
+ } from '../types.js';
11
+ import { ReceiptKeyCache } from './key-cache.js';
12
+ import {
13
+ abortError,
14
+ canonicalJson,
15
+ deepFreeze,
16
+ snapshotJson,
17
+ verificationError,
18
+ waitWithSignal,
19
+ type DeepReadonly,
20
+ } from './json.js';
21
+ import { MAX_RECEIPT_KEY_SET_BYTES, verifyDecisionReceipt, type ReceiptClaims } from './verify.js';
22
+
23
+ export interface VerificationRequestOptions {
24
+ signal?: AbortSignal;
25
+ operationTimeoutMs?: number;
26
+ timeoutMs?: number;
27
+ maxRetries?: number;
28
+ }
29
+
30
+ interface Context {
31
+ receiptIssuer: string;
32
+ expectedWorkspaceId?: string;
33
+ operationTimeoutMs: number;
34
+ /** Stable configured API origin, used only to identify this trusted key source. */
35
+ baseUrl?: string;
36
+ retrieveSession: (id: string, options: VerificationRequestOptions) => Promise<VersionedResult<Session>>;
37
+ retrieveSurface: (
38
+ id: string,
39
+ revision: number,
40
+ options: VerificationRequestOptions,
41
+ ) => Promise<ApiResult<SurfaceRevision>>;
42
+ publicGet: (
43
+ path: string,
44
+ options: VerificationRequestOptions & { maxResponseBytes: number },
45
+ ) => Promise<ApiResult<unknown>>;
46
+ }
47
+
48
+ export interface VerifyResponseInput {
49
+ sessionId: string;
50
+ response: AcceptedResponse;
51
+ expectedWorkspaceId?: string;
52
+ }
53
+
54
+ export interface VerifiedResponse {
55
+ claims: DeepReadonly<ReceiptClaims>;
56
+ response: DeepReadonly<AcceptedResponse>;
57
+ surface: DeepReadonly<InteractiveSurfaceRevision>;
58
+ }
59
+
60
+ export interface ReceiptResource {
61
+ /** Full receipt verification with authorized current context and exact immutable revision. */
62
+ verifyResponse(
63
+ input: VerifyResponseInput,
64
+ options?: VerificationRequestOptions,
65
+ ): Promise<DeepReadonly<VerifiedResponse>>;
66
+ }
67
+
68
+ /** Internal bridge: all HTTP is supplied by the client's ordinary bounded transport. */
69
+ export function createReceiptResource(context: Context): ReceiptResource {
70
+ // Copy configuration/callbacks; mutation of an application-owned config object has no effect.
71
+ const issuer = context.receiptIssuer;
72
+ const configuredWorkspace = context.expectedWorkspaceId;
73
+ const defaultBudget = context.operationTimeoutMs;
74
+ const retrieve = context.retrieveSession;
75
+ const surfaceRead = context.retrieveSurface;
76
+ const publicGet = context.publicGet;
77
+ const keyPath = '/.well-known/sess-receipt-keys.json';
78
+ const cache = new ReceiptKeyCache({
79
+ issuer,
80
+ keySource: `${context.baseUrl ?? 'configured-api-origin'}${keyPath}`,
81
+ load: async (options) =>
82
+ (await publicGet(keyPath, { ...options, maxResponseBytes: MAX_RECEIPT_KEY_SET_BYTES })).data,
83
+ });
84
+ return Object.freeze({
85
+ async verifyResponse(
86
+ input: VerifyResponseInput,
87
+ options: VerificationRequestOptions = {},
88
+ ): Promise<DeepReadonly<VerifiedResponse>> {
89
+ const sessionId = input.sessionId;
90
+ const response = snapshotJson(input.response);
91
+ const requestedWorkspace = input.expectedWorkspaceId;
92
+ const timeoutMs = options.timeoutMs;
93
+ const maxRetries = options.maxRetries;
94
+ const originalSignal = options.signal;
95
+ const budget = options.operationTimeoutMs ?? defaultBudget;
96
+ if (!Number.isSafeInteger(budget) || budget <= 0 || budget > 2_147_483_647) {
97
+ throw new SessError(
98
+ 'configuration',
99
+ 'Receipt verification requires a finite positive operation timeout.',
100
+ );
101
+ }
102
+ if (!response || response.receipt === null) {
103
+ throw verificationError(
104
+ 'LEGACY_RECEIPT_UNAVAILABLE',
105
+ 'This accepted response has no verifiable receipt.',
106
+ );
107
+ }
108
+ if (requestedWorkspace && configuredWorkspace && requestedWorkspace !== configuredWorkspace) {
109
+ throw verificationError(
110
+ 'AUDIENCE_MISMATCH',
111
+ 'The supplied workspace differs from this client’s trusted workspace.',
112
+ );
113
+ }
114
+ if (originalSignal?.aborted) throw abortError(originalSignal);
115
+ const controller = new AbortController();
116
+ const abort = () => controller.abort(originalSignal?.reason);
117
+ originalSignal?.addEventListener('abort', abort, { once: true });
118
+ const started = performance.now();
119
+ const timer = setTimeout(
120
+ () =>
121
+ controller.abort(new SessError('timeout', 'Receipt verification exceeded its overall deadline.')),
122
+ budget,
123
+ );
124
+ const requestOptions = (): VerificationRequestOptions => {
125
+ if (controller.signal.aborted) throw abortError(controller.signal);
126
+ const remaining = Math.floor(budget - (performance.now() - started));
127
+ if (remaining <= 0) {
128
+ controller.abort(new SessError('timeout', 'Receipt verification exceeded its overall deadline.'));
129
+ throw abortError(controller.signal);
130
+ }
131
+ return {
132
+ signal: controller.signal,
133
+ operationTimeoutMs: remaining,
134
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
135
+ ...(maxRetries !== undefined ? { maxRetries } : {}),
136
+ };
137
+ };
138
+ try {
139
+ const current = await waitWithSignal(retrieve(sessionId, requestOptions()), controller.signal);
140
+ // Copy at the read boundary; transport adapters must not be able to mutate verified data later.
141
+ const currentSnapshot = snapshotJson(current);
142
+ const trustedWorkspace =
143
+ requestedWorkspace ?? configuredWorkspace ?? currentSnapshot.meta.workspaceId;
144
+ if (typeof trustedWorkspace !== 'string' || trustedWorkspace.length === 0) {
145
+ throw verificationError(
146
+ 'VERIFICATION_CONTEXT_MISSING',
147
+ 'Provide expectedWorkspaceId or use a runtime that returns authenticated Sess-Workspace-Id context.',
148
+ );
149
+ }
150
+ if (
151
+ currentSnapshot.meta.workspaceId !== undefined &&
152
+ currentSnapshot.meta.workspaceId !== trustedWorkspace
153
+ ) {
154
+ throw verificationError(
155
+ 'AUDIENCE_MISMATCH',
156
+ 'The authorized resource belongs to a different workspace.',
157
+ );
158
+ }
159
+ if (currentSnapshot.data.id !== sessionId || !('responses' in currentSnapshot.data)) {
160
+ throw verificationError(
161
+ 'RECORD_BINDING_MISMATCH',
162
+ 'The authorized Session does not contain this accepted response.',
163
+ );
164
+ }
165
+ const retained = currentSnapshot.data.responses.filter(
166
+ (candidate) => candidate.event_id === response.event_id,
167
+ );
168
+ if (retained.length !== 1 || canonicalJson(retained[0]) !== canonicalJson(response)) {
169
+ throw verificationError(
170
+ 'RECORD_BINDING_MISMATCH',
171
+ 'The supplied response does not match the authorized accepted record.',
172
+ );
173
+ }
174
+ const retrievedSurface = await waitWithSignal(
175
+ surfaceRead(sessionId, response.revision, requestOptions()),
176
+ controller.signal,
177
+ );
178
+ const surface = snapshotJson(retrievedSurface.data);
179
+ if (surface.id !== sessionId || surface.revision !== response.revision) {
180
+ throw verificationError(
181
+ 'RECORD_BINDING_MISMATCH',
182
+ 'The retrieved Surface is not the requested immutable revision.',
183
+ );
184
+ }
185
+ if (!isInteractiveSurface(surface)) {
186
+ throw verificationError(
187
+ 'RECORD_BINDING_MISMATCH',
188
+ 'An accepted response requires an interactive immutable Surface.',
189
+ );
190
+ }
191
+ const claims = await verifyDecisionReceipt(
192
+ {
193
+ receipt: response.receipt,
194
+ issuer,
195
+ audience: trustedWorkspace,
196
+ expected: {
197
+ sessionId,
198
+ eventId: response.event_id,
199
+ revision: response.revision,
200
+ actionId: response.action_id,
201
+ acceptedAt: response.accepted_at,
202
+ },
203
+ input: response.data,
204
+ interaction: surface.interaction,
205
+ keyResolver: (resolverContext) =>
206
+ cache.resolve({
207
+ ...resolverContext,
208
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
209
+ ...(maxRetries !== undefined ? { maxRetries } : {}),
210
+ }),
211
+ },
212
+ { signal: controller.signal },
213
+ );
214
+ if (response.actor.assurance !== 'link_holder') {
215
+ throw verificationError(
216
+ 'ACTOR_BINDING_MISMATCH',
217
+ 'The accepted response has an unsupported actor assurance.',
218
+ );
219
+ }
220
+ return deepFreeze({ claims, response, surface });
221
+ } finally {
222
+ clearTimeout(timer);
223
+ originalSignal?.removeEventListener('abort', abort);
224
+ }
225
+ },
226
+ });
227
+ }