@sess.si/sdk 0.1.0-rc.4 → 0.1.0-rc.7
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 +56 -1
- package/NOTICE +18 -0
- package/README.md +102 -30
- package/dist/ask.d.ts +150 -0
- package/dist/ask.d.ts.map +1 -0
- package/dist/ask.js +465 -0
- package/dist/ask.js.map +1 -0
- package/dist/cli/main.d.ts +3 -0
- package/dist/cli/main.d.ts.map +1 -0
- package/dist/cli/main.js +8 -0
- package/dist/cli/main.js.map +1 -0
- package/dist/cli/verify.d.ts +14 -0
- package/dist/cli/verify.d.ts.map +1 -0
- package/dist/cli/verify.js +277 -0
- package/dist/cli/verify.js.map +1 -0
- package/dist/client.d.ts +8 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +10 -0
- package/dist/client.js.map +1 -1
- package/dist/generated/openapi.d.ts +6461 -1009
- package/dist/generated/openapi.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internal/decode.d.ts.map +1 -1
- package/dist/internal/decode.js +4 -1
- package/dist/internal/decode.js.map +1 -1
- package/dist/polling.d.ts +8 -0
- package/dist/polling.d.ts.map +1 -1
- package/dist/polling.js +32 -1
- package/dist/polling.js.map +1 -1
- package/dist/qr/encoder.d.ts +11 -0
- package/dist/qr/encoder.d.ts.map +1 -0
- package/dist/qr/encoder.js +344 -0
- package/dist/qr/encoder.js.map +1 -0
- package/dist/qr/index.d.ts +56 -0
- package/dist/qr/index.d.ts.map +1 -0
- package/dist/qr/index.js +151 -0
- package/dist/qr/index.js.map +1 -0
- package/dist/receipts/bundle.d.ts +124 -0
- package/dist/receipts/bundle.d.ts.map +1 -0
- package/dist/receipts/bundle.js +424 -0
- package/dist/receipts/bundle.js.map +1 -0
- package/dist/receipts/index.d.ts +2 -0
- package/dist/receipts/index.d.ts.map +1 -1
- package/dist/receipts/index.js +1 -0
- package/dist/receipts/index.js.map +1 -1
- package/dist/sessions.d.ts.map +1 -1
- package/dist/sessions.js +7 -0
- package/dist/sessions.js.map +1 -1
- package/dist/transport.d.ts +2 -0
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js +11 -2
- package/dist/transport.js.map +1 -1
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/webhooks/index.js +1 -1
- package/dist/webhooks/index.js.map +1 -1
- package/package.json +12 -4
- package/src/ask.ts +636 -0
- package/src/cli/main.ts +8 -0
- package/src/cli/verify.ts +291 -0
- package/src/client.ts +14 -0
- package/src/generated/openapi.ts +6724 -1163
- package/src/index.ts +1 -0
- package/src/internal/decode.ts +3 -1
- package/src/polling.ts +45 -1
- package/src/qr/encoder.ts +345 -0
- package/src/qr/index.ts +203 -0
- package/src/receipts/bundle.ts +547 -0
- package/src/receipts/index.ts +11 -0
- package/src/sessions.ts +11 -0
- package/src/transport.ts +11 -2
- package/src/types.ts +14 -1
- package/src/webhooks/index.ts +1 -1
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
// Decision bundles (bundle-v1, docs/spec/bundle-v1.md): a deliberate disclosure of one accepted
|
|
2
|
+
// decision that anyone can check. verifyDecisionBundle is the SDK face of the Sess verification
|
|
3
|
+
// core: the same check order, bounds, reasons, result object and key-trust rules, proven against
|
|
4
|
+
// the shared conformance corpus. Keys and expected context come only from the caller; nothing in
|
|
5
|
+
// the bundle is trusted. A valid result states what the issuer accepted from someone holding the
|
|
6
|
+
// Session's human link: never who that person is, nor that anything was authorized or executed.
|
|
7
|
+
//
|
|
8
|
+
// verifyDecisionReceipt is a separate, stricter record-bound interface and is unchanged by this
|
|
9
|
+
// module. This module shares its trusted-key validation and canonical JSON helpers.
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { decodeProtectedHeader, errors, importJWK, jwtVerify, type JWTPayload } from 'jose';
|
|
12
|
+
import { canonicalJson, exactKeys, isRecord, jsonDigest } from './json.js';
|
|
13
|
+
import { validateKeySet, type ReceiptKeySet } from './verify.js';
|
|
14
|
+
|
|
15
|
+
const BUNDLE_TYPE = 'sess.decision-bundle';
|
|
16
|
+
const BUNDLE_VERSION = 1;
|
|
17
|
+
const RECEIPT_ALG = 'EdDSA';
|
|
18
|
+
const RECEIPT_TYP = 'sess-receipt+jwt';
|
|
19
|
+
|
|
20
|
+
/** Bounds of a bundle (bundle-v1 §4). A bundle beyond any of them is `oversized`. */
|
|
21
|
+
export const BUNDLE_LIMITS = Object.freeze({
|
|
22
|
+
/** RFC 8785 canonical UTF-8 bytes of the whole bundle. */
|
|
23
|
+
bytes: 1_048_576,
|
|
24
|
+
/** Nesting depth of any value (the bundle object itself is depth 1). */
|
|
25
|
+
depth: 32,
|
|
26
|
+
/** Items in any one array. */
|
|
27
|
+
arrayItems: 1_000,
|
|
28
|
+
/** Members of any one object. */
|
|
29
|
+
objectMembers: 1_000,
|
|
30
|
+
/** JSON values in the whole bundle. */
|
|
31
|
+
nodes: 100_000,
|
|
32
|
+
/** Characters of the receipt's compact JWS. */
|
|
33
|
+
receiptChars: 32_768,
|
|
34
|
+
/** Public keys in `keys.keys`. */
|
|
35
|
+
keys: 16,
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
/** How far in the future a receipt's `iat` may be before it is `not_yet_valid`, in seconds. */
|
|
39
|
+
const CLOCK_TOLERANCE_S = 60;
|
|
40
|
+
|
|
41
|
+
/** One public Ed25519 JWK as disclosed in a bundle. */
|
|
42
|
+
export interface BundleJwk {
|
|
43
|
+
kty: 'OKP';
|
|
44
|
+
crv: 'Ed25519';
|
|
45
|
+
x: string;
|
|
46
|
+
kid: string;
|
|
47
|
+
alg?: 'EdDSA';
|
|
48
|
+
use?: 'sig';
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A bundle-v1 object: exactly these members. */
|
|
52
|
+
export interface DecisionBundle {
|
|
53
|
+
type: 'sess.decision-bundle';
|
|
54
|
+
version: 1;
|
|
55
|
+
/** The receipt-v1 compact JWS, exactly as issued. */
|
|
56
|
+
receipt: string;
|
|
57
|
+
/** The accepted record: the normalized Surface document and the validated input, complete. */
|
|
58
|
+
content: { surface: Record<string, unknown>; input: Record<string, unknown> };
|
|
59
|
+
/** The issuer's public keys. Disclosed for convenience; a verifier never trusts them. */
|
|
60
|
+
keys: { keys: BundleJwk[] };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Receipt-v1 rejection codes (receipt-v1 §6). */
|
|
64
|
+
type ReceiptV1Rejection =
|
|
65
|
+
| 'malformed'
|
|
66
|
+
| 'algorithm'
|
|
67
|
+
| 'missing_kid'
|
|
68
|
+
| 'unknown_kid'
|
|
69
|
+
| 'type'
|
|
70
|
+
| 'signature'
|
|
71
|
+
| 'issuer'
|
|
72
|
+
| 'audience'
|
|
73
|
+
| 'expired'
|
|
74
|
+
| 'claims';
|
|
75
|
+
|
|
76
|
+
/** Why a bundle is invalid: the first check that failed (bundle-v1 §5). */
|
|
77
|
+
export type BundleRejection =
|
|
78
|
+
| 'malformed'
|
|
79
|
+
| 'oversized'
|
|
80
|
+
| 'unsupported_version'
|
|
81
|
+
| 'receipt_malformed'
|
|
82
|
+
| Exclude<ReceiptV1Rejection, 'malformed'>
|
|
83
|
+
| 'not_yet_valid'
|
|
84
|
+
| 'surface_mismatch'
|
|
85
|
+
| 'input_mismatch'
|
|
86
|
+
| 'context_mismatch';
|
|
87
|
+
|
|
88
|
+
/** Application context from the caller's trusted configuration, never from the bundle. */
|
|
89
|
+
export interface ExpectedBundleContext {
|
|
90
|
+
/** The recipient the caller expects (the receipt's `aud`: the Session's workspace). */
|
|
91
|
+
audience?: string;
|
|
92
|
+
workspaceId?: string;
|
|
93
|
+
sessionId?: string;
|
|
94
|
+
eventId?: string;
|
|
95
|
+
/** The Surface revision the decision must be on. */
|
|
96
|
+
revision?: number;
|
|
97
|
+
actionId?: string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Context member names as the result reports them (receipt claim paths). */
|
|
101
|
+
export type BundleContextField =
|
|
102
|
+
'audience' | 'workspace_id' | 'session_id' | 'event_id' | 'surface.revision' | 'action.id';
|
|
103
|
+
|
|
104
|
+
export interface VerifyDecisionBundleOptions {
|
|
105
|
+
/** The issuer the caller trusts (the receipt's `iss`). */
|
|
106
|
+
issuer: string;
|
|
107
|
+
/** The issuer's public verification keys the caller trusts. Keys inside a bundle are never used. */
|
|
108
|
+
trustedKeys: ReceiptKeySet;
|
|
109
|
+
expectedContext?: ExpectedBundleContext;
|
|
110
|
+
/** Defaults to the current time (receipt-v1 current-time expiry). */
|
|
111
|
+
now?: Date;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The verified receipt, presented only when the bundle is valid. */
|
|
115
|
+
export interface VerifiedReceiptSummary {
|
|
116
|
+
key_id: string;
|
|
117
|
+
issuer: string;
|
|
118
|
+
audience: string;
|
|
119
|
+
event_id: string;
|
|
120
|
+
session_id: string;
|
|
121
|
+
workspace_id: string;
|
|
122
|
+
step_id: string;
|
|
123
|
+
surface: { revision: number; hash: string; renderer_version: string };
|
|
124
|
+
action: { id: string; label: string; summary: string };
|
|
125
|
+
input_hash: string;
|
|
126
|
+
accepted_at: string;
|
|
127
|
+
expires_at: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** The result every face reports (bundle-v1 §6). JSON-serializable. */
|
|
131
|
+
export interface DecisionBundleVerification {
|
|
132
|
+
valid: boolean;
|
|
133
|
+
reason: BundleRejection | null;
|
|
134
|
+
/** The verification time, RFC 3339 UTC. */
|
|
135
|
+
checked_at: string;
|
|
136
|
+
/** Whether the disclosed Surface and input match the receipt's hashes. */
|
|
137
|
+
content: 'verified' | 'mismatch' | 'not_checked';
|
|
138
|
+
context: {
|
|
139
|
+
status: 'verified' | 'incomplete' | 'mismatch' | 'unchecked' | 'not_checked';
|
|
140
|
+
/** The context members the caller supplied, in a fixed order. */
|
|
141
|
+
checked: BundleContextField[];
|
|
142
|
+
mismatches: BundleContextField[];
|
|
143
|
+
};
|
|
144
|
+
/** `matched_caller_context` only when the caller's full context (with audience) matched. */
|
|
145
|
+
application_purpose: 'unchecked' | 'matched_caller_context';
|
|
146
|
+
/** Link possession only: never a named or verified person. Null when invalid. */
|
|
147
|
+
actor: { assurance: 'link_holder' } | null;
|
|
148
|
+
receipt: VerifiedReceiptSummary | null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
interface ReceiptV1Claims {
|
|
152
|
+
sess_receipt: 1;
|
|
153
|
+
iss: string;
|
|
154
|
+
aud: string;
|
|
155
|
+
jti: string;
|
|
156
|
+
iat: number;
|
|
157
|
+
exp: number;
|
|
158
|
+
accepted_at: string;
|
|
159
|
+
workspace_id: string;
|
|
160
|
+
session_id: string;
|
|
161
|
+
step_id: string;
|
|
162
|
+
event_id: string;
|
|
163
|
+
surface: { revision: number; hash: string; renderer_version: string };
|
|
164
|
+
action: { id: string; label: string; summary: string };
|
|
165
|
+
input_hash: string;
|
|
166
|
+
actor: { assurance: 'link_holder'; subject: string };
|
|
167
|
+
return_binding: { recipient: string; return_channel_id: string | null };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ------------------------------------------------------------------------------------------------
|
|
171
|
+
// receipt-v1 §6, in its order and with its codes
|
|
172
|
+
// ------------------------------------------------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
class ReceiptV1Failure extends Error {
|
|
175
|
+
readonly code: ReceiptV1Rejection;
|
|
176
|
+
constructor(code: ReceiptV1Rejection) {
|
|
177
|
+
super(code);
|
|
178
|
+
this.code = code;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const DIGEST = /^sha256:[0-9a-f]{64}$/;
|
|
183
|
+
const nonEmpty = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
|
|
184
|
+
|
|
185
|
+
function receiptV1Claims(p: Record<string, unknown>): ReceiptV1Claims {
|
|
186
|
+
const top = [
|
|
187
|
+
'sess_receipt',
|
|
188
|
+
'iss',
|
|
189
|
+
'aud',
|
|
190
|
+
'jti',
|
|
191
|
+
'iat',
|
|
192
|
+
'exp',
|
|
193
|
+
'accepted_at',
|
|
194
|
+
'workspace_id',
|
|
195
|
+
'session_id',
|
|
196
|
+
'step_id',
|
|
197
|
+
'event_id',
|
|
198
|
+
'surface',
|
|
199
|
+
'action',
|
|
200
|
+
'input_hash',
|
|
201
|
+
'actor',
|
|
202
|
+
'return_binding',
|
|
203
|
+
];
|
|
204
|
+
const s = p.surface;
|
|
205
|
+
const a = p.action;
|
|
206
|
+
const act = p.actor;
|
|
207
|
+
const rb = p.return_binding;
|
|
208
|
+
const ok =
|
|
209
|
+
exactKeys(p, top) &&
|
|
210
|
+
p.sess_receipt === 1 &&
|
|
211
|
+
[p.iss, p.aud, p.jti, p.accepted_at, p.workspace_id, p.session_id, p.step_id, p.event_id].every(
|
|
212
|
+
nonEmpty,
|
|
213
|
+
) &&
|
|
214
|
+
p.jti === p.event_id &&
|
|
215
|
+
Number.isSafeInteger(p.iat) &&
|
|
216
|
+
Number.isSafeInteger(p.exp) &&
|
|
217
|
+
typeof p.input_hash === 'string' &&
|
|
218
|
+
DIGEST.test(p.input_hash) &&
|
|
219
|
+
isRecord(s) &&
|
|
220
|
+
exactKeys(s, ['revision', 'hash', 'renderer_version']) &&
|
|
221
|
+
Number.isSafeInteger(s.revision) &&
|
|
222
|
+
(s.revision as number) >= 1 &&
|
|
223
|
+
typeof s.hash === 'string' &&
|
|
224
|
+
DIGEST.test(s.hash) &&
|
|
225
|
+
nonEmpty(s.renderer_version) &&
|
|
226
|
+
isRecord(a) &&
|
|
227
|
+
exactKeys(a, ['id', 'label', 'summary']) &&
|
|
228
|
+
nonEmpty(a.id) &&
|
|
229
|
+
nonEmpty(a.label) &&
|
|
230
|
+
typeof a.summary === 'string' &&
|
|
231
|
+
isRecord(act) &&
|
|
232
|
+
exactKeys(act, ['assurance', 'subject']) &&
|
|
233
|
+
act.assurance === 'link_holder' &&
|
|
234
|
+
typeof act.subject === 'string' &&
|
|
235
|
+
act.subject.startsWith(`${p.workspace_id as string}:`) &&
|
|
236
|
+
isRecord(rb) &&
|
|
237
|
+
exactKeys(rb, ['recipient', 'return_channel_id']) &&
|
|
238
|
+
rb.recipient === p.aud &&
|
|
239
|
+
(rb.return_channel_id === null || nonEmpty(rb.return_channel_id));
|
|
240
|
+
if (!ok) throw new ReceiptV1Failure('claims');
|
|
241
|
+
return p as unknown as ReceiptV1Claims;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* The receipt-v1 rules against trusted keys: compact JWS, pinned EdDSA, a kid the caller trusts
|
|
246
|
+
* (no fallback key), the receipt typ, the signature, the trusted issuer, the expected audience,
|
|
247
|
+
* current-time expiry, then the claims and their canonical serialization. Throws ReceiptV1Failure
|
|
248
|
+
* with the first failing code; any other error means the receipt could not be read at all.
|
|
249
|
+
*/
|
|
250
|
+
async function verifyReceiptV1(
|
|
251
|
+
jws: string,
|
|
252
|
+
keys: ReceiptKeySet,
|
|
253
|
+
options: { issuer: string; audience: string; now: Date },
|
|
254
|
+
): Promise<ReceiptV1Claims> {
|
|
255
|
+
if (jws.split('.').length !== 3) throw new ReceiptV1Failure('malformed');
|
|
256
|
+
let header: ReturnType<typeof decodeProtectedHeader>;
|
|
257
|
+
try {
|
|
258
|
+
header = decodeProtectedHeader(jws);
|
|
259
|
+
} catch {
|
|
260
|
+
throw new ReceiptV1Failure('malformed');
|
|
261
|
+
}
|
|
262
|
+
if (header.alg !== RECEIPT_ALG) throw new ReceiptV1Failure('algorithm');
|
|
263
|
+
if (typeof header.kid !== 'string' || header.kid.length === 0) throw new ReceiptV1Failure('missing_kid');
|
|
264
|
+
const jwk = keys.keys.find((k) => k.kid === header.kid);
|
|
265
|
+
if (!jwk) throw new ReceiptV1Failure('unknown_kid');
|
|
266
|
+
if (header.typ !== RECEIPT_TYP) throw new ReceiptV1Failure('type');
|
|
267
|
+
const key = await importJWK({ kty: jwk.kty, crv: jwk.crv, x: jwk.x }, RECEIPT_ALG);
|
|
268
|
+
let payload: JWTPayload;
|
|
269
|
+
try {
|
|
270
|
+
({ payload } = await jwtVerify(jws, key, {
|
|
271
|
+
algorithms: [RECEIPT_ALG],
|
|
272
|
+
typ: RECEIPT_TYP,
|
|
273
|
+
issuer: options.issuer,
|
|
274
|
+
audience: options.audience,
|
|
275
|
+
currentDate: options.now,
|
|
276
|
+
requiredClaims: ['iss', 'aud', 'iat', 'exp', 'jti'],
|
|
277
|
+
}));
|
|
278
|
+
} catch (e) {
|
|
279
|
+
if (e instanceof errors.JWSSignatureVerificationFailed) throw new ReceiptV1Failure('signature');
|
|
280
|
+
if (e instanceof errors.JWTExpired) throw new ReceiptV1Failure('expired');
|
|
281
|
+
if (e instanceof errors.JOSEAlgNotAllowed) throw new ReceiptV1Failure('algorithm');
|
|
282
|
+
if (e instanceof errors.JWTClaimValidationFailed) {
|
|
283
|
+
if (e.claim === 'aud') throw new ReceiptV1Failure('audience');
|
|
284
|
+
if (e.claim === 'iss') throw new ReceiptV1Failure('issuer');
|
|
285
|
+
throw new ReceiptV1Failure('claims');
|
|
286
|
+
}
|
|
287
|
+
throw new ReceiptV1Failure('malformed');
|
|
288
|
+
}
|
|
289
|
+
const claims = receiptV1Claims(payload as Record<string, unknown>);
|
|
290
|
+
// The signed bytes must be exactly the canonical form of the claims.
|
|
291
|
+
const signed = Buffer.from(jws.split('.')[1] as string, 'base64url');
|
|
292
|
+
if (`sha256:${createHash('sha256').update(signed).digest('hex')}` !== jsonDigest(claims))
|
|
293
|
+
throw new ReceiptV1Failure('claims');
|
|
294
|
+
return claims;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// ------------------------------------------------------------------------------------------------
|
|
298
|
+
// bundle-v1 §2 and §4: shape and bounds
|
|
299
|
+
// ------------------------------------------------------------------------------------------------
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Walks a value iteratively (nesting cannot exhaust the stack): 'oversized' for an exceeded
|
|
303
|
+
* bound, 'malformed' for a value with no JSON form, else null.
|
|
304
|
+
*/
|
|
305
|
+
function structuralProblem(value: unknown): 'malformed' | 'oversized' | null {
|
|
306
|
+
const stack: Array<[unknown, number]> = [[value, 1]];
|
|
307
|
+
let nodes = 0;
|
|
308
|
+
let textBytes = 0;
|
|
309
|
+
while (stack.length > 0) {
|
|
310
|
+
const [v, depth] = stack.pop() as [unknown, number];
|
|
311
|
+
nodes += 1;
|
|
312
|
+
if (nodes > BUNDLE_LIMITS.nodes || depth > BUNDLE_LIMITS.depth) return 'oversized';
|
|
313
|
+
if (v === null || typeof v === 'boolean') continue;
|
|
314
|
+
if (typeof v === 'number') {
|
|
315
|
+
if (!Number.isFinite(v)) return 'malformed';
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
if (typeof v === 'string') {
|
|
319
|
+
// A lower bound of the UTF-8 size: stops a huge string before canonicalization.
|
|
320
|
+
textBytes += v.length;
|
|
321
|
+
if (textBytes > BUNDLE_LIMITS.bytes) return 'oversized';
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (Array.isArray(v)) {
|
|
325
|
+
if (v.length > BUNDLE_LIMITS.arrayItems) return 'oversized';
|
|
326
|
+
for (const item of v) stack.push([item, depth + 1]);
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype) {
|
|
330
|
+
const keys = Object.keys(v);
|
|
331
|
+
if (keys.length > BUNDLE_LIMITS.objectMembers) return 'oversized';
|
|
332
|
+
for (const k of keys) {
|
|
333
|
+
textBytes += k.length;
|
|
334
|
+
stack.push([(v as Record<string, unknown>)[k], depth + 1]);
|
|
335
|
+
}
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
// undefined, functions, symbols, bigint, class instances: no JSON form.
|
|
339
|
+
return 'malformed';
|
|
340
|
+
}
|
|
341
|
+
return null;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const COMPACT_JWS = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;
|
|
345
|
+
const KID = /^[A-Za-z0-9._-]{1,64}$/;
|
|
346
|
+
const JWK_MEMBERS = new Set(['kty', 'crv', 'x', 'kid', 'alg', 'use']);
|
|
347
|
+
|
|
348
|
+
function publicJwkProblem(k: unknown): boolean {
|
|
349
|
+
if (!isRecord(k)) return true;
|
|
350
|
+
// Only the public members: any other member (d, p, q, k, …) makes the bundle malformed, so a
|
|
351
|
+
// bundle never carries private key material.
|
|
352
|
+
if (Object.keys(k).some((m) => !JWK_MEMBERS.has(m))) return true;
|
|
353
|
+
return !(
|
|
354
|
+
k.kty === 'OKP' &&
|
|
355
|
+
k.crv === 'Ed25519' &&
|
|
356
|
+
typeof k.x === 'string' &&
|
|
357
|
+
/^[A-Za-z0-9_-]{43}$/.test(k.x) &&
|
|
358
|
+
typeof k.kid === 'string' &&
|
|
359
|
+
KID.test(k.kid) &&
|
|
360
|
+
(k.alg === undefined || k.alg === RECEIPT_ALG) &&
|
|
361
|
+
(k.use === undefined || k.use === 'sig')
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function shapeProblem(b: unknown): 'malformed' | 'oversized' | 'unsupported_version' | null {
|
|
366
|
+
if (!isRecord(b)) return 'malformed';
|
|
367
|
+
const structural = structuralProblem(b);
|
|
368
|
+
if (structural) return structural;
|
|
369
|
+
let size: number;
|
|
370
|
+
try {
|
|
371
|
+
size = Buffer.byteLength(canonicalJson(b), 'utf8');
|
|
372
|
+
} catch {
|
|
373
|
+
return 'malformed'; // e.g. a lone surrogate
|
|
374
|
+
}
|
|
375
|
+
if (size > BUNDLE_LIMITS.bytes) return 'oversized';
|
|
376
|
+
if (b.type !== BUNDLE_TYPE) return 'malformed';
|
|
377
|
+
if (b.version !== BUNDLE_VERSION) {
|
|
378
|
+
return Number.isSafeInteger(b.version) && (b.version as number) > BUNDLE_VERSION
|
|
379
|
+
? 'unsupported_version'
|
|
380
|
+
: 'malformed';
|
|
381
|
+
}
|
|
382
|
+
if (!exactKeys(b, ['type', 'version', 'receipt', 'content', 'keys'])) return 'malformed';
|
|
383
|
+
if (typeof b.receipt !== 'string') return 'malformed';
|
|
384
|
+
if (b.receipt.length > BUNDLE_LIMITS.receiptChars) return 'oversized';
|
|
385
|
+
const c = b.content;
|
|
386
|
+
if (!isRecord(c) || !exactKeys(c, ['surface', 'input'])) return 'malformed';
|
|
387
|
+
if (!isRecord(c.surface) || !isRecord(c.input)) return 'malformed';
|
|
388
|
+
const k = b.keys;
|
|
389
|
+
if (!isRecord(k) || !exactKeys(k, ['keys']) || !Array.isArray(k.keys)) return 'malformed';
|
|
390
|
+
if (k.keys.length > BUNDLE_LIMITS.keys) return 'oversized';
|
|
391
|
+
if (k.keys.some(publicJwkProblem)) return 'malformed';
|
|
392
|
+
const kids = k.keys.map((j) => (j as BundleJwk).kid);
|
|
393
|
+
if (new Set(kids).size !== kids.length) return 'malformed';
|
|
394
|
+
return null;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** The receipt's declared (unverified) `aud`, used only when the caller expects none. */
|
|
398
|
+
function declaredAudience(jws: string): string | undefined {
|
|
399
|
+
if (!COMPACT_JWS.test(jws)) return undefined;
|
|
400
|
+
try {
|
|
401
|
+
const payload = JSON.parse(
|
|
402
|
+
Buffer.from(jws.split('.')[1] as string, 'base64url').toString('utf8'),
|
|
403
|
+
) as unknown;
|
|
404
|
+
return isRecord(payload) && typeof payload.aud === 'string' && payload.aud.length > 0
|
|
405
|
+
? payload.aud
|
|
406
|
+
: undefined;
|
|
407
|
+
} catch {
|
|
408
|
+
return undefined;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function checkOptions(o: VerifyDecisionBundleOptions): ReceiptKeySet {
|
|
413
|
+
if (typeof o?.issuer !== 'string' || o.issuer.length === 0)
|
|
414
|
+
throw new TypeError('verifyDecisionBundle needs a non-empty trusted issuer');
|
|
415
|
+
if (!o.trustedKeys) throw new TypeError('verifyDecisionBundle needs trusted keys');
|
|
416
|
+
let keys: ReceiptKeySet;
|
|
417
|
+
try {
|
|
418
|
+
keys = validateKeySet(o.trustedKeys);
|
|
419
|
+
} catch {
|
|
420
|
+
throw new TypeError('trustedKeys must be a JWK Set of public Ed25519 keys with unique kids');
|
|
421
|
+
}
|
|
422
|
+
if (o.now !== undefined && (!(o.now instanceof Date) || Number.isNaN(o.now.getTime())))
|
|
423
|
+
throw new TypeError('now must be a valid Date');
|
|
424
|
+
const e = o.expectedContext;
|
|
425
|
+
if (e === undefined) return keys;
|
|
426
|
+
if (!isRecord(e as unknown)) throw new TypeError('expectedContext must be an object');
|
|
427
|
+
for (const k of ['audience', 'workspaceId', 'sessionId', 'eventId', 'actionId'] as const)
|
|
428
|
+
if (e[k] !== undefined && (typeof e[k] !== 'string' || e[k].length === 0))
|
|
429
|
+
throw new TypeError(`expectedContext.${k} must be a non-empty string`);
|
|
430
|
+
if (e.revision !== undefined && (!Number.isSafeInteger(e.revision) || e.revision < 1))
|
|
431
|
+
throw new TypeError('expectedContext.revision must be a positive integer');
|
|
432
|
+
return keys;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function contextChecks(
|
|
436
|
+
e: ExpectedBundleContext | undefined,
|
|
437
|
+
c: ReceiptV1Claims | null,
|
|
438
|
+
): Array<{ field: BundleContextField; ok: boolean }> {
|
|
439
|
+
if (!e) return [];
|
|
440
|
+
const all: Array<[BundleContextField, unknown, unknown]> = [
|
|
441
|
+
['audience', e.audience, c?.aud],
|
|
442
|
+
['workspace_id', e.workspaceId, c?.workspace_id],
|
|
443
|
+
['session_id', e.sessionId, c?.session_id],
|
|
444
|
+
['event_id', e.eventId, c?.event_id],
|
|
445
|
+
['surface.revision', e.revision, c?.surface.revision],
|
|
446
|
+
['action.id', e.actionId, c?.action.id],
|
|
447
|
+
];
|
|
448
|
+
return all
|
|
449
|
+
.filter(([, expected]) => expected !== undefined)
|
|
450
|
+
.map(([field, expected, actual]) => ({ field, ok: expected === actual }));
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// ------------------------------------------------------------------------------------------------
|
|
454
|
+
// Verification
|
|
455
|
+
// ------------------------------------------------------------------------------------------------
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Verifies a bundle-v1 decision bundle offline against the issuer and keys the caller trusts.
|
|
459
|
+
* Every outcome about the bundle is a result, never an exception; only invalid options throw a
|
|
460
|
+
* TypeError. Order (bundle-v1 §5): shape and bounds; the receipt by the receipt-v1 rules; not
|
|
461
|
+
* issued in the future; the disclosed Surface and input against the receipt's hashes; then the
|
|
462
|
+
* caller's expected context.
|
|
463
|
+
*/
|
|
464
|
+
export async function verifyDecisionBundle(
|
|
465
|
+
bundle: unknown,
|
|
466
|
+
options: VerifyDecisionBundleOptions,
|
|
467
|
+
): Promise<DecisionBundleVerification> {
|
|
468
|
+
const trustedKeys = checkOptions(options);
|
|
469
|
+
const now = options.now ?? new Date();
|
|
470
|
+
const expected = options.expectedContext;
|
|
471
|
+
const supplied = contextChecks(expected, null).map((x) => x.field);
|
|
472
|
+
const invalid = (
|
|
473
|
+
reason: BundleRejection,
|
|
474
|
+
over: Partial<Pick<DecisionBundleVerification, 'content' | 'context'>> = {},
|
|
475
|
+
): DecisionBundleVerification => ({
|
|
476
|
+
valid: false,
|
|
477
|
+
reason,
|
|
478
|
+
checked_at: now.toISOString(),
|
|
479
|
+
content: 'not_checked',
|
|
480
|
+
context: { status: 'not_checked', checked: supplied, mismatches: [] },
|
|
481
|
+
application_purpose: 'unchecked',
|
|
482
|
+
actor: null,
|
|
483
|
+
receipt: null,
|
|
484
|
+
...over,
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
const shape = shapeProblem(bundle);
|
|
488
|
+
if (shape) return invalid(shape);
|
|
489
|
+
const b = bundle as DecisionBundle;
|
|
490
|
+
|
|
491
|
+
// Without an expected audience the receipt is checked against its own declared (signed) `aud`;
|
|
492
|
+
// the result then reports the context as unchecked.
|
|
493
|
+
const audience = expected?.audience ?? declaredAudience(b.receipt);
|
|
494
|
+
if (audience === undefined) return invalid('receipt_malformed');
|
|
495
|
+
let claims: ReceiptV1Claims;
|
|
496
|
+
try {
|
|
497
|
+
claims = await verifyReceiptV1(b.receipt, trustedKeys, { issuer: options.issuer, audience, now });
|
|
498
|
+
} catch (e) {
|
|
499
|
+
if (!(e instanceof ReceiptV1Failure)) return invalid('receipt_malformed');
|
|
500
|
+
if (e.code === 'audience')
|
|
501
|
+
return invalid('audience', {
|
|
502
|
+
context: { status: 'mismatch', checked: supplied, mismatches: ['audience'] },
|
|
503
|
+
});
|
|
504
|
+
return invalid(e.code === 'malformed' ? 'receipt_malformed' : e.code);
|
|
505
|
+
}
|
|
506
|
+
if (claims.iat > Math.floor(now.getTime() / 1000) + CLOCK_TOLERANCE_S) return invalid('not_yet_valid');
|
|
507
|
+
|
|
508
|
+
if (claims.surface.hash !== jsonDigest(b.content.surface))
|
|
509
|
+
return invalid('surface_mismatch', { content: 'mismatch' });
|
|
510
|
+
if (claims.input_hash !== jsonDigest(b.content.input))
|
|
511
|
+
return invalid('input_mismatch', { content: 'mismatch' });
|
|
512
|
+
|
|
513
|
+
const checks = contextChecks(expected, claims);
|
|
514
|
+
const mismatches = checks.filter((x) => !x.ok).map((x) => x.field);
|
|
515
|
+
if (mismatches.length > 0)
|
|
516
|
+
return invalid('context_mismatch', {
|
|
517
|
+
content: 'verified',
|
|
518
|
+
context: { status: 'mismatch', checked: supplied, mismatches },
|
|
519
|
+
});
|
|
520
|
+
const status =
|
|
521
|
+
checks.length === 0 ? 'unchecked' : expected?.audience === undefined ? 'incomplete' : 'verified';
|
|
522
|
+
const kid = JSON.parse(Buffer.from(b.receipt.split('.')[0] as string, 'base64url').toString('utf8'))
|
|
523
|
+
.kid as string;
|
|
524
|
+
return {
|
|
525
|
+
valid: true,
|
|
526
|
+
reason: null,
|
|
527
|
+
checked_at: now.toISOString(),
|
|
528
|
+
content: 'verified',
|
|
529
|
+
context: { status, checked: supplied, mismatches: [] },
|
|
530
|
+
application_purpose: status === 'verified' ? 'matched_caller_context' : 'unchecked',
|
|
531
|
+
actor: { assurance: claims.actor.assurance },
|
|
532
|
+
receipt: {
|
|
533
|
+
key_id: kid,
|
|
534
|
+
issuer: claims.iss,
|
|
535
|
+
audience: claims.aud,
|
|
536
|
+
event_id: claims.event_id,
|
|
537
|
+
session_id: claims.session_id,
|
|
538
|
+
workspace_id: claims.workspace_id,
|
|
539
|
+
step_id: claims.step_id,
|
|
540
|
+
surface: { ...claims.surface },
|
|
541
|
+
action: { ...claims.action },
|
|
542
|
+
input_hash: claims.input_hash,
|
|
543
|
+
accepted_at: claims.accepted_at,
|
|
544
|
+
expires_at: new Date(claims.exp * 1000).toISOString(),
|
|
545
|
+
},
|
|
546
|
+
};
|
|
547
|
+
}
|
package/src/receipts/index.ts
CHANGED
|
@@ -8,6 +8,17 @@ export type {
|
|
|
8
8
|
VerifyDecisionReceiptOptions,
|
|
9
9
|
} from './verify.js';
|
|
10
10
|
export type { DeepReadonly } from './json.js';
|
|
11
|
+
export { verifyDecisionBundle, BUNDLE_LIMITS } from './bundle.js';
|
|
12
|
+
export type {
|
|
13
|
+
BundleContextField,
|
|
14
|
+
BundleJwk,
|
|
15
|
+
BundleRejection,
|
|
16
|
+
DecisionBundle,
|
|
17
|
+
DecisionBundleVerification,
|
|
18
|
+
ExpectedBundleContext,
|
|
19
|
+
VerifiedReceiptSummary,
|
|
20
|
+
VerifyDecisionBundleOptions,
|
|
21
|
+
} from './bundle.js';
|
|
11
22
|
export type {
|
|
12
23
|
ReceiptResource,
|
|
13
24
|
VerifyResponseInput,
|
package/src/sessions.ts
CHANGED
|
@@ -72,6 +72,17 @@ export class Sessions {
|
|
|
72
72
|
outcome: 'not_sent',
|
|
73
73
|
}),
|
|
74
74
|
);
|
|
75
|
+
// The floor is fixed; the ceiling is the plan's, checked by the runtime.
|
|
76
|
+
const expiresIn = (body as { expires_in?: unknown } | null)?.expires_in;
|
|
77
|
+
if (
|
|
78
|
+
expiresIn !== undefined &&
|
|
79
|
+
(typeof expiresIn !== 'number' || !Number.isSafeInteger(expiresIn) || expiresIn < 30)
|
|
80
|
+
)
|
|
81
|
+
return Promise.reject(
|
|
82
|
+
new SessError('configuration', 'expires_in must be a whole number of seconds, at least 30.', {
|
|
83
|
+
outcome: 'not_sent',
|
|
84
|
+
}),
|
|
85
|
+
);
|
|
75
86
|
return this.#transport.request(
|
|
76
87
|
{
|
|
77
88
|
name: 'sessions.create',
|
package/src/transport.ts
CHANGED
|
@@ -42,7 +42,7 @@ function credential(value: unknown): string {
|
|
|
42
42
|
if (typeof value !== 'string' || !/^[\x21-\x7e]{1,4096}$/.test(value)) {
|
|
43
43
|
throw new SessError(
|
|
44
44
|
'configuration',
|
|
45
|
-
'Supply a
|
|
45
|
+
'Supply a Sess API key on the server. It must not be empty or contain whitespace or control characters.',
|
|
46
46
|
{ code: 'INVALID_API_KEY', outcome: 'not_sent' },
|
|
47
47
|
);
|
|
48
48
|
}
|
|
@@ -125,6 +125,13 @@ export function retryAfter(header: string | null): number | undefined {
|
|
|
125
125
|
const date = Date.parse(header);
|
|
126
126
|
return Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined;
|
|
127
127
|
}
|
|
128
|
+
/** An IMF-fixdate HTTP `Date` header in milliseconds since the epoch, or undefined. */
|
|
129
|
+
export function httpDate(header: string | null): number | undefined {
|
|
130
|
+
if (header === null || !/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(header))
|
|
131
|
+
return undefined;
|
|
132
|
+
const date = Date.parse(header);
|
|
133
|
+
return Number.isFinite(date) ? date : undefined;
|
|
134
|
+
}
|
|
128
135
|
async function readBody(response: Response, maxBytes: number, signal: AbortSignal): Promise<string> {
|
|
129
136
|
if (!response.body) return '';
|
|
130
137
|
const reader = response.body.getReader();
|
|
@@ -372,7 +379,7 @@ export class Transport {
|
|
|
372
379
|
const remoteId = safeText(remote.request_id, /^[A-Za-z0-9._:-]{1,128}$/, key, true) ?? requestId;
|
|
373
380
|
const rejected = code !== undefined && rejections[response.status]?.includes(code);
|
|
374
381
|
retryable = transientStatuses.has(response.status);
|
|
375
|
-
throw new SessError('api', '
|
|
382
|
+
throw new SessError('api', 'The Sess API returned an error. See the status and code fields.', {
|
|
376
383
|
code,
|
|
377
384
|
reason,
|
|
378
385
|
status: response.status,
|
|
@@ -417,9 +424,11 @@ export class Transport {
|
|
|
417
424
|
throw new SessError('protocol', 'API response has an invalid workspace context.', {
|
|
418
425
|
code: 'INVALID_WORKSPACE_CONTEXT',
|
|
419
426
|
});
|
|
427
|
+
const serverDate = httpDate(response.headers.get('date'));
|
|
420
428
|
const meta: ResponseMeta = {
|
|
421
429
|
status: response.status,
|
|
422
430
|
attempts,
|
|
431
|
+
...(serverDate !== undefined ? { serverDate } : {}),
|
|
423
432
|
...(etag ? { etag } : {}),
|
|
424
433
|
...(requestId ? { requestId } : {}),
|
|
425
434
|
...(workspaceHeader ? { workspaceId: workspaceHeader } : {}),
|
package/src/types.ts
CHANGED
|
@@ -55,7 +55,15 @@ export type SurfaceComponent =
|
|
|
55
55
|
export type InteractiveInteraction = Omit<RawPublishSessionRequest['interaction'], 'source'> & {
|
|
56
56
|
source: { kind: 'sess_surface'; components: SurfaceComponent[] };
|
|
57
57
|
};
|
|
58
|
-
export type CreateSessionRequest = {
|
|
58
|
+
export type CreateSessionRequest = {
|
|
59
|
+
interaction: DisplayInteraction | InteractiveInteraction;
|
|
60
|
+
/**
|
|
61
|
+
* Advanced: how long the human link stays open, in whole seconds from creation: from 30 up to
|
|
62
|
+
* the plan's link lifetime (the runtime checks the ceiling). Absent: the plan's lifetime. The
|
|
63
|
+
* create response's `action_expires_at` says when the link ends; nothing moves it later.
|
|
64
|
+
*/
|
|
65
|
+
expires_in?: number;
|
|
66
|
+
};
|
|
59
67
|
export type PublishSessionRequest = { interaction: InteractiveInteraction };
|
|
60
68
|
|
|
61
69
|
export interface ResponseMeta {
|
|
@@ -66,6 +74,11 @@ export interface ResponseMeta {
|
|
|
66
74
|
workspaceId?: string;
|
|
67
75
|
attempts: number;
|
|
68
76
|
idempotencyKey?: string;
|
|
77
|
+
/**
|
|
78
|
+
* The response's HTTP `Date` in milliseconds since the epoch (whole seconds), when the runtime
|
|
79
|
+
* sent one: the runtime clock at or before the response. Used to observe link expiry.
|
|
80
|
+
*/
|
|
81
|
+
serverDate?: number;
|
|
69
82
|
}
|
|
70
83
|
export interface ApiResult<T> {
|
|
71
84
|
data: T;
|
package/src/webhooks/index.ts
CHANGED
|
@@ -129,7 +129,7 @@ export function verifyWebhook(
|
|
|
129
129
|
Buffer.from(secret.slice(6), 'base64').toString('base64') !== secret.slice(6),
|
|
130
130
|
)
|
|
131
131
|
) {
|
|
132
|
-
throw new SessError('configuration', 'Use the
|
|
132
|
+
throw new SessError('configuration', 'Use the webhook signing secret Sess returned for your workspace.');
|
|
133
133
|
}
|
|
134
134
|
let bytes: Buffer;
|
|
135
135
|
if (typeof rawBody === 'string') {
|