@sess.si/sdk 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,30 @@
1
+ /** The envelope's own schema version (`sess_revision`). */
2
+ export declare const REVISION_ENVELOPE_VERSION = 1;
3
+ /**
4
+ * The revision envelope beside a receipt v2: exactly these nine members. `key_id` and `key_label`
5
+ * name the API key of the Session's owning workspace that published the revision, and that key's
6
+ * label when it was published (both null for any other publisher, and for revisions published
7
+ * before receipt v2). They are the integrator's own key and word for it, never a person.
8
+ */
9
+ export interface RevisionEnvelope {
10
+ sess_revision: 1;
11
+ session_id: string;
12
+ revision: number;
13
+ /** The receipt's `surface.hash`: SHA-256 of the revision's normalized Surface document. */
14
+ surface_hash: string;
15
+ renderer_version: string;
16
+ /** When the revision was published: `YYYY-MM-DDTHH:MM:SS.mmmZ`. */
17
+ published_at: string;
18
+ key_id: string | null;
19
+ /** 0–64 characters; null exactly when `key_id` is null. */
20
+ key_label: string | null;
21
+ /** Null in this version of Sess; an identifier is accepted. */
22
+ grant_id: string | null;
23
+ }
24
+ /**
25
+ * Reads a supplied envelope strictly: exactly the nine members, each of its type, with the
26
+ * canonical `published_at`. Null for anything else (a receipt v2 verifier then refuses it).
27
+ */
28
+ export declare function parseRevisionEnvelope(v: unknown): RevisionEnvelope | null;
29
+ /** `revision_hash`: `sha256:<hex>` of the envelope's RFC 8785 canonical JSON. */
30
+ export declare function revisionHash(envelope: RevisionEnvelope): string;
@@ -0,0 +1,83 @@
1
+ // The revision envelope (receipt-v2 §2, docs/spec/receipt-v2.md): the record of one published
2
+ // Surface revision that a receipt v2 commits to through `surface.revision_hash`, the RFC 8785
3
+ // SHA-256 of the envelope. Sess computes it from the stored revision and returns it beside every
4
+ // receipt v2; a verifier recomputes the digest from the envelope it is given. It is read here
5
+ // exactly as the Sess verification core reads it (same members, types and identifier rules), so
6
+ // an envelope one accepts the other accepts.
7
+ import { exactKeys, isRecord, jsonDigest, wellFormedUnicode } from './json.js';
8
+ /** The envelope's own schema version (`sess_revision`). */
9
+ export const REVISION_ENVELOPE_VERSION = 1;
10
+ /**
11
+ * The canonical `published_at` form: RFC 3339 UTC with exactly three fractional digits, as
12
+ * `Date.prototype.toISOString` writes it.
13
+ */
14
+ const PUBLISHED_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
15
+ const DIGEST = /^sha256:[0-9a-f]{64}$/;
16
+ const ID_MAX = 200;
17
+ /** The key label's bound (at most 64 characters, possibly empty). */
18
+ const KEY_LABEL_MAX = 64;
19
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
20
+ // A bearer credential is never envelope material: Sess owner and management keys, and the
21
+ // unprefixed 22- or 43-character human link token.
22
+ const CREDENTIAL = /^(?:sess_sk_[A-Za-z0-9_-]{43}|sess_mg_[A-Za-z0-9_-]{43}|[A-Za-z0-9_-]{22}|[A-Za-z0-9_-]{43})$/;
23
+ const MEMBERS = [
24
+ 'sess_revision',
25
+ 'session_id',
26
+ 'revision',
27
+ 'surface_hash',
28
+ 'renderer_version',
29
+ 'published_at',
30
+ 'key_id',
31
+ 'key_label',
32
+ 'grant_id',
33
+ ];
34
+ function plain(v) {
35
+ return typeof v === 'string' && v.length > 0 && v.length <= ID_MAX && !CONTROL.test(v) && !/\s/.test(v);
36
+ }
37
+ function identifier(v) {
38
+ return plain(v) && !CREDENTIAL.test(v) && !/sess_(?:sk|mg)_/.test(v);
39
+ }
40
+ function label(v) {
41
+ return typeof v === 'string' && [...v].length <= KEY_LABEL_MAX && wellFormedUnicode(v) && !CONTROL.test(v);
42
+ }
43
+ function publishedAt(v) {
44
+ if (typeof v !== 'string' || !PUBLISHED_AT.test(v))
45
+ return false;
46
+ const t = new Date(v);
47
+ return !Number.isNaN(t.getTime()) && t.toISOString() === v;
48
+ }
49
+ /**
50
+ * Reads a supplied envelope strictly: exactly the nine members, each of its type, with the
51
+ * canonical `published_at`. Null for anything else (a receipt v2 verifier then refuses it).
52
+ */
53
+ export function parseRevisionEnvelope(v) {
54
+ if (!isRecord(v) || !exactKeys(v, MEMBERS))
55
+ return null;
56
+ const ok = v.sess_revision === REVISION_ENVELOPE_VERSION &&
57
+ identifier(v.session_id) &&
58
+ Number.isSafeInteger(v.revision) &&
59
+ v.revision >= 1 &&
60
+ typeof v.surface_hash === 'string' &&
61
+ DIGEST.test(v.surface_hash) &&
62
+ plain(v.renderer_version) &&
63
+ publishedAt(v.published_at) &&
64
+ (v.key_id === null ? v.key_label === null : identifier(v.key_id) && label(v.key_label)) &&
65
+ (v.grant_id === null || identifier(v.grant_id));
66
+ if (!ok)
67
+ return null;
68
+ return {
69
+ sess_revision: REVISION_ENVELOPE_VERSION,
70
+ session_id: v.session_id,
71
+ revision: v.revision,
72
+ surface_hash: v.surface_hash,
73
+ renderer_version: v.renderer_version,
74
+ published_at: v.published_at,
75
+ key_id: v.key_id,
76
+ key_label: v.key_label,
77
+ grant_id: v.grant_id,
78
+ };
79
+ }
80
+ /** `revision_hash`: `sha256:<hex>` of the envelope's RFC 8785 canonical JSON. */
81
+ export function revisionHash(envelope) {
82
+ return jsonDigest(envelope);
83
+ }
@@ -1,8 +1,9 @@
1
1
  export { verifyDecisionReceipt, verifyRendererIdentities } from './verify.js';
