@sess.si/sdk 0.3.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,42 @@
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
+
3
40
  ## 0.3.0 — 2026-11-08
4
41
 
5
42
  - Receipt v2: `verifyDecisionReceipt` and `receipts.verifyResponse()` verify receipts of type
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.3.0
17
+ npm install --save-exact @sess.si/sdk@0.4.0
18
18
  ```
19
19
 
20
20
  ## Ask a person
@@ -120,10 +120,10 @@ async function askShort(question: string) {
120
120
  }
121
121
  ```
122
122
 
123
- **Release status:** `0.3.0` is the current release, served under the `latest` dist-tag. It
124
- verifies receipt v2, which commits to the record of the round it answered, and still verifies
125
- receipt v1. `next` stays at the last release candidate,
126
- `0.1.0-rc.10`. The [changelog](CHANGELOG.md) describes each version; `npm view @sess.si/sdk dist-tags` shows what the registry serves now.
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.
127
127
 
128
128
  ## Commerce
129
129
 
@@ -243,13 +243,14 @@ exact Surface and input, and the issuer's public keys. Check it on your own comp
243
243
  trust (never the keys inside the bundle):
244
244
 
245
245
  ```sh
246
- npx -p @sess.si/sdk@0.3.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
247
247
  ```
248
248
 
