@agent-custody/receipts 0.6.19 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -11
- package/dist/a2a.js +19 -7
- package/dist/approval.d.ts +74 -0
- package/dist/approval.js +196 -0
- package/dist/capture.d.ts +153 -0
- package/dist/capture.js +607 -0
- package/dist/cli.js +221 -6
- package/dist/config.d.ts +144 -0
- package/dist/config.js +92 -3
- package/dist/crypto.d.ts +2 -2
- package/dist/crypto.js +7 -4
- package/dist/delegation.d.ts +7 -0
- package/dist/delegation.js +15 -1
- package/dist/gateway-http.js +13 -1
- package/dist/gateway.d.ts +15 -0
- package/dist/gateway.js +414 -27
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/issue.d.ts +20 -5
- package/dist/issue.js +76 -8
- package/dist/log-sink.d.ts +11 -1
- package/dist/log-sink.js +24 -5
- package/dist/operations.d.ts +101 -0
- package/dist/operations.js +239 -0
- package/dist/otel.js +16 -8
- package/dist/portal.d.ts +23 -2
- package/dist/portal.js +181 -36
- package/dist/receipt.d.ts +54 -8
- package/dist/rest.js +14 -1
- package/dist/retention.d.ts +8 -1
- package/dist/retention.js +21 -2
- package/dist/sdk/index.js +10 -1
- package/dist/simulate.d.ts +58 -0
- package/dist/simulate.js +204 -0
- package/dist/splunk.js +17 -8
- package/dist/upstream.d.ts +9 -7
- package/dist/upstream.js +16 -8
- package/dist/verify.d.ts +18 -0
- package/dist/verify.js +405 -15
- package/docs/approvals.md +107 -0
- package/docs/compliance.md +1 -1
- package/docs/financial-operations.md +99 -0
- package/docs/policies.md +22 -0
- package/docs/tutorials.md +7 -0
- package/docs/usage.md +71 -5
- package/docs/verification.md +35 -10
- package/package.json +1 -1
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/receipts.json +3612 -292
package/dist/index.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export { buildRequest, restUpstream } from "./rest.ts";
|
|
|
5
5
|
export { openExporter, otlpExporter, spanFor } from "./otel.ts";
|
|
6
6
|
export { hecEvent, splunkExporter } from "./splunk.ts";
|
|
7
7
|
export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.ts";
|
|
8
|
+
export * from "./capture.ts";
|
|
8
9
|
export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.ts";
|
|
9
10
|
export { deliverMail, founderNote, PortalStore, portalHandler, readSession, sendFollowUps, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.ts";
|
|
10
11
|
export type { MailOptions, OAuthOptions, PortalOptions, PortalUser, Profile, RunningPortal, StripeOptions } from "./portal.ts";
|
|
@@ -32,8 +33,10 @@ export type { SplunkConfig, SplunkOptions } from "./splunk.ts";
|
|
|
32
33
|
export type { IssuerOptions } from "./issue.ts";
|
|
33
34
|
export type { RestOptions, UpstreamClient } from "./rest.ts";
|
|
34
35
|
export * from "./config.ts";
|
|
36
|
+
export * from "./operations.ts";
|
|
35
37
|
export * from "./crypto.ts";
|
|
36
38
|
export * from "./delegation.ts";
|
|
39
|
+
export * from "./approval.ts";
|
|
37
40
|
export * from "./gateway.ts";
|
|
38
41
|
export * from "./issue.ts";
|
|
39
42
|
export * from "./log.ts";
|
|
@@ -45,3 +48,4 @@ export * from "./sdk/index.ts";
|
|
|
45
48
|
export * from "./sidecar.ts";
|
|
46
49
|
export * from "./upstream.ts";
|
|
47
50
|
export * from "./retention.ts";
|
|
51
|
+
export * from "./simulate.ts";
|
package/dist/index.js
CHANGED
|
@@ -4,6 +4,7 @@ export { buildRequest, restUpstream } from "./rest.js";
|
|
|
4
4
|
export { openExporter, otlpExporter, spanFor } from "./otel.js";
|
|
5
5
|
export { hecEvent, splunkExporter } from "./splunk.js";
|
|
6
6
|
export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.js";
|
|
7
|
+
export * from "./capture.js";
|
|
7
8
|
export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.js";
|
|
8
9
|
export { deliverMail, founderNote, PortalStore, portalHandler, readSession, sendFollowUps, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.js";
|
|
9
10
|
export { exportLog, formatExport } from "./log-export.js";
|
|
@@ -15,8 +16,10 @@ export { adminRoutes, welcomeSheet } from "./log-admin.js";
|
|
|
15
16
|
export { fetchWitnessKeys, Witness } from "./witness.js";
|
|
16
17
|
export { checkLog, formatLogCheck } from "./log-check.js";
|
|
17
18
|
export * from "./config.js";
|
|
19
|
+
export * from "./operations.js";
|
|
18
20
|
export * from "./crypto.js";
|
|
19
21
|
export * from "./delegation.js";
|
|
22
|
+
export * from "./approval.js";
|
|
20
23
|
export * from "./gateway.js";
|
|
21
24
|
export * from "./issue.js";
|
|
22
25
|
export * from "./log.js";
|
|
@@ -28,3 +31,4 @@ export * from "./sdk/index.js";
|
|
|
28
31
|
export * from "./sidecar.js";
|
|
29
32
|
export * from "./upstream.js";
|
|
30
33
|
export * from "./retention.js";
|
|
34
|
+
export * from "./simulate.js";
|
package/dist/issue.d.ts
CHANGED
|
@@ -1,18 +1,33 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type CaptureConfig, type CaptureContext, type PrivateView } from "./capture.ts";
|
|
2
|
+
import { type Envelope, type KeyPair } from "./crypto.ts";
|
|
2
3
|
import { type LogSink } from "./log-sink.ts";
|
|
3
4
|
import type { ReceiptExporter } from "./otel.ts";
|
|
4
5
|
import { type AuthorizationBundle, type AuthorizationPredicate, type ReceiptBundle, type ReceiptPredicate } from "./receipt.ts";
|
|
6
|
+
/** Private recovery data: includes commitment salts. Persist only in an owner-only store, never in a receipt or export. */
|
|
7
|
+
export interface PreparedReceipt {
|
|
8
|
+
envelope: Envelope;
|
|
9
|
+
view: PrivateView<ReceiptPredicate>;
|
|
10
|
+
}
|
|
5
11
|
export interface Issuer {
|
|
6
12
|
keyid: string;
|
|
7
13
|
log: LogSink;
|
|
8
|
-
/**
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Applies the tool's capture rule to the whole predicate, signs the statement, appends it to the log, writes the
|
|
16
|
+
* bundle. Rejects if the log refuses the leaf; no bundle is written then. The predicate is the call in full; what
|
|
17
|
+
* is signed, written, and exported is the view.
|
|
18
|
+
*/
|
|
19
|
+
issue(predicate: ReceiptPredicate, ctx?: CaptureContext, retainPrepared?: (prepared: PreparedReceipt) => PreparedReceipt): Promise<ReceiptBundle>;
|
|
20
|
+
/** The same for an authorization, signed and committed before a consequential call is forwarded. Rejects if the log refuses; the caller must then not forward. */
|
|
21
|
+
authorize(predicate: AuthorizationPredicate, ctx?: CaptureContext): Promise<AuthorizationBundle>;
|
|
12
22
|
}
|
|
13
23
|
export interface IssuerOptions {
|
|
14
24
|
/** told about every receipt after it is written; an exporter's failure never reaches the caller */
|
|
15
25
|
exporter?: ReceiptExporter | undefined;
|
|
26
|
+
/** private evidence: the capture rules by tool, and the key that encrypts (`captureKeyEnv`), applied here to every statement before it is signed */
|
|
27
|
+
capture?: {
|
|
28
|
+
rules?: CaptureConfig | undefined;
|
|
29
|
+
key?: Buffer | undefined;
|
|
30
|
+
} | undefined;
|
|
16
31
|
}
|
|
17
32
|
/** `log` is a sink, or a file path for the local log with tree heads signed by the issuer's key. */
|
|
18
33
|
export declare function createIssuer(key: KeyPair, receiptsDir: string, log: string | LogSink, opts?: IssuerOptions): Issuer;
|
package/dist/issue.js
CHANGED
|
@@ -1,29 +1,97 @@
|
|
|
1
1
|
// Signing, logging and writing a receipt. Shared by every producer: the gateway and the SDK.
|
|
2
|
-
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { chmodSync, lstatSync, mkdirSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { SALTS_DIR, saltsFileFor } from "./retention.js";
|
|
3
4
|
import { join } from "node:path";
|
|
4
|
-
import {
|
|
5
|
+
import { effectiveRule, getAt, privateView } from "./capture.js";
|
|
6
|
+
import { canonicalize, dsseSign, dsseVerify } from "./crypto.js";
|
|
5
7
|
import { fileLog } from "./log-sink.js";
|
|
6
8
|
import { buildAuthorizationStatement, buildStatement, RECEIPT_TYPE } from "./receipt.js";
|
|
7
9
|
/** `log` is a sink, or a file path for the local log with tree heads signed by the issuer's key. */
|
|
8
10
|
export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
9
11
|
const sink = typeof log === "string" ? fileLog(log, key) : log;
|
|
10
12
|
mkdirSync(receiptsDir, { recursive: true });
|
|
13
|
+
const view = (predicate, ctx, prior) => privateView(predicate, effectiveRule(opts.capture?.rules, predicate.tool.name, ctx?.unknownTool), opts.capture?.key, ctx, prior);
|
|
14
|
+
/** the salts directory, checked before anything is signed or appended, so that a problem with it costs no leaf in the log */
|
|
15
|
+
const saltsDir = join(receiptsDir, SALTS_DIR);
|
|
16
|
+
const ensureSaltsDir = () => {
|
|
17
|
+
if (!opts.capture?.rules)
|
|
18
|
+
return;
|
|
19
|
+
// mkdir's mode applies only to a directory it creates: one that was there keeps its own, so it is set after
|
|
20
|
+
mkdirSync(saltsDir, { recursive: true, mode: 0o700 });
|
|
21
|
+
// the directory is the issuer's own: a link left at that name would carry every salt elsewhere
|
|
22
|
+
if (lstatSync(saltsDir).isSymbolicLink())
|
|
23
|
+
throw new Error(`${saltsDir} is a symbolic link; the salts are not written through it`);
|
|
24
|
+
chmodSync(saltsDir, 0o700);
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The view committed in an authorization, by receipt id, until its receipt is issued: the receipt carries the same
|
|
28
|
+
* commitments and salts for the parts they share. Set once the log has taken the authorization, released when the
|
|
29
|
+
* receipt is issued, and bounded: a call that never reaches its receipt does not keep its view for ever.
|
|
30
|
+
*/
|
|
31
|
+
const committed = new Map();
|
|
32
|
+
/** an authorization whose receipt has not followed within this long is a call that died; its view is let go */
|
|
33
|
+
const COMMITTED_FOR_MS = 60 * 60 * 1000;
|
|
34
|
+
const COMMITTED_AT_MOST = 100_000;
|
|
35
|
+
/**
|
|
36
|
+
* The salts behind a statement's digest-only commitments, kept beside the receipts and never in them:
|
|
37
|
+
* `receipts/salts/<id>.json`, the owner's alone. They are what makes a disclosure possible for a value withheld
|
|
38
|
+
* without its value, and what a reviewer must not be handed, since with them a guess can be confirmed. An encrypted
|
|
39
|
+
* commitment carries its salt inside the ciphertext, so that salt is not written: the key alone recovers it.
|
|
40
|
+
*/
|
|
41
|
+
const keepSalts = (v) => {
|
|
42
|
+
const salts = Object.fromEntries((v.predicate.capture?.withheld ?? []).filter((w) => getAt(v.predicate, w)?.$custody === "withheld").map((w) => [JSON.stringify(w), v.salts[JSON.stringify(w)]]));
|
|
43
|
+
if (!Object.keys(salts).length)
|
|
44
|
+
return;
|
|
45
|
+
writeFileSync(saltsFileFor(receiptsDir, v.predicate.receiptId), JSON.stringify({ receiptId: v.predicate.receiptId, salts }, null, 2), { mode: 0o600 });
|
|
46
|
+
};
|
|
11
47
|
return {
|
|
12
48
|
keyid: key.keyid,
|
|
13
49
|
log: sink,
|
|
14
|
-
async issue(predicate) {
|
|
15
|
-
|
|
50
|
+
async issue(predicate, ctx, retainPrepared) {
|
|
51
|
+
ensureSaltsDir();
|
|
52
|
+
// the authorization's view stays until the log has taken the receipt: a producer that retries after a refusal gets the same commitments and salts
|
|
53
|
+
const prior = committed.get(predicate.receiptId)?.view;
|
|
54
|
+
const candidate = view(predicate, ctx, prior);
|
|
55
|
+
// A durable producer may retain the first signed view, salts included, before any append. Concurrent and
|
|
56
|
+
// restarted issuers then commit exactly those bytes rather than re-salting the same logical receipt.
|
|
57
|
+
const prepared = retainPrepared ? retainPrepared({ envelope: dsseSign(RECEIPT_TYPE, buildStatement(candidate.predicate), key), view: candidate }) : { envelope: dsseSign(RECEIPT_TYPE, buildStatement(candidate.predicate), key), view: candidate };
|
|
58
|
+
const pv = prepared.view;
|
|
59
|
+
const v = pv.predicate;
|
|
60
|
+
const envelope = prepared.envelope;
|
|
61
|
+
if (retainPrepared) {
|
|
62
|
+
const checked = dsseVerify(envelope, [key]);
|
|
63
|
+
if (!checked.ok || envelope.payloadType !== RECEIPT_TYPE || v.receiptId !== predicate.receiptId || canonicalize(checked.payload) !== canonicalize(buildStatement(v)))
|
|
64
|
+
throw new Error("prepared receipt does not match this issuer, predicate, or receipt id");
|
|
65
|
+
}
|
|
16
66
|
const entry = await sink.append(canonicalize(envelope));
|
|
67
|
+
committed.delete(predicate.receiptId);
|
|
68
|
+
// the salts once the log has taken the leaf: a receipt the log refused leaves nothing behind
|
|
69
|
+
keepSalts(pv);
|
|
17
70
|
const bundle = { envelope, treeHead: entry.treeHead, inclusion: entry.inclusion };
|
|
18
71
|
writeFileSync(join(receiptsDir, `${predicate.receiptId}.json`), JSON.stringify(bundle, null, 2));
|
|
19
|
-
// After the evidence, not before, and awaited so a process that exits right after issuing still exports.
|
|
72
|
+
// After the evidence, not before, and awaited so a process that exits right after issuing still exports. The
|
|
73
|
+
// exporter sees the view, never the full call.
|
|
20
74
|
if (opts.exporter)
|
|
21
|
-
await opts.exporter.exported(
|
|
75
|
+
await opts.exporter.exported(v, bundle).catch(() => { });
|
|
22
76
|
return bundle;
|
|
23
77
|
},
|
|
24
|
-
async authorize(predicate) {
|
|
25
|
-
|
|
78
|
+
async authorize(predicate, ctx) {
|
|
79
|
+
ensureSaltsDir();
|
|
80
|
+
const pv = view(predicate, ctx);
|
|
81
|
+
const v = pv.predicate;
|
|
82
|
+
const envelope = dsseSign(RECEIPT_TYPE, buildAuthorizationStatement(v), key);
|
|
26
83
|
const entry = await sink.append(canonicalize(envelope));
|
|
84
|
+
// committed: the receipt that follows shares this view; nothing is kept for an authorization the log refused
|
|
85
|
+
const now = Date.now();
|
|
86
|
+
for (const [id, c] of committed) {
|
|
87
|
+
if (now - c.at <= COMMITTED_FOR_MS)
|
|
88
|
+
break;
|
|
89
|
+
committed.delete(id);
|
|
90
|
+
}
|
|
91
|
+
committed.set(predicate.receiptId, { view: pv, at: now });
|
|
92
|
+
if (committed.size > COMMITTED_AT_MOST)
|
|
93
|
+
committed.delete(committed.keys().next().value);
|
|
94
|
+
keepSalts(pv);
|
|
27
95
|
const bundle = { envelope, treeHead: entry.treeHead, inclusion: entry.inclusion };
|
|
28
96
|
// On disk in its own right: if the process dies between forwarding and the receipt, this is the evidence that the call was authorized and sent.
|
|
29
97
|
writeFileSync(join(receiptsDir, `${predicate.receiptId}.authorization.json`), JSON.stringify(bundle, null, 2));
|
package/dist/log-sink.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type IncomingMessage, type ServerResponse } from "node:http";
|
|
2
|
-
import { type Envelope, type KeyPair } from "./crypto.ts";
|
|
2
|
+
import { type Envelope, type KeyPair, type PublicKeyRef } from "./crypto.ts";
|
|
3
3
|
import { type InclusionProof } from "./log.ts";
|
|
4
4
|
import { type AuditEntry, type QuotaState, type LogBackend, type PostgresTenancy, type RateLimitOptions, type PolicyRecord } from "./log-store.ts";
|
|
5
5
|
import { type Signer } from "./signer.ts";
|
|
@@ -27,11 +27,19 @@ export interface HttpLogOptions {
|
|
|
27
27
|
retries?: number;
|
|
28
28
|
/** how long one append may take before it counts as unreachable; default 10000. A log that accepts and never answers must not hold a call forever. */
|
|
29
29
|
timeoutMs?: number;
|
|
30
|
+
/** the log's public keys, pinned: the tree head in every append's answer must be signed by one of them. Without them, the key document at the log's /.well-known/agent-custody-log.json is fetched on first use and pinned for the life of the sink. */
|
|
31
|
+
keys?: PublicKeyRef[];
|
|
32
|
+
/** the id the log must write into every tree head; an answer naming another log, or none, is refused */
|
|
33
|
+
logId?: string;
|
|
30
34
|
fetch?: typeof fetch;
|
|
31
35
|
}
|
|
32
36
|
/**
|
|
33
37
|
* A log reached over HTTP: POST <url>/append with {leaf} or {leafHash}, expecting a LogAppend back. A 429 or a 5xx
|
|
34
38
|
* is retried a few times with backoff, honouring Retry-After; anything else, or the last failure, is the caller's.
|
|
39
|
+
*
|
|
40
|
+
* The answer is not taken on trust. Before it is returned, and so before a pre-committed call is forwarded, the tree
|
|
41
|
+
* head must verify against the log's pinned keys, name the expected log, match the proof's size, and the inclusion
|
|
42
|
+
* proof must place this very leaf under the signed root. A log that answers with anything else has refused the append.
|
|
35
43
|
*/
|
|
36
44
|
export declare function httpLog(url: string, opts?: HttpLogOptions): LogSink;
|
|
37
45
|
export interface LogConfig {
|
|
@@ -41,6 +49,8 @@ export interface LogConfig {
|
|
|
41
49
|
tokenEnv?: string | undefined;
|
|
42
50
|
hashOnly?: boolean | undefined;
|
|
43
51
|
timeoutMs?: number | undefined;
|
|
52
|
+
keys?: string[] | undefined;
|
|
53
|
+
logId?: string | undefined;
|
|
44
54
|
} | undefined;
|
|
45
55
|
}
|
|
46
56
|
/** The sink a config asks for: a remote log when `log` is set, otherwise the local file. */
|
package/dist/log-sink.js
CHANGED
|
@@ -5,11 +5,11 @@
|
|
|
5
5
|
// logHandler and serveLog are the other side: a reference log server over node:http, the same code a hosted log runs.
|
|
6
6
|
import { timingSafeEqual } from "node:crypto";
|
|
7
7
|
import { createServer } from "node:http";
|
|
8
|
-
import { dsseSign } from "./crypto.js";
|
|
8
|
+
import { dsseSign, dsseVerify, loadPublicKey } from "./crypto.js";
|
|
9
9
|
import { createHash } from "node:crypto";
|
|
10
|
-
import { leafHash, MerkleLog } from "./log.js";
|
|
10
|
+
import { leafHash, MerkleLog, verifyInclusion } from "./log.js";
|
|
11
11
|
import { fileBackend, RateLimiter } from "./log-store.js";
|
|
12
|
-
import { localSigner } from "./signer.js";
|
|
12
|
+
import { fetchLogKeys, localSigner } from "./signer.js";
|
|
13
13
|
import { adminRoutes } from "./log-admin.js";
|
|
14
14
|
import { TREEHEAD_TYPE } from "./receipt.js";
|
|
15
15
|
function signedHead(e, key, logId) {
|
|
@@ -39,12 +39,31 @@ export function fileLog(file, key) {
|
|
|
39
39
|
/**
|
|
40
40
|
* A log reached over HTTP: POST <url>/append with {leaf} or {leafHash}, expecting a LogAppend back. A 429 or a 5xx
|
|
41
41
|
* is retried a few times with backoff, honouring Retry-After; anything else, or the last failure, is the caller's.
|
|
42
|
+
*
|
|
43
|
+
* The answer is not taken on trust. Before it is returned, and so before a pre-committed call is forwarded, the tree
|
|
44
|
+
* head must verify against the log's pinned keys, name the expected log, match the proof's size, and the inclusion
|
|
45
|
+
* proof must place this very leaf under the signed root. A log that answers with anything else has refused the append.
|
|
42
46
|
*/
|
|
43
47
|
export function httpLog(url, opts = {}) {
|
|
44
48
|
const f = opts.fetch ?? fetch;
|
|
45
49
|
const base = url.endsWith("/") ? url : `${url}/`;
|
|
46
50
|
const attempts = opts.retries ?? 3;
|
|
47
51
|
const timeoutMs = opts.timeoutMs ?? 10_000;
|
|
52
|
+
let pinned = opts.keys?.length ? Promise.resolve(opts.keys) : null;
|
|
53
|
+
const keys = () => (pinned ??= fetchLogKeys(base, f).then((r) => r.keys).catch((e) => { pinned = null; throw new Error(`log ${url}: its keys could not be fetched to check the append, and none are configured: ${e instanceof Error ? e.message : String(e)}`); }));
|
|
54
|
+
const checked = async (entry, leaf) => {
|
|
55
|
+
const th = dsseVerify(entry.treeHead, await keys());
|
|
56
|
+
if (!th.ok || entry.treeHead.payloadType !== TREEHEAD_TYPE)
|
|
57
|
+
throw new Error(`log ${url} answered with a tree head that does not verify against its keys${th.ok ? " (wrong payload type)" : `: ${th.error}`}`);
|
|
58
|
+
const head = th.payload;
|
|
59
|
+
if (opts.logId !== undefined && head.log !== opts.logId)
|
|
60
|
+
throw new Error(`log ${url} signed a tree head for log "${head.log ?? ""}", not "${opts.logId}"`);
|
|
61
|
+
if (head.treeSize !== entry.inclusion.treeSize)
|
|
62
|
+
throw new Error(`log ${url} answered with a tree head of size ${head.treeSize} and a proof for size ${entry.inclusion.treeSize}`);
|
|
63
|
+
if (!verifyInclusion(leafHash(leaf), entry.inclusion, head.rootHash))
|
|
64
|
+
throw new Error(`log ${url} answered with an inclusion proof that does not place this leaf under the signed root`);
|
|
65
|
+
return entry;
|
|
66
|
+
};
|
|
48
67
|
return {
|
|
49
68
|
kind: "http",
|
|
50
69
|
where: url,
|
|
@@ -70,7 +89,7 @@ export function httpLog(url, opts = {}) {
|
|
|
70
89
|
const body = (await res.json());
|
|
71
90
|
if (!body.inclusion || !body.treeHead)
|
|
72
91
|
throw new Error(`log ${url} returned a malformed append result`);
|
|
73
|
-
return body;
|
|
92
|
+
return checked(body, leaf);
|
|
74
93
|
}
|
|
75
94
|
last = `log ${url} refused the append: ${res.status} ${(await res.text()).slice(0, 200)}`;
|
|
76
95
|
if (res.status !== 429 && res.status < 500)
|
|
@@ -90,7 +109,7 @@ export function openLog(cfg, key) {
|
|
|
90
109
|
const token = cfg.log.tokenEnv ? process.env[cfg.log.tokenEnv] : undefined;
|
|
91
110
|
if (cfg.log.tokenEnv && !token)
|
|
92
111
|
throw new Error(`log token: environment variable ${cfg.log.tokenEnv} is not set`);
|
|
93
|
-
return httpLog(cfg.log.url, { ...(token === undefined ? {} : { token }), ...(cfg.log.hashOnly ? { hashOnly: true } : {}), ...(cfg.log.timeoutMs ? { timeoutMs: cfg.log.timeoutMs } : {}) });
|
|
112
|
+
return httpLog(cfg.log.url, { ...(token === undefined ? {} : { token }), ...(cfg.log.hashOnly ? { hashOnly: true } : {}), ...(cfg.log.timeoutMs ? { timeoutMs: cfg.log.timeoutMs } : {}), ...(cfg.log.keys ? { keys: cfg.log.keys.map(loadPublicKey) } : {}), ...(cfg.log.logId ? { logId: cfg.log.logId } : {}) });
|
|
94
113
|
}
|
|
95
114
|
if (!cfg.logFile)
|
|
96
115
|
throw new Error("config needs logFile or log.url");
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
export declare const OPERATION_META_KEY = "agent-custody/operation";
|
|
2
|
+
export type OperationStatus = "submitted" | "pending" | "confirmed" | "failed" | "unknown";
|
|
3
|
+
/**
|
|
4
|
+
* A stamp that tells one process from a later process with the same PID: the kernel start time of the process.
|
|
5
|
+
* The prefix names the source, so two stamps from different sources never compare equal. Returns undefined when
|
|
6
|
+
* the start time cannot be read.
|
|
7
|
+
*/
|
|
8
|
+
export declare function processStamp(pid: number): string | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* The start time from `ps`, for a system without /proc. `ps` prints it in local time, so the time zone is pinned to
|
|
11
|
+
* UTC: a creator and an operator that run under different TZ values must still get the same text.
|
|
12
|
+
*/
|
|
13
|
+
export declare function psStamp(pid: number): string | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* Whether the process that created an operation may still run. A process that is gone is not alive. A live process
|
|
16
|
+
* with the same PID but another start time is a different process (a container restart gives PID 1 again). When a
|
|
17
|
+
* start time cannot be compared, the answer is "alive": recovery waits, and never releases a live forward.
|
|
18
|
+
*/
|
|
19
|
+
export declare function ownerAlive(op: Pick<OperationRecord, "ownerPid" | "ownerStart">): boolean;
|
|
20
|
+
export interface OperationRecord {
|
|
21
|
+
id: string;
|
|
22
|
+
/** Creator process on this machine. A live submitted call cannot be reconciled underneath its forward. */
|
|
23
|
+
ownerPid: number;
|
|
24
|
+
/** `processStamp` of the creator, so that a later process with the same PID is not taken for it. */
|
|
25
|
+
ownerStart?: string;
|
|
26
|
+
issuerKeyid: string;
|
|
27
|
+
providerDigest?: string;
|
|
28
|
+
idempotencyKey: string;
|
|
29
|
+
principal: string;
|
|
30
|
+
agent: string;
|
|
31
|
+
tool: string;
|
|
32
|
+
argsDigest: string;
|
|
33
|
+
budget: string;
|
|
34
|
+
currency: string;
|
|
35
|
+
amount: number;
|
|
36
|
+
/** UTC date on which this operation was reserved; a retry never moves it to a new budget period. */
|
|
37
|
+
period: string;
|
|
38
|
+
status: OperationStatus;
|
|
39
|
+
originalReceiptId: string;
|
|
40
|
+
/** Signed authorization or execution bundle, saved before forwarding or returning it to the caller. */
|
|
41
|
+
original?: unknown;
|
|
42
|
+
/** The call as the gateway decided it, kept until `original` exists. It lets recovery sign a receipt for a call that was never forwarded. Holds raw request values: keep the database private. */
|
|
43
|
+
unsent?: unknown;
|
|
44
|
+
result?: unknown;
|
|
45
|
+
reconciliation?: unknown;
|
|
46
|
+
updatedAt: string;
|
|
47
|
+
}
|
|
48
|
+
export interface OperationReservation {
|
|
49
|
+
id: string;
|
|
50
|
+
issuerKeyid: string;
|
|
51
|
+
/** Digest of the configured upstream and destination; prevents retrying a key against a changed provider. */
|
|
52
|
+
providerDigest?: string;
|
|
53
|
+
principal: string;
|
|
54
|
+
agent: string;
|
|
55
|
+
tool: string;
|
|
56
|
+
argsDigest: string;
|
|
57
|
+
budget: string;
|
|
58
|
+
currency: string;
|
|
59
|
+
amount: number;
|
|
60
|
+
limit: number;
|
|
61
|
+
originalReceiptId: string;
|
|
62
|
+
/** Normally omitted; the gateway always uses the current UTC date. */
|
|
63
|
+
period?: string;
|
|
64
|
+
/** See `OperationRecord.unsent`. */
|
|
65
|
+
unsent?: unknown;
|
|
66
|
+
}
|
|
67
|
+
export interface OperationUpdate {
|
|
68
|
+
status?: OperationStatus;
|
|
69
|
+
original?: unknown;
|
|
70
|
+
unsent?: unknown;
|
|
71
|
+
result?: unknown;
|
|
72
|
+
reconciliation?: unknown;
|
|
73
|
+
}
|
|
74
|
+
/** One owner-only SQLite database, shared by all gateway sessions/processes using the same budgets. */
|
|
75
|
+
export declare class OperationStore {
|
|
76
|
+
private readonly db;
|
|
77
|
+
constructor(file: string);
|
|
78
|
+
get(id: string): OperationRecord | undefined;
|
|
79
|
+
/** Stable enumeration for an operator recovering outstanding work after a restart. */
|
|
80
|
+
list(): OperationRecord[];
|
|
81
|
+
reserve(input: OperationReservation): {
|
|
82
|
+
created: boolean;
|
|
83
|
+
operation: OperationRecord;
|
|
84
|
+
};
|
|
85
|
+
update(id: string, patch: OperationUpdate): OperationRecord;
|
|
86
|
+
/**
|
|
87
|
+
* Save the signed authorization of a submitted operation, and let the gateway forward. This is a compare-and-set:
|
|
88
|
+
* it refuses once recovery has closed the operation or claimed a reconciliation, whatever a liveness check said,
|
|
89
|
+
* so a call that recovery closed as "not forwarded" is never forwarded afterwards.
|
|
90
|
+
*/
|
|
91
|
+
saveAuthorization(id: string, original: unknown): OperationRecord;
|
|
92
|
+
/**
|
|
93
|
+
* Persist one terminal reconciliation intent before its asynchronous log append; later reconcilers use it.
|
|
94
|
+
* With `unsent`, the claim says that the call was never forwarded, and it holds only while no authorization is saved.
|
|
95
|
+
*/
|
|
96
|
+
claimReconciliation(id: string, candidate: unknown, unsent?: boolean): unknown;
|
|
97
|
+
/** Retain the first signed/captured receipt and its private salts, so every crash/concurrent retry uses identical bytes. */
|
|
98
|
+
prepareReconciliation(id: string, prepared: unknown): unknown;
|
|
99
|
+
close(): void;
|
|
100
|
+
private transaction;
|
|
101
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// A side effect is claimed durably before it may be forwarded. An existing claim is never forwarded again,
|
|
2
|
+
// even after a crash: only a provider reconciliation read may resolve its outcome and release its reservation.
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { closeSync, constants, lstatSync, mkdirSync, openSync, chmodSync, readFileSync } from "node:fs";
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
import { dirname, resolve } from "node:path";
|
|
7
|
+
import { digestOf } from "./crypto.js";
|
|
8
|
+
export const OPERATION_META_KEY = "agent-custody/operation";
|
|
9
|
+
/**
|
|
10
|
+
* A stamp that tells one process from a later process with the same PID: the kernel start time of the process.
|
|
11
|
+
* The prefix names the source, so two stamps from different sources never compare equal. Returns undefined when
|
|
12
|
+
* the start time cannot be read.
|
|
13
|
+
*/
|
|
14
|
+
export function processStamp(pid) {
|
|
15
|
+
try {
|
|
16
|
+
// Linux: field 22 of /proc/<pid>/stat, in clock ticks since boot. The command name (field 2) may hold spaces.
|
|
17
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
18
|
+
const field = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
|
|
19
|
+
if (field)
|
|
20
|
+
return `proc:${field}`;
|
|
21
|
+
}
|
|
22
|
+
catch { /* no /proc: try ps */ }
|
|
23
|
+
return psStamp(pid);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The start time from `ps`, for a system without /proc. `ps` prints it in local time, so the time zone is pinned to
|
|
27
|
+
* UTC: a creator and an operator that run under different TZ values must still get the same text.
|
|
28
|
+
*/
|
|
29
|
+
export function psStamp(pid) {
|
|
30
|
+
try {
|
|
31
|
+
const started = execFileSync("/bin/ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, env: { LC_ALL: "C", TZ: "UTC" }, stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
32
|
+
if (started)
|
|
33
|
+
return `ps:${started}`;
|
|
34
|
+
}
|
|
35
|
+
catch { /* unreadable */ }
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
let own;
|
|
39
|
+
/**
|
|
40
|
+
* Whether the process that created an operation may still run. A process that is gone is not alive. A live process
|
|
41
|
+
* with the same PID but another start time is a different process (a container restart gives PID 1 again). When a
|
|
42
|
+
* start time cannot be compared, the answer is "alive": recovery waits, and never releases a live forward.
|
|
43
|
+
*/
|
|
44
|
+
export function ownerAlive(op) {
|
|
45
|
+
try {
|
|
46
|
+
process.kill(op.ownerPid, 0);
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (error.code === "ESRCH")
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
const now = op.ownerStart === undefined ? undefined : processStamp(op.ownerPid);
|
|
53
|
+
if (op.ownerStart === undefined || now === undefined || op.ownerStart.split(":")[0] !== now.split(":")[0])
|
|
54
|
+
return true;
|
|
55
|
+
return now === op.ownerStart;
|
|
56
|
+
}
|
|
57
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
58
|
+
const STATUS = new Set(["submitted", "pending", "confirmed", "failed", "unknown"]);
|
|
59
|
+
const BINDING = ["issuerKeyid", "providerDigest", "principal", "agent", "tool", "argsDigest", "budget", "currency", "amount"];
|
|
60
|
+
/** One owner-only SQLite database, shared by all gateway sessions/processes using the same budgets. */
|
|
61
|
+
export class OperationStore {
|
|
62
|
+
db;
|
|
63
|
+
constructor(file) {
|
|
64
|
+
const path = resolve(file);
|
|
65
|
+
const directory = dirname(path);
|
|
66
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
67
|
+
const dir = lstatSync(directory);
|
|
68
|
+
if (!dir.isDirectory() || dir.isSymbolicLink() || (dir.mode & 0o077) !== 0)
|
|
69
|
+
throw new Error("operation database needs an owner-only directory (0700)");
|
|
70
|
+
// Create the file without following a symlink, before SQLite can open it. An existing regular file is
|
|
71
|
+
// tightened to 0600; the private parent prevents another user from swapping it while SQLite opens it.
|
|
72
|
+
try {
|
|
73
|
+
closeSync(openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600));
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
if (error.code !== "EEXIST")
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
const stat = lstatSync(path);
|
|
80
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1)
|
|
81
|
+
throw new Error("operation database must be a regular file, without symlinks or hard links");
|
|
82
|
+
chmodSync(path, 0o600);
|
|
83
|
+
// Deliberately lazy: gateways without financial operations never load SQLite (Node 22 may warn).
|
|
84
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
85
|
+
this.db = new DatabaseSync(path);
|
|
86
|
+
this.db.exec("PRAGMA busy_timeout = 10000; PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;");
|
|
87
|
+
this.db.exec("CREATE TABLE IF NOT EXISTS operations (id TEXT PRIMARY KEY, budget TEXT NOT NULL, currency TEXT NOT NULL, period TEXT NOT NULL, amount INTEGER NOT NULL, status TEXT NOT NULL, json TEXT NOT NULL)");
|
|
88
|
+
this.db.exec("CREATE INDEX IF NOT EXISTS operations_budget_period ON operations (budget, period, status)");
|
|
89
|
+
}
|
|
90
|
+
get(id) {
|
|
91
|
+
const row = this.db.prepare("SELECT json FROM operations WHERE id = ?").get(id);
|
|
92
|
+
return row ? JSON.parse(row.json) : undefined;
|
|
93
|
+
}
|
|
94
|
+
/** Stable enumeration for an operator recovering outstanding work after a restart. */
|
|
95
|
+
list() {
|
|
96
|
+
return this.db.prepare("SELECT json FROM operations ORDER BY id").all().map((row) => JSON.parse(row.json));
|
|
97
|
+
}
|
|
98
|
+
reserve(input) {
|
|
99
|
+
if (!UUID.test(input.id))
|
|
100
|
+
throw new Error("operation id must be a lowercase UUID");
|
|
101
|
+
if (!Number.isSafeInteger(input.amount) || input.amount <= 0)
|
|
102
|
+
throw new Error("operation amount must be a positive safe integer in minor units");
|
|
103
|
+
if (!Number.isSafeInteger(input.limit) || input.limit < 0)
|
|
104
|
+
throw new Error("operation budget limit must be a nonnegative safe integer in minor units");
|
|
105
|
+
for (const name of ["issuerKeyid", "principal", "agent", "tool", "argsDigest", "budget", "currency", "originalReceiptId"]) {
|
|
106
|
+
if (typeof input[name] !== "string" || !input[name].length)
|
|
107
|
+
throw new Error(`operation ${name} is required`);
|
|
108
|
+
}
|
|
109
|
+
if (input.budget.length > 128)
|
|
110
|
+
throw new Error("operation budget id must be at most 128 characters");
|
|
111
|
+
if (!/^[A-Z]{3}$/.test(input.currency))
|
|
112
|
+
throw new Error("operation currency must be three uppercase letters");
|
|
113
|
+
const period = input.period ?? new Date().toISOString().slice(0, 10);
|
|
114
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(period) || !Number.isFinite(Date.parse(`${period}T00:00:00.000Z`)) || new Date(`${period}T00:00:00.000Z`).toISOString().slice(0, 10) !== period)
|
|
115
|
+
throw new Error("operation period must be a UTC date");
|
|
116
|
+
return this.transaction(() => {
|
|
117
|
+
const previous = this.get(input.id);
|
|
118
|
+
if (previous) {
|
|
119
|
+
for (const field of BINDING) {
|
|
120
|
+
if (previous[field] !== input[field])
|
|
121
|
+
throw new Error(`operation id is already bound to different ${field}`);
|
|
122
|
+
}
|
|
123
|
+
return { created: false, operation: previous };
|
|
124
|
+
}
|
|
125
|
+
// Bind the currency even when an older operation failed or belongs to a previous day. Changing a
|
|
126
|
+
// budget's unit under the same name would otherwise make its amounts incomparable.
|
|
127
|
+
const otherCurrency = this.db.prepare("SELECT 1 FROM operations WHERE budget = ? AND currency <> ? LIMIT 1").get(input.budget, input.currency);
|
|
128
|
+
if (otherCurrency)
|
|
129
|
+
throw new Error("operation budget is already bound to another currency");
|
|
130
|
+
// Add with BigInt: individual minor-unit amounts are safe JS integers, but a sum need not be.
|
|
131
|
+
const reserved = this.db.prepare("SELECT amount FROM operations WHERE budget = ? AND period = ? AND status <> 'failed'").all(input.budget, period).reduce((sum, row) => sum + BigInt(row.amount), 0n);
|
|
132
|
+
if (reserved + BigInt(input.amount) > BigInt(input.limit))
|
|
133
|
+
throw new Error(`operation budget ${input.budget} exceeded for ${period}`);
|
|
134
|
+
const operation = {
|
|
135
|
+
id: input.id,
|
|
136
|
+
ownerPid: process.pid,
|
|
137
|
+
...((own ??= { stamp: processStamp(process.pid) }).stamp !== undefined ? { ownerStart: own.stamp } : {}),
|
|
138
|
+
issuerKeyid: input.issuerKeyid,
|
|
139
|
+
...(input.providerDigest !== undefined ? { providerDigest: input.providerDigest } : {}),
|
|
140
|
+
idempotencyKey: digestOf({ issuerKeyid: input.issuerKeyid, providerDigest: input.providerDigest ?? null, tool: input.tool, principal: input.principal, agent: input.agent, id: input.id }),
|
|
141
|
+
principal: input.principal,
|
|
142
|
+
agent: input.agent,
|
|
143
|
+
tool: input.tool,
|
|
144
|
+
argsDigest: input.argsDigest,
|
|
145
|
+
budget: input.budget,
|
|
146
|
+
currency: input.currency,
|
|
147
|
+
amount: input.amount,
|
|
148
|
+
period,
|
|
149
|
+
status: "submitted",
|
|
150
|
+
originalReceiptId: input.originalReceiptId,
|
|
151
|
+
...(input.unsent !== undefined ? { unsent: input.unsent } : {}),
|
|
152
|
+
updatedAt: new Date().toISOString(),
|
|
153
|
+
};
|
|
154
|
+
this.db.prepare("INSERT INTO operations (id, budget, currency, period, amount, status, json) VALUES (?, ?, ?, ?, ?, ?, ?)").run(operation.id, operation.budget, operation.currency, operation.period, operation.amount, operation.status, JSON.stringify(operation));
|
|
155
|
+
return { created: true, operation };
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
update(id, patch) {
|
|
159
|
+
if (patch.status !== undefined && !STATUS.has(patch.status))
|
|
160
|
+
throw new Error("invalid operation status");
|
|
161
|
+
return this.transaction(() => {
|
|
162
|
+
const operation = this.get(id);
|
|
163
|
+
if (!operation)
|
|
164
|
+
throw new Error("operation not found");
|
|
165
|
+
if ((operation.status === "confirmed" || operation.status === "failed") && patch.status !== undefined && patch.status !== operation.status)
|
|
166
|
+
throw new Error(`operation ${operation.status} is terminal`);
|
|
167
|
+
const updated = { ...operation, ...patch, updatedAt: new Date().toISOString() };
|
|
168
|
+
this.db.prepare("UPDATE operations SET status = ?, json = ? WHERE id = ?").run(updated.status, JSON.stringify(updated), id);
|
|
169
|
+
return updated;
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Save the signed authorization of a submitted operation, and let the gateway forward. This is a compare-and-set:
|
|
174
|
+
* it refuses once recovery has closed the operation or claimed a reconciliation, whatever a liveness check said,
|
|
175
|
+
* so a call that recovery closed as "not forwarded" is never forwarded afterwards.
|
|
176
|
+
*/
|
|
177
|
+
saveAuthorization(id, original) {
|
|
178
|
+
return this.transaction(() => {
|
|
179
|
+
const operation = this.get(id);
|
|
180
|
+
if (!operation)
|
|
181
|
+
throw new Error("operation not found");
|
|
182
|
+
if (operation.status !== "submitted" || operation.reconciliation !== undefined)
|
|
183
|
+
throw new Error(`operation was closed (${operation.status}) before its call was forwarded`);
|
|
184
|
+
const updated = { ...operation, original, updatedAt: new Date().toISOString() };
|
|
185
|
+
delete updated.unsent;
|
|
186
|
+
this.db.prepare("UPDATE operations SET json = ? WHERE id = ?").run(JSON.stringify(updated), id);
|
|
187
|
+
return updated;
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Persist one terminal reconciliation intent before its asynchronous log append; later reconcilers use it.
|
|
192
|
+
* With `unsent`, the claim says that the call was never forwarded, and it holds only while no authorization is saved.
|
|
193
|
+
*/
|
|
194
|
+
claimReconciliation(id, candidate, unsent = false) {
|
|
195
|
+
if (candidate === undefined || candidate === null)
|
|
196
|
+
throw new Error("reconciliation intent is required");
|
|
197
|
+
return this.transaction(() => {
|
|
198
|
+
const operation = this.get(id);
|
|
199
|
+
if (!operation)
|
|
200
|
+
throw new Error("operation not found");
|
|
201
|
+
if (operation.reconciliation !== undefined)
|
|
202
|
+
return operation.reconciliation;
|
|
203
|
+
if (unsent && (operation.original !== undefined || operation.status !== "submitted"))
|
|
204
|
+
throw new Error("the operation saved its authorization meanwhile; it may have been forwarded");
|
|
205
|
+
const updated = { ...operation, reconciliation: candidate, updatedAt: new Date().toISOString() };
|
|
206
|
+
this.db.prepare("UPDATE operations SET json = ? WHERE id = ?").run(JSON.stringify(updated), id);
|
|
207
|
+
return candidate;
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
/** Retain the first signed/captured receipt and its private salts, so every crash/concurrent retry uses identical bytes. */
|
|
211
|
+
prepareReconciliation(id, prepared) {
|
|
212
|
+
return this.transaction(() => {
|
|
213
|
+
const operation = this.get(id);
|
|
214
|
+
if (!operation || !operation.reconciliation)
|
|
215
|
+
throw new Error("reconciliation intent is required");
|
|
216
|
+
const reconciliation = operation.reconciliation;
|
|
217
|
+
if (reconciliation.prepared !== undefined)
|
|
218
|
+
return reconciliation.prepared;
|
|
219
|
+
const updated = { ...operation, reconciliation: { ...reconciliation, prepared }, updatedAt: new Date().toISOString() };
|
|
220
|
+
this.db.prepare("UPDATE operations SET json = ? WHERE id = ?").run(JSON.stringify(updated), id);
|
|
221
|
+
return prepared;
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
close() { this.db.close(); }
|
|
225
|
+
transaction(body) {
|
|
226
|
+
// The write lock covers BOTH looking up the key and checking/reserving the budget. A second process
|
|
227
|
+
// cannot claim the same operation or pass the same budget check while this one is committing it.
|
|
228
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
229
|
+
try {
|
|
230
|
+
const result = body();
|
|
231
|
+
this.db.exec("COMMIT");
|
|
232
|
+
return result;
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
this.db.exec("ROLLBACK");
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|