@scopebond/hook 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ // `recover` — deliver receipts this computer recorded but never delivered because the key
2
+ // that signed them was revoked first (the computer was replaced, disconnected or retired
3
+ // while records were still queued). The receipts are already signed; nothing is re-signed.
4
+ // The workspace checks each one against the revoked key it kept, accepts them only after
5
+ // an owner or admin approves, and labels them Recovered. Nothing here makes a revoked key
6
+ // usable again.
7
+ import { existsSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { SqliteReceiptStore, loadOrCreateAttester } from "@scopebond/gateway/node";
10
+ import { ingestUrl } from "./cloud.js";
11
+ /** The workspace accepts at most 1 MiB and 100 receipts per request. */
12
+ const MAX_BATCH_BYTES = 900 * 1024;
13
+ const MAX_BATCH_COUNT = 100;
14
+ const MAX_RECEIPT_BYTES = 128 * 1024;
15
+ const PAGE = 500;
16
+ /** How long one batch is retried through lost connections and server errors. */
17
+ const RETRY_FOR_MS = 15 * 60_000;
18
+ const kidOf = (r) => {
19
+ const kid = r.payload.attester?.kid;
20
+ return typeof kid === "string" ? kid : null;
21
+ };
22
+ /** Walk the whole local log once and count receipts per signing key other than `currentKid`. */
23
+ export function groupByEarlierKey(store, currentKid) {
24
+ const groups = new Map();
25
+ for (let after = 0;;) {
26
+ const page = store.page(after, PAGE);
27
+ if (!page.length)
28
+ break;
29
+ for (const { id, receipt } of page) {
30
+ after = id;
31
+ const kid = kidOf(receipt);
32
+ if (!kid || kid === currentKid)
33
+ continue;
34
+ const group = groups.get(kid) ?? { kid, count: 0, first: null, last: null };
35
+ group.count += 1;
36
+ const at = receipt.payload.timestamp;
37
+ if (!group.first || at < group.first)
38
+ group.first = at;
39
+ if (!group.last || at > group.last)
40
+ group.last = at;
41
+ groups.set(kid, group);
42
+ }
43
+ }
44
+ return [...groups.values()].sort((a, b) => (a.first ?? "").localeCompare(b.first ?? ""));
45
+ }
46
+ async function call(io, connection, path, body) {
47
+ const response = await io.fetch(new URL(path, ingestUrl(connection)), {
48
+ method: body === undefined ? "GET" : "POST",
49
+ headers: { authorization: `Bearer ${connection.credential}`, "content-type": "application/json" },
50
+ ...(body === undefined ? {} : { body: typeof body === "string" ? body : JSON.stringify(body) }),
51
+ redirect: "error",
52
+ signal: AbortSignal.timeout(60_000),
53
+ });
54
+ return { status: response.status, json: await response.json().catch(() => ({})) };
55
+ }
56
+ /** Recover every earlier key's receipts, one approval per key. */
57
+ export async function recoverEarlierReceipts(dir, connection, io, options) {
58
+ const result = { groups: 0, accepted: 0, duplicates: 0, rejected: 0, pending: 0, skipped: 0, failed: false };
59
+ const dbPath = join(dir, "receipts.db");
60
+ if (!existsSync(dbPath)) {
61
+ io.log("No local log here, so there is nothing to recover.");
62
+ return result;
63
+ }
64
+ const { attester } = loadOrCreateAttester({ file: join(dir, "attester.key") });
65
+ const store = new SqliteReceiptStore(dbPath);
66
+ try {
67
+ io.log("Reading the local log…");
68
+ const groups = groupByEarlierKey(store, attester.kid);
69
+ if (!groups.length) {
70
+ io.log("✓ Every local record was signed by this computer's current key. Nothing to recover.");
71
+ return result;
72
+ }
73
+ result.groups = groups.length;
74
+ for (const group of groups) {
75
+ io.log(`\n${group.count.toLocaleString()} records signed by an earlier key (${group.kid}), recorded ${group.first} – ${group.last}.`);
76
+ const asked = await call(io, connection, "/v1/recover", { source_kid: group.kid, claimed_count: group.count, first_at: group.first, last_at: group.last });
77
+ if (asked.json.code === "key_not_revoked") {
78
+ io.log(" Skipped: that key is still connected elsewhere, so its records are delivered from there, not recovered.");
79
+ result.skipped += group.count;
80
+ continue;
81
+ }
82
+ if (asked.status === 401) {
83
+ io.log(" This computer's own connection is not valid. Reconnect it first (login), then run recover again.");
84
+ result.failed = true;
85
+ return result;
86
+ }
87
+ if (asked.status >= 400) {
88
+ io.log(` The workspace refused: ${String(asked.json.error ?? `HTTP ${asked.status}`)}`);
89
+ result.skipped += group.count;
90
+ continue;
91
+ }
92
+ const id = String(asked.json.id ?? "");
93
+ let status = String(asked.json.status ?? "");
94
+ if (status === "pending") {
95
+ io.log(` Waiting for an owner or admin to approve it on Activity:\n\n ${String(asked.json.approve_url ?? connection.url)}\n`);
96
+ if (!options.wait) {
97
+ result.pending += group.count;
98
+ io.log(" Run recover again after it is approved.");
99
+ continue;
100
+ }
101
+ const deadline = io.now() + options.waitMs;
102
+ while (status === "pending" && io.now() < deadline) {
103
+ await io.sleep(options.pollMs);
104
+ const polled = await call(io, connection, `/v1/recover/${encodeURIComponent(id)}`).catch(() => null);
105
+ if (polled?.status === 200)
106
+ status = String(polled.json.status ?? status);
107
+ }
108
+ }
109
+ if (status === "declined") {
110
+ io.log(" Declined in the workspace. Nothing was sent.");
111
+ result.skipped += group.count;
112
+ continue;
113
+ }
114
+ if (status !== "approved") {
115
+ io.log(status === "pending" ? " Not approved yet. Run recover again after it is approved." : ` This recovery is ${status}. Run recover again to ask anew.`);
116
+ result.pending += group.count;
117
+ continue;
118
+ }
119
+ io.log(" ✓ Approved. Sending…");
120
+ const sent = await uploadGroup(store, group, id, connection, io);
121
+ result.accepted += sent.accepted;
122
+ result.duplicates += sent.duplicates;
123
+ result.rejected += sent.rejected;
124
+ if (sent.stopped) {
125
+ result.failed = true;
126
+ return result;
127
+ }
128
+ await call(io, connection, `/v1/recover/${encodeURIComponent(id)}/complete`, {}).catch(() => null);
129
+ io.log(` ✓ ${sent.accepted.toLocaleString()} recovered, ${sent.duplicates.toLocaleString()} were already in the workspace, ${sent.rejected.toLocaleString()} refused.`);
130
+ }
131
+ return result;
132
+ }
133
+ finally {
134
+ store.close();
135
+ }
136
+ }
137
+ async function uploadGroup(store, group, id, connection, io) {
138
+ const totals = { accepted: 0, duplicates: 0, rejected: 0, stopped: false };
139
+ let batch = [];
140
+ let bytes = 0;
141
+ let sent = 0;
142
+ const send = async () => {
143
+ if (!batch.length)
144
+ return true;
145
+ const body = `{"receipts":[${batch.join(",")}]}`;
146
+ const started = io.now();
147
+ for (let attempt = 1;; attempt++) {
148
+ const answer = await call(io, connection, `/v1/recover/${encodeURIComponent(id)}/receipts`, body).catch((error) => ({ status: 0, json: { error: error.message } }));
149
+ if (answer.status === 200) {
150
+ totals.accepted += Number(answer.json.accepted ?? 0);
151
+ totals.duplicates += Number(answer.json.duplicates ?? 0);
152
+ totals.rejected += Number(answer.json.rejected_count ?? 0);
153
+ break;
154
+ }
155
+ // Durable but not yet readable, or a network error: the same batch is safe to resend.
156
+ // A laptop that sleeps or changes networks loses the connection for minutes, not
157
+ // seconds: keep resending with backoff for up to RETRY_FOR_MS before giving up.
158
+ if ((answer.status === 0 || answer.status >= 500) && io.now() - started < RETRY_FOR_MS) {
159
+ const wait = Math.min(60_000, 2_000 * 2 ** Math.min(attempt - 1, 5));
160
+ io.log(` ${answer.status === 0 ? "Connection lost" : `The workspace answered ${answer.status}`}; trying the same batch again in ${Math.round(wait / 1000)} s…`);
161
+ await io.sleep(wait);
162
+ continue;
163
+ }
164
+ io.log(` Stopped: ${String(answer.json.error ?? `HTTP ${answer.status}`)}. Records already sent stay recovered; run recover again to continue.`);
165
+ totals.stopped = true;
166
+ return false;
167
+ }
168
+ sent += batch.length;
169
+ if (sent % 1000 < batch.length || sent === group.count)
170
+ io.log(` … ${sent.toLocaleString()} of ${group.count.toLocaleString()}`);
171
+ batch = [];
172
+ bytes = 0;
173
+ return true;
174
+ };
175
+ for (let after = 0;;) {
176
+ const page = store.page(after, PAGE);
177
+ if (!page.length)
178
+ break;
179
+ for (const { id: row, receipt } of page) {
180
+ after = row;
181
+ if (kidOf(receipt) !== group.kid)
182
+ continue;
183
+ const json = JSON.stringify(receipt);
184
+ const size = Buffer.byteLength(json);
185
+ if (size > MAX_RECEIPT_BYTES) {
186
+ totals.rejected += 1;
187
+ continue;
188
+ }
189
+ if (batch.length >= MAX_BATCH_COUNT || bytes + size + 1 > MAX_BATCH_BYTES) {
190
+ if (!(await send()))
191
+ return totals;
192
+ }
193
+ batch.push(json);
194
+ bytes += size + 1;
195
+ }
196
+ }
197
+ if (!(await send()))
198
+ return totals;
199
+ return totals;
200
+ }
201
+ //# sourceMappingURL=recover.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recover.js","sourceRoot":"","sources":["../src/recover.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,yFAAyF;AACzF,2FAA2F;AAC3F,yFAAyF;AACzF,0FAA0F;AAC1F,gBAAgB;AAEhB,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACnF,OAAO,EAAE,SAAS,EAAuB,MAAM,YAAY,CAAC;AAE5D,wEAAwE;AACxE,MAAM,eAAe,GAAG,GAAG,GAAG,IAAI,CAAC;AACnC,MAAM,eAAe,GAAG,GAAG,CAAC;AAC5B,MAAM,iBAAiB,GAAG,GAAG,GAAG,IAAI,CAAC;AACrC,MAAM,IAAI,GAAG,GAAG,CAAC;AACjB,gFAAgF;AAChF,MAAM,YAAY,GAAG,EAAE,GAAG,MAAM,CAAC;AAWjC,MAAM,KAAK,GAAG,CAAC,CAAgB,EAAiB,EAAE;IAChD,MAAM,GAAG,GAAI,CAAC,CAAC,OAA4C,CAAC,QAAQ,EAAE,GAAG,CAAC;IAC1E,OAAO,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC9C,CAAC,CAAC;AAEF,gGAAgG;AAChG,MAAM,UAAU,iBAAiB,CAAC,KAAyB,EAAE,UAAkB;IAC7E,MAAM,MAAM,GAAG,IAAI,GAAG,EAAoB,CAAC;IAC3C,KAAK,IAAI,KAAK,GAAG,CAAC,IAAK,CAAC;QACtB,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACrC,IAA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CAAC;YAClH,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAAC,KAAK,IAAI,IAAI,GAAG,CAAC,CAAC;QACtC,CAAC;IACH,CAAC;IACD,IAAI,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC;QAAE,OAAO,MAAM,CAAC;IACnC,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// `recover` — deliver receipts this computer recorded but never delivered because the key\n// that signed them was revoked first (the computer was replaced, disconnected or retired\n// while records were still queued). The receipts are already signed; nothing is re-signed.\n// The workspace checks each one against the revoked key it kept, accepts them only after\n// an owner or admin approves, and labels them Recovered. Nothing here makes a revoked key\n// usable again.\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { SignedReceipt } from \"@scopebond/gateway\";\nimport { SqliteReceiptStore, loadOrCreateAttester } from \"@scopebond/gateway/node\";\nimport { ingestUrl, type HookConnection } from \"./cloud.js\";\n\n/** The workspace accepts at most 1 MiB and 100 receipts per request. */\nconst MAX_BATCH_BYTES = 900 * 1024;\nconst MAX_BATCH_COUNT = 100;\nconst MAX_RECEIPT_BYTES = 128 * 1024;\nconst PAGE = 500;\n/** How long one batch is retried through lost connections and server errors. */\nconst RETRY_FOR_MS = 15 * 60_000;\n\nexport interface KeyGroup { kid: string; count: number; first: string | null; last: string | null }\n\nexport interface RecoverIo {\n log(line: string): void;\n fetch: typeof fetch;\n sleep(ms: number): Promise<void>;\n now(): number;\n}\n\nconst kidOf = (r: SignedReceipt): string | null => {\n const kid = (r.payload as { attester?: { kid?: unknown } }).attester?.kid;\n return typeof kid === \"string\" ? kid : null;\n};\n\n/** Walk the whole local log once and count receipts per signing key other than `currentKid`. */\nexport function groupByEarlierKey(store: SqliteReceiptStore, currentKid: string): KeyGroup[] {\n const groups = new Map<string, KeyGroup>();\n for (let after = 0; ;) {\n const page = store.page(after, PAGE);\n if (!page.length) break;\n for (const { id, receipt } of page) {\n after = id;\n const kid = kidOf(receipt);\n if (!kid || kid === currentKid) continue;\n const group = groups.get(kid) ?? { kid, count: 0, first: null, last: null };\n group.count += 1;\n const at = receipt.payload.timestamp;\n if (!group.first || at < group.first) group.first = at;\n if (!group.last || at > group.last) group.last = at;\n groups.set(kid, group);\n }\n }\n return [...groups.values()].sort((a, b) => (a.first ?? \"\").localeCompare(b.first ?? \"\"));\n}\n\ninterface Answer { status: number; json: Record<string, unknown> }\n\nasync function call(io: RecoverIo, connection: HookConnection, path: string, body?: unknown): Promise<Answer> {\n const response = await io.fetch(new URL(path, ingestUrl(connection)), {\n method: body === undefined ? \"GET\" : \"POST\",\n headers: { authorization: `Bearer ${connection.credential}`, \"content-type\": \"application/json\" },\n ...(body === undefined ? {} : { body: typeof body === \"string\" ? body : JSON.stringify(body) }),\n redirect: \"error\",\n signal: AbortSignal.timeout(60_000),\n });\n return { status: response.status, json: await response.json().catch(() => ({})) as Record<string, unknown> };\n}\n\nexport interface RecoverOptions { wait: boolean; waitMs: number; pollMs: number }\n\nexport interface RecoverResult { groups: number; accepted: number; duplicates: number; rejected: number; pending: number; skipped: number; failed: boolean }\n\n/** Recover every earlier key's receipts, one approval per key. */\nexport async function recoverEarlierReceipts(\n dir: string, connection: HookConnection, io: RecoverIo, options: RecoverOptions,\n): Promise<RecoverResult> {\n const result: RecoverResult = { groups: 0, accepted: 0, duplicates: 0, rejected: 0, pending: 0, skipped: 0, failed: false };\n const dbPath = join(dir, \"receipts.db\");\n if (!existsSync(dbPath)) { io.log(\"No local log here, so there is nothing to recover.\"); return result; }\n const { attester } = loadOrCreateAttester({ file: join(dir, \"attester.key\") });\n const store = new SqliteReceiptStore(dbPath);\n try {\n io.log(\"Reading the local log…\");\n const groups = groupByEarlierKey(store, attester.kid);\n if (!groups.length) { io.log(\"✓ Every local record was signed by this computer's current key. Nothing to recover.\"); return result; }\n result.groups = groups.length;\n for (const group of groups) {\n io.log(`\\n${group.count.toLocaleString()} records signed by an earlier key (${group.kid}), recorded ${group.first} – ${group.last}.`);\n const asked = await call(io, connection, \"/v1/recover\", { source_kid: group.kid, claimed_count: group.count, first_at: group.first, last_at: group.last });\n if (asked.json.code === \"key_not_revoked\") {\n io.log(\" Skipped: that key is still connected elsewhere, so its records are delivered from there, not recovered.\");\n result.skipped += group.count; continue;\n }\n if (asked.status === 401) { io.log(\" This computer's own connection is not valid. Reconnect it first (login), then run recover again.\"); result.failed = true; return result; }\n if (asked.status >= 400) { io.log(` The workspace refused: ${String(asked.json.error ?? `HTTP ${asked.status}`)}`); result.skipped += group.count; continue; }\n const id = String(asked.json.id ?? \"\");\n let status = String(asked.json.status ?? \"\");\n if (status === \"pending\") {\n io.log(` Waiting for an owner or admin to approve it on Activity:\\n\\n ${String(asked.json.approve_url ?? connection.url)}\\n`);\n if (!options.wait) { result.pending += group.count; io.log(\" Run recover again after it is approved.\"); continue; }\n const deadline = io.now() + options.waitMs;\n while (status === \"pending\" && io.now() < deadline) {\n await io.sleep(options.pollMs);\n const polled = await call(io, connection, `/v1/recover/${encodeURIComponent(id)}`).catch(() => null);\n if (polled?.status === 200) status = String(polled.json.status ?? status);\n }\n }\n if (status === \"declined\") { io.log(\" Declined in the workspace. Nothing was sent.\"); result.skipped += group.count; continue; }\n if (status !== \"approved\") { io.log(status === \"pending\" ? \" Not approved yet. Run recover again after it is approved.\" : ` This recovery is ${status}. Run recover again to ask anew.`); result.pending += group.count; continue; }\n io.log(\" ✓ Approved. Sending…\");\n const sent = await uploadGroup(store, group, id, connection, io);\n result.accepted += sent.accepted; result.duplicates += sent.duplicates; result.rejected += sent.rejected;\n if (sent.stopped) { result.failed = true; return result; }\n await call(io, connection, `/v1/recover/${encodeURIComponent(id)}/complete`, {}).catch(() => null);\n io.log(` ✓ ${sent.accepted.toLocaleString()} recovered, ${sent.duplicates.toLocaleString()} were already in the workspace, ${sent.rejected.toLocaleString()} refused.`);\n }\n return result;\n } finally {\n store.close();\n }\n}\n\nasync function uploadGroup(\n store: SqliteReceiptStore, group: KeyGroup, id: string, connection: HookConnection, io: RecoverIo,\n): Promise<{ accepted: number; duplicates: number; rejected: number; stopped: boolean }> {\n const totals = { accepted: 0, duplicates: 0, rejected: 0, stopped: false };\n let batch: string[] = [];\n let bytes = 0;\n let sent = 0;\n const send = async (): Promise<boolean> => {\n if (!batch.length) return true;\n const body = `{\"receipts\":[${batch.join(\",\")}]}`;\n const started = io.now();\n for (let attempt = 1; ; attempt++) {\n const answer = await call(io, connection, `/v1/recover/${encodeURIComponent(id)}/receipts`, body).catch((error: Error) => ({ status: 0, json: { error: error.message } } as Answer));\n if (answer.status === 200) {\n totals.accepted += Number(answer.json.accepted ?? 0);\n totals.duplicates += Number(answer.json.duplicates ?? 0);\n totals.rejected += Number(answer.json.rejected_count ?? 0);\n break;\n }\n // Durable but not yet readable, or a network error: the same batch is safe to resend.\n // A laptop that sleeps or changes networks loses the connection for minutes, not\n // seconds: keep resending with backoff for up to RETRY_FOR_MS before giving up.\n if ((answer.status === 0 || answer.status >= 500) && io.now() - started < RETRY_FOR_MS) {\n const wait = Math.min(60_000, 2_000 * 2 ** Math.min(attempt - 1, 5));\n io.log(` ${answer.status === 0 ? \"Connection lost\" : `The workspace answered ${answer.status}`}; trying the same batch again in ${Math.round(wait / 1000)} s…`);\n await io.sleep(wait);\n continue;\n }\n io.log(` Stopped: ${String(answer.json.error ?? `HTTP ${answer.status}`)}. Records already sent stay recovered; run recover again to continue.`);\n totals.stopped = true;\n return false;\n }\n sent += batch.length;\n if (sent % 1000 < batch.length || sent === group.count) io.log(` … ${sent.toLocaleString()} of ${group.count.toLocaleString()}`);\n batch = []; bytes = 0;\n return true;\n };\n for (let after = 0; ;) {\n const page = store.page(after, PAGE);\n if (!page.length) break;\n for (const { id: row, receipt } of page) {\n after = row;\n if (kidOf(receipt) !== group.kid) continue;\n const json = JSON.stringify(receipt);\n const size = Buffer.byteLength(json);\n if (size > MAX_RECEIPT_BYTES) { totals.rejected += 1; continue; }\n if (batch.length >= MAX_BATCH_COUNT || bytes + size + 1 > MAX_BATCH_BYTES) { if (!(await send())) return totals; }\n batch.push(json); bytes += size + 1;\n }\n }\n if (!(await send())) return totals;\n return totals;\n}\n"]}
package/dist/runtime.d.ts CHANGED
@@ -50,6 +50,8 @@ export declare const dir: (d: string) => string;
50
50
  /** The write protection that is always on, whoever manages the rules: the hook's own settings and those of the agents it
51
51
  * guards. A workspace can relax CI-configuration writes; it can never relax these. */
52
52
  export declare const GUARDRAIL_WRITE_PATTERN: string;
53
+ /** The always-on floor as bare lookaheads, for a pattern that must also refuse these paths (the hook's own folder included). */
54
+ export declare const GUARDRAIL_LOOKAHEADS: string;
53
55
  export declare const DESTRUCTIVE: string[];
54
56
  /** Upgrade the starter-policy patterns an older hook wrote, in memory, so a user who
55
57
  * installed an earlier version gets the current protections without re-running init.
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAOA,OAAO,EAA6C,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGnG,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAgC,KAAK,cAAc,EAAE,MAAM,YAAY,CAAC;AAO/E,OAAO,EAAoB,KAAK,gBAAgB,EAAsB,MAAM,oBAAoB,CAAC;AAEjG,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf;;uFAEmF;IACnF,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB;iFAC6E;IAC7E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;sEACkE;IAClE,KAAK,CAAC,EAAE;QAAE,UAAU,EAAE,cAAc,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;QAAC,cAAc,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACvF;AAED,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,O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RITE = "^" + [...GUARDRAIL_WRITE, ...CI_WRITE].join("") + ".+";
52
52
  /** The write protection that is always on, whoever manages the rules: the hook's own settings and those of the agents it
53
53
  * guards. A workspace can relax CI-configuration writes; it can never relax these. */
54
54
  export const GUARDRAIL_WRITE_PATTERN = "^" + GUARDRAIL_WRITE.join("") + ".+";
55
+ /** The always-on floor as bare lookaheads, for a pattern that must also refuse these paths (the hook's own folder included). */
56
+ export const GUARDRAIL_LOOKAHEADS = under("\\.scopebond") + GUARDRAIL_WRITE.join("");
55
57
  const PROTECTED_READ = "^" + [
56
58
  under("\\.scopebond"),
57
59
  `(?!.*${ci("\\.(?:key|pem|p12|pfx|jks|keystore)")}$)`,
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,6EAA6E;AAC7E,iFAAiF;AACjF,sDAAsD;AAEtD,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,0BAA0B,EAAsB,MAAM,oBAAoB,CAAC;AACnG,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AACjF,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,EAAE,cAAc,EAAE,YAAY,EAAuB,MAAM,YAAY,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAsB,MAAM,cAAc,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,O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AC;4BAAS,CAAC;wBAAC,eAAe,GAAG,IAAI,CAAC;oBAAC,CAAC;oBACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,yCAAyC,OAAO,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;gBACzL,CAAC;gBACD,OAAO,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;YAChE,CAAC;YACD,OAAO,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;QAC7C,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// The hook runtime: a check-only (M0) gateway built once from the enrolled\n// machine key, policy and a durable local receipt log. Each mapped action is\n// signed by the machine key, decided against policy and countersigned — locally,\n// with no HTTP server and no Cloud dependency in 0.1.\n\nimport { readFileSync, existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { createGateway, StaticPrincipalKeyRegistry, type CloudExporter } from \"@scopebond/gateway\";\nimport { loadOrCreateAttester, openReceiptStore } from \"@scopebond/gateway/node\";\nimport { createSigner } from \"@scopebond/sdk\";\nimport type { Mapped } from \"./map.js\";\nimport { attachExporter, flushBounded, type HookConnection } from \"./cloud.js\";\nimport { explainDeny, type ExplainIntent } from \"./explain.js\";\nimport { RULES_FILE, loadRules } from \"./rules.js\";\nimport { applyRootScope } from \"./paths.js\";\nimport { withActionGroup, actionGroupId, ACTION_GROUP_PARAM } from \"./group.js\";\nimport { cliCommand } from \"./version.js\";\nimport { openDispatchGuard, DELEGATION_ENV } from \"@scopebond/gateway/node\";\nimport { dispatchIntentOf, type DispatchDecision, type DispatchGuard } from \"@scopebond/gateway\";\n\nexport interface RuntimeConfig {\n policyPath: string;\n keyPath: string;\n attesterPath: string;\n dbPath: string;\n /** Strict mode: an unmapped tool is policy-checked (and denied by a closed\n * allowlist) instead of observed. Fail-closed for tools with no taxonomy\n * mapping; default false (observe, matching the connector conformance vector). */\n strict?: boolean;\n /** The working directory the harness reported, used to resolve workspace roots when\n * the rule set lists `allowed_roots`. Defaults to the process directory. */\n cwd?: string;\n /** When connected to a Cloud workspace, receipts are auto-exported to the portal.\n * Export is best-effort and never changes the local decision. */\n cloud?: { connection: HookConnection; fetch?: typeof fetch; flushTimeoutMs?: number };\n}\n\nexport interface Decision {\n decision: \"allow\" | \"deny\" | \"not_evaluated\";\n reason: string;\n /** The clause that decided a deny, when the verdict named one. */\n clauseId?: string | null;\n /** The deciding receipt (the denied one, or the first allow). */\n receipt?: unknown;\n /** Every receipt produced — one per simple command in a decomposed shell call. */\n receipts?: unknown[];\n /** Each action as actually evaluated (after root scoping and grouping), with its\n * receipt: what the observation emitters bind a request digest to. */\n /** What the dispatch boundary spent or refused for this call, when one is configured. */\n dispatch?: DispatchDecision;\n dispatched?: Array<{ action: { action_type: string; params: Record<string, unknown> }; receipt?: unknown }>;\n}\n\n// The hook's own config and keys must be off-limits to the agent it governs:\n// otherwise the agent could rewrite its policy or read the signing keys and the\n// receipts stop meaning anything. These patterns are \"allow if the path does NOT\n// match a protected location\"; they run against the cwd-relative path the mapper\n// produces (and equally against an absolute one).\n//\n// Matching is case-insensitive — Windows and macOS open `.ENV` and `.env` as the\n// same file — by expanding each letter to a two-case class (policy patterns are\n// plain regular expressions with no flags). `ci()` is applied to literal text only.\nexport const ci = (s: string): string => s.replace(/[A-Za-z]/g, (c) => `[${c.toLowerCase()}${c.toUpperCase()}]`);\nexport const under = (dir: string): string => `(?!(?:.*/)?${ci(dir)}(?:/|$))`; // dir itself or anything inside it\nexport const named = (file: string): string => `(?!(?:.*/)?${ci(file)}$)`; // exactly this file name\nexport const dir = (d: string): string => `(?!(?:.*/)?${ci(d)}/?$)`; // the directory itself (a recursive read or copy)\n\n// The protected-write set, in two typed groups the catalog classifies separately:\n// guardrail/hook configuration (C02) and CI configuration (H03).\nconst GUARDRAIL_WRITE_PREV = [\n under(\"\\\\.scopebond\"), `(?!(?:.*/)?${ci(\"\\\\.claude/settings\")})`, under(\"\\\\.claude/hooks\"), under(\"\\\\.claude/agents\"),\n `(?!(?:.*/)?${ci(\"\\\\.cursor/hooks\")})`, named(\"\\\\.codex/hooks\\\\.json\"), named(\"\\\\.codex/config\\\\.toml\"), named(\"\\\\.mcp\\\\.json\"),\n under(\"\\\\.git/hooks\"), named(\"\\\\.git/config\"), under(\"\\\\.husky\"),\n];\nconst CI_WRITE_PREV = [\n under(\"\\\\.github/workflows\"), under(\"\\\\.github/actions\"), named(\"\\\\.gitlab-ci\\\\.yml\"), named(\"\\\\.gitlab-ci\\\\.yaml\"), under(\"\\\\.circleci\"),\n named(\"azure-pipelines\\\\.yml\"), named(\"Jenkinsfile\"),\n];\nconst GUARDRAIL_WRITE = [...GUARDRAIL_WRITE_PREV, named(\"\\\\.cursor/mcp\\\\.json\"), under(\"\\\\.githooks\")];\nconst CI_WRITE = [\n ...CI_WRITE_PREV,\n named(\"azure-pipelines\\\\.yaml\"), named(\"bitbucket-pipelines\\\\.yml\"), named(\"\\\\.travis\\\\.yml\"), named(\"\\\\.drone\\\\.yml\"),\n named(\"cloudbuild\\\\.yaml\"), named(\"cloudbuild\\\\.yml\"), under(\"\\\\.buildkite\"),\n];\n// What 0.8 compiled, kept so an installed policy that still carries it verbatim is\n// upgraded in memory (see LEGACY_STARTER_PATTERNS).\nconst PROTECTED_WRITE_PREV = \"^\" + [...GUARDRAIL_WRITE_PREV, ...CI_WRITE_PREV].join(\"\") + \".+\";\nconst PROTECTED_WRITE = \"^\" + [...GUARDRAIL_WRITE, ...CI_WRITE].join(\"\") + \".+\";\n/** The write protection that is always on, whoever manages the rules: the hook's own settings and those of the agents it\n * guards. A workspace can relax CI-configuration writes; it can never relax these. */\nexport const GUARDRAIL_WRITE_PATTERN = \"^\" + GUARDRAIL_WRITE.join(\"\") + \".+\";\n\nconst PROTECTED_READ = \"^\" + [\n under(\"\\\\.scopebond\"),\n `(?!.*${ci(\"\\\\.(?:key|pem|p12|pfx|jks|keystore)\")}$)`,\n // .env, .env.* — except templates whose name ends in .example/.sample/.template/.dist\n `(?!(?:.*/)?${ci(\"\\\\.env\")}(?!(?:\\\\.[^/]*)?\\\\.(?:${ci(\"example\")}|${ci(\"sample\")}|${ci(\"template\")}|${ci(\"dist\")})$)(?:\\\\.[^/]*)?$)`,\n named(\"\\\\.envrc\"),\n // Credentials outside the workspace that an agent can reach by absolute or ~ path,\n // and their directories as a whole (`cp -r ~/.ssh`, `grep -r x ~/.aws`).\n `(?!(?:.*/)?${ci(\"\\\\.ssh\")}(?:$|/(?!.*${ci(\"\\\\.pub\")}$)(?!${ci(\"known_hosts\")}$)(?!${ci(\"config\")}$)))`,\n `(?!(?:.*/)?${ci(\"\\\\.aws\")}(?:$|/(?!${ci(\"config\")}$)))`,\n named(\"\\\\.npmrc\"), named(\"\\\\.pypirc\"), named(\"\\\\.netrc\"), named(\"_netrc\"), named(\"\\\\.git-credentials\"),\n dir(\"\\\\.kube\"), named(\"\\\\.kube/config\"), dir(\"\\\\.docker\"), named(\"\\\\.docker/config\\\\.json\"),\n under(\"\\\\.config/gcloud\"), under(\"\\\\.azure\"), under(\"\\\\.gnupg\"),\n dir(\"\\\\.config/gh\"), named(\"\\\\.config/gh/hosts\\\\.yml\"), named(\"\\\\.claude/\\\\.credentials\\\\.json\"),\n].join(\"\") + \".+\";\n\n// Destructive programs, POSIX and Windows. The mapper records the program as typed,\n// so the pattern accepts any case and an executable suffix (`RM.exe`, `Remove-Item`).\nexport const DESTRUCTIVE = [\n \"rm\", \"sudo\", \"doas\", \"shutdown\", \"reboot\", \"halt\", \"poweroff\", \"mkfs\", \"dd\", \"shred\", \"truncate\", \"unlink\", \"wipe\", \"srm\",\n \"del\", \"rd\", \"rmdir\", \"erase\", \"deltree\", \"format\", \"diskpart\", \"remove-item\", \"ri\", \"clear-content\", \"clc\", \"stop-computer\", \"restart-computer\",\n];\nconst SAFE_SHELL = `^(?!(?:${DESTRUCTIVE.map(ci).join(\"|\")})(?:${ci(\"\\\\.(?:exe|cmd|bat|com|ps1)\")})?$).+`;\n\n// A push destination the starter policy refuses: main, master, release/*, the\n// \"every branch\" flags (`--all`, `--mirror`, `--branches`) and a push whose\n// destination the mapper could not read (`--unknown`: a git alias, a configured push\n// refspec, `send-pack`), in any case. `--tags` alone pushes only tags and is allowed.\nconst SAFE_REF = `^(?!(?:${ci(\"main\")}|${ci(\"master\")})$)(?!${ci(\"release\")}/)(?!-(?!-${ci(\"tags\")}$)).+`;\n\n// Patterns written by earlier starter policies (0.3–0.5), upgraded in memory when a\n// policy on disk still carries them verbatim. An operator's own edits never match\n// these strings and are left untouched.\nconst LEGACY_STARTER_PATTERNS: Record<string, string> = {\n [PROTECTED_WRITE_PREV]: PROTECTED_WRITE,\n \"^(?!(?:main|master)$)(?!release/).+\": SAFE_REF,\n \"^(?!(?:rm|sudo|shutdown|reboot|mkfs|dd|del|rd|rmdir|erase|deltree|format|Remove-Item|ri)$).+\": SAFE_SHELL,\n \"^(?!(?:rm|sudo|shutdown|reboot|mkfs|dd)$).+\": SAFE_SHELL,\n \"^(?!(?:.*/)?\\\\.scopebond/)(?!(?:.*/)?\\\\.claude/settings)(?!(?:.*/)?\\\\.cursor/hooks)(?!(?:.*/)?\\\\.codex/(?:hooks\\\\.json|config\\\\.toml)$)(?!(?:.*/)?\\\\.git/hooks/)(?!(?:.*/)?\\\\.github/workflows/)(?!(?:.*/)?\\\\.github/actions/)(?!(?:.*/)?\\\\.gitlab-ci\\\\.yml$)(?!(?:.*/)?\\\\.circleci/)(?!(?:.*/)?azure-pipelines\\\\.yml$)(?!(?:.*/)?Jenkinsfile$).+\": PROTECTED_WRITE,\n \"^(?!(?:.*/)?\\\\.scopebond/)(?!(?:.*/)?\\\\.claude/settings)(?!(?:.*/)?\\\\.cursor/hooks)(?!(?:.*/)?\\\\.git/hooks/)(?!(?:.*/)?\\\\.github/workflows/)(?!(?:.*/)?\\\\.github/actions/)(?!(?:.*/)?\\\\.gitlab-ci\\\\.yml$)(?!(?:.*/)?\\\\.circleci/)(?!(?:.*/)?azure-pipelines\\\\.yml$)(?!(?:.*/)?Jenkinsfile$).+\": PROTECTED_WRITE,\n \"^(?!(?:.*/)?\\\\.scopebond/)(?!(?:.*/)?\\\\.claude/settings)(?!(?:.*/)?\\\\.cursor/hooks)(?!(?:.*/)?\\\\.git/hooks/).+\": PROTECTED_WRITE,\n \"^(?!(?:.*/)?\\\\.scopebond/)(?!.*\\\\.key$)(?!(?:.*/)?\\\\.env(?:\\\\.(?!example$|sample$|template$)[^/]*)?$).+\": PROTECTED_READ,\n \"^(?!(?:.*/)?\\\\.scopebond/)(?!.*\\\\.key$).+\": PROTECTED_READ,\n};\n\n/** Upgrade the starter-policy patterns an older hook wrote, in memory, so a user who\n * installed an earlier version gets the current protections without re-running init.\n * Only exact legacy strings are replaced; any other pattern is the operator's own. */\nexport function upgradeStarterPolicy<T>(policy: T): T {\n const p = policy as { clauses?: Array<{ param_bounds?: Record<string, { pattern?: string }> }> };\n for (const clause of p?.clauses ?? []) {\n for (const bound of Object.values(clause?.param_bounds ?? {})) {\n if (bound && typeof bound.pattern === \"string\" && LEGACY_STARTER_PATTERNS[bound.pattern]) bound.pattern = LEGACY_STARTER_PATTERNS[bound.pattern];\n }\n }\n return policy;\n}\n\n/** The default starter policy for a coding agent: protect release branches, deny\n * destructive programs, allow workspace file access except the hook's own config\n * and keys, and trust only the enrolled machine key. Every threshold is the\n * operator's to edit. */\nexport function starterPolicy(agentKid: string): Record<string, unknown> {\n return {\n vocabulary_version: \"1.0\", policy_id: \"coding-agent\", version: 1,\n clauses: [\n {\n id: \"protect-branches\", type: \"action_allowlist\", mode: \"enforce\", action_types: [\"git.push\"],\n param_bounds: { ref: { pattern: SAFE_REF } },\n description: \"Deny pushes to main, master and release/* (any case, any refspec spelling), pushes of every branch at once (--all, --mirror) and pushes whose destination cannot be read from the command (a git alias, a configured push refspec, send-pack). A tags-only push (--tags) is allowed.\",\n },\n {\n id: \"safe-shell\", type: \"action_allowlist\", mode: \"enforce\", action_types: [\"shell.exec\"],\n param_bounds: { program: { pattern: SAFE_SHELL } },\n description: \"Deny destructive programs — POSIX (rm, sudo, doas, shutdown, reboot, mkfs, dd, shred, truncate, unlink, wipe) and Windows/PowerShell (del, rd, rmdir, erase, deltree, format, diskpart, Remove-Item, Clear-Content) — in any case and with or without .exe. An empty program (a command that could not be parsed, or whose program is only known at run time: $VAR, $(…), eval of a variable) is denied. Argument-shaped deletion (find -delete, git clean) is not a program name and is not covered here.\",\n },\n {\n id: \"protect-write\", type: \"action_allowlist\", mode: \"enforce\", action_types: [\"file.write\"],\n param_bounds: { path: { pattern: PROTECTED_WRITE } },\n description: \"Allow workspace writes, but never to the hook's policy/keys, Claude Code settings, hooks and agents, Cursor or Codex hook settings, .mcp.json and .cursor/mcp.json, git hooks (.git/hooks, .githooks) and git config, Husky hooks, or CI config (.github/workflows, .github/actions, .gitlab-ci.yml/.yaml, .circleci, azure-pipelines, bitbucket-pipelines.yml, .travis.yml, .drone.yml, cloudbuild, .buildkite, Jenkinsfile). Case-insensitive.\",\n },\n {\n id: \"protect-read\", type: \"action_allowlist\", mode: \"enforce\", action_types: [\"file.read\"],\n param_bounds: { path: { pattern: PROTECTED_READ } },\n description: \"Allow workspace reads, but never signing keys and key containers (*.key, *.pem, *.p12, *.pfx, *.jks), environment secret files (.env, .env.*, .envrc — except names ending in .example/.sample/.template/.dist), SSH private keys and the .ssh directory, cloud/registry/git credentials (.aws except .aws/config, .npmrc, .pypirc, .netrc, .git-credentials, .kube/config, .docker/config.json, gcloud, Azure, GnuPG, the GitHub CLI's hosts.yml, Claude Code's .credentials.json) or the hook's own .scopebond directory. Case-insensitive.\",\n },\n {\n id: \"observe-net-mcp\", type: \"action_allowlist\", mode: \"monitor\",\n action_types: [\"net.fetch\", \"mcp.tool.call\"],\n description: \"Observe network fetches and MCP tool calls (recorded, not blocked) — add bounds to enforce.\",\n },\n { id: \"keys\", type: \"key_policy\", active_keys: [agentKid], description: \"Only the enrolled machine key may sign.\" },\n ],\n };\n}\n\n/** Build the runtime. Throws on any setup failure (unparseable policy, missing\n * key, unavailable store) — the CLI turns that into a fail-closed deny. */\nexport function createHookRuntime(config: RuntimeConfig) {\n const policy = upgradeStarterPolicy(JSON.parse(readFileSync(config.policyPath, \"utf8\")));\n const agent = createSigner({ privateKeyPem: readFileSync(config.keyPath, \"utf8\") });\n const keys = new StaticPrincipalKeyRegistry([\n { kid: agent.kid, publicKeyPem: agent.publicKeyPem, purposes: [\"agent\"], status: \"active\" },\n ]);\n const { attester } = loadOrCreateAttester({ file: config.attesterPath });\n // When the project has a readable rule set, a denial names the command that edits it\n // rather than the generated file.\n const rulesRemedy = existsSync(join(dirname(config.policyPath), RULES_FILE))\n ? `run \\`${cliCommand(\"rules\")}\\` to see the limits in plain terms, or edit ${join(dirname(config.policyPath), RULES_FILE)}`\n : undefined;\n const { store: baseStore } = openReceiptStore({ db: config.dbPath });\n // When connected, mirror every stored receipt to the hosted portal through a\n // durable outbox. The wrapped store's decision is unchanged; export is best-effort.\n let store = baseStore;\n let exporter: CloudExporter | undefined;\n let outbox: { close(): void } | undefined;\n if (config.cloud) {\n const attached = attachExporter(config.dbPath + \".cloud-outbox.db\", config.cloud.connection, baseStore, config.cloud.fetch);\n store = attached.store;\n exporter = attached.exporter;\n outbox = attached.outbox;\n }\n const scopeRoots = loadRules(dirname(config.policyPath))?.allowed_roots ?? [];\n // The dispatch boundary is checked once per tool call, after every intent has been allowed, so the\n // gateway's own per-intent hook only reports what the runtime already decided for this call.\n const boundary = openDispatchGuard(dirname(config.policyPath));\n let boundaryVerdict: DispatchDecision | null = null;\n const gatewayGuard: DispatchGuard = { authorize: async () => boundaryVerdict ?? { allow: true, reason: \"ok\", consumed_approvals: [], budgets: [] } };\n const gateway = createGateway({ policy, authentication: { keys }, attester, store, mode: \"check_only\", dispatchGuard: gatewayGuard });\n\n return {\n gateway,\n agentKid: agent.kid,\n exporter,\n /** Deliver queued receipts to Cloud with a bounded timeout, then it is safe to\n * exit. Undelivered receipts persist in the durable outbox for the next run. */\n async flush(): Promise<void> {\n if (exporter) await flushBounded(exporter, config.cloud?.flushTimeoutMs);\n },\n /** Release the SQLite handles. The hook is a per-tool-call process, and a writer that\n * exits without closing leaves its write-ahead log on disk for the next process to\n * extend — measured at ~11 KiB of WAL per receipt against ~1.7 KiB when closed, so a\n * busy session was writing tens of megabytes of pure overhead into the user's project.\n * Always safe to call, and every exit path should. */\n close(): void {\n try { baseStore.close?.(); } catch { /* the decision is already recorded */ }\n try { outbox?.close(); } catch { /* best effort */ }\n try { boundary?.close(); } catch { /* best effort */ }\n },\n /** Decide one mapped action, recording a receipt either way. */\n async evaluateOne(mapped: Mapped): Promise<Decision> {\n const signed = agent.sign(mapped.intent);\n if (!mapped.evaluated && !config.strict) {\n // Unknown tool or unparseable command, non-strict: observe without\n // evaluating — grants nothing (D30).\n const { receipt } = await gateway.observeAction({ intent: signed.intent, authorization: signed.authorization });\n return { decision: \"not_evaluated\", reason: `no policy applies to ${mapped.intent.action_type}`, receipt };\n }\n // Evaluated actions, and (in strict mode) unmapped tool.<name>/opaque commands,\n // go through policy — a closed allowlist denies an unlisted action.\n const result = await gateway.handleAction({ intent: signed.intent, authorization: signed.authorization });\n if (result.allowed) return { decision: \"allow\", reason: result.reason, receipt: result.receipt };\n // A deny is the one message the user and their agent actually read, so it is\n // composed from the deciding clause's own words rather than the engine's\n // internal reason (\"param ref fails pattern\").\n const clauseId = result.verdict?.clause_id ?? null;\n return {\n decision: \"deny\",\n reason: explainDeny({\n policy, clauseId, detail: result.reason,\n intent: signed.intent as ExplainIntent, policyPath: config.policyPath,\n postHoc: mapped.postHoc,\n // Point at the editable surface when there is one. `policy.json` is compiled\n // from `rules.json`, so telling someone to hand-edit it invites a change the\n // next `rules` run would overwrite.\n remedy: rulesRemedy,\n }),\n clauseId,\n receipt: result.receipt,\n };\n },\n /** Decide a whole tool call. A shell call decomposes into several simple\n * commands; every one is recorded, and a single deny denies the call. */\n async evaluate(mapped: Mapped | Mapped[], options: { groupKey?: string } = {}): Promise<Decision> {\n const raw = Array.isArray(mapped) ? mapped : [mapped];\n if (raw.length === 0) return { decision: \"not_evaluated\", reason: \"no action\", receipts: [] };\n // Every intent of one tool call carries one parent group id, so the receipts of a\n // decomposed call (a command, its file reads and writes, a rename destination)\n // link to each other and count once as an action. It is part of the signed\n // intent, so it is authenticated by the same signature as the rest.\n const scoped = scopeRoots.length ? applyRootScope(raw, { cwd: config.cwd ?? process.cwd(), roots: scopeRoots }) : raw;\n const list = withActionGroup(scoped, actionGroupId(options.groupKey));\n const receipts: unknown[] = [];\n const dispatched: NonNullable<Decision[\"dispatched\"]> = [];\n let allow: Decision | null = null;\n let notEvaluated: Decision | null = null;\n for (const m of list) {\n const d = await this.evaluateOne(m);\n if (d.receipt !== undefined) receipts.push(d.receipt);\n dispatched.push({ action: { action_type: m.intent.action_type, params: m.intent.params as Record<string, unknown> }, ...(d.receipt !== undefined ? { receipt: d.receipt } : {}) });\n if (d.decision === \"deny\") return { ...d, receipts, dispatched }; // any deny denies the call\n if (d.decision === \"allow\" && !allow) allow = d;\n if (d.decision === \"not_evaluated\" && !notEvaluated) notEvaluated = d;\n }\n // No deny: allow if any command was evaluated-and-allowed, else not_evaluated.\n const chosen = allow ?? notEvaluated!;\n if (boundary) {\n // Immediately before permitted dispatch: approvals are consumed and the budget slot is reserved\n // atomically, once for the whole parent action, or nothing is spent and the call is denied.\n const group = String(list[0]!.intent.params[ACTION_GROUP_PARAM]);\n const delegation = process.env[DELEGATION_ENV] ?? \"\";\n const verdict = await boundary.authorize({\n actor: agent.kid, action_group: group, policy_digest: gateway.policyHash,\n intents: list.map((m) => dispatchIntentOf(m.intent as never)),\n ...(delegation !== \"\" ? { delegation_id: delegation } : {}),\n });\n if (!verdict.allow) {\n // Record the refusal as its own denied receipt, then deny the call.\n boundaryVerdict = verdict;\n try {\n const last = list[list.length - 1]!;\n const signed = agent.sign(last.intent);\n const result = await gateway.handleAction({ intent: signed.intent, authorization: signed.authorization });\n if (result.receipt !== undefined) receipts.push(result.receipt);\n } finally { boundaryVerdict = null; }\n return { decision: \"deny\", reason: `Scopebond blocked this before it ran: ${verdict.reason}${verdict.detail ? ` (${verdict.detail})` : \"\"}`, receipts, dispatched, dispatch: verdict };\n }\n return { ...chosen, receipts, dispatched, dispatch: verdict };\n }\n return { ...chosen, receipts, dispatched };\n },\n };\n}\n"]}
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,6EAA6E;AAC7E,iFAAiF;AACjF,sDAAsD;AAEtD,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,0BAA0B,EAAsB,MAAM,oBAAoB,CAAC;AACnG,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AACjF,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,EAAE,cAAc,EAAE,YAAY,EAAuB,MAAM,YAAY,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAsB,MAAM,cAAc,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAC5E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Q,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;oBAClE,CAAC;4BAAS,CAAC;wBAAC,eAAe,GAAG,IAAI,CAAC;oBAAC,CAAC;oBACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,yCAAyC,OAAO,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;gBACzL,CAAC;gBACD,OAAO,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;YAChE,CAAC;YACD,OAAO,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;QAC7C,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// The hook runtime: a check-only (M0) gateway built once from the enrolled\n// machine key, policy and a durable local receipt log. Each mapped action is\n// signed by the machine key, decided against policy and countersigned — locally,\n// with no HTTP server and no Cloud dependency in 0.1.\n\nimport { readFileSync, existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { createGateway, StaticPrincipalKeyRegistry, type CloudExporter } from \"@scopebond/gateway\";\nimport { loadOrCreateAttester, openReceiptStore } from \"@scopebond/gateway/node\";\nimport { createSigner } from \"@scopebond/sdk\";\nimport type { Mapped } from \"./map.js\";\nimport { attachExporter, flushBounded, type HookConnection } from \"./cloud.js\";\nimport { explainDeny, type ExplainIntent } from \"./explain.js\";\nimport { RULES_FILE, loadRules } from \"./rules.js\";\nimport { applyRootScope } from \"./paths.js\";\nimport { withActionGroup, actionGroupId, ACTION_GROUP_PARAM } from \"./group.js\";\nimport { cliCommand } from \"./version.js\";\nimport { openDispatchGuard, DELEGATION_ENV } from \"@scopebond/gateway/node\";\nimport { dispatchIntentOf, type DispatchDecision, type DispatchGuard } from \"@scopebond/gateway\";\n\nexport interface RuntimeConfig {\n policyPath: string;\n keyPath: string;\n attesterPath: string;\n dbPath: string;\n /** Strict mode: an unmapped tool is policy-checked (and denied by a closed\n * allowlist) instead of observed. Fail-closed for tools with no taxonomy\n * mapping; default false (observe, matching the connector conformance vector). */\n strict?: boolean;\n /** The working directory the harness reported, used to resolve workspace roots when\n * the rule set lists `allowed_roots`. Defaults to the process directory. */\n cwd?: string;\n /** When connected to a Cloud workspace, receipts are auto-exported to the portal.\n * Export is best-effort and never changes the local decision. */\n cloud?: { connection: HookConnection; fetch?: typeof fetch; flushTimeoutMs?: number };\n}\n\nexport interface Decision {\n decision: \"allow\" | \"deny\" | \"not_evaluated\";\n reason: string;\n /** The clause that decided a deny, when the verdict named one. */\n clauseId?: string | null;\n /** The deciding receipt (the denied one, or the first allow). */\n receipt?: unknown;\n /** Every receipt produced — one per simple command in a decomposed shell call. */\n receipts?: unknown[];\n /** Each action as actually evaluated (after root scoping and grouping), with its\n * receipt: what the observation emitters bind a request digest to. */\n /** What the dispatch boundary spent or refused for this call, when one is configured. */\n dispatch?: DispatchDecision;\n dispatched?: Array<{ action: { action_type: string; params: Record<string, unknown> }; receipt?: unknown }>;\n}\n\n// The hook's own config and keys must be off-limits to the agent it governs:\n// otherwise the agent could rewrite its policy or read the signing keys and the\n// receipts stop meaning anything. These patterns are \"allow if the path does NOT\n// match a protected location\"; they run against the cwd-relative path the mapper\n// produces (and equally against an absolute one).\n//\n// Matching is case-insensitive — Windows and macOS open `.ENV` and `.env` as the\n// same file — by expanding each letter to a two-case class (policy patterns are\n// plain regular expressions with no flags). `ci()` is applied to literal text only.\nexport const ci = (s: string): string => s.replace(/[A-Za-z]/g, (c) => `[${c.toLowerCase()}${c.toUpperCase()}]`);\nexport const under = (dir: string): string => `(?!(?:.*/)?${ci(dir)}(?:/|$))`; // dir itself or anything inside it\nexport const named = (file: string): string => `(?!(?:.*/)?${ci(file)}$)`; // exactly this file name\nexport const dir = (d: string): string => `(?!(?:.*/)?${ci(d)}/?$)`; // the directory itself (a recursive read or copy)\n\n// The protected-write set, in two typed groups the catalog classifies separately:\n// guardrail/hook configuration (C02) and CI configuration (H03).\nconst GUARDRAIL_WRITE_PREV = [\n under(\"\\\\.scopebond\"), `(?!(?:.*/)?${ci(\"\\\\.claude/settings\")})`, under(\"\\\\.claude/hooks\"), under(\"\\\\.claude/agents\"),\n `(?!(?:.*/)?${ci(\"\\\\.cursor/hooks\")})`, named(\"\\\\.codex/hooks\\\\.json\"), named(\"\\\\.codex/config\\\\.toml\"), named(\"\\\\.mcp\\\\.json\"),\n under(\"\\\\.git/hooks\"), named(\"\\\\.git/config\"), under(\"\\\\.husky\"),\n];\nconst CI_WRITE_PREV = [\n under(\"\\\\.github/workflows\"), under(\"\\\\.github/actions\"), named(\"\\\\.gitlab-ci\\\\.yml\"), named(\"\\\\.gitlab-ci\\\\.yaml\"), under(\"\\\\.circleci\"),\n named(\"azure-pipelines\\\\.yml\"), named(\"Jenkinsfile\"),\n];\nconst GUARDRAIL_WRITE = [...GUARDRAIL_WRITE_PREV, named(\"\\\\.cursor/mcp\\\\.json\"), under(\"\\\\.githooks\")];\nconst CI_WRITE = [\n ...CI_WRITE_PREV,\n named(\"azure-pipelines\\\\.yaml\"), named(\"bitbucket-pipelines\\\\.yml\"), named(\"\\\\.travis\\\\.yml\"), named(\"\\\\.drone\\\\.yml\"),\n named(\"cloudbuild\\\\.yaml\"), named(\"cloudbuild\\\\.yml\"), under(\"\\\\.buildkite\"),\n];\n// What 0.8 compiled, kept so an installed policy that still carries it verbatim is\n// upgraded in memory (see LEGACY_STARTER_PATTERNS).\nconst PROTECTED_WRITE_PREV = \"^\" + [...GUARDRAIL_WRITE_PREV, ...CI_WRITE_PREV].join(\"\") + \".+\";\nconst PROTECTED_WRITE = \"^\" + [...GUARDRAIL_WRITE, ...CI_WRITE].join(\"\") + \".+\";\n/** The write protection that is always on, whoever manages the rules: the hook's own settings and those of the agents it\n * guards. A workspace can relax CI-configuration writes; it can never relax these. */\nexport const GUARDRAIL_WRITE_PATTERN = \"^\" + GUARDRAIL_WRITE.join(\"\") + \".+\";\n/** The always-on floor as bare lookaheads, for a pattern that must also refuse these paths (the hook's own folder included). */\nexport const GUARDRAIL_LOOKAHEADS = under(\"\\\\.scopebond\") + GUARDRAIL_WRITE.join(\"\");\n\nconst PROTECTED_READ = \"^\" + [\n under(\"\\\\.scopebond\"),\n `(?!.*${ci(\"\\\\.(?:key|pem|p12|pfx|jks|keystore)\")}$)`,\n // .env, .env.* — except templates whose name ends in .example/.sample/.template/.dist\n `(?!(?:.*/)?${ci(\"\\\\.env\")}(?!(?:\\\\.[^/]*)?\\\\.(?:${ci(\"example\")}|${ci(\"sample\")}|${ci(\"template\")}|${ci(\"dist\")})$)(?:\\\\.[^/]*)?$)`,\n named(\"\\\\.envrc\"),\n // Credentials outside the workspace that an agent can reach by absolute or ~ path,\n // and their directories as a whole (`cp -r ~/.ssh`, `grep -r x ~/.aws`).\n `(?!(?:.*/)?${ci(\"\\\\.ssh\")}(?:$|/(?!.*${ci(\"\\\\.pub\")}$)(?!${ci(\"known_hosts\")}$)(?!${ci(\"config\")}$)))`,\n `(?!(?:.*/)?${ci(\"\\\\.aws\")}(?:$|/(?!${ci(\"config\")}$)))`,\n named(\"\\\\.npmrc\"), named(\"\\\\.pypirc\"), named(\"\\\\.netrc\"), named(\"_netrc\"), named(\"\\\\.git-credentials\"),\n dir(\"\\\\.kube\"), named(\"\\\\.kube/config\"), dir(\"\\\\.docker\"), named(\"\\\\.docker/config\\\\.json\"),\n under(\"\\\\.config/gcloud\"), under(\"\\\\.azure\"), under(\"\\\\.gnupg\"),\n dir(\"\\\\.config/gh\"), named(\"\\\\.config/gh/hosts\\\\.yml\"), named(\"\\\\.claude/\\\\.credentials\\\\.json\"),\n].join(\"\") + \".+\";\n\n// Destructive programs, POSIX and Windows. The mapper records the program as typed,\n// so the pattern accepts any case and an executable suffix (`RM.exe`, `Remove-Item`).\nexport const DESTRUCTIVE = [\n \"rm\", \"sudo\", \"doas\", \"shutdown\", \"reboot\", \"halt\", \"poweroff\", \"mkfs\", \"dd\", \"shred\", \"truncate\", \"unlink\", \"wipe\", \"srm\",\n \"del\", \"rd\", \"rmdir\", \"erase\", \"deltree\", \"format\", \"diskpart\", \"remove-item\", \"ri\", \"clear-content\", \"clc\", \"stop-computer\", \"restart-computer\",\n];\nconst SAFE_SHELL = `^(?!(?:${DESTRUCTIVE.map(ci).join(\"|\")})(?:${ci(\"\\\\.(?:exe|cmd|bat|com|ps1)\")})?$).+`;\n\n// A push destination the starter policy refuses: main, master, release/*, the\n// \"every branch\" flags (`--all`, `--mirror`, `--branches`) and a push whose\n// destination the mapper could not read (`--unknown`: a git alias, a configured push\n// refspec, `send-pack`), in any case. `--tags` alone pushes only tags and is allowed.\nconst SAFE_REF = `^(?!(?:${ci(\"main\")}|${ci(\"master\")})$)(?!${ci(\"release\")}/)(?!-(?!-${ci(\"tags\")}$)).+`;\n\n// Patterns written by earlier starter policies (0.3–0.5), upgraded in memory when a\n// policy on disk still carries them verbatim. An operator's own edits never match\n// these strings and are left untouched.\nconst LEGACY_STARTER_PATTERNS: Record<string, string> = {\n [PROTECTED_WRITE_PREV]: PROTECTED_WRITE,\n \"^(?!(?:main|master)$)(?!release/).+\": SAFE_REF,\n \"^(?!(?:rm|sudo|shutdown|reboot|mkfs|dd|del|rd|rmdir|erase|deltree|format|Remove-Item|ri)$).+\": SAFE_SHELL,\n \"^(?!(?:rm|sudo|shutdown|reboot|mkfs|dd)$).+\": SAFE_SHELL,\n \"^(?!(?:.*/)?\\\\.scopebond/)(?!(?:.*/)?\\\\.claude/settings)(?!(?:.*/)?\\\\.cursor/hooks)(?!(?:.*/)?\\\\.codex/(?:hooks\\\\.json|config\\\\.toml)$)(?!(?:.*/)?\\\\.git/hooks/)(?!(?:.*/)?\\\\.github/workflows/)(?!(?:.*/)?\\\\.github/actions/)(?!(?:.*/)?\\\\.gitlab-ci\\\\.yml$)(?!(?:.*/)?\\\\.circleci/)(?!(?:.*/)?azure-pipelines\\\\.yml$)(?!(?:.*/)?Jenkinsfile$).+\": PROTECTED_WRITE,\n \"^(?!(?:.*/)?\\\\.scopebond/)(?!(?:.*/)?\\\\.claude/settings)(?!(?:.*/)?\\\\.cursor/hooks)(?!(?:.*/)?\\\\.git/hooks/)(?!(?:.*/)?\\\\.github/workflows/)(?!(?:.*/)?\\\\.github/actions/)(?!(?:.*/)?\\\\.gitlab-ci\\\\.yml$)(?!(?:.*/)?\\\\.circleci/)(?!(?:.*/)?azure-pipelines\\\\.yml$)(?!(?:.*/)?Jenkinsfile$).+\": PROTECTED_WRITE,\n \"^(?!(?:.*/)?\\\\.scopebond/)(?!(?:.*/)?\\\\.claude/settings)(?!(?:.*/)?\\\\.cursor/hooks)(?!(?:.*/)?\\\\.git/hooks/).+\": PROTECTED_WRITE,\n \"^(?!(?:.*/)?\\\\.scopebond/)(?!.*\\\\.key$)(?!(?:.*/)?\\\\.env(?:\\\\.(?!example$|sample$|template$)[^/]*)?$).+\": PROTECTED_READ,\n \"^(?!(?:.*/)?\\\\.scopebond/)(?!.*\\\\.key$).+\": PROTECTED_READ,\n};\n\n/** Upgrade the starter-policy patterns an older hook wrote, in memory, so a user who\n * installed an earlier version gets the current protections without re-running init.\n * Only exact legacy strings are replaced; any other pattern is the operator's own. */\nexport function upgradeStarterPolicy<T>(policy: T): T {\n const p = policy as { clauses?: Array<{ param_bounds?: Record<string, { pattern?: string }> }> };\n for (const clause of p?.clauses ?? []) {\n for (const bound of Object.values(clause?.param_bounds ?? {})) {\n if (bound && typeof bound.pattern === \"string\" && LEGACY_STARTER_PATTERNS[bound.pattern]) bound.pattern = LEGACY_STARTER_PATTERNS[bound.pattern];\n }\n }\n return policy;\n}\n\n/** The default starter policy for a coding agent: protect release branches, deny\n * destructive programs, allow workspace file access except the hook's own config\n * and keys, and trust only the enrolled machine key. Every threshold is the\n * operator's to edit. */\nexport function starterPolicy(agentKid: string): Record<string, unknown> {\n return {\n vocabulary_version: \"1.0\", policy_id: \"coding-agent\", version: 1,\n clauses: [\n {\n id: \"protect-branches\", type: \"action_allowlist\", mode: \"enforce\", action_types: [\"git.push\"],\n param_bounds: { ref: { pattern: SAFE_REF } },\n description: \"Deny pushes to main, master and release/* (any case, any refspec spelling), pushes of every branch at once (--all, --mirror) and pushes whose destination cannot be read from the command (a git alias, a configured push refspec, send-pack). A tags-only push (--tags) is allowed.\",\n },\n {\n id: \"safe-shell\", type: \"action_allowlist\", mode: \"enforce\", action_types: [\"shell.exec\"],\n param_bounds: { program: { pattern: SAFE_SHELL } },\n description: \"Deny destructive programs — POSIX (rm, sudo, doas, shutdown, reboot, mkfs, dd, shred, truncate, unlink, wipe) and Windows/PowerShell (del, rd, rmdir, erase, deltree, format, diskpart, Remove-Item, Clear-Content) — in any case and with or without .exe. An empty program (a command that could not be parsed, or whose program is only known at run time: $VAR, $(…), eval of a variable) is denied. Argument-shaped deletion (find -delete, git clean) is not a program name and is not covered here.\",\n },\n {\n id: \"protect-write\", type: \"action_allowlist\", mode: \"enforce\", action_types: [\"file.write\"],\n param_bounds: { path: { pattern: PROTECTED_WRITE } },\n description: \"Allow workspace writes, but never to the hook's policy/keys, Claude Code settings, hooks and agents, Cursor or Codex hook settings, .mcp.json and .cursor/mcp.json, git hooks (.git/hooks, .githooks) and git config, Husky hooks, or CI config (.github/workflows, .github/actions, .gitlab-ci.yml/.yaml, .circleci, azure-pipelines, bitbucket-pipelines.yml, .travis.yml, .drone.yml, cloudbuild, .buildkite, Jenkinsfile). Case-insensitive.\",\n },\n {\n id: \"protect-read\", type: \"action_allowlist\", mode: \"enforce\", action_types: [\"file.read\"],\n param_bounds: { path: { pattern: PROTECTED_READ } },\n description: \"Allow workspace reads, but never signing keys and key containers (*.key, *.pem, *.p12, *.pfx, *.jks), environment secret files (.env, .env.*, .envrc — except names ending in .example/.sample/.template/.dist), SSH private keys and the .ssh directory, cloud/registry/git credentials (.aws except .aws/config, .npmrc, .pypirc, .netrc, .git-credentials, .kube/config, .docker/config.json, gcloud, Azure, GnuPG, the GitHub CLI's hosts.yml, Claude Code's .credentials.json) or the hook's own .scopebond directory. Case-insensitive.\",\n },\n {\n id: \"observe-net-mcp\", type: \"action_allowlist\", mode: \"monitor\",\n action_types: [\"net.fetch\", \"mcp.tool.call\"],\n description: \"Observe network fetches and MCP tool calls (recorded, not blocked) — add bounds to enforce.\",\n },\n { id: \"keys\", type: \"key_policy\", active_keys: [agentKid], description: \"Only the enrolled machine key may sign.\" },\n ],\n };\n}\n\n/** Build the runtime. Throws on any setup failure (unparseable policy, missing\n * key, unavailable store) — the CLI turns that into a fail-closed deny. */\nexport function createHookRuntime(config: RuntimeConfig) {\n const policy = upgradeStarterPolicy(JSON.parse(readFileSync(config.policyPath, \"utf8\")));\n const agent = createSigner({ privateKeyPem: readFileSync(config.keyPath, \"utf8\") });\n const keys = new StaticPrincipalKeyRegistry([\n { kid: agent.kid, publicKeyPem: agent.publicKeyPem, purposes: [\"agent\"], status: \"active\" },\n ]);\n const { attester } = loadOrCreateAttester({ file: config.attesterPath });\n // When the project has a readable rule set, a denial names the command that edits it\n // rather than the generated file.\n const rulesRemedy = existsSync(join(dirname(config.policyPath), RULES_FILE))\n ? `run \\`${cliCommand(\"rules\")}\\` to see the limits in plain terms, or edit ${join(dirname(config.policyPath), RULES_FILE)}`\n : undefined;\n const { store: baseStore } = openReceiptStore({ db: config.dbPath });\n // When connected, mirror every stored receipt to the hosted portal through a\n // durable outbox. The wrapped store's decision is unchanged; export is best-effort.\n let store = baseStore;\n let exporter: CloudExporter | undefined;\n let outbox: { close(): void } | undefined;\n if (config.cloud) {\n const attached = attachExporter(config.dbPath + \".cloud-outbox.db\", config.cloud.connection, baseStore, config.cloud.fetch);\n store = attached.store;\n exporter = attached.exporter;\n outbox = attached.outbox;\n }\n const scopeRoots = loadRules(dirname(config.policyPath))?.allowed_roots ?? [];\n // The dispatch boundary is checked once per tool call, after every intent has been allowed, so the\n // gateway's own per-intent hook only reports what the runtime already decided for this call.\n const boundary = openDispatchGuard(dirname(config.policyPath));\n let boundaryVerdict: DispatchDecision | null = null;\n const gatewayGuard: DispatchGuard = { authorize: async () => boundaryVerdict ?? { allow: true, reason: \"ok\", consumed_approvals: [], budgets: [] } };\n const gateway = createGateway({ policy, authentication: { keys }, attester, store, mode: \"check_only\", dispatchGuard: gatewayGuard });\n\n return {\n gateway,\n agentKid: agent.kid,\n exporter,\n /** Deliver queued receipts to Cloud with a bounded timeout, then it is safe to\n * exit. Undelivered receipts persist in the durable outbox for the next run. */\n async flush(): Promise<void> {\n if (exporter) await flushBounded(exporter, config.cloud?.flushTimeoutMs);\n },\n /** Release the SQLite handles. The hook is a per-tool-call process, and a writer that\n * exits without closing leaves its write-ahead log on disk for the next process to\n * extend — measured at ~11 KiB of WAL per receipt against ~1.7 KiB when closed, so a\n * busy session was writing tens of megabytes of pure overhead into the user's project.\n * Always safe to call, and every exit path should. */\n close(): void {\n try { baseStore.close?.(); } catch { /* the decision is already recorded */ }\n try { outbox?.close(); } catch { /* best effort */ }\n try { boundary?.close(); } catch { /* best effort */ }\n },\n /** Decide one mapped action, recording a receipt either way. */\n async evaluateOne(mapped: Mapped): Promise<Decision> {\n const signed = agent.sign(mapped.intent);\n if (!mapped.evaluated && !config.strict) {\n // Unknown tool or unparseable command, non-strict: observe without\n // evaluating — grants nothing (D30).\n const { receipt } = await gateway.observeAction({ intent: signed.intent, authorization: signed.authorization });\n return { decision: \"not_evaluated\", reason: `no policy applies to ${mapped.intent.action_type}`, receipt };\n }\n // Evaluated actions, and (in strict mode) unmapped tool.<name>/opaque commands,\n // go through policy — a closed allowlist denies an unlisted action.\n const result = await gateway.handleAction({ intent: signed.intent, authorization: signed.authorization });\n if (result.allowed) return { decision: \"allow\", reason: result.reason, receipt: result.receipt };\n // A deny is the one message the user and their agent actually read, so it is\n // composed from the deciding clause's own words rather than the engine's\n // internal reason (\"param ref fails pattern\").\n const clauseId = result.verdict?.clause_id ?? null;\n return {\n decision: \"deny\",\n reason: explainDeny({\n policy, clauseId, detail: result.reason,\n intent: signed.intent as ExplainIntent, policyPath: config.policyPath,\n postHoc: mapped.postHoc,\n // Point at the editable surface when there is one. `policy.json` is compiled\n // from `rules.json`, so telling someone to hand-edit it invites a change the\n // next `rules` run would overwrite.\n remedy: rulesRemedy,\n }),\n clauseId,\n receipt: result.receipt,\n };\n },\n /** Decide a whole tool call. A shell call decomposes into several simple\n * commands; every one is recorded, and a single deny denies the call. */\n async evaluate(mapped: Mapped | Mapped[], options: { groupKey?: string } = {}): Promise<Decision> {\n const raw = Array.isArray(mapped) ? mapped : [mapped];\n if (raw.length === 0) return { decision: \"not_evaluated\", reason: \"no action\", receipts: [] };\n // Every intent of one tool call carries one parent group id, so the receipts of a\n // decomposed call (a command, its file reads and writes, a rename destination)\n // link to each other and count once as an action. It is part of the signed\n // intent, so it is authenticated by the same signature as the rest.\n const scoped = scopeRoots.length ? applyRootScope(raw, { cwd: config.cwd ?? process.cwd(), roots: scopeRoots }) : raw;\n const list = withActionGroup(scoped, actionGroupId(options.groupKey));\n const receipts: unknown[] = [];\n const dispatched: NonNullable<Decision[\"dispatched\"]> = [];\n let allow: Decision | null = null;\n let notEvaluated: Decision | null = null;\n for (const m of list) {\n const d = await this.evaluateOne(m);\n if (d.receipt !== undefined) receipts.push(d.receipt);\n dispatched.push({ action: { action_type: m.intent.action_type, params: m.intent.params as Record<string, unknown> }, ...(d.receipt !== undefined ? { receipt: d.receipt } : {}) });\n if (d.decision === \"deny\") return { ...d, receipts, dispatched }; // any deny denies the call\n if (d.decision === \"allow\" && !allow) allow = d;\n if (d.decision === \"not_evaluated\" && !notEvaluated) notEvaluated = d;\n }\n // No deny: allow if any command was evaluated-and-allowed, else not_evaluated.\n const chosen = allow ?? notEvaluated!;\n if (boundary) {\n // Immediately before permitted dispatch: approvals are consumed and the budget slot is reserved\n // atomically, once for the whole parent action, or nothing is spent and the call is denied.\n const group = String(list[0]!.intent.params[ACTION_GROUP_PARAM]);\n const delegation = process.env[DELEGATION_ENV] ?? \"\";\n const verdict = await boundary.authorize({\n actor: agent.kid, action_group: group, policy_digest: gateway.policyHash,\n intents: list.map((m) => dispatchIntentOf(m.intent as never)),\n ...(delegation !== \"\" ? { delegation_id: delegation } : {}),\n });\n if (!verdict.allow) {\n // Record the refusal as its own denied receipt, then deny the call.\n boundaryVerdict = verdict;\n try {\n const last = list[list.length - 1]!;\n const signed = agent.sign(last.intent);\n const result = await gateway.handleAction({ intent: signed.intent, authorization: signed.authorization });\n if (result.receipt !== undefined) receipts.push(result.receipt);\n } finally { boundaryVerdict = null; }\n return { decision: \"deny\", reason: `Scopebond blocked this before it ran: ${verdict.reason}${verdict.detail ? ` (${verdict.detail})` : \"\"}`, receipts, dispatched, dispatch: verdict };\n }\n return { ...chosen, receipts, dispatched, dispatch: verdict };\n }\n return { ...chosen, receipts, dispatched };\n },\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scopebond/hook",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Scopebond hook for Claude Code, Cursor, and OpenAI Codex — checks coding-agent actions against policy before they run and records a signed receipt locally.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Avouro LLC",
@@ -43,8 +43,8 @@
43
43
  ],
44
44
  "dependencies": {
45
45
  "@scopebond/policy-schema": "^0.5.0",
46
- "@scopebond/sdk": "^0.1.3",
47
- "@scopebond/gateway": "^0.9.0"
46
+ "@scopebond/gateway": "^0.10.0",
47
+ "@scopebond/sdk": "^0.1.3"
48
48
  },
49
49
  "publishConfig": {
50
50
  "access": "public"