- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/key-admin.ts?draft=login-timeout&format=json
149 linesFirst import 93% · review 6% · pinch 1%0 versions changed it
1// abso key new, list and revoke (abso issue 116). The admin token is read at
2// run time and sent only as a header. It is never an argument and never printed.
4import { readFileSync } from "node:fs";
5import { homedir } from "node:os";
6import { join } from "node:path";
7import { UsageError } from "./args.ts";
8import type { Config } from "./config.ts";
9import { fromEnv } from "./env-names.ts";
10import { homeFile } from "./state-dir.ts";
12function originOf(server: string): string {
13 try {
14 return new URL(server).origin;
15 } catch {
16 return server;
17 }
18}
20/** The admin token goes only to a server named in ABSO_ADMIN_SERVERS (comma-separated): none is built in. */
21export function adminGoesTo(server: string, extra = ""): boolean {
22 const allowed = [
23 ...extra
24 .split(",")
25 .map((s) => s.trim())
26 .filter((s) => s !== ""),
27 ];
28 const origin = originOf(server);
29 return allowed.some((s) => originOf(s) === origin);
30}
32export function adminToken(env: Readonly<Record<string, string | undefined>> = process.env): string {
33 const fromVar = fromEnv(env, "ADMIN_TOKEN")?.trim();
34 if (fromVar) return fromVar;
35 try {
36 const fromFile = readFileSync(homeFile(homedir(), "admin-token"), "utf8").trim();
37 if (fromFile) return fromFile;
38 } catch {}
39 throw new UsageError("abso key needs the admin token in ABSO_ADMIN_TOKEN or ~/.abso/admin-token");
40}
42function scrub(text: string, secrets: readonly string[]): string {
43 let out = text.replace(/abso_sk_[A-Za-z0-9_-]+/g, "[redacted]");
44 for (const secret of secrets) if (secret.length > 0) out = out.split(secret).join("[redacted]");
45 return out;
46}
48async function call(config: Config, admin: string, method: "GET" | "POST", path: string): Promise<unknown> {
49 if (!adminGoesTo(config.server, fromEnv(process.env, "ADMIN_SERVERS")))
50 throw new UsageError(
51 `abso key will not send the admin token to ${config.server}; ABSO_ADMIN_SERVERS names the servers it may go to`,
52 );
53 const secrets = [admin, config.token ?? ""].filter((s) => s.length > 0);
54 let response: Response;
55 try {
56 response = await fetch(`${config.server.replace(/\/+$/, "")}${path}`, {
57 method,
58 headers: {
59 ...(config.token ? { authorization: `Bearer ${config.token}` } : {}),
60 "x-abso-admin": admin,
61 },
62 signal: AbortSignal.timeout(30_000),
63 });
64 } catch (err) {
65 throw new UsageError(scrub(err instanceof Error ? err.message : String(err), secrets));
66 }
67 const text = await response.text();
68 if (!response.ok)
69 throw new UsageError(scrub(text.slice(0, 500) || `the server answered ${response.status}`, secrets));
70 try {
71 return JSON.parse(text) as unknown;
72 } catch {
73 throw new UsageError("the server's answer was not JSON");
74 }
75}
77export interface IssuedKey {
78 id: string;
79 key: string;
80 agent: string;
81}
83export async function keyNew(
84 config: Config,
85 admin: string,
86 agent: string,
87 project = config.project,
88 expires?: string,
89 role?: "owner" | "writer" | "reader",
90): Promise<IssuedKey> {
91 const query = `project=${encodeURIComponent(project)}&agent=${encodeURIComponent(agent)}${expires ? `&expires=${encodeURIComponent(expires)}` : ""}${role ? `&role=${role}` : ""}`;
92 const body = (await call(config, admin, "POST", `/admin/agent-keys?${query}`)) as Partial<IssuedKey>;
93 if (typeof body.id !== "string" || typeof body.key !== "string")
94 throw new UsageError("the server did not return a key");
95 return { id: body.id, key: body.key, agent: typeof body.agent === "string" ? body.agent : agent };
96}
98/** What `abso key new` may show. The key is included only with --print. */
99export function issuedPublic(issued: IssuedKey, print: boolean): { id: string; agent: string; key?: string } {
100 return print ? { id: issued.id, agent: issued.agent, key: issued.key } : { id: issued.id, agent: issued.agent };
101}
103export interface ListedKey {
104 id: string;
105 agent: string;
106 issuedBy: string;
107 at: number;
108 lastUsed: number | null;
109 revokedAt: number | null;
110 expiresAt?: number | null;
111}
113export async function keyList(
114 config: Config,
115 admin: string,
116 agent?: string,
117 project = config.project,
118): Promise<ListedKey[]> {
119 const query = `project=${encodeURIComponent(project)}${agent ? `&agent=${encodeURIComponent(agent)}` : ""}`;
120 const body = (await call(config, admin, "GET", `/admin/agent-keys?${query}`)) as { keys?: ListedKey[] };
121 return body.keys ?? [];
122}
124export async function keyRevoke(config: Config, admin: string, id: string, project = config.project): Promise<boolean> {
125 const body = (await call(
126 config,
127 admin,
128 "POST",
129 `/admin/agent-keys/revoke?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}`,
130 )) as { revoked?: boolean };
131 return body.revoked === true;
132}
134/** What `abso key list` prints. The key's value is not a field, so it cannot appear. */
135export function keyListText(keys: readonly ListedKey[]): string {
136 if (keys.length === 0) return "No keys.";
137 return keys
138 .map((k) => {
139 const when = new Date(k.at).toISOString().slice(0, 16).replace("T", " ");
140 const used =
141 k.lastUsed === null
142 ? "never used"
143 : `last used ${new Date(k.lastUsed).toISOString().slice(0, 16).replace("T", " ")}`;
144 const until = k.expiresAt ? `, until ${new Date(k.expiresAt).toISOString().slice(0, 10)}` : "";
145 const state = k.revokedAt === null ? used : "revoked";
146 return `${k.id} ${k.agent} ${k.issuedBy} ${when} ${state}${until}`;
147 })
148 .join("\n");
149}