@sess.si/sdk 0.1.0-rc.7 → 0.1.0-rc.8

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 (57) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +41 -0
  3. package/dist/ask.d.ts +20 -8
  4. package/dist/ask.d.ts.map +1 -1
  5. package/dist/ask.js +43 -8
  6. package/dist/ask.js.map +1 -1
  7. package/dist/cli/verify.d.ts +1 -1
  8. package/dist/cli/verify.d.ts.map +1 -1
  9. package/dist/cli/verify.js +49 -3
  10. package/dist/cli/verify.js.map +1 -1
  11. package/dist/errors.d.ts +18 -0
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +22 -1
  14. package/dist/errors.js.map +1 -1
  15. package/dist/generated/openapi.d.ts +489 -42
  16. package/dist/generated/openapi.d.ts.map +1 -1
  17. package/dist/internal/decode.d.ts.map +1 -1
  18. package/dist/internal/decode.js +37 -0
  19. package/dist/internal/decode.js.map +1 -1
  20. package/dist/polling.d.ts +4 -3
  21. package/dist/polling.d.ts.map +1 -1
  22. package/dist/polling.js +64 -18
  23. package/dist/polling.js.map +1 -1
  24. package/dist/receipts/index.d.ts +3 -1
  25. package/dist/receipts/index.d.ts.map +1 -1
  26. package/dist/receipts/index.js +2 -1
  27. package/dist/receipts/index.js.map +1 -1
  28. package/dist/receipts/renderers.d.ts +58 -0
  29. package/dist/receipts/renderers.d.ts.map +1 -0
  30. package/dist/receipts/renderers.js +154 -0
  31. package/dist/receipts/renderers.js.map +1 -0
  32. package/dist/receipts/resource.d.ts.map +1 -1
  33. package/dist/receipts/resource.js +27 -0
  34. package/dist/receipts/resource.js.map +1 -1
  35. package/dist/receipts/verify.d.ts +24 -1
  36. package/dist/receipts/verify.d.ts.map +1 -1
  37. package/dist/receipts/verify.js +63 -17
  38. package/dist/receipts/verify.js.map +1 -1
  39. package/dist/transport.d.ts.map +1 -1
  40. package/dist/transport.js +27 -2
  41. package/dist/transport.js.map +1 -1
  42. package/dist/types.d.ts +76 -7
  43. package/dist/types.d.ts.map +1 -1
  44. package/dist/types.js.map +1 -1
  45. package/package.json +1 -1
  46. package/src/ask.ts +63 -16
  47. package/src/cli/verify.ts +61 -3
  48. package/src/errors.ts +31 -0
  49. package/src/generated/openapi.ts +489 -42
  50. package/src/internal/decode.ts +29 -0
  51. package/src/polling.ts +70 -18
  52. package/src/receipts/index.ts +3 -1
  53. package/src/receipts/renderers.ts +220 -0
  54. package/src/receipts/resource.ts +37 -0
  55. package/src/receipts/verify.ts +108 -22
  56. package/src/transport.ts +35 -2
  57. package/src/types.ts +75 -4
@@ -139,10 +139,36 @@ export function decodeCreate(value: unknown, allowInsecureLocalhost = false): Cr
139
139
  export function isLoopback(host: string): boolean {
140
140
  return host === 'localhost' || host === '[::1]' || /^127\.(?:\d{1,3}\.){2}\d{1,3}$/.test(host);
141
141
  }
