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.
package/cli/sidecar.mjs CHANGED
@@ -9,12 +9,16 @@ 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 { plantedDigests } from "./tripwires.mjs";
13
+ import { createTripwireReporter, decoyInHeaders, decoysInHook, TRIPWIRE_PATH } from "./tripwire-sidecar.mjs";
12
14
  import { answer, createWatchFeed, hostIsThisListener, isNotACall, isLocalCaller, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
13
15
  import { createStopGate, HOOK_PATH, SELF_READ_TIMEOUT_MS, selfAnswerState } from "./subscription-gate.mjs";
14
16
  import { createToolGate } from "./tool-gate.mjs";
15
17
  import { OTLP_LOGS_PATH, readClaudeCodeEvents } from "./otlp-logs.mjs";
16
18
  import { CLIENT_EVENTS_PATH, CLIENT_EVENTS_SOURCE, createCallUploader } from "./client-events-upload.mjs";
17
19
  import { heldUsageWindow, WINDOW_PATH } from "./usage-window.mjs";
20
+ import { createMemoryCustody } from "./memory-custody-sidecar.mjs";
21
+ import { presentsSidecarKey, sidecarKey } from "./sidecar-token.mjs";
18
22
 
19
23
  // Hop-by-hop headers plus the ones the sidecar rebuilds itself. `proxy-connection`
20
24
  // and friends only appear once something is used as a FORWARD proxy, which is
@@ -46,6 +50,31 @@ const STRIP_REQ = new Set([
46
50
  // machine at all, since not sending the key IS the sidecar.
47
51
  const CREDENTIAL_HEADER = /(^|[-_])(api[-_]?key|authorization|auth|token|secret|credentials?)$/i;
48
52
 
53
+ /** What a caller without the sidecar's key is told (review C-03). */
54
+ const SIDECAR_KEY_HELP =
55
+ "This sidecar only forwards calls that present its key. On this machine run `passcontrol env <client>` " +
56
+ "(or `passcontrol configure claude-code|codex --write`) and use the API key it prints. The old placeholder no longer works.";
57
+
58
+ // A hook call without the key (review C-03 follow-up). Claude Code treats an HTTP error
59
+ // from a hook as "carry on", so a 401 here would quietly switch the tool gate off for
60
+ // anyone whose settings predate the key. Instead it gets a 2xx answer that stops the
61
+ // session and refuses the tool, and nothing in it is scanned, reported or decided.
62
+ const KEYLESS_HOOK_REASON =
63
+ "PassControl refused this hook call: it carries no sidecar key. Run `passcontrol configure claude-code --write` " +
64
+ "(or `passcontrol configure codex --write`) again on this machine, then restart the session.";
65
+
66
+ export function keylessHookAnswer(head) {
67
+ const event = /"hook_event_name"\s*:\s*"([A-Za-z]{1,40})"/u.exec(String(head ?? ""))?.[1] ?? "";
68
+ const out = { continue: false, stopReason: KEYLESS_HOOK_REASON };
69
+ if (event === "PreToolUse") {
70
+ out.hookSpecificOutput = { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: KEYLESS_HOOK_REASON };
71
+ } else {
72
+ out.decision = "block";
73
+ out.reason = KEYLESS_HOOK_REASON;
74
+ }
75
+ return out;
76
+ }
77
+
49
78
  function isStripped(name) {
50
79
  const key = name.toLowerCase();
51
80
  return STRIP_REQ.has(key) || CREDENTIAL_HEADER.test(key);
@@ -158,11 +187,17 @@ export function createSidecar({
158
187
  // Subscription mode, Phase 1b: upload the calls Claude Code reports to the
159
188
  // gateway's agent page (cli/client-events-upload.mjs). `--no-report-calls` turns it off.
160
189
  reportCalls = true,
190
+ // Idea 12: the digests of the decoys `configure tripwires` planted on this machine.
191
+ // Read once at start; a re-run of configure takes effect on the next sidecar start.
192
+ tripwireDigests = plantedDigests(),
161
193
  }) {
162
194
  // The upstream URL below is built from this, not from the argument: the
163
195
  // sidecar forwards a bearer visa on every proxied request, so its destination
164
196
  // is part of the credential's security rather than a formatting detail.
165
197
  const origin = bareGatewayOrigin(gateway);
198
+ // Review C-03: what a local caller must present before anything is forwarded with
199
+ // this run's visa (cli/sidecar-token.mjs). Derived from the passport, never stored.
200
+ const callerKey = sidecarKey(passportSecret);
166
201
  const visas = createVisaClient({
167
202
  gateway: origin,
168
203
  passportId,
@@ -216,6 +251,7 @@ export function createSidecar({
216
251
  })]);
217
252
  const answer = await Promise.race([deadline, selfAnswerState(response)]);
218
253
  if (answer.state === "open") {
254
+ memoryCustody.setView(answer.memory);
219
255
  readHighVersion = Math.max(readHighVersion, highAtStart);
220
256
  readRelayVersion = Math.max(readRelayVersion, relayAtStart);
221
257
  if (answer.injection?.mode === "hold" && !reportCalls && !holdOptOutWarned) {
@@ -230,6 +266,29 @@ export function createSidecar({
230
266
  }
231
267
  const stopGate = createStopGate({ readSelf, dashboardUrl: `${origin}/dashboard` });
232
268
 
269
+ // Idea 13: memory custody (cli/memory-custody-sidecar.mjs). Hashes and kinds only.
270
+ const MEMORY_CUSTODY_PATH = "/api/v1/memory-custody";
271
+ const MEMORY_CUSTODY_TIMEOUT_MS = 4_000;
272
+ async function sendMemoryCustody(payload) {
273
+ const response = await visas.fetchWithVisa((visa) =>
274
+ fetch(`${origin}${MEMORY_CUSTODY_PATH}`, {
275
+ method: "POST",
276
+ redirect: "manual",
277
+ headers: {
278
+ "content-type": "application/json",
279
+ authorization: `Bearer ${visa}`,
280
+ "x-passcontrol-run": runId,
281
+ "x-passcontrol-proof": visas.createProof(visa, "POST", new URL(MEMORY_CUSTODY_PATH, origin)),
282
+ "accept-encoding": "identity",
283
+ },
284
+ body: JSON.stringify(payload),
285
+ signal: AbortSignal.timeout(MEMORY_CUSTODY_TIMEOUT_MS),
286
+ })
287
+ );
288
+ return { status: response.status, body: await response.json().catch(() => null) };
289
+ }
290
+ const memoryCustody = createMemoryCustody({ send: sendMemoryCustody, onWarn: (m) => warn(m) });
291
+
233
292
  // Phase 2's `ask_owner` tool rules: the gateway asks the owner (their alert
234
293
  // destination is in its Vault) and holds each request a few seconds; this asks
235
294
  // again until the owner answers or the tool gate's wait runs out.
@@ -311,6 +370,36 @@ export function createSidecar({
311
370
  }
312
371
  const injectionSeen = new Set();
313
372
  const uploader = reportCalls ? createCallUploader({ send: sendReportedCalls }) : null;
373
+ // Idea 12. Reports go as this agent, through the same visa path as every upload.
374
+ async function sendTripwire(body) {
375
+ const response = await visas.fetchWithVisa((visa) =>
376
+ fetch(`${origin}${TRIPWIRE_PATH}`, {
377
+ method: "POST",
378
+ redirect: "manual",
379
+ headers: {
380
+ "content-type": "application/json",
381
+ authorization: `Bearer ${visa}`,
382
+ "x-passcontrol-run": runId,
383
+ "x-passcontrol-proof": visas.createProof(visa, "POST", new URL(TRIPWIRE_PATH, origin)),
384
+ "accept-encoding": "identity",
385
+ },
386
+ body: JSON.stringify(body),
387
+ signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
388
+ })
389
+ );
390
+ return { status: response.status };
391
+ }
392
+ const tripwires = tripwireDigests.size > 0 ? createTripwireReporter({ send: sendTripwire }) : null;
393
+ const lastTools = [];
394
+ const TOOL_NAME = /^[A-Za-z0-9_.-]{1,128}$/;
395
+ function noteTools(input) {
396
+ const calls = input.hook_event_name === "PostToolBatch" && Array.isArray(input.tool_calls) ? input.tool_calls : [input];
397
+ for (const c of calls) {
398
+ if (typeof c?.tool_name === "string" && TOOL_NAME.test(c.tool_name)) lastTools.push(c.tool_name);
399
+ }
400
+ while (lastTools.length > 5) lastTools.shift();
401
+ }
402
+ const recentTools = () => [...lastTools];
314
403
  // Its decisions reach the agent's page with the reported calls (same opt-out).
315
404
  const toolGate = createToolGate({
316
405
  askOwner,
@@ -444,6 +533,36 @@ export function createSidecar({
444
533
  res.end();
445
534
  }
446
535
 
536
+ // Idea 13: `passcontrol memory review` asks here, from this machine only.
537
+ const MEMORY_REVIEW_PATH = "/_passcontrol/memory";
538
+ async function serveMemoryReview(req, res) {
539
+ const port = server.address()?.port;
540
+ req.resume();
541
+ if (req.method !== "GET") return answer(res, 405, "method_not_allowed", "GET only.");
542
+ if (!isLocalCaller(req, port)) return answer(res, 403, "memory_refused", "For this machine only.");
543
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
544
+ const cwd = url.searchParams.get("cwd");
545
+ if (!cwd || !cwd.startsWith("/")) return answer(res, 400, "memory_cwd", "Pass the workspace as ?cwd=/absolute/path.");
546
+ const out = await memoryCustody.review(cwd, url.searchParams.get("client") === "codex" ? "codex" : "claude-code").catch(() => ({ state: "unavailable", items: [] }));
547
+ const body = JSON.stringify(out);
548
+ res.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
549
+ res.end(body);
550
+ }
551
+
552
+ function refuseKeylessHook(req, res) {
553
+ // Only the start is kept, for the event name; the rest is drained, never parsed.
554
+ let head = "";
555
+ req.on("data", (c) => {
556
+ if (head.length < HOOK_PEEK_BYTES) head += c.toString("utf8").slice(0, HOOK_PEEK_BYTES - head.length);
557
+ });
558
+ req.on("end", () => {
559
+ const body = JSON.stringify(keylessHookAnswer(head));
560
+ res.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
561
+ res.end(body);
562
+ });
563
+ req.on("error", () => res.destroy());
564
+ }
565
+
447
566
  function serveHook(req, res) {
448
567
  const port = server.address()?.port;
449
568
  if (req.method !== "POST") {
@@ -500,6 +619,18 @@ export function createSidecar({
500
619
  // Bounded by HOOK_BODY_LIMIT; 8 MB of hostile text scans in under half a second
501
620
  // (measured 2026-10-31). Only the upload is asynchronous.
502
621
  if (input.hook_event_name === "PostToolBatch" || input.hook_event_name === "PostToolUse") {
622
+ // Idea 12: a planted decoy in what a tool returned to the model is Seen. Digests
623
+ // only leave; the upload is not awaited and never changes the hook answer.
624
+ if (tripwires) {
625
+ try {
626
+ noteTools(input);
627
+ const seenDecoys = decoysInHook(input, tripwireDigests);
628
+ if (seenDecoys.length) tripwires.seen(seenDecoys).catch(() => {});
629
+ tripwires.heartbeat().catch(() => {});
630
+ } catch {
631
+ // Local telemetry must never change the hook answer.
632
+ }
633
+ }
503
634
  try {
504
635
  for (const event of findingsFromHook(input, { seen: injectionSeen })) {
505
636
  // A gap holds like a strong finding (1.7.1).
@@ -513,6 +644,14 @@ export function createSidecar({
513
644
  // Local telemetry must never change the hook answer.
514
645
  }
515
646
  }
647
+ // Idea 13: memory custody sees the event first, so a check that arms the hold has
648
+ // armed it before the tool gate decides this very tool.
649
+ const hookParams = new URL(req.url ?? "/", "http://127.0.0.1").searchParams;
650
+ await memoryCustody.hook(input, {
651
+ client: hookParams.get("client") === "codex" ? "codex" : "claude-code",
652
+ // API mode's own hooks (configure writes `mode=api` on its tool hook, `note=only` on its prompt hook).
653
+ api: hookParams.get("mode") === "api" || hookParams.get("note") === "only",
654
+ });
516
655
  let out;
517
656
  try {
518
657
  if (input.hook_event_name === "PreToolUse") await freshInjectionFor(input.tool_name);
@@ -531,7 +670,7 @@ export function createSidecar({
531
670
  // must not outrun its taint (cloud review 2026-11-03, SC-B). The gateway then
532
671
  // decides: no taint there answers `not_ask_owner`, and the tool goes.
533
672
  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());
673
+ tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url), unconfirmed ? "tainted" : stopGate.injection(), memoryCustody.state(input.session_id));
535
674
  } catch {
536
675
  tool = {};
537
676
  }
@@ -545,6 +684,31 @@ export function createSidecar({
545
684
  req.on("error", () => res.destroy());
546
685
  }
547
686
 
687
+ // Idea 13, API mode: the tool results and memory sections a model request carries.
688
+ // Bounded: past the wait the call goes on and the hold is armed (fail closed).
689
+ async function memoryCustodyOfRequest(req, body) {
690
+ if (!body || memoryCustody.state() === "off") return null;
691
+ const session = lineageOf(req.headers)?.session;
692
+ const withhold = memoryCustody.mode() === "withhold";
693
+ if (body.length > 16 * 1024 * 1024) return withhold ? memoryCustody.fallback(session, null) : null;
694
+ let parsed;
695
+ try {
696
+ parsed = JSON.parse(body.toString("utf8"));
697
+ } catch {
698
+ return null; // not a JSON model request: there is no memory in it to cut
699
+ }
700
+ if (!session && !withhold) return null;
701
+ let timer;
702
+ const result = await Promise.race([
703
+ memoryCustody.modelRequest(session, parsed).then((b) => ({ done: true, b })),
704
+ new Promise((resolve) => { timer = setTimeout(() => resolve({ done: false }), 5_000); }),
705
+ ]).finally(() => clearTimeout(timer));
706
+ // Withhold mode never forwards what it did not finish checking: on a timeout every memory
707
+ // section is cut and the session is held (fail closed).
708
+ const next = result.done ? result.b : withhold ? memoryCustody.fallback(session, parsed) : null;
709
+ return next ? Buffer.from(JSON.stringify(next)) : null;
710
+ }
711
+
548
712
  const localBaseUrl = () => {
549
713
  const address = server?.listening ? server.address() : null;
550
714
  return `http://${host}:${address?.port ?? port}`;
@@ -692,7 +856,16 @@ export function createSidecar({
692
856
  // The sidecar's own paths: answered here, never forwarded with a visa.
693
857
  if (String(req.url ?? "").startsWith(LOCAL_PREFIX)) {
694
858
  const localPath = String(req.url).split("?")[0];
859
+ // Review C-03 follow-up: the sidecar's own paths ask for the key too. The hook
860
+ // reports tool output and files approvals with the visa, the receiver reports
861
+ // calls, and the rest show what the agent did.
862
+ if (!presentsSidecarKey(req.headers, callerKey)) {
863
+ if (localPath === HOOK_PATH && req.method === "POST") return void refuseKeylessHook(req, res);
864
+ req.resume();
865
+ return answer(res, 401, "sidecar_caller_unauthenticated", SIDECAR_KEY_HELP);
866
+ }
695
867
  if (localPath === HOOK_PATH) return serveHook(req, res);
868
+ if (localPath === MEMORY_REVIEW_PATH) return void serveMemoryReview(req, res);
696
869
  if (localPath === OTLP_LOGS_PATH) return serveOtlpLogs(req, res);
697
870
  if (localPath === WINDOW_PATH) return serveWindow(req, res);
698
871
  feed.serve(req, res, { port: server.address()?.port });
@@ -712,9 +885,35 @@ export function createSidecar({
712
885
 
713
886
  let watch = null;
714
887
  try {
888
+ // Idea 12: a planted decoy in a credential header is Used. The sidecar would strip
889
+ // it and send its own visa, so the gateway would never see it: refuse here with the
890
+ // answer an unknown key gets, and report it first, so the stop happens before the
891
+ // answer. A report that fails still refuses; nothing is forwarded either way.
892
+ // Read from the headers only, so it runs before the body and before the key check
893
+ // below: a caller without the key who presents a decoy still trips the wire.
894
+ const decoy = tripwires ? decoyInHeaders(req.headers, tripwireDigests, isStripped) : null;
895
+ if (decoy) {
896
+ req.resume();
897
+ await tripwires.used(decoy, recentTools());
898
+ feed.record({ outcome: "denied", code: "invalid_credential", status: 401, lineage: lineageOf(req.headers), startedAt });
899
+ res.writeHead(401, { "content-type": "application/json" });
900
+ res.end(JSON.stringify({ error: "invalid_credential" }));
901
+ return;
902
+ }
903
+ // Review C-03: a local caller must present this sidecar's key, or nothing is
904
+ // forwarded with the visa. Checked before the body is read, so a refused caller
905
+ // cannot make the sidecar buffer it.
906
+ if (!presentsSidecarKey(req.headers, callerKey)) {
907
+ req.resume();
908
+ feed.record({ outcome: "denied", code: "sidecar_caller_unauthenticated", status: 401, lineage: lineageOf(req.headers), startedAt });
909
+ answer(res, 401, "sidecar_caller_unauthenticated", SIDECAR_KEY_HELP);
910
+ return;
911
+ }
715
912
  const body = await readBody(req);
716
913
  watch = watchCall(req, verdict.path, body, startedAt);
717
- const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, verdict.path, body, visa));
914
+ // Idea 13: in withhold mode the body may come back with pending memory cut out.
915
+ const sent = (await memoryCustodyOfRequest(req, body)) ?? body;
916
+ const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, verdict.path, sent, visa));
718
917
  writeResponse(res, upstream, req.headers, watch);
719
918
  } catch (e) {
720
919
  upstreamFailed(res, watch, req, verdict.path, e);
@@ -850,13 +1049,17 @@ export function startSidecar(opts) {
850
1049
  if (ollamaPort != null) {
851
1050
  ollamaServer.listen(ollamaPort, host, () => {
852
1051
  step(`Ollama API (local models) on http://${host}:${ollamaPort}: set OLLAMA_HOST=${host}:${ollamaPort}`);
1052
+ // Review C-03: OLLAMA_HOST is host:port only, so an Ollama client cannot send a key,
1053
+ // and this port cannot ask for one. Said out loud rather than left implied.
1054
+ step(" Any program on this machine can use that port, inside this agent's scope and budget.");
853
1055
  });
854
1056
  }
855
1057
  server.listen(port, host, () => {
856
1058
  step(`PassControl visa sidecar forwarding to ${gateway}`);
857
1059
  step(`Listening on http://${host}:${port}`);
858
1060
  step(`Point your agent at: http://${host}:${port}/api/v1/anthropic (or /api/v1/openai)`);
859
- step("API key = anything (ignored). Visa is minted + refreshed automatically.");
1061
+ step("API key = this sidecar's key: `passcontrol env <client>` prints it. Other callers are refused.");
1062
+ step("Visa is minted + refreshed automatically.");
860
1063
  step(
861
1064
  journal
862
1065
  ? `Journal: ${journal.path} (receipt ids, times, statuses and declared sessions only; --no-journal turns it off)`
@@ -46,6 +46,7 @@ function writeCache(file, nowMs, line) {
46
46
  export async function statuslineText({
47
47
  port,
48
48
  host = "127.0.0.1",
49
+ sidecarKey = null,
49
50
  cacheFile,
50
51
  now = () => Date.now(),
51
52
  fetch: fetchImpl = globalThis.fetch,
@@ -61,7 +62,8 @@ export async function statuslineText({
61
62
  let response;
62
63
  try {
63
64
  response = await fetchImpl(`http://${host}:${port}/api/v1/self`, {
64
- headers: { accept: "application/json" },
65
+ // The sidecar's key (review C-03): /api/v1/self is forwarded with the visa.
66
+ headers: { accept: "application/json", ...(sidecarKey ? { authorization: `Bearer ${sidecarKey}` } : {}) },
65
67
  signal: controller.signal,
66
68
  });
67
69
  } catch {
@@ -139,12 +141,13 @@ export function readStatusInput(stream = process.stdin, waitMs = STDIN_WAIT_MS)
139
141
  * Hands the usage window to the sidecar, for `watch` and `/passcontrol`. Best effort:
140
142
  * a sidecar that is not running only means the boards do not show it.
141
143
  */
142
- export async function postUsageWindow({ port, host = "127.0.0.1", window, fetch: fetchImpl = globalThis.fetch, timeoutMs = 500 }) {
144
+ export async function postUsageWindow({ port, host = "127.0.0.1", window, sidecarKey = null, fetch: fetchImpl = globalThis.fetch, timeoutMs = 500 }) {
143
145
  if (!window) return;
144
146
  try {
145
147
  const response = await fetchImpl(`http://${host}:${port}${WINDOW_PATH}`, {
146
148
  method: "POST",
147
- headers: { "content-type": "application/json" },
149
+ // The sidecar's own paths ask for its key too (review C-03 follow-up).
150
+ headers: { "content-type": "application/json", ...(sidecarKey ? { authorization: `Bearer ${sidecarKey}` } : {}) },
148
151
  body: JSON.stringify(window),
149
152
  signal: AbortSignal.timeout(timeoutMs),
150
153
  });
@@ -158,9 +161,9 @@ export async function postUsageWindow({ port, host = "127.0.0.1", window, fetch:
158
161
  * The status line with the usage window, when Claude Code sent one: the budget line
159
162
  * may come from the cache, the window is always this run's. Never throws.
160
163
  */
161
- export async function statuslineWithWindow({ input, port, host = "127.0.0.1", fetch: fetchImpl = globalThis.fetch, budgetLine }) {
164
+ export async function statuslineWithWindow({ input, port, host = "127.0.0.1", sidecarKey = null, fetch: fetchImpl = globalThis.fetch, budgetLine }) {
162
165
  const window = readUsageWindow(input);
163
- const [line] = await Promise.all([budgetLine(), postUsageWindow({ port, host, window, fetch: fetchImpl })]);
166
+ const [line] = await Promise.all([budgetLine(), postUsageWindow({ port, host, window, sidecarKey, fetch: fetchImpl })]);
164
167
  const text = usageWindowText(window, { short: true });
165
168
  return text ? `${line} · ${text}` : line;
166
169
  }
@@ -206,9 +209,12 @@ export function notInPathText(remoteHost) {
206
209
  const row = ([label, value]) => ` ${label.padEnd(11)} ${value}`;
207
210
 
208
211
  /** The usage window the sidecar holds, as short text, or "". Never throws. */
209
- async function readSidecarWindow({ host, port, fetch: fetchImpl, signal }) {
212
+ async function readSidecarWindow({ host, port, sidecarKey = null, fetch: fetchImpl, signal }) {
210
213
  try {
211
- const response = await fetchImpl(`http://${host}:${port}${WINDOW_PATH}`, { headers: { accept: "application/json" }, signal });
214
+ const response = await fetchImpl(`http://${host}:${port}${WINDOW_PATH}`, {
215
+ headers: { accept: "application/json", ...(sidecarKey ? { authorization: `Bearer ${sidecarKey}` } : {}) },
216
+ signal,
217
+ });
212
218
  if (!response.ok) {
213
219
  await response.body?.cancel().catch(() => {});
214
220
  return "";
@@ -228,6 +234,7 @@ async function readSidecarWindow({ host, port, fetch: fetchImpl, signal }) {
228
234
  export async function statusPanelText({
229
235
  port,
230
236
  host = "127.0.0.1",
237
+ sidecarKey = null,
231
238
  gateway,
232
239
  session = null,
233
240
  subscription = false,
@@ -236,6 +243,7 @@ export async function statusPanelText({
236
243
  }) {
237
244
  const dashboard = `${String(gateway ?? "").replace(/\/+$/, "")}/dashboard`;
238
245
  const headers = { accept: "application/json" };
246
+ if (sidecarKey) headers.authorization = `Bearer ${sidecarKey}`;
239
247
  if (typeof session === "string" && DECLARED_SESSION.test(session)) headers["x-claude-code-session-id"] = session;
240
248
 
241
249
  const controller = new AbortController();
@@ -293,7 +301,7 @@ export async function statusPanelText({
293
301
  if (typeof self?.budget !== "object" || self.budget === null) return "PassControl · unreadable answer";
294
302
  const agentId = typeof self.agent_id === "string" && UUID.test(self.agent_id) ? self.agent_id : null;
295
303
  const title = `PassControl${agentId ? ` · agent ${agentId.slice(0, 8)}` : ""}${limitReached(self) ? " · LIMIT REACHED" : paused(self) ? " · PAUSED" : ""}`;
296
- const window = subscription ? await readSidecarWindow({ host, port, fetch: fetchImpl, signal: controller.signal }) : "";
304
+ const window = subscription ? await readSidecarWindow({ host, port, sidecarKey, fetch: fetchImpl, signal: controller.signal }) : "";
297
305
  return [
298
306
  title,
299
307
  "",
@@ -146,7 +146,12 @@ export function createStopGate({
146
146
  if (answer.state === "open" && answer.self) latest = { self: answer.self, at: now() };
147
147
  if (answer.state === "open") {
148
148
  injectionEntry = { value: answer.injection, at: now() };
149
- rules = { read: answer.toolRules && typeof answer.toolRules === "object" ? answer.toolRules : { state: "none" }, at: now() };
149
+ rules = {
150
+ read: answer.toolRules && typeof answer.toolRules === "object" ? answer.toolRules : { state: "none" },
151
+ at: now(),
152
+ // Idea 11: the mission's local-tool section, when the agent is on one.
153
+ ...(answer.mission && typeof answer.mission === "object" ? { mission: answer.mission } : {}),
154
+ };
150
155
  }
151
156
  if (["open", "stopped"].includes(answer.state) || (session !== null && answer.state === "session_stopped")) {
152
157
  record(session, answer.state);
@@ -284,6 +289,9 @@ export async function selfAnswerState(response) {
284
289
  const toolRules = body && typeof body === "object" ? body.tool_rules : undefined;
285
290
  const answer = toolRules && typeof toolRules === "object" ? { state: "open", toolRules } : { state: "open" };
286
291
  if (body && typeof body === "object" && Object.hasOwn(body, "injection")) answer.injection = body.injection;
292
+ if (body && typeof body === "object" && body.mission && typeof body.mission === "object") answer.mission = body.mission;
293
+ // Idea 13: the memory hold (absent when the owner has memory custody off).
294
+ if (body && typeof body === "object" && Object.hasOwn(body, "memory")) answer.memory = body.memory;
287
295
  // The limits and the soft pause, for the agent's note; nothing else from the answer is kept.
288
296
  if (body && typeof body === "object" && body.budget && typeof body.budget === "object") {
289
297
  const kept = (v) => (v && typeof v === "object" ? v : null);
package/cli/tool-gate.mjs CHANGED
@@ -27,6 +27,7 @@
27
27
  // page: tool name, decision, rule number and wait. Never the command, path or URL.
28
28
  import { underTaint } from "./injection-hold.mjs";
29
29
  import { evaluateToolRules, parseToolRules } from "./tool-rules.mjs";
30
+ import { evaluateMissionTools, toolItemKey } from "./mission-tools.mjs";
30
31
 
31
32
  /** The wait ends this long before Claude Code would give up on the hook. */
32
33
  export const HOOK_MARGIN_S = 30;
@@ -86,8 +87,9 @@ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Da
86
87
  * The rules from the latest trusted /self read, or null.
87
88
  * @param {number | null} hookTimeoutS What the hook's URL says it waits; null when it does not say.
88
89
  * @param {"off" | "clear" | "tainted" | "unknown"} injection
90
+ * @param {"off" | "clear" | "held"} memory idea 13: unresolved memory arrivals hold the same tools
89
91
  */
90
- async function decide(input, rulesEntry, hookTimeoutS, injection = "off") {
92
+ async function decide(input, rulesEntry, hookTimeoutS, injection = "off", memory = "off") {
91
93
  if (input?.hook_event_name !== "PreToolUse") return {};
92
94
  if (needsRefresh || refreshing) {
93
95
  if (!refreshing) {
@@ -114,10 +116,13 @@ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Da
114
116
  }
115
117
 
116
118
  const original = evaluateToolRules(parsed, input);
117
- const hit = injection === "tainted" ? underTaint(original, input.tool_name) : original;
119
+ const hit = injection === "tainted" || memory === "held" ? underTaint(original, input.tool_name) : original;
118
120
  const escalated = hit.reason === "injection_taint";
119
121
  // `/self` says only that the agent is tainted, not why: a tell, or output not fully checked (1.7.1).
120
- const guardText = "This tool was held by the injection guard: something the agent recently read looked like a prompt injection, or could not be fully checked.";
122
+ const guardText =
123
+ injection !== "tainted" && memory === "held"
124
+ ? "This tool was held by memory custody: the agent's memory files have entries waiting for the owner's review (they arrived with no custody record, or were written while outside content was in its context)."
125
+ : "This tool was held by the injection guard: something the agent recently read looked like a prompt injection, or could not be fully checked.";
121
126
  let warning = {};
122
127
  if (injection === "unknown" && (injectionWarnedAt === null || now() - injectionWarnedAt >= WARN_EVERY_MS)) {
123
128
  injectionWarnedAt = now();
@@ -129,6 +134,43 @@ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Da
129
134
  try { onHold({ tool: String(input.tool_name ?? "").slice(0, 128), outcome }); } catch {}
130
135
  }
131
136
  }
137
+ // Idea 11: the agent's mission, local-tool section. A GUARD RAIL, not a boundary
138
+ // (cli/mission-tools.mjs says why). Only adds friction where the rules above are
139
+ // not already stricter: a deny stays a deny, an ask_owner still asks the owner.
140
+ // Outside an enforcing mission the call holds through Claude Code's own prompt;
141
+ // shadow mode records what it would have held and changes nothing.
142
+ const mission = rulesEntry?.mission;
143
+ if (mission && (hit.effect === null || hit.effect === "ask") && !escalated) {
144
+ // Mission-only (R11-01): between missions nothing is standing authority, so every
145
+ // tool the rules do not already decide holds here, as the gateway holds services.
146
+ if (mission.only === true && mission.state === "none") {
147
+ record(input, "mission_outside", null, 0);
148
+ return withWarning(
149
+ verdict(
150
+ "ask",
151
+ "PassControl: this agent works only on missions, and none is in force. Confirm it here if you meant it; a mission is approved by the owner. This check is a guard rail on this machine, not a boundary."
152
+ )
153
+ );
154
+ }
155
+ if (mission.state === "ok" && Array.isArray(mission.tools)) {
156
+ const judged = evaluateMissionTools(mission.tools, input);
157
+ if (judged.state === "outside" && mission.mode === "enforce") {
158
+ record(input, "mission_outside", null, 0);
159
+ const what = judged.missing.map((item) => toolItemKey(item)).join(", ");
160
+ return withWarning(
161
+ verdict(
162
+ "ask",
163
+ `PassControl: this is outside this agent's mission (${short(what)}). Confirm it here if you meant it; widening the mission itself needs the owner. This check is a guard rail on this machine, not a boundary.`
164
+ )
165
+ );
166
+ }
167
+ if (judged.state === "outside") record(input, "mission_would_hold", null, 0);
168
+ } else if (mission.state === "unknown" && (warnedAt === null || now() - warnedAt >= WARN_EVERY_MS)) {
169
+ warnedAt = now();
170
+ warning = { ...warning, systemMessage: "PassControl could not read this agent's mission yet, so this goes ahead. The gateway still enforces it for models and services." };
171
+ }
172
+ }
173
+
132
174
  const ruleIndex = escalated ? null : hit.ruleIndex;
133
175
  if (hit.effect === null) return withWarning({});
134
176
  const rule = escalated ? "injection guard" : `rule ${hit.ruleIndex + 1}`;
@@ -0,0 +1,20 @@
1
+ export interface DecoyCandidates {
2
+ candidates: string[];
3
+ truncated: boolean;
4
+ }
5
+ export const TRIPWIRE_SCAN_LIMITS: Readonly<{
6
+ maxCandidates: number;
7
+ maxDepth: number;
8
+ streamWindow: number;
9
+ streamTail: number;
10
+ seam: number;
11
+ }>;
12
+ /** A credential header's value, plus its decoded HTTP Basic credentials when it is Basic auth. */
13
+ export function credentialHeaderTexts(raw: unknown): string[];
14
+ export function findDecoyCandidates(text: string): DecoyCandidates;
15
+ export function candidatesInJson(value: unknown): DecoyCandidates & { gaps: ("depth_limit" | "candidate_limit")[] };
16
+ export function createStreamCandidateFinder(): {
17
+ push(fragment: string): void;
18
+ finish(): DecoyCandidates;
19
+ retained(): number;
20
+ };