@scopebond/hook 0.8.1 → 0.10.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.
Files changed (110) hide show
  1. package/README.md +239 -0
  2. package/dist/budget-load.d.ts +68 -0
  3. package/dist/budget-load.d.ts.map +1 -0
  4. package/dist/budget-load.js +164 -0
  5. package/dist/budget-load.js.map +1 -0
  6. package/dist/capabilities.d.ts +103 -0
  7. package/dist/capabilities.d.ts.map +1 -0
  8. package/dist/capabilities.js +212 -0
  9. package/dist/capabilities.js.map +1 -0
  10. package/dist/classify.d.ts +17 -0
  11. package/dist/classify.d.ts.map +1 -0
  12. package/dist/classify.js +78 -0
  13. package/dist/classify.js.map +1 -0
  14. package/dist/cli.d.ts.map +1 -1
  15. package/dist/cli.js +585 -13
  16. package/dist/cli.js.map +1 -1
  17. package/dist/cloud.d.ts +8 -0
  18. package/dist/cloud.d.ts.map +1 -1
  19. package/dist/cloud.js.map +1 -1
  20. package/dist/dispatch-cli.d.ts +2 -0
  21. package/dist/dispatch-cli.d.ts.map +1 -0
  22. package/dist/dispatch-cli.js +128 -0
  23. package/dist/dispatch-cli.js.map +1 -0
  24. package/dist/explain.d.ts.map +1 -1
  25. package/dist/explain.js +2 -1
  26. package/dist/explain.js.map +1 -1
  27. package/dist/group.d.ts +12 -0
  28. package/dist/group.d.ts.map +1 -0
  29. package/dist/group.js +55 -0
  30. package/dist/group.js.map +1 -0
  31. package/dist/index.d.ts +29 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +19 -0
  34. package/dist/index.js.map +1 -1
  35. package/dist/install.d.ts +10 -0
  36. package/dist/install.d.ts.map +1 -1
  37. package/dist/install.js +56 -0
  38. package/dist/install.js.map +1 -1
  39. package/dist/managed.d.ts +69 -0
  40. package/dist/managed.d.ts.map +1 -0
  41. package/dist/managed.js +184 -0
  42. package/dist/managed.js.map +1 -0
  43. package/dist/map.d.ts +4 -0
  44. package/dist/map.d.ts.map +1 -1
  45. package/dist/map.js +29 -1
  46. package/dist/map.js.map +1 -1
  47. package/dist/obs-emitter.d.ts +132 -0
  48. package/dist/obs-emitter.d.ts.map +1 -0
  49. package/dist/obs-emitter.js +415 -0
  50. package/dist/obs-emitter.js.map +1 -0
  51. package/dist/obs-store.d.ts +160 -0
  52. package/dist/obs-store.d.ts.map +1 -0
  53. package/dist/obs-store.js +367 -0
  54. package/dist/obs-store.js.map +1 -0
  55. package/dist/obs-upload.d.ts +24 -0
  56. package/dist/obs-upload.d.ts.map +1 -0
  57. package/dist/obs-upload.js +231 -0
  58. package/dist/obs-upload.js.map +1 -0
  59. package/dist/observation.d.ts +232 -0
  60. package/dist/observation.d.ts.map +1 -0
  61. package/dist/observation.js +308 -0
  62. package/dist/observation.js.map +1 -0
  63. package/dist/paths.d.ts +15 -0
  64. package/dist/paths.d.ts.map +1 -0
  65. package/dist/paths.js +79 -0
  66. package/dist/paths.js.map +1 -0
  67. package/dist/policy-load.d.ts +60 -0
  68. package/dist/policy-load.d.ts.map +1 -0
  69. package/dist/policy-load.js +151 -0
  70. package/dist/policy-load.js.map +1 -0
  71. package/dist/policy-sync.d.ts +45 -0
  72. package/dist/policy-sync.d.ts.map +1 -0
  73. package/dist/policy-sync.js +171 -0
  74. package/dist/policy-sync.js.map +1 -0
  75. package/dist/proof.d.ts +30 -0
  76. package/dist/proof.d.ts.map +1 -0
  77. package/dist/proof.js +186 -0
  78. package/dist/proof.js.map +1 -0
  79. package/dist/rules.d.ts +20 -0
  80. package/dist/rules.d.ts.map +1 -1
  81. package/dist/rules.js +50 -0
  82. package/dist/rules.js.map +1 -1
  83. package/dist/runtime.d.ts +21 -1
  84. package/dist/runtime.d.ts.map +1 -1
  85. package/dist/runtime.js +77 -10
  86. package/dist/runtime.js.map +1 -1
  87. package/dist/scan.d.ts +7 -0
  88. package/dist/scan.d.ts.map +1 -0
  89. package/dist/scan.js +38 -0
  90. package/dist/scan.js.map +1 -0
  91. package/dist/shell.d.ts.map +1 -1
  92. package/dist/shell.js +12 -3
  93. package/dist/shell.js.map +1 -1
  94. package/dist/sql-classify.d.ts +11 -0
  95. package/dist/sql-classify.d.ts.map +1 -0
  96. package/dist/sql-classify.js +251 -0
  97. package/dist/sql-classify.js.map +1 -0
  98. package/dist/typed-infra.d.ts +73 -0
  99. package/dist/typed-infra.d.ts.map +1 -0
  100. package/dist/typed-infra.js +758 -0
  101. package/dist/typed-infra.js.map +1 -0
  102. package/dist/typed-ops.d.ts +140 -0
  103. package/dist/typed-ops.d.ts.map +1 -0
  104. package/dist/typed-ops.js +549 -0
  105. package/dist/typed-ops.js.map +1 -0
  106. package/dist/vectors.d.ts +40 -0
  107. package/dist/vectors.d.ts.map +1 -0
  108. package/dist/vectors.js +219 -0
  109. package/dist/vectors.js.map +1 -0
  110. package/package.json +5 -5
