@bolyra/receipts 0.11.1 → 0.12.1

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,1410 @@
1
+ /**
2
+ * Approval-to-execution binding primitive
3
+ * (docs/superpowers/specs/2026-10-25-approval-binding-design.md).
4
+ *
5
+ * Three pieces, all inside the signed payloads:
6
+ *
7
+ * 1. An approval receipt (`bolyra.approval`, scheme `bab1`) binds the reviewed
8
+ * action — requester, audience, tool, operation id — and a digest of the
9
+ * exact reviewed arguments, together with who approved it and when.
10
+ * 2. `executeApproved` verifies that receipt immediately before dispatch and
11
+ * dispatches only the immutable argument snapshot it checked. It is the
12
+ * only path that dispatches; there is no standalone guard to misuse.
13
+ * 3. An execution observation (`bolyra.execution`, scheme `beo1`) links to the
14
+ * approval receipt hash, the operation and attempt ids and the digest of the
15
+ * dispatched snapshot, and verifies offline with
16
+ * `verifyApprovalExecutionLink`.
17
+ *
18
+ * What this does NOT establish (the README repeats the list): verified human
19
+ * identity because a name was signed; authorization correctness; downstream
20
+ * commitment from dispatch; exactly-once execution; protection against
21
+ * bypassing the hook; log completeness; live vendor integration. The receipt
22
+ * records what the operator asserted was reviewed; it carries the argument
23
+ * digest only, never the arguments.
24
+ *
25
+ * No function here logs, writes files or makes network calls.
26
+ */
27
+
28
+ import * as secp256k1 from '@noble/secp256k1';
29
+ import { sha256 } from '@noble/hashes/sha256';
30
+ import { bytesToHex } from '@noble/hashes/utils';
31
+ import { canonicalize } from './canonical';
32
+ import { computeReceiptHash } from './chain';
33
+ import { signReceipt, verifyReceipt } from './sign';
34
+ import type { ReceiptSignerConfig, SignedReceipt } from './types';
35
+
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // Constants
39
+ // ---------------------------------------------------------------------------
40
+
41
+ /** Domain-separation tag for the arguments digest, terminated by an explicit 0x00. */
42
+ export const ARGUMENTS_DIGEST_DST = 'bolyra.approval.arguments/1';
43
+ /** Maximum container nesting depth of the argument object (the root object is depth 1). */
44
+ export const ARGUMENTS_MAX_DEPTH = 64;
45
+ /** Maximum serialized size (UTF-8 bytes) of the argument text and of its canonical form. */
46
+ export const ARGUMENTS_MAX_BYTES = 1024 * 1024;
47
+
48
+ /** Fixed text returned with every link verification result. */
49
+ export const LINK_VERIFICATION_STATEMENT =
50
+ 'A PASS establishes only that the approval receipt and the execution observation are validly signed ' +
51
+ 'by the expected signers and that the observation links to that approval receipt, operation, context ' +
52
+ 'and argument digest. It does not establish human review, actual dispatch, consumption, response ' +
53
+ 'success, business-state freshness or committed effect.';
54
+
55
+ const ID_PATTERN = /^[\x21-\x7e]{1,256}$/;
56
+ const APPROVER_PATTERN = /^[\x20-\x7e]{1,256}$/;
57
+ const RFC3339_MS_Z = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
58
+ const HEX64 = /^[0-9a-f]{64}$/;
59
+ const HEX_0X64 = /^0x[0-9a-f]{64}$/;
60
+ const HEX_0X16 = /^0x[0-9a-f]{16}$/;
61
+ const ADDRESS_PATTERN = /^0x[0-9a-fA-F]{40}$/;
62
+ const SIGNATURE_VALUE_PATTERN = /^0x[0-9a-f]{130}$/;
63
+ const PRIVATE_KEY_PATTERN = /^(0x)?[0-9a-fA-F]{64}$/;
64
+ const FORBIDDEN_KEYS: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype']);
65
+ /** Exclusive upper bound for clock samples: Date.prototype.toISOString must yield a 4-digit year. */
66
+ const MAX_TIMESTAMP_MS = Date.UTC(10000, 0, 1);
67
+ /** Upper bound for any untrusted value echoed into a diagnostic detail. */
68
+ const MAX_DETAIL_CHARS = 120;
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // Types — data model (§4)
72
+ // ---------------------------------------------------------------------------
73
+
74
+ export type JsonPrimitive = string | number | boolean | null;
75
+ export type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
76
+ export type JsonObject = { [key: string]: JsonValue };
77
+
78
+ export interface ApprovalBinding {
79
+ scheme: 'bab1';
80
+ /** Identity that requested the action, as asserted by the operator. */
81
+ requester: string;
82
+ /** Execution audience: the server / system that will execute. */
83
+ audience: string;
84
+ /** Action / tool name. */
85
+ tool: string;
86
+ /** Operator-assigned, unique per operation. */
87
+ operationId: string;
88
+ /** computeArgumentsDigest() of the reviewed arguments (64 lowercase hex). */
89
+ argumentsDigest: string;
90
+ }
91
+
92
+ export type ApprovalDecision = 'approved' | 'denied';
93
+
94
+ export type ApprovalValidity = { kind: 'once' } | { kind: 'until'; notAfter: string };
95
+
96
+ export interface ApprovalAssertion {
97
+ /** Exactly as the approval source asserted it (printable ASCII, 1..256). */
98
+ approver: string;
99
+ /** Provenance label of the approval source. */
100
+ source: string;
101
+ decision: ApprovalDecision;
102
+ /** RFC 3339 UTC with exactly 3-digit milliseconds and a Z suffix. */
103
+ decidedAt: string;
104
+ validity: ApprovalValidity;
105
+ /** External approval-request identifier, verbatim. */
106
+ requestId?: string;
107
+ }
108
+
109
+ export interface ApprovalReceiptPayload {
110
+ v: 1;
111
+ kind: 'bolyra.approval';
112
+ /** Unix seconds. */
113
+ issuedAt: number;
114
+ issuer: string;
115
+ keyId: string;
116
+ binding: ApprovalBinding;
117
+ approval: ApprovalAssertion;
118
+ }
119
+
120
+ export interface ExecutionFields {
121
+ scheme: 'beo1';
122
+ /** computeReceiptHash(approval receipt); verifiers recompute. */
123
+ approvalReceiptHash: string;
124
+ /** Approval envelope id; verifiers re-derive it from payloadHash. */
125
+ approvalReceiptId: string;
126
+ operationId: string;
127
+ /** Operator-assigned per dispatch attempt. */
128
+ attemptId: string;
129
+ requester: string;
130
+ audience: string;
131
+ tool: string;
132
+ /** computeArgumentsDigest() of the dispatched snapshot (same DST). */
133
+ actionDigest: string;
134
+ /** Captured immediately before invoking dispatch. */
135
+ dispatchedAt: string;
136
+ /** What the dispatch promise did — NOT a confirmed effect. */
137
+ outcome: 'returned' | 'threw';
138
+ }
139
+
140
+ export interface ExecutionReceiptPayload {
141
+ v: 1;
142
+ kind: 'bolyra.execution';
143
+ issuedAt: number;
144
+ issuer: string;
145
+ keyId: string;
146
+ execution: ExecutionFields;
147
+ }
148
+
149
+ // ---------------------------------------------------------------------------
150
+ // Types — function interfaces (§5)
151
+ // ---------------------------------------------------------------------------
152
+
153
+ export interface ApprovalReceiptInput {
154
+ /** Defaults to 1; any other value throws. */
155
+ v?: 1;
156
+ /** Defaults to 'bolyra.approval'; any other value throws. */
157
+ kind?: 'bolyra.approval';
158
+ /** Unix seconds; defaults to now. */
159
+ issuedAt?: number;
160
+ binding: {
161
+ /** Defaults to 'bab1'; any other value throws. */
162
+ scheme?: 'bab1';
163
+ requester: string;
164
+ audience: string;
165
+ tool: string;
166
+ operationId: string;
167
+ };
168
+ approval: ApprovalAssertion;
169
+ /** The reviewed arguments as JSON text; only their digest enters the receipt. */
170
+ argumentsJson: string;
171
+ }
172
+
173
+ export interface ApprovalContext {
174
+ requester: string;
175
+ audience: string;
176
+ tool: string;
177
+ operationId: string;
178
+ }
179
+
180
+ export interface ConsumeClaim {
181
+ /** Recovered signer address, lowercase. Namespace the store by it. */
182
+ signer: string;
183
+ /** Full payloadHash of the approval receipt — the replay identity. */
184
+ payloadHash: string;
185
+ operationId: string;
186
+ }
187
+
188
+ /**
189
+ * Operator-owned, atomic, durable claim across all executors. Only the literal
190
+ * `true` permits dispatch. The guard cannot know whether the approved operation
191
+ * already produced its effect; business-state checks belong to the operator and
192
+ * must be made atomically with the mutation.
193
+ */
194
+ export type ConsumeFn = (claim: ConsumeClaim) => boolean;
195
+
196
+ export type DispatchFn<R> = (
197
+ snapshot: Readonly<JsonObject>,
198
+ checkedContext: Readonly<ApprovalContext>,
199
+ ) => R | Promise<R>;
200
+
201
+ export interface ExecuteApprovedParams {
202
+ receipt: SignedReceipt<ApprovalReceiptPayload>;
203
+ /** Address the approval receipt must recover to. Required, non-empty. */
204
+ expectedSigner: string;
205
+ context: ApprovalContext;
206
+ argumentsJson: string;
207
+ attemptId: string;
208
+ /** Required for `once` receipts. */
209
+ consume?: ConsumeFn;
210
+ /** When present, a `bolyra.execution` observation is signed after settlement. */
211
+ observer?: ReceiptSignerConfig;
212
+ /** Defaults to `() => new Date()`. */
213
+ clock?: () => Date;
214
+ }
215
+
216
+ export type BlockedExecutionCode =
217
+ | 'malformed_input'
218
+ | 'malformed_receipt'
219
+ | 'wrong_kind'
220
+ | 'keyid_mismatch'
221
+ | 'signature_invalid'
222
+ | 'untrusted_signer'
223
+ | 'decision_not_approved'
224
+ | 'future_decision'
225
+ | 'expired'
226
+ | 'context_mismatch'
227
+ | 'arguments_out_of_domain'
228
+ | 'arguments_mismatch'
229
+ | 'consume_required'
230
+ | 'consume_rejected'
231
+ | 'observer_invalid'
232
+ | 'invalid_clock';
233
+
234
+ export interface BlockedExecution {
235
+ outcome: 'blocked';
236
+ code: BlockedExecutionCode;
237
+ detail: string;
238
+ }
239
+
240
+ export interface ReturnedExecution<R> {
241
+ outcome: 'returned';
242
+ value: R;
243
+ observation?: SignedReceipt<ExecutionReceiptPayload>;
244
+ observationError?: Error;
245
+ }
246
+
247
+ export type ApprovedExecution<R> = BlockedExecution | ReturnedExecution<R>;
248
+
249
+ /** The dispatch promise rejected (or dispatch threw). Carries the observation when one was signed. */
250
+ export class ApprovedExecutionError extends Error {
251
+ readonly cause: unknown;
252
+ readonly observation?: SignedReceipt<ExecutionReceiptPayload>;
253
+ readonly observationError?: Error;
254
+
255
+ constructor(
256
+ cause: unknown,
257
+ observation?: SignedReceipt<ExecutionReceiptPayload>,
258
+ observationError?: Error,
259
+ ) {
260
+ super('approved dispatch threw');
261
+ this.name = 'ApprovedExecutionError';
262
+ this.cause = cause;
263
+ if (observation !== undefined) this.observation = observation;
264
+ if (observationError !== undefined) this.observationError = observationError;
265
+ }
266
+ }
267
+
268
+ export type LinkCheckId = 'A1' | 'A2' | 'A3' | 'E1' | 'E2' | 'L1' | 'L2' | 'L3' | 'L4';
269
+
270
+ export interface LinkCheck {
271
+ id: LinkCheckId;
272
+ status: 'PASS' | 'FAIL';
273
+ detail: string;
274
+ }
275
+
276
+ export interface LinkVerificationResult {
277
+ ok: boolean;
278
+ checks: LinkCheck[];
279
+ statement: string;
280
+ }
281
+
282
+ export interface VerifyLinkParams {
283
+ /** Untrusted input; validated as unknown. */
284
+ approval: unknown;
285
+ /** Untrusted input; validated as unknown. */
286
+ observation: unknown;
287
+ expectedApprovalSigner: string;
288
+ expectedExecutionSigner: string;
289
+ }
290
+
291
+ export type ArgumentsValidation = { ok: true } | { ok: false; detail: string };
292
+
293
+ // ---------------------------------------------------------------------------
294
+ // Small helpers
295
+ // ---------------------------------------------------------------------------
296
+
297
+ type Validation = { ok: true } | { ok: false; detail: string };
298
+
299
+ const OK: Validation = { ok: true };
300
+
301
+ function fail(detail: string): { ok: false; detail: string } {
302
+ return { ok: false, detail };
303
+ }
304
+
305
+ function utf8(str: string): Uint8Array {
306
+ return new TextEncoder().encode(str);
307
+ }
308
+
309
+ function joinPath(path: string, member: string): string {
310
+ return path === '' ? member : `${path}.${member}`;
311
+ }
312
+
313
+ function isObjectLike(v: unknown): v is Record<string, unknown> {
314
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
315
+ }
316
+
317
+ function truncate(text: string): string {
318
+ return text.length > MAX_DETAIL_CHARS ? text.slice(0, MAX_DETAIL_CHARS - 1) + '…' : text;
319
+ }
320
+
321
+ /**
322
+ * Bounded, non-throwing rendering of an untrusted value for diagnostics. Never
323
+ * invokes user code: no toString/valueOf/toJSON, no template interpolation of
324
+ * symbols or null-prototype objects, no JSON.stringify of bigint or cycles.
325
+ */
326
+ function formatUnknown(v: unknown): string {
327
+ try {
328
+ switch (typeof v) {
329
+ case 'string':
330
+ return truncate(JSON.stringify(v));
331
+ case 'number':
332
+ case 'boolean':
333
+ return String(v);
334
+ case 'undefined':
335
+ return 'undefined';
336
+ case 'bigint':
337
+ return `${truncate(v.toString())}n (bigint)`;
338
+ case 'symbol':
339
+ return 'symbol';
340
+ case 'function':
341
+ return 'function';
342
+ default:
343
+ if (v === null) return 'null';
344
+ return Array.isArray(v) ? 'array' : 'object';
345
+ }
346
+ } catch {
347
+ return 'unprintable';
348
+ }
349
+ }
350
+
351
+ /** Bounded, non-throwing message for a caught value (Error-like or anything else). */
352
+ /** Property read that never throws (revoked or trapping Proxies, throwing getters). */
353
+ function safeRead(target: unknown, key: string): unknown {
354
+ try {
355
+ return (target as Record<string, unknown>)[key];
356
+ } catch {
357
+ return undefined;
358
+ }
359
+ }
360
+
361
+ function errorMessage(e: unknown): string {
362
+ try {
363
+ if (typeof e === 'object' && e !== null) {
364
+ const message = safeRead(e, 'message');
365
+ if (typeof message === 'string') {
366
+ const name = safeRead(e, 'name');
367
+ return truncate(typeof name === 'string' && name.length > 0 ? `${name}: ${message}` : message);
368
+ }
369
+ }
370
+ return `non-Error value thrown: ${formatUnknown(e)}`;
371
+ } catch {
372
+ return 'unprintable error';
373
+ }
374
+ }
375
+
376
+ /** Wraps a caught value into an Error without ever invoking its own conversion methods. */
377
+ function toError(e: unknown): Error {
378
+ // `instanceof` runs prototype machinery: a revoked Proxy or a throwing
379
+ // getPrototypeOf trap would throw here and break the settlement contract.
380
+ try {
381
+ if (e instanceof Error) return e;
382
+ } catch {
383
+ // fall through
384
+ }
385
+ return new Error(errorMessage(e));
386
+ }
387
+
388
+ function describe(v: unknown): string {
389
+ return formatUnknown(v);
390
+ }
391
+
392
+ /** Strict RFC 3339 UTC-ms-Z: pattern plus an exact round-trip through Date. */
393
+ function parseRfc3339MsZ(value: unknown): number | undefined {
394
+ if (typeof value !== 'string' || !RFC3339_MS_Z.test(value)) return undefined;
395
+ const ms = Date.parse(value);
396
+ if (!Number.isFinite(ms)) return undefined;
397
+ if (new Date(ms).toISOString() !== value) return undefined;
398
+ return ms;
399
+ }
400
+
401
+ /**
402
+ * Closed-schema member check: unknown members are rejected first, then every
403
+ * required member must be present. Presence is `in`, so a member explicitly
404
+ * set to `undefined` is present and is rejected by its type check instead of
405
+ * being silently dropped by JSON serialization.
406
+ */
407
+ function checkMembers(
408
+ obj: Record<string, unknown>,
409
+ path: string,
410
+ required: readonly string[],
411
+ optional: readonly string[] = [],
412
+ ): Validation {
413
+ for (const key of Object.keys(obj)) {
414
+ if (!required.includes(key) && !optional.includes(key)) {
415
+ return fail(`unknown member "${joinPath(path, truncate(key))}" (closed schema)`);
416
+ }
417
+ }
418
+ for (const key of required) {
419
+ if (!(key in obj)) {
420
+ return fail(`missing required member "${joinPath(path, key)}"`);
421
+ }
422
+ }
423
+ return OK;
424
+ }
425
+
426
+ function checkId(obj: Record<string, unknown>, path: string, member: string): Validation {
427
+ const v = obj[member];
428
+ if (typeof v !== 'string' || !ID_PATTERN.test(v)) {
429
+ return fail(
430
+ `member "${joinPath(path, member)}" must be an id: printable ASCII excluding space (0x21..0x7E), 1..256 characters`,
431
+ );
432
+ }
433
+ return OK;
434
+ }
435
+
436
+ function checkNonEmptyString(obj: Record<string, unknown>, path: string, member: string): Validation {
437
+ const v = obj[member];
438
+ if (typeof v !== 'string' || v.length === 0) {
439
+ return fail(`member "${joinPath(path, member)}" must be a non-empty string`);
440
+ }
441
+ return OK;
442
+ }
443
+
444
+ function deepFreeze<T>(value: T): T {
445
+ if (typeof value === 'object' && value !== null && !Object.isFrozen(value)) {
446
+ Object.freeze(value);
447
+ for (const key of Object.getOwnPropertyNames(value)) {
448
+ deepFreeze((value as Record<string, unknown>)[key]);
449
+ }
450
+ }
451
+ return value;
452
+ }
453
+
454
+ // ---------------------------------------------------------------------------
455
+ // §4.3 — bab1 argument domain and digest
456
+ // ---------------------------------------------------------------------------
457
+ //
458
+ // Arguments enter ONLY as JSON text. The validator runs on JSON.parse output,
459
+ // which can hold nothing but plain objects, dense arrays, strings, finite
460
+ // numbers, booleans and null, with own enumerable string-keyed data
461
+ // properties: no prototypes to forge, no accessors, no exotic objects, no
462
+ // shared references, no cycles. The value-type checks below are defense in
463
+ // depth, written with plain property access. JSON.parse collapses duplicate
464
+ // keys last-wins ({"a":1,"a":2} binds a:2); the digest binds the parsed
465
+ // object, not the text. JSON.parse("-0") IS -0 and is rejected.
466
+
467
+ type PathStack = Array<string | number>;
468
+
469
+ const SIZE_CAP_DETAIL = 'serialized size exceeds the 1 MiB cap';
470
+
471
+ function renderPath(stack: PathStack): string {
472
+ let out = '$';
473
+ for (const part of stack) out += typeof part === 'number' ? `[${part}]` : `.${truncate(part)}`;
474
+ return out;
475
+ }
476
+
477
+ /**
478
+ * Running lower bound of the canonical serialization size (two quotes plus at
479
+ * least one byte per UTF-16 code unit for strings, exact for numbers, keys,
480
+ * literals and punctuation). A lower bound never rejects data whose exact
481
+ * canonical size fits; the exact check follows the walk.
482
+ */
483
+ interface ByteCount {
484
+ bytes: number;
485
+ }
486
+
487
+ function charge(count: ByteCount, bytes: number, stack: PathStack): string | undefined {
488
+ count.bytes += bytes;
489
+ return count.bytes > ARGUMENTS_MAX_BYTES ? `${SIZE_CAP_DETAIL} at ${renderPath(stack)}` : undefined;
490
+ }
491
+
492
+ function validateJsonNode(node: unknown, stack: PathStack, depth: number, count: ByteCount): string | undefined {
493
+ switch (typeof node) {
494
+ case 'string':
495
+ return charge(count, node.length + 2, stack);
496
+ case 'boolean':
497
+ return charge(count, node ? 4 : 5, stack);
498
+ case 'number':
499
+ if (!Number.isFinite(node)) return `non-finite number at ${renderPath(stack)}`;
500
+ if (Object.is(node, -0)) return `negative zero at ${renderPath(stack)}`;
501
+ return charge(count, String(node).length, stack);
502
+ case 'object':
503
+ break;
504
+ default:
505
+ // undefined, function, symbol, bigint: unreachable from JSON.parse
506
+ return `unsupported ${typeof node} at ${renderPath(stack)}`;
507
+ }
508
+ if (node === null) return charge(count, 4, stack);
509
+ if (depth > ARGUMENTS_MAX_DEPTH) return `nesting depth exceeds ${ARGUMENTS_MAX_DEPTH} at ${renderPath(stack)}`;
510
+ if (Array.isArray(node)) {
511
+ let problem = charge(count, 2 + Math.max(0, node.length - 1), stack);
512
+ if (problem) return problem;
513
+ for (let i = 0; i < node.length; i++) {
514
+ stack.push(i);
515
+ problem = validateJsonNode(node[i], stack, depth + 1, count);
516
+ stack.pop();
517
+ if (problem) return problem;
518
+ }
519
+ return undefined;
520
+ }
521
+ // Object.keys lists the own "__proto__" property JSON.parse creates.
522
+ const keys = Object.keys(node);
523
+ let problem = charge(count, 2 + Math.max(0, keys.length - 1), stack);
524
+ if (problem) return problem;
525
+ for (const key of keys) {
526
+ if (FORBIDDEN_KEYS.has(key)) return `forbidden key "${key}" at ${renderPath(stack)}`;
527
+ problem = charge(count, key.length + 3, stack);
528
+ if (problem) return problem;
529
+ stack.push(key);
530
+ problem = validateJsonNode((node as Record<string, unknown>)[key], stack, depth + 1, count);
531
+ stack.pop();
532
+ if (problem) return problem;
533
+ }
534
+ return undefined;
535
+ }
536
+
537
+ type AnalyzedArguments =
538
+ | { ok: true; value: JsonObject; canonical: string }
539
+ | { ok: false; detail: string };
540
+
541
+ /** Parse once (try/catch), validate the parsed tree, canonicalize, apply both size caps. */
542
+ function analyzeArgumentsJson(argumentsJson: unknown): AnalyzedArguments {
543
+ if (typeof argumentsJson !== 'string') {
544
+ return fail(`argumentsJson must be a string, got ${describe(argumentsJson)}`);
545
+ }
546
+ if (utf8(argumentsJson).length > ARGUMENTS_MAX_BYTES) {
547
+ return fail('argument text exceeds the 1 MiB size cap');
548
+ }
549
+ let parsed: unknown;
550
+ try {
551
+ parsed = JSON.parse(argumentsJson);
552
+ } catch (e) {
553
+ return fail(`invalid JSON: ${errorMessage(e)}`);
554
+ }
555
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
556
+ return fail(`arguments must be a JSON object, got ${describe(parsed)}`);
557
+ }
558
+ const problem = validateJsonNode(parsed, [], 1, { bytes: 0 });
559
+ if (problem) return fail(problem);
560
+ const canonical = canonicalize(parsed);
561
+ if (utf8(canonical).length > ARGUMENTS_MAX_BYTES) {
562
+ return fail(`canonical ${SIZE_CAP_DETAIL}`);
563
+ }
564
+ return { ok: true, value: parsed as JsonObject, canonical };
565
+ }
566
+
567
+ /**
568
+ * bab1 domain check for argument JSON text: invalid JSON → ok:false with an
569
+ * "invalid JSON" detail; otherwise the parsed tree must be a non-array object
570
+ * whose values are objects, arrays, strings, finite numbers, booleans or null,
571
+ * with no -0, no `__proto__`/`constructor`/`prototype` key at any depth,
572
+ * nesting depth ≤ 64, text and canonical form ≤ 1 MiB.
573
+ */
574
+ export function validateArgumentsJson(argumentsJson: string): ArgumentsValidation {
575
+ const analyzed = analyzeArgumentsJson(argumentsJson);
576
+ return analyzed.ok ? OK : fail(analyzed.detail);
577
+ }
578
+
579
+ function digestCanonical(canonical: string): string {
580
+ const dst = utf8(ARGUMENTS_DIGEST_DST);
581
+ const body = utf8(canonical);
582
+ const input = new Uint8Array(dst.length + 1 + body.length);
583
+ input.set(dst, 0);
584
+ input[dst.length] = 0x00;
585
+ input.set(body, dst.length + 1);
586
+ return bytesToHex(sha256(input));
587
+ }
588
+
589
+ type ParsedArguments =
590
+ | { ok: true; value: Readonly<JsonObject>; digest: string }
591
+ | { ok: false; detail: string };
592
+
593
+ /** The deep-frozen parsed tree is the snapshot used for both the digest and dispatch. */
594
+ function parseArguments(argumentsJson: string): ParsedArguments {
595
+ const analyzed = analyzeArgumentsJson(argumentsJson);
596
+ if (!analyzed.ok) return analyzed;
597
+ return { ok: true, value: deepFreeze(analyzed.value), digest: digestCanonical(analyzed.canonical) };
598
+ }
599
+
600
+ /**
601
+ * argumentsDigest = sha256hex( utf8("bolyra.approval.arguments/1") || 0x00 || utf8(canonicalize(value)) )
602
+ * where `value` is the parsed, bab1-validated argument object. Throws on
603
+ * invalid JSON or out-of-domain values.
604
+ */
605
+ export function computeArgumentsDigest(argumentsJson: string): string {
606
+ if (typeof argumentsJson !== 'string') {
607
+ throw new TypeError('computeArgumentsDigest: argumentsJson must be a string');
608
+ }
609
+ const parsed = parseArguments(argumentsJson);
610
+ if (!parsed.ok) {
611
+ throw new Error(`computeArgumentsDigest: ${parsed.detail}`);
612
+ }
613
+ return parsed.digest;
614
+ }
615
+
616
+ // ---------------------------------------------------------------------------
617
+ // Payload validators (closed schemas)
618
+ // ---------------------------------------------------------------------------
619
+
620
+ interface ApprovalTimes {
621
+ decidedAtMs: number;
622
+ notAfterMs?: number;
623
+ }
624
+
625
+ function validateApprovalPayloadMembers(payload: Record<string, unknown>, path: string): Validation {
626
+ let r = checkMembers(payload, path, ['v', 'kind', 'issuedAt', 'issuer', 'keyId', 'binding', 'approval']);
627
+ if (!r.ok) return r;
628
+ if (payload.v !== 1) return fail(`member "${joinPath(path, 'v')}" must be 1`);
629
+ if (payload.kind !== 'bolyra.approval') return fail(`member "${joinPath(path, 'kind')}" must be "bolyra.approval"`);
630
+ if (!Number.isSafeInteger(payload.issuedAt) || (payload.issuedAt as number) < 0) {
631
+ return fail(`member "${joinPath(path, 'issuedAt')}" must be a non-negative integer (unix seconds)`);
632
+ }
633
+ r = checkNonEmptyString(payload, path, 'issuer');
634
+ if (!r.ok) return r;
635
+ r = checkNonEmptyString(payload, path, 'keyId');
636
+ if (!r.ok) return r;
637
+
638
+ const bindingPath = joinPath(path, 'binding');
639
+ const binding = payload.binding;
640
+ if (!isObjectLike(binding)) return fail(`member "${bindingPath}" must be an object`);
641
+ r = checkMembers(binding, bindingPath, ['scheme', 'requester', 'audience', 'tool', 'operationId', 'argumentsDigest']);
642
+ if (!r.ok) return r;
643
+ if (binding.scheme !== 'bab1') return fail(`member "${joinPath(bindingPath, 'scheme')}" must be "bab1"`);
644
+ for (const member of ['requester', 'audience', 'tool', 'operationId']) {
645
+ r = checkId(binding, bindingPath, member);
646
+ if (!r.ok) return r;
647
+ }
648
+ if (typeof binding.argumentsDigest !== 'string' || !HEX64.test(binding.argumentsDigest)) {
649
+ return fail(`member "${joinPath(bindingPath, 'argumentsDigest')}" must be 64 lowercase hex characters`);
650
+ }
651
+
652
+ return validateApprovalAssertion(payload.approval, joinPath(path, 'approval'));
653
+ }
654
+
655
+ function validateApprovalAssertion(approval: unknown, path: string): Validation {
656
+ if (!isObjectLike(approval)) return fail(`member "${path}" must be an object`);
657
+ let r = checkMembers(approval, path, ['approver', 'source', 'decision', 'decidedAt', 'validity'], ['requestId']);
658
+ if (!r.ok) return r;
659
+ if (typeof approval.approver !== 'string' || !APPROVER_PATTERN.test(approval.approver)) {
660
+ return fail(`member "${joinPath(path, 'approver')}" must be printable ASCII (0x20..0x7E), 1..256 characters`);
661
+ }
662
+ r = checkId(approval, path, 'source');
663
+ if (!r.ok) return r;
664
+ if (approval.decision !== 'approved' && approval.decision !== 'denied') {
665
+ return fail(`member "${joinPath(path, 'decision')}" must be "approved" or "denied"`);
666
+ }
667
+ if (parseRfc3339MsZ(approval.decidedAt) === undefined) {
668
+ return fail(`member "${joinPath(path, 'decidedAt')}" must match YYYY-MM-DDTHH:MM:SS.mmmZ exactly (3-digit ms, UTC Z)`);
669
+ }
670
+ const validityPath = joinPath(path, 'validity');
671
+ const validity = approval.validity;
672
+ if (!isObjectLike(validity)) return fail(`member "${validityPath}" must be an object`);
673
+ if (validity.kind === 'once') {
674
+ r = checkMembers(validity, validityPath, ['kind']);
675
+ if (!r.ok) return r;
676
+ } else if (validity.kind === 'until') {
677
+ r = checkMembers(validity, validityPath, ['kind', 'notAfter']);
678
+ if (!r.ok) return r;
679
+ if (parseRfc3339MsZ(validity.notAfter) === undefined) {
680
+ return fail(`member "${joinPath(validityPath, 'notAfter')}" must match YYYY-MM-DDTHH:MM:SS.mmmZ exactly (3-digit ms, UTC Z)`);
681
+ }
682
+ } else {
683
+ return fail(`member "${joinPath(validityPath, 'kind')}" must be "once" or "until"`);
684
+ }
685
+ if ('requestId' in approval) {
686
+ r = checkId(approval, path, 'requestId');
687
+ if (!r.ok) return r;
688
+ }
689
+ return OK;
690
+ }
691
+
692
+ function approvalTimes(payload: ApprovalReceiptPayload): ApprovalTimes {
693
+ const decidedAtMs = parseRfc3339MsZ(payload.approval.decidedAt) as number;
694
+ const validity = payload.approval.validity;
695
+ return validity.kind === 'until'
696
+ ? { decidedAtMs, notAfterMs: parseRfc3339MsZ(validity.notAfter) as number }
697
+ : { decidedAtMs };
698
+ }
699
+
700
+ function validateExecutionPayloadMembers(payload: Record<string, unknown>, path: string): Validation {
701
+ let r = checkMembers(payload, path, ['v', 'kind', 'issuedAt', 'issuer', 'keyId', 'execution']);
702
+ if (!r.ok) return r;
703
+ if (payload.v !== 1) return fail(`member "${joinPath(path, 'v')}" must be 1`);
704
+ if (payload.kind !== 'bolyra.execution') return fail(`member "${joinPath(path, 'kind')}" must be "bolyra.execution"`);
705
+ if (!Number.isSafeInteger(payload.issuedAt) || (payload.issuedAt as number) < 0) {
706
+ return fail(`member "${joinPath(path, 'issuedAt')}" must be a non-negative integer (unix seconds)`);
707
+ }
708
+ r = checkNonEmptyString(payload, path, 'issuer');
709
+ if (!r.ok) return r;
710
+ r = checkNonEmptyString(payload, path, 'keyId');
711
+ if (!r.ok) return r;
712
+
713
+ const execPath = joinPath(path, 'execution');
714
+ const exec = payload.execution;
715
+ if (!isObjectLike(exec)) return fail(`member "${execPath}" must be an object`);
716
+ r = checkMembers(exec, execPath, [
717
+ 'scheme',
718
+ 'approvalReceiptHash',
719
+ 'approvalReceiptId',
720
+ 'operationId',
721
+ 'attemptId',
722
+ 'requester',
723
+ 'audience',
724
+ 'tool',
725
+ 'actionDigest',
726
+ 'dispatchedAt',
727
+ 'outcome',
728
+ ]);
729
+ if (!r.ok) return r;
730
+ if (exec.scheme !== 'beo1') return fail(`member "${joinPath(execPath, 'scheme')}" must be "beo1"`);
731
+ if (typeof exec.approvalReceiptHash !== 'string' || !HEX_0X64.test(exec.approvalReceiptHash)) {
732
+ return fail(`member "${joinPath(execPath, 'approvalReceiptHash')}" must be 0x + 64 lowercase hex characters`);
733
+ }
734
+ if (typeof exec.approvalReceiptId !== 'string' || !HEX_0X16.test(exec.approvalReceiptId)) {
735
+ return fail(`member "${joinPath(execPath, 'approvalReceiptId')}" must be 0x + 16 lowercase hex characters`);
736
+ }
737
+ for (const member of ['operationId', 'attemptId', 'requester', 'audience', 'tool']) {
738
+ r = checkId(exec, execPath, member);
739
+ if (!r.ok) return r;
740
+ }
741
+ if (typeof exec.actionDigest !== 'string' || !HEX64.test(exec.actionDigest)) {
742
+ return fail(`member "${joinPath(execPath, 'actionDigest')}" must be 64 lowercase hex characters`);
743
+ }
744
+ if (parseRfc3339MsZ(exec.dispatchedAt) === undefined) {
745
+ return fail(`member "${joinPath(execPath, 'dispatchedAt')}" must match YYYY-MM-DDTHH:MM:SS.mmmZ exactly (3-digit ms, UTC Z)`);
746
+ }
747
+ if (exec.outcome !== 'returned' && exec.outcome !== 'threw') {
748
+ return fail(`member "${joinPath(execPath, 'outcome')}" must be "returned" or "threw"`);
749
+ }
750
+ return OK;
751
+ }
752
+
753
+ type EnvelopeCode = 'malformed_receipt' | 'wrong_kind' | 'keyid_mismatch';
754
+
755
+ type EnvelopeValidation<P> =
756
+ | { ok: true; receipt: SignedReceipt<P> }
757
+ | { ok: false; code: EnvelopeCode; detail: string };
758
+
759
+ /**
760
+ * Structural validation of a signed envelope of one of the new kinds: closed
761
+ * schema at every level, kind, v, scheme, envelope/payload keyId agreement,
762
+ * signature alg and byte lengths, derived id. Signature VALIDITY is a
763
+ * separate step (verifyReceipt).
764
+ */
765
+ function validateEnvelope<P>(
766
+ value: unknown,
767
+ kind: 'bolyra.approval' | 'bolyra.execution',
768
+ validatePayload: (payload: Record<string, unknown>, path: string) => Validation,
769
+ ): EnvelopeValidation<P> {
770
+ const bad = (detail: string): EnvelopeValidation<P> => ({ ok: false, code: 'malformed_receipt', detail });
771
+ if (!isObjectLike(value)) return bad(`receipt must be an object, got ${describe(value)}`);
772
+ let r = checkMembers(value, '', ['id', 'payload', 'signature']);
773
+ if (!r.ok) return bad(r.detail);
774
+ const payload = value.payload;
775
+ if (!isObjectLike(payload)) return bad('member "payload" must be an object');
776
+ if (payload.kind !== kind) {
777
+ return { ok: false, code: 'wrong_kind', detail: `expected payload.kind "${kind}", got ${formatUnknown(payload.kind)}` };
778
+ }
779
+ r = validatePayload(payload, 'payload');
780
+ if (!r.ok) return bad(r.detail);
781
+
782
+ const signature = value.signature;
783
+ if (!isObjectLike(signature)) return bad('member "signature" must be an object');
784
+ r = checkMembers(signature, 'signature', ['alg', 'keyId', 'signer', 'payloadHash', 'value']);
785
+ if (!r.ok) return bad(r.detail);
786
+ if (typeof signature.keyId !== 'string') return bad('member "signature.keyId" must be a string');
787
+ if (signature.keyId !== payload.keyId) {
788
+ return {
789
+ ok: false,
790
+ code: 'keyid_mismatch',
791
+ detail: `envelope signature.keyId ${formatUnknown(signature.keyId)} differs from payload.keyId ${formatUnknown(payload.keyId)}`,
792
+ };
793
+ }
794
+ if (signature.alg !== 'ES256K') return bad('member "signature.alg" must be "ES256K"');
795
+ if (typeof signature.signer !== 'string' || !ADDRESS_PATTERN.test(signature.signer)) {
796
+ return bad('member "signature.signer" must be a 20-byte 0x-prefixed hex address');
797
+ }
798
+ if (typeof signature.payloadHash !== 'string' || !HEX_0X64.test(signature.payloadHash)) {
799
+ return bad('member "signature.payloadHash" must be 0x + 64 lowercase hex characters (32 bytes)');
800
+ }
801
+ if (typeof signature.value !== 'string' || !SIGNATURE_VALUE_PATTERN.test(signature.value)) {
802
+ return bad('member "signature.value" must be 0x + 130 lowercase hex characters (65 bytes r||s||v)');
803
+ }
804
+ if (typeof value.id !== 'string' || value.id !== '0x' + signature.payloadHash.slice(2, 18)) {
805
+ return bad('envelope id does not equal the id derived from signature.payloadHash');
806
+ }
807
+ return { ok: true, receipt: value as unknown as SignedReceipt<P> };
808
+ }
809
+
810
+ function validateApprovalEnvelope(value: unknown): EnvelopeValidation<ApprovalReceiptPayload> {
811
+ return validateEnvelope<ApprovalReceiptPayload>(value, 'bolyra.approval', validateApprovalPayloadMembers);
812
+ }
813
+
814
+ function validateExecutionEnvelope(value: unknown): EnvelopeValidation<ExecutionReceiptPayload> {
815
+ return validateEnvelope<ExecutionReceiptPayload>(value, 'bolyra.execution', validateExecutionPayloadMembers);
816
+ }
817
+
818
+ function validateSignerConfig(value: unknown, path: string): Validation {
819
+ if (!isObjectLike(value)) return fail(`${path} must be an object with issuer, keyId and privateKey`);
820
+ let r = checkNonEmptyString(value, path, 'issuer');
821
+ if (!r.ok) return r;
822
+ r = checkNonEmptyString(value, path, 'keyId');
823
+ if (!r.ok) return r;
824
+ const key = value.privateKey;
825
+ if (typeof key !== 'string' || !PRIVATE_KEY_PATTERN.test(key)) {
826
+ return fail(`member "${joinPath(path, 'privateKey')}" must be a 32-byte hex-encoded secp256k1 private key`);
827
+ }
828
+ const clean = key.startsWith('0x') ? key.slice(2) : key;
829
+ if (!secp256k1.utils.isValidPrivateKey(clean)) {
830
+ return fail(`member "${joinPath(path, 'privateKey')}" is not a valid secp256k1 private key`);
831
+ }
832
+ return OK;
833
+ }
834
+
835
+ // ---------------------------------------------------------------------------
836
+ // §5.2 — createApprovalReceipt
837
+ // ---------------------------------------------------------------------------
838
+
839
+ /**
840
+ * Validates every member of `input` and the bab1 domain of `argumentsJson`,
841
+ * computes the digest, builds the §4.1 payload and signs it. Throws on any
842
+ * invalid input, naming the first offending member. Provenance (`approver`,
843
+ * `source`, `decidedAt`, `decision`, `validity`) is never defaulted; only the
844
+ * fixed discriminators (`v`, `kind`, `scheme`) and `issuedAt` have defaults.
845
+ */
846
+ export function createApprovalReceipt(
847
+ input: ApprovalReceiptInput,
848
+ signerConfig: ReceiptSignerConfig,
849
+ ): SignedReceipt<ApprovalReceiptPayload> {
850
+ const throwOn = (r: Validation): void => {
851
+ if (!r.ok) throw new Error(`createApprovalReceipt: ${r.detail}`);
852
+ };
853
+ throwOn(validateSignerConfig(signerConfig, 'signerConfig'));
854
+ if (!isObjectLike(input)) throw new Error(`createApprovalReceipt: input must be an object, got ${describe(input)}`);
855
+
856
+ throwOn(checkMembers(input, '', ['binding', 'approval', 'argumentsJson'], ['v', 'kind', 'issuedAt']));
857
+ if ('v' in input && input.v !== 1) throwOn(fail('member "v" must be 1'));
858
+ if ('kind' in input && input.kind !== 'bolyra.approval') throwOn(fail('member "kind" must be "bolyra.approval"'));
859
+ let issuedAt: number;
860
+ if ('issuedAt' in input) {
861
+ if (!Number.isSafeInteger(input.issuedAt) || (input.issuedAt as number) < 0) {
862
+ throwOn(fail('member "issuedAt" must be a non-negative integer (unix seconds)'));
863
+ }
864
+ issuedAt = input.issuedAt as number;
865
+ } else {
866
+ issuedAt = Math.floor(Date.now() / 1000);
867
+ }
868
+
869
+ const binding = input.binding as unknown;
870
+ if (!isObjectLike(binding)) throwOn(fail('member "binding" must be an object'));
871
+ throwOn(
872
+ checkMembers(binding as Record<string, unknown>, 'binding', ['requester', 'audience', 'tool', 'operationId'], ['scheme']),
873
+ );
874
+ const b = binding as Record<string, unknown>;
875
+ if ('scheme' in b && b.scheme !== 'bab1') throwOn(fail('member "binding.scheme" must be "bab1"'));
876
+
877
+ if (typeof input.argumentsJson !== 'string') throwOn(fail('member "argumentsJson" must be a string'));
878
+ const parsed = parseArguments(input.argumentsJson);
879
+ if (!parsed.ok) throwOn(fail(`member "argumentsJson": ${parsed.detail}`));
880
+ const digest = (parsed as { ok: true; digest: string }).digest;
881
+
882
+ for (const member of ['requester', 'audience', 'tool', 'operationId']) {
883
+ throwOn(checkId(b, 'binding', member));
884
+ }
885
+
886
+ // The approval block is the same closed schema inside the payload; validate
887
+ // the caller's object before copying it member by member.
888
+ throwOn(validateApprovalAssertion(input.approval, 'approval'));
889
+ const a = input.approval;
890
+ const validity: ApprovalValidity =
891
+ a.validity.kind === 'until' ? { kind: 'until', notAfter: a.validity.notAfter } : { kind: 'once' };
892
+
893
+ const payload: ApprovalReceiptPayload = {
894
+ v: 1,
895
+ kind: 'bolyra.approval',
896
+ issuedAt,
897
+ issuer: signerConfig.issuer,
898
+ keyId: signerConfig.keyId,
899
+ binding: {
900
+ scheme: 'bab1',
901
+ requester: b.requester as string,
902
+ audience: b.audience as string,
903
+ tool: b.tool as string,
904
+ operationId: b.operationId as string,
905
+ argumentsDigest: digest,
906
+ },
907
+ approval: {
908
+ approver: a.approver,
909
+ source: a.source,
910
+ decision: a.decision,
911
+ decidedAt: a.decidedAt,
912
+ validity,
913
+ ...(a.requestId !== undefined ? { requestId: a.requestId } : {}),
914
+ },
915
+ };
916
+
917
+ // The emitter never produces what the verifier would reject.
918
+ throwOn(validateApprovalPayloadMembers(payload as unknown as Record<string, unknown>, ''));
919
+ const signed = signReceipt(payload, signerConfig);
920
+ const envelope = validateApprovalEnvelope(signed);
921
+ if (!envelope.ok) throw new Error(`createApprovalReceipt: produced an invalid envelope: ${envelope.detail}`);
922
+ return signed;
923
+ }
924
+
925
+ // ---------------------------------------------------------------------------
926
+ // §5.3 — executeApproved
927
+ // ---------------------------------------------------------------------------
928
+
929
+ function blocked(code: BlockedExecutionCode, detail: string): BlockedExecution {
930
+ return { outcome: 'blocked', code, detail };
931
+ }
932
+
933
+ /**
934
+ * Sample the captured clock: epoch ms via Date.prototype.getTime.call, or
935
+ * undefined when the clock throws, returns a non-Date, an invalid Date, or a
936
+ * time outside the observation timestamp domain (0 <= ms < year 10000, so
937
+ * toISOString yields a 4-digit year and issuedAt is a non-negative integer).
938
+ */
939
+ function sampleClock(clock: () => Date): number | undefined {
940
+ try {
941
+ const t = Date.prototype.getTime.call(clock());
942
+ if (typeof t !== 'number' || !Number.isFinite(t)) return undefined;
943
+ if (t < 0 || t >= MAX_TIMESTAMP_MS) return undefined;
944
+ return t;
945
+ } catch {
946
+ return undefined;
947
+ }
948
+ }
949
+
950
+ const INVALID_CLOCK_DETAIL =
951
+ 'clock threw, did not return a valid Date, or returned a time outside 1970-01-01T00:00:00.000Z..9999-12-31T23:59:59.999Z';
952
+
953
+ /** Attach a no-op sink to a thenable so a rejected consume result never surfaces as an unhandled rejection. Never awaits. */
954
+ function sinkThenable(v: unknown): boolean {
955
+ try {
956
+ if ((typeof v === 'object' && v !== null) || typeof v === 'function') {
957
+ const then = (v as { then?: unknown }).then;
958
+ if (typeof then === 'function') {
959
+ const noop = (): void => undefined;
960
+ (then as (a: () => void, b: () => void) => unknown).call(v, noop, noop);
961
+ return true;
962
+ }
963
+ }
964
+ } catch {
965
+ return true;
966
+ }
967
+ return false;
968
+ }
969
+
970
+ function temporalCheck(nowMs: number, times: ApprovalTimes, label: string): BlockedExecution | undefined {
971
+ if (times.decidedAtMs > nowMs) {
972
+ return blocked('future_decision', `decidedAt is after the ${label} clock sample`);
973
+ }
974
+ if (times.notAfterMs !== undefined && nowMs >= times.notAfterMs) {
975
+ return blocked('expired', `${label} clock sample is at or after validity.notAfter`);
976
+ }
977
+ return undefined;
978
+ }
979
+
980
+ /**
981
+ * State retained across dispatch for observation signing. Deliberately holds
982
+ * NO callbacks: a callback stored here and invoked as a method would receive
983
+ * this object (observer private key, snapshot, receipt) as `this`. The object
984
+ * is frozen; its members are already deep-frozen or cloned.
985
+ */
986
+ interface PreparedDispatch {
987
+ readonly outcome: 'prepared';
988
+ snapshot: Readonly<JsonObject>;
989
+ checkedContext: Readonly<ApprovalContext>;
990
+ receipt: SignedReceipt<ApprovalReceiptPayload>;
991
+ observer: ReceiptSignerConfig | undefined;
992
+ attemptId: string;
993
+ td: number;
994
+ dispatchedAt: string;
995
+ }
996
+
997
+ /**
998
+ * Steps 1–6a of §5.3, fully synchronous: everything that must happen before
999
+ * dispatch, with every caller-controlled read guarded. Any failure here is a
1000
+ * typed blocked result; nothing in here may dispatch.
1001
+ */
1002
+ function prepareDispatch(params: ExecuteApprovedParams, dispatch: unknown): BlockedExecution | PreparedDispatch {
1003
+ // ----- Step 1: capture and snapshot once, before any other read ---------
1004
+ if (!isObjectLike(params)) {
1005
+ return blocked('malformed_input', `params must be an object, got ${describe(params)}`);
1006
+ }
1007
+ let rawReceipt: unknown;
1008
+ let rawExpectedSigner: unknown;
1009
+ let rawContext: unknown;
1010
+ let argumentsJson: unknown;
1011
+ let attemptId: unknown;
1012
+ let consume: unknown;
1013
+ let rawObserver: unknown;
1014
+ let rawClock: unknown;
1015
+ try {
1016
+ rawReceipt = params.receipt;
1017
+ rawExpectedSigner = params.expectedSigner;
1018
+ rawContext = params.context;
1019
+ argumentsJson = params.argumentsJson;
1020
+ attemptId = params.attemptId;
1021
+ consume = params.consume;
1022
+ rawObserver = params.observer;
1023
+ rawClock = params.clock;
1024
+ } catch (e) {
1025
+ return blocked('malformed_input', `reading params threw: ${errorMessage(e)}`);
1026
+ }
1027
+
1028
+ if (typeof dispatch !== 'function') return blocked('malformed_input', 'dispatch must be a function');
1029
+ if (typeof argumentsJson !== 'string') return blocked('malformed_input', 'argumentsJson must be a string');
1030
+ if (typeof attemptId !== 'string' || !ID_PATTERN.test(attemptId)) {
1031
+ return blocked('malformed_input', 'attemptId must be an id: printable ASCII excluding space (0x21..0x7E), 1..256 characters');
1032
+ }
1033
+ if (consume !== undefined && typeof consume !== 'function') {
1034
+ return blocked('malformed_input', 'consume must be a function when provided');
1035
+ }
1036
+ if (rawClock !== undefined && typeof rawClock !== 'function') {
1037
+ return blocked('malformed_input', 'clock must be a function when provided');
1038
+ }
1039
+ if (typeof rawExpectedSigner !== 'string' || rawExpectedSigner.length === 0) {
1040
+ return blocked('malformed_input', 'expectedSigner must be a non-empty string');
1041
+ }
1042
+ const clock: () => Date = rawClock === undefined ? () => new Date() : (rawClock as () => Date);
1043
+ const consumeFn = consume as ConsumeFn | undefined;
1044
+
1045
+ let receiptSnapshot: unknown;
1046
+ let contextSnapshot: unknown;
1047
+ let observerSnapshot: unknown;
1048
+ let expectedSigner: string;
1049
+ try {
1050
+ receiptSnapshot = structuredClone(rawReceipt);
1051
+ contextSnapshot = structuredClone(rawContext);
1052
+ observerSnapshot = rawObserver === undefined ? undefined : structuredClone(rawObserver);
1053
+ expectedSigner = structuredClone(rawExpectedSigner);
1054
+ } catch (e) {
1055
+ return blocked('malformed_input', `params are not structured-cloneable: ${errorMessage(e)}`);
1056
+ }
1057
+
1058
+ if (!isObjectLike(contextSnapshot)) {
1059
+ return blocked('malformed_input', `context must be an object, got ${describe(contextSnapshot)}`);
1060
+ }
1061
+ {
1062
+ let r = checkMembers(contextSnapshot, 'context', ['requester', 'audience', 'tool', 'operationId']);
1063
+ if (!r.ok) return blocked('malformed_input', r.detail);
1064
+ for (const member of ['requester', 'audience', 'tool', 'operationId']) {
1065
+ r = checkId(contextSnapshot, 'context', member);
1066
+ if (!r.ok) return blocked('malformed_input', r.detail);
1067
+ }
1068
+ }
1069
+ const checkedContext = deepFreeze(contextSnapshot as unknown as ApprovalContext);
1070
+
1071
+ const parsed = parseArguments(argumentsJson);
1072
+ if (!parsed.ok) return blocked('arguments_out_of_domain', parsed.detail);
1073
+ const snapshot = parsed.value;
1074
+ const snapshotDigest = parsed.digest;
1075
+
1076
+ // ----- Step 2: observer preflight, before anything is consumed ----------
1077
+ if (observerSnapshot !== undefined) {
1078
+ const r = validateSignerConfig(observerSnapshot, 'observer');
1079
+ if (!r.ok) return blocked('observer_invalid', r.detail);
1080
+ }
1081
+ const observer = observerSnapshot as ReceiptSignerConfig | undefined;
1082
+
1083
+ // ----- Step 3: validate the receipt against the snapshots ---------------
1084
+ const envelope = validateApprovalEnvelope(receiptSnapshot);
1085
+ if (!envelope.ok) return blocked(envelope.code, envelope.detail);
1086
+ const receipt = deepFreeze(envelope.receipt);
1087
+ if (!verifyReceipt(receipt)) {
1088
+ return blocked('signature_invalid', 'ES256K signature does not verify against the payload and claimed signer');
1089
+ }
1090
+ if (!verifyReceipt(receipt, expectedSigner)) {
1091
+ return blocked('untrusted_signer', `receipt signer ${receipt.signature.signer} is not the expected signer`);
1092
+ }
1093
+ if (receipt.payload.approval.decision !== 'approved') {
1094
+ return blocked('decision_not_approved', `approval decision is "${receipt.payload.approval.decision}"`);
1095
+ }
1096
+ for (const member of ['requester', 'audience', 'tool', 'operationId'] as const) {
1097
+ if (receipt.payload.binding[member] !== checkedContext[member]) {
1098
+ return blocked('context_mismatch', `binding.${member} does not equal context.${member}`);
1099
+ }
1100
+ }
1101
+ if (receipt.payload.binding.argumentsDigest !== snapshotDigest) {
1102
+ return blocked('arguments_mismatch', 'argumentsDigest does not equal the digest of the supplied arguments');
1103
+ }
1104
+ const times = approvalTimes(receipt.payload);
1105
+
1106
+ // ----- Step 4: first clock sample -----------------------------------------
1107
+ const t0 = sampleClock(clock);
1108
+ if (t0 === undefined) return blocked('invalid_clock', `${INVALID_CLOCK_DETAIL} (t0)`);
1109
+ const t0Problem = temporalCheck(t0, times, 'first');
1110
+ if (t0Problem) return t0Problem;
1111
+
1112
+ // ----- Step 5: consumption (once receipts only) ---------------------------
1113
+ if (receipt.payload.approval.validity.kind === 'once') {
1114
+ if (consumeFn === undefined) {
1115
+ return blocked('consume_required', 'a once receipt requires a consume callback');
1116
+ }
1117
+ const claim: ConsumeClaim = Object.freeze({
1118
+ signer: receipt.signature.signer.toLowerCase(),
1119
+ payloadHash: receipt.signature.payloadHash,
1120
+ operationId: receipt.payload.binding.operationId,
1121
+ });
1122
+ let decision: unknown;
1123
+ try {
1124
+ decision = consumeFn(claim);
1125
+ } catch (e) {
1126
+ return blocked('consume_rejected', `consume threw: ${errorMessage(e)}`);
1127
+ }
1128
+ if (decision !== true) {
1129
+ // A thenable (Promise or foreign) is never awaited and never authorizes;
1130
+ // sink its eventual rejection so blocking does not leak an unhandled one.
1131
+ const thenable = sinkThenable(decision);
1132
+ return blocked(
1133
+ 'consume_rejected',
1134
+ `consume did not return the literal true (got ${thenable ? 'a thenable' : describe(decision)})`,
1135
+ );
1136
+ }
1137
+ }
1138
+
1139
+ // ----- Step 6a: second clock sample -----------------------------------------
1140
+ const td = sampleClock(clock);
1141
+ if (td === undefined) return blocked('invalid_clock', `${INVALID_CLOCK_DETAIL} (td)`);
1142
+ const tdProblem = temporalCheck(td, times, 'second');
1143
+ if (tdProblem) return tdProblem;
1144
+ const dispatchedAt = new Date(td).toISOString();
1145
+
1146
+ return Object.freeze({
1147
+ outcome: 'prepared' as const,
1148
+ snapshot,
1149
+ checkedContext,
1150
+ receipt,
1151
+ observer,
1152
+ attemptId,
1153
+ td,
1154
+ dispatchedAt,
1155
+ });
1156
+ }
1157
+
1158
+ /**
1159
+ * The only path that dispatches. Follows spec §5.3 steps 1–7 in order:
1160
+ * snapshot once, preflight the observer, validate the receipt against the
1161
+ * snapshots, sample the clock, consume (once receipts), re-check the clock and
1162
+ * dispatch the frozen snapshot, then sign the observation.
1163
+ *
1164
+ * Result contract: any failure before dispatch — including an unexpected
1165
+ * exception — resolves to a typed blocked result and dispatch is never called.
1166
+ * After dispatch the result is always `returned` or an ApprovedExecutionError
1167
+ * rejection carrying the original cause; an observation failure of any kind
1168
+ * is reported as `observationError` and never changes the settlement.
1169
+ */
1170
+ export async function executeApproved<R>(
1171
+ params: ExecuteApprovedParams,
1172
+ dispatch: DispatchFn<R>,
1173
+ ): Promise<ApprovedExecution<R>> {
1174
+ // Captured once, as a local: invoked below as a bare function (`this` is
1175
+ // undefined), never as a method of any internal object.
1176
+ const dispatchFn = dispatch;
1177
+ let prepared: PreparedDispatch;
1178
+ try {
1179
+ const outcome = prepareDispatch(params, dispatchFn);
1180
+ if (outcome.outcome === 'blocked') return outcome;
1181
+ prepared = outcome;
1182
+ } catch (e) {
1183
+ // Fail closed: nothing has been dispatched, so a typed block is always correct.
1184
+ return blocked('malformed_input', `unexpected failure before dispatch: ${errorMessage(e)}`);
1185
+ }
1186
+
1187
+ // ----- Step 6b: dispatch immediately, no await between validation and call --
1188
+ let settlement: { outcome: 'returned'; value: R } | { outcome: 'threw'; cause: unknown };
1189
+ try {
1190
+ const value = await dispatchFn(prepared.snapshot, prepared.checkedContext);
1191
+ settlement = { outcome: 'returned', value };
1192
+ } catch (cause) {
1193
+ settlement = { outcome: 'threw', cause };
1194
+ }
1195
+
1196
+ // ----- Step 7: observation (never alters the settlement) --------------------
1197
+ let observation: SignedReceipt<ExecutionReceiptPayload> | undefined;
1198
+ let observationError: Error | undefined;
1199
+ if (prepared.observer !== undefined) {
1200
+ try {
1201
+ const { receipt, checkedContext, observer } = prepared;
1202
+ const payload: ExecutionReceiptPayload = {
1203
+ v: 1,
1204
+ kind: 'bolyra.execution',
1205
+ issuedAt: Math.floor(prepared.td / 1000),
1206
+ issuer: observer.issuer,
1207
+ keyId: observer.keyId,
1208
+ execution: {
1209
+ scheme: 'beo1',
1210
+ approvalReceiptHash: computeReceiptHash(receipt),
1211
+ approvalReceiptId: receipt.id,
1212
+ operationId: checkedContext.operationId,
1213
+ attemptId: prepared.attemptId,
1214
+ requester: checkedContext.requester,
1215
+ audience: checkedContext.audience,
1216
+ tool: checkedContext.tool,
1217
+ actionDigest: digestCanonical(canonicalize(prepared.snapshot)),
1218
+ dispatchedAt: prepared.dispatchedAt,
1219
+ outcome: settlement.outcome,
1220
+ },
1221
+ };
1222
+ observation = signReceipt(payload, observer);
1223
+ } catch (e) {
1224
+ observationError = toError(e);
1225
+ }
1226
+ }
1227
+
1228
+ if (settlement.outcome === 'returned') {
1229
+ const result: ReturnedExecution<R> = { outcome: 'returned', value: settlement.value };
1230
+ if (observation !== undefined) result.observation = observation;
1231
+ if (observationError !== undefined) result.observationError = observationError;
1232
+ return result;
1233
+ }
1234
+ throw new ApprovedExecutionError(settlement.cause, observation, observationError);
1235
+ }
1236
+
1237
+ // ---------------------------------------------------------------------------
1238
+ // §5.5 — verifyApprovalExecutionLink
1239
+ // ---------------------------------------------------------------------------
1240
+
1241
+ const LINK_CHECK_IDS: readonly LinkCheckId[] = ['A1', 'A2', 'A3', 'E1', 'E2', 'L1', 'L2', 'L3', 'L4'];
1242
+
1243
+ /**
1244
+ * Offline, pure link verification. Always reports all nine checks; a check
1245
+ * whose prerequisite failed is reported FAIL as "not evaluated". Never throws:
1246
+ * hostile inputs (cycles, bigint, throwing getters) yield FAIL checks.
1247
+ */
1248
+ export function verifyApprovalExecutionLink(params: VerifyLinkParams): LinkVerificationResult {
1249
+ try {
1250
+ return verifyLinkChecked(params);
1251
+ } catch (e) {
1252
+ const detail = `verification aborted: ${errorMessage(e)}`;
1253
+ return {
1254
+ ok: false,
1255
+ checks: LINK_CHECK_IDS.map((id) => ({ id, status: 'FAIL', detail })),
1256
+ statement: LINK_VERIFICATION_STATEMENT,
1257
+ };
1258
+ }
1259
+ }
1260
+
1261
+ function verifyLinkChecked(params: VerifyLinkParams): LinkVerificationResult {
1262
+ const checks: LinkCheck[] = [];
1263
+ const pass = (id: LinkCheckId, detail: string): void => {
1264
+ checks.push({ id, status: 'PASS', detail });
1265
+ };
1266
+ const failCheck = (id: LinkCheckId, detail: string): void => {
1267
+ checks.push({ id, status: 'FAIL', detail });
1268
+ };
1269
+ const notEvaluated = (id: LinkCheckId, dependsOn: string): void => {
1270
+ failCheck(id, `not evaluated: ${dependsOn} failed`);
1271
+ };
1272
+
1273
+ let expectedApprovalSigner: unknown;
1274
+ let expectedExecutionSigner: unknown;
1275
+ let approvalClone: unknown;
1276
+ let observationClone: unknown;
1277
+ let approvalCloneError: string | undefined;
1278
+ let observationCloneError: string | undefined;
1279
+ if (!isObjectLike(params)) {
1280
+ approvalCloneError = observationCloneError = `params must be an object, got ${describe(params)}`;
1281
+ } else {
1282
+ try {
1283
+ expectedApprovalSigner = params.expectedApprovalSigner;
1284
+ expectedExecutionSigner = params.expectedExecutionSigner;
1285
+ approvalClone = structuredClone(params.approval);
1286
+ } catch (e) {
1287
+ approvalCloneError = `approval could not be read or cloned: ${errorMessage(e)}`;
1288
+ }
1289
+ try {
1290
+ observationClone = structuredClone(params.observation);
1291
+ } catch (e) {
1292
+ observationCloneError = `observation could not be read or cloned: ${errorMessage(e)}`;
1293
+ }
1294
+ }
1295
+
1296
+ // A1
1297
+ let approval: SignedReceipt<ApprovalReceiptPayload> | undefined;
1298
+ if (approvalCloneError !== undefined) {
1299
+ failCheck('A1', approvalCloneError);
1300
+ } else {
1301
+ const a = validateApprovalEnvelope(approvalClone);
1302
+ if (a.ok) {
1303
+ approval = a.receipt;
1304
+ pass('A1', 'approval receipt: closed schema, kind, scheme, keyId agreement and derived id hold');
1305
+ } else {
1306
+ failCheck('A1', `approval receipt ${a.code}: ${a.detail}`);
1307
+ }
1308
+ }
1309
+
1310
+ // A2
1311
+ if (!approval) {
1312
+ notEvaluated('A2', 'A1');
1313
+ } else if (typeof expectedApprovalSigner !== 'string' || expectedApprovalSigner.length === 0) {
1314
+ failCheck('A2', 'expectedApprovalSigner must be a non-empty string');
1315
+ } else if (!verifyReceipt(approval)) {
1316
+ failCheck('A2', 'approval signature does not verify');
1317
+ } else if (!verifyReceipt(approval, expectedApprovalSigner)) {
1318
+ failCheck('A2', `approval signer ${approval.signature.signer} is not the expected approval signer`);
1319
+ } else {
1320
+ pass('A2', `approval signature valid; signer ${approval.signature.signer} is the expected approval signer`);
1321
+ }
1322
+
1323
+ // A3
1324
+ if (!approval) {
1325
+ notEvaluated('A3', 'A1');
1326
+ } else if (approval.payload.approval.decision !== 'approved') {
1327
+ failCheck('A3', `approval decision is "${approval.payload.approval.decision}"`);
1328
+ } else {
1329
+ pass('A3', 'approval decision is "approved"');
1330
+ }
1331
+
1332
+ // E1
1333
+ let observation: SignedReceipt<ExecutionReceiptPayload> | undefined;
1334
+ if (observationCloneError !== undefined) {
1335
+ failCheck('E1', observationCloneError);
1336
+ } else {
1337
+ const o = validateExecutionEnvelope(observationClone);
1338
+ if (o.ok) {
1339
+ observation = o.receipt;
1340
+ pass('E1', 'execution observation: closed schema, kind, scheme, keyId agreement and derived id hold');
1341
+ } else {
1342
+ failCheck('E1', `execution observation ${o.code}: ${o.detail}`);
1343
+ }
1344
+ }
1345
+
1346
+ // E2
1347
+ if (!observation) {
1348
+ notEvaluated('E2', 'E1');
1349
+ } else if (typeof expectedExecutionSigner !== 'string' || expectedExecutionSigner.length === 0) {
1350
+ failCheck('E2', 'expectedExecutionSigner must be a non-empty string');
1351
+ } else if (!verifyReceipt(observation)) {
1352
+ failCheck('E2', 'observation signature does not verify');
1353
+ } else if (!verifyReceipt(observation, expectedExecutionSigner)) {
1354
+ failCheck('E2', `observation signer ${observation.signature.signer} is not the expected execution signer`);
1355
+ } else {
1356
+ pass('E2', `observation signature valid; signer ${observation.signature.signer} is the expected execution signer`);
1357
+ }
1358
+
1359
+ // L1–L4
1360
+ if (!approval || !observation) {
1361
+ const dep = !approval ? 'A1' : 'E1';
1362
+ notEvaluated('L1', dep);
1363
+ notEvaluated('L2', dep);
1364
+ notEvaluated('L3', dep);
1365
+ notEvaluated('L4', dep);
1366
+ } else {
1367
+ const exec = observation.payload.execution;
1368
+ const binding = approval.payload.binding;
1369
+
1370
+ const recomputedHash = computeReceiptHash(approval);
1371
+ if (exec.approvalReceiptHash !== recomputedHash) {
1372
+ failCheck('L1', 'approvalReceiptHash does not equal the recomputed computeReceiptHash(approval)');
1373
+ } else if (exec.approvalReceiptId !== approval.id) {
1374
+ failCheck('L1', 'approvalReceiptId does not equal the approval receipt id');
1375
+ } else {
1376
+ pass('L1', 'observation references the approval receipt hash and id');
1377
+ }
1378
+
1379
+ const mismatched = (['operationId', 'requester', 'audience', 'tool'] as const).filter(
1380
+ (m) => exec[m] !== binding[m],
1381
+ );
1382
+ if (mismatched.length > 0) {
1383
+ failCheck('L2', `context differs between approval and observation: ${mismatched.join(', ')}`);
1384
+ } else {
1385
+ pass('L2', 'operationId, requester, audience and tool are equal');
1386
+ }
1387
+
1388
+ if (exec.actionDigest !== binding.argumentsDigest) {
1389
+ failCheck('L3', 'actionDigest does not equal the approved argumentsDigest');
1390
+ } else {
1391
+ pass('L3', 'actionDigest equals the approved argumentsDigest');
1392
+ }
1393
+
1394
+ const times = approvalTimes(approval.payload);
1395
+ const dispatchedAtMs = parseRfc3339MsZ(exec.dispatchedAt) as number;
1396
+ if (times.decidedAtMs > dispatchedAtMs) {
1397
+ failCheck('L4', 'dispatchedAt precedes decidedAt');
1398
+ } else if (times.notAfterMs !== undefined && dispatchedAtMs >= times.notAfterMs) {
1399
+ failCheck('L4', 'dispatchedAt is at or after validity.notAfter');
1400
+ } else {
1401
+ pass('L4', 'dispatchedAt is within the approval validity window');
1402
+ }
1403
+ }
1404
+
1405
+ return {
1406
+ ok: checks.every((c) => c.status === 'PASS'),
1407
+ checks,
1408
+ statement: LINK_VERIFICATION_STATEMENT,
1409
+ };
1410
+ }