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/README.md +11 -2
- package/bin/passcontrol.mjs +169 -28
- package/cli/claude-code.mjs +55 -29
- package/cli/codex-hooks.mjs +8 -5
- package/cli/codex.mjs +12 -6
- package/cli/config.mjs +10 -1
- package/cli/login.mjs +80 -22
- package/cli/logout.mjs +14 -2
- package/cli/lowered-keys.mjs +67 -0
- package/cli/memory-custody-sidecar.d.mts +19 -0
- package/cli/memory-custody-sidecar.mjs +470 -0
- package/cli/memory-custody.d.mts +24 -0
- package/cli/memory-custody.mjs +444 -0
- package/cli/memory-inventory.d.mts +15 -0
- package/cli/memory-inventory.mjs +390 -0
- package/cli/memory-review.d.mts +3 -0
- package/cli/memory-review.mjs +70 -0
- package/cli/menu.mjs +1 -0
- package/cli/mission-tools.d.mts +27 -0
- package/cli/mission-tools.mjs +373 -0
- package/cli/presets.mjs +5 -5
- package/cli/protocols.mjs +2 -1
- package/cli/sidecar-token.mjs +83 -0
- package/cli/sidecar.mjs +206 -3
- package/cli/statusline.mjs +16 -8
- package/cli/subscription-gate.mjs +9 -1
- package/cli/tool-gate.mjs +45 -3
- package/cli/tripwire-scan.d.mts +20 -0
- package/cli/tripwire-scan.mjs +279 -0
- package/cli/tripwire-sidecar.d.mts +10 -0
- package/cli/tripwire-sidecar.mjs +84 -0
- package/cli/tripwires.d.mts +21 -0
- package/cli/tripwires.mjs +208 -0
- package/cli/verify.mjs +29 -2
- package/cli/watch.mjs +14 -6
- package/cli/write-approval.mjs +103 -0
- package/package.json +1 -1
- package/sdk/verify.d.ts +13 -3
- package/sdk/verify.js +24 -4
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
// Tripwire decoy candidates (idea 12; research/idea-12-tripwire/).
|
|
2
|
+
//
|
|
3
|
+
// Shared by the gateway (lib/tripwire/*, edge runtime) and the local sidecar, so it is
|
|
4
|
+
// plain JavaScript with no Node built-ins and no hashing: the caller hashes each
|
|
5
|
+
// candidate and asks its registry. A candidate is NOT a finding. Only an exact digest
|
|
6
|
+
// match against a registered decoy is, so a false candidate costs one lookup and can
|
|
7
|
+
// never raise a Seen on its own. That is why this file errs towards proposing too much:
|
|
8
|
+
// no word boundaries (junk glued to a decoy must not hide it), and every decoding layer
|
|
9
|
+
// the design claims is tried.
|
|
10
|
+
//
|
|
11
|
+
// Forms covered (research/idea-12-tripwire/RESULTS.md, S2): plain; JSON \u escapes;
|
|
12
|
+
// percent-encoding; base64 (standard and url-safe, any byte alignment, line-wrapped); hex
|
|
13
|
+
// (either case); one of the first two layers around one of the last two; a decoy split across
|
|
14
|
+
// two ADJACENT string leaves of one JSON body; a decoy split across stream chunks.
|
|
15
|
+
// Forms NOT covered are listed there as accepted limits (compression, encryption,
|
|
16
|
+
// line-wrapped base64, any transformation the agent invents, splits across requests).
|
|
17
|
+
//
|
|
18
|
+
// Linear time: one indexOf pass per signature per layer, and each hit inspects a
|
|
19
|
+
// fixed-size window. Bounded output: at most `maxCandidates` unique candidates, and a
|
|
20
|
+
// truncation is reported, never silently dropped.
|
|
21
|
+
|
|
22
|
+
const PREFIX = "pc_agent_";
|
|
23
|
+
const SECRET_LENGTH = 43;
|
|
24
|
+
const DECOY_LENGTH = PREFIX.length + SECRET_LENGTH; // 52
|
|
25
|
+
const SECRET_CHAR = /^[A-Za-z0-9_-]$/;
|
|
26
|
+
|
|
27
|
+
export const TRIPWIRE_SCAN_LIMITS = Object.freeze({
|
|
28
|
+
maxCandidates: 512,
|
|
29
|
+
maxDepth: 64,
|
|
30
|
+
// Longer than the longest single-decoy encoding this file reads: \u-escaped is 6
|
|
31
|
+
// characters a byte (312), percent-encoded base64 of a decoy is ~216.
|
|
32
|
+
streamWindow: 4096,
|
|
33
|
+
streamTail: 640,
|
|
34
|
+
// Characters of each adjacent leaf joined to find a decoy split across two leaves.
|
|
35
|
+
seam: 640,
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const B64_STD = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
39
|
+
const B64_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
40
|
+
const B64_VALUE = new Map();
|
|
41
|
+
for (let i = 0; i < 64; i++) {
|
|
42
|
+
B64_VALUE.set(B64_STD[i], i);
|
|
43
|
+
B64_VALUE.set(B64_URL[i], i);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function encodeBase64(bytes, alphabet) {
|
|
47
|
+
let out = "";
|
|
48
|
+
for (let i = 0; i + 2 < bytes.length; i += 3) {
|
|
49
|
+
const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
|
|
50
|
+
out += alphabet[(n >> 18) & 63] + alphabet[(n >> 12) & 63] + alphabet[(n >> 6) & 63] + alphabet[n & 63];
|
|
51
|
+
}
|
|
52
|
+
return out; // whole groups only: the trailing partial group depends on what follows
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// For each byte alignment k (bytes of the 3-byte group before the prefix), the base64
|
|
56
|
+
// characters of the prefix that do not depend on its neighbours, and how many
|
|
57
|
+
// characters into the group they start.
|
|
58
|
+
const PREFIX_BYTES = Array.from(PREFIX, (c) => c.charCodeAt(0));
|
|
59
|
+
const B64_SIGNATURES = [];
|
|
60
|
+
for (const alphabet of [B64_STD, B64_URL]) {
|
|
61
|
+
for (let k = 0; k < 3; k++) {
|
|
62
|
+
const enc = encodeBase64([...new Array(k).fill(0), ...PREFIX_BYTES], alphabet);
|
|
63
|
+
const skip = k === 0 ? 0 : k + 1; // chars touched by the k leading bytes
|
|
64
|
+
const signature = enc.slice(skip);
|
|
65
|
+
if (!B64_SIGNATURES.some((s) => s.signature === signature)) B64_SIGNATURES.push({ signature, k, skip });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const HEX_SIGNATURE = Array.from(PREFIX, (c) => c.charCodeAt(0).toString(16).padStart(2, "0")).join("");
|
|
69
|
+
|
|
70
|
+
function isSecret(text, start) {
|
|
71
|
+
if (start + SECRET_LENGTH > text.length) return false;
|
|
72
|
+
for (let i = start; i < start + SECRET_LENGTH; i++) {
|
|
73
|
+
if (!SECRET_CHAR.test(text[i])) return false;
|
|
74
|
+
}
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Collects unique candidates up to the cap. */
|
|
79
|
+
class Sink {
|
|
80
|
+
constructor(limit = TRIPWIRE_SCAN_LIMITS.maxCandidates) {
|
|
81
|
+
this.limit = limit;
|
|
82
|
+
this.set = new Set();
|
|
83
|
+
this.truncated = false;
|
|
84
|
+
}
|
|
85
|
+
add(candidate) {
|
|
86
|
+
if (this.set.has(candidate)) return;
|
|
87
|
+
if (this.set.size >= this.limit) {
|
|
88
|
+
this.truncated = true;
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
this.set.add(candidate);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function scanPlain(text, sink) {
|
|
96
|
+
for (let at = text.indexOf(PREFIX); at !== -1; at = text.indexOf(PREFIX, at + 1)) {
|
|
97
|
+
const start = at + PREFIX.length;
|
|
98
|
+
if (isSecret(text, start)) sink.add(text.slice(at, start + SECRET_LENGTH));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function decodeBase64Window(text, from, chars) {
|
|
103
|
+
const bytes = [];
|
|
104
|
+
let acc = 0;
|
|
105
|
+
let bits = 0;
|
|
106
|
+
for (let i = from; i < from + chars && i < text.length; i++) {
|
|
107
|
+
const v = B64_VALUE.get(text[i]);
|
|
108
|
+
if (v === undefined) break;
|
|
109
|
+
acc = (acc << 6) | v;
|
|
110
|
+
bits += 6;
|
|
111
|
+
if (bits >= 8) {
|
|
112
|
+
bits -= 8;
|
|
113
|
+
bytes.push((acc >> bits) & 0xff);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return String.fromCharCode(...bytes);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function scanBase64(text, sink) {
|
|
120
|
+
// A decoy needs the k leading bytes plus 52: ceil((k + 52) / 3) groups.
|
|
121
|
+
for (const { signature, k, skip } of B64_SIGNATURES) {
|
|
122
|
+
for (let at = text.indexOf(signature); at !== -1; at = text.indexOf(signature, at + 1)) {
|
|
123
|
+
const groupStart = at - skip;
|
|
124
|
+
if (groupStart < 0) continue;
|
|
125
|
+
const chars = Math.ceil((k + DECOY_LENGTH) / 3) * 4;
|
|
126
|
+
const decoded = decodeBase64Window(text, groupStart, chars);
|
|
127
|
+
const value = decoded.slice(k, k + DECOY_LENGTH);
|
|
128
|
+
if (value.startsWith(PREFIX) && isSecret(value, PREFIX.length)) sink.add(value);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function scanHex(text, sink) {
|
|
134
|
+
const lower = text.toLowerCase();
|
|
135
|
+
for (let at = lower.indexOf(HEX_SIGNATURE); at !== -1; at = lower.indexOf(HEX_SIGNATURE, at + 1)) {
|
|
136
|
+
if (at + DECOY_LENGTH * 2 > lower.length) continue;
|
|
137
|
+
let value = "";
|
|
138
|
+
for (let i = 0; i < DECOY_LENGTH; i++) {
|
|
139
|
+
const pair = lower.slice(at + i * 2, at + i * 2 + 2);
|
|
140
|
+
if (!/^[0-9a-f]{2}$/.test(pair)) break;
|
|
141
|
+
value += String.fromCharCode(parseInt(pair, 16));
|
|
142
|
+
}
|
|
143
|
+
if (value.length === DECOY_LENGTH && isSecret(value, PREFIX.length)) sink.add(value);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function unescapeJson(text) {
|
|
148
|
+
if (!text.includes("\\")) return null;
|
|
149
|
+
// Any number of backslashes before the u: JSON inside a JSON string escapes the escape
|
|
150
|
+
// (`\\u0070`), and that is how a nested tool result arrives (S2 suite, red team R3-07).
|
|
151
|
+
const out = text.replace(/\\+u([0-9a-fA-F]{4})/g, (_, h) => String.fromCharCode(parseInt(h, 16))).replace(/\\+\//g, "/");
|
|
152
|
+
return out === text ? null : out;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function decodePercent(text) {
|
|
156
|
+
if (!text.includes("%")) return null;
|
|
157
|
+
const out = text.replace(/%([0-9a-fA-F]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16)));
|
|
158
|
+
return out === text ? null : out;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function scanLayers(text, sink) {
|
|
162
|
+
const layers = [text];
|
|
163
|
+
// Line-wrapped base64 or hex (MIME's 76 columns, `base64` without -w0, PEM-style): the
|
|
164
|
+
// same text with line breaks removed. Red team R1-06.
|
|
165
|
+
if (text.includes("\n") || text.includes("\r")) {
|
|
166
|
+
const unwrapped = text.replace(/[\r\n]+/g, "");
|
|
167
|
+
if (unwrapped !== text) layers.push(unwrapped);
|
|
168
|
+
}
|
|
169
|
+
const json = unescapeJson(text);
|
|
170
|
+
if (json !== null) layers.push(json);
|
|
171
|
+
const percent = decodePercent(text);
|
|
172
|
+
if (percent !== null) layers.push(percent);
|
|
173
|
+
for (const layer of layers) {
|
|
174
|
+
scanPlain(layer, sink);
|
|
175
|
+
scanBase64(layer, sink);
|
|
176
|
+
scanHex(layer, sink);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Candidates in one string. Never throws on a string. */
|
|
181
|
+
/**
|
|
182
|
+
* A credential header's value, plus what its HTTP Basic credentials decode to, when it is
|
|
183
|
+
* Basic auth (curl -u, git credential helpers; red team R2-01/02). The gateway and the
|
|
184
|
+
* sidecar both read headers through this, so the two cannot disagree (review R12-10).
|
|
185
|
+
* Standard or URL-safe base64; anything that is not base64 adds nothing.
|
|
186
|
+
*/
|
|
187
|
+
export function credentialHeaderTexts(raw) {
|
|
188
|
+
if (typeof raw !== "string") return [];
|
|
189
|
+
const texts = [raw];
|
|
190
|
+
const basic = /^\s*basic\s+([A-Za-z0-9+/=_-]{1,4096})\s*$/i.exec(raw);
|
|
191
|
+
if (basic) {
|
|
192
|
+
try {
|
|
193
|
+
texts.push(atob(basic[1].replace(/-/g, "+").replace(/_/g, "/")));
|
|
194
|
+
} catch {
|
|
195
|
+
// Not base64: nothing more to read.
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return texts;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function findDecoyCandidates(text) {
|
|
202
|
+
const sink = new Sink();
|
|
203
|
+
if (typeof text === "string" && text.length > 0) scanLayers(text, sink);
|
|
204
|
+
return { candidates: [...sink.set], truncated: sink.truncated };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Candidates in a parsed JSON value: every string leaf (base64 media included, because
|
|
209
|
+
* a text document travels as base64), plus the seam between each pair of adjacent
|
|
210
|
+
* leaves, so a decoy cut across two messages is still read whole.
|
|
211
|
+
*/
|
|
212
|
+
export function candidatesInJson(value) {
|
|
213
|
+
const sink = new Sink();
|
|
214
|
+
const gaps = new Set();
|
|
215
|
+
let previous = "";
|
|
216
|
+
const seam = TRIPWIRE_SCAN_LIMITS.seam;
|
|
217
|
+
const pending = [[value, 0]];
|
|
218
|
+
const visited = new WeakSet();
|
|
219
|
+
const leaf = (text) => {
|
|
220
|
+
scanLayers(text, sink);
|
|
221
|
+
if (previous) scanLayers(previous.slice(-seam) + text.slice(0, seam), sink);
|
|
222
|
+
previous = text;
|
|
223
|
+
};
|
|
224
|
+
while (pending.length) {
|
|
225
|
+
const [node, depth] = pending.pop();
|
|
226
|
+
if (typeof node === "string") {
|
|
227
|
+
leaf(node);
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
if (node === null || typeof node !== "object") continue;
|
|
231
|
+
if (depth >= TRIPWIRE_SCAN_LIMITS.maxDepth) {
|
|
232
|
+
gaps.add("depth_limit");
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
if (visited.has(node)) continue;
|
|
236
|
+
visited.add(node);
|
|
237
|
+
// Object keys too: a decoy can be a key. Pushed in reverse so leaves come out in order.
|
|
238
|
+
const entries = Array.isArray(node) ? node.map((v) => [null, v]) : Object.entries(node);
|
|
239
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
240
|
+
const [key, child] = entries[i];
|
|
241
|
+
pending.push([child, depth + 1]);
|
|
242
|
+
if (key !== null && key.length >= PREFIX.length) pending.push([key, depth + 1]);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
if (sink.truncated) gaps.add("candidate_limit");
|
|
246
|
+
return { candidates: [...sink.set], truncated: sink.truncated, gaps: [...gaps] };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* For text that arrives in fragments (a streamed answer, a chunked body): a bounded
|
|
251
|
+
* window scanned as it grows, keeping a tail longer than any encoded decoy.
|
|
252
|
+
*/
|
|
253
|
+
export function createStreamCandidateFinder() {
|
|
254
|
+
const { streamWindow, streamTail } = TRIPWIRE_SCAN_LIMITS;
|
|
255
|
+
const sink = new Sink();
|
|
256
|
+
let window = "";
|
|
257
|
+
return {
|
|
258
|
+
push(fragment) {
|
|
259
|
+
if (typeof fragment !== "string" || fragment.length === 0) return;
|
|
260
|
+
for (let at = 0; at < fragment.length; ) {
|
|
261
|
+
const room = streamWindow - window.length;
|
|
262
|
+
window += fragment.slice(at, at + room);
|
|
263
|
+
at += room;
|
|
264
|
+
if (window.length >= streamWindow) {
|
|
265
|
+
scanLayers(window, sink);
|
|
266
|
+
window = window.slice(-streamTail);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
},
|
|
270
|
+
finish() {
|
|
271
|
+
scanLayers(window, sink);
|
|
272
|
+
window = "";
|
|
273
|
+
return { candidates: [...sink.set], truncated: sink.truncated };
|
|
274
|
+
},
|
|
275
|
+
retained() {
|
|
276
|
+
return window.length;
|
|
277
|
+
},
|
|
278
|
+
};
|
|
279
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export const TRIPWIRE_PATH: string;
|
|
2
|
+
export const TRIPWIRE_SOURCE: string;
|
|
3
|
+
export const HEARTBEAT_MS: number;
|
|
4
|
+
export function decoyInHeaders(headers: Record<string, unknown>, digests: Set<string>, isCredentialHeader: (name: string) => boolean): string | null;
|
|
5
|
+
export function decoysInHook(input: unknown, digests: Set<string>): string[];
|
|
6
|
+
export function createTripwireReporter(input: { send(body: unknown): Promise<{ status: number }>; now?: () => number }): {
|
|
7
|
+
used(digest: string, tools?: string[]): Promise<{ status: number }>;
|
|
8
|
+
seen(digests: string[]): Promise<{ status: number }>;
|
|
9
|
+
heartbeat(): Promise<{ status: number }>;
|
|
10
|
+
};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// The sidecar's tripwire checks (idea 12). Local, digest-only: the sidecar reads the
|
|
2
|
+
// manifest `configure tripwires` wrote (digests, never decoys), so nothing it sends can
|
|
3
|
+
// carry a decoy, and nothing it holds is one.
|
|
4
|
+
//
|
|
5
|
+
// * Used: a request the sidecar relays carries a planted decoy in a credential header.
|
|
6
|
+
// The sidecar strips credentials before forwarding (that is its job), so this is the
|
|
7
|
+
// only place such a decoy can be seen. The request is refused locally with the same 401
|
|
8
|
+
// an unknown key gets, and reported; the gateway stops the decoy's agent and this one.
|
|
9
|
+
// * Seen: a planted decoy appears in tool output a PostToolBatch/PostToolUse hook hands
|
|
10
|
+
// the model (subscription mode, where the gateway never sees model traffic).
|
|
11
|
+
// * Heartbeat: the scan is running, at most once per HEARTBEAT_MS (coverage, not safety).
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { candidatesInJson, credentialHeaderTexts } from "./tripwire-scan.mjs";
|
|
14
|
+
|
|
15
|
+
export const TRIPWIRE_PATH = "/api/v1/tripwire";
|
|
16
|
+
export const TRIPWIRE_SOURCE = "passcontrol-sidecar";
|
|
17
|
+
export const HEARTBEAT_MS = 10 * 60 * 1000;
|
|
18
|
+
const DECOY = /pc_agent_[A-Za-z0-9_-]{43}/g;
|
|
19
|
+
|
|
20
|
+
const digest = (value) => createHash("sha256").update(value, "utf8").digest("base64url");
|
|
21
|
+
|
|
22
|
+
/** The planted digest a credential-bearing header carries, or null. */
|
|
23
|
+
export function decoyInHeaders(headers, digests, isCredentialHeader) {
|
|
24
|
+
if (!digests || digests.size === 0) return null;
|
|
25
|
+
for (const [name, raw] of Object.entries(headers ?? {})) {
|
|
26
|
+
if (!isCredentialHeader(name)) continue;
|
|
27
|
+
const values = Array.isArray(raw) ? raw : [raw];
|
|
28
|
+
for (const value of values) {
|
|
29
|
+
// Basic auth is decoded first: `pc_agent_` is not visible in its base64 (R12-10).
|
|
30
|
+
for (const text of credentialHeaderTexts(value)) {
|
|
31
|
+
if (!text.includes("pc_agent_")) continue;
|
|
32
|
+
for (const m of text.matchAll(DECOY)) {
|
|
33
|
+
const d = digest(m[0]);
|
|
34
|
+
if (digests.has(d)) return d;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Planted digests that appear in the tool output of a hook input. Never throws. */
|
|
43
|
+
export function decoysInHook(input, digests) {
|
|
44
|
+
try {
|
|
45
|
+
if (!digests || digests.size === 0) return [];
|
|
46
|
+
let outputs = [];
|
|
47
|
+
if (input?.hook_event_name === "PostToolBatch" && Array.isArray(input.tool_calls)) outputs = input.tool_calls.map((c) => c?.tool_response);
|
|
48
|
+
else if (input?.hook_event_name === "PostToolUse") outputs = [input.tool_response ?? input.tool_output ?? input.output];
|
|
49
|
+
else return [];
|
|
50
|
+
const hits = new Set();
|
|
51
|
+
for (const c of candidatesInJson(outputs).candidates) {
|
|
52
|
+
const d = digest(c);
|
|
53
|
+
if (digests.has(d)) hits.add(d);
|
|
54
|
+
}
|
|
55
|
+
return [...hits];
|
|
56
|
+
} catch {
|
|
57
|
+
return [];
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Sends reports through the sidecar's authenticated path. `send(body)` posts JSON to
|
|
63
|
+
* TRIPWIRE_PATH with the sidecar's visa and returns { status }. `used` is awaited so the
|
|
64
|
+
* stop has happened (or is known to have failed) before the relayed request is answered.
|
|
65
|
+
*/
|
|
66
|
+
export function createTripwireReporter({ send, now = Date.now }) {
|
|
67
|
+
let lastBeat = 0;
|
|
68
|
+
const post = async (reports) => {
|
|
69
|
+
try {
|
|
70
|
+
return await send({ source: TRIPWIRE_SOURCE, reports });
|
|
71
|
+
} catch {
|
|
72
|
+
return { status: 0 };
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
used: (digestValue, tools = []) => post([{ kind: "used", digest: digestValue, tools: tools.slice(-5) }]),
|
|
77
|
+
seen: (digests) => (digests.length ? post(digests.slice(0, 20).map((d) => ({ kind: "seen", digest: d }))) : Promise.resolve({ status: 204 })),
|
|
78
|
+
heartbeat: () => {
|
|
79
|
+
if (now() - lastBeat < HEARTBEAT_MS) return Promise.resolve({ status: 204 });
|
|
80
|
+
lastBeat = now();
|
|
81
|
+
return post([{ kind: "heartbeat" }]);
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export const TRIPWIRE_PLACEMENTS: Record<"state_backup" | "anthropic_pair", { rel(slug: string): string; content(decoy: string, origin?: string): string }>;
|
|
2
|
+
export const DEFAULT_TRIPWIRE_PLACEMENTS: string[];
|
|
3
|
+
export function tripwirePlacementChoices(): string;
|
|
4
|
+
export function generateDecoy(): string;
|
|
5
|
+
export function decoyDigest(decoy: string): string;
|
|
6
|
+
export function tripwireManifestPath(env?: Record<string, string | undefined>): string;
|
|
7
|
+
export function readTripwireManifest(file?: string): { version: number; agents: Record<string, { placements: { placement: string; path: string; digest: string; plantedAt: string }[] }> };
|
|
8
|
+
export function plantedDigests(file?: string): Set<string>;
|
|
9
|
+
export function slugOf(agentId: string): string;
|
|
10
|
+
export function enclosingRepo(dir: string): string | null;
|
|
11
|
+
export function checkTarget(home: string, rel: string, ownDigest: string | undefined): string;
|
|
12
|
+
export function plantTripwires(input: {
|
|
13
|
+
home?: string;
|
|
14
|
+
agentId: string;
|
|
15
|
+
origin: string;
|
|
16
|
+
placements?: string[];
|
|
17
|
+
register(decoys: { placement: string; digest: string }[], replace: boolean): Promise<unknown>;
|
|
18
|
+
manifestFile?: string;
|
|
19
|
+
dryRun?: boolean;
|
|
20
|
+
}): Promise<{ planted: { placement: string; path: string }[]; rotated?: boolean; dryRun?: boolean }>;
|
|
21
|
+
export function removeTripwires(input: { agentId: string; retire(): Promise<unknown>; manifestFile?: string }): Promise<{ removed: string[]; kept: string[] }>;
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// `passcontrol configure tripwires` — plant, rotate and remove tripwire decoys (idea 12).
|
|
2
|
+
//
|
|
3
|
+
// A decoy is a Direct Agent Key in every byte (`pc_agent_` + 43 base64url characters from 32
|
|
4
|
+
// random bytes), generated HERE, on the owner's machine. The gateway receives only its
|
|
5
|
+
// digest and the name of the place it was planted, so the plaintext never crosses the
|
|
6
|
+
// network. Planting order: register the digests first, then write the files, so a decoy is
|
|
7
|
+
// never on disk without being armed. Rotation registers new digests with `replace` (the old
|
|
8
|
+
// ones are retired, and stay armed 30 days) and overwrites only files this tool wrote.
|
|
9
|
+
//
|
|
10
|
+
// Placement rules, each from a measurement (research/idea-12-tripwire/RESULTS.md, S1/S3):
|
|
11
|
+
// * outside any git repository: GitHub push protection rejects credential-shaped files,
|
|
12
|
+
// and a repo is what agents read most;
|
|
13
|
+
// * never in a file a tool loads by itself (`~/.env` is found by python-dotenv's
|
|
14
|
+
// find_dotenv walking up from a project; `.passcontrol` by this CLI walking up): that
|
|
15
|
+
// would make honest software PRESENT the decoy, a false Used and a false suspension;
|
|
16
|
+
// * in hidden directories (ripgrep skips them by default) and, for the quiet placement,
|
|
17
|
+
// with no keyword at all: honest searches name specific variables, and in 1,103 public
|
|
18
|
+
// interactive sessions none searched for `pc_agent_` or `PASSCONTROL`.
|
|
19
|
+
// Never follows a symlink, never overwrites a file it did not write, and keeps a 0600
|
|
20
|
+
// manifest of digests (never decoys) for the sidecar's local checks.
|
|
21
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
22
|
+
import fs from "node:fs";
|
|
23
|
+
import os from "node:os";
|
|
24
|
+
import path from "node:path";
|
|
25
|
+
|
|
26
|
+
const PREFIX = "pc_agent_";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The placements `configure tripwires` can plant, in default order. The CLI's usage string
|
|
30
|
+
* is generated from this list (CLAUDE.md: never hand-type a list of supported things).
|
|
31
|
+
*/
|
|
32
|
+
export const TRIPWIRE_PLACEMENTS = {
|
|
33
|
+
// A bare value in a backup-named file under XDG state: found by listing or reading
|
|
34
|
+
// PassControl's state, or by searching for the key shape itself. No keyword to match.
|
|
35
|
+
state_backup: {
|
|
36
|
+
rel: (slug) => `.local/state/passcontrol/agent-key-${slug}.bak`,
|
|
37
|
+
content: (decoy) => `${decoy}\n`,
|
|
38
|
+
},
|
|
39
|
+
// The exact file the dashboard's Setup page gives for a Direct Agent Key: a base URL that
|
|
40
|
+
// is this gateway, and the key. Used as written, it routes the decoy back to PassControl
|
|
41
|
+
// (S5). Not in ~/.config/passcontrol, which honest PassControl debugging reads.
|
|
42
|
+
anthropic_pair: {
|
|
43
|
+
rel: (slug) => `.config/anthropic/credentials-${slug}.env`,
|
|
44
|
+
content: (decoy, origin) => `ANTHROPIC_BASE_URL=${origin}/api/v1/anthropic\nANTHROPIC_API_KEY=${decoy}\n`,
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
export const DEFAULT_TRIPWIRE_PLACEMENTS = ["state_backup", "anthropic_pair"];
|
|
48
|
+
|
|
49
|
+
export function tripwirePlacementChoices() {
|
|
50
|
+
return Object.keys(TRIPWIRE_PLACEMENTS).join(",");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function generateDecoy() {
|
|
54
|
+
return PREFIX + randomBytes(32).toString("base64url");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Same digest the gateway's registry and a real Direct Agent Key use. */
|
|
58
|
+
export function decoyDigest(decoy) {
|
|
59
|
+
return createHash("sha256").update(decoy, "utf8").digest("base64url");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function tripwireManifestPath(env = process.env) {
|
|
63
|
+
const base = env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
|
|
64
|
+
return path.join(base, "passcontrol", "tripwires.json");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function readTripwireManifest(file = tripwireManifestPath()) {
|
|
68
|
+
try {
|
|
69
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
70
|
+
return value && typeof value === "object" && value.agents && typeof value.agents === "object" ? value : { version: 1, agents: {} };
|
|
71
|
+
} catch {
|
|
72
|
+
return { version: 1, agents: {} };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function writeManifest(file, manifest) {
|
|
77
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
78
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
79
|
+
fs.writeFileSync(tmp, JSON.stringify(manifest, null, 2) + "\n", { mode: 0o600 });
|
|
80
|
+
fs.renameSync(tmp, file);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Every planted digest on this machine, for the sidecar. */
|
|
84
|
+
export function plantedDigests(file = tripwireManifestPath()) {
|
|
85
|
+
const out = new Set();
|
|
86
|
+
for (const agent of Object.values(readTripwireManifest(file).agents)) {
|
|
87
|
+
for (const p of agent?.placements ?? []) if (typeof p?.digest === "string") out.add(p.digest);
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function slugOf(agentId) {
|
|
93
|
+
return String(agentId).replace(/[^A-Za-z0-9]/g, "").slice(0, 12).toLowerCase() || "agent";
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The git work tree containing `dir`, or null. Walks up looking for `.git`. */
|
|
97
|
+
export function enclosingRepo(dir) {
|
|
98
|
+
let at = path.resolve(dir);
|
|
99
|
+
for (;;) {
|
|
100
|
+
if (fs.existsSync(path.join(at, ".git"))) return at;
|
|
101
|
+
const parent = path.dirname(at);
|
|
102
|
+
if (parent === at) return null;
|
|
103
|
+
at = parent;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function lstatOrNull(p) {
|
|
108
|
+
try {
|
|
109
|
+
return fs.lstatSync(p);
|
|
110
|
+
} catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Refuses anything unsafe; returns the absolute target. */
|
|
116
|
+
export function checkTarget(home, rel, ownDigest) {
|
|
117
|
+
const target = path.resolve(home, rel);
|
|
118
|
+
if (!target.startsWith(path.resolve(home) + path.sep)) throw new Error(`refusing ${rel}: outside the home folder`);
|
|
119
|
+
if (path.basename(target) === ".passcontrol" || path.basename(target) === ".env") {
|
|
120
|
+
throw new Error(`refusing ${rel}: a file name tools load on their own`);
|
|
121
|
+
}
|
|
122
|
+
// Every existing ancestor below home must be a real directory, not a symlink.
|
|
123
|
+
let at = path.resolve(home);
|
|
124
|
+
for (const part of path.relative(home, path.dirname(target)).split(path.sep).filter(Boolean)) {
|
|
125
|
+
at = path.join(at, part);
|
|
126
|
+
const st = lstatOrNull(at);
|
|
127
|
+
if (st && (st.isSymbolicLink() || !st.isDirectory())) throw new Error(`refusing ${rel}: ${at} is not a plain directory`);
|
|
128
|
+
}
|
|
129
|
+
const existingParent = (() => {
|
|
130
|
+
let p = path.dirname(target);
|
|
131
|
+
while (!fs.existsSync(p)) p = path.dirname(p);
|
|
132
|
+
return p;
|
|
133
|
+
})();
|
|
134
|
+
const repo = enclosingRepo(existingParent);
|
|
135
|
+
if (repo) throw new Error(`refusing ${rel}: inside the git repository ${repo}`);
|
|
136
|
+
const st = lstatOrNull(target);
|
|
137
|
+
if (st) {
|
|
138
|
+
if (st.isSymbolicLink() || !st.isFile()) throw new Error(`refusing ${rel}: exists and is not a plain file`);
|
|
139
|
+
const current = fs.readFileSync(target, "utf8");
|
|
140
|
+
const mine = ownDigest && [...current.matchAll(/pc_agent_[A-Za-z0-9_-]{43}/g)].some((m) => decoyDigest(m[0]) === ownDigest);
|
|
141
|
+
if (!mine) throw new Error(`refusing ${rel}: a file is already there that this tool did not write`);
|
|
142
|
+
}
|
|
143
|
+
return target;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Plan, register, then write. `register(decoys, replace)` sends digests to the gateway and
|
|
148
|
+
* throws on refusal. Returns what was planted (paths and placements, never the decoys).
|
|
149
|
+
*/
|
|
150
|
+
export async function plantTripwires({ home = os.homedir(), agentId, origin, placements = DEFAULT_TRIPWIRE_PLACEMENTS, register, manifestFile = tripwireManifestPath(), dryRun = false }) {
|
|
151
|
+
if (!agentId) throw new Error("an agent id is required (--agent <id>)");
|
|
152
|
+
if (!/^https?:\/\/[^/\s]+$/.test(String(origin ?? ""))) throw new Error("the gateway origin must be a bare origin");
|
|
153
|
+
for (const p of placements) if (!Object.hasOwn(TRIPWIRE_PLACEMENTS, p)) throw new Error(`unknown placement ${p}; use: ${tripwirePlacementChoices()}`);
|
|
154
|
+
const manifest = readTripwireManifest(manifestFile);
|
|
155
|
+
const previous = manifest.agents[agentId]?.placements ?? [];
|
|
156
|
+
const slug = slugOf(agentId);
|
|
157
|
+
const plan = placements.map((placement) => {
|
|
158
|
+
const spec = TRIPWIRE_PLACEMENTS[placement];
|
|
159
|
+
const rel = spec.rel(slug);
|
|
160
|
+
const prior = previous.find((p) => p.placement === placement);
|
|
161
|
+
const target = checkTarget(home, rel, prior?.digest);
|
|
162
|
+
const decoy = generateDecoy();
|
|
163
|
+
return { placement, target, decoy, digest: decoyDigest(decoy), content: spec.content(decoy, origin) };
|
|
164
|
+
});
|
|
165
|
+
if (dryRun) return { planted: plan.map(({ placement, target }) => ({ placement, path: target })), dryRun: true };
|
|
166
|
+
|
|
167
|
+
// A rotation retires only what THIS machine planted (review R12-08).
|
|
168
|
+
await register(
|
|
169
|
+
plan.map(({ placement, digest }) => ({ placement, digest })),
|
|
170
|
+
previous.length > 0,
|
|
171
|
+
previous.map((p) => p.digest).filter((d) => typeof d === "string")
|
|
172
|
+
);
|
|
173
|
+
|
|
174
|
+
for (const item of plan) {
|
|
175
|
+
fs.mkdirSync(path.dirname(item.target), { recursive: true, mode: 0o700 });
|
|
176
|
+
const tmp = `${item.target}.${process.pid}.tmp`;
|
|
177
|
+
fs.writeFileSync(tmp, item.content, { mode: 0o600, flag: "wx" });
|
|
178
|
+
fs.renameSync(tmp, item.target);
|
|
179
|
+
}
|
|
180
|
+
const now = new Date().toISOString();
|
|
181
|
+
manifest.agents[agentId] = {
|
|
182
|
+
placements: plan.map(({ placement, target, digest }) => ({ placement, path: target, digest, plantedAt: now })),
|
|
183
|
+
};
|
|
184
|
+
writeManifest(manifestFile, manifest);
|
|
185
|
+
return { planted: plan.map(({ placement, target }) => ({ placement, path: target })), rotated: previous.length > 0 };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Retire at the gateway, then delete only the files whose decoy is still the one planted. */
|
|
189
|
+
export async function removeTripwires({ agentId, retire, manifestFile = tripwireManifestPath() }) {
|
|
190
|
+
const manifest = readTripwireManifest(manifestFile);
|
|
191
|
+
const entry = manifest.agents[agentId];
|
|
192
|
+
await retire();
|
|
193
|
+
const removed = [];
|
|
194
|
+
const kept = [];
|
|
195
|
+
for (const p of entry?.placements ?? []) {
|
|
196
|
+
const st = lstatOrNull(p.path);
|
|
197
|
+
if (!st || !st.isFile() || st.isSymbolicLink()) continue;
|
|
198
|
+
const current = fs.readFileSync(p.path, "utf8");
|
|
199
|
+
const ours = [...current.matchAll(/pc_agent_[A-Za-z0-9_-]{43}/g)].some((m) => decoyDigest(m[0]) === p.digest);
|
|
200
|
+
if (ours) {
|
|
201
|
+
fs.unlinkSync(p.path);
|
|
202
|
+
removed.push(p.path);
|
|
203
|
+
} else kept.push(p.path);
|
|
204
|
+
}
|
|
205
|
+
delete manifest.agents[agentId];
|
|
206
|
+
writeManifest(manifestFile, manifest);
|
|
207
|
+
return { removed, kept };
|
|
208
|
+
}
|
package/cli/verify.mjs
CHANGED
|
@@ -118,8 +118,34 @@ async function verifySigned(
|
|
|
118
118
|
return { ok: false, reason: "bad_signature" };
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
-
export function verifyReceipt(jws, options) {
|
|
122
|
-
|
|
121
|
+
export async function verifyReceipt(jws, options) {
|
|
122
|
+
const result = await verifySigned(jws, RECEIPT_TYP, options);
|
|
123
|
+
if (result.ok && result.claims.ver === 4 && !validGatewayEndingClaims(result.claims)) {
|
|
124
|
+
return { ok: false, reason: "claims" };
|
|
125
|
+
}
|
|
126
|
+
return result;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// v4 changes WHO acted. Reject contradictory identity evidence even when signed.
|
|
130
|
+
// Keep in sync with sdk/verify.ts.
|
|
131
|
+
function validGatewayEndingClaims(c) {
|
|
132
|
+
const auth = c.auth;
|
|
133
|
+
const end = c.end;
|
|
134
|
+
return c.sub === "gateway" &&
|
|
135
|
+
!["vjti", "act", "passportId", "visaJti", "agentAccessKeyId", "credentialUseId"].some((key) => key in c) &&
|
|
136
|
+
!!auth && typeof auth === "object" && !Array.isArray(auth) && auth.kind === "gateway_ending" &&
|
|
137
|
+
!["act", "kid", "use", "dlg", "dep", "ch", "prf"].some((key) => key in auth) &&
|
|
138
|
+
!!end && !Array.isArray(end) &&
|
|
139
|
+
typeof end.thg === "string" && end.thg.length > 0 &&
|
|
140
|
+
typeof end.knd === "string" && end.knd.length > 0 &&
|
|
141
|
+
["kill_switch", "session", "service", "mission_end", "budget_pause"].includes(end.trg) &&
|
|
142
|
+
Number.isSafeInteger(end.sat) && end.sat >= 0;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Plain identity wording for the owner-stop receipt, not an agent credential. */
|
|
146
|
+
export function describeGatewayEnding(ending) {
|
|
147
|
+
const trigger = { kill_switch: "kill switch", session: "session stop", service: "service stop", mission_end: "mission end", budget_pause: "budget pause line" }[ending.trg];
|
|
148
|
+
return `Ended by PassControl on the owner's stop (${trigger}), not a call by the agent. No passport or agent key signed it.`;
|
|
123
149
|
}
|
|
124
150
|
|
|
125
151
|
/**
|
|
@@ -390,6 +416,7 @@ export async function verifySession(input, options) {
|
|
|
390
416
|
|
|
391
417
|
/** Human-readable one-liners. Kept here so the CLI and its tests agree on wording. */
|
|
392
418
|
export const FAILURE_REASONS = {
|
|
419
|
+
claims: "the receipt carries missing or conflicting gateway ending claims",
|
|
393
420
|
malformed: "not a compact JWS",
|
|
394
421
|
bad_signature: "signature does not verify against the issuer's published key",
|
|
395
422
|
wrong_type: "this artifact is a different type than the one you asked to verify",
|