@sess.si/sdk 0.2.0 → 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/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 — 2026-11-08
4
+
5
+ - Receipt v2: `verifyDecisionReceipt` and `receipts.verifyResponse()` verify receipts of type
6
+ `sess-receipt-2+jwt`, which commit by hash (`surface.revision_hash`) to the round's
7
+ `revision_envelope`: when the round was published and, when one of your API keys published it,
8
+ that key's ID and its label at the time. A receipt v2 is verified only with its envelope:
9
+ `verifyResponse()` passes the response's own `revision_envelope`, and `verifyDecisionReceipt`
10
+ takes it as `revisionEnvelope`. A missing, malformed or different envelope is refused with
11
+ code `REVISION_ENVELOPE_MISMATCH`, after the issuer, audience, expiry and signature checks.
12
+ Receipt v1 (`sess-receipt+jwt`) is verified exactly as before.
13
+ - `AcceptedResponse.revision_envelope`, `SessionEvent.revision_envelope` (`GET
14
+ /v1/sessions/{id}/events`) and the `response.accepted` webhook message's `revision_envelope`:
15
+ present beside a receipt v2, absent beside a receipt v1. `verifyWebhook` accepts the member.
16
+ New types `RevisionEnvelope`, `ReceiptClaimsV1` and `ReceiptClaimsV2`; `ReceiptClaims` is now
17
+ their union.
18
+ - `verifyDecisionBundle` and `sess verify` read bundle-v2 (a receipt v2 with its envelope) as well
19
+ as bundle-v1, with the new reason `revision`. A valid bundle-v2 result carries
20
+ `surface.revision_hash` and the verified `revision_envelope`. A bundle `version` above 2 is
21
+ `unsupported_version`. The receipt-v2 and bundle-v2 specifications and the bundle-v2
22
+ conformance corpus are copies from Sess commit `c67c792`.
23
+ - The runtime dependencies are unchanged. The default `User-Agent` names the new version.
24
+
3
25
  ## 0.2.0 — 2026-11-06
4
26
 
5
27
  - A rating in `sess.ask`: a field `{ type: 'rating' }` asks for a whole number from 1 to `max`.
package/README.md CHANGED
@@ -14,7 +14,7 @@ terminal with a verified receipt.
14
14
  **Install** the SDK in your own server project:
15
15
 
16
16
  ```sh
17
- npm install --save-exact @sess.si/sdk@0.2.0
17
+ npm install --save-exact @sess.si/sdk@0.3.0
18
18
  ```
19
19
 
20
20
  ## Ask a person
@@ -120,8 +120,9 @@ async function askShort(question: string) {
120
120
  }
121
121
  ```
122
122
 
123
- **Release status:** `0.2.0` is the current release, served under the `latest` dist-tag. It adds
124
- the rating field and respondents to `sess.ask`. `next` stays at the last release candidate,
123
+ **Release status:** `0.3.0` is the current release, served under the `latest` dist-tag. It
124
+ verifies receipt v2, which commits to the record of the round it answered, and still verifies
125
+ receipt v1. `next` stays at the last release candidate,
125
126
  `0.1.0-rc.10`. The [changelog](CHANGELOG.md) describes each version; `npm view @sess.si/sdk dist-tags` shows what the registry serves now.
126
127
 
127
128
  ## Commerce
@@ -242,10 +243,10 @@ exact Surface and input, and the issuer's public keys. Check it on your own comp
242
243
  trust (never the keys inside the bundle):
243
244
 
244
245
  ```sh