2
2
  export { BUNDLED_RENDERER_IDENTITIES, BUNDLED_RENDERER_LIST, newerRendererList } from './renderers.js';
3
3
  export type { RendererIdentitiesDocument, RendererIdentity, RendererList } from './renderers.js';
4
- export type { ReceiptClaims, ReceiptPublicKey, ReceiptKeySet, ReceiptKeyResolver, VerifyDecisionReceiptInput, VerifyDecisionReceiptOptions, } from './verify.js';
4
+ export type { RevisionEnvelope } from './envelope.js';
5
+ export type { ReceiptClaims, ReceiptClaimsV1, ReceiptClaimsV2, ReceiptPublicKey, ReceiptKeySet, ReceiptKeyResolver, VerifyDecisionReceiptInput, VerifyDecisionReceiptOptions, } from './verify.js';
5
6
  export type { DeepReadonly } from './json.js';
6
7
  export { verifyDecisionBundle, BUNDLE_LIMITS } from './bundle.js';
7
- export type { BundleContextField, BundleJwk, BundleRejection, DecisionBundle, DecisionBundleVerification, ExpectedBundleContext, VerifiedReceiptSummary, VerifyDecisionBundleOptions, } from './bundle.js';
8
+ export type { BundleContextField, BundleJwk, BundleRejection, DecisionBundle, DecisionBundleV1, DecisionBundleV2, DecisionBundleVerification, ExpectedBundleContext, VerifiedReceiptSummary, VerifyDecisionBundleOptions, } from './bundle.js';
8
9
  export type { ReceiptResource, VerifyResponseInput, VerifiedResponse, VerificationRequestOptions, } from './resource.js';
