passcontrol 1.7.2 → 1.8.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,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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "1.7.2",
3
+ "version": "1.8.0",
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",