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