245
- npx -p @sess.si/sdk@0.2.0 sess verify bundle.json --issuer https://api.sess.si --keys sess-receipt-keys.json
246
+ npx -p @sess.si/sdk@0.3.0 sess verify bundle.json --issuer https://api.sess.si --keys sess-receipt-keys.json
246
247
  ```
247
248
 
248
- The `sess` command first ships in `0.1.0-rc.5`; any later version, `0.2.0` included, has it.
249
+ The `sess` command first ships in `0.1.0-rc.5`; any later version, `0.3.0` included, has it.
249
250
 
250
251
  You'll see `Valid decision bundle.` and what was accepted, when, on which revision; or `Invalid`
251
252
  and the first reason. Exit status is 0 valid, 1 invalid, 2 usage error; add `--json` for the full
@@ -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',
@@ -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) {
@@ -327,8 +340,9 @@ export function decodeEvents(value, expectedId) {
327
340
  string(e.action_id, actionPattern);
328
341
  object(e.data);
329
342
  receipt(e.receipt);
343
+ revisionEnvelope(e);
330
344
  }
331
- else if (actor !== 'owner')
345
+ else if (actor !== 'owner' || e.revision_envelope !== undefined)
332
346
  protocol();
333
347
  }
334
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.2.0";
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.2.0';
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
  }
@@ -0,0 +1,30 @@
1
+ /** The envelope's own schema version (`sess_revision`). */
2
+ export declare const REVISION_ENVELOPE_VERSION = 1;
3
+ /**
4
+ * The revision envelope beside a receipt v2: exactly these nine members. `key_id` and `key_label`
5
+ * name the API key of the Session's owning workspace that published the revision, and that key's
6
+ * label when it was published (both null for any other publisher, and for revisions published
7
+ * before receipt v2). They are the integrator's own key and word for it, never a person.
8
+ */
9
+ export interface RevisionEnvelope {
10
+ sess_revision: 1;
11
+ session_id: string;
12
+ revision: number;
13
+ /** The receipt's `surface.hash`: SHA-256 of the revision's normalized Surface document. */
14
+ surface_hash: string;
15
+ renderer_version: string;
16
+ /** When the revision was published: `YYYY-MM-DDTHH:MM:SS.mmmZ`. */
17
+ published_at: string;
18
+ key_id: string | null;
19
+ /** 0–64 characters; null exactly when `key_id` is null. */
20
+ key_label: string | null;
21
+ /** Null in this version of Sess; an identifier is accepted. */
22
+ grant_id: string | null;
23
+ }
24
+ /**
25
+ * Reads a supplied envelope strictly: exactly the nine members, each of its type, with the
26
+ * canonical `published_at`. Null for anything else (a receipt v2 verifier then refuses it).
27
+ */
28
+ export declare function parseRevisionEnvelope(v: unknown): RevisionEnvelope | null;
29
+ /** `revision_hash`: `sha256:<hex>` of the envelope's RFC 8785 canonical JSON. */
30
+ export declare function revisionHash(envelope: RevisionEnvelope): string;
@@ -0,0 +1,83 @@
1
+ // The revision envelope (receipt-v2 §2, docs/spec/receipt-v2.md): the record of one published
2
+ // Surface revision that a receipt v2 commits to through `surface.revision_hash`, the RFC 8785
3
+ // SHA-256 of the envelope. Sess computes it from the stored revision and returns it beside every
4
+ // receipt v2; a verifier recomputes the digest from the envelope it is given. It is read here
5
+ // exactly as the Sess verification core reads it (same members, types and identifier rules), so
6
+ // an envelope one accepts the other accepts.
7
+ import { exactKeys, isRecord, jsonDigest, wellFormedUnicode } from './json.js';
8
+ /** The envelope's own schema version (`sess_revision`). */
9
+ export const REVISION_ENVELOPE_VERSION = 1;
10
+ /**
11
+ * The canonical `published_at` form: RFC 3339 UTC with exactly three fractional digits, as
12
+ * `Date.prototype.toISOString` writes it.
13
+ */
14
+ const PUBLISHED_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
15
+ const DIGEST = /^sha256:[0-9a-f]{64}$/;
16
+ const ID_MAX = 200;
17
+ /** The key label's bound (at most 64 characters, possibly empty). */
18
+ const KEY_LABEL_MAX = 64;
19
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
20
+ // A bearer credential is never envelope material: Sess owner and management keys, and the
21
+ // unprefixed 22- or 43-character human link token.
22
+ const CREDENTIAL = /^(?:sess_sk_[A-Za-z0-9_-]{43}|sess_mg_[A-Za-z0-9_-]{43}|[A-Za-z0-9_-]{22}|[A-Za-z0-9_-]{43})$/;
23
+ const MEMBERS = [
24
+ 'sess_revision',
25
+ 'session_id',
26
+ 'revision',
27
+ 'surface_hash',
28
+ 'renderer_version',
29
+ 'published_at',
30
+ 'key_id',
31
+ 'key_label',
32
+ 'grant_id',
33
+ ];
34
+ function plain(v) {
35
+ return typeof v === 'string' && v.length > 0 && v.length <= ID_MAX && !CONTROL.test(v) && !/\s/.test(v);
36
+ }
37
+ function identifier(v) {
38
+ return plain(v) && !CREDENTIAL.test(v) && !/sess_(?:sk|mg)_/.test(v);
39
+ }
40
+ function label(v) {
41
+ return typeof v === 'string' && [...v].length <= KEY_LABEL_MAX && wellFormedUnicode(v) && !CONTROL.test(v);
42
+ }
43
+ function publishedAt(v) {
44
+ if (typeof v !== 'string' || !PUBLISHED_AT.test(v))
45
+ return false;
46
+ const t = new Date(v);
47
+ return !Number.isNaN(t.getTime()) && t.toISOString() === v;
48
+ }
49
+ /**
50
+ * Reads a supplied envelope strictly: exactly the nine members, each of its type, with the
51
+ * canonical `published_at`. Null for anything else (a receipt v2 verifier then refuses it).
52
+ */
53
+ export function parseRevisionEnvelope(v) {
54
+ if (!isRecord(v) || !exactKeys(v, MEMBERS))
55
+ return null;
56
+ const ok = v.sess_revision === REVISION_ENVELOPE_VERSION &&
57
+ identifier(v.session_id) &&
58
+ Number.isSafeInteger(v.revision) &&
59
+ v.revision >= 1 &&
60
+ typeof v.surface_hash === 'string' &&
61
+ DIGEST.test(v.surface_hash) &&
62
+ plain(v.renderer_version) &&
63
+ publishedAt(v.published_at) &&
64
+ (v.key_id === null ? v.key_label === null : identifier(v.key_id) && label(v.key_label)) &&
65
+ (v.grant_id === null || identifier(v.grant_id));
66
+ if (!ok)
67
+ return null;
68
+ return {
69
+ sess_revision: REVISION_ENVELOPE_VERSION,
70
+ session_id: v.session_id,
71
+ revision: v.revision,
72
+ surface_hash: v.surface_hash,
73
+ renderer_version: v.renderer_version,
74
+ published_at: v.published_at,
75
+ key_id: v.key_id,
76
+ key_label: v.key_label,
77
+ grant_id: v.grant_id,
78
+ };
79
+ }
80
+ /** `revision_hash`: `sha256:<hex>` of the envelope's RFC 8785 canonical JSON. */
81
+ export function revisionHash(envelope) {
82
+ return jsonDigest(envelope);
83
+ }
@@ -1,8 +1,9 @@
1
1
  export { verifyDecisionReceipt, verifyRendererIdentities } from './verify.js';
2
2
  export { BUNDLED_RENDERER_IDENTITIES, BUNDLED_RENDERER_LIST, newerRendererList } from './renderers.js';
3
3
  export type { RendererIdentitiesDocument, RendererIdentity, RendererList } from './renderers.js';
4
- export type { ReceiptClaims, ReceiptPublicKey, ReceiptKeySet, ReceiptKeyResolver, VerifyDecisionReceiptInput, VerifyDecisionReceiptOptions, } from './verify.js';
4
+ export type { RevisionEnvelope } from './envelope.js';
5
+ export type { ReceiptClaims, ReceiptClaimsV1, ReceiptClaimsV2, ReceiptPublicKey, ReceiptKeySet, ReceiptKeyResolver, VerifyDecisionReceiptInput, VerifyDecisionReceiptOptions, } from './verify.js';
5
6
  export type { DeepReadonly } from './json.js';
6
7
  export { verifyDecisionBundle, BUNDLE_LIMITS } from './bundle.js';
7
- export type { BundleContextField, BundleJwk, BundleRejection, DecisionBundle, DecisionBundleVerification, ExpectedBundleContext, VerifiedReceiptSummary, VerifyDecisionBundleOptions, } from './bundle.js';
8
+ export type { BundleContextField, BundleJwk, BundleRejection, DecisionBundle, DecisionBundleV1, DecisionBundleV2, DecisionBundleVerification, ExpectedBundleContext, VerifiedReceiptSummary, VerifyDecisionBundleOptions, } from './bundle.js';
8
9
  export type { ReceiptResource, VerifyResponseInput, VerifiedResponse, VerificationRequestOptions, } from './resource.js';
@@ -114,6 +114,9 @@ export function createReceiptResource(context) {
114
114
  const claims = await verifyDecisionReceipt({
115
115
  receipt: response.receipt,
116
116
  ...(rendererIdentities !== undefined ? { rendererIdentities } : {}),
117
+ // Receipt v2: the envelope returned beside it (the authorized record's own, compared
118
+ // above); a receipt v1 has none and the verifier does not read it.
119
+ revisionEnvelope: response.revision_envelope ?? null,
117
120
  issuer,
118
121
  audience: trustedWorkspace,
119
122
  expected: {
@@ -1,6 +1,7 @@
1
1
  import type { InteractiveSurfaceRevision } from '../types.js';
2
2
  import { type DeepReadonly } from './json.js';
3
3
  import { type RendererIdentitiesDocument, type RendererList } from './renderers.js';
4
+ import { type RevisionEnvelope } from './envelope.js';
4
5
  export declare const MAX_RECEIPT_BYTES: number;
5
6
  export declare const MAX_RECEIPT_KEY_SET_BYTES: number;
6
7
  /** Public Ed25519 verification material; private JWK parameters are refused. */
@@ -23,7 +24,22 @@ export type ReceiptKeyResolver = (context: {
23
24
  readonly issuer: string;
24
25
  readonly signal?: AbortSignal;
25
26
  }) => ReceiptKeySet | Promise<ReceiptKeySet>;
26
- export interface ReceiptClaims {
27
+ /** A verified receipt's claims: version 1, or version 2 (v1's plus `surface.revision_hash`). */
28
+ export type ReceiptClaims = ReceiptClaimsV1 | ReceiptClaimsV2;
29
+ /**
30
+ * Receipt v2 (receipt-v2 §3): the claims of receipt v1, unchanged, with `sess_receipt: 2` and
31
+ * `surface.revision_hash`, the SHA-256 of the revision envelope the receipt commits to.
32
+ */
33
+ export interface ReceiptClaimsV2 extends Omit<ReceiptClaimsV1, 'sess_receipt' | 'surface'> {
34
+ sess_receipt: 2;
35
+ surface: {
36
+ revision: number;
37
+ hash: string;
38
+ renderer_version: string;
39
+ revision_hash: string;
40
+ };
41
+ }
42
+ export interface ReceiptClaimsV1 {
27
43
  sess_receipt: 1;
28
44
  iss: string;
29
45
  aud: string;
@@ -83,6 +99,13 @@ export interface VerifyDecisionReceiptInput {
83
99
  * only through its signature under the same trusted keys and issuer.
84
100
  */
85
101
  rendererIdentities?: RendererIdentitiesDocument;
102
+ /**
103
+ * The revision envelope returned beside the receipt (`revision_envelope` on the accepted
104
+ * response, the Session event or the webhook message). Required for a receipt v2, which is
105
+ * refused with `REVISION_ENVELOPE_MISMATCH` without it or with any other envelope; not read for
106
+ * a receipt v1.
107
+ */
108
+ revisionEnvelope?: RevisionEnvelope | null;
86
109
  }
87
110
  export interface VerifyDecisionReceiptOptions {
88
111
  /** An explicit verification instant, useful for deliberate archival verification/tests. */
@@ -94,8 +117,15 @@ export interface VerifyDecisionReceiptOptions {
94
117
  /** Validates and copies the whole set, not merely the key selected by the token. */
95
118
  export declare function validateKeySet(raw: unknown): ReceiptKeySet;
96
119
  /**
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.
120
+ * Fully verifies a receipt and its exact accepted record. Explicit keys make this function
121
+ * entirely offline. A valid receipt attests the accepted record, not business authority.
122
+ *
123
+ * The protected `typ` decides the version: `sess-receipt+jwt` is receipt v1, verified exactly as
124
+ * before (`revisionEnvelope` is not read); `sess-receipt-2+jwt` is receipt v2, verified only with
125
+ * the revision envelope it commits to. A receipt v2 whose envelope is missing or null, malformed,
126
+ * of another digest than `surface.revision_hash`, or naming another Session, revision, Surface
127
+ * hash or renderer identity is refused with `REVISION_ENVELOPE_MISMATCH`, after the issuer,
128
+ * audience, record, time and signature checks.
99
129
  */
100
130
  export declare function verifyDecisionReceipt(input: VerifyDecisionReceiptInput, options?: VerifyDecisionReceiptOptions): Promise<DeepReadonly<ReceiptClaims>>;
101
131
  /**
@@ -1,6 +1,7 @@
1
1
  import { compactVerify, importJWK } from 'jose';
2
2
  import { abortError, canonicalJson, checkedInstant, deepFreeze, exactKeys, isRecord, jsonDigest, snapshotJson, verificationError, waitWithSignal, } from './json.js';
3
3
  import { BUNDLED_RENDERER_IDENTITIES, verifyRendererList, } from './renderers.js';
4
+ import { parseRevisionEnvelope, revisionHash } from './envelope.js';
4
5
  export const MAX_RECEIPT_BYTES = 64 * 1024;
5
6
  export const MAX_RECEIPT_KEY_SET_BYTES = 256 * 1024;
6
7
  const MAX_KEYS = 64;
@@ -9,6 +10,10 @@ const SESSION_ID = /^ses_[0-9A-HJKMNP-TV-Z]{26}$/;
9
10
  const EVENT_ID = /^evt_[0-9A-HJKMNP-TV-Z]{26}$/;
10
11
  const ACTION_ID = /^[a-z][a-z0-9_]{0,31}$/;
11
12
  const DIGEST = /^sha256:[0-9a-f]{64}$/;
13
+ /** Protected `typ` of a receipt v1 (receipt-v1); it names version 1 only. */
14
+ const RECEIPT_TYP_V1 = 'sess-receipt+jwt';
15
+ /** Protected `typ` of a receipt v2 (receipt-v2); it names version 2 only. */
16
+ const RECEIPT_TYP_V2 = 'sess-receipt-2+jwt';
12
17
  function identifier(value) {
13
18
  return (typeof value === 'string' &&
14
19
  value.length > 0 &&
@@ -87,13 +92,15 @@ function headerOf(encoded) {
87
92
  throw verificationError('UNSUPPORTED_HEADER', 'Duplicate receipt header fields are not supported.');
88
93
  if (parsed.alg !== 'EdDSA')
89
94
  throw verificationError('UNSUPPORTED_ALGORITHM', 'The receipt must use the supported EdDSA algorithm.');
90
- if (parsed.typ !== 'sess-receipt+jwt')
95
+ // The typ names the version: sess-receipt+jwt is receipt v1 only, sess-receipt-2+jwt v2 only.
96
+ const version = parsed.typ === RECEIPT_TYP_V1 ? 1 : parsed.typ === RECEIPT_TYP_V2 ? 2 : null;
97
+ if (version === null)
91
98
  throw verificationError('UNSUPPORTED_TYPE', 'The receipt has an unsupported protected type.');
92
- return parsed;
99
+ return { ...parsed, version };
93
100
  }
94
- function claimsOf(raw) {
95
- if (!isRecord(raw) || raw.sess_receipt !== 1) {
96
- throw verificationError('UNSUPPORTED_RECEIPT_VERSION', 'Only receipt format version 1 is supported.');
101
+ function claimsOf(raw, version) {
102
+ if (!isRecord(raw) || raw.sess_receipt !== version) {
103
+ throw verificationError('UNSUPPORTED_RECEIPT_VERSION', 'The receipt format version does not match its protected type (versions 1 and 2 are supported).');
97
104
  }
98
105
  const top = [
99
106
  'sess_receipt',
@@ -125,7 +132,10 @@ function claimsOf(raw) {
125
132
  raw.exp <= raw.iat ||
126
133
  checkedInstant(raw.accepted_at) === undefined ||
127
134
  !isRecord(surface) ||
128
- !exactKeys(surface, ['revision', 'hash', 'renderer_version']) ||
135
+ !exactKeys(surface, version === 2
136
+ ? ['revision', 'hash', 'renderer_version', 'revision_hash']
137
+ : ['revision', 'hash', 'renderer_version']) ||
138
+ (version === 2 && (typeof surface.revision_hash !== 'string' || !DIGEST.test(surface.revision_hash))) ||
129
139
  !Number.isSafeInteger(surface.revision) ||
130
140
  surface.revision < 1 ||
131
141
  typeof surface.hash !== 'string' ||
@@ -157,8 +167,15 @@ function claimsOf(raw) {
157
167
  return raw;
158
168
  }
159
169
  /**
160
- * Fully verifies a version-1 receipt and its exact accepted record. Explicit keys make this
161
- * function entirely offline. A valid receipt attests the accepted record, not business authority.
170
+ * Fully verifies a receipt and its exact accepted record. Explicit keys make this function
171
+ * entirely offline. A valid receipt attests the accepted record, not business authority.
172
+ *
173
+ * The protected `typ` decides the version: `sess-receipt+jwt` is receipt v1, verified exactly as
174
+ * before (`revisionEnvelope` is not read); `sess-receipt-2+jwt` is receipt v2, verified only with
175
+ * the revision envelope it commits to. A receipt v2 whose envelope is missing or null, malformed,
176
+ * of another digest than `surface.revision_hash`, or naming another Session, revision, Surface
177
+ * hash or renderer identity is refused with `REVISION_ENVELOPE_MISMATCH`, after the issuer,
178
+ * audience, record, time and signature checks.
162
179
  */
163
180
  export async function verifyDecisionReceipt(input, options = {}) {
164
181
  // Capture all caller-owned data and options before a resolver can yield control.
@@ -178,6 +195,14 @@ export async function verifyDecisionReceipt(input, options = {}) {
178
195
  const expected = snapshotJson(input.expected);
179
196
  const acceptedInput = snapshotJson(input.input);
180
197
  const interaction = snapshotJson(input.interaction);
198
+ // Captured now (before a resolver can yield), judged only for a receipt v2 once its signature holds.
199
+ let suppliedEnvelope;
200
+ try {
201
+ suppliedEnvelope = input.revisionEnvelope == null ? null : snapshotJson(input.revisionEnvelope);
202
+ }
203
+ catch {
204
+ suppliedEnvelope = MALFORMED_ENVELOPE;
205
+ }
181
206
  const resolver = input.keyResolver;
182
207
  const keys = input.keys === undefined ? undefined : validateKeySet(input.keys);
183
208
  const rendererList = input.rendererIdentities === undefined ? undefined : snapshotJson(input.rendererIdentities);
@@ -220,7 +245,7 @@ export async function verifyDecisionReceipt(input, options = {}) {
220
245
  catch {
221
246
  throw verificationError('MALFORMED_RECEIPT', 'The receipt payload is not JSON.');
222
247
  }
223
- const claims = claimsOf(snapshotJson(raw));
248
+ const claims = claimsOf(snapshotJson(raw), header.version);
224
249
  if (canonicalJson(claims) !== payloadText) {
225
250
  throw verificationError('NON_CANONICAL_PAYLOAD', 'The signed receipt payload must be RFC 8785 canonical JSON.');
226
251
  }
@@ -278,6 +303,8 @@ export async function verifyDecisionReceipt(input, options = {}) {
278
303
  throw abortError(signal);
279
304
  throw verificationError('INVALID_SIGNATURE', 'The receipt signature did not verify with the trusted Ed25519 key.');
280
305
  }
306
+ if (claims.sess_receipt === 2)
307
+ checkRevisionEnvelope(claims, suppliedEnvelope);
281
308
  // Decision 0009 Amendment 13: the renderer identity is one this release bundles, or one on the
282
309
  // issuer's list that verifies under the same trusted keys.
283
310
  const renderer = claims.surface.renderer_version;
@@ -294,6 +321,22 @@ export async function verifyDecisionReceipt(input, options = {}) {
294
321
  }
295
322
  return deepFreeze(claims);
296
323
  }
324
+ const MALFORMED_ENVELOPE = Symbol('malformed revision envelope');
325
+ /** Receipt v2: the supplied envelope must be the one the receipt commits to (receipt-v2 §7). */
326
+ function checkRevisionEnvelope(claims, supplied) {
327
+ if (supplied === null)
328
+ throw verificationError('REVISION_ENVELOPE_MISMATCH', 'A version 2 receipt is verified only with its revision envelope, and none was supplied.');
329
+ const envelope = parseRevisionEnvelope(supplied);
330
+ if (envelope === null)
331
+ throw verificationError('REVISION_ENVELOPE_MISMATCH', 'The revision envelope is malformed.');
332
+ if (revisionHash(envelope) !== claims.surface.revision_hash)
333
+ throw verificationError('REVISION_ENVELOPE_MISMATCH', 'The revision envelope is not the one the receipt commits to.');
334
+ if (envelope.session_id !== claims.session_id ||
335
+ envelope.revision !== claims.surface.revision ||
336
+ envelope.surface_hash !== claims.surface.hash ||
337
+ envelope.renderer_version !== claims.surface.renderer_version)
338
+ throw verificationError('REVISION_ENVELOPE_MISMATCH', 'The revision envelope names another Session, revision, Surface or renderer.');
339
+ }
297
340
  /** Resolves a kid to a trusted key: from the explicit set, or the trusted resolver (validated). */
298
341
  function trustedKeyLookup(keys, resolver, issuer, signal) {
299
342
  return async (kid) => {
package/dist/types.d.ts CHANGED
@@ -1,19 +1,40 @@
1
1
  import type { components } from './generated/openapi.js';
2
+ import type { RevisionEnvelope } from './receipts/envelope.js';
2
3
  /** Unmodified types generated from the reviewed public HTTP contract. */
3
4
  export type { components, paths, operations } from './generated/openapi.js';
5
+ export type { RevisionEnvelope } from './receipts/envelope.js';
4
6
  type Schemas = components['schemas'];
5
7
  export type RawCreateSessionRequest = Schemas['CreateSessionRequest'];
6
8
  export type RawPublishSessionRequest = Schemas['PatchSessionRequest'];
7
9
  export type CreateSessionResponse = Schemas['CreateSessionResponse'];
8
10
  export type DisplaySession = Schemas['SessionResponse'];
9
- export type InteractiveSession = Schemas['InteractiveSessionResponse'];
11
+ /**
12
+ * Receipt v2 (receipt-v2 §2): `revision_envelope` is written by hand beside the generated
13
+ * contract types. It is present beside a receipt v2 and absent beside a receipt v1.
14
+ */
15
+ interface RevisionEnvelopeMember {
16
+ /**
17
+ * The revision envelope the receipt v2 commits to (`surface.revision_hash`): when the revision
18
+ * was published and, when one of your API keys published it, that key's ID and its label at the
19
+ * time. `receipts.verifyResponse` verifies the receipt with it. Absent beside a receipt v1.
20
+ */
21
+ revision_envelope?: RevisionEnvelope;
22
+ }
23
+ type GeneratedInteractiveSession = Schemas['InteractiveSessionResponse'];
24
+ type GeneratedSessionEvents = Schemas['SessionEventsResponse'];
25
+ export type AcceptedResponse = GeneratedInteractiveSession['responses'][number] & RevisionEnvelopeMember;
26
+ export type InteractiveSession = Omit<GeneratedInteractiveSession, 'responses'> & {
27
+ responses: AcceptedResponse[];
28
+ };
10
29
  export type Session = DisplaySession | InteractiveSession;
11
30
  export type DisplaySurfaceRevision = Schemas['SessionResponse'];
12
31
  export type InteractiveSurfaceRevision = Schemas['InteractiveSurfaceResponse'];
13
32
  export type SurfaceRevision = DisplaySurfaceRevision | InteractiveSurfaceRevision;
14
- export type AcceptedResponse = InteractiveSession['responses'][number];
15
- export type SessionEvents = Schemas['SessionEventsResponse'];
16
- export type SessionEvent = SessionEvents['events'][number];
33
+ /** One Event of `GET /v1/sessions/{id}/events`; `revision_envelope` on `response.accepted` only. */
34
+ export type SessionEvent = GeneratedSessionEvents['events'][number] & RevisionEnvelopeMember;
35
+ export type SessionEvents = Omit<GeneratedSessionEvents, 'events'> & {
36
+ events: SessionEvent[];
37
+ };
17
38
  /**
18
39
  * The Sess link's state at the time of a Session read (Decision 0009 Amendment 10): `live` takes
19
40
  * answers; `lapsed` is past its deadline but the person can still ask for more time, so the
@@ -1,6 +1,14 @@
1
1
  import type { components } from '../generated/openapi.js';
2
2
  import { type DeepReadonly } from '../receipts/json.js';
3
- export type WebhookEvent = components['schemas']['WebhookDelivery'];
3
+ import type { RevisionEnvelope } from '../receipts/envelope.js';
4
+ /**
5
+ * A `response.accepted` delivery. A receipt v2's message also carries `revision_envelope` beside
6
+ * `receipt` (receipt-v2 §10); a receipt v1's message has no such member.
7
+ */
8
+ export type WebhookEvent = components['schemas']['WebhookDelivery'] & {
9
+ /** Beside a receipt v2 only: the revision envelope the receipt commits to. */
10
+ revision_envelope?: RevisionEnvelope;
11
+ };
4
12
  export type WebhookChallenge = components['schemas']['WebhookVerification'];
5
13
  export type VerifiedWebhook = DeepReadonly<WebhookEvent | WebhookChallenge>;
6
14
  export type WebhookHeaders = Headers | Readonly<Record<string, string | readonly string[] | undefined>>;
@@ -148,6 +148,9 @@ export function verifyWebhook(rawBody, headers, options) {
148
148
  }
149
149
  return deepFreeze(value);
150
150
  }
151
+ // A receipt v2's message carries its revision envelope beside the receipt; a receipt v1's has
152
+ // exactly the members it always had. The envelope itself is judged by receipt verification.
153
+ const withEnvelope = Object.hasOwn(value, 'revision_envelope');
151
154
  if (value.type !== 'response.accepted' ||
152
155
  !exactKeys(value, [
153
156
  'type',
@@ -159,7 +162,9 @@ export function verifyWebhook(rawBody, headers, options) {
159
162
  'data',
160
163
  'accepted_at',
161
164
  'receipt',
165
+ ...(withEnvelope ? ['revision_envelope'] : []),
162
166
  ]) ||
167
+ (withEnvelope && (!isRecord(value.revision_envelope) || typeof value.receipt !== 'string')) ||
163
168
  typeof value.event_id !== 'string' ||
164
169
  !EVENT_ID.test(value.event_id) ||
165
170
  value.event_id !== id ||
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sess.si/sdk",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Ask a person from your server and continue with their verified answer. Sess API client with receipt and webhook verification.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",