142
+ /** One accepted extension of the Sess link (Decision 0009 Amendment 10), numbered in order. */
143
+ function linkExtension(value: unknown, number: number): void {
144
+ const v = object(value);
145
+ if (integer(v.number) !== number) protocol();
146
+ date(v.previous_action_expires_at);
147
+ date(v.action_expires_at);
148
+ if (typeof v.from_lapsed !== 'boolean') protocol();
149
+ date(v.extended_at);
150
+ }
151
+ /** The extension history: at most ten records, numbered 1, 2, … in order. */
152
+ function linkExtensions(value: unknown): void {
153
+ const items = array(value);
154
+ if (items.length > 10) protocol();
155
+ items.forEach((item, i) => linkExtension(item, i + 1));
156
+ }
157
+ /**
158
+ * A Session read's link timing (Decision 0009 Amendment 10), checked when present. A runtime
159
+ * before link timing omits it; the wait then keeps its earlier rule (the deadline is final).
160
+ */
161
+ function linkTiming(v: Record<string, unknown>): void {
162
+ if (v.link_state !== undefined) oneOf(v.link_state, ['live', 'lapsed', 'expired']);
163
+ if (v.action_expires_horizon !== undefined) nullableDate(v.action_expires_horizon);
164
+ if (v.extensions_used !== undefined && integer(v.extensions_used, 0) > 10) protocol();
165
+ if (v.extensions !== undefined) linkExtensions(v.extensions);
166
+ }
142
167
  export function decodeSession(value: unknown, expectedId: string): Session {
143
168
  const v = object(value);
144
169
  if (string(v.id, sessionPattern) !== expectedId) protocol();
145
170
  const rev = integer(v.revision);
171
+ linkTiming(v);
146
172
  const mode = object(v.interaction).mode;
147
173
  if (mode === 'display') {
148
174
  interaction(v.interaction, 'display');
@@ -210,6 +236,9 @@ export function decodeEvents(value: unknown, expectedId: string): SessionEvents
210
236
  receipt(e.receipt);
211
237
  } else if (actor !== 'owner') protocol();
212
238
  }
239
+ // Decision 0009 Amendment 10: the link's extensions are listed beside the Events (never as an
240
+ // Event type), only where the deployment enables them.
241
+ if (v.link_extensions !== undefined) linkExtensions(v.link_extensions);
213
242
  return value as SessionEvents;
214
243
  }
215
244
  function endpoint(value: unknown): void {
package/src/polling.ts CHANGED
@@ -11,23 +11,44 @@ import type {
11
11
  } from './types.js';
12
12
 
13
13
  /**
14
- * Once a Session's link has expired (`action_expires_at`), the wait reads it once more when the
15
- * runtime clock is this far past the expiry, then ends: an answer accepted before the expiry is
16
- * returned; otherwise the wait ends with `LINK_EXPIRED`. Two seconds covers the one-second
14
+ * Once a Session's link has reached its end (its deadline, `action_expires_at`, or while the
15
+ * person can still extend it, its horizon), the wait reads it once more when the runtime clock is
16
+ * this far past that end, then ends: an answer accepted before the end is returned; otherwise the
17
+ * wait ends with `LINK_EXPIRED`. Two seconds covers the one-second
17
18
  * resolution of the HTTP `Date` header plus an answer accepted just before the expiry whose write
18
19
  * is still landing, and keeps the end prompt.
19
20
  */
20
21
  export const LINK_EXPIRY_GRACE_MS = 2000;
21
22
 
22
- /** The Session's link expiry in milliseconds since the epoch, when it carries a valid one. */
23
- function linkExpiry(session: InteractiveSession): number | undefined {
24
- const value: unknown = (session as { action_expires_at?: unknown }).action_expires_at;
23
+ /** An RFC 3339 UTC instant in milliseconds since the epoch, when the value is a valid one. */
24
+ function instant(value: unknown): number | undefined {
25
25
  if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value))
26
26
  return undefined;
27
27
  const ms = Date.parse(value);
28
28
  return Number.isFinite(ms) ? ms : undefined;
29
29
  }
30
30
 
