@sess.si/sdk 0.2.0 → 0.4.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,64 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0 — 2026-11-18
4
+
5
+ - Receipt v2 reads the frozen revision envelope, `sess_revision: 2`, and only it: ten common
6
+ members (`sess_revision`, `revision`, `session_id`, `surface_hash`, `renderer_version`,
7
+ `published_at`, `key_id`, `grant_id`, `agent_target`, `ask_id`), then exactly one of `titles`
8
+ (`nonce`, `grant_title`, `target_title`, `owner_name`) or `titles_digest`. `revision_hash` is
9
+ the digest of the compact form, so both forms of one round verify the same. Each title is one
10
+ line of plain text, 1 to 60 code points, under the shared title rule (no bidirectional,
11
+ zero-width or invisible characters). There is no `key_label`. Both forms, neither, any other
12
+ member, and the nine-member `sess_revision: 1` envelope that 0.3.0 read (never issued) are
13
+ refused with `REVISION_ENVELOPE_MISMATCH`. A receipt v2 `action.label` over 24 code points is
14
+ `INVALID_CLAIMS`. 0.3.x cannot read an issued receipt v2; update to this version.
15
+ - A receipt newer than this release, a later Sess receipt type or an envelope of a later
16
+ `sess_revision`, is reported as newer, never as a verification failure, and nothing is
17
+ returned: `verifyDecisionReceipt`, `receipts.verifyResponse()`, and `sess.ask()`'s `answer()`
18
+ and `read()`, throw a `SessError` of the new kind `receipt_newer` with code `RECEIPT_NEWER`;
19
+ `verifyDecisionBundle` returns `unsupported_version`; `sess verify` says the bundle is newer and
20
+ exits with the new status 3.
21
+ - `verifyDecisionBundle` refuses a bundle-v2 whose envelope is the compact form (a QR code's, never
22
+ a file's) with `revision`. A valid result's `revision_envelope` is the full form.
23
+ - New types `RevisionEnvelopeFull`, `RevisionEnvelopeCompact`, `EnvelopeTitles` and
24
+ `EnvelopeAgentTarget`; `RevisionEnvelope` is now the union of the two forms. The receipt-v2 and
25
+ bundle-v2 specifications and the bundle-v2 conformance corpus are copies from Sess commit
26
+ `33cfc41`.
27
+ - Fix: `verifyWebhook` refused the webhook messages Sess sends for a Sess Ask, with
28
+ `WEBHOOK_INVALID_PAYLOAD`. It now accepts them:
29
+ - `response.accepted` for one respondent to an Ask carries `ask_id` (`ask_…`) beside
30
+ `session_id`. The member is checked as an Ask ID and returned as `WebhookEvent.ask_id`. Any
31
+ other Session's message is unchanged and has no `ask_id`.
32
+ - `ask.closed` is its own message: exactly `type`, `event_id`, `ask_id`, `closed_by` (`max` or
33
+ `owner`), `started` and `closed_at`, each checked, its `event_id` equal to the `webhook-id`
34
+ header. It is returned as the new exported type `AskClosed`; `VerifiedWebhook` is now the
35
+ union of `WebhookEvent`, `AskClosed` and `WebhookChallenge`. Code that narrows on `type` and
36
+ treats every message that is not a challenge as `response.accepted` should check for
37
+ `ask.closed` too.
38
+ - The runtime dependencies are unchanged. The default `User-Agent` names the new version.
39
+
40
+ ## 0.3.0 — 2026-11-08
41
+
42
+ - Receipt v2: `verifyDecisionReceipt` and `receipts.verifyResponse()` verify receipts of type
43
+ `sess-receipt-2+jwt`, which commit by hash (`surface.revision_hash`) to the round's
44
+ `revision_envelope`: when the round was published and, when one of your API keys published it,
45
+ that key's ID and its label at the time. A receipt v2 is verified only with its envelope:
46
+ `verifyResponse()` passes the response's own `revision_envelope`, and `verifyDecisionReceipt`
47
+ takes it as `revisionEnvelope`. A missing, malformed or different envelope is refused with
48
+ code `REVISION_ENVELOPE_MISMATCH`, after the issuer, audience, expiry and signature checks.
49
+ Receipt v1 (`sess-receipt+jwt`) is verified exactly as before.
50
+ - `AcceptedResponse.revision_envelope`, `SessionEvent.revision_envelope` (`GET
51
+ /v1/sessions/{id}/events`) and the `response.accepted` webhook message's `revision_envelope`:
52
+ present beside a receipt v2, absent beside a receipt v1. `verifyWebhook` accepts the member.
53
+ New types `RevisionEnvelope`, `ReceiptClaimsV1` and `ReceiptClaimsV2`; `ReceiptClaims` is now
54
+ their union.
55
+ - `verifyDecisionBundle` and `sess verify` read bundle-v2 (a receipt v2 with its envelope) as well
56
+ as bundle-v1, with the new reason `revision`. A valid bundle-v2 result carries
57
+ `surface.revision_hash` and the verified `revision_envelope`. A bundle `version` above 2 is
58
+ `unsupported_version`. The receipt-v2 and bundle-v2 specifications and the bundle-v2
59
+ conformance corpus are copies from Sess commit `c67c792`.
60
+ - The runtime dependencies are unchanged. The default `User-Agent` names the new version.
61
+
3
62
  ## 0.2.0 — 2026-11-06
4
63
 
5
64
  - 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.4.0
18
18
  ```
19
19
 
20
20
  ## Ask a person
@@ -120,9 +120,10 @@ 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,
125
- `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.
123
+ **Release status:** `0.4.0` is the current release, served under the `latest` dist-tag. It
124
+ verifies receipt v2 in its frozen format, still verifies receipt v1, and accepts a Sess Ask's
125
+ webhook messages. A receipt newer than this release is reported as newer, never as a failed check.
126
+ `next` stays at the last release candidate, `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
128
129
 
@@ -242,13 +243,14 @@ 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.4.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.4.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
- and the first reason. Exit status is 0 valid, 1 invalid, 2 usage error; add `--json` for the full
252
+ and the first reason; or `This bundle is newer than @sess.si/sdk {version}. Update @sess.si/sdk to
253
+ check it.` when the bundle is newer than your version can check. Exit status is 0 valid, 1 invalid, 2 usage error, 3 newer; add `--json` for the full
252
254
  result. Nothing is sent anywhere. In code, use `verifyDecisionBundle` from `@sess.si/sdk/receipts`
253
255
  ([Security](docs/security.md#decision-bundles)). Formats: [receipt-v1](docs/spec/receipt-v1.md) and
254
256
  [bundle-v1](docs/spec/bundle-v1.md).
@@ -1,13 +1,17 @@
1
- /** Exit codes: valid, invalid bundle, usage or file error. */
1
+ /**
2
+ * Exit codes: valid, invalid bundle, usage or file error, and a bundle newer than this release
3
+ * checks (a later bundle version, receipt type or revision envelope: reported, never a failure).
4
+ */
2
5
  export declare const EXIT: Readonly<{
3
6
  valid: 0;
4
7
  invalid: 1;
5
8
  usage: 2;
9
+ newer: 3;
6
10
  }>;
7
11
  export interface CliIo {
8
12
  stdout: (text: string) => void;
9
13
  stderr: (text: string) => void;
10
14
  }
11
- export declare const USAGE = "Usage: sess verify <bundle.json> --issuer <url> --keys <jwks.json> [options]\n\nChecks a Sess decision bundle on this computer against the issuer and keys you trust.\nNothing is sent anywhere. Keys inside the bundle are never trusted.\n\nRequired:\n --issuer <url> the receipt issuer you trust, for example https://api.sess.si\n --keys <file> that issuer's public keys (a JWK Set) you obtained yourself\n\nExpected context (optional; only what you pass is checked):\n --audience <id> the workspace the decision must belong to\n --workspace <id> the workspace ID\n --session <id> the Session ID\n --event <id> the Event ID\n --revision <n> the Surface revision\n --action <id> the action ID\n\nRenderer identity (optional):\n --renderers <file> the issuer's signed renderer list you obtained yourself\n (<issuer>/.well-known/sess-renderer-identities.json); also checks that the\n receipt's renderer identity is one this release knows or one on that list\n\nOther:\n --now <time> check at this RFC 3339 time instead of now\n --json print the full result as JSON\n -h, --help show this help\n\nExit status: 0 valid, 1 invalid, 2 usage or file error.\n";
15
+ export declare const USAGE = "Usage: sess verify <bundle.json> --issuer <url> --keys <jwks.json> [options]\n\nChecks a Sess decision bundle on this computer against the issuer and keys you trust.\nNothing is sent anywhere. Keys inside the bundle are never trusted.\n\nRequired:\n --issuer <url> the receipt issuer you trust, for example https://api.sess.si\n --keys <file> that issuer's public keys (a JWK Set) you obtained yourself\n\nExpected context (optional; only what you pass is checked):\n --audience <id> the workspace the decision must belong to\n --workspace <id> the workspace ID\n --session <id> the Session ID\n --event <id> the Event ID\n --revision <n> the Surface revision\n --action <id> the action ID\n\nRenderer identity (optional):\n --renderers <file> the issuer's signed renderer list you obtained yourself\n (<issuer>/.well-known/sess-renderer-identities.json); also checks that the\n receipt's renderer identity is one this release knows or one on that list\n\nOther:\n --now <time> check at this RFC 3339 time instead of now\n --json print the full result as JSON\n -h, --help show this help\n\nExit status: 0 valid, 1 invalid, 2 usage or file error, 3 newer than this version checks.\n";
12
16
  /** Runs `sess <argv>`; resolves to the exit code. Never throws. */
13
17
  export declare function runCli(argv: readonly string[], io: CliIo): Promise<number>;
@@ -5,10 +5,14 @@
5
5
  import { readFile, stat } from 'node:fs/promises';
6
6
  import { parseArgs } from 'node:util';
7
7
  import { verifyDecisionBundle, } from '../receipts/bundle.js';
8
+ import { SDK_VERSION } from '../internal/version.js';
8
9
  import { BUNDLED_RENDERER_IDENTITIES } from '../receipts/renderers.js';
9
10
  import { validateKeySet, verifyRendererIdentities } from '../receipts/verify.js';
10
- /** Exit codes: valid, invalid bundle, usage or file error. */
11
- export const EXIT = Object.freeze({ valid: 0, invalid: 1, usage: 2 });
11
+ /**
12
+ * Exit codes: valid, invalid bundle, usage or file error, and a bundle newer than this release
13
+ * checks (a later bundle version, receipt type or revision envelope: reported, never a failure).
14
+ */
15
+ export const EXIT = Object.freeze({ valid: 0, invalid: 1, usage: 2, newer: 3 });
12
16
  /** A bundle file larger than this is not read (the bundle bound itself is 1 MiB canonical). */
13
17
  const MAX_BUNDLE_FILE_BYTES = 16 * 1024 * 1024;
14
18
  const MAX_KEYS_FILE_BYTES = 1024 * 1024;
@@ -40,7 +44,7 @@ Other:
40
44
  --json print the full result as JSON
41
45
  -h, --help show this help
42
46
 
43
- Exit status: 0 valid, 1 invalid, 2 usage or file error.
47
+ Exit status: 0 valid, 1 invalid, 2 usage or file error, 3 newer than this version checks.
44
48
  `;
45
49
  class UsageError extends Error {
46
50
  }
@@ -182,9 +186,8 @@ function parse(argv) {
182
186
  };
183
187
  }
