passcontrol 1.3.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 +455 -10
- package/cli/budget-format.mjs +113 -0
- package/cli/claude-code.mjs +80 -16
- package/cli/config.mjs +36 -2
- package/cli/declared-session.mjs +61 -0
- package/cli/delegation.d.mts +60 -0
- package/cli/delegation.mjs +192 -0
- package/cli/journal.mjs +84 -0
- package/cli/mcp/README.md +4 -1
- package/cli/mcp/gateway.mjs +13 -0
- package/cli/mcp/server.mjs +27 -0
- package/cli/menu.mjs +7 -0
- package/cli/profiles.mjs +92 -0
- package/cli/protocols.d.mts +2 -0
- package/cli/protocols.mjs +17 -1
- package/cli/sidecar.mjs +194 -20
- package/cli/statusline.mjs +213 -0
- package/cli/verify.mjs +215 -5
- 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 +115 -0
- package/sdk/verify.js +219 -1
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// How an agent's limits read to a person: the MCP `budget` tool and
|
|
2
|
+
// `passcontrol statusline`, both fed by the gateway's GET /api/v1/self.
|
|
3
|
+
//
|
|
4
|
+
// Money arrives as integer microcents (1 USD = 100,000,000). Unknown is "?" and
|
|
5
|
+
// never "$0.00"; no limit says so; a real amount under a cent is "<$0.01".
|
|
6
|
+
|
|
7
|
+
const MICROCENTS_PER_USD = 100_000_000;
|
|
8
|
+
const MICROCENTS_PER_CENT = 1_000_000;
|
|
9
|
+
|
|
10
|
+
/** Microcents as dollars, or "?" when the count could not be read. */
|
|
11
|
+
export function formatUsd(microcents) {
|
|
12
|
+
if (microcents === null || microcents === undefined || !Number.isFinite(Number(microcents))) return "?";
|
|
13
|
+
const value = Number(microcents);
|
|
14
|
+
if (value > 0 && value < MICROCENTS_PER_CENT) return "<$0.01";
|
|
15
|
+
const dollars = Math.round(value / MICROCENTS_PER_CENT) / 100;
|
|
16
|
+
return `$${dollars.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A token count the way a status line has room for: 950, 12.3k, 1.2M. */
|
|
20
|
+
function formatTokens(n) {
|
|
21
|
+
if (n === null || n === undefined || !Number.isFinite(Number(n))) return "?";
|
|
22
|
+
const v = Number(n);
|
|
23
|
+
if (v >= 1_000_000) return `${trim(v / 1_000_000)}M`;
|
|
24
|
+
if (v >= 1_000) return `${trim(v / 1_000)}k`;
|
|
25
|
+
return String(v);
|
|
26
|
+
}
|
|
27
|
+
const trim = (v) => (Math.round(v * 10) / 10).toString();
|
|
28
|
+
|
|
29
|
+
function resetsIn(seconds) {
|
|
30
|
+
const s = Number(seconds);
|
|
31
|
+
if (!Number.isFinite(s) || s <= 0) return null;
|
|
32
|
+
if (s >= 86_400) return `${Math.round(s / 86_400)}d`;
|
|
33
|
+
if (s >= 3_600) return `${Math.round(s / 3_600)}h`;
|
|
34
|
+
return `${Math.max(1, Math.round(s / 60))}m`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const PERIOD_WORD = { day: "today", month: "this month" };
|
|
38
|
+
const PERIOD_LABEL = { day: "Today", month: "This month" };
|
|
39
|
+
|
|
40
|
+
/** One line for Claude Code's status line. The most pressing limit wins. */
|
|
41
|
+
export function statusLine(self) {
|
|
42
|
+
const b = self?.budget ?? {};
|
|
43
|
+
const prefix = "PassControl · ";
|
|
44
|
+
if (b.period && b.period.unknown) return `${prefix}limit unknown`;
|
|
45
|
+
if (b.period) {
|
|
46
|
+
return `${prefix}${formatUsd(b.period.used_microcents)} of ${formatUsd(b.period.limit_microcents)} ${PERIOD_WORD[b.period.kind] ?? ""}`.trimEnd();
|
|
47
|
+
}
|
|
48
|
+
if (b.cost) return `${prefix}${formatUsd(b.cost.used_microcents)} of ${formatUsd(b.cost.limit_microcents)} total`;
|
|
49
|
+
if (b.tokens) return `${prefix}${formatTokens(b.tokens.used)} of ${formatTokens(b.tokens.limit)} tokens`;
|
|
50
|
+
return `${prefix}no limit`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Every limit, with what is left: the MCP tool's text answer. */
|
|
54
|
+
export function budgetLines(self) {
|
|
55
|
+
const b = self?.budget ?? {};
|
|
56
|
+
const lines = [];
|
|
57
|
+
if (b.period && b.period.unknown) {
|
|
58
|
+
lines.push("The periodic spending limit could not be read right now.");
|
|
59
|
+
} else if (b.period) {
|
|
60
|
+
const reset = resetsIn(b.period.resets_in_seconds);
|
|
61
|
+
lines.push(
|
|
62
|
+
`${PERIOD_LABEL[b.period.kind] ?? "This period"}: ${formatUsd(b.period.used_microcents)} of ${formatUsd(b.period.limit_microcents)} used, ` +
|
|
63
|
+
`${formatUsd(b.period.remaining_microcents)} left${reset ? ` (resets in ${reset})` : ""}.`
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
if (b.cost) {
|
|
67
|
+
lines.push(
|
|
68
|
+
`Lifetime: ${formatUsd(b.cost.used_microcents)} of ${formatUsd(b.cost.limit_microcents)} used, ${formatUsd(b.cost.remaining_microcents)} left.`
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
if (b.tokens) {
|
|
72
|
+
lines.push(`Tokens: ${formatTokens(b.tokens.used)} of ${formatTokens(b.tokens.limit)} used, ${formatTokens(b.tokens.remaining)} left.`);
|
|
73
|
+
}
|
|
74
|
+
if (lines.length === 0) lines.push("No spending or token limit is set for this agent.");
|
|
75
|
+
return lines;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Every limit as a [label, value] row, for the `/passcontrol` panel in Claude Code
|
|
80
|
+
* (`passcontrol statusline --panel`): "Today", "$0.42 of $10.00 · $9.58 left · resets in 7h".
|
|
81
|
+
*/
|
|
82
|
+
export function panelRows(self) {
|
|
83
|
+
const b = self?.budget ?? {};
|
|
84
|
+
const rows = [];
|
|
85
|
+
if (b.period && b.period.unknown) {
|
|
86
|
+
rows.push(["Limit", "could not be read right now"]);
|
|
87
|
+
} else if (b.period) {
|
|
88
|
+
const reset = resetsIn(b.period.resets_in_seconds);
|
|
89
|
+
rows.push([
|
|
90
|
+
PERIOD_LABEL[b.period.kind] ?? "This period",
|
|
91
|
+
`${formatUsd(b.period.used_microcents)} of ${formatUsd(b.period.limit_microcents)} · ${formatUsd(b.period.remaining_microcents)} left${reset ? ` · resets in ${reset}` : ""}`,
|
|
92
|
+
]);
|
|
93
|
+
}
|
|
94
|
+
if (b.cost) {
|
|
95
|
+
rows.push(["Lifetime", `${formatUsd(b.cost.used_microcents)} of ${formatUsd(b.cost.limit_microcents)} · ${formatUsd(b.cost.remaining_microcents)} left`]);
|
|
96
|
+
}
|
|
97
|
+
if (b.tokens) {
|
|
98
|
+
rows.push(["Tokens", `${formatTokens(b.tokens.used)} of ${formatTokens(b.tokens.limit)} · ${formatTokens(b.tokens.remaining)} left`]);
|
|
99
|
+
}
|
|
100
|
+
if (rows.length === 0) rows.push(["Limit", "none set"]);
|
|
101
|
+
return rows;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Whether a limit has nothing left, so the gateway refuses calls until it resets or is raised. */
|
|
105
|
+
export function limitReached(self) {
|
|
106
|
+
const b = self?.budget ?? {};
|
|
107
|
+
const spent = (left) => left !== null && left !== undefined && Number.isFinite(Number(left)) && Number(left) <= 0;
|
|
108
|
+
return Boolean(
|
|
109
|
+
(b.period && !b.period.unknown && spent(b.period.remaining_microcents)) ||
|
|
110
|
+
(b.cost && spent(b.cost.remaining_microcents)) ||
|
|
111
|
+
(b.tokens && spent(b.tokens.remaining))
|
|
112
|
+
);
|
|
113
|
+
}
|
package/cli/claude-code.mjs
CHANGED
|
@@ -6,10 +6,12 @@
|
|
|
6
6
|
// Bearer token with no "use this API key?" prompt. The sidecar strips it and the
|
|
7
7
|
// gateway injects the real key, so Claude Code never holds one.
|
|
8
8
|
//
|
|
9
|
-
// The settings file belongs to the user. Only these two keys
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
9
|
+
// The settings file belongs to the user. Only these two keys, and with
|
|
10
|
+
// --statusline a `statusLine` running `passcontrol statusline`, are written or
|
|
11
|
+
// removed, in one save; the previous file is backed up, a file that is not a JSON
|
|
12
|
+
// object is refused rather than overwritten, a different gateway already
|
|
13
|
+
// configured is not replaced without --force, and a status line the user already
|
|
14
|
+
// has is never replaced at all.
|
|
13
15
|
import fs from "node:fs";
|
|
14
16
|
import os from "node:os";
|
|
15
17
|
import path from "node:path";
|
|
@@ -63,34 +65,96 @@ function save(target, value, exists) {
|
|
|
63
65
|
return backupPath;
|
|
64
66
|
}
|
|
65
67
|
|
|
66
|
-
|
|
68
|
+
/**
|
|
69
|
+
* The env keys, and with `statusLineCommand` the status line too, in ONE save:
|
|
70
|
+
* two saves would back up the first save's output and lose the user's original.
|
|
71
|
+
*/
|
|
72
|
+
export function writeClaudeCodeSettings({ target, baseUrl, force = false, statusLineCommand = null }) {
|
|
67
73
|
const { exists, value } = readSettings(target);
|
|
68
74
|
const env = typeof value.env === "object" && value.env !== null && !Array.isArray(value.env) ? value.env : {};
|
|
69
75
|
const rawKeyFound = typeof env.ANTHROPIC_API_KEY === "string" && env.ANTHROPIC_API_KEY.length > 0;
|
|
70
76
|
const current = env.ANTHROPIC_BASE_URL;
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
if (typeof current === "string" && current && current !== baseUrl && !force) {
|
|
77
|
+
const envDone = current === baseUrl && env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER;
|
|
78
|
+
if (!envDone && typeof current === "string" && current && current !== baseUrl && !force) {
|
|
75
79
|
throw new Error(
|
|
76
80
|
`${target} already points Claude Code at ${current}. Re-run with --force to replace that address with PassControl's.`
|
|
77
81
|
);
|
|
78
82
|
}
|
|
79
|
-
|
|
80
|
-
|
|
83
|
+
let next = envDone ? value : { ...value, env: { ...env, ...claudeCodeEnv(baseUrl) } };
|
|
84
|
+
let statusLine;
|
|
85
|
+
if (statusLineCommand) {
|
|
86
|
+
const line = withStatusLine(next, statusLineCommand);
|
|
87
|
+
next = line.value;
|
|
88
|
+
statusLine = line.existing !== undefined ? { changed: false, existing: line.existing } : { changed: line.changed };
|
|
89
|
+
}
|
|
90
|
+
const changed = !envDone || Boolean(statusLine?.changed);
|
|
91
|
+
const backupPath = changed ? save(target, next, exists) : null;
|
|
92
|
+
return { changed, backupPath, rawKeyFound, ...(statusLine ? { statusLine } : {}) };
|
|
81
93
|
}
|
|
82
94
|
|
|
95
|
+
/** PassControl's two env keys and its status line, in one save. */
|
|
83
96
|
export function removeClaudeCodeSettings({ target }) {
|
|
84
97
|
if (!fs.existsSync(target)) return { changed: false };
|
|
85
98
|
const { value } = readSettings(target);
|
|
99
|
+
let next = value;
|
|
86
100
|
const env = typeof value.env === "object" && value.env !== null && !Array.isArray(value.env) ? value.env : null;
|
|
87
101
|
// Only an address this command could have written: a gateway someone else set
|
|
88
102
|
// up is not ours to remove.
|
|
89
|
-
if (
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
103
|
+
if (env && env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER) {
|
|
104
|
+
const { ANTHROPIC_BASE_URL: _url, ANTHROPIC_AUTH_TOKEN: _token, ...rest } = env;
|
|
105
|
+
next = { ...value };
|
|
106
|
+
if (Object.keys(rest).length) next.env = rest;
|
|
107
|
+
else delete next.env;
|
|
108
|
+
}
|
|
109
|
+
if (isOurStatusLine(next.statusLine)) {
|
|
110
|
+
const { statusLine: _ours, ...rest } = next;
|
|
111
|
+
next = rest;
|
|
112
|
+
}
|
|
113
|
+
if (next === value) return { changed: false };
|
|
94
114
|
save(target, next, true);
|
|
95
115
|
return { changed: true };
|
|
96
116
|
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Whether a status line is one `configure claude-code --statusline` wrote: the
|
|
120
|
+
* installed `passcontrol` binary, or this repo's own bin run through node.
|
|
121
|
+
*/
|
|
122
|
+
function isOurStatusLine(statusLine) {
|
|
123
|
+
const command = typeof statusLine?.command === "string" ? statusLine.command : "";
|
|
124
|
+
return /^(passcontrol|node "[^"]*passcontrol\.mjs") statusline\b/.test(command);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* `value` with PassControl's status line set, unless the user already has one of
|
|
129
|
+
* their own: then `existing` names it and `value` is unchanged.
|
|
130
|
+
*/
|
|
131
|
+
function withStatusLine(value, command) {
|
|
132
|
+
const current = value.statusLine;
|
|
133
|
+
if (current && !isOurStatusLine(current)) {
|
|
134
|
+
return { value, changed: false, existing: typeof current.command === "string" ? current.command : "(not a command)" };
|
|
135
|
+
}
|
|
136
|
+
if (current && current.type === "command" && current.command === command) return { value, changed: false };
|
|
137
|
+
return { value: { ...value, statusLine: { type: "command", command } }, changed: true };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The agent's budget in Claude Code's status line, on its own. A status line the
|
|
142
|
+
* user already has is never replaced: the answer names it and nothing is written.
|
|
143
|
+
*/
|
|
144
|
+
export function writeClaudeCodeStatusLine({ target, command }) {
|
|
145
|
+
const { exists, value } = readSettings(target);
|
|
146
|
+
const line = withStatusLine(value, command);
|
|
147
|
+
if (line.existing !== undefined) return { changed: false, existing: line.existing };
|
|
148
|
+
if (!line.changed) return { changed: false };
|
|
149
|
+
save(target, line.value, exists);
|
|
150
|
+
return { changed: true };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function removeClaudeCodeStatusLine({ target }) {
|
|
154
|
+
if (!fs.existsSync(target)) return { changed: false };
|
|
155
|
+
const { value } = readSettings(target);
|
|
156
|
+
if (!isOurStatusLine(value.statusLine)) return { changed: false };
|
|
157
|
+
const { statusLine: _ours, ...rest } = value;
|
|
158
|
+
save(target, rest, true);
|
|
159
|
+
return { changed: true };
|
|
160
|
+
}
|
package/cli/config.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import os from "node:os";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { WORKSPACE_EXPORT_PROTOCOL } from "./protocols.mjs";
|
|
6
|
+
import { profilePath, readProfile, selectedProfile } from "./profiles.mjs";
|
|
6
7
|
import {
|
|
7
8
|
createPassportCredentialStore,
|
|
8
9
|
keyStorageDeclaration,
|
|
@@ -164,7 +165,10 @@ export function loadConfigSources({ cwd = process.cwd(), env = process.env } = {
|
|
|
164
165
|
*/
|
|
165
166
|
export const configInjectedKeys = new Set();
|
|
166
167
|
|
|
167
|
-
export function applyConfigSourcesToEnv({ cwd = process.cwd(), env = process.env } = {}) {
|
|
168
|
+
export function applyConfigSourcesToEnv({ cwd = process.cwd(), env = process.env, argv = process.argv } = {}) {
|
|
169
|
+
// The profile is chosen BEFORE any file lands in the environment: a project's
|
|
170
|
+
// `.passcontrol` must not pick which identity this machine speaks as.
|
|
171
|
+
const profile = selectedProfile(argv, env);
|
|
168
172
|
const sources = loadConfigSources({ cwd, env });
|
|
169
173
|
const merged = {};
|
|
170
174
|
for (const source of sources) Object.assign(merged, source.values);
|
|
@@ -174,6 +178,21 @@ export function applyConfigSourcesToEnv({ cwd = process.cwd(), env = process.env
|
|
|
174
178
|
configInjectedKeys.add(key);
|
|
175
179
|
}
|
|
176
180
|
}
|
|
181
|
+
if (profile !== null) {
|
|
182
|
+
// One identity per coding tool (cli/profiles.mjs). The named profile beats the
|
|
183
|
+
// config FILES (naming it is the more specific statement); the operator's shell
|
|
184
|
+
// still beats everything.
|
|
185
|
+
const file = profilePath(profile, env);
|
|
186
|
+
const values = readProfile(profile, env);
|
|
187
|
+
if (!values) throw new Error(`No profile named ${profile}. List them with \`passcontrol profile list\`.`);
|
|
188
|
+
for (const [key, value] of Object.entries(values)) {
|
|
189
|
+
if (env[key] === undefined || configInjectedKeys.has(key)) {
|
|
190
|
+
env[key] = value;
|
|
191
|
+
configInjectedKeys.add(key);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
sources.push({ type: "profile", name: profile, path: file, values });
|
|
195
|
+
}
|
|
177
196
|
return sources;
|
|
178
197
|
}
|
|
179
198
|
|
|
@@ -286,12 +305,15 @@ function currentConfig() {
|
|
|
286
305
|
provider,
|
|
287
306
|
model: resolveModel(provider),
|
|
288
307
|
sources: configSources,
|
|
308
|
+
profile: configSources.find((source) => source.type === "profile")?.name ?? null,
|
|
289
309
|
};
|
|
290
310
|
}
|
|
291
311
|
|
|
292
312
|
export const config = currentConfig();
|
|
293
313
|
|
|
294
314
|
export function configPathLabel(sources = configSources) {
|
|
315
|
+
const profile = sources.find((source) => source.type === "profile");
|
|
316
|
+
if (profile) return profile.path;
|
|
295
317
|
const project = sources.find((source) => source.type === "project");
|
|
296
318
|
const global = sources.find((source) => source.type === "global");
|
|
297
319
|
if (project) return project.path;
|
|
@@ -655,6 +677,18 @@ export function formatProxyError(status, body) {
|
|
|
655
677
|
if (status === 402 && error === "blocked_budget_period") {
|
|
656
678
|
return `${blocked}\n→ The agent's daily or monthly limit is spent; it resets at the next UTC day or month (see the retry-after header).\n→ Fix: wait for the reset, or raise the limit in the dashboard.`;
|
|
657
679
|
}
|
|
680
|
+
if (status === 402 && error === "blocked_budget_delegation") {
|
|
681
|
+
return `${blocked}\n→ This worker's delegation (or one above it) used its spending cap.\n→ Fix: ask the agent that delegated to it for a new delegation with a larger cap.`;
|
|
682
|
+
}
|
|
683
|
+
if (status === 403 && error === "delegation_revoked") {
|
|
684
|
+
return `${blocked}\n→ The owner revoked this worker's delegation, or every delegation issued before a point in time.\n→ Fix: ask the agent that delegated to it for a new one.`;
|
|
685
|
+
}
|
|
686
|
+
if (status === 503 && error === "delegation_state_unavailable") {
|
|
687
|
+
return `${blocked}\n→ PassControl could not confirm this delegation is still valid, so it refused rather than guess.\n→ Fix: retry shortly; if it persists, ask for a new delegation.`;
|
|
688
|
+
}
|
|
689
|
+
if (status === 402 && error === "blocked_budget_subagent") {
|
|
690
|
+
return `${blocked}\n→ A sub-agent used the per-session cap the agent's policy sets for each sub-agent. The main agent and other sub-agents keep running.\n→ Fix: start a new session, or raise subagent_session_cap_cents in the agent's policy.`;
|
|
691
|
+
}
|
|
658
692
|
if (status === 403 && error === "blocked_policy" && rule === "max_output_tokens") {
|
|
659
693
|
const ceiling = Number.isSafeInteger(limit) ? ` (${limit})` : "";
|
|
660
694
|
return reason === "missing"
|
|
@@ -671,7 +705,7 @@ export function formatProxyError(status, body) {
|
|
|
671
705
|
return `${blocked}\n→ The workspace has no provider key stored for this provider.\n→ Fix: add one under Settings → Provider credentials in the dashboard.`;
|
|
672
706
|
}
|
|
673
707
|
if (status === 400 && error === "server_side_tools_unsupported") {
|
|
674
|
-
return `${blocked}\n→ The request uses a hosted tool PassControl does not price, such as image generation or an
|
|
708
|
+
return `${blocked}\n→ The request uses a hosted tool PassControl does not price, such as image generation, an MCP server, or Claude Code's advisor with an unpriced model.\n→ Fix: remove that tool, or call it outside PassControl (Claude Code: /advisor → No advisor). Priced tools such as web search pass.`;
|
|
675
709
|
}
|
|
676
710
|
// 402 is also how the gateway refuses a call it cannot price under a dollar
|
|
677
711
|
// limit; a bigger budget fixes none of those, so each gets its own advice.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// The session a relayed call declares, exactly as the gateway reads it from the request
|
|
2
|
+
// headers (lib/client-lineage.ts `readClientLineage`, which the proxy calls without the
|
|
3
|
+
// body): Claude Code's session header, else a Codex session its headers agree on, else
|
|
4
|
+
// this sidecar run's own id (`x-passcontrol-run`, which the sidecar sets on every call).
|
|
5
|
+
//
|
|
6
|
+
// A second copy because the sidecar is plain ESM and cannot import the gateway's
|
|
7
|
+
// TypeScript. tests/declared-session-parity.test.ts runs both over every captured
|
|
8
|
+
// Claude Code and Codex request and fails the day they disagree: the journal is
|
|
9
|
+
// filtered by this value, so a mismatch could hide a real omission.
|
|
10
|
+
|
|
11
|
+
const DECLARED = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
12
|
+
const declared = (value) => (typeof value === "string" && DECLARED.test(value) ? value : null);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The session a call declares, and the sub-agent inside it: what `passcontrol watch`
|
|
16
|
+
* puts on a call's row (F6). The gateway's own rules, mirrored: the CLI's agent ids
|
|
17
|
+
* count only next to the CLI's own session; when the run id stands in, they name
|
|
18
|
+
* agents inside a session we could not read, so they are dropped, and the client's
|
|
19
|
+
* own `x-passcontrol-agent` / `x-passcontrol-parent` are read instead. A parent with
|
|
20
|
+
* no agent describes nobody.
|
|
21
|
+
*
|
|
22
|
+
* @param {(name: string) => string | null | undefined} header lower-case header lookup
|
|
23
|
+
* @param {string} runId this sidecar run's id
|
|
24
|
+
* @returns {{ session: string, agent: string | null, parent: string | null } | null}
|
|
25
|
+
*/
|
|
26
|
+
export function declaredLineage(header, runId) {
|
|
27
|
+
const claude = declared(header("x-claude-code-session-id"));
|
|
28
|
+
if (claude) {
|
|
29
|
+
const agent = declared(header("x-claude-code-agent-id"));
|
|
30
|
+
return { session: claude, agent, parent: agent ? declared(header("x-claude-code-parent-agent-id")) : null };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const isCodex =
|
|
34
|
+
/^codex/i.test(header("originator") ?? "") ||
|
|
35
|
+
header("x-codex-turn-metadata") != null ||
|
|
36
|
+
header("x-codex-window-id") != null ||
|
|
37
|
+
header("x-codex-parent-thread-id") != null;
|
|
38
|
+
if (isCodex) {
|
|
39
|
+
const raw = [header("session-id"), header("session_id")].filter((v) => v !== null && v !== undefined);
|
|
40
|
+
if (raw.length > 0 && raw.every((v) => declared(v) !== null) && raw.every((v) => v === raw[0])) {
|
|
41
|
+
const session = raw[0];
|
|
42
|
+
const spawned = header("x-codex-parent-thread-id") != null || header("x-openai-subagent") != null;
|
|
43
|
+
const agent = spawned ? declared(header("thread-id")) : null;
|
|
44
|
+
const parentThread = agent ? declared(header("x-codex-parent-thread-id")) : null;
|
|
45
|
+
return { session, agent, parent: parentThread === session ? null : parentThread };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const run = declared(runId);
|
|
50
|
+
if (!run) return null;
|
|
51
|
+
const agent = declared(header("x-passcontrol-agent"));
|
|
52
|
+
return { session: run, agent, parent: agent ? declared(header("x-passcontrol-parent")) : null };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @param {(name: string) => string | null | undefined} header lower-case header lookup
|
|
57
|
+
* @param {string} runId this sidecar run's id
|
|
58
|
+
*/
|
|
59
|
+
export function declaredSession(header, runId) {
|
|
60
|
+
return declaredLineage(header, runId)?.session ?? null;
|
|
61
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export const DELEGATION_TYP: "passcontrol-delegation+jws";
|
|
2
|
+
export const DELEGATION_MAX_DEPTH: number;
|
|
3
|
+
export const DELEGATION_MAX_LIFETIME_S: number;
|
|
4
|
+
|
|
5
|
+
export interface DelegationScopeEntry {
|
|
6
|
+
provider: string;
|
|
7
|
+
models: string[];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface CreateDelegationLinkOptions {
|
|
11
|
+
/** The signer's private key: the agent's passport secret, or a worker's own key. */
|
|
12
|
+
signerPrivateKey: string;
|
|
13
|
+
/** Defaults to the signer's public key; must equal it unless `unchecked`. */
|
|
14
|
+
signerKeyId?: string;
|
|
15
|
+
/** The gateway's issuer origin, e.g. https://passcontrol.vertias.eu. */
|
|
16
|
+
audience: string;
|
|
17
|
+
workerPublicKey: string;
|
|
18
|
+
scope: DelegationScopeEntry[];
|
|
19
|
+
capMicrocents: number;
|
|
20
|
+
ttlSeconds: number;
|
|
21
|
+
/** false: the worker may not delegate on. Default true (depth 2 at most). */
|
|
22
|
+
allowFurtherDelegation?: boolean;
|
|
23
|
+
/** The signer's own chain, when a worker delegates on. */
|
|
24
|
+
parentChain?: string[];
|
|
25
|
+
jti?: string;
|
|
26
|
+
nowMs?: number;
|
|
27
|
+
/** Tests only: skip the local checks. The gateway still refuses. */
|
|
28
|
+
unchecked?: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface DelegationLinkView {
|
|
32
|
+
jti: string;
|
|
33
|
+
iss: string;
|
|
34
|
+
sub: string;
|
|
35
|
+
iat: number;
|
|
36
|
+
exp: number;
|
|
37
|
+
dep: number;
|
|
38
|
+
max: number;
|
|
39
|
+
cap: number;
|
|
40
|
+
scope: DelegationScopeEntry[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type DelegationCheck =
|
|
44
|
+
| { ok: true; leaf: DelegationLinkView; links: DelegationLinkView[]; chainHash: string }
|
|
45
|
+
| { ok: false; reason: string };
|
|
46
|
+
|
|
47
|
+
export function delegationChainHash(chain: readonly string[]): string;
|
|
48
|
+
export function generateWorkerKey(): { publicKey: string; privateKey: string };
|
|
49
|
+
export function createDelegationLink(opts: CreateDelegationLinkOptions): string;
|
|
50
|
+
export function checkDelegationChain(input: {
|
|
51
|
+
chain: unknown;
|
|
52
|
+
rootPassportId: string;
|
|
53
|
+
audience?: string;
|
|
54
|
+
nowSeconds?: number;
|
|
55
|
+
}): DelegationCheck;
|
|
56
|
+
export function verifyReceiptDelegation(
|
|
57
|
+
claims: { iss?: string; sub: string; auth?: unknown },
|
|
58
|
+
chain: readonly string[],
|
|
59
|
+
options?: { audience?: string; nowSeconds?: number }
|
|
60
|
+
): { ok: true; chain: DelegationCheck & { ok: true } } | { ok: false; reason: string };
|
|
@@ -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
|
+
}
|