31
+ /**
32
+ * The link's state as read and the instant it ends for good as far as this read shows: its
33
+ * horizon while the person can still extend it (an extension left), else its deadline
34
+ * (`action_expires_at`). No state from a runtime before link timing (Decision 0009 Amendment 10).
35
+ */
36
+ function linkEnd(session: InteractiveSession): { state: string | undefined; endsAt: number | undefined } {
37
+ const v = session as {
38
+ action_expires_at?: unknown;
39
+ action_expires_horizon?: unknown;
40
+ extensions_used?: unknown;
41
+ link_state?: unknown;
42
+ };
43
+ const deadline = instant(v.action_expires_at);
44
+ const horizon = instant(v.action_expires_horizon);
45
+ const extendable = horizon !== undefined && typeof v.extensions_used === 'number' && v.extensions_used < 10;
46
+ return {
47
+ state: typeof v.link_state === 'string' ? v.link_state : undefined,
48
+ endsAt: extendable && deadline !== undefined ? Math.max(horizon, deadline) : deadline,
49
+ };
50
+ }
51
+
31
52
  export async function waitForResponse(
32
53
  retrieve: (options: RequestOptions) => Promise<VersionedResult<Session>>,
33
54
  id: string,
@@ -52,6 +73,13 @@ export async function waitForResponse(
52
73
  );
53
74
  const budget = deadline(timeoutMs, options.signal);
54
75
  const expires = performance.now() + timeoutMs;
76
+ /**
77
+ * The first read in a row that showed the link expired with no answer at an instant the clocks
78
+ * cannot place past its end: its runtime clock, that clock's resolution, and whether the clock
79
+ * was the runtime's (HTTP Date) or this machine's. Such a read is final only once a later one,
80
+ * at least LINK_EXPIRY_GRACE_MS (plus the resolution) after it on the same clock, still shows it.
81
+ */
82
+ let expiredSince: { at: number; resolutionMs: number; server: boolean } | undefined;
55
83
  const ended = (code: string, message: string) =>
56
84
  new SessError('wait_ended', message, { code, sessionId: id, revision });
57
85
  try {
@@ -79,23 +107,47 @@ export async function waitForResponse(
79
107
  );
80
108
  if (session.revision > revision)
81
109
  throw ended('REVISION_SUPERSEDED', 'The requested unanswered revision was superseded.');
82
- // The link's expiry (Decision 0009 Amendment 7): the runtime accepts no answer after
83
- // action_expires_at, and an answer accepted before it is in every later read. A read made
84
- // when the runtime clock was at least LINK_EXPIRY_GRACE_MS past the expiry, with no answer,
85
- // is final. The runtime clock is the response's HTTP Date (at or before the read), else
86
- // this machine's. Nothing is completed here.
110
+ // The link's end (Decision 0009 Amendments 7 and 10): an answer accepted while the link
111
+ // was live is in every later read. The runtime clock is the response's HTTP Date (at or
112
+ // before the read), else this machine's. Nothing is completed here.
113
+ // - live or lapsed: the Session is still open (a lapsed link takes no answer, but the
114
+ // person can still ask for more time until the horizon). The wait never ends on the
115
+ // link; it reads again soon after the link could end.
116
+ // - expired: final once a read made at least LINK_EXPIRY_GRACE_MS past the link's end, or a
117
+ // read at least the grace after the first expired read on the same clock (an end the
118
+ // clocks cannot place, such as a revocation), still shows it expired with no answer. A
119
+ // short polling interval reads again sooner but never ends the wait inside the grace.
120
+ // - no link_state (a runtime before link timing): the deadline is final, as before.
87
121
  let untilFinalReadMs = Number.POSITIVE_INFINITY;
88
- const cutoff = linkExpiry(session);
89
- if (cutoff !== undefined) {
90
- const observedAt = current.meta.serverDate ?? Date.now();
91
- const finalAt = cutoff + LINK_EXPIRY_GRACE_MS;
92
- if (observedAt >= finalAt)
122
+ const link = linkEnd(session);
123
+ const observedAt = current.meta.serverDate ?? Date.now();
124
+ // A Date header has whole seconds: one more second puts the next read past the instant.
125
+ const resolutionMs = current.meta.serverDate === undefined ? 0 : 1000;
126
+ const server = current.meta.serverDate !== undefined;
127
+ if (link.state !== 'expired' || (expiredSince !== undefined && expiredSince.server !== server))
128
+ expiredSince = undefined;
129
+ if (link.state === 'live' || link.state === 'lapsed') {
130
+ if (link.endsAt !== undefined && link.endsAt + LINK_EXPIRY_GRACE_MS > observedAt)
131
+ untilFinalReadMs = link.endsAt + LINK_EXPIRY_GRACE_MS - observedAt + resolutionMs;
132
+ } else if (link.state === 'expired' || link.endsAt !== undefined) {
133
+ const finalAt = (link.endsAt ?? observedAt) + LINK_EXPIRY_GRACE_MS;
134
+ // Whole-second Date headers: a full grace plus one second between the two headers puts
135
+ // more than the grace between the two reads.
136
+ const graceSeenAt =
137
+ expiredSince === undefined
138
+ ? Number.POSITIVE_INFINITY
139
+ : expiredSince.at + LINK_EXPIRY_GRACE_MS + expiredSince.resolutionMs;
140
+ if (observedAt >= finalAt || observedAt >= graceSeenAt)
93
141
  throw ended(
94
142
  'LINK_EXPIRED',
95
143
  'The Sess link expired with no accepted response for this revision. Nothing was completed.',
96
144
  );
97
- // A Date header has whole seconds: one more second puts the next read past finalAt.
98
- untilFinalReadMs = finalAt - observedAt + (current.meta.serverDate === undefined ? 0 : 1000);
145
+ untilFinalReadMs = finalAt - observedAt + resolutionMs;
146
+ if (link.state === 'expired') {
147
+ expiredSince ??= { at: observedAt, resolutionMs, server };
148
+ const graceEndsAt = expiredSince.at + LINK_EXPIRY_GRACE_MS + expiredSince.resolutionMs;
149
+ untilFinalReadMs = Math.min(untilFinalReadMs, Math.max(1, graceEndsAt - observedAt));
150
+ }
99
151
  }
100
152
  await delay(
101
153
  Math.min(
@@ -1,4 +1,6 @@
1
- export { verifyDecisionReceipt } from './verify.js';
1
+ export { verifyDecisionReceipt, verifyRendererIdentities } from './verify.js';
2
+ export { BUNDLED_RENDERER_IDENTITIES, BUNDLED_RENDERER_LIST, newerRendererList } from './renderers.js';
3
+ export type { RendererIdentitiesDocument, RendererIdentity, RendererList } from './renderers.js';
2
4
  export type {
3
5
  ReceiptClaims,
4
6
  ReceiptPublicKey,
@@ -0,0 +1,220 @@
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
+ // (DOCS/spec/receipt-v1.md §10): 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 {
18
+ abortError,
19
+ canonicalJson,
20
+ exactKeys,
21
+ isRecord,
22
+ snapshotJson,
23
+ verificationError,
24
+ waitWithSignal,
25
+ } from './json.js';
26
+ import type { ReceiptPublicKey } from './verify.js';
27
+
28
+ /** One listed identity and the UTC date it was added. */
29
+ export interface RendererIdentity {
30
+ renderer_version: string;
31
+ since: string;
32
+ }
33
+
34
+ /** A verified list: its edition, when that copy was signed, and its identities in order. */
35
+ export interface RendererList {
36
+ seq: number;
37
+ iat: number;
38
+ identities: readonly RendererIdentity[];
39
+ }
40
+
41
+ /**
42
+ * The issuer's list as published when this SDK was released (edition 1). Its identities are
43
+ * always accepted for their issuer's receipts; a fetched or supplied list is cross-checked
44
+ * against it.
45
+ */
46
+ export const BUNDLED_RENDERER_LIST: Readonly<{ seq: number; identities: readonly RendererIdentity[] }> =
47
+ Object.freeze({
48
+ seq: 1,
49
+ identities: Object.freeze([
50
+ Object.freeze({ renderer_version: 'sess-html-form-1', since: '2026-10-09' }),
51
+ Object.freeze({ renderer_version: 'sess-html-form-2', since: '2026-10-18' }),
52
+ ]),
53
+ });
54
+
55
+ /** The identities known when this SDK was released; always accepted for their issuer's receipts. */
56
+ export const BUNDLED_RENDERER_IDENTITIES: readonly string[] = Object.freeze(
57
+ BUNDLED_RENDERER_LIST.identities.map((i) => i.renderer_version),
58
+ );
59
+
60
+ /** Where an issuer publishes its signed list (application/json). */
61
+ export const RENDERER_IDENTITIES_PATH = '/.well-known/sess-renderer-identities.json';
62
+ export const MAX_RENDERER_IDENTITIES_BYTES = 64 * 1024;
63
+
64
+ /** The published document: the signed list, as a flattened JWS JSON serialization. */
65
+ export interface RendererIdentitiesDocument {
66
+ protected: string;
67
+ payload: string;
68
+ signature: string;
69
+ }
70
+
71
+ const PART = /^[A-Za-z0-9_-]+$/;
72
+ const KID = /^[A-Za-z0-9._-]{1,64}$/;
73
+ const IDENTITY = /^[a-z0-9][a-z0-9.-]{0,63}$/;
74
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
75
+ const TYP = 'sess-renderer-identities+jwt';
76
+
77
+ const invalid = (message: string) => verificationError('INVALID_RENDERER_LIST', message);
78
+
79
+ function decode(segment: string): string {
80
+ const bytes = Buffer.from(segment, 'base64url');
81
+ if (bytes.toString('base64url') !== segment) throw invalid('The renderer list is not canonical base64url.');
82
+ try {
83
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
84
+ } catch {
85
+ throw invalid('The renderer list does not contain valid UTF-8 JSON.');
86
+ }
87
+ }
88
+
89
+ function json(text: string): unknown {
90
+ try {
91
+ return JSON.parse(text);
92
+ } catch {
93
+ throw invalid('The renderer list is not JSON.');
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Verifies a signed renderer-identity list under the issuer's trusted keys. `keyFor` resolves the
99
+ * list's kid to a trusted public key (undefined: not trusted). Returns the verified edition: its
100
+ * seq, its iat and its identities, in order. It must agree with the bundled list
101
+ * (newerRendererList), or it is refused.
102
+ */
103
+ export async function verifyRendererList(
104
+ document: unknown,
105
+ context: {
106
+ issuer: string;
107
+ keyFor: (kid: string) => Promise<ReceiptPublicKey | undefined>;
108
+ signal?: AbortSignal;
109
+ },
110
+ ): Promise<RendererList> {
111
+ const value = snapshotJson(document);
112
+ if (
113
+ !isRecord(value) ||
114
+ !exactKeys(value, ['protected', 'payload', 'signature']) ||
115
+ ![value.protected, value.payload, value.signature].every((p) => typeof p === 'string' && PART.test(p)) ||
116
+ Buffer.byteLength(canonicalJson(value), 'utf8') > MAX_RENDERER_IDENTITIES_BYTES
117
+ ) {
118
+ throw invalid('The renderer list is not a signed renderer-identity document.');
119
+ }
120
+ const { protected: protectedHeader, payload, signature } = value as unknown as RendererIdentitiesDocument;
121
+ const header = json(decode(protectedHeader));
122
+ if (
123
+ !isRecord(header) ||
124
+ !exactKeys(header, ['alg', 'kid', 'typ']) ||
125
+ header.alg !== 'EdDSA' ||
126
+ header.typ !== TYP ||
127
+ typeof header.kid !== 'string' ||
128
+ !KID.test(header.kid)
129
+ ) {
130
+ throw invalid('The renderer list has an unsupported protected header.');
131
+ }
132
+ const signal = context.signal;
133
+ const publicKey = await context.keyFor(header.kid);
134
+ if (!publicKey) throw invalid('The renderer list is not signed with a trusted key.');
135
+ try {
136
+ const key = await waitWithSignal(
137
+ importJWK({ ...publicKey, key_ops: ['verify'], ext: false }, 'EdDSA'),
138
+ signal,
139
+ );
140
+ await waitWithSignal(
141
+ compactVerify(`${protectedHeader}.${payload}.${signature}`, key, { algorithms: ['EdDSA'] }),
142
+ signal,
143
+ );
144
+ } catch {
145
+ if (signal?.aborted) throw abortError(signal);
146
+ throw invalid('The renderer list signature did not verify with the trusted key.');
147
+ }
148
+ const text = decode(payload);
149
+ const claims = json(text);
150
+ if (canonicalJson(claims) !== text) throw invalid('The renderer list payload is not canonical JSON.');
151
+ if (
152
+ !isRecord(claims) ||
153
+ !exactKeys(claims, ['iat', 'identities', 'iss', 'seq', 'sess_renderer_identities']) ||
154
+ claims.sess_renderer_identities !== 1 ||
155
+ !positiveInteger(claims.seq) ||
156
+ !positiveInteger(claims.iat) ||
157
+ !Array.isArray(claims.identities) ||
158
+ claims.identities.length === 0
159
+ ) {
160
+ throw invalid('The renderer list payload has an unsupported shape.');
161
+ }
162
+ if (claims.iss !== context.issuer) throw invalid('The renderer list is from another issuer.');
163
+ const seen = new Set<string>();
164
+ for (const item of claims.identities) {
165
+ if (
166
+ !isRecord(item) ||
167
+ !exactKeys(item, ['renderer_version', 'since']) ||
168
+ typeof item.renderer_version !== 'string' ||
169
+ !IDENTITY.test(item.renderer_version) ||
170
+ seen.has(item.renderer_version) ||
171
+ typeof item.since !== 'string' ||
172
+ !DAY.test(item.since) ||
173
+ !Number.isFinite(Date.parse(`${item.since}T00:00:00Z`)) ||
174
+ new Date(`${item.since}T00:00:00Z`).toISOString().slice(0, 10) !== item.since
175
+ ) {
176
+ throw invalid('The renderer list has a malformed or repeated identity.');
177
+ }
178
+ seen.add(item.renderer_version);
179
+ }
180
+ const list: RendererList = Object.freeze({
181
+ seq: claims.seq as number,
182
+ iat: claims.iat as number,
183
+ identities: Object.freeze(
184
+ (claims.identities as RendererIdentity[]).map((i) =>
185
+ Object.freeze({ renderer_version: i.renderer_version, since: i.since }),
186
+ ),
187
+ ),
188
+ });
189
+ // An authentic list that disagrees with the edition this release bundles is refused.
190
+ newerRendererList(BUNDLED_RENDERER_LIST, list);
191
+ return list;
192
+ }
193
+
194
+ const positiveInteger = (v: unknown): v is number =>
195
+ typeof v === 'number' && Number.isSafeInteger(v) && v >= 1;
196
+
197
+ /**
198
+ * Of two authentic lists of one issuer, the newer edition (the higher seq; for one seq, either:
199
+ * they list the same identities). Containment is the cross-check: the newer list must begin with
200
+ * every identity of the older, in order and with the same dates, and two lists of one seq must
201
+ * list the same identities. Lists that disagree are refused with INVALID_RENDERER_LIST, never
202
+ * merged.
203
+ */
204
+ export function newerRendererList<
205
+ A extends { seq: number; identities: readonly RendererIdentity[] },
206
+ B extends { seq: number; identities: readonly RendererIdentity[] },
207
+ >(a: A, b: B): A | B {
208
+ const [older, newer]: [A | B, A | B] = b.seq < a.seq ? [b, a] : [a, b];
209
+ const prefix =
210
+ newer.identities.length >= older.identities.length &&
211
+ older.identities.every(
212
+ (o, i) =>
213
+ newer.identities[i]?.renderer_version === o.renderer_version &&
214
+ newer.identities[i]?.since === o.since,
215
+ );
216
+ if (!prefix || (older.seq === newer.seq && newer.identities.length !== older.identities.length)) {
217
+ throw invalid('The renderer lists disagree.');
218
+ }
219
+ return newer;
220
+ }
@@ -18,8 +18,30 @@ import {
18
18
  waitWithSignal,
19
19
  type DeepReadonly,
20
20
  } from './json.js';
21
+ import {
22
+ BUNDLED_RENDERER_IDENTITIES,
23
+ MAX_RENDERER_IDENTITIES_BYTES,
24
+ RENDERER_IDENTITIES_PATH,
25
+ type RendererIdentitiesDocument,
26
+ } from './renderers.js';
21
27
  import { MAX_RECEIPT_KEY_SET_BYTES, verifyDecisionReceipt, type ReceiptClaims } from './verify.js';
22
28
 
29
+ /**
30
+ * The renderer identity a receipt names, read without trusting it: only to decide whether the
31
+ * issuer's signed list is needed (the verifier decides). Undefined when it cannot be read.
32
+ */
33
+ function namedRenderer(receipt: string): string | undefined {
34
+ try {
35
+ const claims: unknown = JSON.parse(
36
+ Buffer.from(receipt.split('.')[1] ?? '', 'base64url').toString('utf8'),
37
+ );
38
+ const surface = (claims as { surface?: { renderer_version?: unknown } } | null)?.surface;
39
+ return typeof surface?.renderer_version === 'string' ? surface.renderer_version : undefined;
40
+ } catch {
41
+ return undefined;
42
+ }
43
+ }
44
+
23
45
  export interface VerificationRequestOptions {
24
46
  signal?: AbortSignal;
25
47
  operationTimeoutMs?: number;
@@ -188,9 +210,24 @@ export function createReceiptResource(context: Context): ReceiptResource {
188
210
  'An accepted response requires an interactive immutable Surface.',
189
211
  );
190
212
  }
213
+ // Decision 0009 Amendment 13: a renderer identity this release does not bundle is
214
+ // accepted only on the issuer's signed list, fetched from the same API origin as the keys.
215
+ const renderer = namedRenderer(response.receipt);
216
+ let rendererIdentities: RendererIdentitiesDocument | undefined;
217
+ if (renderer !== undefined && !BUNDLED_RENDERER_IDENTITIES.includes(renderer)) {
218
+ const listed = await waitWithSignal(
219
+ publicGet(RENDERER_IDENTITIES_PATH, {
220
+ ...requestOptions(),
221
+ maxResponseBytes: MAX_RENDERER_IDENTITIES_BYTES,
222
+ }),
223
+ controller.signal,
224
+ );
225
+ rendererIdentities = listed.data as RendererIdentitiesDocument;
226
+ }
191
227
  const claims = await verifyDecisionReceipt(
192
228
  {
193
229
  receipt: response.receipt,
230
+ ...(rendererIdentities !== undefined ? { rendererIdentities } : {}),
194
231
  issuer,
195
232
  audience: trustedWorkspace,
196
233
  expected: {
@@ -13,6 +13,12 @@ import {
13
13
  waitWithSignal,
14
14
  type DeepReadonly,
15
15
  } from './json.js';
16
+ import {
17
+ BUNDLED_RENDERER_IDENTITIES,
18
+ verifyRendererList,
19
+ type RendererIdentitiesDocument,
20
+ type RendererList,
21
+ } from './renderers.js';
16
22
 
17
23
  export const MAX_RECEIPT_BYTES = 64 * 1024;
18
24
  export const MAX_RECEIPT_KEY_SET_BYTES = 256 * 1024;
@@ -58,7 +64,11 @@ export interface ReceiptClaims {
58
64
  session_id: string;
59
65
  step_id: string;
60
66
  event_id: string;
61
- surface: { revision: number; hash: string; renderer_version: 'sess-html-form-1' };
67
+ /**
68
+ * `renderer_version`: the renderer identity the revision was shown under (Decision 0009
69
+ * Amendment 13): one this release bundles, or one on a list signed by the issuer's trusted keys.
70
+ */
71
+ surface: { revision: number; hash: string; renderer_version: string };
62
72
  action: { id: string; label: string; summary: string };
63
73
  input_hash: string;
64
74
  actor: { assurance: 'link_holder'; subject: string };
@@ -83,6 +93,12 @@ export interface VerifyDecisionReceiptInput {
83
93
  interaction: InteractiveSurfaceRevision['interaction'];
84
94
  keys?: ReceiptKeySet;
85
95
  keyResolver?: ReceiptKeyResolver;
96
+ /**
97
+ * The issuer's signed renderer-identity list (`/.well-known/sess-renderer-identities.json`),
98
+ * needed only for a receipt whose renderer identity this release does not bundle. It is trusted
99
+ * only through its signature under the same trusted keys and issuer.
100
+ */
101
+ rendererIdentities?: RendererIdentitiesDocument;
86
102
  }
87
103
 
88
104
  export interface VerifyDecisionReceiptOptions {
@@ -253,7 +269,8 @@ function claimsOf(raw: unknown): ReceiptClaims {
253
269
  ) {
254
270
  throw verificationError('INVALID_CLAIMS', 'The receipt claims do not match the supported format.');
255
271
  }
256
- if (surface.renderer_version !== 'sess-html-form-1') {
272
+ // Membership (bundled or on a signed list) is checked once the signature holds.
273
+ if (typeof surface.renderer_version !== 'string' || !identifier(surface.renderer_version)) {
257
274
  throw verificationError('UNSUPPORTED_RENDERER', 'The receipt names an unsupported renderer version.');
258
275
  }
259
276
  if (actor.assurance !== 'link_holder' || !identifier(actor.subject)) {
@@ -303,6 +320,8 @@ export async function verifyDecisionReceipt(
303
320
  const interaction = snapshotJson(input.interaction);
304
321
  const resolver = input.keyResolver;
305
322
  const keys = input.keys === undefined ? undefined : validateKeySet(input.keys);
323
+ const rendererList =
324
+ input.rendererIdentities === undefined ? undefined : snapshotJson(input.rendererIdentities);
306
325
  if (
307
326
  (keys === undefined) === (resolver === undefined) ||
308
327
  (resolver !== undefined && typeof resolver !== 'function')
@@ -429,26 +448,8 @@ export async function verifyDecisionReceipt(
429
448
  if (claims.input_hash !== jsonDigest(acceptedInput)) {
430
449
  throw verificationError('INPUT_HASH_MISMATCH', 'The receipt does not bind the accepted typed input.');
431
450
  }
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);
451
+ const keyFor = trustedKeyLookup(keys, resolver, issuer, signal);
452
+ const publicKey = await keyFor(header.kid);
452
453
  if (!publicKey)
453
454
  throw verificationError('UNKNOWN_KEY_ID', 'The receipt signing key is not in the trusted key set.');
454
455
  try {
@@ -464,5 +465,90 @@ export async function verifyDecisionReceipt(
464
465
  'The receipt signature did not verify with the trusted Ed25519 key.',
465
466
  );
466
467
  }
468
+ // Decision 0009 Amendment 13: the renderer identity is one this release bundles, or one on the
469
+ // issuer's list that verifies under the same trusted keys.
470
+ const renderer = claims.surface.renderer_version;
471
+ if (!BUNDLED_RENDERER_IDENTITIES.includes(renderer)) {
472
+ // A list proves the identities it holds; an identity it does not hold is unsupported, never
473
+ // accepted by fallback (an older list says nothing about what was added since).
474
+ const listed =
475
+ rendererList === undefined
476
+ ? []
477
+ : (await verifyRendererList(rendererList, { issuer, keyFor, ...(signal ? { signal } : {}) }))
478
+ .identities;
479
+ if (!listed.some((identity) => identity.renderer_version === renderer)) {
480
+ throw verificationError(
481
+ 'UNSUPPORTED_RENDERER',
482
+ 'The receipt names a renderer identity that is not on the issuer’s signed list.',
483
+ );
484
+ }
485
+ }
467
486
  return deepFreeze(claims);
468
487
  }
488
+
489
+ /** Resolves a kid to a trusted key: from the explicit set, or the trusted resolver (validated). */
490
+ function trustedKeyLookup(
491
+ keys: ReceiptKeySet | undefined,
492
+ resolver: ReceiptKeyResolver | undefined,
493
+ issuer: string,
494
+ signal: AbortSignal | undefined,
495
+ ): (kid: string) => Promise<ReceiptPublicKey | undefined> {
496
+ return async (kid) => {
497
+ let trusted = keys;
498
+ if (!trusted && resolver) {
499
+ let resolved: ReceiptKeySet;
500
+ try {
501
+ resolved = await waitWithSignal(
502
+ Promise.resolve(resolver(Object.freeze({ kid, issuer, ...(signal ? { signal } : {}) }))),
503
+ signal,
504
+ );
505
+ } catch {
506
+ if (signal?.aborted) throw abortError(signal);
507
+ // Callback failures may contain arbitrary application or upstream material,
508
+ // including caller-created SessError instances. Do not forward their fields.
509
+ throw verificationError(
510
+ 'KEY_RESOLUTION_FAILED',
511
+ 'The trusted receipt key resolver could not supply verification keys.',
512
+ );
513
+ }
514
+ trusted = validateKeySet(resolved);
515
+ }
516
+ return trusted?.keys.find((key) => key.kid === kid);
517
+ };
518
+ }
519
+
520
+ /**
521
+ * Verifies an issuer's signed renderer-identity list (Decision 0009 Amendment 13) under the keys
522
+ * you trust for that issuer: exactly one of `keys` or `keyResolver`. Offline with explicit keys.
523
+ * Returns the verified edition: `seq` (order lists by it; see newerRendererList), `iat` and the
524
+ * listed identities, in order.
525
+ */
526
+ export async function verifyRendererIdentities(
527
+ document: RendererIdentitiesDocument,
528
+ context: {
529
+ issuer: string;
530
+ keys?: ReceiptKeySet;
531
+ keyResolver?: ReceiptKeyResolver;
532
+ signal?: AbortSignal;
533
+ },
534
+ ): Promise<RendererList> {
535
+ const issuer = context?.issuer;
536
+ const resolver = context?.keyResolver;
537
+ const keys = context?.keys === undefined ? undefined : validateKeySet(context.keys);
538
+ if (
539
+ !identifier(issuer) ||
540
+ (keys === undefined) === (resolver === undefined) ||
541
+ (resolver !== undefined && typeof resolver !== 'function')
542
+ ) {
543
+ throw verificationError(
544
+ 'VERIFICATION_CONTEXT_MISSING',
545
+ 'A trusted issuer and exactly one trusted public key set or key resolver are required.',
546
+ );
547
+ }
548
+ const signal = context.signal;
549
+ return await verifyRendererList(document, {
550
+ issuer,
551
+ keyFor: trustedKeyLookup(keys, resolver, issuer, signal),
552
+ ...(signal ? { signal } : {}),
553
+ });
554
+ }