anthropic model-access modules: manager (refreshable-grant) and consumer

Phase C of vendor-agnostic model-access (ADR 0050/0054). Two TypeScript
runtime modules:

- anthropic-manager: the refresh token is sealed at rest to the manager
  node's own key (atrest.ts, envelope encryption over X25519) and opened
  ONLY on the manager node. adopt seals the first envelope; refresh opens
  it, calls the Anthropic OAuth token endpoint, re-seals a rotated refresh
  token, and hands the control plane only the access token plus the opaque
  envelope. Also polls licence-grain usage (ADR 0054).
- anthropic-consumer: writes the delivered access token to
  ~/.claude/.credentials.json, access-token-only, atomically (the refresh
  token is never delivered); reports session-grain usage from the CLI
  transcripts; a fail-closed identity guard (expected-uuid plumbing is a
  flagged TODO).

Both run as scheduled containers (ADR 0053). Pure logic covered by
node --test fixtures (at-rest round-trip, credential strip, transcript
sum, refresh merge).

Claude-Session: https://claude.ai/code/session_01LrgweAeERJYBg88c5cKDzF
This commit is contained in:
2026-09-07 01:00:12 +02:00
parent cd46d53464
commit c206e2e11e
19 changed files with 1293 additions and 0 deletions
+75
View File
@@ -0,0 +1,75 @@
// The consumer's scheduled run: take the ACCESS token the mesh delivered and write it where the
// Claude CLI reads it, access-token-only (novox/hq ADR 0050). The refresh token is never here to
// strip — the manager holds it, and a holder's delivery has only ever been the access token.
//
// What the host delivers, per the manifest:
// secrets.model-access -> a file holding the sealed-then-unsealed ACCESS token (the host opened it
// with this node's private key; this process reads plaintext).
// binds.model-access -> a JSON file of the non-secret facts the licence serves (which licence,
// model, and — when the control plane carries them — grant expiry/scopes).
//
// Runs as `mesh-tools run` (no broker) on a schedule, so it is idempotent: same token in, same file
// out.
import { readFileSync } from "node:fs";
import { deliver, type DeliveredGrant } from "../credentials.js";
import { readAccountUuid, check } from "../identity.js";
function required(name: string): string {
const v = process.env[name];
if (!v) throw new Error(`${name} is not set — the consumer runtime was deployed without it`);
return v;
}
/** Read optional non-secret grant metadata (expiry, scopes, subscription) from the bound facts file. */
function readBoundMeta(path: string | undefined): Partial<DeliveredGrant> {
if (!path) return {};
try {
const raw = JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
return {
expiresAt: typeof raw.expiresAt === "number" ? raw.expiresAt : null,
refreshTokenExpiresAt: typeof raw.refreshTokenExpiresAt === "number" ? raw.refreshTokenExpiresAt : null,
scopes: Array.isArray(raw.scopes) ? (raw.scopes as string[]) : null,
subscriptionType: typeof raw.subscriptionType === "string" ? raw.subscriptionType : null,
};
} catch {
return {};
}
}
function main(): void {
const accessToken = readFileSync(required("MESH_MODEL_ACCESS_SECRET_FILE"), "utf8").trim();
if (!accessToken) {
// Nothing was delivered — which reads exactly like a credential that never arrived, so it is
// said rather than written as an empty file the CLI would take for a login it should not do.
throw new Error("[anthropic-consumer] the delivered access token is empty; nothing was written");
}
const meta = readBoundMeta(process.env.MESH_MODEL_ACCESS_BIND_FILE);
const grant: DeliveredGrant = { accessToken, ...meta };
const target = process.env.MESH_CLAUDE_CREDENTIALS_FILE ?? `${homedir()}/.claude/.credentials.json`;
deliver(target, grant);
console.error(`[anthropic-consumer] wrote an access-token-only credential to ${target}`);
// The mis-binding guard, best-effort and fail-closed. The expected account uuid is not yet plumbed
// (identity.ts TODO), so this reports what it can see rather than acting on it — it never delivers
// to a wrong account because it never learns one to deliver to.
const identityFile = process.env.MESH_CLAUDE_IDENTITY_FILE ?? `${homedir()}/.claude.json`;
const found = readAccountUuid(identityFile);
const expected = process.env.MESH_MODEL_ACCESS_ACCOUNT_UUID ?? null;
const verdict = check(found, expected);
if (verdict.state === "wrong-account") {
throw new Error(
`[anthropic-consumer] the CLI is logged in as ${verdict.found}, not the licensed ${verdict.expected}; refusing`,
);
}
console.error(`[anthropic-consumer] identity check: ${verdict.state}`);
}
function homedir(): string {
return process.env.HOME ?? "/root";
}
main();
+82
View File
@@ -0,0 +1,82 @@
// Writing the access token where the Claude CLI reads it — the consumer half of model-access
// (novox/hq ADR 0050). A node holds an ACCESS token and nothing else: it cannot rotate, so it is
// never given a refresh token, and this enforces that on every write.
//
// The file shape and the strip are ported byte-exact from the mature implementation (see the port
// map): `~/.claude/.credentials.json` → `{ claudeAiOauth: { accessToken, expiresAt,
// refreshTokenExpiresAt?, scopes?, subscriptionType? } }`, and the refresh token is deleted, not
// merely omitted, so a full grant left by an interactive login is stripped back to access-only.
import { readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
import { dirname } from "node:path";
/** The access-token-only grant the mesh delivered — what the manager submitted, minus the refresh. */
export interface DeliveredGrant {
readonly accessToken: string;
readonly expiresAt?: number | null;
readonly refreshTokenExpiresAt?: number | null;
readonly scopes?: string[] | null;
readonly subscriptionType?: string | null;
}
interface ClaudeOauth {
accessToken?: string;
expiresAt?: number;
refreshTokenExpiresAt?: number;
scopes?: string[];
subscriptionType?: string;
refreshToken?: string;
}
interface Credentials {
claudeAiOauth?: ClaudeOauth;
[key: string]: unknown;
}
/** Read the existing credentials file, or an empty object if there is none or it is unreadable. */
function readLocal(path: string): Credentials {
try {
return JSON.parse(readFileSync(path, "utf8")) as Credentials;
} catch {
return {};
}
}
/**
* Overlay the delivered grant onto whatever is on disk, then STRIP the refresh token — the node
* carve-out. Returns the object to write, so the strip is testable without touching a file.
*/
export function applyGrant(local: Credentials, grant: DeliveredGrant): Credentials {
const oauth = local.claudeAiOauth ?? {};
const next: Credentials = {
...local,
claudeAiOauth: {
...oauth,
accessToken: grant.accessToken,
...(grant.expiresAt != null ? { expiresAt: grant.expiresAt } : {}),
...(grant.refreshTokenExpiresAt != null
? { refreshTokenExpiresAt: grant.refreshTokenExpiresAt }
: {}),
...(grant.scopes ? { scopes: grant.scopes } : {}),
...(grant.subscriptionType ? { subscriptionType: grant.subscriptionType } : {}),
},
};
// A node NEVER holds a refresh token: delete it, so a full grant on disk is reduced to access-only.
delete next.claudeAiOauth!.refreshToken;
return next;
}
/** Atomic write-then-rename at 0600 — a partial credentials file must never be read as a whole one. */
export function writeCredentials(path: string, creds: Credentials): void {
mkdirSync(dirname(path), { recursive: true });
const tmp = `${path}.tmp`;
writeFileSync(tmp, JSON.stringify(creds, null, 2), { mode: 0o600 });
renameSync(tmp, path);
}
/** Read, overlay, strip, write — the whole consumer credential update, in one call. */
export function deliver(path: string, grant: DeliveredGrant): Credentials {
const next = applyGrant(readLocal(path), grant);
writeCredentials(path, next);
return next;
}
+49
View File
@@ -0,0 +1,49 @@
// The mis-binding guard (novox/hq ADR 0050, port map §identity). Account identity is NOT in the
// token or any API — it lives in a sibling CLI state file, `~/.claude.json` →
// `oauthAccount.accountUuid`. The guard compares the account the CLI is actually logged in as to the
// account the licence was recorded against, and FAILS CLOSED: an absent file or an unrecorded licence
// account refuses rather than guesses, because delivering an access token to the wrong account is the
// exact fault this exists to catch.
//
// **Partial first cut, FLAGGED.** Reading the sibling file is implemented; the licence's recorded
// account uuid is not yet plumbed from the control plane to the consumer (the bound `model.json` does
// not carry it today). So `check` returns `licence-not-adopted` when no expected uuid is supplied,
// which is the fail-closed answer, and the wiring of the expected uuid is a TODO below.
import { readFileSync } from "node:fs";
export type IdentityVerdict =
| { state: "verified"; accountUuid: string }
| { state: "no-identity-file" }
| { state: "licence-not-adopted" }
| { state: "wrong-account"; found: string; expected: string };
interface ClaudeJson {
oauthAccount?: { accountUuid?: string; emailAddress?: string; organizationUuid?: string };
}
/** Read `oauthAccount.accountUuid` from `~/.claude.json`, or null if the file or field is absent. */
export function readAccountUuid(path: string): string | null {
try {
const raw = JSON.parse(readFileSync(path, "utf8")) as ClaudeJson;
return raw.oauthAccount?.accountUuid ?? null;
} catch {
return null;
}
}
/**
* Compare the CLI's logged-in account to the one the licence was recorded against. Pure over its
* inputs so the fail-closed logic is tested without a filesystem.
*
* TODO(novox/hq ADR 0050, Phase C): plumb `expected` — the licence's recorded account uuid — from the
* control plane into the consumer's bound `model.json`, then adopt-on-first-sight or refuse per the
* port map's five states. Until then only the two safe verdicts are reachable: verified when an
* expected uuid is provided and matches, refuse otherwise.
*/
export function check(found: string | null, expected: string | null): IdentityVerdict {
if (found === null) return { state: "no-identity-file" };
if (!expected) return { state: "licence-not-adopted" };
if (found === expected) return { state: "verified", accountUuid: found };
return { state: "wrong-account", found, expected };
}
+91
View File
@@ -0,0 +1,91 @@
{
"module": "anthropic-consumer",
"version": "1",
"capabilities": [
"container-runtime"
],
"requires": [
"model-access"
],
"binds": {
"model-access": "/var/lib/anthropic-consumer/model.json"
},
"secrets": {
"model-access": "/var/lib/anthropic-consumer/access-token"
},
"own-secrets": {
"broker": "/var/lib/mesh/anthropic-consumer/broker"
},
"emits": [
"module.anthropic-consumer.usage.session"
],
"resources": [
{
"id": "mesh-state",
"type": "directory",
"path": "/var/lib/mesh/anthropic-consumer",
"mode": "0700"
},
{
"id": "state",
"type": "directory",
"path": "/var/lib/anthropic-consumer",
"mode": "0700"
},
{
"id": "claude-home",
"type": "directory",
"path": "/var/lib/anthropic-consumer/claude",
"mode": "0700"
},
{
"id": "out",
"type": "directory",
"path": "/var/lib/anthropic-consumer/out",
"mode": "0700"
},
{
"id": "apply",
"type": "container",
"name": "mesh-anthropic-consumer-apply",
"image": "mesh-runtime-anthropic-consumer@sha256:0000000000000000000000000000000000000000000000000000000000000000",
"network": "host",
"schedule": "*/5 * * * *",
"args": [
"run",
"/app/modules/anthropic-consumer/dist/apply/index.js"
],
"volumes": [
"/var/lib/anthropic-consumer:/run/state"
],
"env": {
"MESH_MODEL_ACCESS_SECRET_FILE": "/run/state/access-token",
"MESH_MODEL_ACCESS_BIND_FILE": "/run/state/model.json",
"MESH_CLAUDE_CREDENTIALS_FILE": "/run/state/claude/.credentials.json",
"MESH_CLAUDE_IDENTITY_FILE": "/run/state/claude/.claude.json"
}
},
{
"id": "usage",
"type": "container",
"name": "mesh-anthropic-consumer-usage",
"image": "mesh-runtime-anthropic-consumer@sha256:0000000000000000000000000000000000000000000000000000000000000000",
"network": "host",
"schedule": "*/5 * * * *",
"args": [
"run",
"/app/modules/anthropic-consumer/dist/usage/index.js"
],
"volumes": [
"/var/lib/mesh/anthropic-consumer/broker:/run/secrets/broker:ro",
"/var/lib/anthropic-consumer:/run/state"
],
"env": {
"MESH_BROKER_FILE": "/run/secrets/broker",
"MESH_CLAUDE_PROJECTS_DIR": "/run/state/claude/projects",
"MESH_ANTHROPIC_USAGE_OUT": "/run/state/out/session-usage.json",
"MESH_TOOLS_MAIN": "/app/dist/main.js"
}
}
]
}
+14
View File
@@ -0,0 +1,14 @@
{
"name": "@novox/module-anthropic-consumer",
"version": "0.1.0",
"description": "anthropic-consumer — the consumer side of model-access (ADR 0050): writes the delivered access token to ~/.claude/.credentials.json (access-token-only) and reports session-grain usage from the CLI transcripts (ADR 0054).",
"type": "module",
"private": true,
"dependencies": {
"@novox/mesh-sdk": "^0.1.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
"typescript": "^5.6.0"
}
}
@@ -0,0 +1,32 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { applyGrant, deliver } from "../credentials.ts";
test("applyGrant strips the refresh token a full grant on disk left behind", () => {
const local = { claudeAiOauth: { accessToken: "at-old", refreshToken: "rt-must-not-survive" } };
const next = applyGrant(local, { accessToken: "at-new", expiresAt: 123 });
assert.equal(next.claudeAiOauth!.accessToken, "at-new");
assert.equal(next.claudeAiOauth!.expiresAt, 123);
assert.ok(!("refreshToken" in next.claudeAiOauth!), "a node held onto a refresh token");
});
test("deliver writes the port-map shape, access-token-only, and never a refresh token", () => {
const dir = mkdtempSync(join(tmpdir(), "anthropic-consumer-"));
const path = join(dir, ".credentials.json");
// A prior interactive login left a full grant on disk.
writeFileSync(path, JSON.stringify({ claudeAiOauth: { accessToken: "at-old", refreshToken: "rt-login" } }));
deliver(path, { accessToken: "at-delivered", expiresAt: 999, subscriptionType: "max" });
const raw = readFileSync(path, "utf8");
const creds = JSON.parse(raw);
assert.equal(creds.claudeAiOauth.accessToken, "at-delivered");
assert.equal(creds.claudeAiOauth.expiresAt, 999);
assert.equal(creds.claudeAiOauth.subscriptionType, "max");
assert.doesNotMatch(raw, /rt-login/, "the refresh token is still on disk");
assert.ok(!("refreshToken" in creds.claudeAiOauth));
});
@@ -0,0 +1,48 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { foldTranscript } from "../transcript.ts";
// A captured-shape transcript: two assistant turns and a user line, exactly the fields the port map
// names. Not imagined — the field names match the mature implementation's parse.
const TRANSCRIPT = [
JSON.stringify({ type: "user", timestamp: "2026-01-01T00:00:00Z", cwd: "/work/app", gitBranch: "main" }),
JSON.stringify({
type: "assistant",
timestamp: "2026-01-01T00:00:01Z",
costUSD: 0.01,
message: {
model: "claude-opus-4-8",
usage: { input_tokens: 100, cache_creation_input_tokens: 20, cache_read_input_tokens: 5, output_tokens: 40 },
},
}),
JSON.stringify({
type: "assistant",
timestamp: "2026-01-01T00:00:02Z",
costUSD: 0.02,
message: { model: "claude-opus-4-8", usage: { input_tokens: 200, output_tokens: 60 } },
}),
"", // a half-written trailing line is ordinary and must not be fatal.
].join("\n");
test("a transcript sums per-session token counts, cost, and metadata", () => {
const s = foldTranscript("session-abc", TRANSCRIPT);
assert.equal(s.sessionId, "session-abc");
assert.equal(s.turns, 2);
assert.equal(s.inputTokens, 300);
assert.equal(s.cacheCreationTokens, 20);
assert.equal(s.cacheReadTokens, 5);
assert.equal(s.outputTokens, 100);
assert.equal(Math.round(s.costUSD * 100) / 100, 0.03);
assert.equal(s.model, "claude-opus-4-8");
assert.equal(s.gitBranch, "main");
assert.equal(s.cwd, "/work/app");
assert.equal(s.startedAt, "2026-01-01T00:00:00Z");
assert.equal(s.lastActive, "2026-01-01T00:00:02Z");
});
test("a malformed line is skipped, not fatal", () => {
const s = foldTranscript("s", 'not json\n{"type":"assistant","message":{"usage":{"output_tokens":7}}}');
assert.equal(s.outputTokens, 7);
assert.equal(s.turns, 1);
});
+113
View File
@@ -0,0 +1,113 @@
// Session-grain usage from the CLI's own transcripts (novox/hq ADR 0054). The mature implementation
// reads `~/.claude/projects/<projDir>/<sessionId>.jsonl` and sums the token counts each assistant
// message reports; this ports the token extraction and DROPS the per-message account-attribution
// timeline — the nox (node,module) session has a fixed licence binding (port map "don't-map" #3), so
// there is nothing to attribute per message.
//
// The fields are ported from the port map: assistant lines carry
// `message.usage.{input_tokens,cache_creation_input_tokens,cache_read_input_tokens,output_tokens}`,
// `costUSD`, `message.model`, `timestamp`; user lines carry `cwd`, `gitBranch`.
import { createInterface } from "node:readline";
import { createReadStream } from "node:fs";
/** One session's totals — the session-grain usage row ADR 0054 fixes. */
export interface SessionUsage {
sessionId: string;
model: string | null;
gitBranch: string | null;
cwd: string | null;
turns: number;
inputTokens: number;
cacheCreationTokens: number;
cacheReadTokens: number;
outputTokens: number;
costUSD: number;
startedAt: string | null;
lastActive: string | null;
}
interface Line {
type?: string;
timestamp?: string;
cwd?: string;
gitBranch?: string;
costUSD?: number;
message?: {
model?: string;
usage?: {
input_tokens?: number;
cache_creation_input_tokens?: number;
cache_read_input_tokens?: number;
output_tokens?: number;
};
};
}
function empty(sessionId: string): SessionUsage {
return {
sessionId,
model: null,
gitBranch: null,
cwd: null,
turns: 0,
inputTokens: 0,
cacheCreationTokens: 0,
cacheReadTokens: 0,
outputTokens: 0,
costUSD: 0,
startedAt: null,
lastActive: null,
};
}
/** Fold one transcript line into a session's running totals. Pure, so it is tested on fixtures. */
export function foldLine(acc: SessionUsage, raw: string): SessionUsage {
const line = parse(raw);
if (!line) return acc;
if (line.timestamp) {
if (!acc.startedAt || line.timestamp < acc.startedAt) acc.startedAt = line.timestamp;
if (!acc.lastActive || line.timestamp > acc.lastActive) acc.lastActive = line.timestamp;
}
if (line.type === "user") {
if (line.cwd) acc.cwd = line.cwd;
if (line.gitBranch) acc.gitBranch = line.gitBranch;
}
if (line.type === "assistant") {
acc.turns += 1;
const u = line.message?.usage ?? {};
acc.inputTokens += u.input_tokens ?? 0;
acc.cacheCreationTokens += u.cache_creation_input_tokens ?? 0;
acc.cacheReadTokens += u.cache_read_input_tokens ?? 0;
acc.outputTokens += u.output_tokens ?? 0;
acc.costUSD += line.costUSD ?? 0;
if (!acc.model && line.message?.model) acc.model = line.message.model;
}
return acc;
}
function parse(raw: string): Line | null {
const trimmed = raw.trim();
if (!trimmed) return null;
try {
return JSON.parse(trimmed) as Line;
} catch {
// A malformed line is skipped, never fatal: a transcript is an append-only log the CLI owns, and
// a half-written last line is ordinary.
return null;
}
}
/** Sum a whole transcript string into one session's usage — the tested core of the streaming read. */
export function foldTranscript(sessionId: string, text: string): SessionUsage {
return text.split("\n").reduce(foldLine, empty(sessionId));
}
/** Stream one `<sessionId>.jsonl` file line by line, so a large transcript never loads whole. */
export async function readSessionFile(path: string, sessionId: string): Promise<SessionUsage> {
const acc = empty(sessionId);
const rl = createInterface({ input: createReadStream(path), crlfDelay: Infinity });
for await (const line of rl) foldLine(acc, line);
return acc;
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"noEmit": true
},
"include": [
"credentials.ts",
"transcript.ts",
"identity.ts",
"apply/index.ts",
"usage/index.ts"
]
}
+92
View File
@@ -0,0 +1,92 @@
// Session-grain usage emission (novox/hq ADR 0054). On a schedule, read every transcript under
// `~/.claude/projects/*/<sessionId>.jsonl`, sum its tokens, and emit one session-grain usage event
// per session. The consumer IS the (node,module) session's fixed binding, so no per-message account
// attribution is done — just the totals (port map "don't-map" #3).
//
// Runs as `mesh-tools run` (no broker), so events are emitted best-effort via the sibling mesh-tools
// `emit` primitive; the totals are also written to a file so the reading is observable without one.
import { readdirSync, statSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
import { join, dirname } from "node:path";
import { readSessionFile, type SessionUsage } from "../transcript.js";
function projectsDir(): string {
return process.env.MESH_CLAUDE_PROJECTS_DIR ?? `${process.env.HOME ?? "/root"}/.claude/projects`;
}
/** Every `<sessionId>.jsonl` under the projects tree, with the project directory it sits in. */
function transcripts(root: string): { path: string; sessionId: string }[] {
const found: { path: string; sessionId: string }[] = [];
let projects: string[];
try {
projects = readdirSync(root);
} catch {
return found; // no projects yet is not a failure — there is simply nothing to report.
}
for (const proj of projects) {
const dir = join(root, proj);
let entries: string[];
try {
if (!statSync(dir).isDirectory()) continue;
entries = readdirSync(dir);
} catch {
continue;
}
for (const file of entries) {
if (!file.endsWith(".jsonl")) continue;
found.push({ path: join(dir, file), sessionId: file.replace(/\.jsonl$/, "") });
}
}
return found;
}
async function main(): Promise<void> {
const module = process.env.MESH_MODULE ?? "anthropic-consumer";
const node = process.env.MESH_NODE ?? "unknown";
const readings: SessionUsage[] = [];
for (const t of transcripts(projectsDir())) {
try {
readings.push(await readSessionFile(t.path, t.sessionId));
} catch (err) {
console.error(`[anthropic-consumer] could not read ${t.path}: ${err}`);
}
}
for (const r of readings) {
await emitUsage({ grain: "session", node, module, ...r });
}
if (process.env.MESH_ANTHROPIC_USAGE_OUT) {
atomicWrite(process.env.MESH_ANTHROPIC_USAGE_OUT, JSON.stringify(readings, null, 2));
}
console.error(`[anthropic-consumer] reported ${readings.length} session(s)`);
}
function atomicWrite(path: string, content: string): void {
mkdirSync(dirname(path), { recursive: true });
const tmp = `${path}.tmp`;
writeFileSync(tmp, content, { mode: 0o600 });
renameSync(tmp, path);
}
/** Emit best-effort via the sibling mesh-tools `emit`, which wires a broker a run step has none. */
async function emitUsage(body: Record<string, unknown>): Promise<void> {
const main = process.env.MESH_TOOLS_MAIN ?? "/app/dist/main.js";
const { spawn } = await import("node:child_process");
await new Promise<void>((resolve) => {
const child = spawn(
process.execPath,
[main, "emit", "module.anthropic-consumer.usage.session", JSON.stringify(body)],
{ stdio: "inherit" },
);
child.on("exit", () => resolve());
child.on("error", (err) => {
console.error(`[anthropic-consumer] could not emit usage: ${err}`);
resolve();
});
});
}
await main();