184
188
  const REASON_TEXT = {
185
- malformed: 'the file is not a bundle-v1 decision bundle',
186
- oversized: 'the bundle exceeds a bundle-v1 size bound',
187
- unsupported_version: 'the bundle uses a later format version',
189
+ malformed: 'the file is not a decision bundle (bundle-v1 or bundle-v2)',
190
+ oversized: 'the bundle exceeds a decision bundle size bound',
188
191
  receipt_malformed: 'the receipt cannot be read',
189
192
  algorithm: 'the receipt does not use the EdDSA algorithm',
190
193
  missing_kid: 'the receipt names no key',
@@ -194,7 +197,8 @@ const REASON_TEXT = {
194
197
  issuer: 'the receipt is from another issuer',
195
198
  audience: 'the receipt belongs to another workspace',
196
199
  expired: 'the receipt has expired',
197
- claims: 'the receipt claims are not valid receipt-v1 claims',
200
+ claims: 'the receipt claims are not valid receipt claims',
201
+ revision: 'the revision envelope is missing or is not the one the receipt signed',
198
202
  not_yet_valid: 'the receipt is dated in the future',
199
203
  surface_mismatch: 'the disclosed Surface is not the one the receipt signed',
200
204
  input_mismatch: 'the disclosed input is not the one the receipt signed',
@@ -225,6 +229,10 @@ function summary(r, renderer) {
225
229
  if (renderer)
226
230
  row('Renderer', `${safe(c.surface.renderer_version)} (listed)`);
227
231
  }
232
+ else if (r.reason === 'unsupported_version') {
233
+ // A later bundle version, receipt type or revision envelope: newer, never a damaged file.
234
+ lines.push(`This bundle is newer than @sess.si/sdk ${SDK_VERSION}. Update @sess.si/sdk to check it.`);
235
+ }
228
236
  else {
229
237
  lines.push(`Invalid decision bundle: ${r.reason}`);
230
238
  lines.push(` ${REASON_TEXT[r.reason ?? ''] ?? ''}`);
@@ -312,7 +320,7 @@ export async function runCli(argv, io) {
312
320
  result = { ...result, valid: false, reason: 'renderer' };
313
321
  }
314
322
  io.stdout(parsed.json ? safeJson(renderer ? { ...result, renderer } : result) : summary(result, renderer));
315
- return result.valid ? EXIT.valid : EXIT.invalid;
323
+ return result.valid ? EXIT.valid : result.reason === 'unsupported_version' ? EXIT.newer : EXIT.invalid;
316
324
  }
317
325
  catch (e) {
318
326
  const message = e instanceof UsageError ? e.message : 'unexpected error';
package/dist/errors.d.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  import { inspect } from 'node:util';
2
2
  import type { CreateSessionResponse } from './types.js';
3
- export type SessErrorKind = 'configuration' | 'api' | 'transport' | 'timeout' | 'aborted' | 'protocol' | 'unknown_outcome' | 'receipt_verification' | 'wait_ended';
3
+ export type SessErrorKind = 'configuration' | 'api' | 'transport' | 'timeout' | 'aborted' | 'protocol' | 'unknown_outcome' | 'receipt_verification'
4
+ /**
5
+ * The receipt is newer than this release can check (code `RECEIPT_NEWER`): a later receipt type
6
+ * or a later revision envelope. Nothing was verified and no answer data is returned. It is not a
7
+ * verification failure: update @sess.si/sdk to check it.
8
+ */
9
+ | 'receipt_newer' | 'wait_ended';
4
10
  export type WriteOutcome = 'not_sent' | 'rejected' | 'unknown';
5
11
  export interface SessErrorDetails {
6
12
  code?: string;
@@ -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.4.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.4.0';
@@ -1,3 +1,4 @@
1
+ import { type RevisionEnvelopeFull } 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), in its full form. */
35
+ revision_envelope: RevisionEnvelopeFull;
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,17 @@ 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
+ /**
58
+ * Newer than this release: a later Sess receipt `typ`, or a receipt v2 whose envelope has a
59
+ * later `sess_revision`. A bundle reports it as `unsupported_version`; nothing is released.
60
+ */
61
+ | 'newer';
62
+ /** Why a bundle is invalid: the first check that failed (bundle-v1 §5, bundle-v2 §5). */
63
+ export type BundleRejection = 'malformed' | 'oversized' | 'unsupported_version' | 'receipt_malformed' | Exclude<ReceiptRejection, 'malformed' | 'newer'> | 'not_yet_valid' | 'surface_mismatch' | 'input_mismatch' | 'context_mismatch';
48
64
  /** Application context from the caller's trusted configuration, never from the bundle. */
49
65
  export interface ExpectedBundleContext {
50
66
  /** The recipient the caller expects (the receipt's `aud`: the Session's workspace). */
@@ -76,10 +92,12 @@ export interface VerifiedReceiptSummary {
76
92
  session_id: string;
77
93
  workspace_id: string;
78
94
  step_id: string;
95
+ /** A bundle-v2 result also carries `revision_hash` here (the receipt v2 claim). */
79
96
  surface: {
80
97
  revision: number;
81
98
  hash: string;
82
99
  renderer_version: string;
100
+ revision_hash?: string;
83
101
  };
84
102
  action: {
85
103
  id: string;
@@ -89,8 +107,15 @@ export interface VerifiedReceiptSummary {
89
107
  input_hash: string;
90
108
  accepted_at: string;
91
109
  expires_at: string;
110
+ /**
111
+ * bundle-v2 only: the verified revision envelope, in its full form (absent for a bundle-v1
112
+ * result). A face shows "Asked by" and `published_at` only from here: the most specific title,
113
+ * `titles.grant_title`, else `titles.target_title`, else `titles.owner_name`, each the owner's
114
+ * own words, never a verified identity.
115
+ */
116
+ revision_envelope?: RevisionEnvelopeFull;
92
117
  }
93
- /** The result every face reports (bundle-v1 §6). JSON-serializable. */
118
+ /** The result every face reports (bundle-v1 §6, bundle-v2 §6). JSON-serializable. */
94
119
  export interface DecisionBundleVerification {
95
120
  valid: boolean;
96
121
  reason: BundleRejection | null;
@@ -113,9 +138,10 @@ export interface DecisionBundleVerification {
113
138
  receipt: VerifiedReceiptSummary | null;
114
139
  }
115
140
  /**
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
141
+ * Verifies a bundle-v1 or bundle-v2 decision bundle offline against the issuer and keys the caller
142
+ * trusts. Every outcome about the bundle is a result, never an exception; only invalid options
143
+ * throw a TypeError. Order (bundle-v1 §5, bundle-v2 §5): shape and bounds; the receipt by the
144
+ * receipt-v1 rules (bundle-v1) or the receipt-v2 rules with the bundle's envelope (bundle-v2); not
119
145
  * issued in the future; the disclosed Surface and input against the receipt's hashes; then the
120
146
  * caller's expected context.
121
147
  */
@@ -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';
12
- import { canonicalJson, exactKeys, isRecord, jsonDigest } from './json.js';
14
+ import { parseFullRevisionEnvelope, parseRevisionEnvelope, revisionEnvelopeIsNewer, revisionHash, } from './envelope.js';
15
+ import { canonicalJson, exactKeys, isNewerReceiptTyp, isRecord, jsonDigest, RECEIPT_V2_ACTION_LABEL_MAX, } 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' &&
@@ -88,6 +97,7 @@ function receiptV1Claims(p) {
88
97
  exactKeys(a, ['id', 'label', 'summary']) &&
89
98
  nonEmpty(a.id) &&
90
99
  nonEmpty(a.label) &&
100
+ (version === 1 || [...a.label].length <= RECEIPT_V2_ACTION_LABEL_MAX) &&
91
101
  typeof a.summary === 'string' &&
92
102
  isRecord(act) &&
93
103
  exactKeys(act, ['assurance', 'subject']) &&
@@ -103,12 +113,15 @@ function receiptV1Claims(p) {
103
113
  return p;
104
114
  }
105
115
  /**
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.
116
+ * The receipt rules against trusted keys: compact JWS, pinned EdDSA, a kid the caller trusts
117
+ * (no fallback key), the receipt typ of the bundle's version (bundle-v1 a receipt v1, bundle-v2 a
118
+ * receipt v2), the signature, the trusted issuer, the expected audience, current-time expiry, then
119
+ * the claims and their canonical serialization, and for a receipt v2 the revision envelope it
120
+ * commits to. Throws ReceiptV1Failure with the first failing code; any other error means the
121
+ * receipt could not be read at all.
110
122
  */
111
- async function verifyReceiptV1(jws, keys, options) {
123
+ async function verifyReceiptV1(jws, keys, options, envelope) {
124
+ const typ = options.version === 2 ? RECEIPT_TYP_V2 : RECEIPT_TYP;
112
125
  if (jws.split('.').length !== 3)
113
126
  throw new ReceiptV1Failure('malformed');
114
127
  let header;
@@ -118,6 +131,10 @@ async function verifyReceiptV1(jws, keys, options) {
118
131
  catch {
119
132
  throw new ReceiptV1Failure('malformed');
120
133
  }
134
+ // A Sess format this release does not know is newer, before any other check: its key, its
135
+ // algorithm and its claims may all be ones this release has never seen.
136
+ if (isNewerReceiptTyp(header.typ))
137
+ throw new ReceiptV1Failure('newer');
121
138
  if (header.alg !== RECEIPT_ALG)
122
139
  throw new ReceiptV1Failure('algorithm');
123
140
  if (typeof header.kid !== 'string' || header.kid.length === 0)
@@ -125,14 +142,14 @@ async function verifyReceiptV1(jws, keys, options) {
125
142
  const jwk = keys.keys.find((k) => k.kid === header.kid);
126
143
  if (!jwk)
127
144
  throw new ReceiptV1Failure('unknown_kid');
128
- if (header.typ !== RECEIPT_TYP)
145
+ if (header.typ !== typ)
129
146
  throw new ReceiptV1Failure('type');
130
147
  const key = await importJWK({ kty: jwk.kty, crv: jwk.crv, x: jwk.x }, RECEIPT_ALG);
131
148
  let payload;
132
149
  try {
133
150
  ({ payload } = await jwtVerify(jws, key, {
134
151
  algorithms: [RECEIPT_ALG],
135
- typ: RECEIPT_TYP,
152
+ typ,
136
153
  issuer: options.issuer,
137
154
  audience: options.audience,
138
155
  currentDate: options.now,
@@ -155,11 +172,25 @@ async function verifyReceiptV1(jws, keys, options) {
155
172
  }
156
173
  throw new ReceiptV1Failure('malformed');
157
174
  }
158
- const claims = receiptV1Claims(payload);
175
+ const claims = receiptV1Claims(payload, options.version);
159
176
  // The signed bytes must be exactly the canonical form of the claims.
160
177
  const signed = Buffer.from(jws.split('.')[1], 'base64url');
161
178
  if (`sha256:${createHash('sha256').update(signed).digest('hex')}` !== jsonDigest(claims))
162
179
  throw new ReceiptV1Failure('claims');
180
+ if (options.version === 2) {
181
+ // receipt-v2 §7: missing or null, malformed, of another digest, or of another record. An
182
+ // envelope of a later sess_revision is newer, never read as this version.
183
+ if (envelope !== undefined && envelope !== null && revisionEnvelopeIsNewer(envelope))
184
+ throw new ReceiptV1Failure('newer');
185
+ const parsed = parseRevisionEnvelope(envelope);
186
+ if (parsed === null ||
187
+ revisionHash(parsed) !== claims.surface.revision_hash ||
188
+ parsed.session_id !== claims.session_id ||
189
+ parsed.revision !== claims.surface.revision ||
190
+ parsed.surface_hash !== claims.surface.hash ||
191
+ parsed.renderer_version !== claims.surface.renderer_version)
192
+ throw new ReceiptV1Failure('revision');
193
+ }
163
194
  return claims;
164
195
  }
165
196
  // ------------------------------------------------------------------------------------------------
@@ -250,12 +281,17 @@ function shapeProblem(b) {
250
281
  return 'oversized';
251
282
  if (b.type !== BUNDLE_TYPE)
252
283
  return 'malformed';
253
- if (b.version !== BUNDLE_VERSION) {
254
- return Number.isSafeInteger(b.version) && b.version > BUNDLE_VERSION
284
+ if (b.version !== BUNDLE_VERSION && b.version !== BUNDLE_VERSION_V2) {
285
+ return Number.isSafeInteger(b.version) && b.version > BUNDLE_VERSION_V2
255
286
  ? 'unsupported_version'
256
287
  : 'malformed';
257
288
  }
258
- if (!exactKeys(b, ['type', 'version', 'receipt', 'content', 'keys']))
289
+ const members = ['type', 'version', 'receipt', 'content', 'keys'];
290
+ // bundle-v2: the revision envelope travels with its receipt. A missing, null or malformed one is
291
+ // not a shape problem: the receipt step refuses it as `revision` (bundle-v2 §5).
292
+ if (b.version === BUNDLE_VERSION_V2 && Object.hasOwn(b, 'revision_envelope'))
293
+ members.push('revision_envelope');
294
+ if (!exactKeys(b, members))
259
295
  return 'malformed';
260
296
  if (typeof b.receipt !== 'string')
261
297
  return 'malformed';
@@ -337,9 +373,10 @@ function contextChecks(e, c) {
337
373
  // Verification
338
374
  // ------------------------------------------------------------------------------------------------
339
375
  /**
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
376
+ * Verifies a bundle-v1 or bundle-v2 decision bundle offline against the issuer and keys the caller
377
+ * trusts. Every outcome about the bundle is a result, never an exception; only invalid options
378
+ * throw a TypeError. Order (bundle-v1 §5, bundle-v2 §5): shape and bounds; the receipt by the
379
+ * receipt-v1 rules (bundle-v1) or the receipt-v2 rules with the bundle's envelope (bundle-v2); not
343
380
  * issued in the future; the disclosed Surface and input against the receipt's hashes; then the
344
381
  * caller's expected context.
345
382
  */
@@ -369,8 +406,12 @@ export async function verifyDecisionBundle(bundle, options) {
369
406
  if (audience === undefined)
370
407
  return invalid('receipt_malformed');
371
408
  let claims;
409
+ // bundle-v1 holds a receipt v1, bundle-v2 a receipt v2 (another typ is `type`); a receipt v2 is
410
+ // verified with the bundle's revision envelope (a missing or other one is `revision`).
411
+ const v2 = b.version === BUNDLE_VERSION_V2;
412
+ const envelope = v2 ? b.revision_envelope : undefined;
372
413
  try {
373
- claims = await verifyReceiptV1(b.receipt, trustedKeys, { issuer: options.issuer, audience, now });
414
+ claims = await verifyReceiptV1(b.receipt, trustedKeys, { issuer: options.issuer, audience, now, version: v2 ? 2 : 1 }, envelope);
374
415
  }
375
416
  catch (e) {
376
417
  if (!(e instanceof ReceiptV1Failure))
@@ -379,8 +420,17 @@ export async function verifyDecisionBundle(bundle, options) {
379
420
  return invalid('audience', {
380
421
  context: { status: 'mismatch', checked: supplied, mismatches: ['audience'] },
381
422
  });
423
+ // A receipt newer than this release (a later Sess typ, a later envelope) is a newer bundle:
424
+ // reported as unsupported_version, and nothing is released.
425
+ if (e.code === 'newer')
426
+ return invalid('unsupported_version');
382
427
  return invalid(e.code === 'malformed' ? 'receipt_malformed' : e.code);
383
428
  }
429
+ // A person's file carries the full form: a compact envelope is a QR code's, never a bundle's, so
430
+ // it is refused as `revision` even when its digest matches.
431
+ const verifiedEnvelope = v2 ? parseFullRevisionEnvelope(envelope) : null;
432
+ if (v2 && verifiedEnvelope === null)
433
+ return invalid('revision');
384
434
  if (claims.iat > Math.floor(now.getTime() / 1000) + CLOCK_TOLERANCE_S)
385
435
  return invalid('not_yet_valid');
386
436
  if (claims.surface.hash !== jsonDigest(b.content.surface))
@@ -418,6 +468,8 @@ export async function verifyDecisionBundle(bundle, options) {
418
468
  input_hash: claims.input_hash,
419
469
  accepted_at: claims.accepted_at,
420
470
  expires_at: new Date(claims.exp * 1000).toISOString(),
471
+ // bundle-v2: the envelope as verified (its digest is the receipt's revision_hash).
472
+ ...(verifiedEnvelope ? { revision_envelope: verifiedEnvelope } : {}),
421
473
  },
422
474
  };
423
475
  }