passcontrol 1.7.1 → 1.7.2

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.
@@ -96,7 +96,7 @@ const NOT_IN_A_HOSTNAME = /[\s/\\@?#]/;
96
96
  * `api.anthropic.com`, so a string comparison that treats them as different
97
97
  * hosts is a one-character bypass of the provider refusal below.
98
98
  */
99
- function normalizeHostname(value) {
99
+ export function normalizeHostname(value) {
100
100
  let host = String(value ?? "").trim().toLowerCase();
101
101
  if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1);
102
102
  if (host.endsWith(".")) host = host.slice(0, -1);
package/cli/sidecar.mjs CHANGED
@@ -9,7 +9,7 @@ import { declaredLineage, declaredSession } from "./declared-session.mjs";
9
9
  import { defaultJournalDir, openJournal } from "./journal.mjs";
10
10
  import { heldUnderTaint } from "./injection-hold.mjs";
11
11
  import { findingsFromHook, gapFromOversizedHook } from "./injection-sidecar.mjs";
12
- import { answer, createWatchFeed, isNotACall, isLocalCaller, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
12
+ import { answer, createWatchFeed, hostIsThisListener, isNotACall, isLocalCaller, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
13
13
  import { createStopGate, HOOK_PATH, SELF_READ_TIMEOUT_MS, selfAnswerState } from "./subscription-gate.mjs";
14
14
  import { createToolGate } from "./tool-gate.mjs";
15
15
  import { OTLP_LOGS_PATH, readClaudeCodeEvents } from "./otlp-logs.mjs";
@@ -212,7 +212,7 @@ export function createSidecar({
212
212
  "accept-encoding": "identity",
213
213
  };
214
214
  if (session) headers["x-claude-code-session-id"] = session;
215
- return fetch(`${origin}${path}`, { headers, signal });
215
+ return fetch(`${origin}${path}`, { headers, signal, redirect: "manual" });
216
216
  })]);
217
217
  const answer = await Promise.race([deadline, selfAnswerState(response)]);
218
218
  if (answer.state === "open") {
@@ -253,6 +253,7 @@ export function createSidecar({
253
253
  if (session) headers["x-claude-code-session-id"] = session;
254
254
  return fetch(`${origin}${TOOL_APPROVALS_PATH}`, {
255
255
  method: "POST",
256
+ redirect: "manual",
256
257
  headers,
257
258
  body,
258
259
  signal: AbortSignal.timeout(Math.min(APPROVAL_REQUEST_TIMEOUT_MS, Math.max(1_000, deadline - Date.now()))),
@@ -280,6 +281,7 @@ export function createSidecar({
280
281
  const response = await visas.fetchWithVisa((visa) =>
281
282
  fetch(`${origin}${CLIENT_EVENTS_PATH}`, {
282
283
  method: "POST",
284
+ redirect: "manual",
283
285
  headers: {
284
286
  "content-type": "application/json",
285
287
  authorization: `Bearer ${visa}`,
@@ -523,7 +525,13 @@ export function createSidecar({
523
525
  if (out.continue !== false && input.hook_event_name === "PreToolUse") {
524
526
  let tool;
525
527
  try {
526
- tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url), stopGate.injection());
528
+ // A strong local finding the gateway has not yet been read after (the read
529
+ // just failed) puts a held tool to the gateway's own taint, whatever the cached
530
+ // "clear" says: an agent that floods /self straight after reading an injection
531
+ // must not outrun its taint (cloud review 2026-11-03, SC-B). The gateway then
532
+ // decides: no taint there answers `not_ask_owner`, and the tool goes.
533
+ const unconfirmed = stopGate.injectionHoldMode() && heldUnderTaint(input.tool_name) && highVersion > readHighVersion;
534
+ tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url), unconfirmed ? "tainted" : stopGate.injection());
527
535
  } catch {
528
536
  tool = {};
529
537
  }
@@ -561,7 +569,8 @@ export function createSidecar({
561
569
  headers["x-passcontrol-run"] = runId;
562
570
  headers["x-passcontrol-proof"] = visas.createProof(visa, req.method, new URL(path, origin));
563
571
  headers["accept-encoding"] = "identity";
564
- return fetch(`${origin}${path}`, { method: req.method, headers, body: body ?? undefined });
572
+ // Hand redirects to the agent; never replay the visa, proof or body at Location.
573
+ return fetch(`${origin}${path}`, { method: req.method, headers, body: body ?? undefined, redirect: "manual" });
565
574
  }
566
575
 
567
576
  // A service call's pagination `link` and same-origin `location` name the
@@ -654,7 +663,32 @@ export function createSidecar({
654
663
  }
655
664
  }
656
665
 
666
+ // A proxied call carries this run's visa, so a web page must never get one
667
+ // (cloud review 2026-11-03, SC-A). Browsers mark what they send: an Origin on a
668
+ // cross-origin or non-GET request, and Sec-Fetch-Site on every request
669
+ // (Chrome, Firefox, Safari 16.4+). Agent clients send neither. Node's own fetch
670
+ // does send `sec-fetch-mode: cors`, so that header proves nothing and is not read.
671
+ // A DNS-rebound page sends no Origin, but its Host names the attacker's domain:
672
+ // an origin-form request on a loopback bind must name this listener exactly. A
673
+ // forward-proxy request (absolute form) names its target and goes to the classifier;
674
+ // a page cannot send one. Off loopback (an explicit opt-in) the Host is whatever the
675
+ // network calls this machine, so only the browser check applies there.
676
+ const checksHost = isLoopbackBindHost(host);
677
+ function refuseBrowserCaller(req, res, port) {
678
+ const browser = req.headers.origin !== undefined || req.headers["sec-fetch-site"] !== undefined;
679
+ const rebound = checksHost && String(req.url ?? "").startsWith("/") && !hostIsThisListener(req.headers.host, port);
680
+ if (!browser && !rebound) return false;
681
+ req.resume();
682
+ if (browser) {
683
+ answer(res, 403, "sidecar_browser_refused", "The PassControl sidecar serves agents on this machine, not web pages.");
684
+ } else {
685
+ answer(res, 403, "sidecar_host_refused", `Address the sidecar as 127.0.0.1:${port} or localhost:${port}.`);
686
+ }
687
+ return true;
688
+ }
689
+
657
690
  const server = http.createServer(async (req, res) => {
691
+ if (refuseBrowserCaller(req, res, server.address()?.port)) return;
658
692
  // The sidecar's own paths: answered here, never forwarded with a visa.
659
693
  if (String(req.url ?? "").startsWith(LOCAL_PREFIX)) {
660
694
  const localPath = String(req.url).split("?")[0];
@@ -702,6 +736,7 @@ export function createSidecar({
702
736
  // is not answered here: it goes to the gateway as `/api/version`, so an app
703
737
  // sees the gateway's real answer, including a refusal where `local` is off.
704
738
  const ollamaServer = http.createServer(async (req, res) => {
739
+ if (refuseBrowserCaller(req, res, ollamaServer.address()?.port)) return;
705
740
  if (!String(req.url ?? "").startsWith("/")) {
706
741
  req.resume();
707
742
  res.writeHead(400, { "content-type": "application/json" });
@@ -237,21 +237,35 @@ export function createStopGate({
237
237
  return warnOnce(session ?? "", reason ?? "no answer");
238
238
  }
239
239
 
240
- /** The tool rules from the latest answer, or null once they are older than `maxStaleMs`. */
240
+ /**
241
+ * The tool rules from the latest answer, however old; null only before the first.
242
+ *
243
+ * They used to lapse after `maxStaleMs`, and lapsed rules let every tool through. A
244
+ * read fails when /self's own rate limit is spent, which anything on the machine can
245
+ * do through the sidecar, so "the reads fail" switched the rules off on demand (cloud
246
+ * review 2026-11-03, SC-B). The last rules the gateway gave stay in force until it
247
+ * gives others (owner, 2026-11-04: option 1). Stops are not kept this way: those are
248
+ * the gateway's to enforce, and it does, ahead of the rate limit.
249
+ */
241
250
  function toolRules() {
242
- return rules && age(rules) <= maxStaleMs ? rules : null;
251
+ return rules;
243
252
  }
244
253
 
245
254
  function injection() {
246
255
  if (!injectionEntry || injectionEntry.value === undefined) return "off";
247
- if (age(injectionEntry) > maxStaleMs) return "unknown";
248
256
  const value = injectionEntry.value;
249
- if (!value || value.mode !== "hold" || value.readable !== true) return "unknown";
250
- if (value.tainted_until === null) return "clear";
251
- if (typeof value.tainted_until !== "string") return "unknown";
252
- const until = Date.parse(value.tainted_until);
253
- if (!Number.isFinite(until)) return "unknown";
254
- return until > now() ? "tainted" : "clear";
257
+ let state = "unknown";
258
+ if (value && value.mode === "hold" && value.readable === true) {
259
+ if (value.tainted_until === null) state = "clear";
260
+ else if (typeof value.tainted_until === "string") {
261
+ const until = Date.parse(value.tainted_until);
262
+ if (Number.isFinite(until)) state = until > now() ? "tainted" : "clear";
263
+ }
264
+ }
265
+ // A taint the gateway named holds until the end it named, read or no read (SC-B,
266
+ // as above). Any other state is only as good as its age.
267
+ if (age(injectionEntry) > maxStaleMs && state !== "tainted") return "unknown";
268
+ return state;
255
269
  }
256
270
 
257
271
  // Keep the last known mode even after max-stale: a fresh read may recover it.
@@ -25,4 +25,8 @@ export const TOOL_RULE_LIMITS: {
25
25
  };
26
26
  export function globMatch(pattern: string, text: string): boolean;
27
27
  export function parseToolRules(value: unknown): ParsedToolRules;
28
- export function evaluateToolRules(parsed: { rules: ToolRule[] }, input: ToolRuleInput): ToolRuleVerdict;
28
+ export function evaluateToolRules(
29
+ parsed: { rules: ToolRule[] },
30
+ input: ToolRuleInput,
31
+ options?: { platform?: string; caseless?: boolean }
32
+ ): ToolRuleVerdict;
@@ -25,6 +25,8 @@
25
25
  // Honest limit: these are guard rails for the owner's own sessions. `sh -c`, an alias,
26
26
  // a script file or a different tool gets round a command rule.
27
27
 
28
+ import { normalizeHostname } from "./proxy-policy.mjs";
29
+
28
30
  export const TOOL_RULE_EFFECTS = ["deny", "ask_owner", "ask"];
29
31
  const STRICTNESS = { deny: 3, ask_owner: 2, ask: 1 };
30
32
 
@@ -144,10 +146,17 @@ function normalisePath(raw) {
144
146
  }
145
147
 
146
148
  function commandPieces(command) {
149
+ // Cheap shell forms only, not a Bash parser: quoting, escapes, wrappers and
150
+ // program-specific options can still evade these guard rails.
147
151
  return command
148
- .split(/&&|\|\||[;|\n]/)
152
+ .split(/&&|\|\||\$\(|[;&|\n()`]/)
149
153
  .map((piece) => piece.trim())
150
- .filter(Boolean);
154
+ .filter(Boolean)
155
+ .flatMap((piece) => {
156
+ const stripped = piece.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|"[^"]*"|[^\s'"]*)\s+)+/, "");
157
+ return stripped === piece ? [piece] : [piece, stripped];
158
+ })
159
+ .map((piece) => piece.replace(/\s+/g, " "));
151
160
  }
152
161
 
153
162
  function toolMatches(pattern, name) {
@@ -161,14 +170,22 @@ function toolMatches(pattern, name) {
161
170
  *
162
171
  * Input a rule needs but cannot read (no command, a URL that does not parse) counts as
163
172
  * matching that rule: a rule the owner wrote is not skipped because the input was odd.
173
+ *
174
+ * Path rules ignore case where the filesystem does (cloud review 2026-11-03, SC-E):
175
+ * macOS and Windows by default, so `/users/NAS/.SSH/key` meets a deny on
176
+ * `/Users/nas/.ssh/*`. Every effect is restrictive, so this only ever makes the gate
177
+ * stricter for the sidecar. `caseless` overrides the platform; the gateway passes it
178
+ * both ways (see app/api/v1/tool-approvals), since a caseless deny must not pre-empt
179
+ * its taint hold.
164
180
  */
165
- export function evaluateToolRules(parsed, input) {
181
+ export function evaluateToolRules(parsed, input, { platform = typeof process === "undefined" ? "" : process.platform, caseless } = {}) {
182
+ const ignoreCase = caseless ?? (platform === "darwin" || platform === "win32");
166
183
  const name = typeof input?.tool_name === "string" ? input.tool_name : "";
167
184
  const toolInput = isRecord(input?.tool_input) ? input.tool_input : {};
168
185
  let best = null;
169
186
  parsed.rules.forEach((rule, ruleIndex) => {
170
187
  if (!toolMatches(rule.tool, name)) return;
171
- const subject = subjectFor(rule, name, toolInput, input);
188
+ const subject = subjectFor(rule, name, toolInput, input, ignoreCase);
172
189
  if (subject === undefined) return;
173
190
  if (!best || STRICTNESS[rule.effect] > STRICTNESS[best.effect]) best = { effect: rule.effect, ruleIndex, subject };
174
191
  });
@@ -176,7 +193,7 @@ export function evaluateToolRules(parsed, input) {
176
193
  }
177
194
 
178
195
  // The matched text, `undefined` when the rule does not apply to this input.
179
- function subjectFor(rule, name, toolInput, input) {
196
+ function subjectFor(rule, name, toolInput, input, ignoreCase) {
180
197
  if (rule.command !== undefined) {
181
198
  if (typeof toolInput.command !== "string") return "";
182
199
  return commandPieces(toolInput.command).find((piece) => globMatch(rule.command, piece));
@@ -187,20 +204,22 @@ function subjectFor(rule, name, toolInput, input) {
187
204
  if (raw === undefined && SEARCH_TOOLS.has(name) && typeof input?.cwd === "string") raw = input.cwd;
188
205
  if (raw === undefined) return "";
189
206
  const path = normalisePath(raw);
190
- return globMatch(rule.path, path) ? path : undefined;
207
+ const hit = ignoreCase ? globMatch(rule.path.toLowerCase(), path.toLowerCase()) : globMatch(rule.path, path);
208
+ return hit ? path : undefined;
191
209
  }
192
210
  if (rule.domain !== undefined) {
193
211
  let host;
194
212
  try {
195
- host = new URL(String(toolInput.url)).hostname.toLowerCase();
213
+ host = normalizeHostname(new URL(String(toolInput.url)).hostname);
196
214
  } catch {
197
215
  return "";
198
216
  }
199
- if (rule.domain.startsWith("*.")) {
200
- const base = rule.domain.slice(2);
217
+ const domain = normalizeHostname(rule.domain);
218
+ if (domain.startsWith("*.")) {
219
+ const base = domain.slice(2);
201
220
  return host === base || host.endsWith(`.${base}`) ? host : undefined;
202
221
  }
203
- return host === rule.domain ? host : undefined;
222
+ return host === domain ? host : undefined;
204
223
  }
205
224
  return name;
206
225
  }
@@ -39,6 +39,9 @@ export function createVisaClient({
39
39
  passport_id: passportId,
40
40
  ts: now(),
41
41
  nonce: randomUUID(),
42
+ // Signed, so this proof is good at the challenge door only (cloud review
43
+ // CP5). An older gateway ignores the field.
44
+ purpose: "challenge",
42
45
  // Omitted, never guessed at: every older client, the SDK and the examples
43
46
  // mint without one, and an absent claim is a state the dashboard says out
44
47
  // loud rather than a tier it assumes.
@@ -116,7 +116,7 @@ export async function peekText(body, limit = REFUSAL_PEEK_BYTES) {
116
116
  const LOOPBACK_PEER = /^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}|::1|::ffff:127\.\d{1,3}\.\d{1,3}\.\d{1,3})$/;
117
117
  const LOOPBACK_NAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
118
118
 
119
- function hostIsThisListener(hostHeader, port) {
119
+ export function hostIsThisListener(hostHeader, port) {
120
120
  if (typeof hostHeader !== "string") return false;
121
121
  const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(hostHeader.trim().toLowerCase());
122
122
  return Boolean(match && LOOPBACK_NAMES.has(match[1]) && Number(match[2]) === port);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "1.7.1",
3
+ "version": "1.7.2",
4
4
  "description": "Identity, scope and budget controls for AI agents while provider keys stay server-side.",
5
5
  "license": "BUSL-1.1",
6
6
  "homepage": "https://passcontrol.vertias.eu",
@@ -102,7 +102,14 @@ export class PassControl {
102
102
  }
103
103
  /** Sign a fresh challenge and exchange it for a visa. */
104
104
  async mint() {
105
- const payloadObj = { passport_id: this.passportId, ts: Date.now(), nonce: crypto.randomUUID() };
105
+ // `purpose` is signed, so this proof is good at one passport door only (cloud
106
+ // review CP5). An older gateway ignores the field.
107
+ const payloadObj = {
108
+ passport_id: this.passportId,
109
+ ts: Date.now(),
110
+ nonce: crypto.randomUUID(),
111
+ purpose: this.delegationChain ? "delegated" : "challenge",
112
+ };
106
113
  const payloadBytes = new TextEncoder().encode(JSON.stringify(payloadObj));
107
114
  const payload = bytesToB64url(payloadBytes);
108
115
  const signature = bytesToB64url(ed25519.sign(payloadBytes, this.secret));