Skip to content

Commit 896d4df

Browse files
phasenullclaude
andauthored
typetorch keys create / list / revoke: named API keys with roles on the backend (#42)
- create: POST /v1/admin/keys { name, role, expiresDays? }; the key printed once (--json: in key), registered with the scrubber the moment it arrives, never written anywhere; no error quotes a reply that held a key - list [--all]: id, name, role, scopes, expires, last used, built-in / revoked - revoke <id>: DELETE /v1/admin/keys/{id}; built-in env:* ids and pasted whole keys refused locally - validation: name [a-z0-9._-]{1,48}, the five roles, --expires 1-3650 days (90d, 365d, 1y) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9d53ee9 commit 896d4df

6 files changed

Lines changed: 510 additions & 6 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,7 @@ show whether signing is ready, with placeholders instead of real signatures. Any
238238
| `typetorch backend bless [--url <url>] [--no-open]` | trusts one browser for admin when you sign in with typetorch.dev: sends the public signing keys to the backend, signs its one-time challenge with the main prod key (it never leaves this PC) and opens the single-use link (5 minutes) |
239239
| `typetorch report <seq\|artifact\|latest> [--branch]` | what the servers did with one deploy; exits 1 when one failed or rolled back (see "Fleet") |
240240
| `typetorch keys init [--key-file]` / `keys init --fallback [--force] [--yes]` / `keys rotate [--yes]` / `keys resign` | the signing keys: see "Signing prod deploys" |
241+
| `typetorch keys create --name <name> --role <game\|lookup\|support\|analyst\|admin> [--expires 365d\|90d\|1y]` / `keys list [--all]` / `keys revoke <id>` | named API keys with roles on the backend (plans/31), with `TYPETORCH_ADMIN_TOKEN`: for tools that must not hold the admin token (a support bot reading one player's rows). `create` prints the key `ttk_<id>_<secret>` ONCE (`--json`: in `key`) and never writes it anywhere; `list` shows id, name, role, scopes, expiry, last use, built-in / revoked; `revoke` ends one at once (built-in `env:*` keys, the env tokens, are rotated in the backend's environment instead) |
241242
| `typetorch pin <artifact> --branch <b> (--servers <ids> \| --pct <1-99>)` / `pin --unpin --branch <b> (--servers <ids> \| --all)` | A/B experiment pins, signed on prod-channel branches; `--by`, `--dry-run` |
242243
| `typetorch reject <id> [--reason]` / `typetorch proposals [--all]` | drop a proposal / list them |
243244
| `typetorch assets sync [--dry-run] [--deploy <branch>] [--place-version <n> \| --studio-export <file>]` | hot assets: export the instances marked `TypeTorchAsset` from the place's latest published version (or the Studio plugin's export), upload new and changed ones, write `typetorch.assets.lock.json`; see "Hot assets" |

‎src/backend.ts‎

Lines changed: 77 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ export interface BackendRequestOptions {
148148
timeoutMs?: number;
149149
}
150150

