Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
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?format=json
153 linesFirst import 90% · review 6% · readspeed 3% · pinch 1%Last change readspeed in version 271, 6 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.
3
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 }
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);
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");
41/** What an admin command says each time it uses the admin token, and where it came from. Never the token. */
42export function adminTokenWords(env: Readonly<Record<string, string | undefined>> = process.env): string {
43 return `Using the admin token, from ${fromEnv(env, "ADMIN_TOKEN")?.trim() ? "ABSO_ADMIN_TOKEN" : "~/.abso/admin-token"}.`;
46function scrub(text: string, secrets: readonly string[]): string {
47 let out = text.replace(/abso_sk_[A-Za-z0-9_-]+/g, "[redacted]");
48 for (const secret of secrets) if (secret.length > 0) out = out.split(secret).join("[redacted]");
49 return out;
52async function call(config: Config, admin: string, method: "GET" | "POST", path: string): Promise<unknown> {
53 if (!adminGoesTo(config.server, fromEnv(process.env, "ADMIN_SERVERS")))
54 throw new UsageError(
55 `abso key will not send the admin token to ${config.server}; ABSO_ADMIN_SERVERS names the servers it may go to`,
56 );
57 const secrets = [admin, config.token ?? ""].filter((s) => s.length > 0);
58 let response: Response;
59 try {
60 response = await fetch(`${config.server.replace(/\/+$/, "")}${path}`, {
61 method,
62 headers: {
63 ...(config.token ? { authorization: `Bearer ${config.token}` } : {}),
64 "x-abso-admin": admin,
65 },
66 signal: AbortSignal.timeout(30_000),
67 });
68 } catch (err) {
69 throw new UsageError(scrub(err instanceof Error ? err.message : String(err), secrets));
70 }
71 const text = await response.text();
72 if (!response.ok)
73 throw new UsageError(scrub(text.slice(0, 500) || `the server answered ${response.status}`, secrets));
74 try {
75 return JSON.parse(text) as unknown;
76 } catch {
77 throw new UsageError("the server's answer was not JSON");
78 }
81export interface IssuedKey {
82 id: string;
83 key: string;
84 agent: string;
87export async function keyNew(
88 config: Config,
89 admin: string,
90 agent: string,
91 project = config.project,
92 expires?: string,
93 role?: "owner" | "writer" | "reader",
94): Promise<IssuedKey> {
95 const query = `project=${encodeURIComponent(project)}&agent=${encodeURIComponent(agent)}${expires ? `&expires=${encodeURIComponent(expires)}` : ""}${role ? `&role=${role}` : ""}`;
96 const body = (await call(config, admin, "POST", `/admin/agent-keys?${query}`)) as Partial<IssuedKey>;
97 if (typeof body.id !== "string" || typeof body.key !== "string")
98 throw new UsageError("the server did not return a key");
99 return { id: body.id, key: body.key, agent: typeof body.agent === "string" ? body.agent : agent };
102/** What `abso key new` may show. The key is included only with --print. */
103export function issuedPublic(issued: IssuedKey, print: boolean): { id: string; agent: string; key?: string } {
104 return print ? { id: issued.id, agent: issued.agent, key: issued.key } : { id: issued.id, agent: issued.agent };
107export interface ListedKey {
108 id: string;
109 agent: string;
110 issuedBy: string;
111 at: number;
112 lastUsed: number | null;
113 revokedAt: number | null;
114 expiresAt?: number | null;
117export async function keyList(
118 config: Config,
119 admin: string,
120 agent?: string,
121 project = config.project,
122): Promise<ListedKey[]> {
123 const query = `project=${encodeURIComponent(project)}${agent ? `&agent=${encodeURIComponent(agent)}` : ""}`;
124 const body = (await call(config, admin, "GET", `/admin/agent-keys?${query}`)) as { keys?: ListedKey[] };
125 return body.keys ?? [];
128export async function keyRevoke(config: Config, admin: string, id: string, project = config.project): Promise<boolean> {
129 const body = (await call(
130 config,
131 admin,
132 "POST",
133 `/admin/agent-keys/revoke?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}`,
134 )) as { revoked?: boolean };
135 return body.revoked === true;
138/** What `abso key list` prints. The key's value is not a field, so it cannot appear. */
139export function keyListText(keys: readonly ListedKey[]): string {
140 if (keys.length === 0) return "No keys.";
141 return keys
142 .map((k) => {
143 const when = new Date(k.at).toISOString().slice(0, 16).replace("T", " ");
144 const used =
145 k.lastUsed === null
146 ? "never used"
147 : `last used ${new Date(k.lastUsed).toISOString().slice(0, 16).replace("T", " ")}`;
148 const until = k.expiresAt ? `, until ${new Date(k.expiresAt).toISOString().slice(0, 10)}` : "";
149 const state = k.revokedAt === null ? used : "revoked";
150 return `${k.id} ${k.agent} ${k.issuedBy} ${when} ${state}${until}`;
151 })
152 .join("\n");