249
- The `sess` command first ships in `0.1.0-rc.5`; any later version, `0.3.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.
250
250
 
251
251
  You'll see `Valid decision bundle.` and what was accepted, when, on which revision; or `Invalid`
252
- 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
253
254
  result. Nothing is sent anywhere. In code, use `verifyDecisionBundle` from `@sess.si/sdk/receipts`
254
255
  ([Security](docs/security.md#decision-bundles)). Formats: [receipt-v1](docs/spec/receipt-v1.md) and
255
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
  }
@@ -184,7 +188,6 @@ function parse(argv) {
184
188
  const REASON_TEXT = {
185
189
  malformed: 'the file is not a decision bundle (bundle-v1 or bundle-v2)',
186
190
  oversized: 'the bundle exceeds a decision bundle size bound',
187
- unsupported_version: 'the bundle uses a later format version',
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',
@@ -226,6 +229,10 @@ function summary(r, renderer) {
226
229
  if (renderer)
227
230
  row('Renderer', `${safe(c.surface.renderer_version)} (listed)`);
228
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
+ }
229
236
  else {
230
237
  lines.push(`Invalid decision bundle: ${r.reason}`);
231
238
  lines.push(` ${REASON_TEXT[r.reason ?? ''] ?? ''}`);
@@ -313,7 +320,7 @@ export async function runCli(argv, io) {
313
320
  result = { ...result, valid: false, reason: 'renderer' };
314
321
  }
315
322
  io.stdout(parsed.json ? safeJson(renderer ? { ...result, renderer } : result) : summary(result, renderer));
316
- return result.valid ? EXIT.valid : EXIT.invalid;
323
+ return result.valid ? EXIT.valid : result.reason === 'unsupported_version' ? EXIT.newer : EXIT.invalid;
317
324
  }
318
325
  catch (e) {
319
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;
@@ -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.3.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.3.0';
2
+ export const SDK_VERSION = '0.4.0';
@@ -1,4 +1,4 @@
1
- import { type RevisionEnvelope } from './envelope.js';
1
+ import { type RevisionEnvelopeFull } from './envelope.js';
2
2
  import { type ReceiptKeySet } from './verify.js';
3
3
  /** Bounds of a bundle (bundle-v1 §4). A bundle beyond any of them is `oversized`. */
4
4
  export declare const BUNDLE_LIMITS: Readonly<{
@@ -31,8 +31,8 @@ export type DecisionBundle = DecisionBundleV1 | DecisionBundleV2;
31
31
  /** A bundle-v2 object: bundle-v1's members plus `revision_envelope`, exactly. */
32
32
  export interface DecisionBundleV2 extends Omit<DecisionBundleV1, 'version'> {
33
33
  version: 2;
34
- /** The revision envelope the receipt v2 commits to (receipt-v2 §2). */
35
- revision_envelope: RevisionEnvelope;
34
+ /** The revision envelope the receipt v2 commits to (receipt-v2 §2), in its full form. */
35
+ revision_envelope: RevisionEnvelopeFull;
36
36
  }
37
37
  /** A bundle-v1 object: exactly these members. */
38
38
  export interface DecisionBundleV1 {
@@ -53,9 +53,14 @@ export interface DecisionBundleV1 {
53
53
  /** Receipt rejection codes (receipt-v1 §6; receipt-v2 §7 adds `revision`). */
54
54
  type ReceiptRejection = 'malformed' | 'algorithm' | 'missing_kid' | 'unknown_kid' | 'type' | 'signature' | 'issuer' | 'audience' | 'expired' | 'claims'
55
55
  /** Receipt v2: the revision envelope is missing, malformed, or of another digest or record. */
56
- | 'revision';
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';
57
62
  /** Why a bundle is invalid: the first check that failed (bundle-v1 §5, bundle-v2 §5). */
58
- export type BundleRejection = 'malformed' | 'oversized' | 'unsupported_version' | 'receipt_malformed' | Exclude<ReceiptRejection, 'malformed'> | 'not_yet_valid' | 'surface_mismatch' | 'input_mismatch' | 'context_mismatch';
63
+ export type BundleRejection = 'malformed' | 'oversized' | 'unsupported_version' | 'receipt_malformed' | Exclude<ReceiptRejection, 'malformed' | 'newer'> | 'not_yet_valid' | 'surface_mismatch' | 'input_mismatch' | 'context_mismatch';
59
64
  /** Application context from the caller's trusted configuration, never from the bundle. */
60
65
  export interface ExpectedBundleContext {
61
66
  /** The recipient the caller expects (the receipt's `aud`: the Session's workspace). */
@@ -103,11 +108,12 @@ export interface VerifiedReceiptSummary {
103
108
  accepted_at: string;
104
109
  expires_at: string;
105
110
  /**
106
- * bundle-v2 only: the verified revision envelope (absent for a bundle-v1 result). Its
107
- * `key_label` and `published_at` say which of the workspace's API keys published the revision,
108
- * under which label, and when; a face shows a publisher only from here.
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.
109
115
  */
110
- revision_envelope?: RevisionEnvelope;
116
+ revision_envelope?: RevisionEnvelopeFull;
111
117
  }
112
118
  /** The result every face reports (bundle-v1 §6, bundle-v2 §6). JSON-serializable. */
113
119
  export interface DecisionBundleVerification {
@@ -11,8 +11,8 @@
11
11
  // trusted-key validation, revision-envelope reading and canonical JSON helpers.
12
12
  import { createHash } from 'node:crypto';
13
13
  import { decodeProtectedHeader, errors, importJWK, jwtVerify } from 'jose';
14
- import { parseRevisionEnvelope, revisionHash } from './envelope.js';
15
- 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';
16
16
  import { validateKeySet } from './verify.js';
17
17
  const BUNDLE_TYPE = 'sess.decision-bundle';
18
18
  const BUNDLE_VERSION = 1;
@@ -97,6 +97,7 @@ function receiptV1Claims(p, version) {
97
97
  exactKeys(a, ['id', 'label', 'summary']) &&
98
98
  nonEmpty(a.id) &&
99
99
  nonEmpty(a.label) &&
100
+ (version === 1 || [...a.label].length <= RECEIPT_V2_ACTION_LABEL_MAX) &&
100
101
  typeof a.summary === 'string' &&
101
102
  isRecord(act) &&
102
103
  exactKeys(act, ['assurance', 'subject']) &&
@@ -130,6 +131,10 @@ async function verifyReceiptV1(jws, keys, options, envelope) {
130
131
  catch {
131
132
  throw new ReceiptV1Failure('malformed');
132
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');
133
138
  if (header.alg !== RECEIPT_ALG)
134
139
  throw new ReceiptV1Failure('algorithm');
135
140
  if (typeof header.kid !== 'string' || header.kid.length === 0)
@@ -173,7 +178,10 @@ async function verifyReceiptV1(jws, keys, options, envelope) {
173
178
  if (`sha256:${createHash('sha256').update(signed).digest('hex')}` !== jsonDigest(claims))
174
179
  throw new ReceiptV1Failure('claims');
175
180
  if (options.version === 2) {
176
- // receipt-v2 §7: missing or null, malformed, of another digest, or of another record.
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');
177
185
  const parsed = parseRevisionEnvelope(envelope);
178
186
  if (parsed === null ||
179
187
  revisionHash(parsed) !== claims.surface.revision_hash ||
@@ -412,8 +420,17 @@ export async function verifyDecisionBundle(bundle, options) {
412
420
  return invalid('audience', {
413
421
  context: { status: 'mismatch', checked: supplied, mismatches: ['audience'] },
414
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');
415
427
  return invalid(e.code === 'malformed' ? 'receipt_malformed' : e.code);
416
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');
417
434
  if (claims.iat > Math.floor(now.getTime() / 1000) + CLOCK_TOLERANCE_S)
418
435
  return invalid('not_yet_valid');
419
436
  if (claims.surface.hash !== jsonDigest(b.content.surface))
@@ -452,7 +469,7 @@ export async function verifyDecisionBundle(bundle, options) {
452
469
  accepted_at: claims.accepted_at,
453
470
  expires_at: new Date(claims.exp * 1000).toISOString(),
454
471
  // bundle-v2: the envelope as verified (its digest is the receipt's revision_hash).
455
- ...(v2 ? { revision_envelope: parseRevisionEnvelope(envelope) } : {}),
472
+ ...(verifiedEnvelope ? { revision_envelope: verifiedEnvelope } : {}),
456
473
  },
457
474
  };
458
475
  }
@@ -1,30 +1,75 @@
1
- /** The envelope's own schema version (`sess_revision`). */
2
- export declare const REVISION_ENVELOPE_VERSION = 1;
1
+ /** The envelope's own schema version (`sess_revision`); a higher one is newer. */
2
+ export declare const REVISION_ENVELOPE_VERSION = 2;
3
+ /** The registered address the Session started from, as at Start. */
4
+ export interface EnvelopeAgentTarget {
5
+ /** `tgt_…` */
6
+ id: string;
7
+ /** The Target's version bound at Start, a whole number from 1. */
8
+ version: number;
9
+ /** The address, `sess.si/a/{name}`: an owner-chosen public name, not a verified identity. */
10
+ name: string;
11
+ }
12
+ /** The three owner-chosen titles under their nonce. Each is 1–60 code points or null. */
13
+ export interface EnvelopeTitles {
14
+ nonce: string;
15
+ /** Null exactly when `grant_id` is null. */
16
+ grant_title: string | null;
17
+ /** Null when `agent_target` is null. */
18
+ target_title: string | null;
19
+ owner_name: string | null;
20
+ }
3
21
  /**
4
- * The revision envelope beside a receipt v2: exactly these nine members. `key_id` and `key_label`
5
- * name the API key of the Session's owning workspace that published the revision, and that key's
6
- * label when it was published (both null for any other publisher, and for revisions published
7
- * before receipt v2). They are the integrator's own key and word for it, never a person.
22
+ * The ten common members. The owner-chosen names in it (`agent_target.name` and, in the full form,
23
+ * the titles) are the owner's own words, signed by Sess as published, never verified identities.
8
24
  */
9
- export interface RevisionEnvelope {
10
- sess_revision: 1;
11
- session_id: string;
25
+ export interface RevisionEnvelopeCommon {
26
+ sess_revision: 2;
12
27
  revision: number;
28
+ /** `ses_…` */
29
+ session_id: string;
13
30
  /** The receipt's `surface.hash`: SHA-256 of the revision's normalized Surface document. */
14
31
  surface_hash: string;
15
32
  renderer_version: string;
16
33
  /** When the revision was published: `YYYY-MM-DDTHH:MM:SS.mmmZ`. */
17
34
  published_at: string;
35
+ /** The responsible owner key (`key_…`), or null. */
18
36
  key_id: string | null;
19
- /** 0–64 characters; null exactly when `key_id` is null. */
20
- key_label: string | null;
21
- /** Null in this version of Sess; an identifier is accepted. */
37
+ /** A Session grant (`sgr_…`), or null. */
22
38
  grant_id: string | null;
39
+ /** The registered address the Session started from, or null. */
40
+ agent_target: EnvelopeAgentTarget | null;
41
+ /** The Ask a respondent's Session belongs to (`ask_…`), or null. */
42
+ ask_id: string | null;
43
+ }
44
+ /** The full form, with `titles`: every file a person keeps, and every API response. */
45
+ export interface RevisionEnvelopeFull extends RevisionEnvelopeCommon {
46
+ titles: EnvelopeTitles;
23
47
  }
48
+ /** The compact form, with `titles_digest` in place of `titles` (a QR code's). */
49
+ export interface RevisionEnvelopeCompact extends RevisionEnvelopeCommon {
50
+ titles_digest: string;
51
+ }
52
+ /** The revision envelope beside a receipt v2, in either form. */
53
+ export type RevisionEnvelope = RevisionEnvelopeFull | RevisionEnvelopeCompact;
54
+ /**
55
+ * Whether a supplied value is an envelope of a later `sess_revision` than this reader knows: an
56
+ * object whose `sess_revision` is a whole number above 2. A verifier reports it as newer and
57
+ * releases nothing; it is never accepted. A lower or equal version is not newer.
58
+ */
59
+ export declare function revisionEnvelopeIsNewer(v: unknown): boolean;
24
60
  /**
25
- * Reads a supplied envelope strictly: exactly the nine members, each of its type, with the
26
- * canonical `published_at`. Null for anything else (a receipt v2 verifier then refuses it).
61
+ * Reads a supplied envelope strictly: exactly the ten common members, each of its kind, and exactly
62
+ * one of `titles` (exactly its four members, each title under the shared title rule) or
63
+ * `titles_digest`; `titles.grant_title` null exactly when `grant_id` is null, and
64
+ * `titles.target_title` null when `agent_target` is null. Null for anything else: both forms,
65
+ * neither, an extra or missing member at either level, a key label, a `sess_revision` other than 2
66
+ * (see revisionEnvelopeIsNewer). The value returned is a copy in the form given.
27
67
  */
28
68
  export declare function parseRevisionEnvelope(v: unknown): RevisionEnvelope | null;
29
- /** `revision_hash`: `sha256:<hex>` of the envelope's RFC 8785 canonical JSON. */
69
+ /** Reads a supplied envelope as a person's file carries it: the full form only. */
70
+ export declare function parseFullRevisionEnvelope(v: unknown): RevisionEnvelopeFull | null;
71
+ /**
72
+ * `revision_hash`: `sha256:<hex>` of the RFC 8785 canonical JSON of the compact form. A full form's
73
+ * `titles` is replaced by its digest first, so both forms of one revision give the same hash.
74
+ */
30
75
  export declare function revisionHash(envelope: RevisionEnvelope): string;
@@ -1,83 +1,188 @@
1
1
  // The revision envelope (receipt-v2 §2, docs/spec/receipt-v2.md): the record of one published
2
- // Surface revision that a receipt v2 commits to through `surface.revision_hash`, the RFC 8785
3
- // SHA-256 of the envelope. Sess computes it from the stored revision and returns it beside every
4
- // receipt v2; a verifier recomputes the digest from the envelope it is given. It is read here
5
- // exactly as the Sess verification core reads it (same members, types and identifier rules), so
6
- // an envelope one accepts the other accepts.
7
- import { exactKeys, isRecord, jsonDigest, wellFormedUnicode } from './json.js';
8
- /** The envelope's own schema version (`sess_revision`). */
9
- export const REVISION_ENVELOPE_VERSION = 1;
2
+ // Surface revision that a receipt v2 commits to through `surface.revision_hash`. Sess computes it
3
+ // from the stored revision and returns it beside every receipt v2; a verifier recomputes the digest
4
+ // from the envelope it is given. It is read here exactly as the Sess verification core reads it
5
+ // (packages/security/src/revision-envelope.ts at the commit recorded in docs/spec/source.json:
6
+ // same members, types, identifier and title rules), so an envelope one accepts the other accepts.
7
+ //
8
+ // The format, `sess_revision: 2` (receipt-v2 §2, frozen): ten common members, then exactly one of
9
+ // - `titles` (the full form): `{nonce, grant_title, target_title, owner_name}`, exactly these four;
10
+ // - `titles_digest` (the compact form): the unpadded base64url SHA-256 of the RFC 8785 canonical
11
+ // JSON of `titles`, 43 characters.
12
+ // Both, or neither, or any other key at either level, is refused. `revision_hash` is the JCS
13
+ // SHA-256 of the compact form: a full form is first normalised by replacing `titles` with its
14
+ // digest, so both forms of one revision give the same hash. No key label is in the envelope.
15
+ //
16
+ // Forward compatibility (receipt-v2 §7, `newer`): an envelope whose `sess_revision` is a whole number above
17
+ // 2 is newer (revisionEnvelopeIsNewer), never read as this version; a verifier reports it as newer
18
+ // and releases nothing. The nine-member `sess_revision: 1` shape was never issued and is refused.
19
+ import { createHash } from 'node:crypto';
20
+ import { canonicalJson, isRecord, jsonDigest } from './json.js';
21
+ import { isStoredSharedTitle } from './shared-title.js';
22
+ /** The envelope's own schema version (`sess_revision`); a higher one is newer. */
23
+ export const REVISION_ENVELOPE_VERSION = 2;
10
24
  /**
11
25
  * The canonical `published_at` form: RFC 3339 UTC with exactly three fractional digits, as
12
26
  * `Date.prototype.toISOString` writes it.
13
27
  */
14
28
  const PUBLISHED_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
15
29
  const DIGEST = /^sha256:[0-9a-f]{64}$/;
30
+ /** `titles.nonce`: 16 bytes as unpadded base64url. */
31
+ const TITLES_NONCE = /^[A-Za-z0-9_-]{21}[AQgw]$/;
32
+ /** `titles_digest`: a 32-byte SHA-256 as unpadded base64url. */
33
+ const TITLES_DIGEST = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
34
+ /** `agent_target.name`: the share-name rule (3 to 40 characters, a lowercase slug). */
35
+ const AGENT_TARGET_NAME = /^(?=.{3,40}$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
16
36
  const ID_MAX = 200;
17
- /** The key label's bound (at most 64 characters, possibly empty). */
18
- const KEY_LABEL_MAX = 64;
19
37
  const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
20
38
  // A bearer credential is never envelope material: Sess owner and management keys, and the
21
39
  // unprefixed 22- or 43-character human link token.
22
40
  const CREDENTIAL = /^(?:sess_sk_[A-Za-z0-9_-]{43}|sess_mg_[A-Za-z0-9_-]{43}|[A-Za-z0-9_-]{22}|[A-Za-z0-9_-]{43})$/;
23
41
  const MEMBERS = [
24
42
  'sess_revision',
25
- 'session_id',
26
43
  'revision',
44
+ 'session_id',
27
45
  'surface_hash',
28
46
  'renderer_version',
29
47
  'published_at',
30
48
  'key_id',
31
- 'key_label',
32
49
  'grant_id',
50
+ 'agent_target',
51
+ 'ask_id',
33
52
  ];
34
- function plain(v) {
35
- return typeof v === 'string' && v.length > 0 && v.length <= ID_MAX && !CONTROL.test(v) && !/\s/.test(v);
53
+ const TITLES = ['nonce', 'grant_title', 'target_title', 'owner_name'];
54
+ const AGENT_TARGET = ['id', 'version', 'name'];
55
+ function exactly(o, keys) {
56
+ const own = Object.keys(o);
57
+ return own.length === keys.length && keys.every((k) => Object.hasOwn(o, k));
36
58
  }
37
- function identifier(v) {
38
- return plain(v) && !CREDENTIAL.test(v) && !/sess_(?:sk|mg)_/.test(v);
59
+ function renderer(v) {
60
+ return typeof v === 'string' && v.length > 0 && v.length <= ID_MAX && !CONTROL.test(v) && !/\s/.test(v);
39
61
  }
40
- function label(v) {
41
- return typeof v === 'string' && [...v].length <= KEY_LABEL_MAX && wellFormedUnicode(v) && !CONTROL.test(v);
62
+ /** An opaque ID with its prefix and a non-empty body; never a bearer credential. */
63
+ function id(v, prefix) {
64
+ return (typeof v === 'string' &&
65
+ v.length > prefix.length &&
66
+ v.length <= ID_MAX &&
67
+ v.startsWith(prefix) &&
68
+ /^[A-Za-z0-9_-]+$/.test(v) &&
69
+ !CREDENTIAL.test(v) &&
70
+ !/sess_(?:sk|mg)_/.test(v));
42
71
  }
72
+ const whole = (v, min) => Number.isSafeInteger(v) && v >= min;
43
73
  function publishedAt(v) {
44
74
  if (typeof v !== 'string' || !PUBLISHED_AT.test(v))
45
75
  return false;
46
76
  const t = new Date(v);
47
77
  return !Number.isNaN(t.getTime()) && t.toISOString() === v;
48
78
  }
79
+ function agentTarget(v) {
80
+ return (isRecord(v) &&
81
+ exactly(v, AGENT_TARGET) &&
82
+ id(v.id, 'tgt_') &&
83
+ whole(v.version, 1) &&
84
+ typeof v.name === 'string' &&
85
+ AGENT_TARGET_NAME.test(v.name));
86
+ }
87
+ const title = (v) => v === null || isStoredSharedTitle(v);
88
+ function titles(v) {
89
+ return (isRecord(v) &&
90
+ exactly(v, TITLES) &&
91
+ typeof v.nonce === 'string' &&
92
+ TITLES_NONCE.test(v.nonce) &&
93
+ title(v.grant_title) &&
94
+ title(v.target_title) &&
95
+ title(v.owner_name));
96
+ }
97
+ const RULES = {
98
+ sess_revision: (v) => v === REVISION_ENVELOPE_VERSION,
99
+ revision: (v) => whole(v, 1),
100
+ session_id: (v) => id(v, 'ses_'),
101
+ surface_hash: (v) => typeof v === 'string' && DIGEST.test(v),
102
+ renderer_version: renderer,
103
+ published_at: publishedAt,
104
+ key_id: (v) => v === null || id(v, 'key_'),
105
+ grant_id: (v) => v === null || id(v, 'sgr_'),
106
+ agent_target: (v) => v === null || agentTarget(v),
107
+ ask_id: (v) => v === null || id(v, 'ask_'),
108
+ };
49
109
  /**
50
- * Reads a supplied envelope strictly: exactly the nine members, each of its type, with the
51
- * canonical `published_at`. Null for anything else (a receipt v2 verifier then refuses it).
110
+ * `titles_digest`: the unpadded base64url SHA-256 of the UTF-8 bytes of the RFC 8785 canonical
111
+ * JSON of `titles`.
112
+ */
113
+ function titlesDigest(t) {
114
+ return createHash('sha256').update(canonicalJson(t), 'utf8').digest('base64url');
115
+ }
116
+ function isFull(e) {
117
+ return Object.hasOwn(e, 'titles');
118
+ }
119
+ /**
120
+ * Whether a supplied value is an envelope of a later `sess_revision` than this reader knows: an
121
+ * object whose `sess_revision` is a whole number above 2. A verifier reports it as newer and
122
+ * releases nothing; it is never accepted. A lower or equal version is not newer.
123
+ */
124
+ export function revisionEnvelopeIsNewer(v) {
125
+ return (isRecord(v) &&
126
+ Number.isSafeInteger(v.sess_revision) &&
127
+ v.sess_revision > REVISION_ENVELOPE_VERSION);
128
+ }
129
+ /**
130
+ * Reads a supplied envelope strictly: exactly the ten common members, each of its kind, and exactly
131
+ * one of `titles` (exactly its four members, each title under the shared title rule) or
132
+ * `titles_digest`; `titles.grant_title` null exactly when `grant_id` is null, and
133
+ * `titles.target_title` null when `agent_target` is null. Null for anything else: both forms,
134
+ * neither, an extra or missing member at either level, a key label, a `sess_revision` other than 2
135
+ * (see revisionEnvelopeIsNewer). The value returned is a copy in the form given.
52
136
  */
53
137
  export function parseRevisionEnvelope(v) {
54
- if (!isRecord(v) || !exactKeys(v, MEMBERS))
138
+ if (!isRecord(v))
55
139
  return null;
56
- const ok = v.sess_revision === REVISION_ENVELOPE_VERSION &&
57
- identifier(v.session_id) &&
58
- Number.isSafeInteger(v.revision) &&
59
- v.revision >= 1 &&
60
- typeof v.surface_hash === 'string' &&
61
- DIGEST.test(v.surface_hash) &&
62
- plain(v.renderer_version) &&
63
- publishedAt(v.published_at) &&
64
- (v.key_id === null ? v.key_label === null : identifier(v.key_id) && label(v.key_label)) &&
65
- (v.grant_id === null || identifier(v.grant_id));
66
- if (!ok)
140
+ const full = Object.hasOwn(v, 'titles');
141
+ const compact = Object.hasOwn(v, 'titles_digest');
142
+ if (full === compact)
67
143
  return null;
68
- return {
69
- sess_revision: REVISION_ENVELOPE_VERSION,
70
- session_id: v.session_id,
71
- revision: v.revision,
72
- surface_hash: v.surface_hash,
73
- renderer_version: v.renderer_version,
74
- published_at: v.published_at,
75
- key_id: v.key_id,
76
- key_label: v.key_label,
77
- grant_id: v.grant_id,
78
- };
144
+ if (!exactly(v, [...MEMBERS, full ? 'titles' : 'titles_digest']))
145
+ return null;
146
+ const out = {};
147
+ for (const name of MEMBERS) {
148
+ if (!RULES[name](v[name]))
149
+ return null;
150
+ out[name] = v[name];
151
+ }
152
+ if (out.agent_target !== null)
153
+ out.agent_target = { ...out.agent_target };
154
+ if (full) {
155
+ if (!titles(v.titles))
156
+ return null;
157
+ out.titles = { ...v.titles };
158
+ const t = out.titles;
159
+ if ((out.grant_id === null) !== (t.grant_title === null))
160
+ return null;
161
+ if (out.agent_target === null && t.target_title !== null)
162
+ return null;
163
+ }
164
+ else {
165
+ if (typeof v.titles_digest !== 'string' || !TITLES_DIGEST.test(v.titles_digest))
166
+ return null;
167
+ out.titles_digest = v.titles_digest;
168
+ }
169
+ return out;
170
+ }
171
+ /** Reads a supplied envelope as a person's file carries it: the full form only. */
172
+ export function parseFullRevisionEnvelope(v) {
173
+ const e = parseRevisionEnvelope(v);
174
+ return e !== null && isFull(e) ? e : null;
79
175
  }
80
- /** `revision_hash`: `sha256:<hex>` of the envelope's RFC 8785 canonical JSON. */
176
+ /**
177
+ * `revision_hash`: `sha256:<hex>` of the RFC 8785 canonical JSON of the compact form. A full form's
178
+ * `titles` is replaced by its digest first, so both forms of one revision give the same hash.
179
+ */
81
180
  export function revisionHash(envelope) {
82
- return jsonDigest(envelope);
181
+ if (!isFull(envelope))
182
+ return jsonDigest(envelope);
183
+ const compact = {};
184
+ for (const name of MEMBERS)
185
+ compact[name] = envelope[name];
186
+ compact.titles_digest = titlesDigest(envelope.titles);
187
+ return jsonDigest(compact);
83
188
  }
@@ -1,7 +1,7 @@
1
1
  export { verifyDecisionReceipt, verifyRendererIdentities } from './verify.js';
2
2
  export { BUNDLED_RENDERER_IDENTITIES, BUNDLED_RENDERER_LIST, newerRendererList } from './renderers.js';
3
3
  export type { RendererIdentitiesDocument, RendererIdentity, RendererList } from './renderers.js';
4
- export type { RevisionEnvelope } from './envelope.js';
4
+ export type { EnvelopeAgentTarget, EnvelopeTitles, RevisionEnvelope, RevisionEnvelopeCompact, RevisionEnvelopeFull, } from './envelope.js';
5
5
  export type { ReceiptClaims, ReceiptClaimsV1, ReceiptClaimsV2, ReceiptPublicKey, ReceiptKeySet, ReceiptKeyResolver, VerifyDecisionReceiptInput, VerifyDecisionReceiptOptions, } from './verify.js';
6
6
  export type { DeepReadonly } from './json.js';
7
7
  export { verifyDecisionBundle, BUNDLE_LIMITS } from './bundle.js';
@@ -4,6 +4,19 @@ export type DeepReadonly<T> = T extends readonly (infer U)[] ? readonly DeepRead
4
4
  readonly [P in keyof T]: DeepReadonly<T[P]>;
5
5
  } : T;
6
6
  export declare function verificationError(code: string, message: string): SessError;
7
+ /**
8
+ * A receipt newer than this release (a later receipt type, or a later revision envelope): reported
9
+ * as newer, never as a verification failure, and nothing is returned with it.
10
+ */
11
+ export declare function newerReceiptError(): SessError;
12
+ /**
13
+ * Whether a JWS `typ` names a Sess signed format this release does not know: a later receipt
14
+ * version or another Sess receipt type, such as a closing receipt (`sess-<name>+jwt`, other than
15
+ * the two receipt types read here). Any other unknown `typ` is not a Sess format.
16
+ */
17
+ export declare function isNewerReceiptTyp(typ: unknown): boolean;
18
+ /** Receipt v2's action label bound in code points: a longer one is not a valid receipt v2. */
19
+ export declare const RECEIPT_V2_ACTION_LABEL_MAX = 24;
7
20
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
8
21
  export declare function wellFormedUnicode(value: string): boolean;
9
22
  export declare function exactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean;
@@ -1,9 +1,30 @@
1
1
  import canonicalize from 'canonicalize';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { SessError } from '../errors.js';
4
+ import { SDK_VERSION } from '../internal/version.js';
4
5
  export function verificationError(code, message) {
5
6
  return new SessError('receipt_verification', message, { code });
6
7
  }
8
+ /**
9
+ * A receipt newer than this release (a later receipt type, or a later revision envelope): reported
10
+ * as newer, never as a verification failure, and nothing is returned with it.
11
+ */
12
+ export function newerReceiptError() {
13
+ return new SessError('receipt_newer', `This receipt is newer than @sess.si/sdk ${SDK_VERSION}. Update @sess.si/sdk to check it. No answer data was returned.`, { code: 'RECEIPT_NEWER' });
14
+ }
15
+ /**
16
+ * Whether a JWS `typ` names a Sess signed format this release does not know: a later receipt
17
+ * version or another Sess receipt type, such as a closing receipt (`sess-<name>+jwt`, other than
18
+ * the two receipt types read here). Any other unknown `typ` is not a Sess format.
19
+ */
20
+ export function isNewerReceiptTyp(typ) {
21
+ return (typeof typ === 'string' &&
22
+ typ !== 'sess-receipt+jwt' &&
23
+ typ !== 'sess-receipt-2+jwt' &&
24
+ /^sess-[a-z0-9]+(?:-[a-z0-9]+)*\+jwt$/.test(typ));
25
+ }
26
+ /** Receipt v2's action label bound in code points: a longer one is not a valid receipt v2. */
27
+ export const RECEIPT_V2_ACTION_LABEL_MAX = 24;
7
28
  export function isRecord(value) {
8
29
  return value !== null && typeof value === 'object' && !Array.isArray(value);
9
30
  }
@@ -0,0 +1,7 @@
1
+ /** A title's bound, in code points. */
2
+ export declare const SHARED_TITLE_MAX = 60;
3
+ /**
4
+ * Whether `v` is a stored title: a string the shared title rule leaves exactly as it is (a fixed
5
+ * point of the rule, so non-empty, trimmed and within every rule above).
6
+ */
7
+ export declare function isStoredSharedTitle(v: unknown): v is string;
@@ -0,0 +1,127 @@
1
+ // The shared title rule (receipt-v2 §2: one line of plain text), as the revision-envelope reader
2
+ // applies it to every owner-chosen title a receipt v2 carries (`titles.grant_title`,
3
+ // `titles.target_title`, `titles.owner_name`): the frozen receipt v2 format says each title "is
4
+ // normalised by the shared title rule before storage, and stored as normalised", so a title this
5
+ // rule would change or refuse is not a valid envelope title. Ported from the Sess security core
6
+ // (packages/security/src/shared-title.ts at the commit recorded in docs/spec/source.json) with the
7
+ // same behaviour and the same refusal vectors (tests/security/receipts-v2.test.ts).
8
+ /** A title's bound, in code points. */
9
+ export const SHARED_TITLE_MAX = 60;
10
+ /**
11
+ * Characters owner text may not contain: C0/C1 controls other than the newline, the bidirectional
12
+ * embedding/override/isolate controls, zero-width and invisible format characters, and unpaired
13
+ * surrogates. A title refuses these and more (titleRefused).
14
+ */
15
+ const FORBIDDEN_RANGES = [
16
+ [0x00, 0x09],
17
+ [0x0b, 0x1f],
18
+ [0x7f, 0x9f],
19
+ [0x61c, 0x61c],
20
+ [0x200b, 0x200f],
21
+ [0x2028, 0x202e],
22
+ [0x2060, 0x206f],
23
+ [0xd800, 0xdfff],
24
+ [0xfeff, 0xfeff],
25
+ [0xfff9, 0xfffb],
26
+ ];
27
+ const codePoints = (text) => [...text].length;
28
+ /**
29
+ * The display title: one line of plain text, trimmed; no control or format character and none of
30
+ * FORBIDDEN_RANGES, except the joiners and the three flags titleRefused allows; at most
31
+ * SHARED_TITLE_MAX characters; at least one visible character (isVisible); null when empty.
32
+ */
33
+ function normalizeSharedTitle(text) {
34
+ if (titleRefused([...text]))
35
+ return { ok: false };
36
+ const normalized = text.trim();
37
+ if (normalized === '')
38
+ return { ok: true, text: null };
39
+ if (codePoints(normalized) > SHARED_TITLE_MAX)
40
+ return { ok: false };
41
+ if (![...normalized].some(isVisible))
42
+ return { ok: false };
43
+ return { ok: true, text: normalized };
44
+ }
45
+ /**
46
+ * Whether `v` is a stored title: a string the shared title rule leaves exactly as it is (a fixed
47
+ * point of the rule, so non-empty, trimmed and within every rule above).
48
+ */
49
+ export function isStoredSharedTitle(v) {
50
+ if (typeof v !== 'string')
51
+ return false;
52
+ const r = normalizeSharedTitle(v);
53
+ return r.ok && r.text === v;
54
+ }
55
+ /** Every control (Cc, which covers CR and LF) and every format character (Cf). */
56
+ const TITLE_REFUSED = /[\p{Cc}\p{Cf}]/u;
57
+ const ZWNJ = 0x200c;
58
+ const ZWJ = 0x200d;
59
+ const BLACK_FLAG = 0x1f3f4;
60
+ /**
61
+ * The only tag sequences a title may hold: the three RGI subdivision flags, exactly (England,
62
+ * Scotland, Wales: U+1F3F4, the tag letters gbeng, gbsct or gbwls, U+E007F). Any other run of tag
63
+ * characters is refused: it could carry hidden ASCII text behind a plain black flag.
64
+ */
65
+ const RGI_SUBDIVISION_FLAGS = [
66
+ [0x1f3f4, 0xe0067, 0xe0062, 0xe0065, 0xe006e, 0xe0067, 0xe007f],
67
+ [0x1f3f4, 0xe0067, 0xe0062, 0xe0073, 0xe0063, 0xe0074, 0xe007f],
68
+ [0x1f3f4, 0xe0067, 0xe0062, 0xe0077, 0xe006c, 0xe0073, 0xe007f],
69
+ ];
70
+ /** The length of the RGI subdivision flag starting at `i`, or 0. */
71
+ const flagAt = (cps, i) => RGI_SUBDIVISION_FLAGS.find((f) => f.every((c, k) => cps[i + k] === c))?.length ?? 0;
72
+ const MARK = /\p{M}/u;
73
+ const VS15 = 0xfe0e;
74
+ const VS16 = 0xfe0f;
75
+ const EMOJI = /\p{Emoji}/u;
76
+ /**
77
+ * True when a title (as code points) has a character it may not hold. Every Cc and Cf, every
78
+ * default-ignorable code point and every FORBIDDEN_RANGES character is refused, with exactly three
79
+ * exceptions that real text needs:
80
+ * - one presentation selector (VS15, VS16) directly after an emoji character;
81
+ * - ZWNJ and ZWJ between two visible characters (the left neighbour is the base of the grapheme
82
+ * before the joiner: combining marks after it are skipped);
83
+ * - the three RGI subdivision flags, each as its exact code points.
84
+ */
85
+ function titleRefused(chars) {
86
+ const cps = chars.map((ch) => ch.codePointAt(0));
87
+ for (let i = 0; i < cps.length; i++) {
88
+ const c = cps[i];
89
+ if (c === BLACK_FLAG) {
90
+ const flag = flagAt(cps, i);
91
+ if (flag > 0)
92
+ i += flag - 1; // the whole flag, its cancel tag included
93
+ continue; // a plain black flag is a symbol; tags after it fall to the Cf check
94
+ }
95
+ if (c === ZWNJ || c === ZWJ) {
96
+ let left = i - 1;
97
+ while (left >= 0 && MARK.test(chars[left]))
98
+ left--;
99
+ const before = chars[left];
100
+ const after = chars[i + 1];
101
+ if (before === undefined || after === undefined || !isVisible(before) || !isVisible(after))
102
+ return true;
103
+ continue;
104
+ }
105
+ if (c === VS15 || c === VS16) {
106
+ const base = chars[i - 1];
107
+ if (base === undefined || !EMOJI.test(base) || IGNORABLE.test(base))
108
+ return true;
109
+ continue;
110
+ }
111
+ if (IGNORABLE.test(chars[i]))
112
+ return true;
113
+ if (TITLE_REFUSED.test(chars[i]))
114
+ return true;
115
+ if (FORBIDDEN_RANGES.some(([lo, hi]) => c >= lo && c <= hi))
116
+ return true;
117
+ }
118
+ return false;
119
+ }
120
+ /**
121
+ * A visible character: a letter, number, symbol or punctuation (L, N, S, P) that is not a
122
+ * default-ignorable code point (the Hangul fillers are letters by category but draw blank) and not
123
+ * U+2800, the blank Braille pattern. Spaces, marks alone and private use do not count.
124
+ */
125
+ const VISIBLE = /[\p{L}\p{N}\p{S}\p{P}]/u;
126
+ const IGNORABLE = /\p{Default_Ignorable_Code_Point}/u;
127
+ const isVisible = (ch) => VISIBLE.test(ch) && !IGNORABLE.test(ch) && ch.codePointAt(0) !== 0x2800;
@@ -125,7 +125,12 @@ export declare function validateKeySet(raw: unknown): ReceiptKeySet;
125
125
  * the revision envelope it commits to. A receipt v2 whose envelope is missing or null, malformed,
126
126
  * of another digest than `surface.revision_hash`, or naming another Session, revision, Surface
127
127
  * hash or renderer identity is refused with `REVISION_ENVELOPE_MISMATCH`, after the issuer,
128
- * audience, record, time and signature checks.
128
+ * audience, record, time and signature checks. The envelope is `sess_revision: 2`, in its full
129
+ * (`titles`) or compact (`titles_digest`) form; a receipt v2 action label is at most 24 code points.
130
+ *
131
+ * A receipt newer than this release, a later Sess receipt `typ` (checked before anything else in
132
+ * the receipt) or a receipt v2 whose envelope has a later `sess_revision`, is refused with kind
133
+ * `receipt_newer` and code `RECEIPT_NEWER`, never as a verification failure; nothing is returned.
129
134
  */
130
135
  export declare function verifyDecisionReceipt(input: VerifyDecisionReceiptInput, options?: VerifyDecisionReceiptOptions): Promise<DeepReadonly<ReceiptClaims>>;
131
136
  /**
@@ -1,7 +1,7 @@
1
1
  import { compactVerify, importJWK } from 'jose';
2
- import { abortError, canonicalJson, checkedInstant, deepFreeze, exactKeys, isRecord, jsonDigest, snapshotJson, verificationError, waitWithSignal, } from './json.js';
2
+ import { abortError, canonicalJson, checkedInstant, deepFreeze, exactKeys, isNewerReceiptTyp, isRecord, jsonDigest, newerReceiptError, RECEIPT_V2_ACTION_LABEL_MAX, snapshotJson, verificationError, waitWithSignal, } from './json.js';
3
3
  import { BUNDLED_RENDERER_IDENTITIES, verifyRendererList, } from './renderers.js';
4
- import { parseRevisionEnvelope, revisionHash } from './envelope.js';
4
+ import { parseRevisionEnvelope, revisionEnvelopeIsNewer, revisionHash, } from './envelope.js';
5
5
  export const MAX_RECEIPT_BYTES = 64 * 1024;
6
6
  export const MAX_RECEIPT_KEY_SET_BYTES = 256 * 1024;
7
7
  const MAX_KEYS = 64;
@@ -145,6 +145,7 @@ function claimsOf(raw, version) {
145
145
  !identifier(action.id) ||
146
146
  typeof action.label !== 'string' ||
147
147
  action.label.length === 0 ||
148
+ (version === 2 && [...action.label].length > RECEIPT_V2_ACTION_LABEL_MAX) ||
148
149
  typeof action.summary !== 'string' ||
149
150
  typeof raw.input_hash !== 'string' ||
150
151
  !DIGEST.test(raw.input_hash) ||
@@ -175,7 +176,12 @@ function claimsOf(raw, version) {
175
176
  * the revision envelope it commits to. A receipt v2 whose envelope is missing or null, malformed,
176
177
  * of another digest than `surface.revision_hash`, or naming another Session, revision, Surface
177
178
  * hash or renderer identity is refused with `REVISION_ENVELOPE_MISMATCH`, after the issuer,
178
- * audience, record, time and signature checks.
179
+ * audience, record, time and signature checks. The envelope is `sess_revision: 2`, in its full
180
+ * (`titles`) or compact (`titles_digest`) form; a receipt v2 action label is at most 24 code points.
181
+ *
182
+ * A receipt newer than this release, a later Sess receipt `typ` (checked before anything else in
183
+ * the receipt) or a receipt v2 whose envelope has a later `sess_revision`, is refused with kind
184
+ * `receipt_newer` and code `RECEIPT_NEWER`, never as a verification failure; nothing is returned.
179
185
  */
180
186
  export async function verifyDecisionReceipt(input, options = {}) {
181
187
  // Capture all caller-owned data and options before a resolver can yield control.
@@ -236,6 +242,10 @@ export async function verifyDecisionReceipt(input, options = {}) {
236
242
  throw verificationError('INVALID_VERIFICATION_INPUT', 'Verification requires an accepted record and its complete normalized immutable interaction.');
237
243
  }
238
244
  const parts = receipt.split('.');
245
+ // A Sess format this release does not know is newer, before any other check: its key, its
246
+ // algorithm and its claims may all be ones this release has never seen. Nothing is returned.
247
+ if (declaresNewerTyp(parts[0]))
248
+ throw newerReceiptError();
239
249
  const header = headerOf(parts[0]);
240
250
  let raw;
241
251
  const payloadText = decodeSegment(parts[1]);
@@ -322,10 +332,25 @@ export async function verifyDecisionReceipt(input, options = {}) {
322
332
  return deepFreeze(claims);
323
333
  }
324
334
  const MALFORMED_ENVELOPE = Symbol('malformed revision envelope');
325
- /** Receipt v2: the supplied envelope must be the one the receipt commits to (receipt-v2 §7). */
335
+ /** Whether the (unverified) protected header names a later Sess format; never throws. */
336
+ function declaresNewerTyp(encoded) {
337
+ try {
338
+ const parsed = JSON.parse(decodeSegment(encoded));
339
+ return isRecord(parsed) && isNewerReceiptTyp(parsed.typ);
340
+ }
341
+ catch {
342
+ return false;
343
+ }
344
+ }
345
+ /**
346
+ * Receipt v2: the supplied envelope must be the one the receipt commits to (receipt-v2 §7). An
347
+ * envelope of a later `sess_revision` is newer: never accepted, and nothing is returned.
348
+ */
326
349
  function checkRevisionEnvelope(claims, supplied) {
327
350
  if (supplied === null)
328
351
  throw verificationError('REVISION_ENVELOPE_MISMATCH', 'A version 2 receipt is verified only with its revision envelope, and none was supplied.');
352
+ if (revisionEnvelopeIsNewer(supplied))
353
+ throw newerReceiptError();
329
354
  const envelope = parseRevisionEnvelope(supplied);
330
355
  if (envelope === null)
331
356
  throw verificationError('REVISION_ENVELOPE_MISMATCH', 'The revision envelope is malformed.');
package/dist/types.d.ts CHANGED
@@ -2,7 +2,7 @@ import type { components } from './generated/openapi.js';
2
2
  import type { RevisionEnvelope } from './receipts/envelope.js';
3
3
  /** Unmodified types generated from the reviewed public HTTP contract. */
4
4
  export type { components, paths, operations } from './generated/openapi.js';
5
- export type { RevisionEnvelope } from './receipts/envelope.js';
5
+ export type { EnvelopeAgentTarget, EnvelopeTitles, RevisionEnvelope, RevisionEnvelopeCompact, RevisionEnvelopeFull, } from './receipts/envelope.js';
6
6
  type Schemas = components['schemas'];
7
7
  export type RawCreateSessionRequest = Schemas['CreateSessionRequest'];
8
8
  export type RawPublishSessionRequest = Schemas['PatchSessionRequest'];
@@ -15,8 +15,9 @@ export type DisplaySession = Schemas['SessionResponse'];
15
15
  interface RevisionEnvelopeMember {
16
16
  /**
17
17
  * The revision envelope the receipt v2 commits to (`surface.revision_hash`): when the revision
18
- * was published and, when one of your API keys published it, that key's ID and its label at the
19
- * time. `receipts.verifyResponse` verifies the receipt with it. Absent beside a receipt v1.
18
+ * was published, the responsible API key's ID, the registered address or Ask the Session came
19
+ * from, and the titles its owner chose (`sess_revision: 2`). `receipts.verifyResponse` verifies
20
+ * the receipt with it. Absent beside a receipt v1. Read it only from a verified result.
20
21
  */
21
22
  revision_envelope?: RevisionEnvelope;
22
23
  }
@@ -6,11 +6,27 @@ import type { RevisionEnvelope } from '../receipts/envelope.js';
6
6
  * `receipt` (receipt-v2 §10); a receipt v1's message has no such member.
7
7
  */
8
8
  export type WebhookEvent = components['schemas']['WebhookDelivery'] & {
9
+ /** Only for a respondent of a Sess Ask: the Ask's ID (`ask_…`). */
10
+ ask_id?: string;
9
11
  /** Beside a receipt v2 only: the revision envelope the receipt commits to. */
10
12
  revision_envelope?: RevisionEnvelope;
11
13
  };
14
+ /** An `ask.closed` delivery: a Sess Ask closed. Its `event_id` equals the `webhook-id` header. */
15
+ export interface AskClosed {
16
+ type: 'ask.closed';
17
+ /** Stable across retries and redeliveries: deduplicate on it. */
18
+ event_id: string;
19
+ /** The Ask's ID (`ask_…`). */
20
+ ask_id: string;
21
+ /** `max`: the last place was started; `owner`: you closed it. */
22
+ closed_by: 'max' | 'owner';
23
+ /** How many people had started when it closed. */
24
+ started: number;
25
+ /** When it closed (ISO 8601, milliseconds, UTC). */
26
+ closed_at: string;
27
+ }
12
28
  export type WebhookChallenge = components['schemas']['WebhookVerification'];
13
- export type VerifiedWebhook = DeepReadonly<WebhookEvent | WebhookChallenge>;
29
+ export type VerifiedWebhook = DeepReadonly<WebhookEvent | AskClosed | WebhookChallenge>;
14
30
  export type WebhookHeaders = Headers | Readonly<Record<string, string | readonly string[] | undefined>>;
15
31
  export interface VerifyWebhookOptions {
16
32
  /** Workspace-specific secrets from registration/rotation; store outside source control. */
@@ -8,6 +8,7 @@ const MAX_SECRETS = 4;
8
8
  const SECRET = /^whsec_[A-Za-z0-9+/]{43}=$/;
9
9
  const EVENT_ID = /^evt_[0-9A-HJKMNP-TV-Z]{26}$/;
10
10
  const SESSION_ID = /^ses_[0-9A-HJKMNP-TV-Z]{26}$/;
11
+ const ASK_ID = /^ask_[0-9A-HJKMNP-TV-Z]{26}$/;
11
12
  function failure(code, message) {
12
13
  return new SessError('protocol', message, { code, operation: 'webhooks.verify' });
13
14
  }
@@ -148,6 +149,23 @@ export function verifyWebhook(rawBody, headers, options) {
148
149
  }
149
150
  return deepFreeze(value);
150
151
  }
152
+ if (value.type === 'ask.closed') {
153
+ if (!exactKeys(value, ['type', 'event_id', 'ask_id', 'closed_by', 'started', 'closed_at']) ||
154
+ typeof value.event_id !== 'string' ||
155
+ !EVENT_ID.test(value.event_id) ||
156
+ value.event_id !== id ||
157
+ typeof value.ask_id !== 'string' ||
158
+ !ASK_ID.test(value.ask_id) ||
159
+ (value.closed_by !== 'max' && value.closed_by !== 'owner') ||
160
+ !Number.isSafeInteger(value.started) ||
161
+ value.started < 0 ||
162
+ checkedInstant(value.closed_at) === undefined) {
163
+ throw failure('WEBHOOK_INVALID_PAYLOAD', 'The ask.closed webhook event is malformed or does not match its transport identity.');
164
+ }
165
+ return deepFreeze(value);
166
+ }
167
+ // A respondent of an Ask carries its `ask_id`; every other Session's message has no such member.
168
+ const withAsk = Object.hasOwn(value, 'ask_id');
151
169
  // A receipt v2's message carries its revision envelope beside the receipt; a receipt v1's has
152
170
  // exactly the members it always had. The envelope itself is judged by receipt verification.
153
171
  const withEnvelope = Object.hasOwn(value, 'revision_envelope');
@@ -162,8 +180,10 @@ export function verifyWebhook(rawBody, headers, options) {
162
180
  'data',
163
181
  'accepted_at',
164
182
  'receipt',
183
+ ...(withAsk ? ['ask_id'] : []),
165
184
  ...(withEnvelope ? ['revision_envelope'] : []),
166
185
  ]) ||
186
+ (withAsk && (typeof value.ask_id !== 'string' || !ASK_ID.test(value.ask_id))) ||
167
187
  (withEnvelope && (!isRecord(value.revision_envelope) || typeof value.receipt !== 'string')) ||
168
188
  typeof value.event_id !== 'string' ||
169
189
  !EVENT_ID.test(value.event_id) ||
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sess.si/sdk",
3
- "version": "0.3.0",
3
+ "version": "0.4.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",