@sess.si/sdk 0.5.0 → 0.6.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,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0 — 2026-11-22
4
+
5
+ - The closing receipt: when a Session ends with at least one accepted answer, Sess signs how it
6
+ ended and every accepted answer's receipt, in order. `sessions.listEvents()` returns it as
7
+ `closing`, beside `events`, never as an Event; it is absent otherwise. New type
8
+ `SessionClosing`.
9
+ - `receipts.verifyClosing({ sessionId, closing })` verifies it against the Session's Event log and
10
+ the published keys and returns `{ claims, closing }`. `verifyClosingReceipt` in
11
+ `@sess.si/sdk/receipts` verifies one offline. A round receipt offered as a closing receipt is
12
+ refused with `UNSUPPORTED_TYPE`; rounds that are not exactly the signed ones with
13
+ `CLOSING_ROUNDS_MISMATCH`. New types `ClosingReceiptClaims`, `ClosingCause`,
14
+ `VerifyClosingReceiptInput`, `VerifyClosingReceiptOptions`, `VerifyClosingInput` and
15
+ `VerifiedClosing`.
16
+ - Unchanged: `verifyDecisionReceipt` still refuses a closing receipt as newer (`RECEIPT_NEWER`),
17
+ and `verifyWebhook` still refuses every Session message but `response.accepted`.
18
+ - The closing-receipt-v1 specification and conformance corpus are copies from Sess commit
19
+ `7be0bf3`. The runtime dependencies are unchanged.
20
+
3
21
  ## 0.5.0 — 2026-11-21
4
22
 
5
23
  - Sess's tighter text limits: title 60, description 200, heading 40, field label 40, field help
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.5.0
17
+ npm install --save-exact @sess.si/sdk@0.6.0
18
18
  ```
19
19
 
20
20
  ## Ask a person
@@ -121,9 +121,10 @@ async function askShort(question: string) {
121
121
  }
122
122
  ```
123
123
 
124
- **Release status:** `0.5.0` is the current release, served under the `latest` dist-tag. It
125
- checks Sess's tighter text limits before anything is sent, verifies receipt v2 in its frozen format,
126
- still verifies receipt v1, and accepts a Sess Ask's webhook messages. A receipt newer than this
124
+ **Release status:** `0.6.0` is the current release, served under the `latest` dist-tag. It
125
+ returns a Session's closing receipt with its Events and verifies it, checks Sess's tighter text
126
+ limits before anything is sent, verifies receipt v2 in its frozen format, still verifies receipt
127
+ v1, and accepts a Sess Ask's webhook messages. A receipt newer than this
127
128
  release is reported as newer, never as a failed check.
128
129
  `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.
129
130
 
@@ -245,10 +246,10 @@ exact Surface and input, and the issuer's public keys. Check it on your own comp
245
246
  trust (never the keys inside the bundle):
246
247
 
247
248
  ```sh
248
- npx -p @sess.si/sdk@0.5.0 sess verify bundle.json --issuer https://api.sess.si --keys sess-receipt-keys.json
249
+ npx -p @sess.si/sdk@0.6.0 sess verify bundle.json --issuer https://api.sess.si --keys sess-receipt-keys.json
249
250
  ```
250
251
 
251
- The `sess` command first ships in `0.1.0-rc.5`; any later version, `0.5.0` included, has it.
252
+ The `sess` command first ships in `0.1.0-rc.5`; any later version, `0.6.0` included, has it.
252
253
 
253
254
  You'll see `Valid decision bundle.` and what was accepted, when, on which revision; or `Invalid`
254
255
  and the first reason; or `This bundle is newer than @sess.si/sdk {version}. Update @sess.si/sdk to
