@keyboxed/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/keybox.js ADDED
@@ -0,0 +1,665 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { parseArgs } from "node:util";
5
+
6
+ // src/commands.ts
7
+ import { spawn } from "node:child_process";
8
+ import { readFileSync as readFileSync2 } from "node:fs";
9
+
10
+ // src/config.ts
11
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { join } from "node:path";
14
+ function configDir() {
15
+ return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "keybox");
16
+ }
17
+ var configPath = () => join(configDir(), "config.json");
18
+ var deployDir = () => join(configDir(), "deploy");
19
+ function loadConfig() {
20
+ const env = process.env;
21
+ if (env.KEYBOX_URL && env.KEYBOX_ADMIN_TOKEN) {
22
+ return { url: env.KEYBOX_URL, adminToken: env.KEYBOX_ADMIN_TOKEN, name: env.KEYBOX_NAME ?? "keybox", d1Id: "" };
23
+ }
24
+ if (!existsSync(configPath())) return null;
25
+ return JSON.parse(readFileSync(configPath(), "utf8"));
26
+ }
27
+ function requireConfig() {
28
+ const c = loadConfig();
29
+ if (!c) throw new UserError("Not set up yet. Run `keybox init` first.");
30
+ return c;
31
+ }
32
+ function saveConfig(c) {
33
+ mkdirSync(configDir(), { recursive: true, mode: 448 });
34
+ writeFileSync(configPath(), JSON.stringify(c, null, 2) + "\n", { mode: 384 });
35
+ chmodSync(configPath(), 384);
36
+ }
37
+ var UserError = class extends Error {
38
+ };
39
+
40
+ // src/api.ts
41
+ async function api(method, path, body, config = requireConfig()) {
42
+ let res;
43
+ try {
44
+ res = await fetch(`${config.url.replace(/\/$/, "")}/_keybox/admin${path}`, {
45
+ method,
46
+ headers: { authorization: `Bearer ${config.adminToken}`, "content-type": "application/json" },
47
+ body: body === void 0 ? void 0 : JSON.stringify(body)
48
+ });
49
+ } catch {
50
+ throw new UserError(`Could not reach ${config.url}.`);
51
+ }
52
+ const data = await res.json().catch(() => null);
53
+ if (!res.ok) throw new UserError(data?.error?.message ?? `Keybox returned HTTP ${res.status}.`);
54
+ return data;
55
+ }
56
+
57
+ // src/presets.ts
58
+ var PRESETS = {
59
+ openai: {
60
+ hosts: ["api.openai.com"],
61
+ header: "authorization",
62
+ format: "bearer",
63
+ env: (base, token) => ({ OPENAI_BASE_URL: `${base}/api.openai.com/v1`, OPENAI_API_KEY: token })
64
+ },
65
+ anthropic: {
66
+ hosts: ["api.anthropic.com"],
67
+ header: "x-api-key",
68
+ format: "raw",
69
+ env: (base, token) => ({ ANTHROPIC_BASE_URL: `${base}/api.anthropic.com`, ANTHROPIC_API_KEY: token })
70
+ },
71
+ github: { hosts: ["api.github.com"], header: "authorization", format: "bearer" },
72
+ stripe: { hosts: ["api.stripe.com"], header: "authorization", format: "bearer" },
73
+ cloudflare: { hosts: ["api.cloudflare.com"], header: "authorization", format: "bearer" }
74
+ };
75
+ var KEY_VARS = [
76
+ "OPENAI_API_KEY",
77
+ "ANTHROPIC_API_KEY",
78
+ "GITHUB_TOKEN",
79
+ "GH_TOKEN",
80
+ "STRIPE_API_KEY",
81
+ "STRIPE_SECRET_KEY",
82
+ "CLOUDFLARE_API_TOKEN",
83
+ "CLOUDFLARE_API_KEY",
84
+ "AWS_ACCESS_KEY_ID",
85
+ "AWS_SECRET_ACCESS_KEY",
86
+ "AWS_SESSION_TOKEN",
87
+ "GOOGLE_API_KEY",
88
+ "GEMINI_API_KEY",
89
+ "HF_TOKEN",
90
+ "KEYBOX_ADMIN_TOKEN"
91
+ ];
92
+ function envFor(hosts, base, token) {
93
+ const out = { KEYBOX_URL: base, KEYBOX_TOKEN: token };
94
+ for (const p of Object.values(PRESETS)) {
95
+ if (p.env && p.hosts.some((h) => hosts.includes(h))) Object.assign(out, p.env(base, token));
96
+ }
97
+ return out;
98
+ }
99
+
100
+ // src/prompt.ts
101
+ import { createInterface } from "node:readline/promises";
102
+ async function readSecret(label) {
103
+ const stdin = process.stdin;
104
+ if (!stdin.isTTY) {
105
+ let data = "";
106
+ for await (const chunk of stdin) data += chunk;
107
+ return data.replace(/\r?\n$/, "");
108
+ }
109
+ process.stderr.write(`${label}: `);
110
+ stdin.setRawMode(true);
111
+ stdin.resume();
112
+ stdin.setEncoding("utf8");
113
+ return new Promise((resolve, reject) => {
114
+ let value = "";
115
+ const done = (err) => {
116
+ stdin.setRawMode(false);
117
+ stdin.pause();
118
+ stdin.off("data", onData);
119
+ process.stderr.write("\n");
120
+ err ? reject(err) : resolve(value);
121
+ };
122
+ const onData = (s) => {
123
+ for (const ch of s) {
124
+ if (ch === "\r" || ch === "\n") return done();
125
+ if (ch === "") return done(new UserError("Cancelled."));
126
+ if (ch === "\x7F" || ch === "\b") value = value.slice(0, -1);
127
+ else value += ch;
128
+ }
129
+ };
130
+ stdin.on("data", onData);
131
+ });
132
+ }
133
+ async function confirm(question) {
134
+ if (!process.stdin.isTTY) return false;
135
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
136
+ const answer = await rl.question(`${question} [y/N] `);
137
+ rl.close();
138
+ return /^y(es)?$/i.test(answer.trim());
139
+ }
140
+
141
+ // src/ui.ts
142
+ var tty = process.stderr.isTTY && !process.env.NO_COLOR;
143
+ var dim = (s) => tty ? `\x1B[2m${s}\x1B[0m` : s;
144
+ var blue = (s) => tty ? `\x1B[34m${s}\x1B[0m` : s;
145
+ function step(s) {
146
+ process.stderr.write(`${blue("\u25A0")} ${s}
147
+ `);
148
+ }
149
+ function note(s) {
150
+ process.stderr.write(`${dim(" " + s)}
151
+ `);
152
+ }
153
+ function table(rows) {
154
+ if (rows.length === 0) return "";
155
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => (r[i] ?? "").length)));
156
+ return rows.map((r) => r.map((c, i) => i === r.length - 1 ? c : c.padEnd(widths[i])).join(" ")).join("\n") + "\n";
157
+ }
158
+ function when(ms) {
159
+ return new Date(ms).toISOString().replace("T", " ").slice(0, 19);
160
+ }
161
+ function parseDuration(s) {
162
+ const m = /^(\d+)([smhd]?)$/.exec(s.trim());
163
+ if (!m) throw new Error(`bad duration: ${s}`);
164
+ return Number(m[1]) * { "": 1, s: 1, m: 60, h: 3600, d: 86400 }[m[2]];
165
+ }
166
+
167
+ // src/commands.ts
168
+ function guessPreset(name) {
169
+ const prefix = name.split("_")[0];
170
+ if (prefix === "GH") return "github";
171
+ const p = prefix.toLowerCase();
172
+ return p in PRESETS ? p : null;
173
+ }
174
+ async function secretsAdd(name, opts) {
175
+ let spec;
176
+ if (opts.host?.length) {
177
+ spec = { hosts: opts.host, header: opts.header ?? "authorization", format: opts.format ?? "bearer" };
178
+ } else {
179
+ const preset = opts.preset ?? guessPreset(name);
180
+ if (!preset || !PRESETS[preset]) {
181
+ throw new UserError(`Say where ${name} may be sent: --preset ${Object.keys(PRESETS).join("|")} or --host <hostname>.`);
182
+ }
183
+ spec = PRESETS[preset];
184
+ if (!opts.preset) note(`Using preset ${preset}: ${spec.hosts.join(", ")}, ${spec.header} (${spec.format}).`);
185
+ }
186
+ const value = await readSecret(`Value for ${name} (hidden)`);
187
+ if (!value) throw new UserError("No value given.");
188
+ const r = await api("PUT", `/secrets/${name}`, { ...spec, value });
189
+ process.stderr.write(`Stored ${r.name}. It will only ever be sent to ${r.hosts.join(", ")}.
190
+ `);
191
+ }
192
+ function parseDotenv(text) {
193
+ const out = [];
194
+ for (const line of text.split(/\r?\n/)) {
195
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
196
+ if (!m) continue;
197
+ let v = m[2].trim();
198
+ const q = v[0];
199
+ if ((q === '"' || q === "'") && v.lastIndexOf(q) > 0) v = v.slice(1, v.lastIndexOf(q));
200
+ else v = v.replace(/\s+#.*$/, "");
201
+ out.push([m[1], v]);
202
+ }
203
+ return out;
204
+ }
205
+ var SECRET_NAME = /(KEY|TOKEN|SECRET|PAT)$/;
206
+ var NOT_SECRET = /(PUBLISHABLE|PUBLIC)/;
207
+ async function secretsImport(file, opts) {
208
+ let text;
209
+ try {
210
+ text = readFileSync2(file, "utf8");
211
+ } catch {
212
+ throw new UserError(`Cannot read ${file}.`);
213
+ }
214
+ const existing = new Set((await api("GET", "/secrets")).map((x) => x.name));
215
+ const found = [];
216
+ const skipped = [];
217
+ for (const [name, value] of parseDotenv(text)) {
218
+ const preset = guessPreset(name);
219
+ if (!SECRET_NAME.test(name) || NOT_SECRET.test(name)) {
220
+ if (preset) skipped.push([name, "not a credential"]);
221
+ continue;
222
+ }
223
+ if (!preset) skipped.push([name, "no preset; add it with --host"]);
224
+ else if (value.length < 8) skipped.push([name, "empty or placeholder"]);
225
+ else found.push({ name, value, preset });
226
+ }
227
+ const rows = found.map((f) => [f.name, PRESETS[f.preset].hosts.join(","), existing.has(f.name) ? "replaces existing" : "new"]);
228
+ if (rows.length) process.stdout.write(table([["NAME", "ONLY SENT TO", ""], ...rows]));
229
+ for (const [name, why] of skipped) process.stderr.write(`skipped ${name}: ${why}
230
+ `);
231
+ if (!rows.length) return note(`Nothing to import from ${file}.`);
232
+ if (opts.dryRun) return note("Dry run. Nothing was stored.");
233
+ if (!opts.yes && !await confirm(`Store ${found.length} secret${found.length === 1 ? "" : "s"} in Keybox?`)) {
234
+ throw new UserError("Cancelled. Re-run with --yes to skip the prompt.");
235
+ }
236
+ for (const f of found) await api("PUT", `/secrets/${f.name}`, { ...PRESETS[f.preset], value: f.value });
237
+ process.stderr.write(
238
+ `Stored ${found.length}. ${file} still holds the original values. Delete them there and rotate the keys once you have checked Keybox works.
239
+ `
240
+ );
241
+ }
242
+ async function secretsList() {
243
+ const rows = await api("GET", "/secrets");
244
+ if (!rows.length) return note("No secrets yet. Add one with `keybox secrets add NAME`.");
245
+ process.stdout.write(table([["NAME", "HOSTS", "HEADER", "ADDED"], ...rows.map((s) => [s.name, s.hosts.join(","), `${s.header} (${s.format})`, when(s.created_at)])]));
246
+ }
247
+ async function secretsRm(name) {
248
+ const r = await api("DELETE", `/secrets/${name}`);
249
+ process.stderr.write(r.deleted ? `Deleted ${name}.
250
+ ` : `No secret named ${name}.
251
+ `);
252
+ }
253
+ function buildGrants(allow, deny, secrets) {
254
+ const grants = /* @__PURE__ */ new Map();
255
+ const hostOf = (rule) => /^\S+\s+([^/\s]+)/.exec(rule)?.[1] ?? "";
256
+ const resolve = (raw) => {
257
+ const named = /^([A-Z][A-Z0-9_]*)=(.+)$/.exec(raw);
258
+ if (named) return [named[1], named[2].trim()];
259
+ const host = hostOf(raw);
260
+ const bound = secrets.filter((s) => s.hosts.includes(host));
261
+ if (bound.length === 1) return [bound[0].name, raw];
262
+ if (bound.length === 0) throw new UserError(`No stored secret is bound to ${host || "that host"} (rule "${raw}").`);
263
+ throw new UserError(`Several secrets are bound to ${host}; prefix the rule: "${bound[0].name}=${raw}".`);
264
+ };
265
+ for (const raw of allow) {
266
+ const [secret, rule] = resolve(raw);
267
+ const g = grants.get(secret) ?? { secret, allow: [] };
268
+ g.allow.push(rule);
269
+ grants.set(secret, g);
270
+ }
271
+ for (const raw of deny) {
272
+ const named = /^([A-Z][A-Z0-9_]*)=(.+)$/.exec(raw);
273
+ const targets = named ? [grants.get(named[1])] : [...grants.values()].filter((g) => {
274
+ const host = hostOf(raw);
275
+ return host.includes("*") || secrets.find((s) => s.name === g.secret)?.hosts.includes(host);
276
+ });
277
+ const rule = named ? named[2].trim() : raw;
278
+ if (!targets.length || targets.some((t) => !t)) throw new UserError(`Deny rule "${raw}" does not apply to any allowed secret.`);
279
+ for (const g of targets) (g.deny ??= []).push(rule);
280
+ }
281
+ return [...grants.values()];
282
+ }
283
+ async function agentsCreate(name, opts) {
284
+ if (!opts.allow?.length) throw new UserError('Give at least one --allow rule, e.g. --allow "GET api.github.com/repos/**".');
285
+ const secrets = await api("GET", "/secrets");
286
+ const grants = buildGrants(opts.allow, opts.deny ?? [], secrets);
287
+ await api("PUT", `/agents/${name}`, { grants });
288
+ process.stderr.write(`Agent ${name} can now:
289
+ `);
290
+ for (const g of grants) {
291
+ for (const r of g.allow) process.stderr.write(` allow ${r} (with ${g.secret})
292
+ `);
293
+ for (const r of g.deny ?? []) process.stderr.write(` deny ${r}
294
+ `);
295
+ }
296
+ process.stderr.write(`Everything else is denied. Start it with: keybox run ${name} -- <command>
297
+ `);
298
+ }
299
+ async function agentsList() {
300
+ const rows = await api("GET", "/agents");
301
+ if (!rows.length) return note("No agents yet. Create one with `keybox agents create NAME --allow RULE`.");
302
+ const out = [["AGENT", "SECRET", "RULE", "TOKENS"]];
303
+ for (const a of rows) {
304
+ let first = true;
305
+ for (const g of a.grants) {
306
+ for (const [kind, r] of [...g.allow.map((r2) => ["allow", r2]), ...(g.deny ?? []).map((r2) => ["deny", r2])]) {
307
+ out.push([first ? a.name : "", g.secret, `${kind} ${r}`, first ? String(a.active_tokens) : ""]);
308
+ first = false;
309
+ }
310
+ }
311
+ }
312
+ process.stdout.write(table(out));
313
+ }
314
+ async function agentsRm(name) {
315
+ await api("DELETE", `/agents/${name}`);
316
+ process.stderr.write(`Removed ${name} and revoked its tokens.
317
+ `);
318
+ }
319
+ async function agentsToken(name, opts) {
320
+ const m = await api("POST", `/agents/${name}/tokens`, { ttl: parseDuration(opts.ttl) });
321
+ process.stderr.write(`Token ${m.id} for ${name}, expires ${when(m.expires_at)} UTC. It is shown once.
322
+ `);
323
+ process.stdout.write(m.token + "\n");
324
+ }
325
+ async function tokensRevoke(id) {
326
+ const r = await api("DELETE", `/tokens/${id}`);
327
+ process.stderr.write(r.revoked ? `Revoked ${id}.
328
+ ` : `No active token ${id}.
329
+ `);
330
+ }
331
+ var BASE_ENV = ["PATH", "HOME", "USER", "LOGNAME", "SHELL", "TERM", "LANG", "LC_ALL", "TMPDIR", "TZ", "COLORTERM", "NO_COLOR", "FORCE_COLOR"];
332
+ async function run(name, cmd, opts) {
333
+ if (!cmd.length) throw new UserError("Nothing to run. Usage: keybox run AGENT -- command [args]");
334
+ const c = requireConfig();
335
+ const [agents, secrets] = await Promise.all([api("GET", "/agents"), api("GET", "/secrets")]);
336
+ const agent = agents.find((a) => a.name === name);
337
+ if (!agent) throw new UserError(`No agent named ${name}.`);
338
+ const hosts = secrets.filter((s) => agent.grants.some((g) => g.secret === s.name)).flatMap((s) => s.hosts);
339
+ const minted = await api("POST", `/agents/${name}/tokens`, { ttl: parseDuration(opts.ttl) });
340
+ const env = opts.cleanEnv ? Object.fromEntries(BASE_ENV.filter((k) => process.env[k] !== void 0).map((k) => [k, process.env[k]])) : { ...process.env };
341
+ const removed = [];
342
+ for (const k of /* @__PURE__ */ new Set([...KEY_VARS, ...secrets.map((s) => s.name)])) {
343
+ if (env[k] !== void 0) {
344
+ delete env[k];
345
+ removed.push(k);
346
+ }
347
+ }
348
+ if (removed.length) note(`Removed ${removed.join(", ")} from ${name}'s environment.`);
349
+ Object.assign(env, envFor(hosts, c.url.replace(/\/$/, ""), minted.token));
350
+ const revoke = () => api("DELETE", `/tokens/${minted.id}`).catch(() => note(`Could not revoke token ${minted.id}; it expires ${when(minted.expires_at)} UTC.`));
351
+ const child = spawn(cmd[0], cmd.slice(1), { stdio: "inherit", env });
352
+ const ignore = () => {
353
+ };
354
+ process.on("SIGINT", ignore);
355
+ process.on("SIGTERM", () => child.kill("SIGTERM"));
356
+ const code = await new Promise((resolve) => {
357
+ child.on("error", (err) => {
358
+ note(`Could not start ${cmd[0]}: ${err.message}`);
359
+ resolve(127);
360
+ });
361
+ child.on("close", (code2, signal) => resolve(code2 ?? (signal ? 128 + (signalNumber(signal) ?? 1) : 1)));
362
+ });
363
+ await revoke();
364
+ process.off("SIGINT", ignore);
365
+ process.exitCode = code;
366
+ }
367
+ function signalNumber(s) {
368
+ return { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGTERM: 15 }[s];
369
+ }
370
+ function auditLine(r) {
371
+ return [when(r.ts), r.agent ?? "-", r.decision === "allow" ? String(r.status) : r.decision.toUpperCase(), `${r.method} ${r.host ?? ""}${r.path ?? ""}`, r.secret ?? r.reason ?? ""];
372
+ }
373
+ async function audit(opts) {
374
+ let rows = await api("GET", `/audit?limit=${Number(opts.limit) || 50}`);
375
+ process.stdout.write(table([["TIME (UTC)", "AGENT", "RESULT", "REQUEST", "SECRET / REASON"], ...rows.map(auditLine)]));
376
+ if (!opts.follow) return;
377
+ let last = rows.at(-1)?.id ?? 0;
378
+ for (; ; ) {
379
+ await new Promise((r) => setTimeout(r, 2e3));
380
+ rows = await api("GET", `/audit?after=${last}&limit=500`);
381
+ if (rows.length) {
382
+ process.stdout.write(table(rows.map(auditLine)));
383
+ last = rows.at(-1).id;
384
+ }
385
+ }
386
+ }
387
+ async function blocked() {
388
+ const rows = await api("GET", "/blocked");
389
+ process.stdout.write(table([["NEVER PROXIED", "WHY"], ...rows.map((r) => [r.rule, r.reason])]));
390
+ }
391
+
392
+ // src/deploy.ts
393
+ import { createHash, randomBytes } from "node:crypto";
394
+ import { copyFileSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "node:fs";
395
+ import { join as join3 } from "node:path";
396
+
397
+ // src/wrangler.ts
398
+ import { spawn as spawn2 } from "node:child_process";
399
+ import { readFileSync as readFileSync3 } from "node:fs";
400
+ import { createRequire } from "node:module";
401
+ import { dirname, join as join2 } from "node:path";
402
+ function bin() {
403
+ const pkgPath = createRequire(import.meta.url).resolve("wrangler/package.json");
404
+ const pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
405
+ return join2(dirname(pkgPath), pkg.bin.wrangler);
406
+ }
407
+ function wrangler(args, opts = {}) {
408
+ return new Promise((resolve, reject) => {
409
+ const child = spawn2(process.execPath, [bin(), ...args], {
410
+ stdio: [opts.input === void 0 ? "inherit" : "pipe", opts.capture ? "pipe" : "inherit", "inherit"],
411
+ env: { ...process.env, WRANGLER_SEND_METRICS: "false" }
412
+ });
413
+ let out = "";
414
+ child.stdout?.on("data", (d) => out += d);
415
+ if (opts.input !== void 0) child.stdin.end(opts.input);
416
+ child.on("error", reject);
417
+ child.on("close", (code) => {
418
+ if (code === 0) resolve(out);
419
+ else reject(new UserError(`wrangler ${args.slice(0, 2).join(" ")} failed (exit ${code}).`));
420
+ });
421
+ });
422
+ }
423
+ function parseJson(out) {
424
+ const start = out.search(/[[{]/);
425
+ if (start === -1) throw new UserError("Unexpected output from wrangler.");
426
+ return JSON.parse(out.slice(start));
427
+ }
428
+
429
+ // src/deploy.ts
430
+ var COMPAT_DATE = "2026-07-01";
431
+ var asset = (f) => new URL(`../assets/${f}`, import.meta.url).pathname;
432
+ var sha = (path) => createHash("sha256").update(readFileSync4(path)).digest("hex");
433
+ function writeDeployFiles(name, d1Id) {
434
+ const dir = deployDir();
435
+ mkdirSync2(join3(dir, "worker"), { recursive: true, mode: 448 });
436
+ copyFileSync(asset("worker.js"), join3(dir, "worker", "worker.js"));
437
+ copyFileSync(asset("schema.sql"), join3(dir, "schema.sql"));
438
+ const cfg = join3(dir, "wrangler.json");
439
+ writeFileSync2(
440
+ cfg,
441
+ JSON.stringify(
442
+ {
443
+ name,
444
+ main: "worker/worker.js",
445
+ compatibility_date: COMPAT_DATE,
446
+ no_bundle: true,
447
+ workers_dev: true,
448
+ // Request logs would hold paths and headers; Keybox writes its own audit log instead.
449
+ observability: { enabled: false },
450
+ d1_databases: [{ binding: "DB", database_name: name, database_id: d1Id }],
451
+ vars: { KEYBOX_SCRIPT_NAME: name, KEYBOX_D1_ID: d1Id }
452
+ },
453
+ null,
454
+ 2
455
+ ) + "\n"
456
+ );
457
+ return cfg;
458
+ }
459
+ async function findDb(name) {
460
+ const dbs = parseJson(await wrangler(["d1", "list", "--json"], { capture: true }));
461
+ return dbs.find((d) => d.name === name)?.uuid ?? null;
462
+ }
463
+ async function waitConfigured(url) {
464
+ for (let i = 0; i < 30; i++) {
465
+ try {
466
+ const r = await fetch(`${url}/_keybox/health`);
467
+ if (r.ok && (await r.json()).configured) return true;
468
+ } catch {
469
+ }
470
+ await new Promise((r) => setTimeout(r, 1e3));
471
+ }
472
+ return false;
473
+ }
474
+ async function init(opts) {
475
+ const { name } = opts;
476
+ if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name)) throw new UserError("--name must be lowercase letters, digits and dashes.");
477
+ if (loadConfig()) throw new UserError(`Already set up (${configPath()}). Use \`keybox deploy\` to upgrade.`);
478
+ step("Checking your Cloudflare login");
479
+ await wrangler(["whoami"], { capture: true }).catch(() => {
480
+ throw new UserError("Log in to Cloudflare first: npx wrangler login");
481
+ });
482
+ step(`Creating D1 database "${name}"`);
483
+ let d1Id = await findDb(name);
484
+ if (d1Id) note("Database already exists; reusing it.");
485
+ else {
486
+ await wrangler(["d1", "create", name], { capture: true });
487
+ d1Id = await findDb(name);
488
+ }
489
+ if (!d1Id) throw new UserError("Could not find the D1 database after creating it.");
490
+ const cfg = writeDeployFiles(name, d1Id);
491
+ step("Applying schema");
492
+ await wrangler(["d1", "execute", name, "--remote", "--yes", "--file", join3(deployDir(), "schema.sql"), "--config", cfg]);
493
+ step(`Deploying Worker "${name}"`);
494
+ const out = await wrangler(["deploy", "--config", cfg], { capture: true });
495
+ process.stderr.write(out);
496
+ const url = (opts.url ?? /https:\/\/[a-z0-9.-]+\.workers\.dev/.exec(out)?.[0])?.replace(/\/$/, "");
497
+ if (!url) throw new UserError("Deployed, but no workers.dev URL was printed. Re-run with --url https://\u2026");
498
+ step("Setting encryption key and admin token");
499
+ const existing = parseJson(
500
+ await wrangler(["secret", "list", "--config", cfg, "--format", "json"], { capture: true })
501
+ );
502
+ if (existing.some((s) => s.name === "KEYBOX_KEK")) {
503
+ note("This Worker already has an encryption key; keeping it.");
504
+ } else {
505
+ await wrangler(["secret", "put", "KEYBOX_KEK", "--config", cfg], { input: randomBytes(32).toString("base64") });
506
+ }
507
+ const adminToken = "kb_adm_" + randomBytes(32).toString("base64url");
508
+ const hash = createHash("sha256").update(adminToken).digest("hex");
509
+ await wrangler(["secret", "put", "KEYBOX_ADMIN_TOKEN_HASH", "--config", cfg], { input: hash });
510
+ saveConfig({ url, adminToken, name, d1Id });
511
+ step("Waiting for the new version to go live");
512
+ if (!await waitConfigured(url)) note("Not answering as configured yet; give it a minute, then run `keybox status`.");
513
+ process.stderr.write(`
514
+ Keybox is running at ${url}
515
+ The encryption key exists only inside the Worker. Your admin token is in ${configPath()} (mode 600).
516
+
517
+ Next:
518
+ keybox secrets add OPENAI_API_KEY
519
+ keybox agents create my-agent --allow "POST api.openai.com/v1/**"
520
+ keybox run my-agent -- python agent.py
521
+ `);
522
+ }
523
+ async function deploy(opts) {
524
+ const c = requireConfig();
525
+ if (!c.d1Id) throw new UserError("`keybox deploy` needs the config written by `keybox init`.");
526
+ const dir = deployDir();
527
+ const current = existsSync2(join3(dir, "worker", "worker.js")) ? sha(join3(dir, "worker", "worker.js")) : null;
528
+ const next = sha(asset("worker.js"));
529
+ if (current === next && !opts.force) {
530
+ note("The deployed Worker already matches this CLI version.");
531
+ return;
532
+ }
533
+ process.stderr.write(`
534
+ This replaces the Worker that holds your keys.
535
+ deployed ${current ?? "(unknown)"}
536
+ new ${next}
537
+ The new code comes from this copy of @keyboxed/cli. Only continue if you trust it.
538
+ `);
539
+ if (!opts.yes && !await confirm("Deploy?")) throw new UserError("Cancelled.");
540
+ const cfg = writeDeployFiles(c.name, c.d1Id);
541
+ step("Applying schema");
542
+ await wrangler(["d1", "execute", c.name, "--remote", "--yes", "--file", join3(dir, "schema.sql"), "--config", cfg]);
543
+ step("Deploying");
544
+ await wrangler(["deploy", "--config", cfg]);
545
+ note("Done.");
546
+ }
547
+ async function status() {
548
+ const c = requireConfig();
549
+ const health = await (await fetch(`${c.url}/_keybox/health`)).json();
550
+ const [secrets, agents] = await Promise.all([api("GET", "/secrets"), api("GET", "/agents")]);
551
+ process.stdout.write(
552
+ `url ${c.url}
553
+ version ${health.version}
554
+ configured ${health.configured}
555
+ secrets ${secrets.length}
556
+ agents ${agents.length}
557
+ `
558
+ );
559
+ }
560
+
561
+ // src/index.ts
562
+ var HELP = `keybox: give AI agents access to your APIs without giving them your keys.
563
+
564
+ Setup
565
+ keybox init [--name keybox] [--url URL] Deploy Keybox to your Cloudflare account
566
+ keybox deploy [--yes] Upgrade the deployed Worker to this CLI's version
567
+ keybox status
568
+
569
+ Secrets (values are read from stdin or a hidden prompt, never from arguments)
570
+ keybox secrets add NAME [--preset openai|anthropic|github|stripe|cloudflare]
571
+ [--host HOST ... --header NAME --format bearer|raw|basic]
572
+ keybox secrets import FILE [--dry-run] [--yes] Move provider keys from a .env file (values never printed)
573
+ keybox secrets list
574
+ keybox secrets rm NAME
575
+
576
+ Agents
577
+ keybox agents create NAME --allow "GET api.github.com/repos/**" [--allow \u2026] [--deny \u2026]
578
+ keybox agents list
579
+ keybox agents rm NAME
580
+ keybox agents token NAME [--ttl 30d] Long-lived token for a deployed agent
581
+ keybox tokens revoke ID
582
+
583
+ Running
584
+ keybox run AGENT [--ttl 12h] [--clean-env] -- command [args]
585
+ keybox audit [--follow] [--limit 50]
586
+ keybox blocked Calls Keybox never proxies
587
+ `;
588
+ async function main(argv) {
589
+ const dash = argv.indexOf("--");
590
+ const args = dash === -1 ? argv : argv.slice(0, dash);
591
+ const rest = dash === -1 ? [] : argv.slice(dash + 1);
592
+ const { values: o, positionals: p } = parseArgs({
593
+ args,
594
+ allowPositionals: true,
595
+ options: {
596
+ name: { type: "string", default: "keybox" },
597
+ url: { type: "string" },
598
+ yes: { type: "boolean", short: "y", default: false },
599
+ "dry-run": { type: "boolean", default: false },
600
+ force: { type: "boolean", default: false },
601
+ preset: { type: "string" },
602
+ host: { type: "string", multiple: true },
603
+ header: { type: "string" },
604
+ format: { type: "string" },
605
+ allow: { type: "string", multiple: true },
606
+ deny: { type: "string", multiple: true },
607
+ ttl: { type: "string" },
608
+ "clean-env": { type: "boolean", default: false },
609
+ follow: { type: "boolean", short: "f", default: false },
610
+ limit: { type: "string", default: "50" },
611
+ help: { type: "boolean", short: "h", default: false }
612
+ }
613
+ });
614
+ const [group, sub, arg] = p;
615
+ const need = (v, what) => {
616
+ if (!v) throw new UserError(`Missing ${what}. See keybox --help.`);
617
+ return v;
618
+ };
619
+ if (o.help || !group) return void process.stdout.write(HELP);
620
+ switch (`${group} ${["secrets", "agents", "tokens"].includes(group) ? sub ?? "" : ""}`.trim()) {
621
+ case "init":
622
+ return init({ name: o.name, url: o.url });
623
+ case "deploy":
624
+ return deploy({ yes: o.yes, force: o.force });
625
+ case "status":
626
+ return status();
627
+ case "secrets add":
628
+ return secretsAdd(need(arg, "secret name"), { preset: o.preset, host: o.host, header: o.header, format: o.format });
629
+ case "secrets import":
630
+ return secretsImport(need(arg, "file"), { dryRun: o["dry-run"], yes: o.yes });
631
+ case "secrets list":
632
+ return secretsList();
633
+ case "secrets rm":
634
+ return secretsRm(need(arg, "secret name"));
635
+ case "agents create":
636
+ return agentsCreate(need(arg, "agent name"), { allow: o.allow, deny: o.deny });
637
+ case "agents list":
638
+ return agentsList();
639
+ case "agents rm":
640
+ return agentsRm(need(arg, "agent name"));
641
+ case "agents token":
642
+ return agentsToken(need(arg, "agent name"), { ttl: o.ttl ?? "30d" });
643
+ case "tokens revoke":
644
+ return tokensRevoke(need(arg, "token id"));
645
+ case "run":
646
+ return run(need(sub, "agent name"), rest, { ttl: o.ttl ?? "12h", cleanEnv: o["clean-env"] });
647
+ case "audit":
648
+ return audit({ follow: o.follow, limit: o.limit });
649
+ case "blocked":
650
+ return blocked();
651
+ default:
652
+ throw new UserError(`Unknown command: ${p.join(" ")}. See keybox --help.`);
653
+ }
654
+ }
655
+ main(process.argv.slice(2)).catch((err) => {
656
+ if (err instanceof UserError || err instanceof Error && err.name === "TypeError" && "code" in err) {
657
+ process.stderr.write(`keybox: ${err.message}
658
+ `);
659
+ } else {
660
+ process.stderr.write(`keybox: unexpected error
661
+ ${err instanceof Error ? err.stack : String(err)}
662
+ `);
663
+ }
664
+ process.exitCode = 1;
665
+ });