@@ -114,6 +114,9 @@ export function createReceiptResource(context) {
114
114
  const claims = await verifyDecisionReceipt({
115
115
  receipt: response.receipt,
116
116
  ...(rendererIdentities !== undefined ? { rendererIdentities } : {}),
117
+ // Receipt v2: the envelope returned beside it (the authorized record's own, compared
118
+ // above); a receipt v1 has none and the verifier does not read it.
119
+ revisionEnvelope: response.revision_envelope ?? null,
117
120
  issuer,
118
121
  audience: trustedWorkspace,
119
122
  expected: {
@@ -1,6 +1,7 @@
1
1
  import type { InteractiveSurfaceRevision } from '../types.js';
2
2
  import { type DeepReadonly } from './json.js';
3
3
  import { type RendererIdentitiesDocument, type RendererList } from './renderers.js';
4
+ import { type RevisionEnvelope } from './envelope.js';
4
5
  export declare const MAX_RECEIPT_BYTES: number;
5
6
  export declare const MAX_RECEIPT_KEY_SET_BYTES: number;
6
7
  /** Public Ed25519 verification material; private JWK parameters are refused. */
@@ -23,7 +24,22 @@ export type ReceiptKeyResolver = (context: {
23
24
  readonly issuer: string;
24
25
  readonly signal?: AbortSignal;
25
26
  }) => ReceiptKeySet | Promise<ReceiptKeySet>;
26
- export interface ReceiptClaims {
27
+ /** A verified receipt's claims: version 1, or version 2 (v1's plus `surface.revision_hash`). */
28
+ export type ReceiptClaims = ReceiptClaimsV1 | ReceiptClaimsV2;
29
+ /**
30
+ * Receipt v2 (receipt-v2 §3): the claims of receipt v1, unchanged, with `sess_receipt: 2` and
31
+ * `surface.revision_hash`, the SHA-256 of the revision envelope the receipt commits to.
32
+ */
33
+ export interface ReceiptClaimsV2 extends Omit<ReceiptClaimsV1, 'sess_receipt' | 'surface'> {
34
+ sess_receipt: 2;
35
+ surface: {
36
+ revision: number;
37
+ hash: string;
38
+ renderer_version: string;
39
+ revision_hash: string;
40
+ };
41
+ }
42
+ export interface ReceiptClaimsV1 {
27
43
  sess_receipt: 1;
28
44
  iss: string;
29
45
  aud: string;
@@ -83,6 +99,13 @@ export interface VerifyDecisionReceiptInput {
83
99
  * only through its signature under the same trusted keys and issuer.
84
100
  */
85
101
  rendererIdentities?: RendererIdentitiesDocument;
102
+ /**
103
+ * The revision envelope returned beside the receipt (`revision_envelope` on the accepted
104
+ * response, the Session event or the webhook message). Required for a receipt v2, which is
105
+ * refused with `REVISION_ENVELOPE_MISMATCH` without it or with any other envelope; not read for
106
+ * a receipt v1.
107
+ */
108
+ revisionEnvelope?: RevisionEnvelope | null;
86
109
  }
87
110
  export interface VerifyDecisionReceiptOptions {
88
111
  /** An explicit verification instant, useful for deliberate archival verification/tests. */
@@ -94,8 +117,15 @@ export interface VerifyDecisionReceiptOptions {
94
117
  /** Validates and copies the whole set, not merely the key selected by the token. */
95
118
  export declare function validateKeySet(raw: unknown): ReceiptKeySet;
96
119
  /**
97
- * Fully verifies a version-1 receipt and its exact accepted record. Explicit keys make this
98
- * function entirely offline. A valid receipt attests the accepted record, not business authority.
120
+ * Fully verifies a receipt and its exact accepted record. Explicit keys make this function
121
+ * entirely offline. A valid receipt attests the accepted record, not business authority.
122
+ *
123
+ * The protected `typ` decides the version: `sess-receipt+jwt` is receipt v1, verified exactly as
124
+ * before (`revisionEnvelope` is not read); `sess-receipt-2+jwt` is receipt v2, verified only with
125
+ * the revision envelope it commits to. A receipt v2 whose envelope is missing or null, malformed,
126
+ * of another digest than `surface.revision_hash`, or naming another Session, revision, Surface
127
+ * hash or renderer identity is refused with `REVISION_ENVELOPE_MISMATCH`, after the issuer,
128
+ * audience, record, time and signature checks.
99
129
  */
100
130
  export declare function verifyDecisionReceipt(input: VerifyDecisionReceiptInput, options?: VerifyDecisionReceiptOptions): Promise<DeepReadonly<ReceiptClaims>>;
101
131
  /**
@@ -1,6 +1,7 @@
1
1
  import { compactVerify, importJWK } from 'jose';
2
2
  import { abortError, canonicalJson, checkedInstant, deepFreeze, exactKeys, isRecord, jsonDigest, snapshotJson, verificationError, waitWithSignal, } from './json.js';
3
3
  import { BUNDLED_RENDERER_IDENTITIES, verifyRendererList, } from './renderers.js';
4
+ import { parseRevisionEnvelope, revisionHash } from './envelope.js';
4
5
  export const MAX_RECEIPT_BYTES = 64 * 1024;
5
6
  export const MAX_RECEIPT_KEY_SET_BYTES = 256 * 1024;
6
7
  const MAX_KEYS = 64;
@@ -9,6 +10,10 @@ const SESSION_ID = /^ses_[0-9A-HJKMNP-TV-Z]{26}$/;
9
10
  const EVENT_ID = /^evt_[0-9A-HJKMNP-TV-Z]{26}$/;
10
11
  const ACTION_ID = /^[a-z][a-z0-9_]{0,31}$/;
11
12
  const DIGEST = /^sha256:[0-9a-f]{64}$/;
13
+ /** Protected `typ` of a receipt v1 (receipt-v1); it names version 1 only. */
14
+ const RECEIPT_TYP_V1 = 'sess-receipt+jwt';
15
+ /** Protected `typ` of a receipt v2 (receipt-v2); it names version 2 only. */
16
+ const RECEIPT_TYP_V2 = 'sess-receipt-2+jwt';
12
17
  function identifier(value) {
13
18
  return (typeof value === 'string' &&
14
19
  value.length > 0 &&
@@ -87,13 +92,15 @@ function headerOf(encoded) {
87
92
  throw verificationError('UNSUPPORTED_HEADER', 'Duplicate receipt header fields are not supported.');
88
93
  if (parsed.alg !== 'EdDSA')
89
94
  throw verificationError('UNSUPPORTED_ALGORITHM', 'The receipt must use the supported EdDSA algorithm.');
90
- if (parsed.typ !== 'sess-receipt+jwt')
95
+ // The typ names the version: sess-receipt+jwt is receipt v1 only, sess-receipt-2+jwt v2 only.
96
+ const version = parsed.typ === RECEIPT_TYP_V1 ? 1 : parsed.typ === RECEIPT_TYP_V2 ? 2 : null;
97
+ if (version === null)
91
98
  throw verificationError('UNSUPPORTED_TYPE', 'The receipt has an unsupported protected type.');
92
- return parsed;
99
+ return { ...parsed, version };
93
100
  }
94
- function claimsOf(raw) {
95
- if (!isRecord(raw) || raw.sess_receipt !== 1) {
96
- throw verificationError('UNSUPPORTED_RECEIPT_VERSION', 'Only receipt format version 1 is supported.');
101
+ function claimsOf(raw, version) {
102
+ if (!isRecord(raw) || raw.sess_receipt !== version) {
103
+ throw verificationError('UNSUPPORTED_RECEIPT_VERSION', 'The receipt format version does not match its protected type (versions 1 and 2 are supported).');
97
104
  }
98
105
  const top = [
99
106
  'sess_receipt',
@@ -125,7 +132,10 @@ function claimsOf(raw) {
125
132
  raw.exp <= raw.iat ||
126
133
  checkedInstant(raw.accepted_at) === undefined ||
127
134
  !isRecord(surface) ||
128
- !exactKeys(surface, ['revision', 'hash', 'renderer_version']) ||
135
+ !exactKeys(surface, version === 2
136
+ ? ['revision', 'hash', 'renderer_version', 'revision_hash']
137
+ : ['revision', 'hash', 'renderer_version']) ||
138
+ (version === 2 && (typeof surface.revision_hash !== 'string' || !DIGEST.test(surface.revision_hash))) ||
129
139
  !Number.isSafeInteger(surface.revision) ||
130
140
  surface.revision < 1 ||
131
141
  typeof surface.hash !== 'string' ||
@@ -157,8 +167,15 @@ function claimsOf(raw) {
157
167
  return raw;
158
168
  }
159
169
  /**
160
- * Fully verifies a version-1 receipt and its exact accepted record. Explicit keys make this
161
- * function entirely offline. A valid receipt attests the accepted record, not business authority.
170
+ * Fully verifies a receipt and its exact accepted record. Explicit keys make this function
171
+ * entirely offline. A valid receipt attests the accepted record, not business authority.
172
+ *
173
+ * The protected `typ` decides the version: `sess-receipt+jwt` is receipt v1, verified exactly as
174
+ * before (`revisionEnvelope` is not read); `sess-receipt-2+jwt` is receipt v2, verified only with
175
+ * the revision envelope it commits to. A receipt v2 whose envelope is missing or null, malformed,
176
+ * of another digest than `surface.revision_hash`, or naming another Session, revision, Surface
177
+ * hash or renderer identity is refused with `REVISION_ENVELOPE_MISMATCH`, after the issuer,
178
+ * audience, record, time and signature checks.
162
179
  */
163
180
  export async function verifyDecisionReceipt(input, options = {}) {
164
181
  // Capture all caller-owned data and options before a resolver can yield control.
@@ -178,6 +195,14 @@ export async function verifyDecisionReceipt(input, options = {}) {
178
195
  const expected = snapshotJson(input.expected);
179
196
  const acceptedInput = snapshotJson(input.input);
180
197
  const interaction = snapshotJson(input.interaction);
198
+ // Captured now (before a resolver can yield), judged only for a receipt v2 once its signature holds.
199
+ let suppliedEnvelope;
200
+ try {
201
+ suppliedEnvelope = input.revisionEnvelope == null ? null : snapshotJson(input.revisionEnvelope);
202
+ }
203
+ catch {
204
+ suppliedEnvelope = MALFORMED_ENVELOPE;
205
+ }
181
206
  const resolver = input.keyResolver;
182
207
  const keys = input.keys === undefined ? undefined : validateKeySet(input.keys);
183
208
  const rendererList = input.rendererIdentities === undefined ? undefined : snapshotJson(input.rendererIdentities);
@@ -220,7 +245,7 @@ export async function verifyDecisionReceipt(input, options = {}) {
220
245
  catch {
221
246
  throw verificationError('MALFORMED_RECEIPT', 'The receipt payload is not JSON.');
222
247
  }
223
- const claims = claimsOf(snapshotJson(raw));
248
+ const claims = claimsOf(snapshotJson(raw), header.version);
224
249
  if (canonicalJson(claims) !== payloadText) {
225
250
  throw verificationError('NON_CANONICAL_PAYLOAD', 'The signed receipt payload must be RFC 8785 canonical JSON.');
226
251
  }
@@ -278,6 +303,8 @@ export async function verifyDecisionReceipt(input, options = {}) {
278
303
  throw abortError(signal);
279
304
  throw verificationError('INVALID_SIGNATURE', 'The receipt signature did not verify with the trusted Ed25519 key.');
280
305
  }
306
+ if (claims.sess_receipt === 2)
307
+ checkRevisionEnvelope(claims, suppliedEnvelope);
281
308
  // Decision 0009 Amendment 13: the renderer identity is one this release bundles, or one on the
282
309
  // issuer's list that verifies under the same trusted keys.
283
310
  const renderer = claims.surface.renderer_version;
@@ -294,6 +321,22 @@ export async function verifyDecisionReceipt(input, options = {}) {
294
321
  }
295
322
  return deepFreeze(claims);
296
323
  }
324
+ const MALFORMED_ENVELOPE = Symbol('malformed revision envelope');
325
+ /** Receipt v2: the supplied envelope must be the one the receipt commits to (receipt-v2 §7). */
326
+ function checkRevisionEnvelope(claims, supplied) {
327
+ if (supplied === null)
328
+ throw verificationError('REVISION_ENVELOPE_MISMATCH', 'A version 2 receipt is verified only with its revision envelope, and none was supplied.');
329
+ const envelope = parseRevisionEnvelope(supplied);
330
+ if (envelope === null)
331
+ throw verificationError('REVISION_ENVELOPE_MISMATCH', 'The revision envelope is malformed.');
332
+ if (revisionHash(envelope) !== claims.surface.revision_hash)
333
+ throw verificationError('REVISION_ENVELOPE_MISMATCH', 'The revision envelope is not the one the receipt commits to.');
334
+ if (envelope.session_id !== claims.session_id ||
335
+ envelope.revision !== claims.surface.revision ||
336
+ envelope.surface_hash !== claims.surface.hash ||
337
+ envelope.renderer_version !== claims.surface.renderer_version)
338
+ throw verificationError('REVISION_ENVELOPE_MISMATCH', 'The revision envelope names another Session, revision, Surface or renderer.');
339
+ }
297
340
  /** Resolves a kid to a trusted key: from the explicit set, or the trusted resolver (validated). */
298
341
  function trustedKeyLookup(keys, resolver, issuer, signal) {
299
342
  return async (kid) => {
@@ -3,6 +3,8 @@ export interface Operation<T> {
3
3
  name: string;
4
4
  method: 'GET' | 'POST' | 'PATCH' | 'PUT';
5
5
  path: string;
6
+ /** Query parameters, encoded here; the path itself never carries a query. */
7
+ query?: Readonly<Record<string, string>>;
6
8
  status: number;
7
9
  parse?: (value: unknown) => T;
8
10
  body?: unknown;
package/dist/transport.js CHANGED
@@ -4,6 +4,9 @@ import { isLoopback } from './internal/decode.js';
4
4
  import { serializeBody } from './internal/json.js';
5
5
  import { abortError, boundedNumber, deadline, delay, withSignal } from './internal/time.js';
6
6
  import { SDK_VERSION } from './internal/version.js';
7
+ /** Creations, attempted once: an uncertain outcome is `unknown_outcome` and is never retried here. */
8
+ const CREATES = new Set(['sessions.create', 'asks.create']);
9
+ const ASK_CREATE_UNKNOWN = 'Ask creation may have succeeded. It was not retried automatically; an unused Ask reserves nothing, so you may create it again.';
7
10
  const transientStatuses = new Set([408, 429, 500, 502, 503, 504]);
8
11
  const rejections = {
9
12
  400: ['INVALID_SCHEMA', 'UNKNOWN_COMPONENT', 'WEBHOOK_INVALID_URL'],
@@ -253,6 +256,8 @@ export class Transport {
253
256
  op.path.includes('#') ||
254
257
  op.path.includes('?'))
255
258
  throw new SessError('configuration', 'Invalid API resource path.', { outcome: 'not_sent' });
259
+ const query = op.query === undefined ? '' : new URLSearchParams({ ...op.query }).toString();
260
+ const search = query ? `?${query}` : '';
256
261
  const headers = { Accept: 'application/json', 'User-Agent': this.#userAgent };
257
262
  if (body !== undefined)
258
263
  headers['Content-Type'] = 'application/json';
@@ -305,7 +310,7 @@ export class Transport {
305
310
  try {
306
311
  dispatched = true;
307
312
  const pendingResponse = Promise.resolve()
308
- .then(() => this.#fetch(`${this.baseUrl}${op.path}`, {
313
+ .then(() => this.#fetch(`${this.baseUrl}${op.path}${search}`, {
309
314
  method: op.method,
310
315
  headers: { ...headers },
311
316
  ...(body !== undefined ? { body } : {}),
@@ -446,8 +451,11 @@ export class Transport {
446
451
  outcome,
447
452
  idempotencyKey,
448
453
  };
449
- error = new SessError(op.name === 'sessions.create' && outcome === 'unknown' ? 'unknown_outcome' : error.kind, op.name === 'sessions.create' && outcome === 'unknown'
450
- ? 'Session creation may have succeeded. Do not automatically create again; inspect recovery information if available.'
454
+ const uncertainCreate = CREATES.has(op.name) && outcome === 'unknown';
455
+ error = new SessError(uncertainCreate ? 'unknown_outcome' : error.kind, uncertainCreate
456
+ ? op.name === 'asks.create'
457
+ ? ASK_CREATE_UNKNOWN
458
+ : 'Session creation may have succeeded. Do not automatically create again; inspect recovery information if available.'
451
459
  : error.message, details);
452
460
  if (recoveryBody)
453
461
  attachRecovery(error, recoveryBody);
@@ -475,8 +483,10 @@ export class Transport {
475
483
  });
476
484
  if (e.operation)
477
485
  throw e;
478
- throw new SessError(op.name === 'sessions.create' && dispatched ? 'unknown_outcome' : e.kind, op.name === 'sessions.create' && dispatched
479
- ? 'Session creation may have succeeded. Do not automatically create again.'
486
+ throw new SessError(CREATES.has(op.name) && dispatched ? 'unknown_outcome' : e.kind, CREATES.has(op.name) && dispatched
487
+ ? op.name === 'asks.create'
488
+ ? ASK_CREATE_UNKNOWN
489
+ : 'Session creation may have succeeded. Do not automatically create again.'
480
490
  : e.message, {
481
491
  code: e.code,
482
492
  reason: e.reason,
package/dist/types.d.ts CHANGED
@@ -1,19 +1,40 @@
1
1
  import type { components } from './generated/openapi.js';
2
+ import type { RevisionEnvelope } from './receipts/envelope.js';
2
3
  /** Unmodified types generated from the reviewed public HTTP contract. */
3
4
  export type { components, paths, operations } from './generated/openapi.js';
5
+ export type { RevisionEnvelope } from './receipts/envelope.js';
4
6
  type Schemas = components['schemas'];
5
7
  export type RawCreateSessionRequest = Schemas['CreateSessionRequest'];
6
8
  export type RawPublishSessionRequest = Schemas['PatchSessionRequest'];
7
9
  export type CreateSessionResponse = Schemas['CreateSessionResponse'];
8
10
  export type DisplaySession = Schemas['SessionResponse'];
9
- export type InteractiveSession = Schemas['InteractiveSessionResponse'];
11
+ /**
12
+ * Receipt v2 (receipt-v2 §2): `revision_envelope` is written by hand beside the generated
13
+ * contract types. It is present beside a receipt v2 and absent beside a receipt v1.
14
+ */
15
+ interface RevisionEnvelopeMember {
16
+ /**
17
+ * The revision envelope the receipt v2 commits to (`surface.revision_hash`): when the revision
18
+ * was published and, when one of your API keys published it, that key's ID and its label at the
19
+ * time. `receipts.verifyResponse` verifies the receipt with it. Absent beside a receipt v1.
20
+ */
21
+ revision_envelope?: RevisionEnvelope;
22
+ }
23
+ type GeneratedInteractiveSession = Schemas['InteractiveSessionResponse'];
24
+ type GeneratedSessionEvents = Schemas['SessionEventsResponse'];
25
+ export type AcceptedResponse = GeneratedInteractiveSession['responses'][number] & RevisionEnvelopeMember;
26
+ export type InteractiveSession = Omit<GeneratedInteractiveSession, 'responses'> & {
27
+ responses: AcceptedResponse[];
28
+ };
10
29
  export type Session = DisplaySession | InteractiveSession;
11
30
  export type DisplaySurfaceRevision = Schemas['SessionResponse'];
12
31
  export type InteractiveSurfaceRevision = Schemas['InteractiveSurfaceResponse'];
13
32
  export type SurfaceRevision = DisplaySurfaceRevision | InteractiveSurfaceRevision;
14
- export type AcceptedResponse = InteractiveSession['responses'][number];
15
- export type SessionEvents = Schemas['SessionEventsResponse'];
16
- export type SessionEvent = SessionEvents['events'][number];
33
+ /** One Event of `GET /v1/sessions/{id}/events`; `revision_envelope` on `response.accepted` only. */
34
+ export type SessionEvent = GeneratedSessionEvents['events'][number] & RevisionEnvelopeMember;
35
+ export type SessionEvents = Omit<GeneratedSessionEvents, 'events'> & {
36
+ events: SessionEvent[];
37
+ };
17
38
  /**
18
39
  * The Sess link's state at the time of a Session read (Decision 0009 Amendment 10): `live` takes
19
40
  * answers; `lapsed` is past its deadline but the person can still ask for more time, so the
@@ -148,6 +169,15 @@ export type SurfaceComponent = (Component<'heading'> & {
148
169
  option_labels?: {
149
170
  [key: string]: string;
150
171
  };
172
+ /**
173
+ * A rating: with it the schema must be exactly `{ type: 'integer', minimum: 1, maximum: N }`,
174
+ * N from 2 to 10 (stars up to 5, numbered choices above; the answer is the integer).
175
+ * `low` and `high` are optional words at the two ends: a word or two; at most 24 each.
176
+ */
177
+ rating?: {
178
+ low?: string;
179
+ high?: string;
180
+ };
151
181
  schema: FieldSchema;
152
182
  }) | ItemsComponent;
153
183
  type DocumentedAction = RawPublishSessionRequest['interaction']['actions'][number] & {
@@ -197,6 +227,77 @@ export type CreateSessionRequest = {
197
227
  export type PublishSessionRequest = {
198
228
  interaction: InteractiveInteraction;
199
229
  };
230
+ /** `POST /v1/asks`: round one as an interactive create takes it, plus the respondents. */
231
+ export interface CreateAskRequest {
232
+ interaction: InteractiveInteraction;
233
+ respondents: {
234
+ /**
235
+ * How many people may start: at least 2, at most the plan's active-Session limit (Free 25,
236
+ * Starter 50, Pro 100; a trial Ask 2). Exact: it is checked when a person starts.
237
+ */
238
+ max: number;
239
+ /** Advanced: one required "Your name" text field, named `name`, before the first field. Default false. */
240
+ name?: boolean;
241
+ };
242
+ /** Advanced: the one deadline, whole seconds from creation, 30 up to the plan's link lifetime. Absent: that lifetime. */
243
+ expires_in?: number;
244
+ /** Advanced: each respondent's link life from their Start, at least 30 seconds, clamped to what remains. Absent: what remains of the Ask. */
245
+ respondent_expires_in?: number;
246
+ /** Advanced: default true, a respondent's Session completes when its answer is accepted. */
247
+ auto_complete?: boolean;
248
+ }
249
+ export interface CreateAskResponse {
250
+ id: string;
251
+ revision: number;
252
+ /** The link to share with everyone who should answer. Returned once; keep it out of logs. */
253
+ human_url: string;
254
+ /** The Ask's deadline (ISO 8601): from it no one new may start. */
255
+ action_expires_at: string;
256
+ max: number;
257
+ }
258
+ /** Derived at read time: Starts admitted, respondents answered and completed, Starts refused by reason. */
259
+ export interface AskCounts {
260
+ started: number;
261
+ answered: number;
262
+ completed: number;
263
+ refused: {
264
+ full: number;
265
+ closed: number;
266
+ deadline: number;
267
+ minimum_time: number;
268
+ burst: number;
269
+ paused: number;
270
+ network: number;
271
+ };
272
+ }
273
+ /** One respondent as `GET /v1/asks/{id}` lists it: an ordinary Session, or its tombstone once purged. */
274
+ export interface AskRespondentRecord {
275
+ id: string;
276
+ status: 'active' | 'responded' | 'completed' | 'purged';
277
+ revision: number;
278
+ started_at: string;
279
+ completed_at: string | null;
280
+ /** Every accepted answer, in order (none for a tombstone). */
281
+ responses: AcceptedResponse[];
282
+ }
283
+ /** `POST /v1/asks/{id}/close`: the Ask after the close (no answers). */
284
+ export interface AskCloseResponse {
285
+ id: string;
286
+ status: 'open' | 'closed';
287
+ /** Which closed it: `max` (the last place was started), `owner` (you) or `deadline`. Null while open. */
288
+ closed_by: 'max' | 'owner' | 'deadline' | null;
289
+ closed_at: string | null;
290
+ max: number;
291
+ action_expires_at: string;
292
+ auto_complete: boolean;
293
+ counts: AskCounts;
294
+ }
295
+ /** `GET /v1/asks/{id}`: one page of respondents in Start order. */
296
+ export interface AskResponse extends AskCloseResponse {
297
+ sessions: AskRespondentRecord[];
298
+ /** Pass as `cursor` to read the next page; null on the last page. */
299
+ next_cursor: string | null;
300
+ }
200
301
  export interface ResponseMeta {
201
302
  status: number;
202
303
  requestId?: string;
@@ -1,6 +1,14 @@
1
1
  import type { components } from '../generated/openapi.js';
2
2
  import { type DeepReadonly } from '../receipts/json.js';
3
- export type WebhookEvent = components['schemas']['WebhookDelivery'];
3
+ import type { RevisionEnvelope } from '../receipts/envelope.js';
4
+ /**
5
+ * A `response.accepted` delivery. A receipt v2's message also carries `revision_envelope` beside
6
+ * `receipt` (receipt-v2 §10); a receipt v1's message has no such member.
7
+ */
8
+ export type WebhookEvent = components['schemas']['WebhookDelivery'] & {
9
+ /** Beside a receipt v2 only: the revision envelope the receipt commits to. */
10
+ revision_envelope?: RevisionEnvelope;
11
+ };
4
12
  export type WebhookChallenge = components['schemas']['WebhookVerification'];
5
13
  export type VerifiedWebhook = DeepReadonly<WebhookEvent | WebhookChallenge>;
6
14
  export type WebhookHeaders = Headers | Readonly<Record<string, string | readonly string[] | undefined>>;
@@ -148,6 +148,9 @@ export function verifyWebhook(rawBody, headers, options) {
148
148
  }
149
149
  return deepFreeze(value);
150
150
  }
151
+ // A receipt v2's message carries its revision envelope beside the receipt; a receipt v1's has
152
+ // exactly the members it always had. The envelope itself is judged by receipt verification.
153
+ const withEnvelope = Object.hasOwn(value, 'revision_envelope');
151
154
  if (value.type !== 'response.accepted' ||
152
155
  !exactKeys(value, [
153
156
  'type',
@@ -159,7 +162,9 @@ export function verifyWebhook(rawBody, headers, options) {
159
162
  'data',
160
163
  'accepted_at',
161
164
  'receipt',
165
+ ...(withEnvelope ? ['revision_envelope'] : []),
162
166
  ]) ||
167
+ (withEnvelope && (!isRecord(value.revision_envelope) || typeof value.receipt !== 'string')) ||
163
168
  typeof value.event_id !== 'string' ||
164
169
  !EVENT_ID.test(value.event_id) ||
165
170
  value.event_id !== id ||
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sess.si/sdk",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Ask a person from your server and continue with their verified answer. Sess API client with receipt and webhook verification.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",