passcontrol 1.4.0 → 1.5.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/LICENSE +3 -1
- package/README.md +10 -1
- package/bin/passcontrol.mjs +193 -6
- package/cli/budget-format.mjs +37 -0
- package/cli/config.mjs +35 -1
- package/cli/declared-session.mjs +32 -4
- package/cli/delegation.d.mts +60 -0
- package/cli/delegation.mjs +192 -0
- package/cli/menu.mjs +4 -0
- package/cli/profiles.mjs +92 -0
- package/cli/protocols.mjs +3 -1
- package/cli/sidecar.mjs +158 -21
- package/cli/statusline.mjs +125 -1
- package/cli/visa-client.mjs +5 -1
- package/cli/watch-feed.mjs +275 -0
- package/cli/watch.mjs +601 -0
- package/package.json +1 -1
- package/sdk/index.d.ts +2 -1
- package/sdk/index.js +3 -0
- package/sdk/passcontrol.d.ts +46 -0
- package/sdk/passcontrol.js +47 -2
- package/sdk/verify.d.ts +7 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// Signed delegation, client side (Bet D; plans/delegation-design.md §3, §8, §10).
|
|
2
|
+
//
|
|
3
|
+
// Plain ESM, shared by the SDK (sdk/passcontrol.ts, sdk/verify.ts) and the CLI, as
|
|
4
|
+
// cli/protocols.mjs is, so the two verifiers cannot disagree.
|
|
5
|
+
//
|
|
6
|
+
// - createDelegationLink: sign a link handing a worker's key a NARROWER slice. The
|
|
7
|
+
// parent never holds the worker's private key: the worker generates its key and
|
|
8
|
+
// sends only the public half.
|
|
9
|
+
// - checkDelegationChain: the offline half of the gateway's rules, for anyone holding
|
|
10
|
+
// a chain. Signatures by position, issuers, depth, parent hashes, caps and expiries
|
|
11
|
+
// that only narrow. NOT the scope against the agent's current scope: only the
|
|
12
|
+
// gateway knows that, and it checked it when the worker exchanged the chain.
|
|
13
|
+
// - verifyReceiptDelegation: tie a worker's receipt (ver 3, auth.kind "delegated") to
|
|
14
|
+
// the chain that authorised it.
|
|
15
|
+
import { ed25519 } from "@noble/curves/ed25519";
|
|
16
|
+
import { sha256 } from "@noble/hashes/sha256";
|
|
17
|
+
|
|
18
|
+
export const DELEGATION_TYP = "passcontrol-delegation+jws";
|
|
19
|
+
export const DELEGATION_MAX_DEPTH = 2;
|
|
20
|
+
export const DELEGATION_MAX_LIFETIME_S = 24 * 3600;
|
|
21
|
+
const IAT_SKEW_S = 30;
|
|
22
|
+
const MAX_LINK_CHARS = 8192;
|
|
23
|
+
const JTI_RE = /^[A-Za-z0-9_-]{16,64}$/;
|
|
24
|
+
const MEMBERS = ["iss", "sub", "aud", "jti", "iat", "exp", "dep", "max", "scope", "cap"];
|
|
25
|
+
|
|
26
|
+
const enc = new TextEncoder();
|
|
27
|
+
const dec = new TextDecoder();
|
|
28
|
+
|
|
29
|
+
function b64url(bytes) {
|
|
30
|
+
let bin = "";
|
|
31
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
32
|
+
const b64 = typeof btoa !== "undefined" ? btoa(bin) : Buffer.from(bin, "binary").toString("base64");
|
|
33
|
+
return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
34
|
+
}
|
|
35
|
+
function fromB64url(s) {
|
|
36
|
+
const b64 = s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "=");
|
|
37
|
+
const bin = typeof atob !== "undefined" ? atob(b64) : Buffer.from(b64, "base64").toString("binary");
|
|
38
|
+
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
39
|
+
}
|
|
40
|
+
const json = (part) => JSON.parse(dec.decode(fromB64url(part)));
|
|
41
|
+
const isInt = (v) => typeof v === "number" && Number.isSafeInteger(v);
|
|
42
|
+
const keyBytes = (id) => {
|
|
43
|
+
try {
|
|
44
|
+
const k = fromB64url(id);
|
|
45
|
+
return typeof id === "string" && id.length === 43 && k.length === 32 ? k : null;
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/** SHA-256 of the links joined by commas, base64url: what a receipt's `auth.ch` commits to. */
|
|
52
|
+
export function delegationChainHash(chain) {
|
|
53
|
+
return b64url(sha256(enc.encode(chain.join(","))));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** A fresh Ed25519 key for a worker. Keep `privateKey` in the worker; send only `publicKey`. */
|
|
57
|
+
export function generateWorkerKey() {
|
|
58
|
+
const priv = ed25519.utils.randomPrivateKey();
|
|
59
|
+
return { publicKey: b64url(ed25519.getPublicKey(priv)), privateKey: b64url(priv) };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function decodeLink(compact) {
|
|
63
|
+
if (typeof compact !== "string" || compact.length > MAX_LINK_CHARS) return null;
|
|
64
|
+
const [h, p, s, ...rest] = compact.split(".");
|
|
65
|
+
if (rest.length || !h || !p || !s) return null;
|
|
66
|
+
try {
|
|
67
|
+
const header = json(h);
|
|
68
|
+
if (!header || Object.keys(header).length !== 2 || header.alg !== "EdDSA" || header.typ !== DELEGATION_TYP) return null;
|
|
69
|
+
const payload = json(p);
|
|
70
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
|
|
71
|
+
const signature = fromB64url(s);
|
|
72
|
+
if (signature.length !== 64) return null;
|
|
73
|
+
return { payload, signingInput: `${h}.${p}`, signature };
|
|
74
|
+
} catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Sign one link. `parentChain` is the signer's own chain when a WORKER delegates on
|
|
81
|
+
* (depth 2); omit it when the agent's passport signs. The local checks mirror the
|
|
82
|
+
* gateway's, so a bad link fails here with a reason rather than at the exchange.
|
|
83
|
+
* `unchecked` skips them (tests only): the gateway still refuses.
|
|
84
|
+
*/
|
|
85
|
+
export function createDelegationLink(opts) {
|
|
86
|
+
const priv = fromB64url(opts.signerPrivateKey);
|
|
87
|
+
if (priv.length !== 32) throw new Error("delegation: signerPrivateKey must encode 32 bytes");
|
|
88
|
+
const derived = b64url(ed25519.getPublicKey(priv));
|
|
89
|
+
const iss = opts.signerKeyId ?? derived;
|
|
90
|
+
const parentChain = opts.parentChain ?? [];
|
|
91
|
+
const now = Math.floor((opts.nowMs ?? Date.now()) / 1000);
|
|
92
|
+
const dep = parentChain.length + 1;
|
|
93
|
+
let exp = now + Math.floor(opts.ttlSeconds);
|
|
94
|
+
let max = opts.allowFurtherDelegation === false ? dep : DELEGATION_MAX_DEPTH;
|
|
95
|
+
let ph;
|
|
96
|
+
if (!opts.unchecked && dep > DELEGATION_MAX_DEPTH) {
|
|
97
|
+
throw new Error(`delegation: depth ${dep} is past the maximum of ${DELEGATION_MAX_DEPTH}`);
|
|
98
|
+
}
|
|
99
|
+
if (parentChain.length > 0) {
|
|
100
|
+
const parent = decodeLink(parentChain[parentChain.length - 1]);
|
|
101
|
+
if (!parent) throw new Error("delegation: the parent chain does not decode");
|
|
102
|
+
const p = parent.payload;
|
|
103
|
+
exp = Math.min(exp, p.exp);
|
|
104
|
+
max = Math.min(max, p.max);
|
|
105
|
+
ph = b64url(sha256(enc.encode(parentChain[0])));
|
|
106
|
+
if (!opts.unchecked) {
|
|
107
|
+
if (p.sub !== iss) throw new Error("delegation: only the worker the parent link names may delegate on");
|
|
108
|
+
if (opts.capMicrocents > p.cap) throw new Error("delegation: a link's cap cannot exceed its parent's cap");
|
|
109
|
+
if (dep > p.max) throw new Error("delegation: the parent link does not allow further delegation");
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (!opts.unchecked) {
|
|
113
|
+
if (iss !== derived) throw new Error("delegation: signerKeyId is not the signer's key");
|
|
114
|
+
if (!keyBytes(opts.workerPublicKey)) throw new Error("delegation: workerPublicKey must be a 32-byte key, base64url");
|
|
115
|
+
if (!isInt(opts.capMicrocents) || opts.capMicrocents < 0) throw new Error("delegation: capMicrocents must be a non-negative integer");
|
|
116
|
+
if (!(opts.ttlSeconds > 0) || exp - now > DELEGATION_MAX_LIFETIME_S) throw new Error("delegation: the lifetime must be between 1 second and 24 hours");
|
|
117
|
+
}
|
|
118
|
+
const jti = opts.jti ?? b64url(crypto.getRandomValues(new Uint8Array(18)));
|
|
119
|
+
const payload = {
|
|
120
|
+
iss,
|
|
121
|
+
sub: opts.workerPublicKey,
|
|
122
|
+
aud: opts.audience,
|
|
123
|
+
jti,
|
|
124
|
+
iat: now,
|
|
125
|
+
exp,
|
|
126
|
+
dep,
|
|
127
|
+
max,
|
|
128
|
+
...(ph ? { ph } : {}),
|
|
129
|
+
scope: opts.scope,
|
|
130
|
+
cap: opts.capMicrocents,
|
|
131
|
+
};
|
|
132
|
+
const input = `${b64url(enc.encode(JSON.stringify({ alg: "EdDSA", typ: DELEGATION_TYP })))}.${b64url(enc.encode(JSON.stringify(payload)))}`;
|
|
133
|
+
return `${input}.${b64url(ed25519.sign(enc.encode(input), priv))}`;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The offline rules. `nowSeconds` omitted skips the time checks, which is what a
|
|
138
|
+
* receipt needs: the receipt outlives its delegation, and its signature still holds.
|
|
139
|
+
*/
|
|
140
|
+
export function checkDelegationChain({ chain, rootPassportId, audience, nowSeconds }) {
|
|
141
|
+
const fail = (reason) => ({ ok: false, reason });
|
|
142
|
+
if (!Array.isArray(chain) || chain.length < 1 || chain.length > DELEGATION_MAX_DEPTH) return fail("malformed");
|
|
143
|
+
let parent = { key: rootPassportId, cap: Infinity, exp: Infinity, max: DELEGATION_MAX_DEPTH };
|
|
144
|
+
const links = [];
|
|
145
|
+
for (let i = 0; i < chain.length; i++) {
|
|
146
|
+
const position = i + 1;
|
|
147
|
+
const link = decodeLink(chain[i]);
|
|
148
|
+
if (!link) return fail("malformed");
|
|
149
|
+
const p = link.payload;
|
|
150
|
+
const expected = position === 2 ? [...MEMBERS, "ph"] : MEMBERS;
|
|
151
|
+
if (Object.keys(p).length !== expected.length || !expected.every((k) => k in p)) return fail("malformed");
|
|
152
|
+
if (!keyBytes(p.sub) || !JTI_RE.test(String(p.jti)) || ![p.iat, p.exp, p.dep, p.max, p.cap].every(isInt) || p.cap < 0) return fail("malformed");
|
|
153
|
+
if (p.iss !== parent.key) return fail("issuer");
|
|
154
|
+
const key = keyBytes(parent.key);
|
|
155
|
+
let valid = false;
|
|
156
|
+
try {
|
|
157
|
+
valid = Boolean(key) && ed25519.verify(link.signature, enc.encode(link.signingInput), key);
|
|
158
|
+
} catch {
|
|
159
|
+
valid = false;
|
|
160
|
+
}
|
|
161
|
+
if (!valid) return fail("signature");
|
|
162
|
+
if (audience !== undefined && p.aud !== audience) return fail("audience");
|
|
163
|
+
if (p.dep !== position || p.max > parent.max || p.dep > p.max) return fail("depth");
|
|
164
|
+
if (p.cap > parent.cap) return fail("cap");
|
|
165
|
+
if (p.exp <= p.iat || p.exp > parent.exp || p.exp - p.iat > DELEGATION_MAX_LIFETIME_S) return fail("expiry");
|
|
166
|
+
if (nowSeconds !== undefined && (p.iat > nowSeconds + IAT_SKEW_S || nowSeconds >= p.exp)) return fail("expiry");
|
|
167
|
+
if (position === 2 && p.ph !== b64url(sha256(enc.encode(chain[0])))) return fail("parent_hash");
|
|
168
|
+
links.push({ jti: p.jti, iss: p.iss, sub: p.sub, iat: p.iat, exp: p.exp, dep: p.dep, max: p.max, cap: p.cap, scope: p.scope });
|
|
169
|
+
parent = { key: p.sub, cap: p.cap, exp: p.exp, max: p.max };
|
|
170
|
+
}
|
|
171
|
+
return { ok: true, leaf: links[links.length - 1], links, chainHash: delegationChainHash(chain) };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* A worker's receipt and the chain behind it: the chain is rooted in the receipt's
|
|
176
|
+
* passport (`sub`), its hash is the receipt's `auth.ch`, its leaf is the worker in
|
|
177
|
+
* `auth.act` under `auth.dlg`. Verify the receipt's signature first (verifyReceipt).
|
|
178
|
+
*/
|
|
179
|
+
export function verifyReceiptDelegation(claims, chain, options = {}) {
|
|
180
|
+
void options.nowSeconds;
|
|
181
|
+
const auth = claims && claims.auth;
|
|
182
|
+
if (!auth || auth.kind !== "delegated") return { ok: false, reason: "not_delegated" };
|
|
183
|
+
// No clock: a receipt outlives the delegation it was made under, and what it attests
|
|
184
|
+
// (this chain authorised this worker when the gateway checked it) does not expire.
|
|
185
|
+
const checked = checkDelegationChain({ chain, rootPassportId: claims.sub, audience: options.audience ?? claims.iss });
|
|
186
|
+
if (!checked.ok) return checked;
|
|
187
|
+
if (checked.chainHash !== auth.ch) return { ok: false, reason: "chain_hash" };
|
|
188
|
+
if (checked.leaf.sub !== auth.act || checked.leaf.jti !== auth.dlg || checked.leaf.dep !== auth.dep) {
|
|
189
|
+
return { ok: false, reason: "leaf" };
|
|
190
|
+
}
|
|
191
|
+
return { ok: true, chain: checked };
|
|
192
|
+
}
|
package/cli/menu.mjs
CHANGED
|
@@ -144,6 +144,8 @@ export const GROUPS = [
|
|
|
144
144
|
// sender proof in 0.9, so a workspace in required mode refuses this client
|
|
145
145
|
// while the sidecar keeps working. Most people never run it by hand —
|
|
146
146
|
// `configure <client> --write` wires it into the client's own config.
|
|
147
|
+
// A board that holds the terminal until q, so the same terms as the two servers.
|
|
148
|
+
command({ id: "watch", label: "Watch the sidecar's calls live", run: ["watch"], detail: "watch --port 8788", description: "Read-only board: each call, its sub-agent, model, outcome and time.", effect: "long_running", network: "gateway", keywords: ["board", "live", "subagent", "tail"], needsArgs: true, returnToMenu: true }),
|
|
147
149
|
command({ id: "mcp", label: "Serve MCP to desktop agent clients", run: ["mcp"], detail: "mcp", description: "Stdio server for MCP clients. Its chat sends no sender proof in 0.9.", effect: "long_running", network: "provider", keywords: ["stdio", "claude", "cursor", "desktop"], needsArgs: true, returnToMenu: true }),
|
|
148
150
|
],
|
|
149
151
|
},
|
|
@@ -157,6 +159,7 @@ export const GROUPS = [
|
|
|
157
159
|
command({ id: "agent-suspend", label: "Suspend an agent", run: ["agent", "suspend"], detail: "agent suspend <id>", description: "Temporarily refuse every new call from one active agent.", effect: "tenant_write", network: "gateway", guide: "suspend", needsArgs: true }),
|
|
158
160
|
command({ id: "agent-resume", label: "Resume an agent", run: ["agent", "resume"], detail: "agent resume <id>", description: "Allow a suspended agent to authenticate again.", effect: "tenant_write", network: "gateway", guide: "resume", needsArgs: true }),
|
|
159
161
|
command({ id: "kill", label: "Tenant kill switch", run: ["kill"], detail: "kill on|off", description: "Arm or disarm the workspace-wide emergency stop.", effect: "tenant_write", network: "gateway", guide: "kill", needsArgs: true, current: currentFrom("kill") }),
|
|
162
|
+
command({ id: "profile-list", label: "List coding-tool profiles", run: ["profile", "list"], detail: "profile list", description: "Show each coding tool's own agent: its passport and sidecar port.", keywords: ["profile", "claude code", "codex", "identity"] }),
|
|
160
163
|
],
|
|
161
164
|
},
|
|
162
165
|
{
|
|
@@ -239,6 +242,7 @@ export const GROUPS = [
|
|
|
239
242
|
hint: "revoke, rotate or destroy",
|
|
240
243
|
items: [
|
|
241
244
|
command({ id: "agent-rotate", label: "Rotate a passport key", run: ["agent", "rotate"], detail: "agent rotate <id>", description: "Replace an agent passport and reveal a new private key once.", effect: "irreversible", network: "gateway", needsArgs: true }),
|
|
245
|
+
command({ id: "agent-revoke-delegation", label: "Revoke a delegation", run: ["agent", "revoke-delegation"], detail: "agent revoke-delegation <id>", description: "Permanently stop one delegation, or every one an agent issued before now.", effect: "irreversible", network: "gateway", needsArgs: true }),
|
|
242
246
|
command({ id: "agent-revoke", label: "Revoke an agent permanently", run: ["agent", "revoke"], detail: "agent revoke <id>", description: "Permanently prevent an agent from authenticating again.", effect: "irreversible", network: "gateway", needsArgs: true }),
|
|
243
247
|
command({ id: "keygen-instance", label: "Create a receipt-signing key", run: ["keygen", "instance"], detail: "keygen instance", description: "Reveal a new instance signing seed; replacing a live key requires a rotation plan.", effect: "irreversible", needsArgs: true }),
|
|
244
248
|
command({ id: "reset", label: "Destroy and recreate the local stack", run: ["reset"], detail: "reset --local --confirm RESET", description: "Delete and recreate local stack state after an explicit typed confirmation.", effect: "irreversible", needsArgs: true }),
|
package/cli/profiles.mjs
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// Named profiles: one identity per coding tool (1.4.0 candidate 4, owner 2026-10-10;
|
|
2
|
+
// design plans/one-identity-per-tool.md).
|
|
3
|
+
//
|
|
4
|
+
// A profile is a config file at <config dir>/profiles/<name>, in the global config's
|
|
5
|
+
// format, holding a passport and the sidecar port it serves. It holds a passport
|
|
6
|
+
// SECRET, so it gets the same protection: a 0700 directory, a 0600 file, and nothing
|
|
7
|
+
// in this module ever prints a value.
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
|
|
12
|
+
export const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
13
|
+
|
|
14
|
+
/** The port each coding tool's dedicated sidecar serves. 8788 stays the shared default. */
|
|
15
|
+
export const TOOL_PROFILE_PORTS = { "claude-code": 8790, codex: 8791 };
|
|
16
|
+
|
|
17
|
+
export function profilesDir(env = process.env) {
|
|
18
|
+
const base = env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
|
|
19
|
+
return path.join(base, "passcontrol", "profiles");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function profilePath(name, env = process.env) {
|
|
23
|
+
if (typeof name !== "string" || !PROFILE_NAME_RE.test(name)) {
|
|
24
|
+
throw new Error(`Invalid profile name ${JSON.stringify(String(name)).slice(0, 48)}: use lowercase letters, digits and dashes (up to 32).`);
|
|
25
|
+
}
|
|
26
|
+
return path.join(profilesDir(env), name);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function parse(text) {
|
|
30
|
+
const values = {};
|
|
31
|
+
for (const raw of text.split("\n")) {
|
|
32
|
+
const line = raw.trim();
|
|
33
|
+
if (!line || line.startsWith("#")) continue;
|
|
34
|
+
const eq = line.indexOf("=");
|
|
35
|
+
if (eq <= 0) continue;
|
|
36
|
+
values[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
|
|
37
|
+
}
|
|
38
|
+
return values;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The profile's values, or null when it does not exist. */
|
|
42
|
+
export function readProfile(name, env = process.env) {
|
|
43
|
+
const file = profilePath(name, env);
|
|
44
|
+
if (!fs.existsSync(file)) return null;
|
|
45
|
+
return parse(fs.readFileSync(file, "utf8"));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Merge values into a profile, creating it (and its directory) owner-only. */
|
|
49
|
+
export function writeProfile(name, values, env = process.env) {
|
|
50
|
+
const file = profilePath(name, env);
|
|
51
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
52
|
+
fs.chmodSync(path.dirname(file), 0o700);
|
|
53
|
+
const merged = { ...(readProfile(name, env) ?? {}), ...values };
|
|
54
|
+
const body =
|
|
55
|
+
"# PassControl profile. Keep this file private: it holds a passport secret.\n" +
|
|
56
|
+
Object.entries(merged)
|
|
57
|
+
.map(([k, v]) => `${k}=${v}`)
|
|
58
|
+
.join("\n") +
|
|
59
|
+
"\n";
|
|
60
|
+
fs.writeFileSync(file, body, { mode: 0o600 });
|
|
61
|
+
fs.chmodSync(file, 0o600);
|
|
62
|
+
return file;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Every profile's name, passport id and port; never a secret. */
|
|
66
|
+
export function listProfiles(env = process.env) {
|
|
67
|
+
const dir = profilesDir(env);
|
|
68
|
+
if (!fs.existsSync(dir)) return [];
|
|
69
|
+
return fs
|
|
70
|
+
.readdirSync(dir)
|
|
71
|
+
.filter((name) => PROFILE_NAME_RE.test(name))
|
|
72
|
+
.sort()
|
|
73
|
+
.map((name) => {
|
|
74
|
+
const v = readProfile(name, env) ?? {};
|
|
75
|
+
return { name, passportId: v.PASSPORT_ID ?? "", port: v.SIDECAR_PORT ?? "" };
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The profile this process was asked to use: `--profile <name>` on the command line,
|
|
81
|
+
* or PASSCONTROL_PROFILE from the OPERATOR's shell. Read before any config file is
|
|
82
|
+
* merged into the environment, so a project's `.passcontrol` cannot choose which
|
|
83
|
+
* identity this machine speaks as.
|
|
84
|
+
*/
|
|
85
|
+
export function selectedProfile(argv = process.argv, env = process.env) {
|
|
86
|
+
for (let i = 0; i < argv.length; i++) {
|
|
87
|
+
const arg = argv[i];
|
|
88
|
+
if (arg === "--profile") return argv[i + 1] ?? "";
|
|
89
|
+
if (arg.startsWith("--profile=")) return arg.slice("--profile=".length);
|
|
90
|
+
}
|
|
91
|
+
return env.PASSCONTROL_PROFILE ?? null;
|
|
92
|
+
}
|
package/cli/protocols.mjs
CHANGED
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
// runtime source; its declaration lets Edge TypeScript import the same values.
|
|
4
4
|
export const CONTROL_API_PROTOCOL = { minimum: 1, maximum: 1 };
|
|
5
5
|
export const GATEWAY_API_PROTOCOL = { minimum: 1, maximum: 1 };
|
|
6
|
-
|
|
6
|
+
// 3 (Bet D, 2026-10-10): a WORKER's receipt, auth.kind "delegated". Moved so a verifier
|
|
7
|
+
// that predates delegation refuses it as too new instead of rendering it as passport-signed.
|
|
8
|
+
export const RECEIPT_PROTOCOL = { minimum: 1, maximum: 3 };
|
|
7
9
|
export const AGENT_TOKEN_PROTOCOL = { minimum: 1, maximum: 1 };
|
|
8
10
|
export const WORKSPACE_EXPORT_PROTOCOL = { minimum: 1, maximum: 1 };
|
|
9
11
|
|
package/cli/sidecar.mjs
CHANGED
|
@@ -5,8 +5,9 @@ import { Readable } from "node:stream";
|
|
|
5
5
|
import { bareGatewayOrigin, fail, ok, step, warn } from "./config.mjs";
|
|
6
6
|
import { classifyConnect, classifyProxyRequest, isLoopbackBindHost } from "./proxy-policy.mjs";
|
|
7
7
|
import { createVisaClient } from "./visa-client.mjs";
|
|
8
|
-
import { declaredSession } from "./declared-session.mjs";
|
|
8
|
+
import { declaredLineage, declaredSession } from "./declared-session.mjs";
|
|
9
9
|
import { defaultJournalDir, openJournal } from "./journal.mjs";
|
|
10
|
+
import { createWatchFeed, isBudgetRead, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
|
|
10
11
|
|
|
11
12
|
// Hop-by-hop headers plus the ones the sidecar rebuilds itself. `proxy-connection`
|
|
12
13
|
// and friends only appear once something is used as a FORWARD proxy, which is
|
|
@@ -115,6 +116,10 @@ export function createSidecar({
|
|
|
115
116
|
runId = randomUUID(),
|
|
116
117
|
// cli/journal.mjs, or null for `--no-journal`.
|
|
117
118
|
journal = null,
|
|
119
|
+
// `passcontrol watch`'s feed (cli/watch-feed.mjs). Off when bound off loopback.
|
|
120
|
+
watchFeed = isLoopbackBindHost(host),
|
|
121
|
+
watchCapacity = 200,
|
|
122
|
+
watchMaxSubscribers = 8,
|
|
118
123
|
}) {
|
|
119
124
|
// The upstream URL below is built from this, not from the argument: the
|
|
120
125
|
// sidecar forwards a bearer visa on every proxied request, so its destination
|
|
@@ -131,6 +136,13 @@ export function createSidecar({
|
|
|
131
136
|
|
|
132
137
|
// Used only to print the governed base URL back in a refusal. Read from the
|
|
133
138
|
// live listener when there is one so the advice names the port actually bound.
|
|
139
|
+
const feed = createWatchFeed({ runId, capacity: watchCapacity, maxSubscribers: watchMaxSubscribers, enabled: watchFeed });
|
|
140
|
+
const lineageOf = (headers) =>
|
|
141
|
+
declaredLineage((name) => {
|
|
142
|
+
const v = headers?.[name];
|
|
143
|
+
return Array.isArray(v) ? v[0] : v;
|
|
144
|
+
}, runId);
|
|
145
|
+
|
|
134
146
|
const localBaseUrl = () => {
|
|
135
147
|
const address = server?.listening ? server.address() : null;
|
|
136
148
|
return `http://${host}:${address?.port ?? port}`;
|
|
@@ -165,7 +177,11 @@ export function createSidecar({
|
|
|
165
177
|
// URL — codeload for an archive download — passes through untouched.
|
|
166
178
|
const toLocal = (value) => value.split(`${origin}/api/v1/`).join(`${localBaseUrl()}/api/v1/`);
|
|
167
179
|
|
|
168
|
-
|
|
180
|
+
// `watch` is the board's handle on this call ({ call, startedAt }), or null for one
|
|
181
|
+
// the board does not show. Its outcome is read from the status and, for an error,
|
|
182
|
+
// from a capped peek at a CLONE of the body, so the client's bytes are untouched
|
|
183
|
+
// and nothing here waits on the peek.
|
|
184
|
+
function writeResponse(res, upstream, reqHeaders, watch = null) {
|
|
169
185
|
// At the headers, not at the end of the body: a streamed call whose client
|
|
170
186
|
// disconnects mid-stream still produced a receipt, and the user's record of
|
|
171
187
|
// it must not depend on how long they kept reading. With the session the call
|
|
@@ -184,33 +200,84 @@ export function createSidecar({
|
|
|
184
200
|
if (STRIP_RES.has(name)) return;
|
|
185
201
|
outHeaders[k] = name === "link" || name === "location" ? toLocal(v) : v;
|
|
186
202
|
});
|
|
203
|
+
let peek = null;
|
|
204
|
+
if (watch) {
|
|
205
|
+
const ttfb = Date.now() - watch.startedAt;
|
|
206
|
+
const status = upstream.status;
|
|
207
|
+
res.on("close", () => watch.call.finish());
|
|
208
|
+
if (status < 400) watch.call.settle({ outcome: "boarded", status, ttfb });
|
|
209
|
+
else if (!upstream.body) watch.call.settle({ outcome: "error", status, ttfb });
|
|
210
|
+
else {
|
|
211
|
+
try {
|
|
212
|
+
peek = upstream.clone().body;
|
|
213
|
+
} catch {
|
|
214
|
+
watch.call.settle({ outcome: "error", status, ttfb });
|
|
215
|
+
}
|
|
216
|
+
if (peek) {
|
|
217
|
+
peekText(peek).then((text) => {
|
|
218
|
+
const code = refusalCode(text);
|
|
219
|
+
watch.call.settle({ outcome: code ? "denied" : "error", code, status, ttfb });
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
187
224
|
res.writeHead(upstream.status, outHeaders);
|
|
188
225
|
if (upstream.body) Readable.fromWeb(upstream.body).pipe(res);
|
|
189
226
|
else res.end();
|
|
190
227
|
}
|
|
191
228
|
|
|
229
|
+
/** Begins the board's record of a forwarded call, unless it is the budget read. */
|
|
230
|
+
function watchCall(req, path, body, startedAt) {
|
|
231
|
+
if (isBudgetRead(path)) return null;
|
|
232
|
+
try {
|
|
233
|
+
return { startedAt, call: feed.begin({ startedAt, lineage: lineageOf(req.headers), model: requestModel(body), provider: providerOf(path) }) };
|
|
234
|
+
} catch {
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** A forwarded call that failed before the gateway answered: shown, then answered 502. */
|
|
240
|
+
function upstreamFailed(res, watch, req, path, e) {
|
|
241
|
+
if (!res.headersSent) {
|
|
242
|
+
if (watch) {
|
|
243
|
+
watch.call.settle({ outcome: "error", code: "sidecar_upstream_error", status: 502 });
|
|
244
|
+
watch.call.finish();
|
|
245
|
+
} else if (!isBudgetRead(path)) {
|
|
246
|
+
feed.record({ outcome: "error", code: "sidecar_upstream_error", status: 502, lineage: lineageOf(req.headers), provider: providerOf(path) });
|
|
247
|
+
}
|
|
248
|
+
res.writeHead(502, { "content-type": "application/json" });
|
|
249
|
+
res.end(JSON.stringify({ error: "sidecar_upstream_error", message: e.message }));
|
|
250
|
+
} else {
|
|
251
|
+
res.end();
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
192
255
|
const server = http.createServer(async (req, res) => {
|
|
256
|
+
// The sidecar's own paths: answered here, never forwarded with a visa.
|
|
257
|
+
if (String(req.url ?? "").startsWith(LOCAL_PREFIX)) {
|
|
258
|
+
feed.serve(req, res, { port: server.address()?.port });
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const startedAt = Date.now();
|
|
193
262
|
// Judge the destination before reading the body: a refused host should not
|
|
194
263
|
// get to make the sidecar buffer megabytes on its way to a 403.
|
|
195
264
|
const verdict = classifyProxyRequest({ url: req.url, gatewayOrigin: origin, localBaseUrl: localBaseUrl() });
|
|
196
265
|
if (!verdict.allow) {
|
|
197
266
|
req.resume();
|
|
198
267
|
onRefusal(verdict);
|
|
268
|
+
feed.record({ outcome: "denied", code: verdict.code, status: verdict.status, lineage: lineageOf(req.headers), startedAt });
|
|
199
269
|
writeRefusal(res, verdict);
|
|
200
270
|
return;
|
|
201
271
|
}
|
|
202
272
|
|
|
273
|
+
let watch = null;
|
|
203
274
|
try {
|
|
204
275
|
const body = await readBody(req);
|
|
276
|
+
watch = watchCall(req, verdict.path, body, startedAt);
|
|
205
277
|
const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, verdict.path, body, visa));
|
|
206
|
-
writeResponse(res, upstream, req.headers);
|
|
278
|
+
writeResponse(res, upstream, req.headers, watch);
|
|
207
279
|
} catch (e) {
|
|
208
|
-
|
|
209
|
-
res.writeHead(502, { "content-type": "application/json" });
|
|
210
|
-
res.end(JSON.stringify({ error: "sidecar_upstream_error", message: e.message }));
|
|
211
|
-
} else {
|
|
212
|
-
res.end();
|
|
213
|
-
}
|
|
280
|
+
upstreamFailed(res, watch, req, verdict.path, e);
|
|
214
281
|
}
|
|
215
282
|
});
|
|
216
283
|
|
|
@@ -239,24 +306,24 @@ export function createSidecar({
|
|
|
239
306
|
const probe = url.pathname === "/";
|
|
240
307
|
const mapped = `/api/v1/local${probe ? "/api/version" : url.pathname}${probe ? "" : url.search}`;
|
|
241
308
|
const method = probe ? "GET" : req.method;
|
|
309
|
+
const startedAt = Date.now();
|
|
310
|
+
let watch = null;
|
|
242
311
|
try {
|
|
243
312
|
const body = probe ? null : await readBody(req);
|
|
244
313
|
if (probe) req.resume();
|
|
314
|
+
watch = watchCall(req, mapped, body, startedAt);
|
|
245
315
|
const upstream = await visas.fetchWithVisa((visa) => fetchUpstream({ method, headers: req.headers }, mapped, body, visa));
|
|
246
316
|
if (req.method === "HEAD") {
|
|
317
|
+
watch?.call.settle({ outcome: upstream.status < 400 ? "boarded" : "error", status: upstream.status, ttfb: Date.now() - startedAt });
|
|
318
|
+
watch?.call.finish();
|
|
247
319
|
res.writeHead(upstream.status);
|
|
248
320
|
res.end();
|
|
249
321
|
await upstream.body?.cancel().catch(() => {});
|
|
250
322
|
return;
|
|
251
323
|
}
|
|
252
|
-
writeResponse(res, upstream, req.headers);
|
|
324
|
+
writeResponse(res, upstream, req.headers, watch);
|
|
253
325
|
} catch (e) {
|
|
254
|
-
|
|
255
|
-
res.writeHead(502, { "content-type": "application/json" });
|
|
256
|
-
res.end(JSON.stringify({ error: "sidecar_upstream_error", message: e.message }));
|
|
257
|
-
} else {
|
|
258
|
-
res.end();
|
|
259
|
-
}
|
|
326
|
+
upstreamFailed(res, watch, req, mapped, e);
|
|
260
327
|
}
|
|
261
328
|
});
|
|
262
329
|
|
|
@@ -275,6 +342,7 @@ export function createSidecar({
|
|
|
275
342
|
});
|
|
276
343
|
if (!verdict.allow) {
|
|
277
344
|
onRefusal(verdict);
|
|
345
|
+
feed.record({ outcome: "denied", code: verdict.code, status: verdict.status, lineage: lineageOf(req.headers) });
|
|
278
346
|
writeConnectRefusal(clientSocket, verdict);
|
|
279
347
|
return;
|
|
280
348
|
}
|
|
@@ -292,6 +360,7 @@ export function createSidecar({
|
|
|
292
360
|
clientSocket.destroy();
|
|
293
361
|
return;
|
|
294
362
|
}
|
|
363
|
+
feed.record({ outcome: "error", code: "tunnel_unreachable", status: 502, lineage: lineageOf(req.headers) });
|
|
295
364
|
writeConnectRefusal(clientSocket, {
|
|
296
365
|
status: 502,
|
|
297
366
|
code: "tunnel_unreachable",
|
|
@@ -302,7 +371,7 @@ export function createSidecar({
|
|
|
302
371
|
clientSocket.on("close", () => upstream.destroy());
|
|
303
372
|
});
|
|
304
373
|
|
|
305
|
-
return { server, ollamaServer, getVisa: visas.getVisa, runId };
|
|
374
|
+
return { server, ollamaServer, getVisa: visas.getVisa, runId, feed };
|
|
306
375
|
}
|
|
307
376
|
|
|
308
377
|
/**
|
|
@@ -335,7 +404,7 @@ export function startSidecar(opts) {
|
|
|
335
404
|
onError: (e) =>
|
|
336
405
|
warn(`journal: could not write ${journal.path} (${e.message}). Calls are unaffected; this run is no longer being recorded.`),
|
|
337
406
|
});
|
|
338
|
-
const { server, ollamaServer, getVisa } = createSidecar({ ...opts, runId, journal });
|
|
407
|
+
const { server, ollamaServer, getVisa, feed } = createSidecar({ ...opts, runId, journal });
|
|
339
408
|
if (ollamaPort != null) {
|
|
340
409
|
ollamaServer.listen(ollamaPort, host, () => {
|
|
341
410
|
step(`Ollama API (local models) on http://${host}:${ollamaPort}: set OLLAMA_HOST=${host}:${ollamaPort}`);
|
|
@@ -351,6 +420,11 @@ export function startSidecar(opts) {
|
|
|
351
420
|
? `Journal: ${journal.path} (receipt ids, times, statuses and declared sessions only; --no-journal turns it off)`
|
|
352
421
|
: "Journal: off (--no-journal). Session seals cannot be checked against this run."
|
|
353
422
|
);
|
|
423
|
+
step(
|
|
424
|
+
isLoopbackBindHost(host)
|
|
425
|
+
? `Watch live: passcontrol watch --port ${port} (this machine only; held in memory, never written)`
|
|
426
|
+
: "Watch: off, because this sidecar is bound off loopback."
|
|
427
|
+
);
|
|
354
428
|
// Said at startup rather than only in a refusal, because the whole point of
|
|
355
429
|
// HTTPS_PROXY is that nobody reads the docs first.
|
|
356
430
|
step("HTTPS_PROXY: CONNECT to a provider is refused, not tunnelled — PassControl cannot");
|
|
@@ -363,9 +437,72 @@ export function startSidecar(opts) {
|
|
|
363
437
|
? `CONNECT allowlist: ${allowConnectHosts.join(", ")} (provider hosts are never eligible).\n`
|
|
364
438
|
: "CONNECT allowlist: none — only the gateway.\n"
|
|
365
439
|
);
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
440
|
+
warmVisa({
|
|
441
|
+
getVisa,
|
|
442
|
+
gateway,
|
|
443
|
+
// Closed rather than process.exit(): stderr to a pipe is written
|
|
444
|
+
// asynchronously, and exit() can drop the reason this just printed.
|
|
445
|
+
onRefused: () => {
|
|
446
|
+
process.exitCode = 1;
|
|
447
|
+
// A watching board holds its connection open, and close() waits for it.
|
|
448
|
+
feed.close();
|
|
449
|
+
server.close();
|
|
450
|
+
if (ollamaServer.listening) ollamaServer.close();
|
|
451
|
+
setTimeout(() => process.exit(1), 1000).unref();
|
|
452
|
+
},
|
|
453
|
+
});
|
|
369
454
|
});
|
|
370
455
|
return server;
|
|
371
456
|
}
|
|
457
|
+
|
|
458
|
+
/** Waits between attempts to mint the first visa: backoff, then every 30 seconds. */
|
|
459
|
+
export const WARM_RETRY_MS = [1000, 2000, 4000, 8000, 15000, 30000];
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* A gateway that answered and refused the passport: any 4xx except 408 and 429,
|
|
463
|
+
* which mean "not now". No status (no connection) and 5xx mean "not up yet".
|
|
464
|
+
*/
|
|
465
|
+
export function isPassportRefusal(error) {
|
|
466
|
+
const status = error?.status;
|
|
467
|
+
return typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 429;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* The first visa (sprint T2). A sidecar is often started before its gateway, by
|
|
472
|
+
* `passcontrol start` or a login script, so a gateway that is not answering is
|
|
473
|
+
* waited for, on screen; a refusal ends the process, because retrying it can only
|
|
474
|
+
* fail again and a sidecar that cannot mint must not look like it is running.
|
|
475
|
+
* Resolves true once warmed, false after a refusal (onRefused has run).
|
|
476
|
+
*/
|
|
477
|
+
export async function warmVisa({
|
|
478
|
+
getVisa,
|
|
479
|
+
gateway,
|
|
480
|
+
onRefused,
|
|
481
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
482
|
+
log = { ok, warn, fail },
|
|
483
|
+
delays = WARM_RETRY_MS,
|
|
484
|
+
}) {
|
|
485
|
+
for (let attempt = 0; ; attempt++) {
|
|
486
|
+
try {
|
|
487
|
+
await getVisa();
|
|
488
|
+
log.ok(attempt === 0 ? "visa warmed" : `visa warmed: ${gateway} is answering now`);
|
|
489
|
+
return true;
|
|
490
|
+
} catch (error) {
|
|
491
|
+
if (isPassportRefusal(error)) {
|
|
492
|
+
log.fail(`could not mint a visa: ${error.message}`);
|
|
493
|
+
onRefused(error);
|
|
494
|
+
return false;
|
|
495
|
+
}
|
|
496
|
+
const delay = delays[Math.min(attempt, delays.length - 1)];
|
|
497
|
+
if (attempt === 0) {
|
|
498
|
+
log.warn(
|
|
499
|
+
`${gateway} is not answering yet (${error.message}). Waiting for it, and retrying on its own; ` +
|
|
500
|
+
"calls made before it answers get a 502."
|
|
501
|
+
);
|
|
502
|
+
} else if (attempt % 10 === 0) {
|
|
503
|
+
log.warn(`still waiting for ${gateway} (${error.message})`);
|
|
504
|
+
}
|
|
505
|
+
await sleep(delay);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
}
|