151-
async function adminRequest(options: BackendRequestOptions, method: "GET" | "PUT" | "POST" | "PATCH", path: string, body?: unknown, maxText = 4000): Promise<{ status: number; json?: Record<string, unknown>; text: string }> {
151+
async function adminRequest(options: BackendRequestOptions, method: "GET" | "PUT" | "POST" | "PATCH" | "DELETE", path: string, body?: unknown, maxText = 4000): Promise<{ status: number; json?: Record<string, unknown>; text: string }> {
152152
const base = options.url.replace(/\/+$/, "");
153153
const host = new URL(base).host;
154154
let response: Response;
@@ -318,7 +318,7 @@ function replyError(reply: { json?: Record<string, unknown>; text: string }): st
318318
}
319319

320320
/** One admin call that must answer 200 with a JSON object (else a BackendError naming the route and the status). */
321-
async function adminJson(options: BackendRequestOptions, method: "GET" | "PUT" | "POST" | "PATCH", path: string, body?: unknown): Promise<Record<string, unknown>> {
321+
async function adminJson(options: BackendRequestOptions, method: "GET" | "PUT" | "POST" | "PATCH" | "DELETE", path: string, body?: unknown): Promise<Record<string, unknown>> {
322322
const reply = await adminRequest(options, method, path, body, 200_000);
323323
if (reply.status === 404 && !reply.json?.error) throw new BackendError(`${method} ${path} answered 404: the backend predates this route (update it)`, 404, reply.json);
324324
if (reply.status !== 200 || !reply.json) throw new BackendError(`${method} ${path} answered ${reply.status}: ${replyError(reply)}`, reply.status, reply.json);
@@ -441,3 +441,78 @@ export async function notifyTest(options: BackendRequestOptions, input: { userId
441441
export async function notifySend(options: BackendRequestOptions, input: { userId: number; template: string; params?: Record<string, string>; data?: string }): Promise<NotifySendResult> {
442442
return sendResult(await adminJson(options, "POST", "/v1/notify/send", input), "POST /v1/notify/send");
443443
}
444+
445+
// API keys with roles (plans/31) -----------------------------------------------------------------------------------------
446+
447+
export const API_KEY_ROLES = ["game", "lookup", "support", "analyst", "admin"] as const;
448+
export type ApiKeyRole = (typeof API_KEY_ROLES)[number];
449+
450+
export interface CreatedApiKey {
451+
id: string;
452+
/** The whole key (`ttk_<id>_<secret>`): shown once, registered with the scrubber the moment it arrives. */
453+
key: string;
454+
name: string;
455+
role: string;
456+
scopes: string[];
457+
createdAt: string | number | null;
458+
expiresAt: string | number | null;
459+
}
460+
461+
export interface ApiKeyInfo {
462+
id: string;
463+
name: string;
464+
role: string;
465+
scopes: string[];
466+
createdAt: string | number | null;
467+
createdBy: string | null;
468+
expiresAt: string | number | null;
469+
lastUsedAt: string | number | null;
470+
revokedAt: string | number | null;
471+
builtIn: boolean;
472+
}
473+
474+
const stamp = (value: unknown): string | number | null => (typeof value === "string" || typeof value === "number" ? value : null);
475+
const strings = (value: unknown): string[] => (Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : []);
476+
477+
/**
478+
* POST /v1/admin/keys { name, role, expiresDays? } (admin) -> 201 with the key, once. The key is registered with the
479+
* scrubber before anything else is done with the reply, and no error built here ever quotes a successful reply's body.
480+
*/
481+
export async function createApiKey(options: BackendRequestOptions, input: { name: string; role: ApiKeyRole; expiresDays?: number }): Promise<CreatedApiKey> {
482+
const reply = await adminRequest(options, "POST", "/v1/admin/keys", { name: input.name, role: input.role, ...(input.expiresDays !== undefined ? { expiresDays: input.expiresDays } : {}) });
483+
const key = typeof reply.json?.key === "string" ? reply.json.key : undefined;
484+
if (key) registerSecret(key);
485+
if (reply.status === 200 || reply.status === 201) {
486+
const json = reply.json ?? {};
487+
if (!key || typeof json.id !== "string") throw new BackendError(`POST /v1/admin/keys answered ${reply.status} without an id and a key (the backend is older or broken); if a key was made, revoke it with \`typetorch keys list\` / \`keys revoke\``, reply.status);
488+
return { id: json.id, key, name: typeof json.name === "string" ? json.name : input.name, role: typeof json.role === "string" ? json.role : input.role, scopes: strings(json.scopes), createdAt: stamp(json.createdAt), expiresAt: stamp(json.expiresAt) };
489+
}
490+
if (reply.status === 404 && !reply.json?.error) throw new BackendError("POST /v1/admin/keys answered 404: the backend predates API keys (update it)", 404);
491+
throw new BackendError(`POST /v1/admin/keys answered ${reply.status}: ${key ? "(reply hidden)" : replyError(reply)}`, reply.status);
492+
}
493+
494+
/** GET /v1/admin/keys[?all=1] (admin): the keys (no hash, no secret), built-in env tokens included. */
495+
export async function listApiKeys(options: BackendRequestOptions, all = false): Promise<ApiKeyInfo[]> {
496+
const json = await adminJson(options, "GET", `/v1/admin/keys${all ? "?all=1" : ""}`);
497+
const keys = Array.isArray(json.keys) ? json.keys : [];
498+
return keys
499+
.filter((k): k is Record<string, unknown> => typeof k === "object" && k !== null && !Array.isArray(k))
500+
.map((k) => ({
501+
id: String(k.id ?? "?"),
502+
name: typeof k.name === "string" ? k.name : "",
503+
role: typeof k.role === "string" ? k.role : "?",
504+
scopes: strings(k.scopes),
505+
createdAt: stamp(k.createdAt),
506+
createdBy: typeof k.createdBy === "string" ? k.createdBy : null,
507+
expiresAt: stamp(k.expiresAt),
508+
lastUsedAt: stamp(k.lastUsedAt),
509+
revokedAt: stamp(k.revokedAt),
510+
builtIn: k.builtIn === true,
511+
}));
512+
}
513+
514+
/** DELETE /v1/admin/keys/{id} (admin) -> { ok, id, revokedAt }. */
515+
export async function revokeApiKey(options: BackendRequestOptions, id: string): Promise<{ id: string; revokedAt: string | number | null }> {
516+
const json = await adminJson(options, "DELETE", `/v1/admin/keys/${encodeURIComponent(id)}`);
517+
return { id: typeof json.id === "string" ? json.id : id, revokedAt: stamp(json.revokedAt) };
518+
}

‎src/commands/apikeys.ts‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
/**
2+
* `typetorch keys create | list | revoke`: named API keys with roles on the TypeTorch backend (plans/31), next to the
3+
* prod signing keys that `keys init | rotate | resign` manage (commands/keys.ts). Every call goes to typetorch.json
4+
* backend.url with TYPETORCH_ADMIN_TOKEN:
5+
*
6+
* create POST /v1/admin/keys { name, role, expiresDays? }: the key (`ttk_<id>_<secret>`) is printed ONCE (--json:
7+
* in `key`, for a script that pipes it into a secret store). It is registered with the scrubber the moment
8+
* it arrives, and never written to disk or logged.
9+
* list GET /v1/admin/keys [?all=1]: id, name, role, scopes, expiry, last use, built-in / revoked (never a secret)
10+
* revoke DELETE /v1/admin/keys/{id}; built-in ids (env:*, the env tokens) are refused here: rotate the env instead
11+
*/
12+
import { flagBool, flagString, UsageError, type ParsedArgs } from "../args.ts";
13+
import { API_KEY_ROLES, backendCredentialsWarned, createApiKey, listApiKeys, revokeApiKey, type ApiKeyInfo, type ApiKeyRole, type BackendRequestOptions } from "../backend.ts";
14+
import type { Project } from "../config.ts";
15+
import { ADMIN_TOKEN_VAR, registerSecret } from "../env.ts";
16+
import { bold, dim, emitJson, info, isJson, table, yellow } from "../log.ts";
17+
import { project } from "./common.ts";
18+
19+
export const API_KEY_SUBCOMMANDS = ["create", "list", "revoke"] as const;
20+
export const API_KEY_NAME = /^[a-z0-9._-]{1,48}$/;
21+
export const API_KEY_ID = /^[0-9a-z]{10}$/;
22+
export const EXPIRES_MAX_DAYS = 3650;
23+
24+
export const API_KEYS_USAGE = `typetorch keys create --name <name> --role <game|lookup|support|analyst|admin> [--expires <365d|90d|1y>]
25+
typetorch keys list [--all]
26+
typetorch keys revoke <id>
27+
28+
Named API keys with roles on the TypeTorch backend (plans/31), for tools that must not hold the admin token (a support
29+
bot reading one player's anticheat rows, an analyst's notebook). Through typetorch.json backend.url with
30+
${ADMIN_TOKEN_VAR}.
31+
create makes a key "ttk_<id>_<secret>" and prints it ONCE: store it right away (a secret store, the tool's env);
32+
the backend keeps only its hash. --json returns it in "key". The id is public (lists, the audit log).
33+
--name 1-48 characters of a-z 0-9 . _ -, unique among active keys
34+
--role game (ingest), lookup (identity:resolve), support (+ players:read), analyst (SQL and the named
35+
queries, identity:resolve), admin (everything)
36+
--expires 1-3650 days: 90d, 365d, 1y (default: never)
37+
list every key: id, name, role, scopes, expiry, last use, built-in / revoked; --all includes revoked keys. The env
38+
tokens (TYPETORCH_API_KEY, ${ADMIN_TOKEN_VAR}, TYPETORCH_LOOKUP_TOKEN) show as built-in (env:*)
39+
revoke ends a key at once (it answers 401 from then on). Built-in env:* keys can't be revoked: change the env
40+
variable on the backend instead`;
41+
42+
/** `--expires 365d | 90d | 1y` as days (1-3650). */
43+
export function parseExpires(value: string | undefined): number | undefined {
44+
if (value === undefined) return undefined;
45+
const match = /^(\d+)([dy])$/.exec(value.trim());
46+
const days = match ? Number(match[1]) * (match[2] === "y" ? 365 : 1) : NaN;
47+
if (!Number.isSafeInteger(days) || days < 1 || days > EXPIRES_MAX_DAYS) throw new UsageError(`--expires must be 1-${EXPIRES_MAX_DAYS} days written like 90d, 365d or 1y, got "${value}"`);
48+
return days;
49+
}
50+
51+
export function parseRole(value: string | undefined): ApiKeyRole {
52+
if (value === undefined || !(API_KEY_ROLES as readonly string[]).includes(value)) throw new UsageError(`--role must be one of ${API_KEY_ROLES.join(", ")}${value === undefined ? "" : `, got "${value}"`}`);
53+
return value as ApiKeyRole;
54+
}
55+
56+
export function parseKeyName(value: string | undefined): string {
57+
if (value === undefined || !API_KEY_NAME.test(value)) throw new UsageError(`--name must be 1-48 characters of a-z 0-9 . _ -${value === undefined ? "" : `, got "${value}"`}`);
58+
return value;
59+
}
60+
61+
/** A revoke target: a key id, never a whole key (that one is scrubbed and refused) or a built-in env:* id. */
62+
export function parseRevokeId(value: string | undefined): string {
63+
if (value === undefined) throw new UsageError("typetorch keys revoke <id> (the id from `typetorch keys list`)");
64+
if (value.startsWith("ttk_")) {
65+
registerSecret(value);
66+
throw new UsageError("that is a whole key, not its id: pass only the id (`typetorch keys list`), and treat the key you pasted as exposed");
67+
}
68+
if (value.startsWith("env:")) throw new UsageError(`${value} is a built-in key (an env token on the backend): it can't be revoked; change the variable in the backend's environment and restart it instead`);
69+
if (!API_KEY_ID.test(value)) throw new UsageError(`"${value}" isn't a key id (10 characters of 0-9 a-z, from \`typetorch keys list\`)`);
70+
return value;
71+
}
72+
73+
function backendOptions(proj: Project, fetcher?: typeof fetch): BackendRequestOptions {
74+
const url = proj.config.backend?.url;
75+
if (!url) throw new Error("typetorch.json has no backend.url: API keys live on the TypeTorch backend (typetorch backend setup)");
76+
const admin = backendCredentialsWarned().admin;
77+
if (!admin) throw new Error(`${ADMIN_TOKEN_VAR} isn't set (the game repo's .env or the environment): managing API keys is an admin call`);
78+
return { url, adminToken: admin.value, fetch: fetcher, timeoutMs: 20_000 };
79+
}
80+
81+
/** A timestamp (ISO text, unix ms or unix seconds) as "YYYY-MM-DD HH:MM" UTC, or the fallback. */
82+
export function when(value: string | number | null, fallback: string): string {
83+
if (value === null) return fallback;
84+
const date = typeof value === "number" ? new Date(value < 1e11 ? value * 1000 : value) : new Date(value);
85+
return Number.isNaN(date.getTime()) ? String(value) : date.toISOString().slice(0, 16).replace("T", " ");
86+
}
87+
88+
export function keyState(key: Pick<ApiKeyInfo, "builtIn" | "revokedAt">): string {
89+
return key.builtIn ? "built-in" : key.revokedAt !== null ? `revoked ${when(key.revokedAt, "")}` : "active";
90+
}
91+
92+
export interface ApiKeysDeps {
93+
fetch?: typeof fetch;
94+
}
95+
96+
export async function apiKeysCommand(sub: (typeof API_KEY_SUBCOMMANDS)[number], args: ParsedArgs, deps: ApiKeysDeps = {}) {
97+
const extra = args.positionals.slice(sub === "revoke" ? 2 : 1);
98+
if (extra.length) throw new UsageError(`unexpected argument "${extra[0]}"`);
99+
const misplaced = (flags: string[]) => {
100+
for (const flag of flags) if (args.flags[flag] !== undefined) throw new UsageError(`--${flag} belongs to \`typetorch keys ${flag === "all" ? "list" : "create"}\``);
101+
};
102+
if (sub === "create") {
103+
misplaced(["all"]);
104+
const name = parseKeyName(flagString(args, "name"));
105+
const role = parseRole(flagString(args, "role"));
106+
const expiresDays = parseExpires(flagString(args, "expires"));
107+
const proj = project(args);
108+
const created = await createApiKey(backendOptions(proj, deps.fetch), { name, role, ...(expiresDays !== undefined ? { expiresDays } : {}) });
109+
if (isJson()) return emitJson(created);
110+
info(bold(`API key created: ${created.id} "${created.name}", role ${created.role}${created.scopes.length ? ` (${created.scopes.join(", ")})` : ""}, expires ${when(created.expiresAt, "never")}`));
111+
info("");
112+
info(` ${created.key}`);
113+
info("");
114+
info(yellow("Store it now: it is not shown again (the backend keeps only its hash). Lost it? Revoke it and create another."));
115+
return;
116+
}
117+
if (sub === "list") {
118+
misplaced(["name", "role", "expires"]);
119+
const proj = project(args);
120+
const keys = await listApiKeys(backendOptions(proj, deps.fetch), flagBool(args, "all"));
121+
if (isJson()) return emitJson({ keys });
122+
if (keys.length === 0) {
123+
info("no API keys (and no built-in env tokens reported)");
124+
return;
125+
}
126+
info(table(["id", "name", "role", "scopes", "expires", "last used", "state"], keys.map((k) => [k.id, k.name || "-", k.role, k.scopes.join(",") || "-", when(k.expiresAt, "never"), when(k.lastUsedAt, "never"), keyState(k)])));
127+
if (!flagBool(args, "all")) info(dim(" --all also lists revoked keys"));
128+
return;
129+
}
130+
misplaced(["name", "role", "expires", "all"]);
131+
const id = parseRevokeId(args.positionals[1]);
132+
const proj = project(args);
133+
const revoked = await revokeApiKey(backendOptions(proj, deps.fetch), id);
134+
if (isJson()) return emitJson({ ok: true, id: revoked.id, revokedAt: revoked.revokedAt });
135+
info(bold(`API key ${revoked.id} revoked${revoked.revokedAt !== null ? ` at ${when(revoked.revokedAt, "")}` : ""}: it answers 401 from now on`));
136+
}

‎src/commands/keys.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
* main key(s), the key file is replaced, typetorch.json updated, the rekey hint
1616
* (TypeTorch/rekey) is published, and every prod-channel branch's CURRENT head is re-signed
1717
* (`keys resign`). For a lost or leaked main key; no restart.
18+
* keys create|list|revoke named API keys with roles on the backend (plans/31): commands/apikeys.ts
1819
* keys resign republishes each prod-channel branch's current head as a fresh signed deploy message:
1920
* same artifact and asset, a NEW seq, r = "resign" (kernels update the head, no swap). Under
2021
* the strict rule a head signed by a revoked main key is no longer valid, so this keeps new
@@ -36,6 +37,7 @@ import { KEY_FILE_FLAGS, noteRegistryFlags, openCloud, project, readHistory } fr
3637
import { loadSigner } from "../keyfiles.ts";
3738
import { readSettings } from "../settings.ts";
3839
import { changeSettings } from "./settings.ts";
40+
import { apiKeysCommand, type ApiKeysDeps } from "./apikeys.ts";
3941

4042
export const keysFlags = {
4143
fallback: "boolean",
@@ -46,6 +48,11 @@ export const keysFlags = {
4648
propose: "boolean",
4749
"proposed-by": "string",
4850
...KEY_FILE_FLAGS,
51+
// API keys on the backend (keys create / list / revoke, commands/apikeys.ts)
52+
name: "string",
53+
role: "string",
54+
expires: "string",
55+
all: "boolean",
4956
} as const;
5057

5158
/** Open Cloud clients and the terminal, injectable for tests. */
@@ -418,9 +425,11 @@ export async function resignCommand(ctx: KeysContext) {
418425
if (failed) process.exitCode = 1;
419426
}
420427

421-
export async function keysCommand(args: ParsedArgs, deps: KeysDeps = {}) {
428+
export async function keysCommand(args: ParsedArgs, deps: KeysDeps & ApiKeysDeps = {}) {
422429
const sub = args.positionals[0];
423-
if (sub !== "init" && sub !== "rotate" && sub !== "resign") throw new UsageError(`unknown keys subcommand "${sub ?? ""}" (init, init --fallback, rotate, resign)`);
430+
if (sub === "create" || sub === "list" || sub === "revoke") return apiKeysCommand(sub, args, { fetch: deps.fetch });
431+
if (sub !== "init" && sub !== "rotate" && sub !== "resign") throw new UsageError(`unknown keys subcommand "${sub ?? ""}" (init, init --fallback, rotate, resign; API keys: create, list, revoke)`);
432+
for (const flag of ["name", "role", "expires", "all"]) if (args.flags[flag] !== undefined) throw new UsageError(`--${flag} belongs to \`typetorch keys create\` / \`keys list\``);
424433
const proj = project(args);
425434
const ctx: KeysContext = {
426435
proj,

0 commit comments

Comments
 (0)