package/dist/client.js CHANGED
@@ -24,6 +24,7 @@ export class Sess {
24
24
  operationTimeoutMs: transport.operationTimeoutMs,
25
25
  retrieveSession: (id, requestOptions) => this.sessions.retrieve(id, requestOptions),
26
26
  retrieveSurface: (id, revision, requestOptions) => this.sessions.retrieveSurface(id, revision, requestOptions),
27
+ listEvents: (id, requestOptions) => this.sessions.listEvents(id, requestOptions),
27
28
  publicGet: (path, requestOptions) => transport.request({
28
29
  name: 'receipts.keys',
29
30
  method: 'GET',
@@ -1320,7 +1320,7 @@ export interface paths {
1320
1320
  /**
1321
1321
  * @description Lists the workspace’s receipts in the console, as details only.
1322
1322
  *
1323
- * Each row shows the receipt and Session IDs, the workspace’s sequence number, when the answer was accepted, the witness status and whether the answers are still kept; receipts held unverified have their own view. A receipt or an answer is never shown on this page. The page shows 25 at a time, counted under the same filters, with Previous and Next. Someone who is not signed in is sent to the sign-in page.
1323
+ * Each row shows the receipt and Session IDs, the workspace’s sequence number, when the answer was accepted and whether the answers are still kept; receipts held unverified have their own view. A receipt or an answer is never shown on this page. The page shows 25 at a time, counted under the same filters, with Previous and Next. Someone who is not signed in is sent to the sign-in page.
1324
1324
  *
1325
1325
  * Advanced: The query takes `custody` (`exception`), `from` and `to` (UTC dates, `to` included), `target` (a target ID), `q` (a part of the Session title, matched as plain text) and `cursor`, an opaque page position, forward or back; one that is not of this view gives the first page. The page is labelled "issued records in this defined scope/range".
1326
1326
  */
@@ -1410,7 +1410,7 @@ export interface paths {
1410
1410
  /**
1411
1411
  * @description Shows one receipt of the workspace in the console.
1412
1412
  *
1413
- * You see its receipt number, its event and Session IDs, when the answer was accepted, the witness status and whether the answers are still kept, with Verify and the receipt download when the receipt has a signed archival core. A receipt, an answer or a Sess link is never shown on the page. Another workspace’s receipt, an unknown one and a malformed ID get the same answer; someone who is not signed in is sent to the sign-in page.
1413
+ * You see its receipt number, its event and Session IDs, when the answer was accepted and whether the answers are still kept, with Verify and the receipt download when the receipt has a signed archival core. A receipt, an answer or a Sess link is never shown on the page. Another workspace’s receipt, an unknown one and a malformed ID get the same answer; someone who is not signed in is sent to the sign-in page.
1414
1414
  */
1415
1415
  get: operations['evidenceReceiptPage'];
1416
1416
  put?: never;
@@ -1652,9 +1652,10 @@ export interface paths {
1652
1652
  * - Each published revision, and the completion.
1653
1653
  * - Events never change, and every accepted answer stays listed after later revisions and completion.
1654
1654
  * - Where link extensions are on, every accepted extension of the Sess link is listed beside the events, never with an answer value.
1655
+ * - Once the Session has ended with at least one accepted answer, its closing receipt comes with the events.
1655
1656
  * - A display Session has no events.
1656
1657
  *
1657
- * Advanced: Answers are `response.accepted` by `link_holder`, with the revision, `action_id` and the data; `revision.published` and `session.completed` are by `owner`. Event IDs and sequence numbers never change. The list is not paginated: a Session has a few Events per round. `link_extensions` lists each extension’s old and new deadline, whether it was asked for after the deadline, and when. Responses are sent with `Cache-Control: no-store, no-transform`.
1658
+ * Advanced: Answers are `response.accepted` by `link_holder`, with the revision, `action_id` and the data; `revision.published` and `session.completed` are by `owner`. Event IDs and sequence numbers never change. The list is not paginated: a Session has a few Events per round. `link_extensions` lists each extension’s old and new deadline, whether it was asked for after the deadline, and when. `closing` is the closing receipt (`typ` `sess-closing-receipt+jwt`) with the cause and count it signs: never an Event and never a receipt for one answer, and webhooks do not carry it. Responses are sent with `Cache-Control: no-store, no-transform`.
1658
1659
  */
1659
1660
  get: operations['listSessionEvents'];
1660
1661
  put?: never;
@@ -2136,6 +2137,31 @@ export interface paths {
2136
2137
  patch?: never;
2137
2138
  trace?: never;
2138
2139
  };
2140
+ '/v1/receipts/verify-closing': {
2141
+ parameters: {
2142
+ query?: never;
2143
+ header?: never;
2144
+ path?: never;
2145
+ cookie?: never;
2146
+ };
2147
+ get?: never;
2148
+ put?: never;
2149
+ /**
2150
+ * @description Checks a kept file’s closing receipt and its round receipts with this server’s own receipt keys. No credential needed.
2151
+ *
2152
+ * - Nothing in the request is trusted.
2153
+ * - It reports the closing receipt’s own check, whether the receipts sent are exactly the set it signs, and what a person’s page shows.
2154
+ * - It looks nothing up and stores nothing, and evidence that fails is still a 200 result.
2155
+ *
2156
+ * Advanced: The formats are in the Sess closing-receipt-v1 specification §6.1 and the Sess keep-v4 specification §3. Send the round receipts in the order the file carries them, at most 64. The body is JSON, at most 2097152 bytes. It shares the bundle check’s rate limits per client and in total, and its absolute 2-second deadline from arrival, after which the connection is closed with `Connection: close`. Responses are sent with `Cache-Control: no-store, no-transform` and `Referrer-Policy: no-referrer`, with CORS only for the product site’s origins. Never put a receipt in an address.
2157
+ */
2158
+ post: operations['verifyClosingReceipt'];
2159
+ delete?: never;
2160
+ options?: never;
2161
+ head?: never;
2162
+ patch?: never;
2163
+ trace?: never;
2164
+ };
2139
2165
  '/v1/targets': {
2140
2166
  parameters: {
2141
2167
  query?: never;
@@ -3280,6 +3306,42 @@ export interface components {
3280
3306
  /** @description When the extension was accepted. */
3281
3307
  extended_at: string;
3282
3308
  }[];
3309
+ /** @description The Session’s closing receipt: a signed record of how it ended and of every accepted answer’s receipt, in order. Present only once the Session has ended with at least one accepted answer, its closing receipt is signed and the receipts listed above are exactly the ones it commits to; absent otherwise. */
3310
+ closing?: {
3311
+ /**
3312
+ * @description What `receipt` is: a closing receipt, version 1. Never a receipt for one answer, so never verify it as one.
3313
+ * @constant
3314
+ */
3315
+ typ: 'sess-closing-receipt+jwt';
3316
+ /** @description The closing receipt’s ID, the `jti` it signs. */
3317
+ closure_id: string;
3318
+ /** @description How the Session ended, as the closing receipt signs it: `completed_by_owner` when your agent completed it, `completed_by_ask_rule` when its Ask completed it on the answer, `final_expiry` when its Sess link expired for good. `revoked` ends a Session with no accepted answer, which has no closing receipt. */
3319
+ cause: 'completed_by_owner' | 'completed_by_ask_rule' | 'final_expiry' | 'revoked';
3320
+ /** @description The Event that ended the Session, as the closing receipt signs it: its `session.completed`, or for `final_expiry` the expiry Event Sess recorded, which this list does not include. null only for `revoked`. */
3321
+ terminal_event_id: string | null;
3322
+ /** @description How many answers were accepted in the Session, at least 1: the count the closing receipt signs. Each is a `response.accepted` Event above. */
3323
+ accepted_rounds: number;
3324
+ /** @description The closing receipt exactly as signed: a compact JWS (EdDSA/Ed25519, typ sess-closing-receipt+jwt, no exp) that commits, in order, to the exact bytes of every accepted answer’s receipt. Verify it with GET /.well-known/sess-receipt-keys.json; it is signed once and never re-signed. */
3325
+ receipt: string;
3326
+ };
3327
+ };
3328
+ /** @description The Session’s closing receipt: a signed record of how it ended and of every accepted answer’s receipt, in order. Present only once the Session has ended with at least one accepted answer, its closing receipt is signed and the receipts listed above are exactly the ones it commits to; absent otherwise. */
3329
+ SessionClosing: {
3330
+ /**
3331
+ * @description What `receipt` is: a closing receipt, version 1. Never a receipt for one answer, so never verify it as one.
3332
+ * @constant
3333
+ */
3334
+ typ: 'sess-closing-receipt+jwt';
3335
+ /** @description The closing receipt’s ID, the `jti` it signs. */
3336
+ closure_id: string;
3337
+ /** @description How the Session ended, as the closing receipt signs it: `completed_by_owner` when your agent completed it, `completed_by_ask_rule` when its Ask completed it on the answer, `final_expiry` when its Sess link expired for good. `revoked` ends a Session with no accepted answer, which has no closing receipt. */
3338
+ cause: 'completed_by_owner' | 'completed_by_ask_rule' | 'final_expiry' | 'revoked';
3339
+ /** @description The Event that ended the Session, as the closing receipt signs it: its `session.completed`, or for `final_expiry` the expiry Event Sess recorded, which this list does not include. null only for `revoked`. */
3340
+ terminal_event_id: string | null;
3341
+ /** @description How many answers were accepted in the Session, at least 1: the count the closing receipt signs. Each is a `response.accepted` Event above. */
3342
+ accepted_rounds: number;
3343
+ /** @description The closing receipt exactly as signed: a compact JWS (EdDSA/Ed25519, typ sess-closing-receipt+jwt, no exp) that commits, in order, to the exact bytes of every accepted answer’s receipt. Verify it with GET /.well-known/sess-receipt-keys.json; it is signed once and never re-signed. */
3344
+ receipt: string;
3283
3345
  };
3284
3346
  ReceiptKeysResponse: {
3285
3347
  /** @description The active signing key and every retained verification key (rotation overlap). A receipt verifies with the key whose kid its protected header names; there is no fallback key. */
@@ -3598,6 +3660,45 @@ export interface components {
3598
3660
  expired_for_live_use: boolean | null;
3599
3661
  };
3600
3662
  };
3663
+ ClosingVerifyRequest: {
3664
+ /** @description The kept file’s closing receipt, its exact compact JWS. */
3665
+ closing_receipt: string;
3666
+ /** @description The file’s round receipts, in the order the file carries them. */
3667
+ rounds: {
3668
+ receipt: string;
3669
+ /** @description A receipt v2’s revision envelope, as the file carries it. */
3670
+ revision_envelope?: {
3671
+ [key: string]: unknown;
3672
+ } | null;
3673
+ }[];
3674
+ };
3675
+ ClosingVerifyResponse: {
3676
+ /** @description closing-receipt-v1 §6.1: derived from authenticity and set match alone. */
3677
+ completeness: 'complete' | 'failed' | 'unsupported' | 'none';
3678
+ /** @description The closing receipt’s own authenticity. */
3679
+ closing: {
3680
+ status: 'valid' | 'invalid' | 'missing' | 'unsupported' | 'unverifiable';
3681
+ reason: string;
3682
+ };
3683
+ set_match: {
3684
+ status: 'valid' | 'invalid' | 'missing' | 'unsupported' | 'unverifiable';
3685
+ reason: string;
3686
+ present: number;
3687
+ signed_count: number | null;
3688
+ };
3689
+ independent_time: {
3690
+ /** @constant */
3691
+ status: 'missing';
3692
+ /** @constant */
3693
+ reason: 'no_timestamp_evidence';
3694
+ };
3695
+ /** @description What a person’s page shows: complete (the set-match row, with the signed count), failed (the shared failed-evidence result) or none (no row and no line). */
3696
+ presentation: {
3697
+ state: 'complete' | 'failed' | 'none';
3698
+ count: number | null;
3699
+ anchored_at: string | null;
3700
+ };
3701
+ };
3601
3702
  KeepChallengeRequest: {
3602
3703
  /** @description The Keep grant secrets this browser holds for this link: each the 32-byte secret whose domain-separated SHA-256 was the client_event_id of a round it submitted (`kg-` + hash). A round is authorized only by its own grant. Sent in the body only, never in a URL. */
3603
3704
  grants: string[];
@@ -3652,8 +3753,8 @@ export interface components {
3652
3753
  KeptConversation: {
3653
3754
  /** @constant */
3654
3755
  type: 'sess.kept-conversation';
3655
- /** @description 2 (keep-v2: a round also carries revision_envelope) exactly when the file holds a receipt v2 round; else 1 (keep-v1, as written before receipt v2); 3 (keep-v3, archival-person-projection §3: person envelopes and holder proofs v2) for every file once keep-v3 writing is on. Readers take all three. */
3656
- version: 1 | 2 | 3;
3756
+ /** @description 2 (keep-v2: a round also carries revision_envelope) exactly when the file holds a receipt v2 round; else 1 (keep-v1, as written before receipt v2); 3 (keep-v3, archival-person-projection §3: person envelopes and holder proofs v2) for every file once keep-v3 writing is on; 4 (keep-v4, Decision 0016: keep-v3 with closing_receipt) for every file once keep-v4 writing is on. Readers take all four. */
3757
+ version: 1 | 2 | 3 | 4;
3657
3758
  issuer: string;
3658
3759
  workspace_id: string;
3659
3760
  session_id: string;
@@ -3839,6 +3940,8 @@ export interface components {
3839
3940
  reason: 'not_preserved' | 'final_only' | 'not_enrolled' | 'holder_withheld' | 'holder_core_bound';
3840
3941
  };
3841
3942
  }[];
3943
+ /** @description keep-v4 only (Decision 0016): the Session’s closing receipt (closing-receipt-v1), its exact compact JWS as sealed, present only when the file holds exactly the accepted rounds it commits to; else null. Never a count or list of rounds the file lacks. */
3944
+ closing_receipt?: string | null;
3842
3945
  };
3843
3946
  WebhookRegisterRequest: {
3844
3947
  /** @description Absolute https:// URL on port 443, without user info or fragment. Registering replaces the current endpoint (which stops receiving new deliveries); the new one receives nothing until verified. */
@@ -4207,11 +4310,11 @@ export interface components {
4207
4310
  };
4208
4311
  Error: {
4209
4312
  error: {
4210
- code: 'INVALID_SCHEMA' | 'PAYLOAD_TOO_LARGE' | 'UNAUTHORIZED' | 'SESSION_NOT_FOUND' | 'NOT_FOUND' | 'INTERNAL' | 'UNKNOWN_COMPONENT' | 'SESSION_REVISION_CONFLICT' | 'IDEMPOTENCY_CONFLICT' | 'PRECONDITION_REQUIRED' | 'SESSION_COMPLETED' | 'ACTION_NOT_ALLOWED' | 'ACTION_NOT_FOUND' | 'VALIDATION_FAILED' | 'RESPONSE_LIMIT_REACHED' | 'SERVICE_UNAVAILABLE' | 'RATE_LIMITED' | 'TRIAL_UNAVAILABLE' | 'SIGN_IN_UNAVAILABLE' | 'WEBHOOK_INVALID_URL' | 'WEBHOOK_VERIFICATION_FAILED' | 'WEBHOOK_NOT_CONFIGURED' | 'TARGET_INVALID_URL' | 'TARGET_INVALID_CAPABILITY' | 'TARGET_VERIFICATION_FAILED' | 'TARGET_VERSION_CONFLICT' | 'INVOCATION_TERMINAL' | 'HOLDER_ENROLLMENT_REFUSED' | 'PLAN_LIMIT_REACHED' | 'SUBSCRIPTION_EXISTS' | 'TARGET_NAME_TAKEN' | 'EVIDENCE_RESTRICTED' | 'EVIDENCE_DELETED';
4313
+ code: 'INVALID_SCHEMA' | 'PAYLOAD_TOO_LARGE' | 'UNAUTHORIZED' | 'SESSION_NOT_FOUND' | 'NOT_FOUND' | 'INTERNAL' | 'UNKNOWN_COMPONENT' | 'SESSION_REVISION_CONFLICT' | 'IDEMPOTENCY_CONFLICT' | 'PRECONDITION_REQUIRED' | 'SESSION_COMPLETED' | 'SESSION_ENDED' | 'ACTION_NOT_ALLOWED' | 'ACTION_NOT_FOUND' | 'VALIDATION_FAILED' | 'RESPONSE_LIMIT_REACHED' | 'SERVICE_UNAVAILABLE' | 'RATE_LIMITED' | 'TRIAL_UNAVAILABLE' | 'SIGN_IN_UNAVAILABLE' | 'WEBHOOK_INVALID_URL' | 'WEBHOOK_VERIFICATION_FAILED' | 'WEBHOOK_NOT_CONFIGURED' | 'TARGET_INVALID_URL' | 'TARGET_INVALID_CAPABILITY' | 'TARGET_VERIFICATION_FAILED' | 'TARGET_VERSION_CONFLICT' | 'INVOCATION_TERMINAL' | 'HOLDER_ENROLLMENT_REFUSED' | 'PLAN_LIMIT_REACHED' | 'SUBSCRIPTION_EXISTS' | 'TARGET_NAME_TAKEN' | 'EVIDENCE_RESTRICTED' | 'EVIDENCE_DELETED';
4211
4314
  /** @description Plain words for people; clients read code, field, limit, length and expected, never this text. For a value over its length limit it names the value, its length and the limit, and says how to fix it: "Shorten it to at most <limit> characters." A 401 for a create sent with no Authorization header also names the no-signup trial, POST /v1/trial/sessions. */
4212
4315
  message: string;
4213
4316
  request_id: string;
4214
- /** @description A stable machine-readable refinement of some codes (P1 A4 webhook errors; P2 target, admission and limit errors). */
4317
+ /** @description A stable machine-readable refinement of some codes (P1 A4 webhook errors; P2 target, admission and limit errors; SESSION_ENDED: the terminal cause, `final_expiry` or `revoked`). */
4215
4318
  reason?: string;
4216
4319
  /** @description INVALID_SCHEMA for a value over its length limit, and for an items component (Commerce): a JSON pointer to the value in the request body, for example /interaction/title (for a record key, the pointer names that key) or /interaction/source/components/2/currency; and VALIDATION_FAILED for an agent’s sharing title (reason title_invalid or title_required): /title. A request body that does not match the schema carries field, the pointer to its first failing value, with expected: for a missing property the pointer names it; for an unknown property it is the object that holds it (the unknown name is never repeated); a pointer never passes through a key you chose (it stops at the object holding that key). Other schema errors (malformed JSON, path and query values) carry no field, limit, length, expected or actual. */
4217
4320
  field?: string;
@@ -4817,6 +4920,13 @@ export interface components {
4817
4920
  sent_to: string | null;
4818
4921
  };
4819
4922
  }[];
4923
+ /** @description Decision 0016: the Session’s closing receipt, checked on the server (closing-receipt-v1 §6.1) against the copy as served now. Absent when the copy carries none, or when it can’t be decided here. */
4924
+ closing?: {
4925
+ /** @description true: the copy’s rounds are exactly the set the closing receipt signs; false: the closing receipt it carries does not verify or does not match (the copy is then unverified). */
4926
+ verified: boolean;
4927
+ /** @description The signed count of answers recorded, when verified; else null. */
4928
+ count: number | null;
4929
+ };
4820
4930
  };
4821
4931
  PersonalCopyLabelRequest: {
4822
4932
  item: string;
@@ -9701,7 +9811,7 @@ export interface operations {
9701
9811
  'application/json': components['schemas']['Error'];
9702
9812
  };
9703
9813
  };
9704
- /** @description The Session is already completed, is a display Session, or the idempotency key was used for a different request (`SESSION_COMPLETED`, `ACTION_NOT_ALLOWED` or `IDEMPOTENCY_CONFLICT`). */
9814
+ /** @description The Session is already completed (`SESSION_COMPLETED`); has already ended (`SESSION_ENDED`, with its terminal cause in `reason`: `final_expiry` when its link expired for good, `revoked` when the close of its Ask ended it); or is a display Session (`ACTION_NOT_ALLOWED`). The idempotency key was used for a different request (`IDEMPOTENCY_CONFLICT`). */
9705
9815
  409: {
9706
9816
  headers: {
9707
9817
  [name: string]: unknown;
@@ -11029,6 +11139,66 @@ export interface operations {
11029
11139
  };
11030
11140
  };
11031
11141
  };
11142
+ verifyClosingReceipt: {
11143
+ parameters: {
11144
+ query?: never;
11145
+ header?: never;
11146
+ path?: never;
11147
+ cookie?: never;
11148
+ };
11149
+ requestBody: {
11150
+ content: {
11151
+ 'application/json': components['schemas']['ClosingVerifyRequest'];
11152
+ };
11153
+ };
11154
+ responses: {
11155
+ /** @description The result of the closing check and how to present it. */
11156
+ 200: {
11157
+ headers: {
11158
+ [name: string]: unknown;
11159
+ };
11160
+ content: {
11161
+ 'application/json': components['schemas']['ClosingVerifyResponse'];
11162
+ };
11163
+ };
11164
+ /** @description The body is not a closing check (`INVALID_SCHEMA`). */
11165
+ 400: {
11166
+ headers: {
11167
+ [name: string]: unknown;
11168
+ };
11169
+ content: {
11170
+ 'application/json': components['schemas']['Error'];
11171
+ };
11172
+ };
11173
+ /** @description The body is too large (`PAYLOAD_TOO_LARGE`). */
11174
+ 413: {
11175
+ headers: {
11176
+ [name: string]: unknown;
11177
+ };
11178
+ content: {
11179
+ 'application/json': components['schemas']['Error'];
11180
+ };
11181
+ };
11182
+ /** @description Too many checks; try again after `Retry-After` (`RATE_LIMITED`). */
11183
+ 429: {
11184
+ headers: {
11185
+ [name: string]: unknown;
11186
+ };
11187
+ content: {
11188
+ 'application/json': components['schemas']['Error'];
11189
+ };
11190
+ };
11191
+ /** @description Receipts are not set up here, or the 2-second deadline passed and the connection is closed (`SERVICE_UNAVAILABLE`). */
11192
+ 503: {
11193
+ headers: {
11194
+ [name: string]: unknown;
11195
+ };
11196
+ content: {
11197
+ 'application/json': components['schemas']['Error'];
11198
+ };
11199
+ };
11200
+ };
11201
+ };
11032
11202
  listTargets: {
11033
11203
  parameters: {
11034
11204
  query?: never;
@@ -349,8 +349,29 @@ export function decodeEvents(value, expectedId) {
349
349
  // Event type), only where the deployment enables them.
350
350
  if (v.link_extensions !== undefined)
351
351
  linkExtensions(v.link_extensions);
352
+ // Decision 0016: the closing receipt is its own typed member beside the Events, never an Event
353
+ // and never a round's receipt. Only its shape is checked here; verifying it is verifyClosing's.
354
+ if (v.closing !== undefined)
355
+ closing(v.closing, v.events);
352
356
  return value;
353
357
  }
358
+ const closingPattern = new RegExp(`^cls_${ulid}$`);
359
+ const closingKeys = ['typ', 'closure_id', 'cause', 'terminal_event_id', 'accepted_rounds', 'receipt'];
360
+ function closing(value, events) {
361
+ const v = object(value);
362
+ if (Object.keys(v).length !== closingKeys.length || !closingKeys.every((k) => Object.hasOwn(v, k)))
363
+ protocol();
364
+ if (v.typ !== 'sess-closing-receipt+jwt')
365
+ protocol();
366
+ string(v.closure_id, closingPattern);
367
+ oneOf(v.cause, ['completed_by_owner', 'completed_by_ask_rule', 'final_expiry', 'revoked']);
368
+ if (v.terminal_event_id !== null)
369
+ string(v.terminal_event_id, eventPattern);
370
+ // Present only beside exactly the rounds it signs: its count is the Events' accepted answers.
371
+ if (integer(v.accepted_rounds) !== events.filter((e) => e.type === 'response.accepted').length)
372
+ protocol();
373
+ string(v.receipt, receiptPattern, 8192);
374
+ }
354
375
  function endpoint(value) {
355
376
  const v = object(value);
356
377
  string(v.id, new RegExp(`^whe_${ulid}$`));
@@ -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.5.0";
2
+ export declare const SDK_VERSION = "0.6.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.5.0';
2
+ export const SDK_VERSION = '0.6.0';
@@ -0,0 +1,82 @@
1
+ import { type DeepReadonly } from './json.js';
2
+ import { type ReceiptKeyResolver, type ReceiptKeySet } from './verify.js';
3
+ /** Protected `typ` of a closing receipt (closing-receipt-v1 §1); never a round receipt's. */
4
+ export declare const CLOSING_RECEIPT_TYP = "sess-closing-receipt+jwt";
5
+ /** A closing receipt is at most 8,192 bytes (its archival object's bound, closing-receipt-v1 §7). */
6
+ export declare const MAX_CLOSING_RECEIPT_BYTES = 8192;
7
+ declare const CAUSES: readonly ["completed_by_owner", "completed_by_ask_rule", "final_expiry", "revoked"];
8
+ /** How a Session ended, as its closing receipt signs it (closing-receipt-v1 §4). */
9
+ export type ClosingCause = (typeof CAUSES)[number];
10
+ /** A verified closing receipt's claims (closing-receipt-v1 §2): every member, no other, no `exp`. */
11
+ export interface ClosingReceiptClaims {
12
+ sess_closing_receipt: 1;
13
+ iss: string;
14
+ /** The Session's workspace, equal to `workspace_id`. */
15
+ aud: string;
16
+ /** The closure ID (`cls_…`). */
17
+ jti: string;
18
+ iat: number;
19
+ workspace_id: string;
20
+ session_id: string;
21
+ terminal: {
22
+ /** The Event that ended the Session; null only for `revoked`. */
23
+ event_id: string | null;
24
+ cause: ClosingCause;
25
+ /** `sess` for `final_expiry`, else `owner`: derived from the cause. */
26
+ actor_class: 'owner' | 'sess';
27
+ };
28
+ effective_end_at: string;
29
+ recorded_at: string;
30
+ issued_at: string;
31
+ /** Ordered by scope. Version 1 has `accepted_rounds`; a scope this release does not know is refused as newer. */
32
+ commitments: {
33
+ scope: string;
34
+ count: number;
35
+ commitment: string;
36
+ }[];
37
+ }
38
+ export interface VerifyClosingReceiptInput {
39
+ /** The closing receipt's compact JWS (`closing.receipt` beside a Session's Events). */
40
+ receipt: string;
41
+ /** Trusted protocol identity, independently configured. */
42
+ issuer: string;
43
+ /** Trusted workspace, never read from an unverified receipt. */
44
+ audience: string;
45
+ /** Optional bindings the receipt must name: the Session and the closure (`closing.closure_id`). */
46
+ expected?: {
47
+ sessionId?: string;
48
+ closureId?: string;
49
+ };
50
+ /**
51
+ * Optional: the accepted rounds' receipts, in their Event order. When given, the signed
52
+ * `accepted_rounds` count and commitment must be exactly these receipts' bytes, in this order;
53
+ * any other set is refused with `CLOSING_ROUNDS_MISMATCH`. Each round receipt is verified on its
54
+ * own (`receipts.verifyResponse`); this checks only that the set is the one the receipt signs.
55
+ */
56
+ rounds?: readonly string[];
57
+ keys?: ReceiptKeySet;
58
+ keyResolver?: ReceiptKeyResolver;
59
+ }
60
+ export interface VerifyClosingReceiptOptions {
61
+ signal?: AbortSignal;
62
+ }
63
+ /** The commitment over round receipts' exact bytes, in order (closing-receipt-v1 §3). */
64
+ export declare function closingCommitmentOf(receipts: readonly string[]): string;
65
+ /**
66
+ * Verifies a Session's closing receipt (closing-receipt-v1 §6) under the keys you trust for the
67
+ * issuer: exactly one of `keys` or `keyResolver`. Offline with explicit keys. It returns the
68
+ * verified claims, deeply frozen, or throws a `SessError`; nothing is returned with a refusal.
69
+ *
70
+ * In order: a compact JWS of at most 8,192 bytes; `alg` exactly `EdDSA`; a `kid` you trust;
71
+ * `typ` exactly `sess-closing-receipt+jwt` (a round receipt is refused here with
72
+ * `UNSUPPORTED_TYPE`); the header exactly `alg`, `kid` and `typ`; the Ed25519 signature; the
73
+ * issuer and workspace; the format version; the strict claims, with no `exp`; RFC 8785 canonical
74
+ * JSON; then the optional Session, closure and round-set bindings. A format version above 1, or a
75
+ * commitment scope this release does not know, is newer: kind `receipt_newer`, code
76
+ * `RECEIPT_NEWER`, never a verification failure.
77
+ *
78
+ * A valid closing receipt says only that these are the final accepted rounds Sess signed for the
79
+ * Session, and how it ended; it is not a receipt for any one answer.
80
+ */
81
+ export declare function verifyClosingReceipt(input: VerifyClosingReceiptInput, options?: VerifyClosingReceiptOptions): Promise<DeepReadonly<ClosingReceiptClaims>>;
82
+ export {};
@@ -0,0 +1,237 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { compactVerify, importJWK } from 'jose';
3
+ import { abortError, canonicalJson, checkedInstant, deepFreeze, exactKeys, isRecord, newerReceiptError, snapshotJson, verificationError, waitWithSignal, } from './json.js';
4
+ import { decodeSegment, identifier, trustedKeyLookup, validateKeySet, } from './verify.js';
5
+ /** Protected `typ` of a closing receipt (closing-receipt-v1 §1); never a round receipt's. */
6
+ export const CLOSING_RECEIPT_TYP = 'sess-closing-receipt+jwt';
7
+ /** A closing receipt is at most 8,192 bytes (its archival object's bound, closing-receipt-v1 §7). */
8
+ export const MAX_CLOSING_RECEIPT_BYTES = 8192;
9
+ /** The receipt key ID grammar (verify.ts, bundle.ts). */
10
+ const KID = /^[A-Za-z0-9._-]{1,64}$/;
11
+ /** A round receipt entering the commitment is at most 32,768 bytes (closing-receipt-v1 §3). */
12
+ const MAX_ROUND_RECEIPT_BYTES = 32_768;
13
+ const COMPACT_JWS = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
14
+ /** Three segments; an empty signature (`alg: none`) is refused by its algorithm, not its shape. */
15
+ const JWS_SHAPE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;
16
+ /** The one scope of version 1, and so the only one this release knows. */
17
+ const ACCEPTED_ROUNDS = 'accepted_rounds';
18
+ const SCOPE = /^[a-z][a-z0-9_]{0,63}$/;
19
+ /** A 32-byte SHA-256 as base64url without padding: 43 characters, the last canonical. */
20
+ const COMMITMENT = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
21
+ const COMMITMENTS_MAX = 16;
22
+ const ROUNDS_MAX = 100_000;
23
+ const DOMAIN = 'sess.closing-commitment/v1/accepted_rounds';
24
+ const CAUSES = ['completed_by_owner', 'completed_by_ask_rule', 'final_expiry', 'revoked'];
25
+ /** The commitment over round receipts' exact bytes, in order (closing-receipt-v1 §3). */
26
+ export function closingCommitmentOf(receipts) {
27
+ const hash = createHash('sha256');
28
+ hash.update(Buffer.from(DOMAIN, 'utf8'));
29
+ hash.update(Buffer.from([0]));
30
+ const count = Buffer.alloc(4);
31
+ count.writeUInt32BE(receipts.length);
32
+ hash.update(count);
33
+ for (const receipt of receipts)
34
+ hash.update(createHash('sha256').update(receipt, 'ascii').digest());
35
+ return hash.digest('base64url');
36
+ }
37
+ function actorClassOf(cause) {
38
+ return cause === 'final_expiry' ? 'sess' : 'owner';
39
+ }
40
+ const TOP = [
41
+ 'sess_closing_receipt',
42
+ 'iss',
43
+ 'aud',
44
+ 'jti',
45
+ 'iat',
46
+ 'workspace_id',
47
+ 'session_id',
48
+ 'terminal',
49
+ 'effective_end_at',
50
+ 'recorded_at',
51
+ 'issued_at',
52
+ 'commitments',
53
+ ];
54
+ const invalidClaims = () => verificationError('INVALID_CLAIMS', 'The closing receipt claims do not match the supported format.');
55
+ /** The commitments list's own rules; returns whether it carries a scope this release does not know. */
56
+ function unknownScope(value) {
57
+ if (!Array.isArray(value) || value.length < 1 || value.length > COMMITMENTS_MAX)
58
+ throw invalidClaims();
59
+ let previous = '';
60
+ let unknown = false;
61
+ let rounds = false;
62
+ for (const entry of value) {
63
+ if (!isRecord(entry) ||
64
+ !exactKeys(entry, ['scope', 'count', 'commitment']) ||
65
+ typeof entry.scope !== 'string' ||
66
+ !SCOPE.test(entry.scope) ||
67
+ entry.scope <= previous ||
68
+ !Number.isSafeInteger(entry.count) ||
69
+ entry.count < 0 ||
70
+ typeof entry.commitment !== 'string' ||
71
+ !COMMITMENT.test(entry.commitment))
72
+ throw invalidClaims();
73
+ previous = entry.scope;
74
+ if (entry.scope === ACCEPTED_ROUNDS) {
75
+ if (entry.count < 1 || entry.count > ROUNDS_MAX)
76
+ throw invalidClaims();
77
+ rounds = true;
78
+ }
79
+ else
80
+ unknown = true;
81
+ }
82
+ if (!rounds)
83
+ throw invalidClaims();
84
+ return unknown;
85
+ }
86
+ /** Strict claims (closing-receipt-v1 §6); the format version is decided by the caller first. */
87
+ function claimsOf(raw) {
88
+ if (!exactKeys(raw, TOP))
89
+ throw invalidClaims();
90
+ const newer = unknownScope(raw.commitments);
91
+ const t = raw.terminal;
92
+ const effective = checkedInstant(raw.effective_end_at);
93
+ const recorded = checkedInstant(raw.recorded_at);
94
+ const issued = checkedInstant(raw.issued_at);
95
+ if (![raw.iss, raw.aud, raw.jti, raw.workspace_id, raw.session_id].every(identifier) ||
96
+ raw.aud !== raw.workspace_id ||
97
+ !Number.isSafeInteger(raw.iat) ||
98
+ effective === undefined ||
99
+ recorded === undefined ||
100
+ issued === undefined ||
101
+ effective > recorded ||
102
+ recorded > issued ||
103
+ Math.floor(issued / 1000) !== raw.iat ||
104
+ !isRecord(t) ||
105
+ !exactKeys(t, ['event_id', 'cause', 'actor_class']) ||
106
+ typeof t.cause !== 'string' ||
107
+ !CAUSES.includes(t.cause) ||
108
+ t.actor_class !== actorClassOf(t.cause) ||
109
+ (t.cause === 'revoked' ? t.event_id !== null : !identifier(t.event_id)))
110
+ throw invalidClaims();
111
+ return { claims: raw, newer };
112
+ }
113
+ /**
114
+ * Verifies a Session's closing receipt (closing-receipt-v1 §6) under the keys you trust for the
115
+ * issuer: exactly one of `keys` or `keyResolver`. Offline with explicit keys. It returns the
116
+ * verified claims, deeply frozen, or throws a `SessError`; nothing is returned with a refusal.
117
+ *
118
+ * In order: a compact JWS of at most 8,192 bytes; `alg` exactly `EdDSA`; a `kid` you trust;
119
+ * `typ` exactly `sess-closing-receipt+jwt` (a round receipt is refused here with
120
+ * `UNSUPPORTED_TYPE`); the header exactly `alg`, `kid` and `typ`; the Ed25519 signature; the
121
+ * issuer and workspace; the format version; the strict claims, with no `exp`; RFC 8785 canonical
122
+ * JSON; then the optional Session, closure and round-set bindings. A format version above 1, or a
123
+ * commitment scope this release does not know, is newer: kind `receipt_newer`, code
124
+ * `RECEIPT_NEWER`, never a verification failure.
125
+ *
126
+ * A valid closing receipt says only that these are the final accepted rounds Sess signed for the
127
+ * Session, and how it ended; it is not a receipt for any one answer.
128
+ */
129
+ export async function verifyClosingReceipt(input, options = {}) {
130
+ // Capture all caller-owned data before a resolver can yield control.
131
+ const receipt = input?.receipt;
132
+ if (typeof receipt !== 'string' || receipt.length > MAX_CLOSING_RECEIPT_BYTES || !JWS_SHAPE.test(receipt))
133
+ throw verificationError('MALFORMED_RECEIPT', 'The closing receipt is malformed or exceeds its 8,192-byte limit.');
134
+ const issuer = input.issuer;
135
+ const audience = input.audience;
136
+ if (!identifier(issuer) || !identifier(audience))
137
+ throw verificationError('VERIFICATION_CONTEXT_MISSING', 'A trusted issuer and expected resource workspace are required.');
138
+ const expected = input.expected === undefined ? {} : snapshotJson(input.expected);
139
+ const rounds = input.rounds === undefined ? undefined : snapshotJson(input.rounds);
140
+ if (!isRecord(expected) ||
141
+ !exactKeys(expected, ['sessionId', 'closureId'].filter((k) => Object.hasOwn(expected, k))) ||
142
+ (expected.sessionId !== undefined && !identifier(expected.sessionId)) ||
143
+ (expected.closureId !== undefined && !identifier(expected.closureId)) ||
144
+ (rounds !== undefined &&
145
+ (!Array.isArray(rounds) ||
146
+ rounds.length < 1 ||
147
+ rounds.length > ROUNDS_MAX ||
148
+ rounds.some((r) => typeof r !== 'string' || r.length > MAX_ROUND_RECEIPT_BYTES || !COMPACT_JWS.test(r)))))
149
+ throw verificationError('INVALID_VERIFICATION_INPUT', 'Expected bindings must be identifiers, and rounds one or more compact round receipts.');
150
+ const resolver = input.keyResolver;
151
+ const keys = input.keys === undefined ? undefined : validateKeySet(input.keys);
152
+ if ((keys === undefined) === (resolver === undefined) ||
153
+ (resolver !== undefined && typeof resolver !== 'function'))
154
+ throw verificationError('VERIFICATION_CONTEXT_MISSING', 'Provide exactly one trusted public key set or key resolver.');
155
+ const signal = options.signal;
156
+ if (signal?.aborted)
157
+ throw abortError(signal);
158
+ const parts = receipt.split('.');
159
+ let header;
160
+ const headerText = decodeSegment(parts[0]);
161
+ try {
162
+ header = JSON.parse(headerText);
163
+ }
164
+ catch {
165
+ throw verificationError('MALFORMED_RECEIPT', 'The closing receipt protected header is not JSON.');
166
+ }
167
+ if (!isRecord(header))
168
+ throw verificationError('MALFORMED_RECEIPT', 'The closing receipt protected header is not JSON.');
169
+ if (header.alg !== 'EdDSA')
170
+ throw verificationError('UNSUPPORTED_ALGORITHM', 'The closing receipt must use the supported EdDSA algorithm.');
171
+ if (typeof header.kid !== 'string' || header.kid.length === 0)
172
+ throw verificationError('UNSUPPORTED_HEADER', 'The closing receipt names no signing key.');
173
+ // The whole header is checked before any key is looked up: an application's
174
+ // key resolver only ever sees a key ID of the receipt key grammar from a header of exactly
175
+ // {alg, kid, typ}, each a string and each once (six string tokens are then three names and
176
+ // three values).
177
+ const strings = headerText.match(/"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/g);
178
+ if (!exactKeys(header, ['alg', 'kid', 'typ']) ||
179
+ typeof header.typ !== 'string' ||
180
+ strings?.length !== 6 ||
181
+ !KID.test(header.kid))
182
+ throw verificationError('UNSUPPORTED_HEADER', 'The closing receipt protected header has missing or unsupported fields.');
183
+ const kid = header.kid;
184
+ const publicKey = await trustedKeyLookup(keys, resolver, issuer, signal)(kid);
185
+ if (!publicKey)
186
+ throw verificationError('UNKNOWN_KEY_ID', 'The closing receipt signing key is not in the trusted key set.');
187
+ // A round receipt (or any other format) offered as a closing receipt stops here: after the key,
188
+ // as the specification's first-failure order has it (closing-receipt-v1 §6: unknown_kid, then
189
+ // type) and Sess's own verifier does.
190
+ if (header.typ !== CLOSING_RECEIPT_TYP)
191
+ throw verificationError('UNSUPPORTED_TYPE', 'This is not a closing receipt.');
192
+ try {
193
+ const key = await waitWithSignal(importJWK({ ...publicKey, key_ops: ['verify'], ext: false }, 'EdDSA'), signal);
194
+ await waitWithSignal(compactVerify(receipt, key, { algorithms: ['EdDSA'] }), signal);
195
+ }
196
+ catch {
197
+ if (signal?.aborted)
198
+ throw abortError(signal);
199
+ throw verificationError('INVALID_SIGNATURE', 'The closing receipt signature did not verify with the trusted Ed25519 key.');
200
+ }
201
+ const payloadText = decodeSegment(parts[1]);
202
+ let parsed;
203
+ try {
204
+ parsed = JSON.parse(payloadText);
205
+ }
206
+ catch {
207
+ throw verificationError('MALFORMED_RECEIPT', 'The closing receipt payload is not JSON.');
208
+ }
209
+ const raw = snapshotJson(parsed);
210
+ if (!isRecord(raw))
211
+ throw verificationError('MALFORMED_RECEIPT', 'The closing receipt payload is not a JSON object.');
212
+ if (raw.iss !== issuer)
213
+ throw verificationError('ISSUER_MISMATCH', 'The closing receipt issuer does not match the trusted issuer.');
214
+ if (raw.aud !== audience)
215
+ throw verificationError('AUDIENCE_MISMATCH', 'The closing receipt does not belong to the expected resource workspace.');
216
+ const version = raw.sess_closing_receipt;
217
+ // A later version may constrain what version 1 would release: nothing is released.
218
+ if (Number.isSafeInteger(version) && version > 1)
219
+ throw newerReceiptError();
220
+ if (version !== 1)
221
+ throw verificationError('UNSUPPORTED_RECEIPT_VERSION', 'The closing receipt format version is not supported (version 1 is).');
222
+ const { claims, newer } = claimsOf(raw);
223
+ if (canonicalJson(claims) !== payloadText)
224
+ throw verificationError('NON_CANONICAL_PAYLOAD', 'The signed closing receipt payload must be RFC 8785 canonical JSON.');
225
+ // Only after every other check: an unknown signed scope makes the whole receipt newer.
226
+ if (newer)
227
+ throw newerReceiptError();
228
+ if ((expected.sessionId !== undefined && claims.session_id !== expected.sessionId) ||
229
+ (expected.closureId !== undefined && claims.jti !== expected.closureId))
230
+ throw verificationError('RECORD_BINDING_MISMATCH', 'The closing receipt does not name the expected Session and closure.');
231
+ if (rounds !== undefined) {
232
+ const signed = claims.commitments.find((c) => c.scope === ACCEPTED_ROUNDS);
233
+ if (signed.count !== rounds.length || signed.commitment !== closingCommitmentOf(rounds))
234
+ throw verificationError('CLOSING_ROUNDS_MISMATCH', 'These round receipts are not exactly the accepted rounds the closing receipt signs.');
235
+ }
236
+ return deepFreeze(claims);
237
+ }
@@ -6,4 +6,6 @@ export type { ReceiptClaims, ReceiptClaimsV1, ReceiptClaimsV2, ReceiptPublicKey,
6
6
  export type { DeepReadonly } from './json.js';
7
7
  export { verifyDecisionBundle, BUNDLE_LIMITS } from './bundle.js';
8
8
  export type { BundleContextField, BundleJwk, BundleRejection, DecisionBundle, DecisionBundleV1, DecisionBundleV2, DecisionBundleVerification, ExpectedBundleContext, VerifiedReceiptSummary, VerifyDecisionBundleOptions, } from './bundle.js';
9
- export type { ReceiptResource, VerifyResponseInput, VerifiedResponse, VerificationRequestOptions, } from './resource.js';
9
+ export type { ReceiptResource, VerifyClosingInput, VerifiedClosing, VerifyResponseInput, VerifiedResponse, VerificationRequestOptions, } from './resource.js';
10
+ export { verifyClosingReceipt } from './closing.js';
11
+ export type { ClosingCause, ClosingReceiptClaims, VerifyClosingReceiptInput, VerifyClosingReceiptOptions, } from './closing.js';
@@ -1,3 +1,4 @@
1
1
  export { verifyDecisionReceipt, verifyRendererIdentities } from './verify.js';
2
2
  export { BUNDLED_RENDERER_IDENTITIES, BUNDLED_RENDERER_LIST, newerRendererList } from './renderers.js';
3
3
  export { verifyDecisionBundle, BUNDLE_LIMITS } from './bundle.js';
4
+ export { verifyClosingReceipt } from './closing.js';
@@ -1,4 +1,5 @@
1
- import type { AcceptedResponse, ApiResult, InteractiveSurfaceRevision, Session, SurfaceRevision, VersionedResult } from '../types.js';
1
+ import type { AcceptedResponse, ApiResult, InteractiveSurfaceRevision, Session, SessionClosing, SessionEvents, SurfaceRevision, VersionedResult } from '../types.js';
2
+ import { type ClosingReceiptClaims } from './closing.js';
2
3
  import { type DeepReadonly } from './json.js';
3
4
  import { type ReceiptClaims } from './verify.js';
4
5
  export interface VerificationRequestOptions {
@@ -18,6 +19,18 @@ interface Context {
18
19
  publicGet: (path: string, options: VerificationRequestOptions & {
19
20
  maxResponseBytes: number;
20
21
  }) => Promise<ApiResult<unknown>>;
22
+ /** The Session's Event log, read for closing receipt verification. */
23
+ listEvents?: (id: string, options: VerificationRequestOptions) => Promise<ApiResult<SessionEvents>>;
24
+ }
25
+ export interface VerifyClosingInput {
26
+ sessionId: string;
27
+ /** `closing` from `sessions.listEvents()`. */
28
+ closing: SessionClosing;
29
+ expectedWorkspaceId?: string;
30
+ }
31
+ export interface VerifiedClosing {
32
+ claims: DeepReadonly<ClosingReceiptClaims>;
33
+ closing: DeepReadonly<SessionClosing>;
21
34
  }
22
35
  export interface VerifyResponseInput {
23
36
  sessionId: string;
@@ -32,6 +45,14 @@ export interface VerifiedResponse {
32
45
  export interface ReceiptResource {
33
46
  /** Full receipt verification with authorized current context and exact immutable revision. */
34
47
  verifyResponse(input: VerifyResponseInput, options?: VerificationRequestOptions): Promise<DeepReadonly<VerifiedResponse>>;
48
+ /**
49
+ * Verifies a Session's closing receipt against the authorized Event log: the supplied `closing`
50
+ * must be the one Sess serves now, its receipt must verify under the issuer's published keys
51
+ * (closing-receipt-v1), name this Session, closure, cause, end and count, and commit to exactly
52
+ * the served accepted answers' receipts, in order. Each answer's own receipt is verified with
53
+ * `verifyResponse`.
54
+ */
55
+ verifyClosing(input: VerifyClosingInput, options?: VerificationRequestOptions): Promise<DeepReadonly<VerifiedClosing>>;
35
56
  }
36
57
  /** Internal bridge: all HTTP is supplied by the client's ordinary bounded transport. */
37
58
  export declare function createReceiptResource(context: Context): ReceiptResource;
@@ -1,5 +1,6 @@
1
1
  import { SessError } from '../errors.js';
2
2
  import { isInteractiveSurface } from '../types.js';
3
+ import { verifyClosingReceipt } from './closing.js';
3
4
  import { ReceiptKeyCache } from './key-cache.js';
4
5
  import { abortError, canonicalJson, deepFreeze, snapshotJson, verificationError, waitWithSignal, } from './json.js';
5
6
  import { BUNDLED_RENDERER_IDENTITIES, MAX_RENDERER_IDENTITIES_BYTES, RENDERER_IDENTITIES_PATH, } from './renderers.js';
@@ -18,6 +19,43 @@ function namedRenderer(receipt) {
18
19
  return undefined;
19
20
  }
20
21
  }
22
+ /** One operation's overall deadline and cancellation, as each verification method uses. */
23
+ function deadline(budget, options) {
24
+ if (!Number.isSafeInteger(budget) || budget <= 0 || budget > 2_147_483_647) {
25
+ throw new SessError('configuration', 'Receipt verification requires a finite positive operation timeout.');
26
+ }
27
+ const { timeoutMs, maxRetries, signal: originalSignal } = options;
28
+ if (originalSignal?.aborted)
29
+ throw abortError(originalSignal);
30
+ const controller = new AbortController();
31
+ const abort = () => controller.abort(originalSignal?.reason);
32
+ originalSignal?.addEventListener('abort', abort, { once: true });
33
+ const started = performance.now();
34
+ const expired = () => controller.abort(new SessError('timeout', 'Receipt verification exceeded its overall deadline.'));
35
+ const timer = setTimeout(expired, budget);
36
+ return {
37
+ signal: controller.signal,
38
+ requestOptions() {
39
+ if (controller.signal.aborted)
40
+ throw abortError(controller.signal);
41
+ const remaining = Math.floor(budget - (performance.now() - started));
42
+ if (remaining <= 0) {
43
+ expired();
44
+ throw abortError(controller.signal);
45
+ }
46
+ return {
47
+ signal: controller.signal,
48
+ operationTimeoutMs: remaining,
49
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
50
+ ...(maxRetries !== undefined ? { maxRetries } : {}),
51
+ };
52
+ },
53
+ done() {
54
+ clearTimeout(timer);
55
+ originalSignal?.removeEventListener('abort', abort);
56
+ },
57
+ };
58
+ }
21
59
  /** Internal bridge: all HTTP is supplied by the client's ordinary bounded transport. */
22
60
  export function createReceiptResource(context) {
23
61
  // Copy configuration/callbacks; mutation of an application-owned config object has no effect.
@@ -27,6 +65,7 @@ export function createReceiptResource(context) {
27
65
  const retrieve = context.retrieveSession;
28
66
  const surfaceRead = context.retrieveSurface;
29
67
  const publicGet = context.publicGet;
68
+ const eventsRead = context.listEvents;
30
69
  const keyPath = '/.well-known/sess-receipt-keys.json';
31
70
  const cache = new ReceiptKeyCache({
32
71
  issuer,
@@ -144,5 +183,57 @@ export function createReceiptResource(context) {
144
183
  originalSignal?.removeEventListener('abort', abort);
145
184
  }
146
185
  },
186
+ async verifyClosing(input, options = {}) {
187
+ const sessionId = input?.sessionId;
188
+ const supplied = input?.closing == null ? undefined : snapshotJson(input.closing);
189
+ const requestedWorkspace = input?.expectedWorkspaceId;
190
+ const { timeoutMs, maxRetries } = options;
191
+ if (typeof eventsRead !== 'function')
192
+ throw new SessError('configuration', 'Closing receipt verification needs the Session Event log.');
193
+ if (supplied === undefined || typeof supplied.receipt !== 'string')
194
+ throw verificationError('CLOSING_RECEIPT_UNAVAILABLE', 'This Session has no closing receipt yet: it has not ended with an accepted answer, or its receipt is not signed yet.');
195
+ if (requestedWorkspace && configuredWorkspace && requestedWorkspace !== configuredWorkspace)
196
+ throw verificationError('AUDIENCE_MISMATCH', 'The supplied workspace differs from this client’s trusted workspace.');
197
+ const run = deadline(options.operationTimeoutMs ?? defaultBudget, options);
198
+ try {
199
+ const read = snapshotJson(await waitWithSignal(eventsRead(sessionId, run.requestOptions()), run.signal));
200
+ const trustedWorkspace = requestedWorkspace ?? configuredWorkspace ?? read.meta.workspaceId;
201
+ if (typeof trustedWorkspace !== 'string' || trustedWorkspace.length === 0)
202
+ throw verificationError('VERIFICATION_CONTEXT_MISSING', 'Provide expectedWorkspaceId or use a runtime that returns authenticated Sess-Workspace-Id context.');
203
+ if (read.meta.workspaceId !== undefined && read.meta.workspaceId !== trustedWorkspace)
204
+ throw verificationError('AUDIENCE_MISMATCH', 'The authorized resource belongs to a different workspace.');
205
+ const served = read.data.closing;
206
+ if (read.data.id !== sessionId ||
207
+ served === undefined ||
208
+ canonicalJson(served) !== canonicalJson(supplied))
209
+ throw verificationError('RECORD_BINDING_MISMATCH', 'The supplied closing receipt is not the one the authorized Event log carries.');
210
+ const rounds = read.data.events
211
+ .filter((event) => event.type === 'response.accepted')
212
+ .map((event) => event.receipt);
213
+ if (rounds.some((receipt) => typeof receipt !== 'string'))
214
+ throw verificationError('CLOSING_ROUNDS_MISMATCH', 'An accepted answer in the Event log has no receipt, so it cannot match the closing receipt.');
215
+ const claims = await verifyClosingReceipt({
216
+ receipt: served.receipt,
217
+ issuer,
218
+ audience: trustedWorkspace,
219
+ expected: { sessionId, closureId: served.closure_id },
220
+ rounds: rounds,
221
+ keyResolver: (resolverContext) => cache.resolve({
222
+ ...resolverContext,
223
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
224
+ ...(maxRetries !== undefined ? { maxRetries } : {}),
225
+ }),
226
+ }, { signal: run.signal });
227
+ // The facts served beside the receipt are the ones it signs.
228
+ if (claims.terminal.cause !== served.cause ||
229
+ claims.terminal.event_id !== served.terminal_event_id ||
230
+ claims.commitments.find((c) => c.scope === 'accepted_rounds')?.count !== served.accepted_rounds)
231
+ throw verificationError('RECORD_BINDING_MISMATCH', 'The closing receipt does not sign the cause, end and count served beside it.');
232
+ return deepFreeze({ claims, closing: served });
233
+ }
234
+ finally {
235
+ run.done();
236
+ }
237
+ },
147
238
  });
148
239
  }
@@ -114,8 +114,10 @@ export interface VerifyDecisionReceiptOptions {
114
114
  issuedAtToleranceSeconds?: number;
115
115
  signal?: AbortSignal;
116
116
  }
117
+ export declare function identifier(value: unknown): value is string;
117
118
  /** Validates and copies the whole set, not merely the key selected by the token. */
118
119
  export declare function validateKeySet(raw: unknown): ReceiptKeySet;
120
+ export declare function decodeSegment(segment: string): string;
119
121
  /**
120
122
  * Fully verifies a receipt and its exact accepted record. Explicit keys make this function
121
123
  * entirely offline. A valid receipt attests the accepted record, not business authority.
@@ -133,6 +135,8 @@ export declare function validateKeySet(raw: unknown): ReceiptKeySet;
133
135
  * `receipt_newer` and code `RECEIPT_NEWER`, never as a verification failure; nothing is returned.
134
136
  */
135
137
  export declare function verifyDecisionReceipt(input: VerifyDecisionReceiptInput, options?: VerifyDecisionReceiptOptions): Promise<DeepReadonly<ReceiptClaims>>;
138
+ /** Resolves a kid to a trusted key: from the explicit set, or the trusted resolver (validated). */
139
+ export declare function trustedKeyLookup(keys: ReceiptKeySet | undefined, resolver: ReceiptKeyResolver | undefined, issuer: string, signal: AbortSignal | undefined): (kid: string) => Promise<ReceiptPublicKey | undefined>;
136
140
  /**
137
141
  * Verifies an issuer's signed renderer-identity list (Decision 0009 Amendment 13) under the keys
138
142
  * you trust for that issuer: exactly one of `keys` or `keyResolver`. Offline with explicit keys.
@@ -14,7 +14,7 @@ const DIGEST = /^sha256:[0-9a-f]{64}$/;
14
14
  const RECEIPT_TYP_V1 = 'sess-receipt+jwt';
15
15
  /** Protected `typ` of a receipt v2 (receipt-v2); it names version 2 only. */
16
16
  const RECEIPT_TYP_V2 = 'sess-receipt-2+jwt';
17
- function identifier(value) {
17
+ export function identifier(value) {
18
18
  return (typeof value === 'string' &&
19
19
  value.length > 0 &&
20
20
  value.length <= 200 &&
@@ -56,7 +56,7 @@ export function validateKeySet(raw) {
56
56
  }
57
57
  return deepFreeze(value);
58
58
  }
59
- function decodeSegment(segment) {
59
+ export function decodeSegment(segment) {
60
60
  const bytes = Buffer.from(segment, 'base64url');
61
61
  if (bytes.toString('base64url') !== segment)
62
62
  throw verificationError('MALFORMED_RECEIPT', 'The receipt is not canonical base64url.');
@@ -363,7 +363,7 @@ function checkRevisionEnvelope(claims, supplied) {
363
363
  throw verificationError('REVISION_ENVELOPE_MISMATCH', 'The revision envelope names another Session, revision, Surface or renderer.');
364
364
  }
365
365
  /** Resolves a kid to a trusted key: from the explicit set, or the trusted resolver (validated). */
366
- function trustedKeyLookup(keys, resolver, issuer, signal) {
366
+ export function trustedKeyLookup(keys, resolver, issuer, signal) {
367
367
  return async (kid) => {
368
368
  let trusted = keys;
369
369
  if (!trusted && resolver) {
package/dist/types.d.ts CHANGED
@@ -33,8 +33,16 @@ export type InteractiveSurfaceRevision = Schemas['InteractiveSurfaceResponse'];
33
33
  export type SurfaceRevision = DisplaySurfaceRevision | InteractiveSurfaceRevision;
34
34
  /** One Event of `GET /v1/sessions/{id}/events`; `revision_envelope` on `response.accepted` only. */
35
35
  export type SessionEvent = GeneratedSessionEvents['events'][number] & RevisionEnvelopeMember;
36
- export type SessionEvents = Omit<GeneratedSessionEvents, 'events'> & {
36
+ /**
37
+ * The Session's closing receipt (`closing` on `GET /v1/sessions/{id}/events`): beside the Events,
38
+ * never one of them and never a round's `receipt`. Present only once the Session has ended with at
39
+ * least one accepted answer and the Events carry exactly the rounds it signs. Verify it with
40
+ * `receipts.verifyClosing()` or `verifyClosingReceipt`, never as a receipt for one answer.
41
+ */
42
+ export type SessionClosing = Schemas['SessionClosing'];
43
+ export type SessionEvents = Omit<GeneratedSessionEvents, 'events' | 'closing'> & {
37
44
  events: SessionEvent[];
45
+ closing?: SessionClosing;
38
46
  };
39
47
  /**
40
48
  * The Sess link's state at the time of a Session read (Decision 0009 Amendment 10): `live` takes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sess.si/sdk",
3
- "version": "0.5.0",
3
+ "version": "0.6.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",