// 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** (design 32 §10, ADR 0201, ADR 0206): what is *current* is state, a secret only ever // travels on a request, sealed to its one recipient, and nothing is an event any more: // - **what this node holds** is the module's `holdings` state, one key per node: the account, the kind, // fingerprints and expiries — never a token. Written at start and on every change of the credentials // file, so the licence manager learns a login, or a node already logged in, from the state alone; // - **the grant itself** leaves only when the manager asks `claude_code_grant`, sealed to the key it // gives — the manager adopts a licence by refreshing it, and from then on is its only refresher; // - **what this node should hold** is the manager's `bindings` state; a newer generation for this node // is fetched with the seat's `current` verb, sealed to this module's key, and written access-token-only, // so the agent here never refreshes and a refresh token appearing later is a person's login; // - an MCP server registered through this module is a key in its `servers` state — `all.` for // every node, `.` for one — which every node watches. import { chmodSync, existsSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { createHash } from "node:crypto"; 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"; /** The manager module whose `bindings` state this module reads (ADR 0206). */ export const MANAGER = "claude-licence-manager"; /** A seat's verb as the runtime addresses it: a role, not a module. */ export const seatVerb = (verb: string) => `seat:${SEAT}.${verb}`; /** A token named without being one: the first 16 hex of its SHA-256. */ export const fingerprint = (s: string) => "sha256:" + createHash("sha256").update(s).digest("hex").slice(0, 16); 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 licence this node holds was, as it was last applied: its name, kind and generation. */ export interface Applied extends Binding { readonly generation?: number; } /** What the manager's `bindings` state says one consumer should hold (ADR 0206). */ export interface BindingState { readonly licence: string; readonly kind: "subscription" | "api-key"; readonly generation: number; } /** 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"; generation?: number; sealed: SealedBox; identity?: Identity | null; } /** * What this node holds, as the `holdings` state carries it (ADR 0206): enough for the manager to tell a * login it has not adopted from one it has, and never a token — fingerprints and expiries only. */ export interface Holdings { readonly node: string; readonly identity: Identity | null; readonly kind: "subscription" | "api-key" | null; /** The refresh token's fingerprint, and whether the file holds one at all: a login waiting. */ readonly refresh: { readonly present: boolean; readonly fingerprint: string | null; readonly expiresAt: number | null }; readonly access: { readonly fingerprint: string; readonly expiresAt: number } | null; /** The licence and generation this module last applied, or null before any. */ readonly licence: string | null; readonly generation: number; /** When the credentials file last changed: the newest login of several is tried first. */ readonly changedAt: string | null; } export function holdingsOf(p: Paths): Holdings { const creds = readCredentials(credentialsPath(p)); const o = creds?.claudeAiOauth as Record | undefined; const applied = readJson(bindingPath(p), null); let changedAt: string | null = null; try { changedAt = statSync(credentialsPath(p)).mtime.toISOString(); } catch { /* no file */ } const refreshValue = typeof o?.refreshToken === "string" && o.refreshToken ? o.refreshToken : null; const accessValue = typeof o?.accessToken === "string" && o.accessToken ? o.accessToken : null; const apiKey = existsSync(apiKeyPath(p)); return { node: p.node, identity: readIdentity(accountPath(p)), kind: apiKey ? "api-key" : accessValue ? "subscription" : null, refresh: { present: refreshValue !== null, fingerprint: refreshValue ? fingerprint(refreshValue) : null, expiresAt: o?.refreshTokenExpiresAt == null ? null : Number(o.refreshTokenExpiresAt), }, access: accessValue ? { fingerprint: fingerprint(accessValue), expiresAt: Number(o?.expiresAt ?? 0) } : null, licence: applied?.licence ?? null, generation: applied?.generation ?? 0, changedAt, }; } /** * The full grant in the credentials file, sealed to the key the manager gives — the one time a refresh * token leaves this node, for the manager to adopt by refreshing it (ADR 0206). Null when the file holds * no refresh token: there is nothing to adopt. */ export function grantFor(p: Paths, managerPublicKey: string): { sealed: SealedBox; identity: Identity | null; fingerprint: string } | null { const creds = readCredentials(credentialsPath(p)); if (!holdsLogin(creds)) return null; const oauth = creds!.claudeAiOauth!; return { sealed: seal(JSON.stringify(oauth), managerPublicKey), identity: readIdentity(accountPath(p)), fingerprint: fingerprint(String(oauth.refreshToken)), }; } /** 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(seatVerb("current"), { consumer: 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); } /** * The manager's `bindings` key for this node changed (ADR 0206): fetch the token when the generation is * newer than the one applied. A released binding keeps the last token, which lives hours, and says so. */ export async function onBinding(p: Paths, b: BindingState | null, ask: Ask, write: WriteManaged): Promise { if (!b) return "this node's binding was released; it keeps its last token until it expires"; const applied = readJson(bindingPath(p), null); if (applied && (applied.generation ?? 0) >= b.generation) return null; return JSON.stringify(await pull(p, ask, 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)); // A login waiting here was handed to the manager first (ADR 0206): what comes back is its successor, // and the refresh token in the file is the one the manager just spent. Written access-token-only // either way, so the agent here never refreshes. const d = decideApply(grantOf(local), grant, switched || holdsLogin(local) ? "switch" : "rotation"); if (d.apply) writeCredentials(credentialsPath(p), switched ? replacedBy(local, grant) : withGrant(local, grant)); else outcome = { applied: false, licence: handed.licence, reason: "reason" in d ? d.reason : undefined }; // narrowed by hand: the build compiles without strict // 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"; } const applied: Applied = { licence: handed.licence, kind: handed.kind, generation: handed.generation ?? previous?.generation ?? 0 }; writeFileSync(bindingPath(p), JSON.stringify(applied) + "\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; } // ---- 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[]; } /** The `servers` state, as this module reaches it through the runtime (`state("servers")` in the SDK). */ export interface ServerState { put(key: string, value: Record): Promise; delete(key: string): Promise; keys(): Promise; } /** One change to the `servers` state, as a watch hands it over. */ export interface ServerChange { key: string; op: "put" | "delete"; value?: Record; } /** The key a registration lives at: `all.` for every node, `.` for one. */ export const keyOf = (scope: string, name: string) => `${scope}.${name}`; /** * What this node takes from the `servers` state: the entries for every node and for this one, by key — * kept in memory from the watch, and written through to the module's own file whenever what applies here * changes, so the managed directory can be rendered without the bus. */ export class ServerView { private readonly entries = new Map>(); constructor(private readonly p: Paths) {} /** Take one change; answers whether what applies to this node changed. */ take(c: ServerChange): boolean { const dot = c.key.indexOf("."); const scope = c.key.slice(0, dot), name = c.key.slice(dot + 1); if (dot <= 0 || (scope !== "all" && scope !== this.p.node)) return false; if (c.op === "put" && c.value && entryProblem(name, c.value) === null) this.entries.set(c.key, c.value); else this.entries.delete(c.key); return this.writeThrough(); } /** What applies here: every node's entries, with this node's own laid over them by server name. */ effective(): Servers { const out: Record> = {}; for (const scope of ["all", this.p.node]) { for (const [key, entry] of [...this.entries].sort(([a], [b]) => a.localeCompare(b))) { if (key.startsWith(scope + ".")) out[key.slice(scope.length + 1)] = entry; } } return out; } private writeThrough(): boolean { const now = JSON.stringify(this.effective(), null, 2) + "\n"; let before = ""; try { before = readFileSync(registryPath(this.p), "utf8"); } catch { /* none yet */ } if (now === before) return false; writeFileSync(registryPath(this.p), now, { mode: 0o600 }); return true; } } /** A change from the watch: take it, and render when what applies here changed. */ export function onServerChange(view: ServerView, c: ServerChange, p: Paths, write: WriteManaged): string | null { if (!view.take(c)) return null; renderNow(p, write); return `${c.op === "put" ? "registered" : "unregistered"} ${c.key}`; } const scopesOf = (p: Paths, nodes: Registration["nodes"]): string[] => nodes === undefined ? [p.node] : nodes === "all" ? ["all"] : nodes; /** * Register (or with no entry, unregister) a server: a put (or delete) per scope in the `servers` state. * Taken into this node's view at once, so the answer says what it did here; every other node takes it * from its watch, and a node that joins later from the current state. */ export async function registerServer(p: Paths, r: Registration, servers: ServerState, view: ServerView, write: WriteManaged, others: () => Promise): Promise> { if (r.entry) { const problem = entryProblem(r.name, r.entry); if (problem) return { registered: false, reason: problem }; } const scopes = scopesOf(p, r.nodes); // Compared before and after rather than read from take(): this node's own watch may hand the view the // same change first, and then take() here finds nothing new although this call made it. const before = JSON.stringify(view.effective()); for (const scope of scopes) { const key = keyOf(scope, r.name); if (r.entry) await servers.put(key, r.entry); else await servers.delete(key); view.take({ key, op: r.entry ? "put" : "delete", value: r.entry }); } const changedHere = JSON.stringify(view.effective()) !== before; const here = scopes.includes("all") || scopes.includes(p.node); const answer: Record = { [r.entry ? "registered" : "unregistered"]: r.name, on: r.nodes === undefined ? [p.node] : r.nodes, here: here ? (changedHere ? "changed" : "already so") : "not this node", rendered: changedHere ? renderNow(p, write) : [], }; if (!r.entry && view.effective()[r.name]) { answer.still = `${r.name} still applies here from another registration (for every node, or for this one); unregister that too`; } 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; } export { MANAGED_DIR };