// What claude-code does on a node, written against two things it is handed — a way to ask a tool on the // bus and a way to emit an event — so every path is tested without a bus (novox/hq design 36 §4–§5, // ADR 0183, ADR 0198). // // **Over NATS, in two kinds** (design 32 §10): an event says that something happened and carries no // secret, because a stream keeps it; a token travels on a request, which nothing keeps. So: // - the licence manager's `licence.rotated` and `licence.switched` events tell this module to ask the // seat for its current token, sealed to the key it sends with the request; // - a login a person made here — a refresh token this module never writes — is offered to the seat at // once, sealed to the seat's key: the one moment a refresh token travels, because the login made the // manager's stale; // - an MCP server registered for more nodes than this one is an `mcp.registered` event every node's // claude-code consumes, so a node that was off takes it when it is back. import { chmodSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { render, entryProblem, MANAGED_DIR, type Binding, type Facts, type Settings, type Servers } from "./render.js"; import { generateKeyPair, open, seal, type SealedBox } from "./seal.js"; import { decideApply, grantOf, holdsLogin, readCredentials, replacedBy, withGrant, writeCredentials, type Grant } from "./grant.js"; import { readIdentity, writeIdentity, type Identity } from "./identity.js"; export const SEAT = "anthropic-licence-manager"; export interface Paths { state: string; facts: string; settings: string; home: string; node: string; } /** A tool on the bus: its address and arguments in, its JSON answer out. */ export type Ask = (address: string, args: Record) => Promise; /** An event of this module's, by its local name. */ export type Emit = (type: string, body: unknown) => Promise; /** Write one managed file; answers what happened. */ export type WriteManaged = (name: string, content: string) => string; export const readJson = (p: string, fallback: T): T => { try { return JSON.parse(readFileSync(p, "utf8")) as T; } catch { return fallback; } }; const credentialsPath = (p: Paths) => join(p.home, ".claude", ".credentials.json"); const accountPath = (p: Paths) => join(p.home, ".claude.json"); const bindingPath = (p: Paths) => join(p.state, "licence.json"); const apiKeyPath = (p: Paths) => join(p.state, "api-key"); export const helperPath = (p: Paths) => join(p.state, "api-key-helper"); const keyPath = (p: Paths) => join(p.state, "key.pem"); const pubPath = (p: Paths) => join(p.state, "key.pub.pem"); const registryPath = (p: Paths) => join(p.state, "mcp-servers.json"); export function keypair(p: Paths): { publicKey: string; privateKey: string } { if (!existsSync(keyPath(p))) { const k = generateKeyPair(); writeFileSync(keyPath(p), k.privateKey, { mode: 0o600 }); writeFileSync(pubPath(p), k.publicKey, { mode: 0o644 }); } return { privateKey: readFileSync(keyPath(p), "utf8"), publicKey: readFileSync(pubPath(p), "utf8") }; } export function registered(p: Paths): Servers { return readJson(registryPath(p), {}); } export function renderNow(p: Paths, write: WriteManaged): string[] { const facts = readJson(p.facts, null); if (!facts?.console) throw new Error(`the mesh has not rendered ${p.facts} yet; nothing to write`); const files = render(facts, readJson(p.settings, {}), readJson(bindingPath(p), null), helperPath(p), registered(p)); return Object.entries(files).map(([name, content]) => write(name, content)); } // ---- the licence ---------------------------------------------------------------------------------- /** What the seat answers to `current`: the licence this node is bound to and its token, sealed. */ export interface Current { licence: string; kind: "subscription" | "api-key"; sealed: SealedBox; identity?: Identity | null; } /** Ask the seat for this node's current token and apply it. */ export async function pull(p: Paths, ask: Ask, write: WriteManaged): Promise> { const answer = (await ask(`${SEAT}.current`, { node: p.node, public_key: keypair(p).publicKey })) as Current | null; if (!answer?.sealed) return { applied: false, reason: "the seat holds no licence for this node" }; return apply(p, answer, write); } /** Apply what the seat handed over. A switch replaces the grant whole and cleans up after the old licence. */ export function apply(p: Paths, handed: Current, write: WriteManaged): Record { const plain = open(handed.sealed, keypair(p).privateKey); const previous = readJson(bindingPath(p), null); const switched = previous?.licence !== handed.licence; let outcome: Record = { applied: true, licence: handed.licence, kind: handed.kind, switched }; if (handed.kind === "api-key") { writeFileSync(apiKeyPath(p), plain.trim() + "\n", { mode: 0o600 }); writeFileSync(helperPath(p), `#!/bin/sh\nexec cat '${apiKeyPath(p)}'\n`, { mode: 0o700 }); chmodSync(helperPath(p), 0o700); } else { const grant = JSON.parse(plain) as Grant; const local = readCredentials(credentialsPath(p)); const d = decideApply(grantOf(local), grant, switched ? "switch" : "rotation"); if (d.apply) writeCredentials(credentialsPath(p), switched ? replacedBy(local, grant) : withGrant(local, grant)); else outcome = { applied: false, licence: handed.licence, reason: d.reason }; // Away from the API key: it goes, with its helper. rmSync(apiKeyPath(p), { force: true }); rmSync(helperPath(p), { force: true }); } if (switched && handed.identity?.accountUuid) { outcome.account = writeIdentity(accountPath(p), handed.identity) ? "updated" : "unchanged"; } writeFileSync(bindingPath(p), JSON.stringify({ licence: handed.licence, kind: handed.kind }) + "\n", { mode: 0o600 }); try { outcome.rendered = renderNow(p, write); // the key-helper comes or goes with the licence's kind } catch (err) { outcome.rendered = { failed: err instanceof Error ? err.message : String(err) }; } return outcome; } /** A licence event from the manager: is it for this node? */ export function concerns(p: Paths, type: string, body: { licence?: string; node?: string }): boolean { if (type.endsWith("licence.switched")) return body.node === p.node; if (type.endsWith("licence.rotated")) return body.licence === readJson(bindingPath(p), null)?.licence; return false; } /** A refresh token in the credentials file is a login: this module never writes one. Offer it to the seat. */ export async function offerLogin(p: Paths, ask: Ask): Promise | null> { const creds = readCredentials(credentialsPath(p)); if (!holdsLogin(creds)) return null; const key = (await ask(`${SEAT}.public_key`, {})) as { public_key?: string } | null; if (!key?.public_key) throw new Error("the licence manager did not say what key to seal a login to"); return (await ask(`${SEAT}.adopt`, { node: p.node, identity: readIdentity(accountPath(p)), sealed: seal(JSON.stringify(creds!.claudeAiOauth), key.public_key), })) as Record; } // ---- MCP servers ---------------------------------------------------------------------------------- export interface Registration { name: string; entry?: Record; /** Which nodes: this one (absent), every node running the module ("all"), or a list. */ nodes?: "all" | string[]; } function setRegistered(p: Paths, name: string, entry: Record | null): boolean { const list = { ...registered(p) } as Record>; const before = JSON.stringify(list[name] ?? null); if (entry) list[name] = entry; else delete list[name]; if (JSON.stringify(list[name] ?? null) === before) return false; writeFileSync(registryPath(p), JSON.stringify(list, null, 2) + "\n", { mode: 0o600 }); return true; } const targets = (p: Paths, nodes: Registration["nodes"]) => nodes === "all" ? true : Array.isArray(nodes) ? nodes.includes(p.node) : false; /** Register (or with no entry, unregister) here, and announce it for the other nodes asked for. */ export async function registerServer(p: Paths, r: Registration, emit: Emit, write: WriteManaged, others: () => Promise): Promise> { if (r.entry) { const problem = entryProblem(r.name, r.entry); if (problem) return { registered: false, reason: problem }; } const here = r.nodes === undefined || targets(p, r.nodes); const changed = here ? setRegistered(p, r.name, r.entry ?? null) : false; const rendered = here && changed ? renderNow(p, write) : []; if (r.nodes !== undefined) { await emit(r.entry ? "mcp.registered" : "mcp.unregistered", { name: r.name, entry: r.entry ?? null, nodes: r.nodes }); } const answer: Record = { [r.entry ? "registered" : "unregistered"]: r.name, on: r.nodes === undefined ? [p.node] : r.nodes, here: here ? (changed ? "changed" : "already so") : "not this node", rendered, }; if (r.nodes === undefined) { // The question the operator wanted asked: here only, or more? const elsewhere = (await others().catch(() => [] as string[])).filter((n) => n !== p.node); answer.also = elsewhere.length ? `claude-code also runs on ${elsewhere.join(", ")}. To ${r.entry ? "register" : "unregister"} it there too, call again with nodes: "all" or a list of those nodes.` : `To do the same on every node running claude-code, call again with nodes: "all".`; } return answer; } /** An `mcp.registered`/`mcp.unregistered` event from any node's claude-code: apply it if it names this node. */ export function onServerEvent(p: Paths, type: string, body: Registration, write: WriteManaged): string | null { if (!body?.name || !targets(p, body.nodes)) return null; const entry = type.endsWith("mcp.registered") ? body.entry ?? null : null; if (entry && entryProblem(body.name, entry)) return null; if (!setRegistered(p, body.name, entry)) return null; renderNow(p, write); return `${entry ? "registered" : "unregistered"} ${body.name} from an event`; } export { MANAGED_DIR };