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

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 (65) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +27 -0
  4. package/README.md +327 -2
  5. package/dist/ask.d.ts +161 -0
  6. package/dist/ask.js +499 -0
  7. package/dist/cli/main.d.ts +2 -0
  8. package/dist/cli/main.js +7 -0
  9. package/dist/cli/verify.d.ts +13 -0
  10. package/dist/cli/verify.js +322 -0
  11. package/dist/client.d.ts +19 -0
  12. package/dist/client.js +43 -0
  13. package/dist/commerce/builders.d.ts +99 -0
  14. package/dist/commerce/builders.js +208 -0
  15. package/dist/commerce/currency.d.ts +4 -0
  16. package/dist/commerce/currency.js +25 -0
  17. package/dist/commerce/items.d.ts +119 -0
  18. package/dist/commerce/items.js +280 -0
  19. package/dist/commerce/lint.d.ts +16 -0
  20. package/dist/commerce/lint.js +56 -0
  21. package/dist/errors.d.ts +61 -0
  22. package/dist/errors.js +63 -0
  23. package/dist/generated/openapi.d.ts +8360 -0
  24. package/dist/generated/openapi.js +1 -0
  25. package/dist/index.d.ts +11 -0
  26. package/dist/index.js +6 -0
  27. package/dist/internal/decode.d.ts +20 -0
  28. package/dist/internal/decode.js +380 -0
  29. package/dist/internal/json.d.ts +3 -0
  30. package/dist/internal/json.js +74 -0
  31. package/dist/internal/time.d.ts +10 -0
  32. package/dist/internal/time.js +70 -0
  33. package/dist/internal/version.d.ts +2 -0
  34. package/dist/internal/version.js +2 -0
  35. package/dist/polling.d.ts +11 -0
  36. package/dist/polling.js +137 -0
  37. package/dist/qr/encoder.d.ts +10 -0
  38. package/dist/qr/encoder.js +343 -0
  39. package/dist/qr/index.d.ts +55 -0
  40. package/dist/qr/index.js +150 -0
  41. package/dist/receipts/bundle.d.ts +123 -0
  42. package/dist/receipts/bundle.js +423 -0
  43. package/dist/receipts/index.d.ts +8 -0
  44. package/dist/receipts/index.js +3 -0
  45. package/dist/receipts/json.d.ts +21 -0
  46. package/dist/receipts/json.js +151 -0
  47. package/dist/receipts/key-cache.d.ts +27 -0
  48. package/dist/receipts/key-cache.js +109 -0
  49. package/dist/receipts/renderers.d.ts +57 -0
  50. package/dist/receipts/renderers.js +153 -0
  51. package/dist/receipts/resource.d.ts +38 -0
  52. package/dist/receipts/resource.js +145 -0
  53. package/dist/receipts/verify.d.ts +112 -0
  54. package/dist/receipts/verify.js +339 -0
  55. package/dist/sessions.d.ts +18 -0
  56. package/dist/sessions.js +151 -0
  57. package/dist/transport.d.ts +30 -0
  58. package/dist/transport.js +511 -0
  59. package/dist/types.d.ts +283 -0
  60. package/dist/types.js +8 -0
  61. package/dist/webhook-resource.d.ts +12 -0
  62. package/dist/webhook-resource.js +51 -0
  63. package/dist/webhooks/index.d.ts +21 -0
  64. package/dist/webhooks/index.js +183 -0
  65. package/package.json +82 -4
