@scopebond/hook 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/init.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"init.js","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,iFAAiF;AACjF,uCAAuC;AAEvC,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,MAAM,UAAU,QAAQ,CAAC,GAAW,EAAE,OAA4B,EAAE;IAClE,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACpC,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;IACvC,MAAM,YAAY,GAAG,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;IAC/C,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,EAAE,aAAa,CAAC,CAAC;IAC5C,kFAAkF;IAClF,MAAM,aAAa,GAAG,IAAI,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC;IAC9C,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;QAAE,aAAa,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;IACpE,0FAA0F;IAC1F,oBAAoB,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;IACxC,oBAAoB,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;IAC7C,MAAM,KAAK,GAAG,YAAY,CAAC,EAAE,aAAa,EAAE,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;IAC7E,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;QAC1C,aAAa,CAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACtF,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,GAAG,EAAE,UAAU,EAAE,CAAC;AAC7C,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,cAAc,CAAC,OAA4B;IACzD,IAAI,OAAO,KAAK,QAAQ,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC,SAAS,CAAC;YACpB,OAAO,EAAE,CAAC;YACV,KAAK,EAAE;gBACL,oBAAoB,EAAE,CAAC,EAAE,OAAO,EAAE,uBAAuB,EAAE,CAAC;gBAC5D,kBAAkB,EAAE,CAAC,EAAE,OAAO,EAAE,uBAAuB,EAAE,CAAC;gBAC1D,cAAc,EAAE,CAAC,EAAE,OAAO,EAAE,uBAAuB,EAAE,CAAC;gBACtD,aAAa,EAAE,CAAC,EAAE,OAAO,EAAE,uBAAuB,EAAE,CAAC;aACtD;SACF,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IACd,CAAC;IACD,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,KAAK,EAAE;YACL,UAAU,EAAE,CAAC,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,uBAAuB,EAAE,CAAC,EAAE,CAAC;SAC/F;KACF,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACd,CAAC","sourcesContent":["// `scopebond-hook init` — scaffold the local enrollment: a machine signing key, a\n// gateway countersigning key and a starter policy. Keys and receipts stay on the\n// machine; no credentials are handled.\n\nimport { mkdirSync, writeFileSync, existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { loadOrCreateAttester } from \"@scopebond/gateway/node\";\nimport { createSigner } from \"@scopebond/sdk\";\nimport { starterPolicy } from \"./runtime.js\";\n\nexport function scaffold(dir: string, opts: { force?: boolean } = {}): { agentKid: string; policyPath: string } {\n mkdirSync(dir, { recursive: true });\n const keyPath = join(dir, \"agent.key\");\n const attesterPath = join(dir, \"attester.key\");\n const policyPath = join(dir, \"policy.json\");\n // Never let the signing keys, the Cloud credential or the local log be committed.\n const gitignorePath = join(dir, \".gitignore\");\n if (!existsSync(gitignorePath)) writeFileSync(gitignorePath, \"*\\n\");\n // Machine signing key (agent) + gateway countersigning key (attester). Reused if present.\n loadOrCreateAttester({ file: keyPath });\n loadOrCreateAttester({ file: attesterPath });\n const agent = createSigner({ privateKeyPem: readFileSync(keyPath, \"utf8\") });\n if (!existsSync(policyPath) || opts.force) {\n writeFileSync(policyPath, JSON.stringify(starterPolicy(agent.kid), null, 2) + \"\\n\");\n }\n return { agentKid: agent.kid, policyPath };\n}\n\n/** The harness configuration snippet to install the hook. */\nexport function harnessSnippet(harness: \"claude\" | \"cursor\"): string {\n if (harness === \"cursor\") {\n return JSON.stringify({\n version: 1,\n hooks: {\n beforeShellExecution: [{ command: \"scopebond-hook cursor\" }],\n beforeMCPExecution: [{ command: \"scopebond-hook cursor\" }],\n beforeReadFile: [{ command: \"scopebond-hook cursor\" }],\n afterFileEdit: [{ command: \"scopebond-hook cursor\" }],\n },\n }, null, 2);\n }\n return JSON.stringify({\n hooks: {\n PreToolUse: [{ matcher: \"*\", hooks: [{ type: \"command\", command: \"scopebond-hook claude\" }] }],\n },\n }, null, 2);\n}\n"]}
1
+ {"version":3,"file":"init.js","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,iFAAiF;AACjF,uCAAuC;AAEvC,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,UAAU,EAAE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C;IACD,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,KAAK,EAAE;YACL,UAAU,EAAE,CAAC,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC;SAC7F;KACF,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACd,CAAC","sourcesContent":["// `scopebond-hook init` — scaffold the local enrollment: a machine signing key, a\n// gateway countersigning key and a starter policy. Keys and receipts stay on the\n// machine; no credentials are handled.\n\nimport { mkdirSync, writeFileSync, existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { loadOrCreateAttester } from \"@scopebond/gateway/node\";\nimport { createSigner } from \"@scopebond/sdk\";\nimport { starterPolicy } from \"./runtime.js\";\nimport { hookCommand } from \"./version.js\";\n\nexport function scaffold(dir: string, opts: { force?: boolean } = {}): { agentKid: string; policyPath: string } {\n mkdirSync(dir, { recursive: true });\n const keyPath = join(dir, \"agent.key\");\n const attesterPath = join(dir, \"attester.key\");\n const policyPath = join(dir, \"policy.json\");\n // Never let the signing keys, the Cloud credential or the local log be committed.\n const gitignorePath = join(dir, \".gitignore\");\n if (!existsSync(gitignorePath)) writeFileSync(gitignorePath, \"*\\n\");\n // Machine signing key (agent) + gateway countersigning key (attester). Reused if present.\n loadOrCreateAttester({ file: keyPath });\n loadOrCreateAttester({ file: attesterPath });\n const agent = createSigner({ privateKeyPem: readFileSync(keyPath, \"utf8\") });\n if (!existsSync(policyPath) || opts.force) {\n writeFileSync(policyPath, JSON.stringify(starterPolicy(agent.kid), null, 2) + \"\\n\");\n }\n return { agentKid: agent.kid, policyPath };\n}\n\n/** Install the hook into the agent's own config file, merging with anything already\n * there (idempotent — safe to run twice). Returns the file it wrote. This is what\n * lets `connect` finish setup without the user hand-editing JSON.\n * `cwd` defaults to the current directory (the project root the user runs it in). */\nexport function installHarness(harness: \"claude\" | \"cursor\", cwd: string = process.cwd()): string {\n const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null && !Array.isArray(v);\n const file = harness === \"cursor\" ? join(cwd, \".cursor\", \"hooks.json\") : join(cwd, \".claude\", \"settings.json\");\n mkdirSync(dirname(file), { recursive: true });\n let config: Record<string, unknown> = {};\n if (existsSync(file)) { try { const p = JSON.parse(readFileSync(file, \"utf8\")); if (isRecord(p)) config = p; } catch { /* start fresh on unreadable */ } }\n const hooks = isRecord(config.hooks) ? config.hooks : (config.hooks = {});\n const cursorCmd = hookCommand(\"cursor\");\n const claudeCmd = hookCommand(\"claude\");\n // Match any existing Scopebond hook entry (pinned or a legacy bare `scopebond-hook`)\n // so re-running never appends a duplicate and an old bare command is replaced.\n const isScopebond = (cmd: unknown): boolean => typeof cmd === \"string\" && /(^|\\s)(npx\\s+.*)?@scopebond\\/hook|(^|\\s)scopebond-hook(\\s|$)/.test(cmd);\n const entryMatches = (e: unknown): boolean =>\n isRecord(e) && (isScopebond(e.command) || (Array.isArray(e.hooks) && e.hooks.some((h) => isRecord(h) && isScopebond(h.command))));\n if (harness === \"cursor\") {\n config.version = config.version ?? 1;\n for (const event of [\"beforeShellExecution\", \"beforeMCPExecution\", \"beforeReadFile\", \"afterFileEdit\"]) {\n const list = Array.isArray((hooks as Record<string, unknown>)[event]) ? (hooks as Record<string, unknown[]>)[event] : ((hooks as Record<string, unknown[]>)[event] = []);\n const existing = list.findIndex(entryMatches);\n if (existing >= 0) list[existing] = { command: cursorCmd }; else list.push({ command: cursorCmd });\n }\n } else {\n const list = Array.isArray((hooks as Record<string, unknown>).PreToolUse) ? (hooks as Record<string, unknown[]>).PreToolUse : ((hooks as Record<string, unknown[]>).PreToolUse = []);\n const existing = list.findIndex(entryMatches);\n const entry = { matcher: \"*\", hooks: [{ type: \"command\", command: claudeCmd }] };\n if (existing >= 0) list[existing] = entry; else list.push(entry);\n }\n writeFileSync(file, JSON.stringify(config, null, 2) + \"\\n\");\n return file;\n}\n\n/** The harness configuration snippet to install the hook (version-pinned npx). */\nexport function harnessSnippet(harness: \"claude\" | \"cursor\"): string {\n if (harness === \"cursor\") {\n const cmd = hookCommand(\"cursor\");\n return JSON.stringify({\n version: 1,\n hooks: {\n beforeShellExecution: [{ command: cmd }],\n beforeMCPExecution: [{ command: cmd }],\n beforeReadFile: [{ command: cmd }],\n afterFileEdit: [{ command: cmd }],\n },\n }, null, 2);\n }\n return JSON.stringify({\n hooks: {\n PreToolUse: [{ matcher: \"*\", hooks: [{ type: \"command\", command: hookCommand(\"claude\") }] }],\n },\n }, null, 2);\n}\n"]}
package/dist/map.d.ts CHANGED
@@ -4,14 +4,20 @@ export interface NormalizedIntent {
4
4
  }
