@sess.si/sdk 0.3.0 → 0.5.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.
@@ -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
  }
@@ -111,7 +112,7 @@ export interface ItemsComponent {
111
112
  name?: string;
112
113
  /** 1–100 rows, in order. */
113
114
  rows: {
114
- /** What one line is: at most 80. Example: `Design retainer, October` */
115
+ /** What one line is: at most 30. Example: `Design retainer, October` */
115
116
  name: string;
116
117
  /** Optional second line: quantity, unit price or a reference; at most 160. Example: `3 × $150.00` */
117
118
  detail?: string;
@@ -139,7 +140,7 @@ export interface ItemsComponent {
139
140
  * `length` (on `SessError`) name the value and the most it may have.
140
141
  */
141
142
  export type SurfaceComponent = (Component<'heading'> & {
142
- /** A section heading: a few words; at most 60. Example: `Order details` */
143
+ /** A section heading: a few words; at most 40. Example: `Order details` */
143
144
  text: string;
144
145
  }) | (Component<'text'> & {
145
146
  /**
@@ -151,21 +152,21 @@ export type SurfaceComponent = (Component<'heading'> & {
151
152
  /** Optional caption above the record: a few words; at most 200. Example: `Order 1042` */
152
153
  label?: string;
153
154
  /**
154
- * Rows shown verbatim, 1–50. A row's name: a word or two; at most 40 (example `Amount`).
155
+ * Rows shown verbatim, 1–50. A row's name: a word or two; at most 24 (example `Amount`).
155
156
  * A row's value: a string of at most 200, or a number, boolean or null (example `$120.00`).
156
157
  */
157
158
  fields: {
158
159
  [key: string]: string | number | boolean | null;
159
160
  };
160
161
  }) | (Omit<Component<'field'>, 'schema'> & {
161
- /** What the field asks for: short, a few words; at most 60. Example: `Refund amount` */
162
+ /** What the field asks for: short, a few words; at most 40. Example: `Refund amount` */
162
163
  label: string;
163
164
  /**
164
- * Optional help under the label: one hint; at most 160.
165
+ * Optional help under the label: one hint; at most 120.
165
166
  * Example: `Leave it as is to refund the full amount.`
166
167
  */
167
168
  description?: string;
168
- /** The words shown for one choice: short; at most 60. Example: `Next Monday` */
169
+ /** The words shown for one choice: short; at most 30. Example: `Next Monday` */
169
170
  option_labels?: {
170
171
  [key: string]: string;
171
172
  };
@@ -181,24 +182,24 @@ export type SurfaceComponent = (Component<'heading'> & {
181
182
  schema: FieldSchema;
182
183
  }) | ItemsComponent;
183
184
  type DocumentedAction = RawPublishSessionRequest['interaction']['actions'][number] & {
184
- /** A button: a verb, 1–3 words; at most 24. Examples: `Approve`, `Send refund` */
185
+ /** A button: a verb, 1–3 words; at most 16. Examples: `Approve`, `Send refund` */
185
186
  label: string;
186
187
  };
187
188
  /**
188
189
  * An interactive Surface: a title, plain-text components and typed fields, and 1–5 actions.
189
- * Limits in Unicode code points: title 80, description 280, heading 60, text 4000, record
190
- * caption 200, row name 40, row string value 200, field label 60, field help 160, option label
191
- * 60, button 24; at most 5 actions.
190
+ * Limits in Unicode code points: title 60, description 200, heading 40, text 4000, record
191
+ * caption 200, row name 24, row string value 200, field label 40, field help 120, option label
192
+ * 30, button 16; at most 5 actions.
192
193
  */
193
194
  export type InteractiveInteraction = Omit<RawPublishSessionRequest['interaction'], 'source' | 'actions'> & {
194
195
  /**
195
- * The page's heading: a question or a task, about 40 characters; at most 80.
196
+ * The page's heading: a question or a task, about 40 characters; at most 60.
196
197
  * Examples: `Approve the refund?`, `Pick a delivery date`
197
198
  */
198
199
  title: string;
199
200
  /**
200
201
  * Optional context under the title: what the person decides and why, in one or two plain
201
- * sentences; at most 280. Example: `The customer was charged twice for order 1042.`
202
+ * sentences; at most 200. Example: `The customer was charged twice for order 1042.`
202
203
  */
203
204
  description?: string;
204
205
  /**
@@ -210,7 +211,7 @@ export type InteractiveInteraction = Omit<RawPublishSessionRequest['interaction'
210
211
  kind: 'sess_surface';
211
212
  components: SurfaceComponent[];
212
213
  };
213
- /** The buttons, 1–5. A button: a verb, 1–3 words; at most 24. */
214
+ /** The buttons, 1–5. A button: a verb, 1–3 words; at most 16. */
214
215
  actions: DocumentedAction[];
215
216
  };
216
217
  export type CreateSessionRequest = {
@@ -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.5.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",