@sess.si/sdk 0.1.1 → 0.3.0

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.
package/dist/asks.js ADDED
@@ -0,0 +1,100 @@
1
+ import { SessError } from './errors.js';
2
+ import { Transport, pathSegment } from './transport.js';
3
+ import { decodeAsk, decodeAskClose, decodeAskCreate } from './internal/decode.js';
4
+ /** The fewest respondents an Ask takes, and the shortest lifetime, in seconds (the ceilings are the plan's). */
5
+ export const ASK_RESPONDENTS_FLOOR = 2;
6
+ const LIFETIME_FLOOR_SECONDS = 30;
7
+ function notSent(message) {
8
+ return new SessError('configuration', message, { outcome: 'not_sent' });
9
+ }
10
+ function seconds(value) {
11
+ return (value === undefined ||
12
+ (typeof value === 'number' && Number.isSafeInteger(value) && value >= LIFETIME_FLOOR_SECONDS));
13
+ }
14
+ /** The query of one page; checked before the request is sent. */
15
+ export function pageQuery(options) {
16
+ const { cursor, limit } = options;
17
+ if (cursor !== undefined && (typeof cursor !== 'string' || !/^[\x21-\x7e]{1,200}$/.test(cursor)))
18
+ throw notSent('cursor must be the next_cursor of the page before.');
19
+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1 || limit > 100))
20
+ throw notSent('limit must be a whole number from 1 to 100.');
21
+ if (cursor === undefined && limit === undefined)
22
+ return undefined;
23
+ return {
24
+ ...(cursor !== undefined ? { cursor } : {}),
25
+ ...(limit !== undefined ? { limit: String(limit) } : {}),
26
+ };
27
+ }
28
+ /**
29
+ * `POST /v1/asks`, attempted once: a lost reply may mean creation succeeded, and it is never
30
+ * retried here (an unused Ask reserves nothing, so creating again is safe). Internal: the one
31
+ * public way to create an Ask is `sess.ask({ ..., respondents })`; there is no second create verb.
32
+ */
33
+ export function createAsk(transport, body, options = {}) {
34
+ if ('idempotencyKey' in options || 'ifMatch' in options)
35
+ return Promise.reject(notSent('Ask creation does not support idempotency keys or If-Match.'));
36
+ const max = body.respondents.max;
37
+ if (!Number.isSafeInteger(max) || max < ASK_RESPONDENTS_FLOOR)
38
+ return Promise.reject(notSent(`respondents.max must be a whole number, at least ${ASK_RESPONDENTS_FLOOR}.`));
39
+ for (const key of ['expires_in', 'respondent_expires_in'])
40
+ if (!seconds(body[key]))
41
+ return Promise.reject(notSent(`${key} must be a whole number of seconds, at least 30.`));
42
+ return transport.request({
43
+ name: 'asks.create',
44
+ method: 'POST',
45
+ path: '/v1/asks',
46
+ body,
47
+ status: 201,
48
+ retry: 'never',
49
+ parse: (value) => decodeAskCreate(value, transport.allowInsecureLocalhost),
50
+ }, options);
51
+ }
52
+ /**
53
+ * Advanced: read or close an Ask by its ID (`/v1/asks/{id}`), for example after a restart. The
54
+ * handle from `sess.ask({ ..., respondents })` has the same read and close, with typed, verified
55
+ * answers; prefer it.
56
+ */
57
+ export class Asks {
58
+ #transport;
59
+ constructor(transport) {
60
+ this.#transport = transport;
61
+ }
62
+ /**
63
+ * Reads an Ask: open or closed, its counts, and one page of respondents with their accepted
64
+ * answers. Returning an answer here is that respondent's retrieval, as a Session read is.
65
+ * The answers are not yet receipt-verified; the handle's `read()` verifies them.
66
+ */
67
+ retrieve(id, options = {}) {
68
+ const { cursor: _cursor, limit: _limit, ...requestOptions } = options;
69
+ let query;
70
+ try {
71
+ query = pageQuery(options);
72
+ }
73
+ catch (error) {
74
+ return Promise.reject(error);
75
+ }
76
+ return this.#transport.request({
77
+ name: 'asks.retrieve',
78
+ method: 'GET',
79
+ path: `/v1/asks/${pathSegment(id)}`,
80
+ ...(query ? { query } : {}),
81
+ status: 200,
82
+ retry: 'safe',
83
+ parse: (value) => decodeAsk(value, id),
84
+ }, requestOptions);
85
+ }
86
+ /**
87
+ * Closes an Ask now: no one new can start; respondents who have not answered have their links
88
+ * ended. Closing a closed Ask changes nothing, so this is safe to repeat.
89
+ */
90
+ close(id, options) {
91
+ return this.#transport.request({
92
+ name: 'asks.close',
93
+ method: 'POST',
94
+ path: `/v1/asks/${pathSegment(id)}/close`,
95
+ status: 200,
96
+ retry: 'safe',
97
+ parse: (value) => decodeAskClose(value, id),
98
+ }, options);
99
+ }
100
+ }
@@ -182,8 +182,8 @@ function parse(argv) {
182
182
  };
