passcontrol 1.7.2 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,373 @@
1
+ // Mission-bound visas (idea 11): the LOCAL-TOOL half of a mission envelope.
2
+ //
3
+ // One file for both sides, like tool-rules.mjs: the sidecar classifies a Claude Code
4
+ // PreToolUse call with it, the gateway validates a mission's `tools` section with it,
5
+ // and the replay measurement uses the same classifier on the sanitised feed. The
6
+ // three can never disagree about what an item admits.
7
+ //
8
+ // ── HONEST LIMIT, said in every copy that shows this section ────────────────────
9
+ // Hooks are a GUARD RAIL, not a boundary. The sidecar sees what Claude Code tells
10
+ // it. A script file, an alias, `sh -c`, an interpreter one-liner or a process the
11
+ // agent starts outside Claude Code gets round anything here. The gateway is the
12
+ // boundary for models and services, because it holds the credential; this file
13
+ // only adds friction to the owner's own sessions.
14
+ //
15
+ // Item vocabulary (typed, so a whole repository is ONE item, not many paths):
16
+ // { kind: "workspace", root: "/abs/dir", write: bool } file tools under root
17
+ // { kind: "shell", class: <SHELL_CLASSES> } a class of shell command
18
+ // { kind: "host", host: "exact.host", via: "web"|"browser"|"shell" }
19
+ // { kind: "tool", name: "ExactToolName" } one named tool
20
+ // { kind: "memory_write" } writes to agent memory files
21
+ //
22
+ // Classes that are NEVER admitted by a template or by history, only by the owner for
23
+ // this one mission: network, opaque, vcs_push, rm_rf, container, memory writes (NEVER_LEARNED).
24
+
25
+ export const SHELL_CLASSES = [
26
+ "inspect",
27
+ "build",
28
+ "vcs_local",
29
+ "process",
30
+ "fs_mutate",
31
+ "container",
32
+ "network",
33
+ "opaque",
34
+ "vcs_push",
35
+ "rm_rf",
36
+ ];
37
+ // container: `docker run -v /:/host` is a full escape, so a container class learned from
38
+ // history admitted it (red team round 1, L24 under strategy D).
39
+ export const NEVER_LEARNED = new Set(["shell:network", "shell:opaque", "shell:vcs_push", "shell:rm_rf", "shell:container", "memory_write"]);
40
+ export const HOST_VIA = ["web", "browser", "shell"];
41
+
42
+ const INSPECT = new Set(
43
+ "cd ls cat head tail grep rg egrep fgrep sed awk wc find echo pwd which file stat diff sort uniq cut tr jq less more tree du df date true false test [ printf basename dirname realpath readlink type command whoami uname hostname id cmp comm column nl od xxd shasum sha256sum md5 md5sum base64 strings".split(" ")
44
+ );
45
+ const BUILD = new Set(
46
+ "npm npx node python python3 pip pip3 tsc vitest jest make cargo go deno bun pnpm yarn pytest ruff eslint prettier psql sqlite3 swift xcodebuild gradle mvn java javac ruby bundle rake".split(" ")
47
+ );
48
+ const PROCESS = new Set("kill pkill ps lsof sleep wait jobs pgrep top fg bg disown".split(" "));
49
+ const FS_MUTATE = new Set("cp mv mkdir touch rm rmdir ln chmod chown tee install unzip tar gzip gunzip zip".split(" "));
50
+ const CONTAINER = new Set("docker docker-compose podman kubectl colima".split(" "));
51
+ const NETWORK = new Set("curl wget gh ssh scp sftp rsync nc ncat telnet ftp open http https dig nslookup ping".split(" "));
52
+ // A command that runs ANOTHER command or arbitrary code is opaque: what it does is not
53
+ // in its first word.
54
+ const OPAQUE = new Set(
55
+ "bash sh zsh dash fish eval exec source . env sudo doas xargs nohup timeout time watch nice osascript perl for while until if case function select coproc { (".split(" ")
56
+ );
57
+
58
+ /** Tools that act only on the agent's own task list, plans or questions to the owner. */
59
+ export const INTERNAL_TOOLS = new Set([
60
+ "TaskCreate",
61
+ "TaskUpdate",
62
+ "TaskGet",
63
+ "TaskList",
64
+ "TaskStop",
65
+ "TaskOutput",
66
+ "TodoWrite",
67
+ "ToolSearch",
68
+ "AskUserQuestion",
69
+ "ReadNotifications",
70
+ "Monitor",
71
+ "ListAgents",
72
+ "EnterPlanMode",
73
+ "ExitPlanMode",
74
+ "BashOutput",
75
+ "KillShell",
76
+ ]);
77
+ const READ_TOOLS = new Set(["Read", "Glob", "Grep", "LS", "NotebookRead"]);
78
+ const WRITE_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
79
+ const PATH_FIELD = { Read: "file_path", Edit: "file_path", MultiEdit: "file_path", Write: "file_path", NotebookEdit: "notebook_path", Glob: "path", Grep: "path", LS: "path", NotebookRead: "notebook_path" };
80
+ const BROWSER_NAV = /^mcp__claude-in-chrome__navigate$/u;
81
+
82
+ const HOST = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/u;
83
+ const TOOL_NAME = /^[A-Za-z0-9_.-]{1,128}$/u;
84
+ const MEMORY_FILE = /(?:^|\/)(?:CLAUDE\.md|CLAUDE\.local\.md|AGENTS\.md|MEMORY\.md|\.claude\/(?:settings(?:\.local)?\.json|memory\/[^/]+|agents\/[^/]+|commands\/[^/]+|skills\/.+))$/u;
85
+
86
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
87
+
88
+ /** An absolute, normalised POSIX directory: no `.`/`..`, no `//`, no trailing `/`, not `/`. */
89
+ export function validRoot(root) {
90
+ if (typeof root !== "string" || root.length < 2 || root.length > 1024 || !root.startsWith("/")) return false;
91
+ if (root.endsWith("/") || root.includes("//") || root.includes("\\") || /[\u0000-\u001f\u007f]/u.test(root)) return false;
92
+ const parts = root.slice(1).split("/");
93
+ return parts.every((p) => p !== "" && p !== "." && p !== "..");
94
+ }
95
+
96
+ /** Lexical normalisation of an absolute path. Null when it is not absolute or escapes /. */
97
+ export function normalisePath(path) {
98
+ if (typeof path !== "string" || !path.startsWith("/") || path.length > 4096) return null;
99
+ if (path.includes("\\") || /[\u0000-\u001f\u007f]/u.test(path)) return null;
100
+ const out = [];
101
+ for (const part of path.split("/")) {
102
+ if (part === "" || part === ".") continue;
103
+ if (part === "..") {
104
+ if (out.length === 0) return null;
105
+ out.pop();
106
+ continue;
107
+ }
108
+ out.push(part);
109
+ }
110
+ return `/${out.join("/")}`;
111
+ }
112
+
113
+ /** Is `path` (already normalised) `root` itself or under it, on a segment boundary? */
114
+ export function within(root, path) {
115
+ return path === root || path.startsWith(`${root}/`);
116
+ }
117
+
118
+ export function normaliseHost(raw) {
119
+ if (typeof raw !== "string") return null;
120
+ let host = raw.trim().toLowerCase();
121
+ if (host.endsWith(".")) host = host.slice(0, -1);
122
+ return HOST.test(host) ? host : null;
123
+ }
124
+
125
+ /** A single tool item, validated. Returns a fresh canonical object or null. */
126
+ export function parseToolItem(item) {
127
+ if (!isRecord(item)) return null;
128
+ const keys = Object.keys(item).sort().join(",");
129
+ switch (item.kind) {
130
+ case "workspace":
131
+ if (keys !== "kind,root,write" || !validRoot(item.root) || typeof item.write !== "boolean") return null;
132
+ return { kind: "workspace", root: item.root, write: item.write };
133
+ case "shell":
134
+ if (keys !== "class,kind" || !SHELL_CLASSES.includes(item.class)) return null;
135
+ return { kind: "shell", class: item.class };
136
+ case "host":
137
+ if (keys !== "host,kind,via" || !HOST_VIA.includes(item.via)) return null;
138
+ if (typeof item.host !== "string" || normaliseHost(item.host) !== item.host) return null;
139
+ return { kind: "host", host: item.host, via: item.via };
140
+ case "tool":
141
+ if (keys !== "kind,name" || typeof item.name !== "string" || !TOOL_NAME.test(item.name)) return null;
142
+ return { kind: "tool", name: item.name };
143
+ case "memory_write":
144
+ if (keys !== "kind") return null;
145
+ return { kind: "memory_write" };
146
+ default:
147
+ return null;
148
+ }
149
+ }
150
+
151
+ /** Does item `outer` admit everything item `inner` admits? Conservative: unknown → false. */
152
+ export function toolItemContains(outer, inner) {
153
+ if (!outer || !inner || outer.kind !== inner.kind) return false;
154
+ switch (outer.kind) {
155
+ case "workspace":
156
+ return within(outer.root, inner.root) && (outer.write || !inner.write);
157
+ case "shell":
158
+ return outer.class === inner.class;
159
+ case "host":
160
+ return outer.host === inner.host && outer.via === inner.via;
161
+ case "tool":
162
+ return outer.name === inner.name;
163
+ case "memory_write":
164
+ return true;
165
+ default:
166
+ return false;
167
+ }
168
+ }
169
+
170
+ /** A stable key for an item, used for sets and for "learned from history". */
171
+ export function toolItemKey(item) {
172
+ switch (item.kind) {
173
+ case "workspace":
174
+ return `workspace:${item.write ? "rw" : "r"}:${item.root}`;
175
+ case "shell":
176
+ return `shell:${item.class}`;
177
+ case "host":
178
+ return `host:${item.via}:${item.host}`;
179
+ case "tool":
180
+ return `tool:${item.name}`;
181
+ case "memory_write":
182
+ return "memory_write";
183
+ default:
184
+ return "unknown";
185
+ }
186
+ }
187
+
188
+ /** The shell class of one simple command's first word (after assignments). */
189
+ export function shellClassOf(word) {
190
+ if (typeof word !== "string" || word === "") return "opaque";
191
+ const base = word.includes("/") ? word.slice(word.lastIndexOf("/") + 1) : word;
192
+ if (base === "git") return "vcs_local";
193
+ if (INSPECT.has(base)) return "inspect";
194
+ if (BUILD.has(base)) return "build";
195
+ if (PROCESS.has(base)) return "process";
196
+ if (FS_MUTATE.has(base)) return "fs_mutate";
197
+ if (CONTAINER.has(base)) return "container";
198
+ if (NETWORK.has(base)) return "network";
199
+ if (OPAQUE.has(base)) return "opaque";
200
+ return "opaque";
201
+ }
202
+
203
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/u;
204
+ // An interpreter handed code inline runs whatever that code says, so it is opaque, not
205
+ // a build step (red team round 1: `python3 -c "urlopen(evil)"` was admitted as build).
206
+ const INTERPRETERS = new Set(["python", "python3", "node", "perl", "ruby", "php", "deno", "bun", "osascript", "pwsh", "powershell"]);
207
+ const INLINE_CODE = new Set(["-c", "-e", "--eval", "-p", "--print", "-r", "-m", "-E", "-x", "eval", "--command"]);
208
+ const REDIRECT = /^(?:\d?[<>]{1,2}|&>|<<<?)$/u;
209
+
210
+ /**
211
+ * Does an interpreter invocation run code the hook cannot see in its arguments?
212
+ * Inline code (-c, -e, --eval=…, combined -Ic), code from STDIN (no script argument,
213
+ * `-`, /dev/stdin: `echo … | python3`, `python3 - < x`), or code from a URL
214
+ * (`deno run https://…`). Red team round 3 found the stdin and URL forms admitted as
215
+ * build. A script FILE (`python3 x.py`) stays build: what the file does is the named
216
+ * guard-rail limit (RED-TEAM.md L30).
217
+ */
218
+ function interpreterRunsUnseenCode(rest) {
219
+ if (rest.length === 1 && ["--version", "-v", "-V", "--help"].includes(rest[0])) return false;
220
+ if (rest.some((a) => INLINE_CODE.has(a) || /^-[a-zA-Z]*[ce]$/u.test(a) || /^--(?:eval|print|command)=/u.test(a))) return true;
221
+ if (rest.some((a) => /^['"]?https?:\/\//u.test(a))) return true;
222
+ const positional = [];
223
+ for (let i = 0; i < rest.length; i++) {
224
+ const a = rest[i];
225
+ if (REDIRECT.test(a)) {
226
+ i++; // the redirect's target is not a script
227
+ continue;
228
+ }
229
+ if (/^[<>]/u.test(a)) continue; // `<file` written without a space
230
+ if (a.startsWith("-") && a !== "-") continue;
231
+ positional.push(a);
232
+ }
233
+ if (positional.length === 0) return true;
234
+ // `deno run x.ts`, `bun run x`: the subcommand is not the script.
235
+ const script = ["run", "x", "exec"].includes(positional[0]) ? positional[1] : positional[0];
236
+ return script === undefined || script === "-" || script === "/dev/stdin";
237
+ }
238
+
239
+ /**
240
+ * Split a shell command into simple commands and classify each. Deliberately
241
+ * pessimistic: command substitution, backticks, process substitution, a heredoc or
242
+ * an unbalanced quote make the WHOLE command opaque, because what runs is not in
243
+ * the words we can see. Returns the set of items the command needs.
244
+ */
245
+ export function classifyShell(command) {
246
+ const items = new Map();
247
+ const add = (cls) => items.set(`shell:${cls}`, { kind: "shell", class: cls });
248
+ if (typeof command !== "string" || command.length === 0 || command.length > 100_000) {
249
+ add("opaque");
250
+ return [...items.values()];
251
+ }
252
+ if (/\$\(|`|<\(|>\(|<<|\beval\b/u.test(command)) add("opaque");
253
+ // Quote-aware split on ; & | && || and newlines.
254
+ const segments = [];
255
+ let current = "";
256
+ let quote = null;
257
+ for (let i = 0; i < command.length; i++) {
258
+ const c = command[i];
259
+ if (quote) {
260
+ if (c === quote) quote = null;
261
+ else if (c === "\\" && quote === '"') {
262
+ current += c + (command[i + 1] ?? "");
263
+ i++;
264
+ continue;
265
+ }
266
+ current += c;
267
+ continue;
268
+ }
269
+ if (c === "'" || c === '"') {
270
+ quote = c;
271
+ current += c;
272
+ continue;
273
+ }
274
+ if (c === "\\") {
275
+ current += c + (command[i + 1] ?? "");
276
+ i++;
277
+ continue;
278
+ }
279
+ if (c === ";" || c === "&" || c === "|" || c === "\n") {
280
+ segments.push(current);
281
+ current = "";
282
+ continue;
283
+ }
284
+ current += c;
285
+ }
286
+ if (quote) add("opaque");
287
+ segments.push(current);
288
+ for (const segment of segments) {
289
+ const words = segment.trim().split(/\s+/u).filter(Boolean);
290
+ let w = 0;
291
+ while (w < words.length && ASSIGNMENT.test(words[w])) w++;
292
+ if (w >= words.length) continue; // assignments only, or empty
293
+ const first = words[w].replace(/^['"]|['"]$/gu, "");
294
+ const rest = words.slice(w + 1);
295
+ const base = first.includes("/") ? first.slice(first.lastIndexOf("/") + 1) : first;
296
+ const inline = INTERPRETERS.has(base) && interpreterRunsUnseenCode(rest);
297
+ const cls = inline ? "opaque" : shellClassOf(first);
298
+ if (first === "git" && rest.includes("push")) add("vcs_push");
299
+ else if ((first === "rm" || first.endsWith("/rm")) && rest.some((a) => /^-[a-zA-Z]*[rR][a-zA-Z]*$/u.test(a) || a === "--recursive")) add("rm_rf");
300
+ else add(cls);
301
+ if (cls === "network") {
302
+ for (const arg of rest) {
303
+ const m = /^['"]?https?:\/\/([^/:'"\s?#]+)/u.exec(arg);
304
+ const host = m ? normaliseHost(m[1]) : null;
305
+ if (host) items.set(`host:shell:${host}`, { kind: "host", host, via: "shell" });
306
+ }
307
+ }
308
+ // An append or write to a memory file through the shell.
309
+ if (rest.some((a, i) => (a === ">>" || a === ">") && MEMORY_FILE.test(rest[i + 1] ?? "")) || rest.some((a) => /^>>?\S/u.test(a) && MEMORY_FILE.test(a.replace(/^>>?/u, "")))) {
310
+ items.set("memory_write", { kind: "memory_write" });
311
+ }
312
+ }
313
+ if (items.size === 0) add("inspect");
314
+ return [...items.values()];
315
+ }
316
+
317
+ /**
318
+ * Every item a PreToolUse call needs. A call with no recognisable shape needs the
319
+ * item for its tool name, so an unknown tool is held until the owner names it.
320
+ */
321
+ export function itemsForToolCall(input) {
322
+ const tool = typeof input?.tool_name === "string" ? input.tool_name : "";
323
+ const ti = isRecord(input?.tool_input) ? input.tool_input : {};
324
+ if (tool === "Bash") return classifyShell(typeof ti.command === "string" ? ti.command : "");
325
+ if (READ_TOOLS.has(tool) || WRITE_TOOLS.has(tool)) {
326
+ const field = PATH_FIELD[tool];
327
+ const raw = typeof ti[field] === "string" ? ti[field] : READ_TOOLS.has(tool) && tool !== "Read" ? null : "";
328
+ const write = WRITE_TOOLS.has(tool);
329
+ if (raw === null) return [{ kind: "tool", name: tool }]; // Glob/Grep with no path: the cwd, unknown here
330
+ const path = normalisePath(raw);
331
+ if (path === null) return [{ kind: "tool", name: `${tool}:unresolved-path` }];
332
+ const items = [{ kind: "workspace", root: path, write }];
333
+ if (write && MEMORY_FILE.test(path)) items.push({ kind: "memory_write" });
334
+ return items;
335
+ }
336
+ if (tool === "WebFetch") {
337
+ let host = null;
338
+ try {
339
+ host = normaliseHost(new URL(String(ti.url ?? "")).hostname);
340
+ } catch {
341
+ host = null;
342
+ }
343
+ return [host ? { kind: "host", host, via: "web" } : { kind: "tool", name: "WebFetch:unresolved-host" }];
344
+ }
345
+ if (BROWSER_NAV.test(tool)) {
346
+ let host = null;
347
+ try {
348
+ host = normaliseHost(new URL(String(ti.url ?? "")).hostname);
349
+ } catch {
350
+ host = null;
351
+ }
352
+ return [host ? { kind: "host", host, via: "browser" } : { kind: "tool", name: `${tool}:unresolved-host` }];
353
+ }
354
+ if (TOOL_NAME.test(tool)) return [{ kind: "tool", name: tool }];
355
+ return [{ kind: "tool", name: "unknown-tool" }];
356
+ }
357
+
358
+ /** Items a mission admits for free: the agent's own task list. Never effects. */
359
+ export function internalItem(item) {
360
+ return item.kind === "tool" && INTERNAL_TOOLS.has(item.name);
361
+ }
362
+
363
+ /**
364
+ * The decision for a tool call against a mission's `tools` section.
365
+ * `inside` when every needed item is contained in some mission item; otherwise
366
+ * `outside` with the items that were missing. Workspace items of the CALL carry the
367
+ * exact path as `root`, so containment is "the path is under an admitted root".
368
+ */
369
+ export function evaluateMissionTools(missionTools, input) {
370
+ const needed = itemsForToolCall(input);
371
+ const missing = needed.filter((n) => !internalItem(n) && !missionTools.some((m) => toolItemContains(m, n)));
372
+ return missing.length ? { state: "outside", missing } : { state: "inside", missing: [] };
373
+ }
package/cli/presets.mjs CHANGED
@@ -51,7 +51,7 @@ export const SERVICE_ENV = {
51
51
  "# GitHub REST through PassControl. What this agent may do is set on its page in the",
52
52
  "# dashboard, under GitHub access; the workspace's GitHub token stays in PassControl.",
53
53
  ],
54
- usage: "# Octokit: new Octokit({ baseUrl: process.env.GITHUB_API_URL }) — and no auth option.",
54
+ usage: "# Octokit: new Octokit({ baseUrl: process.env.GITHUB_API_URL, auth: process.env.PASSCONTROL_SIDECAR_KEY })",
55
55
  },
56
56
  telegram: {
57
57
  label: "Telegram",
@@ -60,7 +60,7 @@ export const SERVICE_ENV = {
60
60
  "# Telegram Bot API through PassControl. What this agent may do is set on its page in the",
61
61
  "# dashboard, under Telegram access; the bot token stays in PassControl.",
62
62
  ],
63
- usage: '# Call a method by name, with no token in the URL: curl "$TELEGRAM_API_URL/getMe"',
63
+ usage: '# Call a method by name, with no bot token in the URL: curl -H "x-api-key: $PASSCONTROL_SIDECAR_KEY" "$TELEGRAM_API_URL/getMe"',
64
64
  },
65
65
  brave: {
66
66
  label: "Brave Search",
@@ -69,7 +69,7 @@ export const SERVICE_ENV = {
69
69
  "# Brave Search through PassControl. What this agent may search is set on its page in the",
70
70
  "# dashboard, under Brave Search access; the API key stays in PassControl. Brave bills per search.",
71
71
  ],
72
- usage: '# Search with no key header: curl "$BRAVE_SEARCH_API_URL/web/search?q=passcontrol"',
72
+ usage: '# Search with the sidecar key, not a Brave key: curl -H "x-api-key: $PASSCONTROL_SIDECAR_KEY" "$BRAVE_SEARCH_API_URL/web/search?q=passcontrol"',
73
73
  },
74
74
  notion: {
75
75
  label: "Notion",
@@ -78,7 +78,7 @@ export const SERVICE_ENV = {
78
78
  "# Notion through PassControl. What this agent may do is set on its page in the dashboard,",
79
79
  "# under Notion access; the integration token stays in PassControl.",
80
80
  ],
81
- usage: "# @notionhq/client: new Client({ baseUrl: process.env.NOTION_API_URL }) — and no auth option.",
81
+ usage: "# @notionhq/client: new Client({ baseUrl: process.env.NOTION_API_URL, auth: process.env.PASSCONTROL_SIDECAR_KEY })",
82
82
  },
83
83
  discord: {
84
84
  label: "Discord",
@@ -87,7 +87,7 @@ export const SERVICE_ENV = {
87
87
  "# Discord's bot API through PassControl. What this agent may do is set on its page in the",
88
88
  "# dashboard, under Discord access; the bot token stays in PassControl.",
89
89
  ],
90
- usage: '# discord.js: new REST({ api: process.env.DISCORD_API_URL, version: "10" }).setToken("sidecar") — any token; the sidecar replaces it.',
90
+ usage: '# discord.js: new REST({ api: process.env.DISCORD_API_URL, version: "10" }).setToken(process.env.PASSCONTROL_SIDECAR_KEY)',
91
91
  },
92
92
  };
93
93
 
package/cli/protocols.mjs CHANGED
@@ -5,7 +5,8 @@ export const CONTROL_API_PROTOCOL = { minimum: 1, maximum: 1 };
5
5
  export const GATEWAY_API_PROTOCOL = { minimum: 1, maximum: 1 };
6
6
  // 3 (Bet D, 2026-10-10): a WORKER's receipt, auth.kind "delegated". Moved so a verifier
7
7
  // that predates delegation refuses it as too new instead of rendering it as passport-signed.
8
- export const RECEIPT_PROTOCOL = { minimum: 1, maximum: 3 };
8
+ // 4: an ending sent by the gateway on the owner's stop. Older verifiers must refuse it.
9
+ export const RECEIPT_PROTOCOL = { minimum: 1, maximum: 4 };
9
10
  export const AGENT_TOKEN_PROTOCOL = { minimum: 1, maximum: 1 };
10
11
  export const WORKSPACE_EXPORT_PROTOCOL = { minimum: 1, maximum: 1 };
11
12
 
@@ -0,0 +1,83 @@
1
+ // The sidecar's own key (review C-03, 2026-11-15).
2
+ //
3
+ // The sidecar holds the agent's passport and attaches a visa to what it forwards. It
4
+ // refuses web pages, but until this release it asked a local program for nothing, and
5
+ // a loopback port is shared by every user account on the machine. So a second user,
6
+ // or a process deliberately denied the passport file, could spend inside the agent's
7
+ // scope and budget through it.
8
+ //
9
+ // Now every forwarded call must present this key, in any header an API client puts
10
+ // its key in (Authorization Bearer, x-api-key, api-key, x-goog-api-key, or the
11
+ // password of a proxy URL). It is derived from the passport secret, so:
12
+ // - nothing new is stored: whoever can read the passport can compute it, which is
13
+ // exactly who may use the sidecar already;
14
+ // - the sidecar and `passcontrol env` / `configure` compute the same value;
15
+ // - rotating the passport changes it (re-run `passcontrol env` or `configure`).
16
+ // It is NOT a provider key and grants nothing at the gateway: the sidecar strips it
17
+ // before forwarding, like every credential header.
18
+ //
19
+ // The old public placeholder ("passcontrol-sidecar", "passcontrol") is refused: it is
20
+ // printed in the docs, so accepting it would leave the gap open.
21
+ import { createHmac, timingSafeEqual } from "node:crypto";
22
+
23
+ export const SIDECAR_KEY_PREFIX = "pcs_";
24
+ const LABEL = "passcontrol-sidecar-local-v1";
25
+
26
+ /** The key callers must present to a sidecar running with this passport secret. */
27
+ export function sidecarKey(passportSecret) {
28
+ const secret = String(passportSecret ?? "");
29
+ if (!secret) return null;
30
+ return `${SIDECAR_KEY_PREFIX}${createHmac("sha256", Buffer.from(secret, "utf8")).update(LABEL).digest("base64url")}`;
31
+ }
32
+
33
+ /** Looks like a sidecar key this CLI wrote (for finding and undoing its own settings). */
34
+ export function isSidecarKey(value) {
35
+ return typeof value === "string" && value.startsWith(SIDECAR_KEY_PREFIX);
36
+ }
37
+
38
+ const CREDENTIAL_HEADER = /(^|[-_])(api[-_]?key|authorization|auth|token|secret|credentials?)$/i;
39
+
40
+ /** Every value a caller could have meant as its key, from any credential-shaped header. */
41
+ export function presentedKeys(headers = {}) {
42
+ const out = [];
43
+ for (const [name, raw] of Object.entries(headers)) {
44
+ if (!CREDENTIAL_HEADER.test(name)) continue;
45
+ for (const value of Array.isArray(raw) ? raw : [raw]) {
46
+ if (typeof value !== "string") continue;
47
+ const v = value.trim();
48
+ const space = v.indexOf(" ");
49
+ const scheme = space > 0 ? v.slice(0, space).toLowerCase() : "";
50
+ const rest = space > 0 ? v.slice(space + 1).trim() : v;
51
+ if (scheme === "basic") {
52
+ // A proxy URL's credentials (HTTP_PROXY=http://user:<key>@127.0.0.1:8788).
53
+ let decoded = "";
54
+ try {
55
+ decoded = Buffer.from(rest, "base64").toString("utf8");
56
+ } catch {
57
+ decoded = "";
58
+ }
59
+ const colon = decoded.indexOf(":");
60
+ if (colon >= 0) out.push(decoded.slice(0, colon), decoded.slice(colon + 1));
61
+ else if (decoded) out.push(decoded);
62
+ } else {
63
+ // The whole value (x-api-key: <key>), and after any scheme word too:
64
+ // "Bearer <key>", Octokit's "token <key>", discord.js's "Bot <key>".
65
+ out.push(v);
66
+ if (scheme) out.push(rest);
67
+ }
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+
73
+ /** True when some header carries `expected`. Compared in constant time per candidate. */
74
+ export function presentsSidecarKey(headers, expected) {
75
+ if (!expected) return false;
76
+ const want = Buffer.from(expected, "utf8");
77
+ let found = false;
78
+ for (const candidate of presentedKeys(headers)) {
79
+ const got = Buffer.from(candidate, "utf8");
80
+ if (got.length === want.length && timingSafeEqual(got, want)) found = true;
81
+ }
82
+ return found;
83
+ }