@@ -0,0 +1,109 @@
1
+ import { SessError } from '../errors.js';
2
+ import { abortError, verificationError, waitWithSignal } from './json.js';
3
+ import { validateKeySet } from './verify.js';
4
+ /** One bounded, issuer/source-scoped cache per client; no global `kid` cache. */
5
+ export class ReceiptKeyCache {
6
+ #issuer;
7
+ #keySource;
8
+ #load;
9
+ #ttl;
10
+ #cooldown;
11
+ #requestTimeout;
12
+ #keys;
13
+ #loadedAt = 0;
14
+ #attemptedAt = -Infinity;
15
+ #lastFailure;
16
+ #flight;
17
+ constructor(options) {
18
+ this.#issuer = options.issuer;
19
+ this.#keySource = options.keySource;
20
+ this.#load = options.load;
21
+ this.#ttl = options.ttlMs ?? 5 * 60_000;
22
+ this.#cooldown = options.refreshCooldownMs ?? 10_000;
23
+ this.#requestTimeout = options.requestTimeoutMs ?? 5_000;
24
+ if (!this.#issuer ||
25
+ !this.#keySource ||
26
+ typeof this.#load !== 'function' ||
27
+ !Number.isFinite(this.#ttl) ||
28
+ this.#ttl < 1 ||
29
+ this.#ttl > 5 * 60_000 ||
30
+ !Number.isFinite(this.#cooldown) ||
31
+ this.#cooldown < 1 ||
32
+ this.#cooldown > 60_000 ||
33
+ !Number.isFinite(this.#requestTimeout) ||
34
+ this.#requestTimeout < 1 ||
35
+ this.#requestTimeout > 10_000) {
36
+ throw new SessError('configuration', 'Invalid receipt key-cache configuration.');
37
+ }
38
+ }
39
+ async resolve(context) {
40
+ if (context.issuer !== this.#issuer) {
41
+ throw verificationError('ISSUER_MISMATCH', 'The key cache belongs to a different trusted issuer.');
42
+ }
43
+ if (context.signal?.aborted)
44
+ throw abortError(context.signal);
45
+ const fresh = this.#keys !== undefined && Date.now() - this.#loadedAt < this.#ttl;
46
+ if (fresh && this.#keys?.keys.some((key) => key.kid === context.kid))
47
+ return this.#keys;
48
+ if (this.#flight)
49
+ return this.#join(this.#flight, context.signal);
50
+ // Every unknown key can trigger at most one shared refresh in this cooldown, including
51
+ // failures. Cold-start misses use the initial fetch, never an immediate redundant fetch.
52
+ if (Date.now() - this.#attemptedAt < this.#cooldown) {
53
+ if (fresh && this.#keys)
54
+ return this.#keys;
55
+ if (this.#lastFailure instanceof SessError)
56
+ throw this.#lastFailure;
57
+ throw verificationError('KEY_FETCH_COOLDOWN', 'Receipt-key refresh is cooling down after a recent attempt.');
58
+ }
59
+ return this.#join(this.#start(context), context.signal);
60
+ }
61
+ #start(options) {
62
+ const controller = new AbortController();
63
+ this.#attemptedAt = Date.now();
64
+ const timer = setTimeout(() => controller.abort(new SessError('timeout', 'Receipt-key retrieval exceeded its deadline.')), this.#requestTimeout);
65
+ const flight = { controller, waiters: 0, promise: Promise.resolve({ keys: [] }) };
66
+ const load = Promise.resolve().then(() => this.#load({
67
+ signal: controller.signal,
68
+ operationTimeoutMs: this.#requestTimeout,
69
+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
70
+ ...(options.maxRetries !== undefined ? { maxRetries: options.maxRetries } : {}),
71
+ }));
72
+ flight.promise = waitWithSignal(load, controller.signal)
73
+ .then((raw) => {
74
+ const keys = validateKeySet(raw);
75
+ this.#keys = keys;
76
+ this.#loadedAt = Date.now();
77
+ this.#lastFailure = undefined;
78
+ return keys;
79
+ })
80
+ .catch((error) => {
81
+ if (this.#flight === flight)
82
+ this.#lastFailure = error;
83
+ throw error;
84
+ })
85
+ .finally(() => {
86
+ clearTimeout(timer);
87
+ if (this.#flight === flight)
88
+ this.#flight = undefined;
89
+ });
90
+ this.#flight = flight;
91
+ return flight;
92
+ }
93
+ async #join(flight, signal) {
94
+ flight.waiters += 1;
95
+ try {
96
+ return await waitWithSignal(flight.promise, signal);
97
+ }
98
+ finally {
99
+ flight.waiters -= 1;
100
+ // One cancelled caller must not cancel another caller's shared fetch. When everyone
101
+ // leaves, release the underlying transport and its timer promptly.
102
+ if (flight.waiters === 0 && this.#flight === flight) {
103
+ this.#flight = undefined;
104
+ this.#attemptedAt = -Infinity;
105
+ flight.controller.abort(new SessError('aborted', 'Receipt-key retrieval has no remaining waiters.'));
106
+ }
107
+ }
108
+ }
109
+ }
@@ -0,0 +1,57 @@
1
+ import type { ReceiptPublicKey } from './verify.js';
2
+ /** One listed identity and the UTC date it was added. */
3
+ export interface RendererIdentity {
4
+ renderer_version: string;
5
+ since: string;
6
+ }
7
+ /** A verified list: its edition, when that copy was signed, and its identities in order. */
8
+ export interface RendererList {
9
+ seq: number;
10
+ iat: number;
11
+ identities: readonly RendererIdentity[];
12
+ }
13
+ /**
14
+ * The issuer's list as published when this SDK was released (edition 1). Its identities are
15
+ * always accepted for their issuer's receipts; a fetched or supplied list is cross-checked
16
+ * against it.
17
+ */
18
+ export declare const BUNDLED_RENDERER_LIST: Readonly<{
19
+ seq: number;
20
+ identities: readonly RendererIdentity[];
21
+ }>;
22
+ /** The identities known when this SDK was released; always accepted for their issuer's receipts. */
23
+ export declare const BUNDLED_RENDERER_IDENTITIES: readonly string[];
24
+ /** Where an issuer publishes its signed list (application/json). */
25
+ export declare const RENDERER_IDENTITIES_PATH = "/.well-known/sess-renderer-identities.json";
26
+ export declare const MAX_RENDERER_IDENTITIES_BYTES: number;
27
+ /** The published document: the signed list, as a flattened JWS JSON serialization. */
28
+ export interface RendererIdentitiesDocument {
29
+ protected: string;
30
+ payload: string;
31
+ signature: string;
32
+ }
33
+ /**
34
+ * Verifies a signed renderer-identity list under the issuer's trusted keys. `keyFor` resolves the
35
+ * list's kid to a trusted public key (undefined: not trusted). Returns the verified edition: its
36
+ * seq, its iat and its identities, in order. It must agree with the bundled list
37
+ * (newerRendererList), or it is refused.
38
+ */
39
+ export declare function verifyRendererList(document: unknown, context: {
40
+ issuer: string;
41
+ keyFor: (kid: string) => Promise<ReceiptPublicKey | undefined>;
42
+ signal?: AbortSignal;
43
+ }): Promise<RendererList>;
44
+ /**
45
+ * Of two authentic lists of one issuer, the newer edition (the higher seq; for one seq, either:
46
+ * they list the same identities). Containment is the cross-check: the newer list must begin with
47
+ * every identity of the older, in order and with the same dates, and two lists of one seq must
48
+ * list the same identities. Lists that disagree are refused with INVALID_RENDERER_LIST, never
49
+ * merged.
50
+ */
51
+ export declare function newerRendererList<A extends {
52
+ seq: number;
53
+ identities: readonly RendererIdentity[];
54
+ }, B extends {
55
+ seq: number;
56
+ identities: readonly RendererIdentity[];
57
+ }>(a: A, b: B): A | B;
@@ -0,0 +1,153 @@
1
+ // Decision 0009 Amendment 13: the renderer identities a receipt's `surface.renderer_version` may
2
+ // name. A receipt verifies when its identity is one this release bundles, or is on a list signed
3
+ // with the issuer's trusted receipt keys, so a future Sess page change needs no SDK update.
4
+ //
5
+ // The issuer publishes the list at `<issuer>/.well-known/sess-renderer-identities.json`
6
+ // (receipt-v1 §10, docs/spec/receipt-v1.md in this repository): one JWS in the RFC 7515 flattened JSON serialization
7
+ // {"protected", "payload", "signature"}, protected header {"alg": "EdDSA", "kid",
8
+ // "typ": "sess-renderer-identities+jwt"}, payload the RFC 8785 canonical JSON
9
+ // {"iat", "identities": [{"renderer_version", "since"}, …], "iss", "seq",
10
+ // "sess_renderer_identities": 1}. `seq` is the list's edition (higher in every later published
11
+ // edition; a copy re-signed unchanged keeps it) and `iat` when that copy was signed (NumericDate);
12
+ // the signature covers both. The list only grows; a list is trusted only through its signature,
13
+ // never because it was supplied beside a receipt. Authentic lists are ordered by `seq`, with
14
+ // containment as the cross-check (newerRendererList); an older list proves the identities it
15
+ // holds and never their absence.
16
+ import { compactVerify, importJWK } from 'jose';
17
+ import { abortError, canonicalJson, exactKeys, isRecord, snapshotJson, verificationError, waitWithSignal, } from './json.js';
18
+ /**
19
+ * The issuer's list as published when this SDK was released (edition 1). Its identities are
20
+ * always accepted for their issuer's receipts; a fetched or supplied list is cross-checked
21
+ * against it.
22
+ */
23
+ export const BUNDLED_RENDERER_LIST = Object.freeze({
24
+ seq: 1,
25
+ identities: Object.freeze([
26
+ Object.freeze({ renderer_version: 'sess-html-form-1', since: '2026-10-09' }),
27
+ Object.freeze({ renderer_version: 'sess-html-form-2', since: '2026-10-18' }),
28
+ ]),
29
+ });
30
+ /** The identities known when this SDK was released; always accepted for their issuer's receipts. */
31
+ export const BUNDLED_RENDERER_IDENTITIES = Object.freeze(BUNDLED_RENDERER_LIST.identities.map((i) => i.renderer_version));
32
+ /** Where an issuer publishes its signed list (application/json). */
33
+ export const RENDERER_IDENTITIES_PATH = '/.well-known/sess-renderer-identities.json';
34
+ export const MAX_RENDERER_IDENTITIES_BYTES = 64 * 1024;
35
+ const PART = /^[A-Za-z0-9_-]+$/;
36
+ const KID = /^[A-Za-z0-9._-]{1,64}$/;
37
+ const IDENTITY = /^[a-z0-9][a-z0-9.-]{0,63}$/;
38
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
39
+ const TYP = 'sess-renderer-identities+jwt';
40
+ const invalid = (message) => verificationError('INVALID_RENDERER_LIST', message);
41
+ function decode(segment) {
42
+ const bytes = Buffer.from(segment, 'base64url');
43
+ if (bytes.toString('base64url') !== segment)
44
+ throw invalid('The renderer list is not canonical base64url.');
45
+ try {
46
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
47
+ }
48
+ catch {
49
+ throw invalid('The renderer list does not contain valid UTF-8 JSON.');
50
+ }
51
+ }
52
+ function json(text) {
53
+ try {
54
+ return JSON.parse(text);
55
+ }
56
+ catch {
57
+ throw invalid('The renderer list is not JSON.');
58
+ }
59
+ }
60
+ /**
61
+ * Verifies a signed renderer-identity list under the issuer's trusted keys. `keyFor` resolves the
62
+ * list's kid to a trusted public key (undefined: not trusted). Returns the verified edition: its
63
+ * seq, its iat and its identities, in order. It must agree with the bundled list
64
+ * (newerRendererList), or it is refused.
65
+ */
66
+ export async function verifyRendererList(document, context) {
67
+ const value = snapshotJson(document);
68
+ if (!isRecord(value) ||
69
+ !exactKeys(value, ['protected', 'payload', 'signature']) ||
70
+ ![value.protected, value.payload, value.signature].every((p) => typeof p === 'string' && PART.test(p)) ||
71
+ Buffer.byteLength(canonicalJson(value), 'utf8') > MAX_RENDERER_IDENTITIES_BYTES) {
72
+ throw invalid('The renderer list is not a signed renderer-identity document.');
73
+ }
74
+ const { protected: protectedHeader, payload, signature } = value;
75
+ const header = json(decode(protectedHeader));
76
+ if (!isRecord(header) ||
77
+ !exactKeys(header, ['alg', 'kid', 'typ']) ||
78
+ header.alg !== 'EdDSA' ||
79
+ header.typ !== TYP ||
80
+ typeof header.kid !== 'string' ||
81
+ !KID.test(header.kid)) {
82
+ throw invalid('The renderer list has an unsupported protected header.');
83
+ }
84
+ const signal = context.signal;
85
+ const publicKey = await context.keyFor(header.kid);
86
+ if (!publicKey)
87
+ throw invalid('The renderer list is not signed with a trusted key.');
88
+ try {
89
+ const key = await waitWithSignal(importJWK({ ...publicKey, key_ops: ['verify'], ext: false }, 'EdDSA'), signal);
90
+ await waitWithSignal(compactVerify(`${protectedHeader}.${payload}.${signature}`, key, { algorithms: ['EdDSA'] }), signal);
91
+ }
92
+ catch {
93
+ if (signal?.aborted)
94
+ throw abortError(signal);
95
+ throw invalid('The renderer list signature did not verify with the trusted key.');
96
+ }
97
+ const text = decode(payload);
98
+ const claims = json(text);
99
+ if (canonicalJson(claims) !== text)
100
+ throw invalid('The renderer list payload is not canonical JSON.');
101
+ if (!isRecord(claims) ||
102
+ !exactKeys(claims, ['iat', 'identities', 'iss', 'seq', 'sess_renderer_identities']) ||
103
+ claims.sess_renderer_identities !== 1 ||
104
+ !positiveInteger(claims.seq) ||
105
+ !positiveInteger(claims.iat) ||
106
+ !Array.isArray(claims.identities) ||
107
+ claims.identities.length === 0) {
108
+ throw invalid('The renderer list payload has an unsupported shape.');
109
+ }
110
+ if (claims.iss !== context.issuer)
111
+ throw invalid('The renderer list is from another issuer.');
112
+ const seen = new Set();
113
+ for (const item of claims.identities) {
114
+ if (!isRecord(item) ||
115
+ !exactKeys(item, ['renderer_version', 'since']) ||
116
+ typeof item.renderer_version !== 'string' ||
117
+ !IDENTITY.test(item.renderer_version) ||
118
+ seen.has(item.renderer_version) ||
119
+ typeof item.since !== 'string' ||
120
+ !DAY.test(item.since) ||
121
+ !Number.isFinite(Date.parse(`${item.since}T00:00:00Z`)) ||
122
+ new Date(`${item.since}T00:00:00Z`).toISOString().slice(0, 10) !== item.since) {
123
+ throw invalid('The renderer list has a malformed or repeated identity.');
124
+ }
125
+ seen.add(item.renderer_version);
126
+ }
127
+ const list = Object.freeze({
128
+ seq: claims.seq,
129
+ iat: claims.iat,
130
+ identities: Object.freeze(claims.identities.map((i) => Object.freeze({ renderer_version: i.renderer_version, since: i.since }))),
131
+ });
132
+ // An authentic list that disagrees with the edition this release bundles is refused.
133
+ newerRendererList(BUNDLED_RENDERER_LIST, list);
134
+ return list;
135
+ }
136
+ const positiveInteger = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 1;
137
+ /**
138
+ * Of two authentic lists of one issuer, the newer edition (the higher seq; for one seq, either:
139
+ * they list the same identities). Containment is the cross-check: the newer list must begin with
140
+ * every identity of the older, in order and with the same dates, and two lists of one seq must
141
+ * list the same identities. Lists that disagree are refused with INVALID_RENDERER_LIST, never
142
+ * merged.
143
+ */
144
+ export function newerRendererList(a, b) {
145
+ const [older, newer] = b.seq < a.seq ? [b, a] : [a, b];
146
+ const prefix = newer.identities.length >= older.identities.length &&
147
+ older.identities.every((o, i) => newer.identities[i]?.renderer_version === o.renderer_version &&
148
+ newer.identities[i]?.since === o.since);
149
+ if (!prefix || (older.seq === newer.seq && newer.identities.length !== older.identities.length)) {
150
+ throw invalid('The renderer lists disagree.');
151
+ }
152
+ return newer;
153
+ }
@@ -0,0 +1,38 @@
1
+ import type { AcceptedResponse, ApiResult, InteractiveSurfaceRevision, Session, SurfaceRevision, VersionedResult } from '../types.js';
2
+ import { type DeepReadonly } from './json.js';
3
+ import { type ReceiptClaims } from './verify.js';
4
+ export interface VerificationRequestOptions {
5
+ signal?: AbortSignal;
6
+ operationTimeoutMs?: number;
7
+ timeoutMs?: number;
8
+ maxRetries?: number;
9
+ }
10
+ interface Context {
11
+ receiptIssuer: string;
12
+ expectedWorkspaceId?: string;
13
+ operationTimeoutMs: number;
14
+ /** Stable configured API origin, used only to identify this trusted key source. */
15
+ baseUrl?: string;
16
+ retrieveSession: (id: string, options: VerificationRequestOptions) => Promise<VersionedResult<Session>>;
17
+ retrieveSurface: (id: string, revision: number, options: VerificationRequestOptions) => Promise<ApiResult<SurfaceRevision>>;
18
+ publicGet: (path: string, options: VerificationRequestOptions & {
19
+ maxResponseBytes: number;
20
+ }) => Promise<ApiResult<unknown>>;
21
+ }
22
+ export interface VerifyResponseInput {
23
+ sessionId: string;
24
+ response: AcceptedResponse;
25
+ expectedWorkspaceId?: string;
26
+ }
27
+ export interface VerifiedResponse {
28
+ claims: DeepReadonly<ReceiptClaims>;
29
+ response: DeepReadonly<AcceptedResponse>;
30
+ surface: DeepReadonly<InteractiveSurfaceRevision>;
31
+ }
32
+ export interface ReceiptResource {
33
+ /** Full receipt verification with authorized current context and exact immutable revision. */
34
+ verifyResponse(input: VerifyResponseInput, options?: VerificationRequestOptions): Promise<DeepReadonly<VerifiedResponse>>;
35
+ }
36
+ /** Internal bridge: all HTTP is supplied by the client's ordinary bounded transport. */
37
+ export declare function createReceiptResource(context: Context): ReceiptResource;
38
+ export {};
@@ -0,0 +1,145 @@
1
+ import { SessError } from '../errors.js';
2
+ import { isInteractiveSurface } from '../types.js';
3
+ import { ReceiptKeyCache } from './key-cache.js';
4
+ import { abortError, canonicalJson, deepFreeze, snapshotJson, verificationError, waitWithSignal, } from './json.js';
5
+ import { BUNDLED_RENDERER_IDENTITIES, MAX_RENDERER_IDENTITIES_BYTES, RENDERER_IDENTITIES_PATH, } from './renderers.js';
6
+ import { MAX_RECEIPT_KEY_SET_BYTES, verifyDecisionReceipt } from './verify.js';
7
+ /**
8
+ * The renderer identity a receipt names, read without trusting it: only to decide whether the
9
+ * issuer's signed list is needed (the verifier decides). Undefined when it cannot be read.
10
+ */
11
+ function namedRenderer(receipt) {
12
+ try {
13
+ const claims = JSON.parse(Buffer.from(receipt.split('.')[1] ?? '', 'base64url').toString('utf8'));
14
+ const surface = claims?.surface;
15
+ return typeof surface?.renderer_version === 'string' ? surface.renderer_version : undefined;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ /** Internal bridge: all HTTP is supplied by the client's ordinary bounded transport. */
22
+ export function createReceiptResource(context) {
23
+ // Copy configuration/callbacks; mutation of an application-owned config object has no effect.
24
+ const issuer = context.receiptIssuer;
25
+ const configuredWorkspace = context.expectedWorkspaceId;
26
+ const defaultBudget = context.operationTimeoutMs;
27
+ const retrieve = context.retrieveSession;
28
+ const surfaceRead = context.retrieveSurface;
29
+ const publicGet = context.publicGet;
30
+ const keyPath = '/.well-known/sess-receipt-keys.json';
31
+ const cache = new ReceiptKeyCache({
32
+ issuer,
33
+ keySource: `${context.baseUrl ?? 'configured-api-origin'}${keyPath}`,
34
+ load: async (options) => (await publicGet(keyPath, { ...options, maxResponseBytes: MAX_RECEIPT_KEY_SET_BYTES })).data,
35
+ });
36
+ return Object.freeze({
37
+ async verifyResponse(input, options = {}) {
38
+ const sessionId = input.sessionId;
39
+ const response = snapshotJson(input.response);
40
+ const requestedWorkspace = input.expectedWorkspaceId;
41
+ const timeoutMs = options.timeoutMs;
42
+ const maxRetries = options.maxRetries;
43
+ const originalSignal = options.signal;
44
+ const budget = options.operationTimeoutMs ?? defaultBudget;
45
+ if (!Number.isSafeInteger(budget) || budget <= 0 || budget > 2_147_483_647) {
46
+ throw new SessError('configuration', 'Receipt verification requires a finite positive operation timeout.');
47
+ }
48
+ if (!response || response.receipt === null) {
49
+ throw verificationError('LEGACY_RECEIPT_UNAVAILABLE', 'This accepted response has no verifiable receipt.');
50
+ }
51
+ if (requestedWorkspace && configuredWorkspace && requestedWorkspace !== configuredWorkspace) {
52
+ throw verificationError('AUDIENCE_MISMATCH', 'The supplied workspace differs from this client’s trusted workspace.');
53
+ }
54
+ if (originalSignal?.aborted)
55
+ throw abortError(originalSignal);
56
+ const controller = new AbortController();
57
+ const abort = () => controller.abort(originalSignal?.reason);
58
+ originalSignal?.addEventListener('abort', abort, { once: true });
59
+ const started = performance.now();
60
+ const timer = setTimeout(() => controller.abort(new SessError('timeout', 'Receipt verification exceeded its overall deadline.')), budget);
61
+ const requestOptions = () => {
62
+ if (controller.signal.aborted)
63
+ throw abortError(controller.signal);
64
+ const remaining = Math.floor(budget - (performance.now() - started));
65
+ if (remaining <= 0) {
66
+ controller.abort(new SessError('timeout', 'Receipt verification exceeded its overall deadline.'));
67
+ throw abortError(controller.signal);
68
+ }
69
+ return {
70
+ signal: controller.signal,
71
+ operationTimeoutMs: remaining,
72
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
73
+ ...(maxRetries !== undefined ? { maxRetries } : {}),
74
+ };
75
+ };
76
+ try {
77
+ const current = await waitWithSignal(retrieve(sessionId, requestOptions()), controller.signal);
78
+ // Copy at the read boundary; transport adapters must not be able to mutate verified data later.
79
+ const currentSnapshot = snapshotJson(current);
80
+ const trustedWorkspace = requestedWorkspace ?? configuredWorkspace ?? currentSnapshot.meta.workspaceId;
81
+ if (typeof trustedWorkspace !== 'string' || trustedWorkspace.length === 0) {
82
+ throw verificationError('VERIFICATION_CONTEXT_MISSING', 'Provide expectedWorkspaceId or use a runtime that returns authenticated Sess-Workspace-Id context.');
83
+ }
84
+ if (currentSnapshot.meta.workspaceId !== undefined &&
85
+ currentSnapshot.meta.workspaceId !== trustedWorkspace) {
86
+ throw verificationError('AUDIENCE_MISMATCH', 'The authorized resource belongs to a different workspace.');
87
+ }
88
+ if (currentSnapshot.data.id !== sessionId || !('responses' in currentSnapshot.data)) {
89
+ throw verificationError('RECORD_BINDING_MISMATCH', 'The authorized Session does not contain this accepted response.');
90
+ }
91
+ const retained = currentSnapshot.data.responses.filter((candidate) => candidate.event_id === response.event_id);
92
+ if (retained.length !== 1 || canonicalJson(retained[0]) !== canonicalJson(response)) {
93
+ throw verificationError('RECORD_BINDING_MISMATCH', 'The supplied response does not match the authorized accepted record.');
94
+ }
95
+ const retrievedSurface = await waitWithSignal(surfaceRead(sessionId, response.revision, requestOptions()), controller.signal);
96
+ const surface = snapshotJson(retrievedSurface.data);
97
+ if (surface.id !== sessionId || surface.revision !== response.revision) {
98
+ throw verificationError('RECORD_BINDING_MISMATCH', 'The retrieved Surface is not the requested immutable revision.');
99
+ }
100
+ if (!isInteractiveSurface(surface)) {
101
+ throw verificationError('RECORD_BINDING_MISMATCH', 'An accepted response requires an interactive immutable Surface.');
102
+ }
103
+ // Decision 0009 Amendment 13: a renderer identity this release does not bundle is
104
+ // accepted only on the issuer's signed list, fetched from the same API origin as the keys.
105
+ const renderer = namedRenderer(response.receipt);
106
+ let rendererIdentities;
107
+ if (renderer !== undefined && !BUNDLED_RENDERER_IDENTITIES.includes(renderer)) {
108
+ const listed = await waitWithSignal(publicGet(RENDERER_IDENTITIES_PATH, {
109
+ ...requestOptions(),
110
+ maxResponseBytes: MAX_RENDERER_IDENTITIES_BYTES,
111
+ }), controller.signal);
112
+ rendererIdentities = listed.data;
113
+ }
114
+ const claims = await verifyDecisionReceipt({
115
+ receipt: response.receipt,
116
+ ...(rendererIdentities !== undefined ? { rendererIdentities } : {}),
117
+ issuer,
118
+ audience: trustedWorkspace,
119
+ expected: {
120
+ sessionId,
121
+ eventId: response.event_id,
122
+ revision: response.revision,
123
+ actionId: response.action_id,
124
+ acceptedAt: response.accepted_at,
125
+ },
126
+ input: response.data,
127
+ interaction: surface.interaction,
128
+ keyResolver: (resolverContext) => cache.resolve({
129
+ ...resolverContext,
130
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
131
+ ...(maxRetries !== undefined ? { maxRetries } : {}),
132
+ }),
133
+ }, { signal: controller.signal });
134
+ if (response.actor.assurance !== 'link_holder') {
135
+ throw verificationError('ACTOR_BINDING_MISMATCH', 'The accepted response has an unsupported actor assurance.');
136
+ }
137
+ return deepFreeze({ claims, response, surface });
138
+ }
139
+ finally {
140
+ clearTimeout(timer);
141
+ originalSignal?.removeEventListener('abort', abort);
142
+ }
143
+ },
144
+ });
145
+ }
@@ -0,0 +1,112 @@
1
+ import type { InteractiveSurfaceRevision } from '../types.js';
2
+ import { type DeepReadonly } from './json.js';
3
+ import { type RendererIdentitiesDocument, type RendererList } from './renderers.js';
4
+ export declare const MAX_RECEIPT_BYTES: number;
5
+ export declare const MAX_RECEIPT_KEY_SET_BYTES: number;
6
+ /** Public Ed25519 verification material; private JWK parameters are refused. */
7
+ export interface ReceiptPublicKey {
8
+ kty: 'OKP';
9
+ crv: 'Ed25519';
10
+ x: string;
11
+ kid: string;
12
+ alg?: 'EdDSA';
13
+ use?: 'sig';
14
+ key_ops?: readonly 'verify'[];
15
+ ext?: boolean;
16
+ }
17
+ export interface ReceiptKeySet {
18
+ keys: readonly ReceiptPublicKey[];
19
+ }
20
+ /** A resolver is explicitly trusted application configuration, never JWT URL discovery. */
21
+ export type ReceiptKeyResolver = (context: {
22
+ readonly kid: string;
23
+ readonly issuer: string;
24
+ readonly signal?: AbortSignal;
25
+ }) => ReceiptKeySet | Promise<ReceiptKeySet>;
26
+ export interface ReceiptClaims {
27
+ sess_receipt: 1;
28
+ iss: string;
29
+ aud: string;
30
+ jti: string;
31
+ iat: number;
32
+ exp: number;
33
+ accepted_at: string;
34
+ workspace_id: string;
35
+ session_id: string;
36
+ step_id: string;
37
+ event_id: string;
38
+ /**
39
+ * `renderer_version`: the renderer identity the revision was shown under (Decision 0009
40
+ * Amendment 13): one this release bundles, or one on a list signed by the issuer's trusted keys.
41
+ */
42
+ surface: {
43
+ revision: number;
44
+ hash: string;
45
+ renderer_version: string;
46
+ };
47
+ action: {
48
+ id: string;
49
+ label: string;
50
+ summary: string;
51
+ };
52
+ input_hash: string;
53
+ actor: {
54
+ assurance: 'link_holder';
55
+ subject: string;
56
+ };
57
+ return_binding: {
58
+ recipient: string;
59
+ return_channel_id: null;
60
+ };
61
+ }
62
+ export interface VerifyDecisionReceiptInput {
63
+ receipt: string | null;
64
+ /** Trusted protocol identity, independently configured. */
65
+ issuer: string;
66
+ /** Trusted resource workspace, never read from an unverified receipt. */
67
+ audience: string;
68
+ expected: {
69
+ sessionId: string;
70
+ eventId: string;
71
+ revision: number;
72
+ actionId: string;
73
+ acceptedAt: string;
74
+ };
75
+ input: Record<string, unknown>;
76
+ /** The complete normalized `interaction` from the immutable Surface endpoint. */
77
+ interaction: InteractiveSurfaceRevision['interaction'];
78
+ keys?: ReceiptKeySet;
79
+ keyResolver?: ReceiptKeyResolver;
80
+ /**
81
+ * The issuer's signed renderer-identity list (`/.well-known/sess-renderer-identities.json`),
82
+ * needed only for a receipt whose renderer identity this release does not bundle. It is trusted
83
+ * only through its signature under the same trusted keys and issuer.
84
+ */
85
+ rendererIdentities?: RendererIdentitiesDocument;
86
+ }
87
+ export interface VerifyDecisionReceiptOptions {
88
+ /** An explicit verification instant, useful for deliberate archival verification/tests. */
89
+ now?: Date;
90
+ /** Issued-time tolerance only, 0–60 seconds. Expiry never receives a grace interval. */
91
+ issuedAtToleranceSeconds?: number;
92
+ signal?: AbortSignal;
93
+ }
94
+ /** Validates and copies the whole set, not merely the key selected by the token. */
95
+ export declare function validateKeySet(raw: unknown): ReceiptKeySet;
96
+ /**
97
+ * Fully verifies a version-1 receipt and its exact accepted record. Explicit keys make this
98
+ * function entirely offline. A valid receipt attests the accepted record, not business authority.
99
+ */
100
+ export declare function verifyDecisionReceipt(input: VerifyDecisionReceiptInput, options?: VerifyDecisionReceiptOptions): Promise<DeepReadonly<ReceiptClaims>>;
101
+ /**
102
+ * Verifies an issuer's signed renderer-identity list (Decision 0009 Amendment 13) under the keys
103
+ * you trust for that issuer: exactly one of `keys` or `keyResolver`. Offline with explicit keys.
104
+ * Returns the verified edition: `seq` (order lists by it; see newerRendererList), `iat` and the
105
+ * listed identities, in order.
106
+ */
107
+ export declare function verifyRendererIdentities(document: RendererIdentitiesDocument, context: {
108
+ issuer: string;
109
+ keys?: ReceiptKeySet;
110
+ keyResolver?: ReceiptKeyResolver;
111
+ signal?: AbortSignal;
112
+ }): Promise<RendererList>;