5
5
  export interface Mapped {
6
6
  intent: NormalizedIntent;
7
- /** false when no taxonomy type applies: emitted as tool.<name> and routed to the
8
- * observation path (not_evaluated), never granted. */
7
+ /** false when no taxonomy type applies (an unknown tool, or a shell command that
8
+ * could not be parsed): emitted to the observation path (not_evaluated) in normal
9
+ * mode and denied by the closed allowlist in strict mode — never granted. */
9
10
  evaluated: boolean;
10
11
  /** The native tool/event name, for diagnostics. */
11
12
  source: string;
12
13
  }
13
- /** Map a Claude Code PreToolUse payload to a normalized taxonomy action. */
14
- export declare function mapClaudeToolUse(input: Record<string, unknown>): Mapped;
15
- /** Map a Cursor hook event to a normalized taxonomy action. */
16
- export declare function mapCursorEvent(event: string, payload: Record<string, unknown>): Mapped;
14
+ /** A bare `git push` (no ref) pushes the current branch. The mapper cannot know it,
15
+ * so the runtime resolves it and fills it in here, before evaluation — otherwise the
16
+ * starter policy's ref bound would fail-closed on every plain push. Only git.push
17
+ * intents with no ref are touched. */
18
+ export declare function fillPushBranch(mapped: Mapped[], branch: string | null | undefined): Mapped[];
19
+ /** Map a Claude Code PreToolUse payload to the normalized actions it represents. */
20
+ export declare function mapClaudeToolUse(input: Record<string, unknown>): Mapped[];
21
+ /** Map a Cursor hook event to the normalized actions it represents. */
22
+ export declare function mapCursorEvent(event: string, payload: Record<string, unknown>): Mapped[];
17
23
  //# sourceMappingURL=map.d.ts.map
package/dist/map.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"map.d.ts","sourceRoot":"","sources":["../src/map.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AACD,MAAM,WAAW,MAAM;IACrB,MAAM,EAAE,gBAAgB,CAAC;IACzB;2DACuD;IACvD,SAAS,EAAE,OAAO,CAAC;IACnB,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAC;CAChB;AAqDD,4EAA4E;AAC5E,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAkBvE;AAED,+DAA+D;AAC/D,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAkBtF"}
1
+ {"version":3,"file":"map.d.ts","sourceRoot":"","sources":["../src/map.ts"],"names":[],"mappings":"AAYA,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AACD,MAAM,WAAW,MAAM;IACrB,MAAM,EAAE,gBAAgB,CAAC;IACzB;;kFAE8E;IAC9E,SAAS,EAAE,OAAO,CAAC;IACnB,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAC;CAChB;AA+DD;;;uCAGuC;AACvC,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,EAAE,CAM5F;AAED,oFAAoF;AACpF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,EAAE,CAkBzE;AAED,uEAAuE;AACvE,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,EAAE,CAkBxF"}
package/dist/map.js CHANGED
@@ -1,47 +1,58 @@
1
- // The mapper: a pure function from a coding agent's native tool call to a
2
- // normalized Scopebond action (Action Taxonomy v1). This is the connector's core
3
- // — deterministic and side-effect free, so it can be conformance-tested directly.
4
- import { digest, redactCommand } from "./minimize.js";
1
+ // The mapper: a pure function from a coding agent's native tool call to the
2
+ // normalized Scopebond actions (Action Taxonomy v1) it represents. Deterministic
3
+ // and side-effect free, so it can be conformance-tested directly.
4
+ //
5
+ // A shell tool call can carry several commands (`a && b`, `$(c)`, `bash -c '…'`);
6
+ // the mapper decomposes it and returns one intent per simple command, so the
7
+ // runtime evaluates every one and denies if any is out of policy. Non-shell tools
8
+ // map to a single intent (a one-element array).
9
+ import { digest, redactCommand, scrubParam, scrubSecrets } from "./minimize.js";
10
+ import { decomposeShell, parseGitPush } from "./shell.js";
11
+ const basename = (t) => t.replace(/^.*[\\/]/, "");
5
12
  const rel = (value, cwd) => {
6
13
  const s = String(value ?? "");
7
14
  if (cwd && s.startsWith(cwd))
8
15
  return s.slice(cwd.length).replace(/^[\\/]+/, "");
9
16
  return s;
10
17
  };
