The licence manager, in Go, and claude-code's half of ADR 0206
claude-licence-manager holds the anthropic-licence-manager seat: it reads every node's holdings state, adopts a login it does not hold by refreshing it (newest first, once per account), keeps each grant alive under a lease, publishes what each consumer should hold as its bindings state with a generation, and answers current sealed to the consumer's key. Postgres store prepared by a run-once step; grants encrypted with the vault's key. claude-code reports what its node holds (fingerprints and account, never a token), hands its grant over only when the manager asks, watches its binding and fetches the token on a newer generation, and writes access-token-only. Its ask now reads the runtime's answer as a value and addresses seats as seats.
This commit is contained in:
+116
-36
@@ -2,19 +2,21 @@
|
||||
// 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 through this module is **state, not an event** (novox/hq ADR 0201): one
|
||||
// key per server in the module's `servers` bucket — `all.<server>` for every node, `<node>.<server>`
|
||||
// for one — which every node watches. A node that joins later, or was off, reads the whole current set
|
||||
// at start; unregistering is a delete. A secret never goes in an entry: the runtime refuses one.
|
||||
// **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.<server>` for
|
||||
// every node, `<node>.<server>` for one — which every node watches.
|
||||
|
||||
import { chmodSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
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";
|
||||
@@ -23,6 +25,13 @@ import { decideApply, grantOf, holdsLogin, readCredentials, replacedBy, withGran
|
||||
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;
|
||||
@@ -79,25 +88,112 @@ export function renderNow(p: Paths, write: WriteManaged): string[] {
|
||||
|
||||
// ---- 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<string, unknown> | undefined;
|
||||
const applied = readJson<Applied | null>(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<Record<string, unknown>> {
|
||||
const answer = (await ask(`${SEAT}.current`, { node: p.node, public_key: keypair(p).publicKey })) as Current | null;
|
||||
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<string | null> {
|
||||
if (!b) return "this node's binding was released; it keeps its last token until it expires";
|
||||
const applied = readJson<Applied | null>(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<string, unknown> {
|
||||
const plain = open(handed.sealed, keypair(p).privateKey);
|
||||
const previous = readJson<Binding | null>(bindingPath(p), null);
|
||||
const previous = readJson<Applied | null>(bindingPath(p), null);
|
||||
const switched = previous?.licence !== handed.licence;
|
||||
let outcome: Record<string, unknown> = { applied: true, licence: handed.licence, kind: handed.kind, switched };
|
||||
if (handed.kind === "api-key") {
|
||||
@@ -107,7 +203,10 @@ export function apply(p: Paths, handed: Current, write: WriteManaged): Record<st
|
||||
} else {
|
||||
const grant = JSON.parse(plain) as Grant;
|
||||
const local = readCredentials(credentialsPath(p));
|
||||
const d = decideApply(grantOf(local), grant, switched ? "switch" : "rotation");
|
||||
// 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.
|
||||
@@ -117,7 +216,8 @@ export function apply(p: Paths, handed: Current, write: WriteManaged): Record<st
|
||||
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 });
|
||||
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) {
|
||||
@@ -126,26 +226,6 @@ export function apply(p: Paths, handed: Current, write: WriteManaged): Record<st
|
||||
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<Binding | null>(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<Record<string, unknown> | 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<string, unknown>;
|
||||
}
|
||||
|
||||
// ---- MCP servers ----------------------------------------------------------------------------------
|
||||
|
||||
export interface Registration {
|
||||
|
||||
Reference in New Issue
Block a user