|
| 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 | +} |
0 commit comments