183
183
  }
184
184
  const REASON_TEXT = {
185
- malformed: 'the file is not a bundle-v1 decision bundle',
186
- oversized: 'the bundle exceeds a bundle-v1 size bound',
185
+ malformed: 'the file is not a decision bundle (bundle-v1 or bundle-v2)',
186
+ oversized: 'the bundle exceeds a decision bundle size bound',
187
187
  unsupported_version: 'the bundle uses a later format version',
188
188
  receipt_malformed: 'the receipt cannot be read',
189
189
  algorithm: 'the receipt does not use the EdDSA algorithm',
@@ -194,7 +194,8 @@ const REASON_TEXT = {
194
194
  issuer: 'the receipt is from another issuer',
195
195
  audience: 'the receipt belongs to another workspace',
196
196
  expired: 'the receipt has expired',
197
- claims: 'the receipt claims are not valid receipt-v1 claims',
197
+ claims: 'the receipt claims are not valid receipt claims',
198
+ revision: 'the revision envelope is missing or is not the one the receipt signed',
198
199
  not_yet_valid: 'the receipt is dated in the future',
199
200
  surface_mismatch: 'the disclosed Surface is not the one the receipt signed',
200
201
  input_mismatch: 'the disclosed input is not the one the receipt signed',
package/dist/client.d.ts CHANGED
@@ -1,14 +1,24 @@
1
1
  import type { SessOptions } from './types.js';
2
2
  import { Sessions } from './sessions.js';
3
+ import { Asks } from './asks.js';
3
4
  import { WebhookResource } from './webhook-resource.js';
4
5
  import { createReceiptResource } from './receipts/resource.js';
5
- import { type AskAnswer, type AskField, type AskHandle, type AskInput, type AskOptions } from './ask.js';
6
+ import { type AskAnswer, type AskField, type AskHandle, type AskInput, type AskOptions, type AskRespondents, type AskRespondentsAnswer, type AskRespondentsHandle, type AskRespondentsInput } from './ask.js';
6
7
  /** Server-side client. Construction has no network or installation side effects. */
7
8
  export declare class Sess {
9
+ #private;
8
10
  readonly sessions: Sessions;
9
11
  readonly webhooks: WebhookResource;
10
12
  readonly receipts: ReturnType<typeof createReceiptResource>;
13
+ /** Advanced: read or close an Ask by its ID. Create one with `sess.ask({ ..., respondents })`. */
14
+ readonly asks: Asks;
11
15
  constructor(options: SessOptions);
16
+ /**
17
+ * Asks many people one question through one link: with `respondents`, Sess creates an Ask, and
18
+ * each person who starts gets their own page. The handle carries the link to share before any
19
+ * wait; `read()` returns each respondent's verified, typed answer and `close()` ends it.
20
+ */
21
+ ask<const F extends readonly AskField[], const R extends AskRespondents>(input: AskRespondentsInput<F, R>, options?: AskOptions): Promise<AskRespondentsHandle<AskRespondentsAnswer<F, R>>>;
12
22
  /**
13
23
  * Asks one question with simple typed fields. Invalid input fails before credential lookup or
14
24
  * network access. The Session is created once with the whole interaction, and the returned
package/dist/client.js CHANGED
@@ -1,16 +1,21 @@
1
1
  import { Transport } from './transport.js';
2
2
  import { Sessions } from './sessions.js';
3
+ import { Asks, createAsk } from './asks.js';
3
4
  import { WebhookResource } from './webhook-resource.js';
4
5
  import { createReceiptResource } from './receipts/resource.js';
5
- import { ask } from './ask.js';
6
+ import { ask, } from './ask.js';
6
7
  /** Server-side client. Construction has no network or installation side effects. */
7
8
  export class Sess {
8
9
  sessions;
9
10
  webhooks;
10
11
  receipts;
12
+ /** Advanced: read or close an Ask by its ID. Create one with `sess.ask({ ..., respondents })`. */
13
+ asks;
14
+ #ask;
11
15
  constructor(options) {
12
16
  const transport = new Transport(options);
13
17
  this.sessions = new Sessions(transport);
18
+ this.asks = new Asks(transport);
14
19
  this.webhooks = new WebhookResource(transport);
15
20
  this.receipts = createReceiptResource({
16
21
  baseUrl: transport.baseUrl,
@@ -29,15 +34,15 @@ export class Sess {
29
34
  parse: (value) => value,
30
35
  }, requestOptions),
31
36
  });
37
+ this.#ask = {
38
+ sessions: this.sessions,
39
+ receipts: this.receipts,
40
+ asks: this.asks,
41
+ createAsk: (body, requestOptions) => createAsk(transport, body, requestOptions),
42
+ };
32
43
  Object.freeze(this);
33
44
  }
34
- /**
35
- * Asks one question with simple typed fields. Invalid input fails before credential lookup or
36
- * network access. The Session is created once with the whole interaction, and the returned
37
- * handle carries the private link before any wait. `answer()` verifies the answer, checks that it
38
- * is still current, completes the Session and returns the typed values.
39
- */
40
45
  ask(input, options) {
41
- return ask(this.sessions, this.receipts, input, options);
46
+ return ask(this.#ask, input, options);
42
47
  }
43
48
  }
package/dist/index.d.ts CHANGED
@@ -2,6 +2,8 @@ export { Sess } from './client.js';
2
2
  export { SessError } from './errors.js';
3
3
  export type { SessErrorKind, SessErrorDetails, WriteOutcome } from './errors.js';
4
4
  export type { AskAnswer, AskAnswerOptions, AskField, AskHandle, AskInput, AskOptions } from './ask.js';
5
+ export type { AskClosed, AskRead, AskRespondent, AskRespondents, AskRespondentsAnswer, AskRespondentsHandle, AskRespondentsInput, } from './ask.js';
6
+ export type { AskReadOptions, Asks } from './asks.js';
5
7
  export * from './types.js';
6
8
  export { ITEMS_DEFAULT_LABELS, ITEMS_LIMITS, items, money } from './commerce/items.js';
7
9
  export type { Amount, ItemLineInput, ItemPaymentInput, ItemRowInput, ItemsInput, Money, } from './commerce/items.js';
@@ -1,4 +1,4 @@
1
- import type { AcceptedResponse, CreateSessionResponse, Deliveries, Session, SessionEvents, SurfaceRevision, WebhookRegisterResponse, WebhookResponse, WebhookRotateResponse, WebhookVerifyResponse, RedeliverResponse } from '../types.js';
1
+ import type { AcceptedResponse, AskCloseResponse, AskResponse, CreateAskResponse, CreateSessionResponse, Deliveries, Session, SessionEvents, SurfaceRevision, WebhookRegisterResponse, WebhookResponse, WebhookRotateResponse, WebhookVerifyResponse, RedeliverResponse } from '../types.js';
2
2
  export declare const ulid = "[0-9A-HJKMNP-TV-Z]{26}";
3
3
  export declare const sessionPattern: RegExp;
4
4
  export declare function protocol(): never;
@@ -8,6 +8,13 @@ export declare function integer(value: unknown, minimum?: number): number;
8
8
  /** Keeps all additive JSON fields intact; this is a boundary decoder, not normalization. */
9
9
  export declare function decodeAccepted(value: unknown): AcceptedResponse;
10
10
  export declare function decodeCreate(value: unknown, allowInsecureLocalhost?: boolean): CreateSessionResponse;
11
+ export declare const askPattern: RegExp;
12
+ /** `POST /v1/asks`: the Ask's id, round one, its one link, its deadline and cap. */
13
+ export declare function decodeAskCreate(value: unknown, allowInsecureLocalhost?: boolean): CreateAskResponse;
14
+ /** `POST /v1/asks/{id}/close`: the Ask after the close, without respondents. */
15
+ export declare function decodeAskClose(value: unknown, expectedId: string): AskCloseResponse;
16
+ /** `GET /v1/asks/{id}`: one page of respondents; each answer is an ordinary accepted response. */
17
+ export declare function decodeAsk(value: unknown, expectedId: string): AskResponse;
11
18
  export declare function isLoopback(host: string): boolean;
12
19
  export declare function decodeSession(value: unknown, expectedId: string): Session;
13
20
  export declare function decodeSurface(value: unknown, expectedId: string, revision: number): SurfaceRevision;
@@ -50,6 +50,18 @@ function receipt(value) {
50
50
  if (value !== null)
51
51
  string(value, receiptPattern, 65536);
52
52
  }
53
+ /**
54
+ * Receipt v2: the revision envelope beside a receipt, absent beside a receipt v1. Only its place
55
+ * is checked here (an object beside a receipt); receipt verification judges its members and
56
+ * digest, so a wrong envelope is a verification refusal, never a silently accepted answer.
57
+ */
58
+ function revisionEnvelope(record) {
59
+ if (record.revision_envelope === undefined)
60
+ return;
61
+ object(record.revision_envelope);
62
+ if (typeof record.receipt !== 'string')
63
+ protocol();
64
+ }
53
65
  function interaction(value, mode) {
54
66
  const v = object(value);
55
67
  if (v.mode !== mode)
@@ -115,6 +127,7 @@ export function decodeAccepted(value) {
115
127
  protocol();
116
128
  date(v.accepted_at);
117
129
  receipt(v.receipt);
130
+ revisionEnvelope(v);
118
131
  return value;
119
132
  }
120
133
  export function decodeCreate(value, allowInsecureLocalhost = false) {
@@ -124,7 +137,12 @@ export function decodeCreate(value, allowInsecureLocalhost = false) {
124
137
  // The link's expiry; checked when present (a runtime before the link-lifetime slice omits it).
125
138
  if (v.action_expires_at !== undefined)
126
139
  date(v.action_expires_at);
127
- const text = string(v.human_url, /^[^\s\u0000-\u001f\u007f]+$/, 4096);
140
+ humanLink(v.human_url, allowInsecureLocalhost);
141
+ return value;
142
+ }
143
+ /** A human link: absolute HTTPS (HTTP only on explicit loopback), no credentials, query or fragment. */
144
+ function humanLink(value, allowInsecureLocalhost) {
145
+ const text = string(value, /^[^\s\u0000-\u001f\u007f]+$/, 4096);
128
146
  let url;
129
147
  try {
130
148
  url = new URL(text);
@@ -139,6 +157,75 @@ export function decodeCreate(value, allowInsecureLocalhost = false) {
139
157
  !(url.protocol === 'https:' ||
140
158
  (allowInsecureLocalhost && url.protocol === 'http:' && isLoopback(url.hostname))))
141
159
  protocol();
160
+ }
161
+ export const askPattern = new RegExp(`^ask_${ulid}$`);
162
+ const ASK_REFUSALS = ['full', 'closed', 'deadline', 'minimum_time', 'burst', 'paused', 'network'];
163
+ /** `POST /v1/asks`: the Ask's id, round one, its one link, its deadline and cap. */
164
+ export function decodeAskCreate(value, allowInsecureLocalhost = false) {
165
+ const v = object(value);
166
+ string(v.id, askPattern);
167
+ if (integer(v.revision) !== 1)
168
+ protocol();
169
+ humanLink(v.human_url, allowInsecureLocalhost);
170
+ date(v.action_expires_at);
171
+ integer(v.max);
172
+ return value;
173
+ }
174
+ function askSummary(v, expectedId) {
175
+ if (string(v.id, askPattern) !== expectedId)
176
+ protocol();
177
+ oneOf(v.status, ['open', 'closed']);
178
+ if (v.status === 'open' ? v.closed_by !== null || v.closed_at !== null : v.closed_by === null)
179
+ protocol();
180
+ if (v.closed_by !== null)
181
+ oneOf(v.closed_by, ['max', 'owner', 'deadline']);
182
+ nullableDate(v.closed_at);
183
+ integer(v.max);
184
+ date(v.action_expires_at);
185
+ if (typeof v.auto_complete !== 'boolean')
186
+ protocol();
187
+ const counts = object(v.counts);
188
+ for (const key of ['started', 'answered', 'completed'])
189
+ integer(counts[key], 0);
190
+ const refused = object(counts.refused);
191
+ for (const key of ASK_REFUSALS)
192
+ integer(refused[key], 0);
193
+ }
194
+ /** `POST /v1/asks/{id}/close`: the Ask after the close, without respondents. */
195
+ export function decodeAskClose(value, expectedId) {
196
+ const v = object(value);
197
+ askSummary(v, expectedId);
198
+ if ('sessions' in v)
199
+ protocol();
200
+ return value;
201
+ }
202
+ /** `GET /v1/asks/{id}`: one page of respondents; each answer is an ordinary accepted response. */
203
+ export function decodeAsk(value, expectedId) {
204
+ const v = object(value);
205
+ askSummary(v, expectedId);
206
+ const seen = new Set();
207
+ for (const item of array(v.sessions)) {
208
+ const s = object(item);
209
+ const id = string(s.id, sessionPattern);
210
+ if (seen.has(id))
211
+ protocol();
212
+ seen.add(id);
213
+ oneOf(s.status, ['active', 'responded', 'completed', 'purged']);
214
+ const revision = integer(s.revision);
215
+ date(s.started_at);
216
+ nullableDate(s.completed_at);
217
+ const revisions = new Set();
218
+ for (const response of array(s.responses)) {
219
+ const r = decodeAccepted(response);
220
+ if (r.revision > revision || revisions.has(r.revision))
221
+ protocol();
222
+ revisions.add(r.revision);
223
+ }
224
+ if (s.status === 'purged' && revisions.size)
225
+ protocol();
226
+ }
227
+ if (v.next_cursor !== null)
228
+ string(v.next_cursor, undefined, 200);
142
229
  return value;
143
230
  }
144
231
  export function isLoopback(host) {
@@ -253,8 +340,9 @@ export function decodeEvents(value, expectedId) {
253
340
  string(e.action_id, actionPattern);
254
341
  object(e.data);
255
342
  receipt(e.receipt);
343
+ revisionEnvelope(e);
256
344
  }
257
- else if (actor !== 'owner')
345
+ else if (actor !== 'owner' || e.revision_envelope !== undefined)
258
346
  protocol();
259
347
  }
260
348
  // Decision 0009 Amendment 10: the link's extensions are listed beside the Events (never as an
@@ -1,2 +1,2 @@
1
1
  /** This package's version, sent in the User-Agent header. Tests check it against package.json. */
2
- export declare const SDK_VERSION = "0.1.1";
2
+ export declare const SDK_VERSION = "0.3.0";
@@ -1,2 +1,2 @@
1
1
  /** This package's version, sent in the User-Agent header. Tests check it against package.json. */
2
- export const SDK_VERSION = '0.1.1';
2
+ export const SDK_VERSION = '0.3.0';
@@ -1,3 +1,4 @@
1
+ import { type RevisionEnvelope } from './envelope.js';
1
2
  import { type ReceiptKeySet } from './verify.js';
2
3
  /** Bounds of a bundle (bundle-v1 §4). A bundle beyond any of them is `oversized`. */
3
4
  export declare const BUNDLE_LIMITS: Readonly<{
@@ -25,8 +26,16 @@ export interface BundleJwk {
25
26
  alg?: 'EdDSA';
26
27
  use?: 'sig';
27
28
  }
29
+ /** A decision bundle: bundle-v1 (a receipt v1) or bundle-v2 (a receipt v2 and its envelope). */
30
+ export type DecisionBundle = DecisionBundleV1 | DecisionBundleV2;
31
+ /** A bundle-v2 object: bundle-v1's members plus `revision_envelope`, exactly. */
32
+ export interface DecisionBundleV2 extends Omit<DecisionBundleV1, 'version'> {
33
+ version: 2;
34
+ /** The revision envelope the receipt v2 commits to (receipt-v2 §2). */
35
+ revision_envelope: RevisionEnvelope;
36
+ }
28
37
  /** A bundle-v1 object: exactly these members. */
29
- export interface DecisionBundle {
38
+ export interface DecisionBundleV1 {
30
39
  type: 'sess.decision-bundle';
31
40
  version: 1;
32
41
  /** The receipt-v1 compact JWS, exactly as issued. */
@@ -41,10 +50,12 @@ export interface DecisionBundle {
41
50
  keys: BundleJwk[];
42
51
  };
43
52
  }
44
- /** Receipt-v1 rejection codes (receipt-v1 §6). */
45
- type ReceiptV1Rejection = 'malformed' | 'algorithm' | 'missing_kid' | 'unknown_kid' | 'type' | 'signature' | 'issuer' | 'audience' | 'expired' | 'claims';
46
- /** Why a bundle is invalid: the first check that failed (bundle-v1 §5). */
47
- export type BundleRejection = 'malformed' | 'oversized' | 'unsupported_version' | 'receipt_malformed' | Exclude<ReceiptV1Rejection, 'malformed'> | 'not_yet_valid' | 'surface_mismatch' | 'input_mismatch' | 'context_mismatch';
53
+ /** Receipt rejection codes (receipt-v1 §6; receipt-v2 §7 adds `revision`). */
54
+ type ReceiptRejection = 'malformed' | 'algorithm' | 'missing_kid' | 'unknown_kid' | 'type' | 'signature' | 'issuer' | 'audience' | 'expired' | 'claims'
55
+ /** Receipt v2: the revision envelope is missing, malformed, or of another digest or record. */
56
+ | 'revision';
57
+ /** Why a bundle is invalid: the first check that failed (bundle-v1 §5, bundle-v2 §5). */
58
+ export type BundleRejection = 'malformed' | 'oversized' | 'unsupported_version' | 'receipt_malformed' | Exclude<ReceiptRejection, 'malformed'> | 'not_yet_valid' | 'surface_mismatch' | 'input_mismatch' | 'context_mismatch';
48
59
  /** Application context from the caller's trusted configuration, never from the bundle. */
49
60
  export interface ExpectedBundleContext {
50
61
  /** The recipient the caller expects (the receipt's `aud`: the Session's workspace). */
@@ -76,10 +87,12 @@ export interface VerifiedReceiptSummary {
76
87
  session_id: string;
77
88
  workspace_id: string;
78
89
  step_id: string;
90
+ /** A bundle-v2 result also carries `revision_hash` here (the receipt v2 claim). */
79
91
  surface: {
80
92
  revision: number;
81
93
  hash: string;
82
94
  renderer_version: string;
95
+ revision_hash?: string;
83
96
  };
84
97
  action: {
85
98
  id: string;
@@ -89,8 +102,14 @@ export interface VerifiedReceiptSummary {
89
102
  input_hash: string;
90
103
  accepted_at: string;
91
104
  expires_at: string;
105
+ /**
106
+ * bundle-v2 only: the verified revision envelope (absent for a bundle-v1 result). Its
107
+ * `key_label` and `published_at` say which of the workspace's API keys published the revision,
108
+ * under which label, and when; a face shows a publisher only from here.
109
+ */
110
+ revision_envelope?: RevisionEnvelope;
92
111
  }
93
- /** The result every face reports (bundle-v1 §6). JSON-serializable. */
112
+ /** The result every face reports (bundle-v1 §6, bundle-v2 §6). JSON-serializable. */
94
113
  export interface DecisionBundleVerification {
95
114
  valid: boolean;
96
115
  reason: BundleRejection | null;
@@ -113,9 +132,10 @@ export interface DecisionBundleVerification {
113
132
  receipt: VerifiedReceiptSummary | null;
114
133
  }
115
134
  /**
116
- * Verifies a bundle-v1 decision bundle offline against the issuer and keys the caller trusts.
117
- * Every outcome about the bundle is a result, never an exception; only invalid options throw a
118
- * TypeError. Order (bundle-v1 §5): shape and bounds; the receipt by the receipt-v1 rules; not
135
+ * Verifies a bundle-v1 or bundle-v2 decision bundle offline against the issuer and keys the caller
136
+ * trusts. Every outcome about the bundle is a result, never an exception; only invalid options
137
+ * throw a TypeError. Order (bundle-v1 §5, bundle-v2 §5): shape and bounds; the receipt by the
138
+ * receipt-v1 rules (bundle-v1) or the receipt-v2 rules with the bundle's envelope (bundle-v2); not
119
139
  * issued in the future; the disclosed Surface and input against the receipt's hashes; then the
120
140
  * caller's expected context.
121
141
  */
@@ -1,20 +1,25 @@
1
- // Decision bundles (bundle-v1, docs/spec/bundle-v1.md): a deliberate disclosure of one accepted
2
- // decision that anyone can check. verifyDecisionBundle is the SDK face of the Sess verification
3
- // core: the same check order, bounds, reasons, result object and key-trust rules, proven against
4
- // the shared conformance corpus. Keys and expected context come only from the caller; nothing in
5
- // the bundle is trusted. A valid result states what the issuer accepted from someone holding the
6
- // Session's human link: never who that person is, nor that anything was authorized or executed.
1
+ // Decision bundles (bundle-v1, docs/spec/bundle-v1.md; bundle-v2, docs/spec/bundle-v2.md): a
2
+ // deliberate disclosure of one accepted decision that anyone can check. verifyDecisionBundle is the
3
+ // SDK face of the Sess verification core: the same check order, bounds, reasons, result object and
4
+ // key-trust rules, proven against the shared conformance corpora. Keys and expected context come
5
+ // only from the caller; nothing in the bundle is trusted. A valid result states what the issuer
6
+ // accepted from someone holding the Session's human link: never who that person is, nor that
7
+ // anything was authorized or executed. bundle-v1 holds a receipt v1, unchanged; bundle-v2 holds a
8
+ // receipt v2 and the revision envelope it commits to.
7
9
  //
8
- // verifyDecisionReceipt is a separate, stricter record-bound interface and is unchanged by this
9
- // module. This module shares its trusted-key validation and canonical JSON helpers.
10
+ // verifyDecisionReceipt is a separate, stricter record-bound interface. This module shares its
11
+ // trusted-key validation, revision-envelope reading and canonical JSON helpers.
10
12
  import { createHash } from 'node:crypto';
11
13
  import { decodeProtectedHeader, errors, importJWK, jwtVerify } from 'jose';
14
+ import { parseRevisionEnvelope, revisionHash } from './envelope.js';
12
15
  import { canonicalJson, exactKeys, isRecord, jsonDigest } from './json.js';
13
16
  import { validateKeySet } from './verify.js';
14
17
  const BUNDLE_TYPE = 'sess.decision-bundle';
15
18
  const BUNDLE_VERSION = 1;
19
+ const BUNDLE_VERSION_V2 = 2;
16
20
  const RECEIPT_ALG = 'EdDSA';
17
21
  const RECEIPT_TYP = 'sess-receipt+jwt';
22
+ const RECEIPT_TYP_V2 = 'sess-receipt-2+jwt';
18
23
  /** Bounds of a bundle (bundle-v1 §4). A bundle beyond any of them is `oversized`. */
19
24
  export const BUNDLE_LIMITS = Object.freeze({
20
25
  /** RFC 8785 canonical UTF-8 bytes of the whole bundle. */
@@ -35,7 +40,7 @@ export const BUNDLE_LIMITS = Object.freeze({
35
40
  /** How far in the future a receipt's `iat` may be before it is `not_yet_valid`, in seconds. */
36
41
  const CLOCK_TOLERANCE_S = 60;
37
42
  // ------------------------------------------------------------------------------------------------
38
- // receipt-v1 §6, in its order and with its codes
43
+ // receipt-v1 §6 and receipt-v2 §7, in their order and with their codes
39
44
  // ------------------------------------------------------------------------------------------------
40
45
  class ReceiptV1Failure extends Error {
41
46
  code;
@@ -46,7 +51,7 @@ class ReceiptV1Failure extends Error {
46
51
  }
47
52
  const DIGEST = /^sha256:[0-9a-f]{64}$/;
48
53
  const nonEmpty = (v) => typeof v === 'string' && v.length > 0;
49
- function receiptV1Claims(p) {
54
+ function receiptV1Claims(p, version) {
50
55
  const top = [
51
56
  'sess_receipt',
52
57
  'iss',
@@ -70,7 +75,7 @@ function receiptV1Claims(p) {
70
75
  const act = p.actor;
71
76
  const rb = p.return_binding;
72
77
  const ok = exactKeys(p, top) &&
73
- p.sess_receipt === 1 &&
78
+ p.sess_receipt === version &&
74
79
  [p.iss, p.aud, p.jti, p.accepted_at, p.workspace_id, p.session_id, p.step_id, p.event_id].every(nonEmpty) &&
75
80
  p.jti === p.event_id &&
76
81
  Number.isSafeInteger(p.iat) &&
@@ -78,7 +83,11 @@ function receiptV1Claims(p) {
78
83
  typeof p.input_hash === 'string' &&
79
84
  DIGEST.test(p.input_hash) &&
80
85
  isRecord(s) &&
81
- exactKeys(s, ['revision', 'hash', 'renderer_version']) &&
86
+ (version === 2
87
+ ? exactKeys(s, ['revision', 'hash', 'renderer_version', 'revision_hash']) &&
88
+ typeof s.revision_hash === 'string' &&
89
+ DIGEST.test(s.revision_hash)
90
+ : exactKeys(s, ['revision', 'hash', 'renderer_version'])) &&
82
91
  Number.isSafeInteger(s.revision) &&
83
92
  s.revision >= 1 &&
84
93
  typeof s.hash === 'string' &&
@@ -103,12 +112,15 @@ function receiptV1Claims(p) {
103
112
  return p;
104
113
  }
105
114
  /**
106
- * The receipt-v1 rules against trusted keys: compact JWS, pinned EdDSA, a kid the caller trusts
107
- * (no fallback key), the receipt typ, the signature, the trusted issuer, the expected audience,
108
- * current-time expiry, then the claims and their canonical serialization. Throws ReceiptV1Failure
109
- * with the first failing code; any other error means the receipt could not be read at all.
115
+ * The receipt rules against trusted keys: compact JWS, pinned EdDSA, a kid the caller trusts
116
+ * (no fallback key), the receipt typ of the bundle's version (bundle-v1 a receipt v1, bundle-v2 a
117
+ * receipt v2), the signature, the trusted issuer, the expected audience, current-time expiry, then
118
+ * the claims and their canonical serialization, and for a receipt v2 the revision envelope it
119
+ * commits to. Throws ReceiptV1Failure with the first failing code; any other error means the
120
+ * receipt could not be read at all.
110
121
  */
111
- async function verifyReceiptV1(jws, keys, options) {
122
+ async function verifyReceiptV1(jws, keys, options, envelope) {
123
+ const typ = options.version === 2 ? RECEIPT_TYP_V2 : RECEIPT_TYP;
112
124
  if (jws.split('.').length !== 3)
113
125
  throw new ReceiptV1Failure('malformed');
114
126
  let header;
@@ -125,14 +137,14 @@ async function verifyReceiptV1(jws, keys, options) {
125
137
  const jwk = keys.keys.find((k) => k.kid === header.kid);
126
138
  if (!jwk)
127
139
  throw new ReceiptV1Failure('unknown_kid');
128
- if (header.typ !== RECEIPT_TYP)
140
+ if (header.typ !== typ)
129
141
  throw new ReceiptV1Failure('type');
130
142
  const key = await importJWK({ kty: jwk.kty, crv: jwk.crv, x: jwk.x }, RECEIPT_ALG);
131
143
  let payload;
132
144
  try {
133
145
  ({ payload } = await jwtVerify(jws, key, {
134
146
  algorithms: [RECEIPT_ALG],
135
- typ: RECEIPT_TYP,
147
+ typ,
136
148
  issuer: options.issuer,
137
149
  audience: options.audience,
138
150
  currentDate: options.now,
@@ -155,11 +167,22 @@ async function verifyReceiptV1(jws, keys, options) {
155
167
  }
156
168
  throw new ReceiptV1Failure('malformed');
157
169
  }
158
- const claims = receiptV1Claims(payload);
170
+ const claims = receiptV1Claims(payload, options.version);
159
171
  // The signed bytes must be exactly the canonical form of the claims.
160
172
  const signed = Buffer.from(jws.split('.')[1], 'base64url');
161
173
  if (`sha256:${createHash('sha256').update(signed).digest('hex')}` !== jsonDigest(claims))
162
174
  throw new ReceiptV1Failure('claims');
175
+ if (options.version === 2) {
176
+ // receipt-v2 §7: missing or null, malformed, of another digest, or of another record.
177
+ const parsed = parseRevisionEnvelope(envelope);
178
+ if (parsed === null ||
179
+ revisionHash(parsed) !== claims.surface.revision_hash ||
180
+ parsed.session_id !== claims.session_id ||
181
+ parsed.revision !== claims.surface.revision ||
182
+ parsed.surface_hash !== claims.surface.hash ||
183
+ parsed.renderer_version !== claims.surface.renderer_version)
184
+ throw new ReceiptV1Failure('revision');
185
+ }
163
186
  return claims;
164
187
  }
165
188
  // ------------------------------------------------------------------------------------------------
@@ -250,12 +273,17 @@ function shapeProblem(b) {
250
273
  return 'oversized';
251
274
  if (b.type !== BUNDLE_TYPE)
252
275
  return 'malformed';
253
- if (b.version !== BUNDLE_VERSION) {
254
- return Number.isSafeInteger(b.version) && b.version > BUNDLE_VERSION
276
+ if (b.version !== BUNDLE_VERSION && b.version !== BUNDLE_VERSION_V2) {
277
+ return Number.isSafeInteger(b.version) && b.version > BUNDLE_VERSION_V2
255
278
  ? 'unsupported_version'
256
279
  : 'malformed';
257
280
  }
258
- if (!exactKeys(b, ['type', 'version', 'receipt', 'content', 'keys']))
281
+ const members = ['type', 'version', 'receipt', 'content', 'keys'];
282
+ // bundle-v2: the revision envelope travels with its receipt. A missing, null or malformed one is
283
+ // not a shape problem: the receipt step refuses it as `revision` (bundle-v2 §5).
284
+ if (b.version === BUNDLE_VERSION_V2 && Object.hasOwn(b, 'revision_envelope'))
285
+ members.push('revision_envelope');
286
+ if (!exactKeys(b, members))
259
287
  return 'malformed';
260
288
  if (typeof b.receipt !== 'string')
261
289
  return 'malformed';
@@ -337,9 +365,10 @@ function contextChecks(e, c) {
337
365
  // Verification
338
366
  // ------------------------------------------------------------------------------------------------
339
367
  /**
340
- * Verifies a bundle-v1 decision bundle offline against the issuer and keys the caller trusts.
341
- * Every outcome about the bundle is a result, never an exception; only invalid options throw a
342
- * TypeError. Order (bundle-v1 §5): shape and bounds; the receipt by the receipt-v1 rules; not
368
+ * Verifies a bundle-v1 or bundle-v2 decision bundle offline against the issuer and keys the caller
369
+ * trusts. Every outcome about the bundle is a result, never an exception; only invalid options
370
+ * throw a TypeError. Order (bundle-v1 §5, bundle-v2 §5): shape and bounds; the receipt by the
371
+ * receipt-v1 rules (bundle-v1) or the receipt-v2 rules with the bundle's envelope (bundle-v2); not
343
372
  * issued in the future; the disclosed Surface and input against the receipt's hashes; then the
344
373
  * caller's expected context.
345
374
  */
@@ -369,8 +398,12 @@ export async function verifyDecisionBundle(bundle, options) {
369
398
  if (audience === undefined)
370
399
  return invalid('receipt_malformed');
371
400
  let claims;
401
+ // bundle-v1 holds a receipt v1, bundle-v2 a receipt v2 (another typ is `type`); a receipt v2 is
402
+ // verified with the bundle's revision envelope (a missing or other one is `revision`).
403
+ const v2 = b.version === BUNDLE_VERSION_V2;
404
+ const envelope = v2 ? b.revision_envelope : undefined;
372
405
  try {
373
- claims = await verifyReceiptV1(b.receipt, trustedKeys, { issuer: options.issuer, audience, now });
406
+ claims = await verifyReceiptV1(b.receipt, trustedKeys, { issuer: options.issuer, audience, now, version: v2 ? 2 : 1 }, envelope);
374
407
  }
375
408
  catch (e) {
376
409
  if (!(e instanceof ReceiptV1Failure))
@@ -418,6 +451,8 @@ export async function verifyDecisionBundle(bundle, options) {
418
451
  input_hash: claims.input_hash,
419
452
  accepted_at: claims.accepted_at,
420
453
  expires_at: new Date(claims.exp * 1000).toISOString(),
454
+ // bundle-v2: the envelope as verified (its digest is the receipt's revision_hash).
455
+ ...(v2 ? { revision_envelope: parseRevisionEnvelope(envelope) } : {}),
421
456
  },
422
457
  };
423
458
  }