passcontrol 1.4.0 → 1.5.1
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 +266 -8
- package/cli/budget-format.mjs +37 -0
- package/cli/claude-code.mjs +179 -0
- package/cli/client-events-upload.mjs +212 -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/otlp-logs.mjs +96 -0
- package/cli/profiles.mjs +92 -0
- package/cli/protocols.mjs +3 -1
- package/cli/sidecar.mjs +441 -21
- package/cli/statusline.mjs +223 -1
- package/cli/subscription-gate.mjs +213 -0
- package/cli/tool-gate.mjs +152 -0
- package/cli/tool-rules.d.mts +28 -0
- package/cli/tool-rules.mjs +206 -0
- package/cli/usage-window.mjs +66 -0
- package/cli/visa-client.mjs +5 -1
- package/cli/watch-feed.mjs +345 -0
- package/cli/watch.mjs +640 -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 }),
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Subscription mode's eyes (Phase 1): Claude Code's own
|
|
2
|
+
// OpenTelemetry log export, received on the sidecar's loopback listener.
|
|
3
|
+
//
|
|
4
|
+
// A Pro/Max session talks to Anthropic directly, so no call passes the sidecar. Claude
|
|
5
|
+
// Code reports each one itself when `CLAUDE_CODE_ENABLE_TELEMETRY=1` and its log
|
|
6
|
+
// exporter points here (OTLP http/json): `claude_code.api_request` with the model,
|
|
7
|
+
// tokens, API-equivalent cost and duration, and `claude_code.api_error` with the
|
|
8
|
+
// status. Prompts and tool inputs are redacted by Claude Code by default.
|
|
9
|
+
//
|
|
10
|
+
// Every record also carries the user's email, account id and organisation id. This
|
|
11
|
+
// parser copies an ALLOWLIST of fields and nothing else, so those never reach the
|
|
12
|
+
// board, a log line or a later upload. Each copied value is held to a pattern.
|
|
13
|
+
//
|
|
14
|
+
// What a reported call is NOT: a call PassControl saw. It is what the client says it
|
|
15
|
+
// did. The board shows it as SEEN, never BOARDED, and its cost as API-equivalent:
|
|
16
|
+
// a subscription pays a flat fee, and nothing here is ever charged to a budget.
|
|
17
|
+
|
|
18
|
+
export const OTLP_LOGS_PATH = "/_passcontrol/otlp/v1/logs";
|
|
19
|
+
|
|
20
|
+
const SERVICE = "claude-code";
|
|
21
|
+
const KINDS = { "claude_code.api_request": "api_request", "claude_code.api_error": "api_error" };
|
|
22
|
+
// The same patterns the watch feed holds its fields to (cli/watch-feed.mjs).
|
|
23
|
+
const DECLARED = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
24
|
+
const MODEL = /^[A-Za-z0-9._:/@-]{1,100}$/;
|
|
25
|
+
|
|
26
|
+
const held = (pattern, value) => (typeof value === "string" && pattern.test(value) ? value : null);
|
|
27
|
+
|
|
28
|
+
/** An OTLP AnyValue as a JS value: string, number, or null. int64 may arrive as a string. */
|
|
29
|
+
function scalar(value) {
|
|
30
|
+
if (!value || typeof value !== "object") return null;
|
|
31
|
+
if (typeof value.stringValue === "string") return value.stringValue;
|
|
32
|
+
if (value.intValue !== undefined) {
|
|
33
|
+
const n = typeof value.intValue === "string" ? Number(value.intValue) : value.intValue;
|
|
34
|
+
return Number.isFinite(n) ? n : null;
|
|
35
|
+
}
|
|
36
|
+
if (typeof value.doubleValue === "number" && Number.isFinite(value.doubleValue)) return value.doubleValue;
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function attributeMap(attributes) {
|
|
41
|
+
const map = new Map();
|
|
42
|
+
if (!Array.isArray(attributes)) return map;
|
|
43
|
+
for (const a of attributes) {
|
|
44
|
+
if (a && typeof a.key === "string") map.set(a.key, scalar(a.value));
|
|
45
|
+
}
|
|
46
|
+
return map;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const count = (v) => (typeof v === "number" && Number.isInteger(v) && v >= 0 && v < 2 ** 53 ? v : null);
|
|
50
|
+
const status = (v) => (typeof v === "number" && Number.isInteger(v) && v >= 100 && v < 600 ? v : null);
|
|
51
|
+
|
|
52
|
+
function timeMs(record) {
|
|
53
|
+
const raw = record?.timeUnixNano ?? record?.observedTimeUnixNano;
|
|
54
|
+
const n = typeof raw === "string" ? Number(raw.slice(0, -6) || "0") : typeof raw === "number" ? Math.floor(raw / 1e6) : NaN;
|
|
55
|
+
return Number.isFinite(n) && n > 0 ? n : null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The model calls in one OTLP ExportLogsServiceRequest (JSON). Never throws.
|
|
60
|
+
* @returns {Array<{ kind: "api_request" | "api_error", session: string | null, at: number | null, model: string | null,
|
|
61
|
+
* costMicros: number | null, inputTokens: number | null, outputTokens: number | null, cacheReadTokens: number | null,
|
|
62
|
+
* cacheCreationTokens: number | null, durationMs: number | null, status: number | null, agent: string | null }>}
|
|
63
|
+
*/
|
|
64
|
+
export function readClaudeCodeEvents(body) {
|
|
65
|
+
const events = [];
|
|
66
|
+
try {
|
|
67
|
+
if (!body || typeof body !== "object" || !Array.isArray(body.resourceLogs)) return events;
|
|
68
|
+
for (const resourceLog of body.resourceLogs) {
|
|
69
|
+
if (attributeMap(resourceLog?.resource?.attributes).get("service.name") !== SERVICE) continue;
|
|
70
|
+
for (const scopeLog of Array.isArray(resourceLog.scopeLogs) ? resourceLog.scopeLogs : []) {
|
|
71
|
+
for (const record of Array.isArray(scopeLog?.logRecords) ? scopeLog.logRecords : []) {
|
|
72
|
+
const kind = KINDS[scalar(record?.body)];
|
|
73
|
+
if (!kind) continue;
|
|
74
|
+
const a = attributeMap(record.attributes);
|
|
75
|
+
events.push({
|
|
76
|
+
kind,
|
|
77
|
+
session: held(DECLARED, a.get("session.id")),
|
|
78
|
+
at: timeMs(record),
|
|
79
|
+
model: held(MODEL, a.get("model")),
|
|
80
|
+
costMicros: kind === "api_request" ? count(a.get("cost_usd_micros")) : null,
|
|
81
|
+
inputTokens: count(a.get("input_tokens")),
|
|
82
|
+
outputTokens: count(a.get("output_tokens")),
|
|
83
|
+
cacheReadTokens: count(a.get("cache_read_tokens")),
|
|
84
|
+
cacheCreationTokens: count(a.get("cache_creation_tokens")),
|
|
85
|
+
durationMs: count(a.get("duration_ms")),
|
|
86
|
+
status: kind === "api_error" ? status(a.get("status_code")) : null,
|
|
87
|
+
agent: held(DECLARED, a.get("agent.name")),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
} catch {
|
|
93
|
+
// A malformed export shows nothing rather than breaking the sidecar.
|
|
94
|
+
}
|
|
95
|
+
return events;
|
|
96
|
+
}
|
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
|
|