11
- /** The invoked program's basename, after stripping sudo and `env VAR=val` prefixes. */
12
- function programOf(command) {
13
- const stripped = command.trim().replace(/^sudo\s+/, "").replace(/^(?:env\s+\S+=\S+\s+)+/, "");
14
- const first = stripped.split(/\s+/)[0] ?? "";
15
- return first.replace(/^.*[\\/]/, "");
16
- }
17
- // Best-effort `git push [--force|-f] [remote] [ref]` parse. Ambiguous pushes omit
18
- // the ref, which a ref bound then denies (fail closed).
19
- function parseGitPush(command) {
20
- const t = command.trim().replace(/^sudo\s+/, "");
21
- if (!/^git\s+push(\s|$)/.test(t))
22
- return null;
23
- const force = /(?:^|\s)(?:--force\b|--force-with-lease\b|-f\b)/.test(t);
24
- const rest = t.replace(/^git\s+push\b/, "").trim();
25
- const positional = rest.split(/\s+/).filter((a) => a && !a.startsWith("-"));
26
- const params = { force };
27
- if (positional[0])
28
- params.remote = positional[0];
29
- if (positional[1])
30
- params.ref = positional[1].replace(/^[^:]*:/, ""); // src:dst → dst
31
- return params;
32
- }
33
- function mapShell(command, cwd) {
34
- const push = parseGitPush(command);
35
- if (push)
36
- return { intent: { action_type: "git.push", params: push }, evaluated: true, source: "shell" };
18
+ /** Map one parsed simple command to a git.push or shell.exec intent. An opaque
19
+ * (unparseable) command becomes an un-evaluated shell.exec so it fails closed. */
20
+ function mapSimpleCommand(sc, cwd) {
21
+ if (sc.opaque) {
22
+ return {
23
+ intent: { action_type: "shell.exec", params: { command: redactCommand(sc.raw), program: "", ...(cwd ? { cwd } : {}) } },
24
+ evaluated: false, source: "shell",
25
+ };
26
+ }
27
+ const push = parseGitPush(sc);
28
+ if (push) {
29
+ const params = { force: push.force };
30
+ if (push.remote !== undefined)
31
+ params.remote = scrubParam(push.remote);
32
+ if (push.ref !== undefined)
33
+ params.ref = scrubParam(push.ref);
34
+ return { intent: { action_type: "git.push", params }, evaluated: true, source: "shell" };
35
+ }
37
36
  return {
38
37
  intent: {
39
38
  action_type: "shell.exec",
40
- params: { command: redactCommand(command), program: programOf(command), ...(cwd ? { cwd } : {}) },
39
+ // Scrub before storing: the raw command through the blob-aware scrubber, and
40
+ // the whole first token BEFORE taking its basename, so a bare-secret command
41
+ // containing "/" cannot leak a path-fragment as the program.
42
+ params: { command: redactCommand(sc.raw), program: basename(scrubSecrets(sc.programRaw)), ...(cwd ? { cwd } : {}) },
41
43
  },
42
44
  evaluated: true, source: "shell",
43
45
  };
44
46
  }
47
+ /** Decompose a shell command into one intent per simple command it will run. An
48
+ * empty command yields a single un-evaluated placeholder (nothing to grant). */
49
+ function mapShell(command, cwd) {
50
+ const commands = decomposeShell(command);
51
+ if (commands.length === 0) {
52
+ return [{ intent: { action_type: "shell.exec", params: { command: redactCommand(command), program: "" } }, evaluated: false, source: "shell" }];
53
+ }
54
+ return commands.map((sc) => mapSimpleCommand(sc, cwd));
55
+ }
45
56
  function parseMcpName(name) {
46
57
  if (!name.startsWith("mcp__"))
47
58
  return null;
@@ -51,15 +62,28 @@ function parseMcpName(name) {
51
62
  return { server: parts[1], tool: parts.slice(2).join("__") };
52
63
  }
53
64
  function splitUrl(url) {
65
+ // The query string is dropped; a token in the path or an unparseable URL is scrubbed.
54
66
  try {
55
67
  const u = new URL(url);
56
- return { host: u.host, path: u.pathname };
68
+ return { host: u.host, path: scrubParam(u.pathname) };
57
69
  }
58
70
  catch {
59
- return { host: url, path: "" };
71
+ return { host: scrubParam(url), path: "" };
60
72
  }
61
73
  }
62
- /** Map a Claude Code PreToolUse payload to a normalized taxonomy action. */
74
+ const one = (intent, evaluated, source) => [{ intent, evaluated, source }];
75
+ /** A bare `git push` (no ref) pushes the current branch. The mapper cannot know it,
76
+ * so the runtime resolves it and fills it in here, before evaluation — otherwise the
77
+ * starter policy's ref bound would fail-closed on every plain push. Only git.push
78
+ * intents with no ref are touched. */
79
+ export function fillPushBranch(mapped, branch) {
80
+ if (!branch)
81
+ return mapped;
82
+ return mapped.map((m) => m.intent.action_type === "git.push" && m.intent.params.ref === undefined
83
+ ? { ...m, intent: { ...m.intent, params: { ...m.intent.params, ref: scrubParam(branch) } } }
84
+ : m);
85
+ }
86
+ /** Map a Claude Code PreToolUse payload to the normalized actions it represents. */
63
87
  export function mapClaudeToolUse(input) {
64
88
  const name = String(input?.tool_name ?? "");
65
89
  const ti = (input?.tool_input ?? {});
@@ -67,21 +91,21 @@ export function mapClaudeToolUse(input) {
67
91
  if (name === "Bash")
68
92
  return mapShell(String(ti.command ?? ""), cwd);
69
93
  if (name === "Write" || name === "Edit" || name === "MultiEdit")
70
- return { intent: { action_type: "file.write", params: { path: rel(ti.file_path, cwd) } }, evaluated: true, source: name };
94
+ return one({ action_type: "file.write", params: { path: rel(ti.file_path, cwd) } }, true, name);
71
95
  if (name === "NotebookEdit")
72
- return { intent: { action_type: "file.write", params: { path: rel(ti.notebook_path ?? ti.file_path, cwd) } }, evaluated: true, source: name };
96
+ return one({ action_type: "file.write", params: { path: rel(ti.notebook_path ?? ti.file_path, cwd) } }, true, name);
73
97
  if (name === "Read")
74
- return { intent: { action_type: "file.read", params: { path: rel(ti.file_path, cwd) } }, evaluated: true, source: name };
98
+ return one({ action_type: "file.read", params: { path: rel(ti.file_path, cwd) } }, true, name);
75
99
  if (name === "WebFetch") {
76
100
  const { host, path } = splitUrl(String(ti.url ?? ""));
77
- return { intent: { action_type: "net.fetch", params: { host, path, method: "GET" } }, evaluated: true, source: name };
101
+ return one({ action_type: "net.fetch", params: { host, path, method: "GET" } }, true, name);
78
102
  }
79
103
  const mcp = parseMcpName(name);
80
104
  if (mcp)
81
- return { intent: { action_type: "mcp.tool.call", params: { server: mcp.server, tool: mcp.tool, args_digest: digest(ti) } }, evaluated: true, source: name };
82
- return { intent: { action_type: `tool.${name.toLowerCase()}`, params: {} }, evaluated: false, source: name };
105
+ return one({ action_type: "mcp.tool.call", params: { server: mcp.server, tool: mcp.tool, args_digest: digest(ti) } }, true, name);
106
+ return one({ action_type: `tool.${name.toLowerCase()}`, params: {} }, false, name);
83
107
  }
84
- /** Map a Cursor hook event to a normalized taxonomy action. */
108
+ /** Map a Cursor hook event to the normalized actions it represents. */
85
109
  export function mapCursorEvent(event, payload) {
86
110
  const p = payload ?? {};
87
111
  const cwd = p.cwd ? String(p.cwd) : undefined;
@@ -89,16 +113,16 @@ export function mapCursorEvent(event, payload) {
89
113
  case "beforeShellExecution":
90
114
  return mapShell(String(p.command ?? ""), cwd);
91
115
  case "beforeReadFile":
92
- return { intent: { action_type: "file.read", params: { path: rel(p.path ?? p.file_path, cwd) } }, evaluated: true, source: event };
116
+ return one({ action_type: "file.read", params: { path: rel(p.path ?? p.file_path, cwd) } }, true, event);
93
117
  case "afterFileEdit":
94
- return { intent: { action_type: "file.write", params: { path: rel(p.path ?? p.file_path, cwd) } }, evaluated: true, source: event };
118
+ return one({ action_type: "file.write", params: { path: rel(p.path ?? p.file_path, cwd) } }, true, event);
95
119
  case "beforeMCPExecution": {
96
120
  const server = String(p.server ?? p.server_name ?? "");
97
121
  const tool = String(p.tool ?? p.tool_name ?? "");
98
- return { intent: { action_type: "mcp.tool.call", params: { server, tool, args_digest: digest(p.args ?? p.arguments ?? {}) } }, evaluated: true, source: event };
122
+ return one({ action_type: "mcp.tool.call", params: { server, tool, args_digest: digest(p.args ?? p.arguments ?? {}) } }, true, event);
99
123
  }
100
124
  default:
101
- return { intent: { action_type: `tool.${event.toLowerCase()}`, params: {} }, evaluated: false, source: event };
125
+ return one({ action_type: `tool.${event.toLowerCase()}`, params: {} }, false, event);
102
126
  }
103
127
  }
104
128
  //# sourceMappingURL=map.js.map
package/dist/map.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"map.js","sourceRoot":"","sources":["../src/map.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,iFAAiF;AACjF,kFAAkF;AAElF,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAetD,MAAM,GAAG,GAAG,CAAC,KAAc,EAAE,GAAY,EAAU,EAAE;IACnD,MAAM,CAAC,GAAG,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC;IAC9B,IAAI,GAAG,IAAI,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IAChF,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AAEF,uFAAuF;AACvF,SAAS,SAAS,CAAC,OAAe;IAChC,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,UAAU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EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IACnH,CAAC;AACH,CAAC","sourcesContent":["// The mapper: a pure function from a coding agent's native tool call to a\n// normalized Scopebond action (Action Taxonomy v1). This is the connector's core\n// — deterministic and side-effect free, so it can be conformance-tested directly.\n\nimport { digest, redactCommand } from \"./minimize.js\";\n\nexport interface NormalizedIntent {\n action_type: string;\n params: Record<string, unknown>;\n}\nexport interface Mapped {\n intent: NormalizedIntent;\n /** false when no taxonomy type applies: emitted as tool.<name> and routed to the\n * observation path (not_evaluated), never granted. */\n evaluated: boolean;\n /** The native tool/event name, for diagnostics. */\n source: string;\n}\n\nconst rel = (value: unknown, cwd?: string): string => {\n const s = String(value ?? \"\");\n if (cwd && s.startsWith(cwd)) return s.slice(cwd.length).replace(/^[\\\\/]+/, \"\");\n return s;\n};\n\n/** The invoked program's basename, after stripping sudo and `env VAR=val` prefixes. */\nfunction programOf(command: string): string {\n const stripped = command.trim().replace(/^sudo\\s+/, \"\").replace(/^(?:env\\s+\\S+=\\S+\\s+)+/, \"\");\n const first = stripped.split(/\\s+/)[0] ?? \"\";\n return first.replace(/^.*[\\\\/]/, \"\");\n}\n\n// Best-effort `git push [--force|-f] [remote] [ref]` parse. Ambiguous pushes omit\n// the ref, which a ref bound then denies (fail closed).\nfunction parseGitPush(command: string): Record<string, unknown> | null {\n const t = command.trim().replace(/^sudo\\s+/, \"\");\n if (!/^git\\s+push(\\s|$)/.test(t)) return null;\n const force = /(?:^|\\s)(?:--force\\b|--force-with-lease\\b|-f\\b)/.test(t);\n const rest = t.replace(/^git\\s+push\\b/, \"\").trim();\n const positional = rest.split(/\\s+/).filter((a) => a && !a.startsWith(\"-\"));\n const params: Record<string, unknown> = { force };\n if (positional[0]) params.remote = positional[0];\n if (positional[1]) params.ref = positional[1].replace(/^[^:]*:/, \"\"); // src:dst → dst\n return params;\n}\n\nfunction mapShell(command: string, cwd?: string): Mapped {\n const push = parseGitPush(command);\n if (push) return { intent: { action_type: \"git.push\", params: push }, evaluated: true, source: \"shell\" };\n return {\n intent: {\n action_type: \"shell.exec\",\n params: { command: redactCommand(command), program: programOf(command), ...(cwd ? { cwd } : {}) },\n },\n evaluated: true, source: \"shell\",\n };\n}\n\nfunction parseMcpName(name: string): { server: string; tool: string } | null {\n if (!name.startsWith(\"mcp__\")) return null;\n const parts = name.split(\"__\");\n if (parts.length < 3) return null;\n return { server: parts[1], tool: parts.slice(2).join(\"__\") };\n}\n\nfunction splitUrl(url: string): { host: string; path: string } {\n try { const u = new URL(url); return { host: u.host, path: u.pathname }; }\n catch { return { host: url, path: \"\" }; }\n}\n\n/** Map a Claude Code PreToolUse payload to a normalized taxonomy action. */\nexport function mapClaudeToolUse(input: Record<string, unknown>): Mapped {\n const name = String(input?.tool_name ?? \"\");\n const ti = (input?.tool_input ?? {}) as Record<string, unknown>;\n const cwd = input?.cwd ? String(input.cwd) : undefined;\n if (name === \"Bash\") return mapShell(String(ti.command ?? \"\"), cwd);\n if (name === \"Write\" || name === \"Edit\" || name === \"MultiEdit\")\n return { intent: { action_type: \"file.write\", params: { path: rel(ti.file_path, cwd) } }, evaluated: true, source: name };\n if (name === \"NotebookEdit\")\n return { intent: { action_type: \"file.write\", params: { path: rel(ti.notebook_path ?? ti.file_path, cwd) } }, evaluated: true, source: name };\n if (name === \"Read\")\n return { intent: { action_type: \"file.read\", params: { path: rel(ti.file_path, cwd) } }, evaluated: true, source: name };\n if (name === \"WebFetch\") {\n const { host, path } = splitUrl(String(ti.url ?? \"\"));\n return { intent: { action_type: \"net.fetch\", params: { host, path, method: \"GET\" } }, evaluated: true, source: name };\n }\n const mcp = parseMcpName(name);\n if (mcp) return { intent: { action_type: \"mcp.tool.call\", params: { server: mcp.server, tool: mcp.tool, args_digest: digest(ti) } }, evaluated: true, source: name };\n return { intent: { action_type: `tool.${name.toLowerCase()}`, params: {} }, evaluated: false, source: name };\n}\n\n/** Map a Cursor hook event to a normalized taxonomy action. */\nexport function mapCursorEvent(event: string, payload: Record<string, unknown>): Mapped {\n const p = payload ?? {};\n const cwd = p.cwd ? String(p.cwd) : undefined;\n switch (event) {\n case \"beforeShellExecution\":\n return mapShell(String(p.command ?? \"\"), cwd);\n case \"beforeReadFile\":\n return { intent: { action_type: \"file.read\", params: { path: rel(p.path ?? p.file_path, cwd) } }, evaluated: true, source: event };\n case \"afterFileEdit\":\n return { intent: { action_type: \"file.write\", params: { path: rel(p.path ?? p.file_path, cwd) } }, evaluated: true, source: event };\n case \"beforeMCPExecution\": {\n const server = String(p.server ?? p.server_name ?? \"\");\n const tool = String(p.tool ?? p.tool_name ?? \"\");\n return { intent: { action_type: \"mcp.tool.call\", params: { server, tool, args_digest: digest(p.args ?? p.arguments ?? {}) } }, evaluated: true, source: event };\n }\n default:\n return { intent: { action_type: `tool.${event.toLowerCase()}`, params: {} }, evaluated: false, source: event };\n }\n}\n"]}
1
+ {"version":3,"file":"map.js","sourceRoot":"","sources":["../src/map.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,iFAAiF;AACjF,kEAAkE;AAClE,EAAE;AACF,kFAAkF;AAClF,6EAA6E;AAC7E,kFAAkF;AAClF,gDAAgD;AAEhD,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAChF,OAAO,EAAE,cAAc,EAAE,YAAY,EAAsB,MAAM,YAAY,CAAC;AAgB9E,MAAM,QAAQ,GAAG,CAAC,CAAS,EAAU,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;AAElE,MAAM,GAAG,GAAG,CAAC,KAAc,EAAE,GAAY,EAAU,EAAE;IACnD,MAAM,CAAC,GAAG,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC;IAC9B,IAAI,GAAG,IAAI,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,MA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AC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,SAAS,EAAE,GAAG,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;QAC5G,KAAK,oBAAoB,CAAC,CAAC,CAAC;YAC1B,MAAM,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;YACvD,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,SAAS,IAAI,EAAE,CAAC,CAAC;YACjD,OAAO,GAAG,CAAC,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,SAAS,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;QACxI,CAAC;QACD;YACE,OAAO,GAAG,CAAC,EAAE,WAAW,EAAE,QAAQ,KAAK,CAAC,WAAW,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IACzF,CAAC;AACH,CAAC","sourcesContent":["// The mapper: a pure function from a coding agent's native tool call to the\n// normalized Scopebond actions (Action Taxonomy v1) it represents. Deterministic\n// and side-effect free, so it can be conformance-tested directly.\n//\n// A shell tool call can carry several commands (`a && b`, `$(c)`, `bash -c '…'`);\n// the mapper decomposes it and returns one intent per simple command, so the\n// runtime evaluates every one and denies if any is out of policy. Non-shell tools\n// map to a single intent (a one-element array).\n\nimport { digest, redactCommand, scrubParam, scrubSecrets } from \"./minimize.js\";\nimport { decomposeShell, parseGitPush, type SimpleCommand } from \"./shell.js\";\n\nexport interface NormalizedIntent {\n action_type: string;\n params: Record<string, unknown>;\n}\nexport interface Mapped {\n intent: NormalizedIntent;\n /** false when no taxonomy type applies (an unknown tool, or a shell command that\n * could not be parsed): emitted to the observation path (not_evaluated) in normal\n * mode and denied by the closed allowlist in strict mode — never granted. */\n evaluated: boolean;\n /** The native tool/event name, for diagnostics. */\n source: string;\n}\n\nconst basename = (t: string): string => t.replace(/^.*[\\\\/]/, \"\");\n\nconst rel = (value: unknown, cwd?: string): string => {\n const s = String(value ?? \"\");\n if (cwd && s.startsWith(cwd)) return s.slice(cwd.length).replace(/^[\\\\/]+/, \"\");\n return s;\n};\n\n/** Map one parsed simple command to a git.push or shell.exec intent. An opaque\n * (unparseable) command becomes an un-evaluated shell.exec so it fails closed. */\nfunction mapSimpleCommand(sc: SimpleCommand, cwd?: string): Mapped {\n if (sc.opaque) {\n return {\n intent: { action_type: \"shell.exec\", params: { command: redactCommand(sc.raw), program: \"\", ...(cwd ? { cwd } : {}) } },\n evaluated: false, source: \"shell\",\n };\n }\n const push = parseGitPush(sc);\n if (push) {\n const params: Record<string, unknown> = { force: push.force };\n if (push.remote !== undefined) params.remote = scrubParam(push.remote);\n if (push.ref !== undefined) params.ref = scrubParam(push.ref);\n return { intent: { action_type: \"git.push\", params }, evaluated: true, source: \"shell\" };\n }\n return {\n intent: {\n action_type: \"shell.exec\",\n // Scrub before storing: the raw command through the blob-aware scrubber, and\n // the whole first token BEFORE taking its basename, so a bare-secret command\n // containing \"/\" cannot leak a path-fragment as the program.\n params: { command: redactCommand(sc.raw), program: basename(scrubSecrets(sc.programRaw)), ...(cwd ? { cwd } : {}) },\n },\n evaluated: true, source: \"shell\",\n };\n}\n\n/** Decompose a shell command into one intent per simple command it will run. An\n * empty command yields a single un-evaluated placeholder (nothing to grant). */\nfunction mapShell(command: string, cwd?: string): Mapped[] {\n const commands = decomposeShell(command);\n if (commands.length === 0) {\n return [{ intent: { action_type: \"shell.exec\", params: { command: redactCommand(command), program: \"\" } }, evaluated: false, source: \"shell\" }];\n }\n return commands.map((sc) => mapSimpleCommand(sc, cwd));\n}\n\nfunction parseMcpName(name: string): { server: string; tool: string } | null {\n if (!name.startsWith(\"mcp__\")) return null;\n const parts = name.split(\"__\");\n if (parts.length < 3) return null;\n return { server: parts[1], tool: parts.slice(2).join(\"__\") };\n}\n\nfunction splitUrl(url: string): { host: string; path: string } {\n // The query string is dropped; a token in the path or an unparseable URL is scrubbed.\n try { const u = new URL(url); return { host: u.host, path: scrubParam(u.pathname) }; }\n catch { return { host: scrubParam(url), path: \"\" }; }\n}\n\nconst one = (intent: NormalizedIntent, evaluated: boolean, source: string): Mapped[] => [{ intent, evaluated, source }];\n\n/** A bare `git push` (no ref) pushes the current branch. The mapper cannot know it,\n * so the runtime resolves it and fills it in here, before evaluation — otherwise the\n * starter policy's ref bound would fail-closed on every plain push. Only git.push\n * intents with no ref are touched. */\nexport function fillPushBranch(mapped: Mapped[], branch: string | null | undefined): Mapped[] {\n if (!branch) return mapped;\n return mapped.map((m) =>\n m.intent.action_type === \"git.push\" && m.intent.params.ref === undefined\n ? { ...m, intent: { ...m.intent, params: { ...m.intent.params, ref: scrubParam(branch) } } }\n : m);\n}\n\n/** Map a Claude Code PreToolUse payload to the normalized actions it represents. */\nexport function mapClaudeToolUse(input: Record<string, unknown>): Mapped[] {\n const name = String(input?.tool_name ?? \"\");\n const ti = (input?.tool_input ?? {}) as Record<string, unknown>;\n const cwd = input?.cwd ? String(input.cwd) : undefined;\n if (name === \"Bash\") return mapShell(String(ti.command ?? \"\"), cwd);\n if (name === \"Write\" || name === \"Edit\" || name === \"MultiEdit\")\n return one({ action_type: \"file.write\", params: { path: rel(ti.file_path, cwd) } }, true, name);\n if (name === \"NotebookEdit\")\n return one({ action_type: \"file.write\", params: { path: rel(ti.notebook_path ?? ti.file_path, cwd) } }, true, name);\n if (name === \"Read\")\n return one({ action_type: \"file.read\", params: { path: rel(ti.file_path, cwd) } }, true, name);\n if (name === \"WebFetch\") {\n const { host, path } = splitUrl(String(ti.url ?? \"\"));\n return one({ action_type: \"net.fetch\", params: { host, path, method: \"GET\" } }, true, name);\n }\n const mcp = parseMcpName(name);\n if (mcp) return one({ action_type: \"mcp.tool.call\", params: { server: mcp.server, tool: mcp.tool, args_digest: digest(ti) } }, true, name);\n return one({ action_type: `tool.${name.toLowerCase()}`, params: {} }, false, name);\n}\n\n/** Map a Cursor hook event to the normalized actions it represents. */\nexport function mapCursorEvent(event: string, payload: Record<string, unknown>): Mapped[] {\n const p = payload ?? {};\n const cwd = p.cwd ? String(p.cwd) : undefined;\n switch (event) {\n case \"beforeShellExecution\":\n return mapShell(String(p.command ?? \"\"), cwd);\n case \"beforeReadFile\":\n return one({ action_type: \"file.read\", params: { path: rel(p.path ?? p.file_path, cwd) } }, true, event);\n case \"afterFileEdit\":\n return one({ action_type: \"file.write\", params: { path: rel(p.path ?? p.file_path, cwd) } }, true, event);\n case \"beforeMCPExecution\": {\n const server = String(p.server ?? p.server_name ?? \"\");\n const tool = String(p.tool ?? p.tool_name ?? \"\");\n return one({ action_type: \"mcp.tool.call\", params: { server, tool, args_digest: digest(p.args ?? p.arguments ?? {}) } }, true, event);\n }\n default:\n return one({ action_type: `tool.${event.toLowerCase()}`, params: {} }, false, event);\n }\n}\n"]}
@@ -1,5 +1,10 @@
1
1
  export declare const sha256: (value: string) => string;
2
2
  export declare const digest: (value: unknown) => string;
3
+ /** Scrub a structured parameter (a program name, a remote, a URL path): credential
4
+ * assignments and recognizable token shapes only, so policy matching on ordinary
5
+ * values is unaffected. */
6
+ export declare function scrubParam(text: string): string;
7
+ /** Scrub free text: everything `scrubParam` removes plus generic high-entropy blobs. */
3
8
  export declare function scrubSecrets(text: string): string;
4
9
  /** A privacy-preserving representation of a shell command: a scrubbed, truncated
5
10
  * head plus a digest of the full original. The full command is never retained. */
@@ -1 +1 @@
1
- {"version":3,"file":"minimize.d.ts","sourceRoot":"","sources":["../src/minimize.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,MAAM,GAAI,OAAO,MAAM,KAAG,MAAsE,CAAC;AAC9G,eAAO,MAAM,MAAM,GAAI,OAAO,OAAO,KAAG,MAA2C,CAAC;AAYpF,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMjD;AAED;mFACmF;AACnF,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,SAAK,GAAG,MAAM,CAInE"}
1
+ {"version":3,"file":"minimize.d.ts","sourceRoot":"","sources":["../src/minimize.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,MAAM,GAAI,OAAO,MAAM,KAAG,MAAsE,CAAC;AAC9G,eAAO,MAAM,MAAM,GAAI,OAAO,OAAO,KAAG,MAA2C,CAAC;AAmDpF;;4BAE4B;AAC5B,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAI/C;AAED,wFAAwF;AACxF,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAIjD;AAED;mFACmF;AACnF,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,SAAK,GAAG,MAAM,CAInE"}
package/dist/minimize.js CHANGED
@@ -5,20 +5,66 @@ import { createHash } from "node:crypto";
5
5
  import { canonical } from "@scopebond/policy-schema/canonical";
6
6
  export const sha256 = (value) => "sha256:" + createHash("sha256").update(value).digest("hex");
7
7
  export const digest = (value) => sha256(canonical(value));
8
- // Command-line shapes that commonly carry secrets. Over-scrubbing is safe.
9
- const SECRET_PATTERNS = [
10
- /(--?(?:password|passwd|pwd|token|secret|api[-_]?key|auth)[=\s]+)(\S+)/gi,
11
- /(Authorization:\s*Bearer\s+)(\S+)/gi,
12
- /\b(gh[pousr]_[A-Za-z0-9]{20,})\b/g, // GitHub tokens
13
- /\b(sk-[A-Za-z0-9]{20,})\b/g, // OpenAI-style keys
14
- /\b(AKIA[0-9A-Z]{16})\b/g, // AWS access key id
15
- /\b([A-Za-z0-9+/]{40,}={0,2})\b/g, // long base64 blobs
8
+ const MASK = "***";
9
+ // A flag or header value: a quoted string or a run of non-whitespace.
10
+ const VALUE = String.raw `("[^"]*"|'[^']*'|\S+)`;
11
+ // Each rule states its own replacement. `$1` keeps a non-secret label (a flag or
12
+ // header name); the secret itself is always dropped whole. Over-scrubbing is safe.
13
+ // Every pattern is a single pass over simple character classes (no nested
14
+ // quantifiers), so matching stays linear in the command length.
15
+ const SECRET_RULES = [
16
+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, MASK],
17
+ [new RegExp(String.raw `(--?(?:password|passwd|pwd|token|secret|api[-_]?key|access[-_]?key|auth|credentials?)[=\s]+)${VALUE}`, "gi"), `$1${MASK}`],
18
+ [new RegExp(String.raw `((?:^|\s)(?:-u|--user)[=\s]+)${VALUE}`, "g"), `$1${MASK}`],
19
+ [/(Authorization:\s*(?:Bearer|Basic|Token)\s+)[^\s"']+/gi, `$1${MASK}`],
20
+ [/((?:x-api-key|api-key|x-auth-token|x-access-token|private-token)\s*:\s*)[^\s"']+/gi, `$1${MASK}`],
21
+ [/(:\/\/)[^\s/@:]+:[^\s/@]+@/g, `$1${MASK}@`], // URL userinfo
22
+ [/\bgh[pousr]_[A-Za-z0-9]{20,}/g, MASK], // GitHub tokens
23
+ [/\bgithub_pat_[A-Za-z0-9_]{20,}/g, MASK], // GitHub fine-grained tokens
24
+ [/\bglpat-[A-Za-z0-9_-]{20,}/g, MASK], // GitLab tokens
25
+ [/\bnpm_[A-Za-z0-9]{20,}/g, MASK], // npm tokens
26
+ [/\bxox[abeoprs]-[A-Za-z0-9-]{10,}/g, MASK], // Slack tokens
27
+ [/\b[sr]k_(?:live|test)_[A-Za-z0-9]{16,}/g, MASK], // Stripe keys
28
+ [/\bsk-[A-Za-z0-9_-]{20,}/g, MASK], // OpenAI/Anthropic-style keys
29
+ [/\bAIza[0-9A-Za-z_-]{30,}/g, MASK], // Google API keys
30
+ [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, MASK], // AWS access key ids
31
+ [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, MASK], // JWTs
16
32
  ];
33
+ // Generic high-entropy shapes. Applied to free text only (the command head), never to
34
+ // structured parameters a policy matches on: a long path or a commit id is not a secret.
35
+ const BLOB_RULES = [
36
+ [/\b[A-Fa-f0-9]{32,}\b/g, MASK], // long hex blobs
37
+ [/[A-Za-z0-9+/_-]{40,}={0,2}/g, MASK], // long base64/base64url blobs
38
+ ];
39
+ const SECRET_NAME = /token|secret|passw|pwd|api_?key|access_?key|private_?key|auth|credential|session/i;
40
+ // `NAME=value` where the name looks like a credential (`GH_TOKEN=…`, `export
41
+ // AWS_SECRET_ACCESS_KEY=…`). Done per whitespace-delimited word rather than with
42
+ // one regex so a long identifier cannot cause backtracking.
43
+ function scrubAssignments(text) {
44
+ return text.replace(/\S+/g, (word) => {
45
+ const eq = word.indexOf("=");
46
+ if (eq <= 0 || eq === word.length - 1)
47
+ return word;
48
+ const name = word.slice(0, eq);
49
+ if (name.startsWith("-") || !SECRET_NAME.test(name))
50
+ return word; // flags are handled by SECRET_RULES
51
+ return `${name}=${MASK}`;
52
+ });
53
+ }
54
+ /** Scrub a structured parameter (a program name, a remote, a URL path): credential
55
+ * assignments and recognizable token shapes only, so policy matching on ordinary
56
+ * values is unaffected. */
57
+ export function scrubParam(text) {
58
+ let out = scrubAssignments(text);
59
+ for (const [re, replacement] of SECRET_RULES)
60
+ out = out.replace(re, replacement);
61
+ return out;
62
+ }
63
+ /** Scrub free text: everything `scrubParam` removes plus generic high-entropy blobs. */
17
64
  export function scrubSecrets(text) {
18
- let out = text;
19
- for (const re of SECRET_PATTERNS) {
20
- out = out.replace(re, (_m, p1, p2) => (p2 !== undefined ? `${p1}***` : "***"));
21
- }
65
+ let out = scrubParam(text);
66
+ for (const [re, replacement] of BLOB_RULES)
67
+ out = out.replace(re, replacement);
22
68
  return out;
23
69
  }
24
70
  /** A privacy-preserving representation of a shell command: a scrubbed, truncated
@@ -1 +1 @@
1
- {"version":3,"file":"minimize.js","sourceRoot":"","sources":["../src/minimize.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QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC;IACrF,OAAO,GAAG,IAAI,KAAK,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC;AACxC,CAAC","sourcesContent":["// Data minimization for the hook: file contents are never stored, shell commands\n// are reduced to a scrubbed head plus a digest, and common secret shapes are\n// removed before anything is written or signed (SB09).\n\nimport { createHash } from \"node:crypto\";\nimport { canonical } from \"@scopebond/policy-schema/canonical\";\n\nexport const sha256 = (value: string): string => \"sha256:\" + createHash(\"sha256\").update(value).digest(\"hex\");\nexport const digest = (value: unknown): string => sha256(canonical(value as never));\n\n// Command-line shapes that commonly carry secrets. Over-scrubbing is safe.\nconst SECRET_PATTERNS: RegExp[] = [\n /(--?(?:password|passwd|pwd|token|secret|api[-_]?key|auth)[=\\s]+)(\\S+)/gi,\n /(Authorization:\\s*Bearer\\s+)(\\S+)/gi,\n /\\b(gh[pousr]_[A-Za-z0-9]{20,})\\b/g, // GitHub tokens\n /\\b(sk-[A-Za-z0-9]{20,})\\b/g, // OpenAI-style keys\n /\\b(AKIA[0-9A-Z]{16})\\b/g, // AWS access key id\n /\\b([A-Za-z0-9+/]{40,}={0,2})\\b/g, // long base64 blobs\n];\n\nexport function scrubSecrets(text: string): string {\n let out = text;\n for (const re of SECRET_PATTERNS) {\n out = out.replace(re, (_m, p1: string, p2?: string) => (p2 !== undefined ? `${p1}***` : \"***\"));\n }\n return out;\n}\n\n/** A privacy-preserving representation of a shell command: a scrubbed, truncated\n * head plus a digest of the full original. The full command is never retained. */\nexport function redactCommand(command: string, headLen = 64): string {\n const scrubbed = scrubSecrets(command);\n const head = scrubbed.length > headLen ? `${scrubbed.slice(0, headLen)}…` : scrubbed;\n return `${head} (${sha256(command)})`;\n}\n"]}
1
+ {"version":3,"file":"minimize.js","sourceRoot":"","sources":["../src/minimize.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,6EAA6E;AAC7E,uDA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IAAY;IACrC,IAAI,GAAG,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IACjC,KAAK,MAAM,CAAC,EAAE,EAAE,WAAW,CAAC,IAAI,YAAY;QAAE,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC;IACjF,OAAO,GAAG,CAAC;AACb,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,IAAI,GAAG,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;IAC3B,KAAK,MAAM,CAAC,EAAE,EAAE,WAAW,CAAC,IAAI,UAAU;QAAE,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC;IAC/E,OAAO,GAAG,CAAC;AACb,CAAC;AAED;mFACmF;AACnF,MAAM,UAAU,aAAa,CAAC,OAAe,EAAE,OAAO,GAAG,EAAE;IACzD,MAAM,QAAQ,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;IACvC,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC;IACrF,OAAO,GAAG,IAAI,KAAK,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC;AACxC,CAAC","sourcesContent":["// Data minimization for the hook: file contents are never stored, shell commands\n// are reduced to a scrubbed head plus a digest, and common secret shapes are\n// removed before anything is written or signed (SB09).\n\nimport { createHash } from \"node:crypto\";\nimport { canonical } from \"@scopebond/policy-schema/canonical\";\n\nexport const sha256 = (value: string): string => \"sha256:\" + createHash(\"sha256\").update(value).digest(\"hex\");\nexport const digest = (value: unknown): string => sha256(canonical(value as never));\n\nconst MASK = \"***\";\n// A flag or header value: a quoted string or a run of non-whitespace.\nconst VALUE = String.raw`(\"[^\"]*\"|'[^']*'|\\S+)`;\n\n// Each rule states its own replacement. `$1` keeps a non-secret label (a flag or\n// header name); the secret itself is always dropped whole. Over-scrubbing is safe.\n// Every pattern is a single pass over simple character classes (no nested\n// quantifiers), so matching stays linear in the command length.\nconst SECRET_RULES: ReadonlyArray<readonly [RegExp, string]> = [\n [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, MASK],\n [new RegExp(String.raw`(--?(?:password|passwd|pwd|token|secret|api[-_]?key|access[-_]?key|auth|credentials?)[=\\s]+)${VALUE}`, \"gi\"), `$1${MASK}`],\n [new RegExp(String.raw`((?:^|\\s)(?:-u|--user)[=\\s]+)${VALUE}`, \"g\"), `$1${MASK}`],\n [/(Authorization:\\s*(?:Bearer|Basic|Token)\\s+)[^\\s\"']+/gi, `$1${MASK}`],\n [/((?:x-api-key|api-key|x-auth-token|x-access-token|private-token)\\s*:\\s*)[^\\s\"']+/gi, `$1${MASK}`],\n [/(:\\/\\/)[^\\s/@:]+:[^\\s/@]+@/g, `$1${MASK}@`], // URL userinfo\n [/\\bgh[pousr]_[A-Za-z0-9]{20,}/g, MASK], // GitHub tokens\n [/\\bgithub_pat_[A-Za-z0-9_]{20,}/g, MASK], // GitHub fine-grained tokens\n [/\\bglpat-[A-Za-z0-9_-]{20,}/g, MASK], // GitLab tokens\n [/\\bnpm_[A-Za-z0-9]{20,}/g, MASK], // npm tokens\n [/\\bxox[abeoprs]-[A-Za-z0-9-]{10,}/g, MASK], // Slack tokens\n [/\\b[sr]k_(?:live|test)_[A-Za-z0-9]{16,}/g, MASK], // Stripe keys\n [/\\bsk-[A-Za-z0-9_-]{20,}/g, MASK], // OpenAI/Anthropic-style keys\n [/\\bAIza[0-9A-Za-z_-]{30,}/g, MASK], // Google API keys\n [/\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b/g, MASK], // AWS access key ids\n [/\\beyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}/g, MASK], // JWTs\n];\n\n// Generic high-entropy shapes. Applied to free text only (the command head), never to\n// structured parameters a policy matches on: a long path or a commit id is not a secret.\nconst BLOB_RULES: ReadonlyArray<readonly [RegExp, string]> = [\n [/\\b[A-Fa-f0-9]{32,}\\b/g, MASK], // long hex blobs\n [/[A-Za-z0-9+/_-]{40,}={0,2}/g, MASK], // long base64/base64url blobs\n];\n\nconst SECRET_NAME = /token|secret|passw|pwd|api_?key|access_?key|private_?key|auth|credential|session/i;\n\n// `NAME=value` where the name looks like a credential (`GH_TOKEN=…`, `export\n// AWS_SECRET_ACCESS_KEY=…`). Done per whitespace-delimited word rather than with\n// one regex so a long identifier cannot cause backtracking.\nfunction scrubAssignments(text: string): string {\n return text.replace(/\\S+/g, (word) => {\n const eq = word.indexOf(\"=\");\n if (eq <= 0 || eq === word.length - 1) return word;\n const name = word.slice(0, eq);\n if (name.startsWith(\"-\") || !SECRET_NAME.test(name)) return word; // flags are handled by SECRET_RULES\n return `${name}=${MASK}`;\n });\n}\n\n/** Scrub a structured parameter (a program name, a remote, a URL path): credential\n * assignments and recognizable token shapes only, so policy matching on ordinary\n * values is unaffected. */\nexport function scrubParam(text: string): string {\n let out = scrubAssignments(text);\n for (const [re, replacement] of SECRET_RULES) out = out.replace(re, replacement);\n return out;\n}\n\n/** Scrub free text: everything `scrubParam` removes plus generic high-entropy blobs. */\nexport function scrubSecrets(text: string): string {\n let out = scrubParam(text);\n for (const [re, replacement] of BLOB_RULES) out = out.replace(re, replacement);\n return out;\n}\n\n/** A privacy-preserving representation of a shell command: a scrubbed, truncated\n * head plus a digest of the full original. The full command is never retained. */\nexport function redactCommand(command: string, headLen = 64): string {\n const scrubbed = scrubSecrets(command);\n const head = scrubbed.length > headLen ? `${scrubbed.slice(0, headLen)}…` : scrubbed;\n return `${head} (${sha256(command)})`;\n}\n"]}
package/dist/runtime.d.ts CHANGED
@@ -21,11 +21,15 @@ export interface RuntimeConfig {
21
21
  export interface Decision {
22
22
  decision: "allow" | "deny" | "not_evaluated";
23
23
  reason: string;
24
+ /** The deciding receipt (the denied one, or the first allow). */
24
25
  receipt?: unknown;
26
+ /** Every receipt produced — one per simple command in a decomposed shell call. */
27
+ receipts?: unknown[];
25
28
  }
26
29
  /** The default starter policy for a coding agent: protect release branches, deny
27
- * destructive programs, allow workspace file access, and trust only the enrolled
28
- * machine key. Every threshold is the operator's to edit. */
30
+ * destructive programs, allow workspace file access except the hook's own config
31
+ * and keys, and trust only the enrolled machine key. Every threshold is the
32
+ * operator's to edit. */
29
33
  export declare function starterPolicy(agentKid: string): Record<string, unknown>;
30
34
  /** Build the runtime. Throws on any setup failure (unparseable policy, missing
31
35
  * key, unavailable store) — the CLI turns that into a fail-closed deny. */
@@ -36,6 +40,10 @@ export declare function createHookRuntime(config: RuntimeConfig): {
36
40
  /** Deliver queued receipts to Cloud with a bounded timeout, then it is safe to
37
41
  * exit. Undelivered receipts persist in the durable outbox for the next run. */
38
42
  flush(): Promise<void>;
39
- evaluate(mapped: Mapped): Promise<Decision>;
43
+ /** Decide one mapped action, recording a receipt either way. */
44
+ evaluateOne(mapped: Mapped): Promise<Decision>;
45
+ /** Decide a whole tool call. A shell call decomposes into several simple
46
+ * commands; every one is recorded, and a single deny denies the call. */
47
+ evaluate(mapped: Mapped | Mapped[]): Promise<Decision>;
40
48
  };
41
49
  //# sourceMappingURL=runtime.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAMA,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;AAE/E,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB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AE,MAAM,CAAA;KAAE,CAAC;CACvF;AAED,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,OAAO,GAAG,MAAM,GAAG,eAAe,CAAC;IAC7C,MAAM,EAAE,MAAM,CAAC;IACf,iEAAiE;IACjE,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,kFAAkF;IAClF,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAC;CACtB;AAUD;;;0BAG0B;AAC1B,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAgCvE;AAED;4EAC4E;AAC5E,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,aAAa;;;;IAuBnD;qFACiF;aAClE,OAAO,CAAC,IAAI,CAAC;IAG5B,gEAAgE;wBACtC,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;IAapD;8EAC0E;qBACnD,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,QAAQ,CAAC;EAkB/D"}
package/dist/runtime.js CHANGED
@@ -7,9 +7,17 @@ import { createGateway, StaticPrincipalKeyRegistry } from "@scopebond/gateway";
7
7
  import { loadOrCreateAttester, openReceiptStore } from "@scopebond/gateway/node";
8
8
  import { createSigner } from "@scopebond/sdk";
9
9
  import { attachExporter, flushBounded } from "./cloud.js";
10
+ // The hook's own config and keys must be off-limits to the agent it governs:
11
+ // otherwise the agent could rewrite its policy or read the signing keys and the
12
+ // receipts stop meaning anything. These patterns are "allow if the path does NOT
13
+ // match a protected location"; they run against the cwd-relative path the mapper
14
+ // produces (and equally against an absolute one).
15
+ const PROTECTED_WRITE = "^(?!(?:.*/)?\\.scopebond/)(?!(?:.*/)?\\.claude/settings)(?!(?:.*/)?\\.cursor/hooks)(?!(?:.*/)?\\.git/hooks/).+";
16
+ const PROTECTED_READ = "^(?!(?:.*/)?\\.scopebond/)(?!.*\\.key$).+";
10
17
  /** The default starter policy for a coding agent: protect release branches, deny
11
- * destructive programs, allow workspace file access, and trust only the enrolled
12
- * machine key. Every threshold is the operator's to edit. */
18
+ * destructive programs, allow workspace file access except the hook's own config
19
+ * and keys, and trust only the enrolled machine key. Every threshold is the
20
+ * operator's to edit. */
13
21
  export function starterPolicy(agentKid) {
14
22
  return {
15
23
  vocabulary_version: "1.0", policy_id: "coding-agent", version: 1,
@@ -22,9 +30,23 @@ export function starterPolicy(agentKid) {
22
30
  {
23
31
  id: "safe-shell", type: "action_allowlist", mode: "enforce", action_types: ["shell.exec"],
24
32
  param_bounds: { program: { pattern: "^(?!(?:rm|sudo|shutdown|reboot|mkfs|dd)$).+" } },
25
- description: "Deny destructive programs (rm, sudo, …).",
33
+ description: "Deny destructive programs (rm, sudo, …). An empty program (an unparseable command) is denied.",
34
+ },
35
+ {
36
+ id: "protect-write", type: "action_allowlist", mode: "enforce", action_types: ["file.write"],
37
+ param_bounds: { path: { pattern: PROTECTED_WRITE } },
38
+ description: "Allow workspace writes, but never to the hook's policy/keys, .claude/settings, .cursor/hooks or git hooks.",
39
+ },
40
+ {
41
+ id: "protect-read", type: "action_allowlist", mode: "enforce", action_types: ["file.read"],
42
+ param_bounds: { path: { pattern: PROTECTED_READ } },
43
+ description: "Allow workspace reads, but never the signing keys (*.key) or the hook's own .scopebond directory.",
44
+ },
45
+ {
46
+ id: "observe-net-mcp", type: "action_allowlist", mode: "monitor",
47
+ action_types: ["net.fetch", "mcp.tool.call"],
48
+ description: "Observe network fetches and MCP tool calls (recorded, not blocked) — add bounds to enforce.",
26
49
  },
27
- { id: "workspace-files", type: "action_allowlist", mode: "enforce", action_types: ["file.write", "file.read"] },
28
50
  { id: "keys", type: "key_policy", active_keys: [agentKid], description: "Only the enrolled machine key may sign." },
29
51
  ],
30
52
  };
@@ -59,18 +81,44 @@ export function createHookRuntime(config) {
59
81
  if (exporter)
60
82
  await flushBounded(exporter, config.cloud?.flushTimeoutMs);
61
83
  },
62
- async evaluate(mapped) {
84
+ /** Decide one mapped action, recording a receipt either way. */
85
+ async evaluateOne(mapped) {
63
86
  const signed = agent.sign(mapped.intent);
64
87
  if (!mapped.evaluated && !config.strict) {
65
- // Unknown tool, non-strict: observe without evaluating — grants nothing (D30).
88
+ // Unknown tool or unparseable command, non-strict: observe without
89
+ // evaluating — grants nothing (D30).
66
90
  const { receipt } = await gateway.observeAction({ intent: signed.intent, authorization: signed.authorization });
67
91
  return { decision: "not_evaluated", reason: `no policy applies to ${mapped.intent.action_type}`, receipt };
68
92
  }
69
- // Evaluated tools, and (in strict mode) unmapped tool.<name> actions, go
70
- // through policy — a closed allowlist denies an unlisted action.
93
+ // Evaluated actions, and (in strict mode) unmapped tool.<name>/opaque commands,
94
+ // go through policy — a closed allowlist denies an unlisted action.
71
95
  const result = await gateway.handleAction({ intent: signed.intent, authorization: signed.authorization });
72
96
  return { decision: result.allowed ? "allow" : "deny", reason: result.reason, receipt: result.receipt };
73
97
  },
98
+ /** Decide a whole tool call. A shell call decomposes into several simple
99
+ * commands; every one is recorded, and a single deny denies the call. */
100
+ async evaluate(mapped) {
101
+ const list = Array.isArray(mapped) ? mapped : [mapped];
102
+ if (list.length === 0)
103
+ return { decision: "not_evaluated", reason: "no action", receipts: [] };
104
+ const receipts = [];
105
+ let allow = null;
106
+ let notEvaluated = null;
107
+ for (const m of list) {
108
+ const d = await this.evaluateOne(m);
109
+ if (d.receipt !== undefined)
110
+ receipts.push(d.receipt);
111
+ if (d.decision === "deny")
112
+ return { ...d, receipts }; // any deny denies the call
113
+ if (d.decision === "allow" && !allow)
114
+ allow = d;
115
+ if (d.decision === "not_evaluated" && !notEvaluated)
116
+ notEvaluated = d;
117
+ }
118
+ // No deny: allow if any command was evaluated-and-allowed, else not_evaluated.
119
+ const chosen = allow ?? notEvaluated;
120
+ return { ...chosen, receipts };
121
+ },
74
122
  };
75
123
  }
76
124
  //# sourceMappingURL=runtime.js.map