package/dist/runtime.js CHANGED
@@ -9,8 +9,12 @@ import { loadOrCreateAttester, openReceiptStore } from "@scopebond/gateway/node"
9
9
  import { createSigner } from "@scopebond/sdk";
10
10
  import { attachExporter, flushBounded } from "./cloud.js";
11
11
  import { explainDeny } from "./explain.js";
12
- import { RULES_FILE } from "./rules.js";
12
+ import { RULES_FILE, loadRules } from "./rules.js";
13
+ import { applyRootScope } from "./paths.js";
14
+ import { withActionGroup, actionGroupId, ACTION_GROUP_PARAM } from "./group.js";
13
15
  import { cliCommand } from "./version.js";
16
+ import { openDispatchGuard, DELEGATION_ENV } from "@scopebond/gateway/node";
17
+ import { dispatchIntentOf } from "@scopebond/gateway";
14
18
  // The hook's own config and keys must be off-limits to the agent it governs:
15
19
  // otherwise the agent could rewrite its policy or read the signing keys and the
16
20
  // receipts stop meaning anything. These patterns are "allow if the path does NOT
@@ -24,13 +28,30 @@ export const ci = (s) => s.replace(/[A-Za-z]/g, (c) => `[${c.toLowerCase()}${c.t
24
28
  export const under = (dir) => `(?!(?:.*/)?${ci(dir)}(?:/|$))`; // dir itself or anything inside it
25
29
  export const named = (file) => `(?!(?:.*/)?${ci(file)}$)`; // exactly this file name
26
30
  export const dir = (d) => `(?!(?:.*/)?${ci(d)}/?$)`; // the directory itself (a recursive read or copy)
27
- const PROTECTED_WRITE = "^" + [
31
+ // The protected-write set, in two typed groups the catalog classifies separately:
32
+ // guardrail/hook configuration (C02) and CI configuration (H03).
33
+ const GUARDRAIL_WRITE_PREV = [
28
34
  under("\\.scopebond"), `(?!(?:.*/)?${ci("\\.claude/settings")})`, under("\\.claude/hooks"), under("\\.claude/agents"),
29
35
  `(?!(?:.*/)?${ci("\\.cursor/hooks")})`, named("\\.codex/hooks\\.json"), named("\\.codex/config\\.toml"), named("\\.mcp\\.json"),
30
36
  under("\\.git/hooks"), named("\\.git/config"), under("\\.husky"),
37
+ ];
38
+ const CI_WRITE_PREV = [
31
39
  under("\\.github/workflows"), under("\\.github/actions"), named("\\.gitlab-ci\\.yml"), named("\\.gitlab-ci\\.yaml"), under("\\.circleci"),
32
40
  named("azure-pipelines\\.yml"), named("Jenkinsfile"),
33
- ].join("") + ".+";
41
+ ];
42
+ const GUARDRAIL_WRITE = [...GUARDRAIL_WRITE_PREV, named("\\.cursor/mcp\\.json"), under("\\.githooks")];
43
+ const CI_WRITE = [
44
+ ...CI_WRITE_PREV,
45
+ named("azure-pipelines\\.yaml"), named("bitbucket-pipelines\\.yml"), named("\\.travis\\.yml"), named("\\.drone\\.yml"),
46
+ named("cloudbuild\\.yaml"), named("cloudbuild\\.yml"), under("\\.buildkite"),
47
+ ];
48
+ // What 0.8 compiled, kept so an installed policy that still carries it verbatim is
49
+ // upgraded in memory (see LEGACY_STARTER_PATTERNS).
50
+ const PROTECTED_WRITE_PREV = "^" + [...GUARDRAIL_WRITE_PREV, ...CI_WRITE_PREV].join("") + ".+";
51
+ const PROTECTED_WRITE = "^" + [...GUARDRAIL_WRITE, ...CI_WRITE].join("") + ".+";
52
+ /** The write protection that is always on, whoever manages the rules: the hook's own settings and those of the agents it
53
+ * guards. A workspace can relax CI-configuration writes; it can never relax these. */
54
+ export const GUARDRAIL_WRITE_PATTERN = "^" + GUARDRAIL_WRITE.join("") + ".+";
34
55
  const PROTECTED_READ = "^" + [
35
56
  under("\\.scopebond"),
36
57
  `(?!.*${ci("\\.(?:key|pem|p12|pfx|jks|keystore)")}$)`,
@@ -62,6 +83,7 @@ const SAFE_REF = `^(?!(?:${ci("main")}|${ci("master")})$)(?!${ci("release")}/)(?
62
83
  // policy on disk still carries them verbatim. An operator's own edits never match
63
84
  // these strings and are left untouched.
64
85
  const LEGACY_STARTER_PATTERNS = {
86
+ [PROTECTED_WRITE_PREV]: PROTECTED_WRITE,
65
87
  "^(?!(?:main|master)$)(?!release/).+": SAFE_REF,
66
88
  "^(?!(?:rm|sudo|shutdown|reboot|mkfs|dd|del|rd|rmdir|erase|deltree|format|Remove-Item|ri)$).+": SAFE_SHELL,
67
89
  "^(?!(?:rm|sudo|shutdown|reboot|mkfs|dd)$).+": SAFE_SHELL,
@@ -105,7 +127,7 @@ export function starterPolicy(agentKid) {
105
127
  {
106
128
  id: "protect-write", type: "action_allowlist", mode: "enforce", action_types: ["file.write"],
107
129
  param_bounds: { path: { pattern: PROTECTED_WRITE } },
108
- 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, git hooks and git config, Husky hooks, or CI config (.github/workflows, .github/actions, .gitlab-ci.yml/.yaml, .circleci, azure-pipelines.yml, Jenkinsfile). Case-insensitive.",
130
+ 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.",
109
131
  },
110
132
  {
111
133
  id: "protect-read", type: "action_allowlist", mode: "enforce", action_types: ["file.read"],
@@ -147,7 +169,13 @@ export function createHookRuntime(config) {
147
169
  exporter = attached.exporter;
148
170
  outbox = attached.outbox;
149
171
  }
150
- const gateway = createGateway({ policy, authentication: { keys }, attester, store, mode: "check_only" });
172
+ const scopeRoots = loadRules(dirname(config.policyPath))?.allowed_roots ?? [];
173
+ // The dispatch boundary is checked once per tool call, after every intent has been allowed, so the
174
+ // gateway's own per-intent hook only reports what the runtime already decided for this call.
175
+ const boundary = openDispatchGuard(dirname(config.policyPath));
176
+ let boundaryVerdict = null;
177
+ const gatewayGuard = { authorize: async () => boundaryVerdict ?? { allow: true, reason: "ok", consumed_approvals: [], budgets: [] } };
178
+ const gateway = createGateway({ policy, authentication: { keys }, attester, store, mode: "check_only", dispatchGuard: gatewayGuard });
151
179
  return {
152
180
  gateway,
153
181
  agentKid: agent.kid,
@@ -172,6 +200,10 @@ export function createHookRuntime(config) {
172
200
  outbox?.close();
173
201
  }
174
202
  catch { /* best effort */ }
203
+ try {
204
+ boundary?.close();
205
+ }
206
+ catch { /* best effort */ }
175
207
  },
176
208
  /** Decide one mapped action, recording a receipt either way. */
177
209
  async evaluateOne(mapped) {
@@ -208,19 +240,27 @@ export function createHookRuntime(config) {
208
240
  },
209
241
  /** Decide a whole tool call. A shell call decomposes into several simple
210
242
  * commands; every one is recorded, and a single deny denies the call. */
211
- async evaluate(mapped) {
212
- const list = Array.isArray(mapped) ? mapped : [mapped];
213
- if (list.length === 0)
243
+ async evaluate(mapped, options = {}) {
244
+ const raw = Array.isArray(mapped) ? mapped : [mapped];
245
+ if (raw.length === 0)
214
246
  return { decision: "not_evaluated", reason: "no action", receipts: [] };
247
+ // Every intent of one tool call carries one parent group id, so the receipts of a
248
+ // decomposed call (a command, its file reads and writes, a rename destination)
249
+ // link to each other and count once as an action. It is part of the signed
250
+ // intent, so it is authenticated by the same signature as the rest.
251
+ const scoped = scopeRoots.length ? applyRootScope(raw, { cwd: config.cwd ?? process.cwd(), roots: scopeRoots }) : raw;
252
+ const list = withActionGroup(scoped, actionGroupId(options.groupKey));
215
253
  const receipts = [];
254
+ const dispatched = [];
216
255
  let allow = null;
217
256
  let notEvaluated = null;
218
257
  for (const m of list) {
219
258
  const d = await this.evaluateOne(m);
220
259
  if (d.receipt !== undefined)
221
260
  receipts.push(d.receipt);
261
+ dispatched.push({ action: { action_type: m.intent.action_type, params: m.intent.params }, ...(d.receipt !== undefined ? { receipt: d.receipt } : {}) });
222
262
  if (d.decision === "deny")
223
- return { ...d, receipts }; // any deny denies the call
263
+ return { ...d, receipts, dispatched }; // any deny denies the call
224
264
  if (d.decision === "allow" && !allow)
225
265
  allow = d;
226
266
  if (d.decision === "not_evaluated" && !notEvaluated)
@@ -228,7 +268,34 @@ export function createHookRuntime(config) {
228
268
  }
229
269
  // No deny: allow if any command was evaluated-and-allowed, else not_evaluated.
230
270
  const chosen = allow ?? notEvaluated;
231
- return { ...chosen, receipts };
271
+ if (boundary) {
272
+ // Immediately before permitted dispatch: approvals are consumed and the budget slot is reserved
273
+ // atomically, once for the whole parent action, or nothing is spent and the call is denied.
274
+ const group = String(list[0].intent.params[ACTION_GROUP_PARAM]);
275
+ const delegation = process.env[DELEGATION_ENV] ?? "";
276
+ const verdict = await boundary.authorize({
277
+ actor: agent.kid, action_group: group, policy_digest: gateway.policyHash,
278
+ intents: list.map((m) => dispatchIntentOf(m.intent)),
279
+ ...(delegation !== "" ? { delegation_id: delegation } : {}),
280
+ });
281
+ if (!verdict.allow) {
282
+ // Record the refusal as its own denied receipt, then deny the call.
283
+ boundaryVerdict = verdict;
284
+ try {
285
+ const last = list[list.length - 1];
286
+ const signed = agent.sign(last.intent);
287
+ const result = await gateway.handleAction({ intent: signed.intent, authorization: signed.authorization });
288
+ if (result.receipt !== undefined)
289
+ receipts.push(result.receipt);
290
+ }
291
+ finally {
292
+ boundaryVerdict = null;
293
+ }
294
+ return { decision: "deny", reason: `Scopebond blocked this before it ran: ${verdict.reason}${verdict.detail ? ` (${verdict.detail})` : ""}`, receipts, dispatched, dispatch: verdict };
295
+ }
296
+ return { ...chosen, receipts, dispatched, dispatch: verdict };
297
+ }
298
+ return { ...chosen, receipts, dispatched };
232
299
  },
233
300
  };
234
301
  }
@@ -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,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AA2B1C,6EAA6E;AAC7E,gFAAgF;AAChF,iFAAiF;AACjF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,iFAAiF;AACjF,gFAAgF;AAChF,oFAAoF;AACpF,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAS,EAAU,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;AACjH,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,GAAW,EAAU,EAAE,CAAC,cAAc,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,CAAI,mCAAmC;AACrH,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC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CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;YACvD,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC;YAC/F,MAAM,QAAQ,GAAc,EAAE,CAAC;YAC/B,IAAI,KAAK,GAAoB,IAAI,CAAC;YAClC,IAAI,YAAY,GAAoB,IAAI,CAAC;YACzC,KAAK,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;gBACrB,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;gBACpC,IAAI,CAAC,CAAC,OAAO,KAAK,SAAS;oBAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;gBACtD,IAAI,CAAC,CAAC,QAAQ,KAAK,MAAM;oBAAE,OAAO,EAAE,GAAG,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAY,2BAA2B;gBAC5F,IAAI,CAAC,CAAC,QAAQ,KAAK,OAAO,IAAI,CAAC,KAAK;oBAAE,KAAK,GAAG,CAAC,CAAC;gBAChD,IAAI,CAAC,CAAC,QAAQ,KAAK,eAAe,IAAI,CAAC,YAAY;oBAAE,YAAY,GAAG,CAAC,CAAC;YACxE,CAAC;YACD,+EAA+E;YAC/E,MAAM,MAAM,GAAG,KAAK,IAAI,YAAa,CAAC;YACtC,OAAO,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,CAAC;QACjC,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 } from \"./rules.js\";\nimport { cliCommand } from \"./version.js\";\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 /** 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}\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\nconst PROTECTED_WRITE = \"^\" + [\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 under(\"\\\\.github/workflows\"), under(\"\\\\.github/actions\"), named(\"\\\\.gitlab-ci\\\\.yml\"), named(\"\\\\.gitlab-ci\\\\.yaml\"), under(\"\\\\.circleci\"),\n named(\"azure-pipelines\\\\.yml\"), named(\"Jenkinsfile\"),\n].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 \"^(?!(?: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, git hooks and git config, Husky hooks, or CI config (.github/workflows, .github/actions, .gitlab-ci.yml/.yaml, .circleci, azure-pipelines.yml, 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 gateway = createGateway({ policy, authentication: { keys }, attester, store, mode: \"check_only\" });\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 },\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[]): Promise<Decision> {\n const list = Array.isArray(mapped) ? mapped : [mapped];\n if (list.length === 0) return { decision: \"not_evaluated\", reason: \"no action\", receipts: [] };\n const receipts: unknown[] = [];\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 if (d.decision === \"deny\") return { ...d, receipts }; // 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 return { ...chosen, receipts };\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,MA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,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,EAAE,MAAM,CAAC,aAAa,EAAE,CAAC,CAAC;wBAC1G,IAAI,MAAM,CAAC,OAAO,KAAK,SAAS;4BAAE,QAAQ,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\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/dist/scan.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export interface Scanned {
2
+ positionals: string[];
3
+ flags: Map<string, string | true>;
4
+ }
5
+ export declare function scan(argv: string[], valued: readonly string[]): Scanned;
6
+ export declare const flagValue: (s: Scanned, ...names: string[]) => string | undefined;
7
+ //# sourceMappingURL=scan.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scan.d.ts","sourceRoot":"","sources":["../src/scan.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,OAAO;IAAG,WAAW,EAAE,MAAM,EAAE,CAAC;IAAC,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,CAAA;CAAE;AAErF,wBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAevE;AAED,eAAO,MAAM,SAAS,GAAI,GAAG,OAAO,EAAE,GAAG,OAAO,MAAM,EAAE,KAAG,MAAM,GAAG,SAGnE,CAAC"}
package/dist/scan.js ADDED
@@ -0,0 +1,38 @@
1
+ // Option scanning shared by the typed-operation derivations.
2
+ export function scan(argv, valued) {
3
+ const positionals = [];
4
+ const flags = new Map();
5
+ const takes = new Set(valued);
6
+ for (let i = 0; i < argv.length; i++) {
7
+ const t = argv[i];
8
+ if (t === "--") {
9
+ positionals.push(...argv.slice(i + 1));
10
+ break;
11
+ }
12
+ if (t.startsWith("--") && t.includes("=")) {
13
+ const at = t.indexOf("=");
14
+ flags.set(t.slice(0, at), t.slice(at + 1));
15
+ continue;
16
+ }
17
+ if (t.startsWith("-") && t.length > 1) {
18
+ if (takes.has(t)) {
19
+ flags.set(t, argv[i + 1] ?? "");
20
+ i += 1;
21
+ }
22
+ else
23
+ flags.set(t, true);
24
+ continue;
25
+ }
26
+ positionals.push(t);
27
+ }
28
+ return { positionals, flags };
29
+ }
30
+ export const flagValue = (s, ...names) => {
31
+ for (const n of names) {
32
+ const v = s.flags.get(n);
33
+ if (typeof v === "string" && v !== "")
34
+ return v;
35
+ }
36
+ return undefined;
37
+ };
38
+ //# sourceMappingURL=scan.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scan.js","sourceRoot":"","sources":["../src/scan.ts"],"names":[],"mappings":"AAAA,6DAA6D;AAI7D,MAAM,UAAU,IAAI,CAAC,IAAc,EAAE,MAAyB;IAC5D,MAAM,WAAW,GAAa,EAAE,CAAC;IACjC,MAAM,KAAK,GAAG,IAAI,GAAG,EAAyB,CAAC;IAC/C,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;IAC9B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC;YAAC,WAAW,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,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,CAAC","sourcesContent":["// Option scanning shared by the typed-operation derivations.\n\nexport interface Scanned { positionals: string[]; flags: Map<string, string | true> }\n\nexport function scan(argv: string[], valued: readonly string[]): Scanned {\n const positionals: string[] = [];\n const flags = new Map<string, string | true>();\n const takes = new Set(valued);\n for (let i = 0; i < argv.length; i++) {\n const t = argv[i];\n if (t === \"--\") { positionals.push(...argv.slice(i + 1)); break; }\n if (t.startsWith(\"--\") && t.includes(\"=\")) { const at = t.indexOf(\"=\"); flags.set(t.slice(0, at), t.slice(at + 1)); continue; }\n if (t.startsWith(\"-\") && t.length > 1) {\n if (takes.has(t)) { flags.set(t, argv[i + 1] ?? \"\"); i += 1; } else flags.set(t, true);\n continue;\n }\n positionals.push(t);\n }\n return { positionals, flags };\n}\n\nexport const flagValue = (s: Scanned, ...names: string[]): string | undefined => {\n for (const n of names) { const v = s.flags.get(n); if (typeof v === \"string\" && v !== \"\") return v; }\n return undefined;\n};\n\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../src/shell.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,QAAQ;IACvB,4EAA4E;IAC5E,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,aAAa;IAC5B;8CAC0C;IAC1C,OAAO,EAAE,MAAM,CAAC;IAChB;sFACkF;IAClF,UAAU,EAAE,MAAM,CAAC;IACnB,qEAAqE;IACrE,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,wEAAwE;IACxE,SAAS,EAAE,QAAQ,EAAE,CAAC;IACtB,oEAAoE;IACpE,GAAG,EAAE,MAAM,CAAC;IACZ,wEAAwE;IACxE,MAAM,EAAE,OAAO,CAAC;CACjB;AAED;;;2DAG2D;AAC3D,eAAO,MAAM,YAAY,GAAI,GAAG,MAAM,KAAG,MAC0C,CAAC;AA6dpF;oEACoE;AACpE,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,K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,GAAG,EAAE,MAAM,CAAC;IACZ,wEAAwE;IACxE,MAAM,EAAE,OAAO,CAAC;CACjB;AAED;;;2DAG2D;AAC3D,eAAO,MAAM,YAAY,GAAI,GAAG,MAAM,KAAG,MAC0C,CAAC;AA6dpF;oEACoE;AACpE,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,SAAI,GAAG,aAAa,EAAE,CA6E1E;AAED,uFAAuF;AACvF,MAAM,WAAW,UAAU;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,OAAO,CAAC;IACf;wFACoF;IACpF,GAAG,CAAC,EAAE,OAAO,CAAC;IACd;uFACmF;IACnF,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAED;;sFAEsF;AACtF,wBAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAIxD;AAGD;;mFAEmF;AACnF,wBAAgB,OAAO,CAAC,GAAG,EAAE,aAAa,GAAG;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,GAAG,IAAI,CActG;AAED;;;;4EAI4E;AAC5E,eAAO,MAAM,WAAW,cAAc,CAAC;AAEvC;;;;;;;;;yCASyC;AACzC,wBAAgB,YAAY,CAAC,GAAG,EAAE,aAAa,GAAG;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,UAAU,EAAE,CAAA;CAAE,GAAG,IAAI,CA4DhI"}
package/dist/shell.js CHANGED
@@ -779,9 +779,15 @@ export function decomposeShell(command, depth = 0) {
779
779
  const nested = (script) => { if (script)
780
780
  out.push(...decomposeShell(script, depth + 1)); };
781
781
  if (SHELLS.has(canon)) {
782
- nested(shellScriptArg(argv));
782
+ const script = shellScriptArg(argv);
783
+ nested(script);
784
+ // A shell given neither a -c script nor a script file reads its program from
785
+ // standard input (`curl … | sh`, `sh -s`): the text that will run is not in the
786
+ // command, so it is opaque rather than safe.
787
+ if (script === null && !argv.some((a) => !a.startsWith("-")) && !argv.some((a) => /^--(?:version|help)$/.test(a)))
788
+ out.push(...opaque(seg));
783
789
  }
784
- else if (canon === "eval") {
790
+ else if (canon === "eval" || canon === "iex" || canon === "invoke-expression") {
785
791
  nested(argv.join(" "));
786
792
  }
787
793
  else if (canon === "trap") {
@@ -975,7 +981,10 @@ export function parseGitPush(cmd) {
975
981
  // `src:dst` pushes to dst; `:dst` deletes dst; `src:` has no destination, so src.
976
982
  const isDelete = del || (colon >= 0 && s.slice(0, colon) === "");
977
983
  const dst = colon >= 0 ? (s.slice(colon + 1) || s.slice(0, colon)) : s;
978
- targets.push({ ref: canonRef(dst.replace(/^\+/, "")), force: f || dst.startsWith("+"), ...(isDelete ? { del: true } : {}) });
984
+ // A destination made of a variable, substitution or glob is only known at run time:
985
+ // it is an unresolved destination, never a safe one.
986
+ const unresolved = /[$`*?[\]{}]/.test(dst);
987
+ targets.push({ ref: unresolved ? UNKNOWN_REF : canonRef(dst.replace(/^\+/, "")), force: f || dst.startsWith("+"), ...(isDelete ? { del: true } : {}) });
979
988
  }
980
989
  if (repo !== undefined && positional.length <= 1 && !everything && !tags)
981
990
  targets.push({ ref: undefined, force, ...(del ? { del: true } : {}) });