Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add a token-authenticated spend export (#1798)

Eric Bakaned11cb6caef5
diff --git a/SECURITY.md b/SECURITY.md
index f8ec950ab..c36699a86 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -181,6 +181,12 @@ these, not through them.
to an intended recipient. The gateway removes the token from the address bar and
places it in a one-day browser cookie, but copied links remain usable and app ACL
changes do not revoke individual link holders.
+- **The spend export token is bearer authorization for org-wide spend.** When
+ `SPEND_EXPORT_TOKEN` is set, anyone holding it can read every scope's daily model-call
+ spend: per-person totals, channel and group names, and the model mix. It reads no
+ conversation content and changes nothing, and each export is audited, but the token is
+ not bound to a caller. Rotating it means replacing the secret in core and in every
+ consumer; core accepts only the current value after it restarts with the new one.
- **Portal sessions have residual risk.** A signed portal session defaults to eight
hours and renews on use. Logout clears the browser cookie but cannot revoke an
already copied session token before its expiration.
diff --git a/docs/deploy-directory.md b/docs/deploy-directory.md
index f7b806497..d6091d790 100644
--- a/docs/deploy-directory.md
+++ b/docs/deploy-directory.md
@@ -68,6 +68,10 @@ The proxy endpoint receives one or more HTTPS `POST`s per bounded classification
A chunk whose score is at or above its threshold resolves to Strict, and any Strict chunk makes the whole classification Strict. When chunks agree, the highest-scoring result supplies the diagnostics. The configured provider is an audit label and metadata namespace, not a built-in adapter name, so any service implementing this contract can be selected. Throttled requests retry with bounded backoff inside the classification deadline. Invalid responses, timeouts, redirects, and other provider errors are unavailable classifications, audited as `error`. Observe mode changes authority, not disclosure: it still sends the full screened content to the configured endpoint, so operators must trust that provider with external messages, files, and surface results.
+## Spend export
+
+`secretEnv.core.SPEND_EXPORT_TOKEN` (at least 32 characters, distinct from every catalogued core secret) turns on `GET /v1/spend/export?from=YYYY-MM-DD&to=YYYY-MM-DD` for an external spend or chargeback system. Requests send `Authorization: Bearer <token>`; the window is whole UTC days, half-open, and at most 93 days long. The response carries `scopeId`, the `window`, `asOf` when the report is served from saved daily totals, and `rows` at the Spend page's ledger grain — one per UTC day, scope, origin (`live`, `cron`, `background`) and model — each with `scopeId`, `kind`, `principalId` (people only, after identity links), `displayName`, `calls`, `costUsd` and the four token counts. `costUsd` is the same estimate the admin Spend page shows, not a provider bill. Without the secret the route answers 404, and every export is audited as `spend.export`. Portal does not forward the route, so callers use the origin that reaches core directly.
+
## Secrets
First-party services publish a typed `SecretSpec` schema. The CLI combines the enabled services and feature predicates with plugin `secrets` and `sandbox.secretEnv` to form the computed secret set. That same schema determines which task receives each secret. Core validates its own required runtime secrets at production boot.
diff --git a/src/api/deps.ts b/src/api/deps.ts
index 94f2393bb..650f59d5c 100644
--- a/src/api/deps.ts
+++ b/src/api/deps.ts
@@ -185,6 +185,7 @@ export interface ServerDeps {
deploymentLayer?: DeploymentLayerStore;
backgroundOwnership?: BackgroundOwnershipControl;
deploymentControlSecret?: string;
+ spendExportToken?: string;
deployDialTimeoutMs?: number;
deployAppsDomain?: string;
deployGateSecret?: string;
diff --git a/src/api/routes/admin/spend.ts b/src/api/routes/admin/spend.ts
index 01d26a44f..57d95e5cb 100644
--- a/src/api/routes/admin/spend.ts
+++ b/src/api/routes/admin/spend.ts
@@ -1,14 +1,17 @@
import { cacheHitRatio } from "../../../admin/metrics-sink.ts";
import { canonicalPerson } from "../../../directory/person.ts";
import { parseScopeId, personalScope, type ScopeId } from "../../../types.ts";
-import type { SessionOrigin, SpendRow } from "../../../sessions/session-store.ts";
+import type { SessionOrigin, SessionStore, SpendRow } from "../../../sessions/session-store.ts";
+import { constantTimeEqual } from "../../../util/crypto.ts";
import { contentDispositionAttachment, contentTypeWithUtf8Charset, sendJson } from "../../http.ts";
import { audit, authorizeAdmin, orgScope } from "../shared.ts";
import { discoverScopes } from "./common.ts";
-import { type ApiCtx } from "../route.ts";
+import { type ApiCtx, type BaseCtx } from "../route.ts";
const DAY_MS = 86_400_000;
const DEFAULT_WINDOW_DAYS = 30;
+const EXPORT_MAX_DAYS = 93;
+const SPEND_EXPORT_PRINCIPAL = "spend-export";
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
const EPOCH_MS = /^\d+$/;
const CSV_FORMULA_LEAD = /^[=+\-@\t\r]/;
@@ -78,6 +81,16 @@ export interface SpendReport {
models: ({ model: string | null } & SpendTotals)[];
}
+export interface SpendExportRow extends Tally {
+ day: string;
+ scopeId: ScopeId;
+ kind: string;
+ principalId: string | null;
+ displayName: string;
+ origin: OriginBucket;
+ model: string | null;
+}
+
export interface SpendSummaryOptions {
from: number;
to: number;
@@ -172,12 +185,26 @@ function totalsOf(byOrigin: Record<OriginBucket, Tally>): SpendTotals {
};
}
+function resolveScope(scopeId: ScopeId): { key: ScopeId; person: string | null; kind: string } {
+ const parsed = parseScopeId(scopeId);
+ const person = parsed.kind === "personal" && parsed.ref ? canonicalPerson(parsed.ref) : null;
+ return {
+ key: person === null ? scopeId : personalScope(person),
+ person,
+ kind: person === null ? (parsed.kind ?? "unknown") : "person",
+ };
+}
+
+function displayNameOf(sources: readonly ScopeId[], label: (scopeId: ScopeId) => string): string {
+ return sources.map(label).find((name) => name) ?? "";
+}
+
function entityOf(acc: EntityAccumulator, label: (scopeId: ScopeId) => string): SpendEntity {
return {
principalId: acc.principalId,
scopeId: acc.scopeId,
kind: acc.kind,
- displayName: acc.sources.map(label).find((name) => name) ?? "",
+ displayName: displayNameOf(acc.sources, label),
...totalsOf(acc.byOrigin),
};
}
@@ -208,18 +235,10 @@ export function summarizeSpend(rows: readonly SpendRow[], opts: SpendSummaryOpti
const modelBuckets = new Map<string | null, Record<OriginBucket, Tally>>();
const orgOrigins = emptyOrigins();
for (const row of rows) {
- const parsed = parseScopeId(row.scopeId);
- const person = parsed.kind === "personal" && parsed.ref ? canonicalPerson(parsed.ref) : null;
- const key = person === null ? row.scopeId : personalScope(person);
+ const { key, person, kind } = resolveScope(row.scopeId);
let acc = accumulators.get(key);
if (!acc) {
- acc = {
- principalId: person,
- scopeId: key,
- kind: person === null ? (parsed.kind ?? "unknown") : "person",
- sources: [],
- byOrigin: emptyOrigins(),
- };
+ acc = { principalId: person, scopeId: key, kind, sources: [], byOrigin: emptyOrigins() };
accumulators.set(key, acc);
}
if (!acc.sources.includes(row.scopeId)) acc.sources.push(row.scopeId);
@@ -290,6 +309,43 @@ export function summarizeSpend(rows: readonly SpendRow[], opts: SpendSummaryOpti
};
}
+export function spendExportRows(rows: readonly SpendRow[], label: (scopeId: ScopeId) => string): SpendExportRow[] {
+ const sources = new Map<ScopeId, ScopeId[]>();
+ const merged = new Map<string, SpendExportRow>();
+ for (const row of rows) {
+ const { key: scopeId, person, kind } = resolveScope(row.scopeId);
+ const seen = sources.get(scopeId);
+ if (!seen) sources.set(scopeId, [row.scopeId]);
+ else if (!seen.includes(row.scopeId)) seen.push(row.scopeId);
+ const origin = originBucket(row.origin);
+ const key = JSON.stringify([row.day, scopeId, origin, row.model]);
+ let out = merged.get(key);
+ if (!out) {
+ out = {
+ day: isoDay(row.day),
+ scopeId,
+ kind,
+ principalId: person,
+ displayName: "",
+ origin,
+ model: row.model,
+ ...emptyTally(),
+ };
+ merged.set(key, out);
+ }
+ addRow(out, row);
+ }
+ return [...merged.values()]
+ .map((out) => ({ ...out, displayName: displayNameOf(sources.get(out.scopeId) ?? [], label) }))
+ .sort(
+ (a, b) =>
+ a.day.localeCompare(b.day) ||
+ a.scopeId.localeCompare(b.scopeId) ||
+ ORIGIN_BUCKETS.indexOf(a.origin) - ORIGIN_BUCKETS.indexOf(b.origin) ||
+ (a.model ?? "").localeCompare(b.model ?? ""),
+ );
+}
+
function csvCell(value: string | number | null): string {
if (value === null) return "";
if (typeof value === "number") return String(value);
@@ -329,16 +385,63 @@ export function spendCsv(report: SpendReport, breakdown: SpendBreakdown = "entit
return lines.join("\r\n") + "\r\n";
}
-function parseBound(raw: string): number | null {
+function parseDay(raw: string): number | null {
const value = raw.trim();
- let parsed = NaN;
- if (DATE_ONLY.test(value)) {
- parsed = Date.parse(`${value}T00:00:00.000Z`);
- if (!Number.isFinite(parsed) || new Date(parsed).toISOString().slice(0, 10) !== value) return null;
- } else if (EPOCH_MS.test(value)) parsed = Number(value);
+ if (!DATE_ONLY.test(value)) return null;
+ const parsed = Date.parse(`${value}T00:00:00.000Z`);
+ return Number.isFinite(parsed) && new Date(parsed).toISOString().slice(0, 10) === value ? parsed : null;
+}
+
+function parseBound(raw: string): number | null {
+ const day = parseDay(raw);
+ if (day !== null || !EPOCH_MS.test(raw.trim())) return day;
+ const parsed = Number(raw.trim());
return Number.isSafeInteger(parsed) && Number.isFinite(new Date(parsed).getTime()) ? parsed : null;
}
+async function loadSpendRows(
+ sessions: SessionStore,
+ range: { from: number; to: number },
+): Promise<{ rows: SpendRow[]; asOf?: number }> {
+ return sessions.spendReport ? sessions.spendReport(range) : { rows: await sessions.spendRollup(range) };
+}
+
+export async function spendExport(ctx: BaseCtx): Promise<void> {
+ const { req, res, app, deps, url } = ctx;
+ const token = deps.spendExportToken;
+ if (!token) return sendJson(res, 404, { error: "not_found" });
+ const authorization = req.headers.authorization;
+ if (typeof authorization !== "string" || !constantTimeEqual(authorization, `Bearer ${token}`))
+ return sendJson(res, 401, { error: "unauthorized" });
+ if (!deps.sessions) return sendJson(res, 503, { error: "spend_unavailable" });
+ const from = parseDay(url.searchParams.get("from") ?? "");
+ const to = parseDay(url.searchParams.get("to") ?? "");
+ if (from === null || to === null)
+ return sendJson(res, 400, { error: "bad_request", message: "from and to must be YYYY-MM-DD dates (UTC)" });
+ if (to <= from || to - from > EXPORT_MAX_DAYS * DAY_MS)
+ return sendJson(res, 400, {
+ error: "bad_request",
+ message: `to must be later than from and at most ${EXPORT_MAX_DAYS} days after it`,
+ });
+ const { rows, asOf } = await loadSpendRows(deps.sessions, { from, to });
+ const labels = await discoverScopes(
+ app,
+ deps,
+ rows.map((r) => r.scopeId),
+ );
+ const scope = orgScope(deps);
+ const window = { from: isoDay(from / DAY_MS), to: isoDay(to / DAY_MS) };
+ const exported = spendExportRows(rows, (id) => labels.get(id) ?? "");
+ audit(deps, {
+ principalId: SPEND_EXPORT_PRINCIPAL,
+ action: "spend.export",
+ resource: "spend",
+ scopeLabel: scope,
+ detail: `${window.from}..${window.to} rows=${exported.length}`,
+ });
+ sendJson(res, 200, { scopeId: scope, window, ...(asOf === undefined ? {} : { asOf }), rows: exported });
+}
+
export async function spend(ctx: ApiCtx): Promise<void> {
const { res, app, deps, url } = ctx;
const scope = orgScope(deps);
@@ -363,9 +466,9 @@ export async function spend(ctx: ApiCtx): Promise<void> {
if (from === null) return bad("from must be a YYYY-MM-DD date (UTC) or epoch milliseconds");
if (to <= from) return bad("to must be later than from");
- const { rows, asOf } = deps.sessions?.spendReport
- ? await deps.sessions.spendReport({ from, to })
- : { rows: (await deps.sessions?.spendRollup({ from, to })) ?? [], asOf: undefined };
+ const { rows, asOf } = deps.sessions
+ ? await loadSpendRows(deps.sessions, { from, to })
+ : { rows: [], asOf: undefined };
const labels = await discoverScopes(
app,
deps,
diff --git a/src/api/routes/index.ts b/src/api/routes/index.ts
index 598ee3e06..61cce7685 100644
--- a/src/api/routes/index.ts
+++ b/src/api/routes/index.ts
@@ -18,6 +18,7 @@ import { brokerGitHttp, GIT_HTTP_BROKER_PREFIX } from "../git-http-broker.ts";
import { keychainRoutes } from "./keychain.ts";
import { secretDropRoutes } from "./secret-drop.ts";
import { adminRoutes } from "./admin.ts";
+import { spendExport } from "./admin/spend.ts";
import { skillPackRoutes } from "./skill-packs.ts";
import { fileUploadRoutes } from "./file-uploads.ts";
import { surfaceRoutes } from "./surface.ts";
@@ -68,6 +69,7 @@ export const rawRoutes: ReadonlyArray<Route<BaseCtx>> = [
},
},
...slackEventRawRoutes,
+ { method: "GET", path: "/v1/spend/export", auth: "public", handle: spendExport },
{ match: (_m, p) => p.startsWith(GIT_HTTP_BROKER_PREFIX), auth: { aud: "credential-broker" }, handle: brokerGitHttp },
...connectorRawRoutes,
...deploymentRawRoutes,
diff --git a/src/config.ts b/src/config.ts
index b55f0203b..a4ade2da8 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -22,7 +22,7 @@ import { parseMemoryStrategyKind, type MemoryStrategyKind } from "./memory/strat
import { parseMemoryProviderConfig, type MemoryProviderConfig } from "./memory/provider-config.ts";
import { sanitizeBranding } from "./resolution/branding.ts";
import type { OrgBranding } from "./resolution/config-store.ts";
-import { validateCoreSecretEnv } from "./deployment/secret-schema.ts";
+import { CORE_SECRET_SPECS, validateCoreSecretEnv } from "./deployment/secret-schema.ts";
import { DEFAULT_CAPTURE_QUIET_MS } from "./memory/strategies/per-turn.ts";
import {
parseSecurityPosture,
@@ -127,6 +127,7 @@ export interface Config {
backgroundWorkEnabled: boolean;
backgroundDeploymentId?: string;
deploymentControlSecret?: string;
+ spendExportToken?: string;
buildSha?: string;
monitorPollMs: number;
skillSyncPollMs: number;
@@ -1180,6 +1181,11 @@ function modelProviderEnvStrict(env: NodeJS.ProcessEnv): ModelProvider | undefin
}
export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
+ if (env.SPEND_EXPORT_TOKEN) {
+ const reused = CORE_SECRET_SPECS.some((spec) => env[spec.name] === env.SPEND_EXPORT_TOKEN);
+ if (!isStrongSigningSecret(env.SPEND_EXPORT_TOKEN) || reused)
+ throw new Error("SPEND_EXPORT_TOKEN must be at least 32 characters and differ from every catalogued core secret");
+ }
if (env.BACKGROUND_DEPLOYMENT_ID !== undefined) {
if (!env.BACKGROUND_DEPLOYMENT_ID.trim() || env.BACKGROUND_DEPLOYMENT_ID.length > 256)
throw new Error("BACKGROUND_DEPLOYMENT_ID must be nonempty and at most 256 characters");
@@ -1607,6 +1613,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
...(env.BACKGROUND_DEPLOYMENT_ID
? { backgroundDeploymentId: env.BACKGROUND_DEPLOYMENT_ID, deploymentControlSecret: env.DEPLOYMENT_CONTROL_SECRET }
: {}),
+ ...(env.SPEND_EXPORT_TOKEN ? { spendExportToken: env.SPEND_EXPORT_TOKEN } : {}),
...(env.GIT_SHA ? { buildSha: env.GIT_SHA } : {}),
monitorPollMs: numEnvStrict("MONITOR_POLL_MS", env.MONITOR_POLL_MS) ?? CONFIG_DEFAULTS.monitorPollMs,
skillSyncPollMs: numEnvStrict("SKILL_SYNC_POLL_MS", env.SKILL_SYNC_POLL_MS) ?? CONFIG_DEFAULTS.skillSyncPollMs,
diff --git a/src/wiring.ts b/src/wiring.ts
index dbdbac7ad..4482cd602 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -2957,6 +2957,7 @@ export function serverDeps(
}
: {}),
allowUnauthenticatedCore: config.allowUnauthenticatedCore,
+ ...(config.spendExportToken ? { spendExportToken: config.spendExportToken } : {}),
...(config.signingSecret ? { signingSecret: config.signingSecret } : {}),
...(config.capabilitySecret ? { capabilitySecret: config.capabilitySecret } : {}),
capabilityTokenCompression: config.capabilityTokenCompression,
diff --git a/test/admin-spend.test.ts b/test/admin-spend.test.ts
index 93057e0bf..0a5be0b02 100644
--- a/test/admin-spend.test.ts
+++ b/test/admin-spend.test.ts
@@ -10,8 +10,9 @@ import { createInsecureTestServer } from "../src/api/server.ts";
import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";
import { cacheHitRatio } from "../src/admin/metrics-sink.ts";
import { buildApp } from "../src/wiring.ts";
-import { scopeId, type SessionType, type TurnRequest } from "../src/types.ts";
-import type { LlmCallUsage, SessionStore } from "../src/sessions/session-store.ts";
+import { scopeId, type TurnRequest } from "../src/types.ts";
+import type { SessionStore } from "../src/sessions/session-store.ts";
+import { bill } from "./support/spend-usage.ts";
import { testConfig } from "./support/test-config.ts";
const DAY = 86_400_000;
@@ -44,34 +45,6 @@ const dm = (principal: string, text: string): TurnRequest => ({
text,
});
-const usage = (over: Partial<LlmCallUsage>): LlmCallUsage => ({
- input: 100,
- output: 20,
- cacheRead: 400,
- cacheWrite: 40,
- totalTokens: 560,
- costUsd: 0,
- ...over,
-});
-
-async function bill(
- sessions: SessionStore,
- threadRef: string,
- type: SessionType,
- scope: string,
- over: Partial<LlmCallUsage>,
- model = "mock",
-): Promise<void> {
- const session = await sessions.getOrCreateByThread(threadRef, type, scope);
- await sessions.recordLlmRequest(session.id, {
- turnSeq: null,
- step: 0,
- model,
- scopeLabel: scope,
- usage: usage(over),
- });
-}
-
async function seedPricedFixture(sessions: SessionStore): Promise<void> {
await bill(sessions, "dm:alice:priced", "dm", scopeId("personal", "alice"), { costUsd: 2 });
await bill(sessions, "cron:nightly:fire:abc123", "dm", scopeId("personal", "alice"), { costUsd: 0.5 });
diff --git a/test/config.test.ts b/test/config.test.ts
index ec54f2292..686e3caad 100644
--- a/test/config.test.ts
+++ b/test/config.test.ts
@@ -10,6 +10,7 @@ import {
numEnv,
CONFIG_DEFAULTS,
} from "../src/config.ts";
+import { CORE_SECRET_SPECS } from "../src/deployment/secret-schema.ts";
const productionEnv = {
NODE_ENV: "production",
@@ -949,6 +950,27 @@ test("background ownership requires durable storage and an independent deploymen
assert.throws(() => loadConfig({ ...env, DEPLOYMENT_CONTROL_SECRET: " ".repeat(32) }), /DEPLOYMENT_CONTROL_SECRET/);
});
+test("the spend export token is optional, strong and never shared with another core secret", () => {
+ const env = {
+ CORE_SIGNING_SECRET: "source-signing-secret-0123456789abcdef",
+ CAPABILITY_SECRET: "capability-secret-0123456789abcdef0123",
+ PORTAL_IDENTITY_SECRET: "portal-identity-secret-0123456789abcdef",
+ SPEND_EXPORT_TOKEN: "spend-export-token-0123456789abcdef01234",
+ };
+ assert.equal(loadConfig(env).spendExportToken, env.SPEND_EXPORT_TOKEN);
+ assert.equal(loadConfig({ ...env, SPEND_EXPORT_TOKEN: undefined }).spendExportToken, undefined);
+ assert.equal(loadConfig({ ...env, SPEND_EXPORT_TOKEN: "" }).spendExportToken, undefined);
+ assert.throws(() => loadConfig({ ...env, SPEND_EXPORT_TOKEN: "short" }), /SPEND_EXPORT_TOKEN/);
+ assert.throws(() => loadConfig({ ...env, SPEND_EXPORT_TOKEN: " ".repeat(40) }), /SPEND_EXPORT_TOKEN/);
+ for (const { name } of CORE_SECRET_SPECS) {
+ assert.throws(
+ () => loadConfig({ ...env, [name]: env.SPEND_EXPORT_TOKEN }),
+ /SPEND_EXPORT_TOKEN/,
+ `${name} must not share the export token`,
+ );
+ }
+});
+
test("sandbox capability TTL is deployment-configurable with a 48-hour default", () => {
assert.equal(loadConfig({}).sandboxCapabilityTtlMs, 48 * 3_600_000);
assert.equal(loadConfig({ SANDBOX_CAPABILITY_TTL_HOURS: "168" }).sandboxCapabilityTtlMs, 168 * 3_600_000);
diff --git a/test/route-auth-conformance.test.ts b/test/route-auth-conformance.test.ts
index ee431fa5c..8cacba684 100644
--- a/test/route-auth-conformance.test.ts
+++ b/test/route-auth-conformance.test.ts
@@ -75,6 +75,7 @@ test("raw routes keep their declared auth contracts (front enforces capability a
const pins: Array<[string, string, RouteAuth]> = [
["GET", "/healthz", "public"],
["GET", "/readyz", "public"],
+ ["GET", "/v1/spend/export", "public"],
["GET", "/v1/credentials/git/gitlab/acme/repo.git/info/refs", { aud: CREDENTIAL_BROKER_AUD }],
["POST", "/v1/credentials/git/gitlab/acme/repo.git/git-upload-pack", { aud: CREDENTIAL_BROKER_AUD }],
];
diff --git a/test/spend-export.test.ts b/test/spend-export.test.ts
new file mode 100644
index 000000000..9fc6dcc16
--- /dev/null
+++ b/test/spend-export.test.ts
@@ -0,0 +1,176 @@
+import "./support/auto-fake-sprites.ts";
+
+import assert from "node:assert/strict";
+import type { AddressInfo } from "node:net";
+import test from "node:test";
+import { createServer } from "../src/api/server.ts";
+import { signRequest } from "../src/auth/source-auth.ts";
+import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";
+import type { SessionStore } from "../src/sessions/session-store.ts";
+import { scopeId } from "../src/types.ts";
+import { buildApp } from "../src/wiring.ts";
+import { bill } from "./support/spend-usage.ts";
+import { testConfig } from "./support/test-config.ts";
+
+const DAY = 86_400_000;
+const sourceSecret = "source-only-secret".repeat(3);
+const exportToken = "spend-export-only-token".repeat(3);
+const today = Math.floor(Date.now() / DAY) * DAY;
+const iso = (ms: number) => new Date(ms).toISOString().slice(0, 10);
+const window = `from=${iso(today - DAY)}&to=${iso(today + DAY)}`;
+
+function fixture(options: { token?: string | null; sessions?: SessionStore | null } = {}) {
+ const built = buildApp(testConfig({ signingSecret: sourceSecret }));
+ const sessions = options.sessions === null ? undefined : (options.sessions ?? createMemorySessionStore());
+ const token = options.token === undefined ? exportToken : options.token;
+ const server = createServer(built.app, {
+ signingSecret: sourceSecret,
+ portalIdentitySecret: "portal-identity-secret".repeat(3),
+ capabilitySecret: "capability-only-secret".repeat(3),
+ requireSignedPortalIdentity: true,
+ admin: built.admin,
+ auditLog: built.auditLog,
+ ...(sessions ? { sessions } : {}),
+ ...(token ? { spendExportToken: token } : {}),
+ });
+ server.listen(0);
+ const base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ const get = (path: string, headers: Record<string, string> = { authorization: `Bearer ${exportToken}` }) =>
+ fetch(base + path, { headers });
+ return { built, sessions, get, close: () => new Promise<void>((resolve) => server.close(() => resolve())) };
+}
+
+test("spend export: absent unless a token is configured", async () => {
+ const s = fixture({ token: null });
+ try {
+ const res = await s.get(`/v1/spend/export?${window}`);
+ assert.equal(res.status, 404);
+ } finally {
+ await s.close();
+ }
+});
+
+test("spend export: missing, wrong, admin-identity and source-signed requests are refused before any spend read", async () => {
+ const store = createMemorySessionStore();
+ let reads = 0;
+ store.spendRollup = async () => {
+ reads++;
+ return [];
+ };
+ const s = fixture({ sessions: store });
+ try {
+ const path = `/v1/spend/export?${window}`;
+ const ts = Math.floor(Date.now() / 1000);
+ const refused: Record<string, string>[] = [
+ {},
+ { authorization: `Bearer ${exportToken}x` },
+ { authorization: exportToken },
+ { authorization: `Bearer ${sourceSecret}` },
+ { "x-admin-actor": "admin-alice@default-org" },
+ { "x-timestamp": String(ts), "x-signature": signRequest(sourceSecret, ts, `GET\n${path}\n`) },
+ ];
+ for (const headers of refused) {
+ const res = await s.get(path, headers);
+ assert.equal(res.status, 401, JSON.stringify(headers));
+ }
+ assert.equal(reads, 0);
+ assert.deepEqual(
+ (await s.built.auditLog.events()).filter((e) => e.action === "spend.export"),
+ [],
+ );
+ } finally {
+ await s.close();
+ }
+});
+
+test("spend export: the token authorizes the export and nothing else", async () => {
+ const s = fixture();
+ try {
+ for (const path of ["/v1/admin/spend", "/v1/admin/whoami", "/v1/admin/users", "/v1/background-work"]) {
+ const res = await s.get(path);
+ assert.equal(res.status, 401, path);
+ }
+ } finally {
+ await s.close();
+ }
+});
+
+test("spend export: rows keep the ledger grain with canonical people, origin buckets and the org scope", async () => {
+ const s = fixture();
+ try {
+ const sessions = s.sessions!;
+ await bill(sessions, "dm:alice:t1", "dm", scopeId("personal", "alice"), { costUsd: 2 }, "claude-opus-5");
+ await bill(sessions, "dm:alice:t2", "dm", scopeId("personal", "alice"), { costUsd: 1 }, "claude-opus-5");
+ await bill(sessions, "cron:nightly:fire:1", "dm", scopeId("personal", "alice"), { costUsd: 0.5 }, "gpt-6-astra");
+ await bill(sessions, "webhook:w1", "channel", scopeId("channel", "C1"), { costUsd: 4 }, "claude-opus-5");
+ await bill(sessions, "ch:C1:t1", "channel", scopeId("channel", "C1"), { costUsd: 3 }, "claude-opus-5");
+ const res = await s.get(`/v1/spend/export?${window}`);
+ assert.equal(res.status, 200);
+ const body: any = await res.json();
+ assert.equal(body.scopeId, "org:default-org");
+ assert.deepEqual(body.window, { from: iso(today - DAY), to: iso(today + DAY) });
+ assert.deepEqual(
+ body.rows.map((r: any) => [r.day, r.scopeId, r.kind, r.principalId, r.origin, r.model, r.calls, r.costUsd]),
+ [
+ [iso(today), "channel:C1", "channel", null, "live", "claude-opus-5", 1, 3],
+ [iso(today), "channel:C1", "channel", null, "background", "claude-opus-5", 1, 4],
+ [iso(today), "personal:alice", "person", "alice", "live", "claude-opus-5", 2, 3],
+ [iso(today), "personal:alice", "person", "alice", "cron", "gpt-6-astra", 1, 0.5],
+ ],
+ );
+ assert.deepEqual(
+ [body.rows[2].input, body.rows[2].output, body.rows[2].cacheRead, body.rows[2].cacheWrite],
+ [200, 40, 800, 80],
+ );
+ const audited = (await s.built.auditLog.events()).filter((e) => e.action === "spend.export");
+ assert.equal(audited.length, 1);
+ assert.equal(audited[0]!.principalId, "spend-export");
+ assert.equal(audited[0]!.detail, `${iso(today - DAY)}..${iso(today + DAY)} rows=4`);
+ } finally {
+ await s.close();
+ }
+});
+
+test("spend export: passes through the saved report's freshness", async () => {
+ const store = createMemorySessionStore();
+ const asOf = Date.UTC(2026, 0, 1);
+ store.spendReport = async (range) => ({ rows: await store.spendRollup(range), asOf });
+ const s = fixture({ sessions: store });
+ try {
+ const body: any = await (await s.get(`/v1/spend/export?${window}`)).json();
+ assert.equal(body.asOf, asOf);
+ assert.deepEqual(body.rows, []);
+ } finally {
+ await s.close();
+ }
+});
+
+test("spend export: the window is whole UTC days, ordered and at most 93 days", async () => {
+ const s = fixture();
+ try {
+ for (const query of [
+ "",
+ `from=${iso(today)}`,
+ `from=${today - DAY}&to=${today}`,
+ `from=${iso(today)}&to=${iso(today)}`,
+ `from=${iso(today)}&to=${iso(today - DAY)}`,
+ `from=${iso(today - 94 * DAY)}&to=${iso(today)}`,
+ "from=2026-02-30&to=2026-03-02",
+ ]) {
+ const res = await s.get(`/v1/spend/export?${query}`);
+ assert.equal(res.status, 400, query);
+ }
+ assert.equal((await s.get(`/v1/spend/export?from=${iso(today - 93 * DAY)}&to=${iso(today)}`)).status, 200);
+ } finally {
+ await s.close();
+ }
+});
+
+test("spend export: an unavailable spend store is an error, not an empty export", async () => {
+ const s = fixture({ sessions: null });
+ try {
+ assert.equal((await s.get(`/v1/spend/export?${window}`)).status, 503);
+ } finally {
+ await s.close();
+ }
+});
diff --git a/test/spend-summary.test.ts b/test/spend-summary.test.ts
index 20db89a25..502fe69a9 100644
--- a/test/spend-summary.test.ts
+++ b/test/spend-summary.test.ts
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import { installPrincipalLinks } from "../src/directory/person.ts";
import { cacheHitRatio } from "../src/admin/metrics-sink.ts";
import type { SpendRow } from "../src/sessions/session-store.ts";
-import { spendCsv, summarizeSpend, type SpendReport } from "../src/api/routes/admin/spend.ts";
+import { spendCsv, spendExportRows, summarizeSpend, type SpendReport } from "../src/api/routes/admin/spend.ts";
const DAY = 86_400_000;
const MON = 20353;
@@ -409,3 +409,47 @@ for (const bucket of ["day", "week"] as const) {
assert.deepEqual(summarize(rows.toReversed(), { bucket, to: (MON + 8) * DAY }).series, report.series);
});
}
+
+test("spendExportRows keeps the ledger grain, merging principal aliases into one person per day, origin and model", (t) => {
+ installPrincipalLinks({ canonical: (id) => (id === "slack-alice" ? "alice" : undefined), aliases: () => [] });
+ t.after(() => installPrincipalLinks(null));
+ const labels = new Map([
+ ["personal:slack-alice", "Alice"],
+ ["personal:alice", "[email protected]"],
+ ["channel:C1", "#general"],
+ ]);
+ const ledger = [
+ row({ day: TUE, scopeId: "channel:C1", origin: "cron", model: "m1", costUsd: 8, calls: 2 }),
+ row({ day: MON, scopeId: "personal:slack-alice", origin: "conversation", model: "m1", costUsd: 2, input: 5 }),
+ row({ day: MON, scopeId: "personal:alice", origin: "conversation", model: "m1", costUsd: 1, input: 3 }),
+ row({ day: MON, scopeId: "personal:alice", origin: "monitor", model: "m1", costUsd: 4 }),
+ row({ day: MON, scopeId: "personal:alice", origin: "webhook", model: "m1", costUsd: 16 }),
+ row({ day: MON, scopeId: "personal:alice", origin: "conversation", model: null, costUsd: 32 }),
+ ];
+ const rows = spendExportRows(ledger, (id) => labels.get(id) ?? "");
+ assert.deepEqual(
+ rows.map((r) => [r.day, r.scopeId, r.kind, r.principalId, r.displayName, r.origin, r.model, r.costUsd, r.calls]),
+ [
+ ["2025-09-22", "personal:alice", "person", "alice", "Alice", "live", null, 32, 1],
+ ["2025-09-22", "personal:alice", "person", "alice", "Alice", "live", "m1", 3, 2],
+ ["2025-09-22", "personal:alice", "person", "alice", "Alice", "background", "m1", 20, 2],
+ ["2025-09-23", "channel:C1", "channel", null, "#general", "cron", "m1", 8, 2],
+ ],
+ );
+ assert.equal(rows[1]!.input, 8);
+ const report = summarize(ledger, { bucket: "day", to: (TUE + 1) * DAY, label: (id) => labels.get(id) ?? "" });
+ assert.equal(
+ rows.reduce((sum, r) => sum + r.costUsd, 0),
+ report.org.costUsd,
+ );
+ assert.equal(
+ rows.filter((r) => r.principalId === "alice").reduce((sum, r) => sum + r.costUsd, 0),
+ report.people.find((p) => p.principalId === "alice")!.costUsd,
+ );
+ const names = new Map([...report.people, ...report.scopes].map((e) => [e.scopeId, e.displayName]));
+ assert.deepEqual(
+ rows.map((r) => r.displayName),
+ rows.map((r) => names.get(r.scopeId)),
+ "the export names each scope exactly as the Spend page does",
+ );
+});
diff --git a/test/support/spend-usage.ts b/test/support/spend-usage.ts
new file mode 100644
index 000000000..0dc3df056
--- /dev/null
+++ b/test/support/spend-usage.ts
@@ -0,0 +1,30 @@
+import type { LlmCallUsage, SessionStore } from "../../src/sessions/session-store.ts";
+import type { SessionType } from "../../src/types.ts";
+
+export const usage = (over: Partial<LlmCallUsage>): LlmCallUsage => ({
+ input: 100,
+ output: 20,
+ cacheRead: 400,
+ cacheWrite: 40,
+ totalTokens: 560,
+ costUsd: 0,
+ ...over,
+});
+
+export async function bill(
+ sessions: SessionStore,
+ threadRef: string,
+ type: SessionType,
+ scope: string,
+ over: Partial<LlmCallUsage>,
+ model = "mock",
+): Promise<void> {
+ const session = await sessions.getOrCreateByThread(threadRef, type, scope);
+ await sessions.recordLlmRequest(session.id, {
+ turnSeq: null,
+ step: 0,
+ model,
+ scopeLabel: scope,
+ usage: usage(over),
+ });
+}