@keyboxed/cli 0.1.1 → 0.2.0

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 CHANGED
@@ -1,11 +1,18 @@
1
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";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res, err) => function __init() {
5
+ if (err) throw err[0];
6
+ try {
7
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ } catch (e) {
9
+ throw err = [e], e;
10
+ }
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
9
16
 
10
17
  // src/config.ts
11
18
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
@@ -14,28 +21,40 @@ import { join } from "node:path";
14
21
  function configDir() {
15
22
  return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "keybox");
16
23
  }
17
- var configPath = () => join(configDir(), "config.json");
18
- var deployDir = () => join(configDir(), "deploy");
19
24
  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: "" };
25
+ const env2 = process.env;
26
+ if (env2.KEYBOX_URL && env2.KEYBOX_ADMIN_TOKEN) {
27
+ return {
28
+ url: env2.KEYBOX_URL,
29
+ adminToken: env2.KEYBOX_ADMIN_TOKEN,
30
+ name: env2.KEYBOX_NAME ?? "keybox",
31
+ d1Id: "",
32
+ accountId: env2.KEYBOX_ACCOUNT_ID ?? env2.CLOUDFLARE_ACCOUNT_ID
33
+ };
23
34
  }
24
35
  if (!existsSync(configPath())) return null;
25
36
  return JSON.parse(readFileSync(configPath(), "utf8"));
26
37
  }
27
38
  function requireConfig() {
28
- const c = loadConfig();
29
- if (!c) throw new UserError("Not set up yet. Run `keybox init` first.");
30
- return c;
39
+ const c2 = loadConfig();
40
+ if (!c2) throw new UserError("Not set up yet. Run `keybox init` first.");
41
+ return c2;
31
42
  }
32
- function saveConfig(c) {
43
+ function saveConfig(c2) {
33
44
  mkdirSync(configDir(), { recursive: true, mode: 448 });
34
- writeFileSync(configPath(), JSON.stringify(c, null, 2) + "\n", { mode: 384 });
45
+ writeFileSync(configPath(), JSON.stringify(c2, null, 2) + "\n", { mode: 384 });
35
46
  chmodSync(configPath(), 384);
36
47
  }
37
- var UserError = class extends Error {
38
- };
48
+ var configPath, deployDir, UserError;
49
+ var init_config = __esm({
50
+ "src/config.ts"() {
51
+ "use strict";
52
+ configPath = () => join(configDir(), "config.json");
53
+ deployDir = () => join(configDir(), "deploy");
54
+ UserError = class extends Error {
55
+ };
56
+ }
57
+ });
39
58
 
40
59
  // src/api.ts
41
60
  async function api(method, path, body, config = requireConfig()) {
@@ -53,144 +72,549 @@ async function api(method, path, body, config = requireConfig()) {
53
72
  if (!res.ok) throw new UserError(data?.error?.message ?? `Keybox returned HTTP ${res.status}.`);
54
73
  return data;
55
74
  }
75
+ var init_api = __esm({
76
+ "src/api.ts"() {
77
+ "use strict";
78
+ init_config();
79
+ }
80
+ });
56
81
 
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;
82
+ // ../shared/grants.ts
83
+ function buildGrants(allow, deny, secrets) {
84
+ const grants = /* @__PURE__ */ new Map();
85
+ const hostOf = (rule) => /^\S+\s+([^/\s]+)/.exec(rule)?.[1] ?? "";
86
+ const resolve = (raw) => {
87
+ const named = /^([A-Z][A-Z0-9_]*)=(.+)$/.exec(raw);
88
+ if (named) return [named[1], named[2].trim()];
89
+ const host = hostOf(raw);
90
+ const bound = secrets.filter((s) => s.hosts.includes(host));
91
+ if (bound.length === 1) return [bound[0].name, raw];
92
+ if (bound.length === 0) throw new Error(`No stored secret is bound to ${host || "that host"} (rule "${raw}").`);
93
+ throw new Error(`Several secrets are bound to ${host}; prefix the rule: "${bound[0].name}=${raw}".`);
94
+ };
95
+ for (const raw of allow) {
96
+ const [secret, rule] = resolve(raw);
97
+ const g = grants.get(secret) ?? { secret, allow: [] };
98
+ g.allow.push(rule);
99
+ grants.set(secret, g);
100
+ }
101
+ for (const raw of deny) {
102
+ const named = /^([A-Z][A-Z0-9_]*)=(.+)$/.exec(raw);
103
+ const targets = named ? [grants.get(named[1])] : [...grants.values()].filter((g) => {
104
+ const host = hostOf(raw);
105
+ return host.includes("*") || secrets.find((s) => s.name === g.secret)?.hosts.includes(host);
106
+ });
107
+ const rule = named ? named[2].trim() : raw;
108
+ if (!targets.length || targets.some((t) => !t)) throw new Error(`Deny rule "${raw}" does not apply to any allowed secret.`);
109
+ for (const g of targets) (g.deny ??= []).push(rule);
110
+ }
111
+ return [...grants.values()];
112
+ }
113
+ var init_grants = __esm({
114
+ "../shared/grants.ts"() {
115
+ }
116
+ });
117
+
118
+ // ../shared/providers.ts
119
+ function byName(name) {
120
+ const n = name.toUpperCase();
121
+ return PROVIDERS.find((p) => p.prefixes.some((pre) => n.startsWith(pre)));
122
+ }
123
+ function byValue(value) {
124
+ return PROVIDERS.find((p) => p.pattern && new RegExp(p.pattern).test(value));
125
+ }
126
+ function detect(name, value) {
127
+ const v = byValue(value);
128
+ const n = name ? byName(name) : void 0;
129
+ const provider = v ?? n;
130
+ const out2 = provider ? { provider, via: v ? "value" : "name" } : {};
131
+ if (v && n && v.id !== n.id) out2.mismatch = n;
132
+ if (provider?.admin && new RegExp(provider.admin).test(value)) out2.adminHint = provider.adminHint;
133
+ return out2;
134
+ }
135
+ function toSecretName(label2) {
136
+ let n = label2.toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, "");
137
+ if (!/^[A-Z]/.test(n)) n = "KEY_" + n;
138
+ return n.slice(0, 64) || "KEY";
139
+ }
140
+ var PROVIDERS, UNSUPPORTED, CREDENTIAL_NAME, PUBLIC_NAME, byId;
141
+ var init_providers = __esm({
142
+ "../shared/providers.ts"() {
143
+ PROVIDERS = [
144
+ { id: "openrouter", label: "OpenRouter", hosts: ["openrouter.ai"], header: "authorization", format: "bearer", prefixes: ["OPENROUTER_"], pattern: "^sk-or-" },
145
+ {
146
+ id: "anthropic",
147
+ label: "Anthropic",
148
+ hosts: ["api.anthropic.com"],
149
+ header: "x-api-key",
150
+ format: "raw",
151
+ prefixes: ["ANTHROPIC_", "CLAUDE_"],
152
+ pattern: "^sk-ant-",
153
+ admin: "^sk-ant-admin",
154
+ adminHint: "This is an Admin API key. Use a workspace API key for agents.",
155
+ env: { ANTHROPIC_BASE_URL: "{base}/api.anthropic.com", ANTHROPIC_API_KEY: "{token}" }
156
+ },
157
+ {
158
+ id: "openai",
159
+ label: "OpenAI",
160
+ hosts: ["api.openai.com"],
161
+ header: "authorization",
162
+ format: "bearer",
163
+ prefixes: ["OPENAI_"],
164
+ pattern: "^sk-(proj-|svcacct-|None-)?[A-Za-z0-9_-]{16,}",
165
+ admin: "^sk-admin-",
166
+ adminHint: "This is an organisation admin key. Use a project key for agents.",
167
+ env: { OPENAI_BASE_URL: "{base}/api.openai.com/v1", OPENAI_API_KEY: "{token}" }
168
+ },
169
+ {
170
+ id: "github",
171
+ label: "GitHub",
172
+ hosts: ["api.github.com"],
173
+ header: "authorization",
174
+ format: "bearer",
175
+ prefixes: ["GITHUB_", "GH_"],
176
+ pattern: "^(ghp_|github_pat_|gho_|ghu_|ghs_)",
177
+ admin: "^ghp_",
178
+ adminHint: "Classic tokens reach every repo you can. Prefer a fine-grained token (github_pat_)."
179
+ },
180
+ {
181
+ id: "stripe",
182
+ label: "Stripe",
183
+ hosts: ["api.stripe.com"],
184
+ header: "authorization",
185
+ format: "bearer",
186
+ prefixes: ["STRIPE_"],
187
+ pattern: "^(sk|rk)_(live|test)_",
188
+ admin: "^sk_live_",
189
+ adminHint: "This is a full live secret key. Prefer a restricted key (rk_live_)."
190
+ },
191
+ { id: "cloudflare", label: "Cloudflare", hosts: ["api.cloudflare.com"], header: "authorization", format: "bearer", prefixes: ["CLOUDFLARE_", "CF_"] },
192
+ { id: "gemini", label: "Google Gemini", hosts: ["generativelanguage.googleapis.com"], header: "x-goog-api-key", format: "raw", prefixes: ["GEMINI_", "GOOGLE_AI_", "GOOGLE_GENERATIVE_AI_", "GOOGLE_API_"], pattern: "^AIza[0-9A-Za-z_-]{35}$" },
193
+ { id: "groq", label: "Groq", hosts: ["api.groq.com"], header: "authorization", format: "bearer", prefixes: ["GROQ_"], pattern: "^gsk_" },
194
+ { id: "mistral", label: "Mistral", hosts: ["api.mistral.ai"], header: "authorization", format: "bearer", prefixes: ["MISTRAL_"] },
195
+ { id: "xai", label: "xAI", hosts: ["api.x.ai"], header: "authorization", format: "bearer", prefixes: ["XAI_", "GROK_"], pattern: "^xai-" },
196
+ { id: "deepseek", label: "DeepSeek", hosts: ["api.deepseek.com"], header: "authorization", format: "bearer", prefixes: ["DEEPSEEK_"] },
197
+ { id: "perplexity", label: "Perplexity", hosts: ["api.perplexity.ai"], header: "authorization", format: "bearer", prefixes: ["PERPLEXITY_", "PPLX_"], pattern: "^pplx-" },
198
+ { id: "together", label: "Together", hosts: ["api.together.xyz"], header: "authorization", format: "bearer", prefixes: ["TOGETHER_"] },
199
+ { id: "fireworks", label: "Fireworks", hosts: ["api.fireworks.ai"], header: "authorization", format: "bearer", prefixes: ["FIREWORKS_"], pattern: "^fw_" },
200
+ { id: "cohere", label: "Cohere", hosts: ["api.cohere.com"], header: "authorization", format: "bearer", prefixes: ["COHERE_", "CO_API_"] },
201
+ { id: "huggingface", label: "Hugging Face", hosts: ["huggingface.co", "router.huggingface.co", "api-inference.huggingface.co"], header: "authorization", format: "bearer", prefixes: ["HF_", "HUGGINGFACE_", "HUGGING_FACE_"], pattern: "^hf_" },
202
+ { id: "replicate", label: "Replicate", hosts: ["api.replicate.com"], header: "authorization", format: "bearer", prefixes: ["REPLICATE_"], pattern: "^r8_" },
203
+ { id: "voyage", label: "Voyage AI", hosts: ["api.voyageai.com"], header: "authorization", format: "bearer", prefixes: ["VOYAGE_"] },
204
+ { id: "elevenlabs", label: "ElevenLabs", hosts: ["api.elevenlabs.io"], header: "xi-api-key", format: "raw", prefixes: ["ELEVENLABS_", "ELEVEN_", "XI_"] },
205
+ { id: "pinecone", label: "Pinecone", hosts: ["api.pinecone.io"], header: "api-key", format: "raw", prefixes: ["PINECONE_"], pattern: "^pcsk_" },
206
+ { id: "tavily", label: "Tavily", hosts: ["api.tavily.com"], header: "authorization", format: "bearer", prefixes: ["TAVILY_"], pattern: "^tvly-" },
207
+ { id: "exa", label: "Exa", hosts: ["api.exa.ai"], header: "x-api-key", format: "raw", prefixes: ["EXA_"] },
208
+ { id: "firecrawl", label: "Firecrawl", hosts: ["api.firecrawl.dev"], header: "authorization", format: "bearer", prefixes: ["FIRECRAWL_"], pattern: "^fc-" },
209
+ { id: "brave", label: "Brave Search", hosts: ["api.search.brave.com"], header: "x-subscription-token", format: "raw", prefixes: ["BRAVE_"] },
210
+ { id: "resend", label: "Resend", hosts: ["api.resend.com"], header: "authorization", format: "bearer", prefixes: ["RESEND_"], pattern: "^re_" },
211
+ { id: "sendgrid", label: "SendGrid", hosts: ["api.sendgrid.com"], header: "authorization", format: "bearer", prefixes: ["SENDGRID_"], pattern: "^SG\\." },
212
+ { id: "postmark", label: "Postmark", hosts: ["api.postmarkapp.com"], header: "x-postmark-server-token", format: "raw", prefixes: ["POSTMARK_"] },
213
+ { id: "slack", label: "Slack", hosts: ["slack.com"], header: "authorization", format: "bearer", prefixes: ["SLACK_"], pattern: "^xox[bpae]-" },
214
+ { id: "linear", label: "Linear", hosts: ["api.linear.app"], header: "authorization", format: "raw", prefixes: ["LINEAR_"], pattern: "^lin_api_" },
215
+ { id: "notion", label: "Notion", hosts: ["api.notion.com"], header: "authorization", format: "bearer", prefixes: ["NOTION_"], pattern: "^(ntn_|secret_)" },
216
+ { id: "vercel", label: "Vercel", hosts: ["api.vercel.com"], header: "authorization", format: "bearer", prefixes: ["VERCEL_"] },
217
+ { id: "netlify", label: "Netlify", hosts: ["api.netlify.com"], header: "authorization", format: "bearer", prefixes: ["NETLIFY_"] },
218
+ { id: "digitalocean", label: "DigitalOcean", hosts: ["api.digitalocean.com"], header: "authorization", format: "bearer", prefixes: ["DIGITALOCEAN_", "DO_"], pattern: "^dop_v1_" },
219
+ { id: "sentry", label: "Sentry", hosts: ["sentry.io"], header: "authorization", format: "bearer", prefixes: ["SENTRY_"], pattern: "^sntry[us]_" }
220
+ ];
221
+ UNSUPPORTED = [
222
+ { match: /^AWS_(SECRET_ACCESS_KEY|ACCESS_KEY_ID|SESSION_TOKEN)$/, why: "AWS signs each request (SigV4); a header cannot carry it" },
223
+ { match: /^(DATABASE_URL|POSTGRES_|MYSQL_|REDIS_URL|MONGO)/, why: "database connection strings are not HTTP APIs" },
224
+ { match: /(PRIVATE_KEY|_PEM|SSH_KEY|SIGNING_KEY|JWT_SECRET|SESSION_SECRET|ENCRYPTION_KEY|NEXTAUTH_SECRET|AUTH_SECRET)$/, why: "used by your own code, not sent to an API" },
225
+ { match: /^(TWILIO_|DEEPGRAM_)/, why: "needs an auth scheme Keybox does not support yet" }
226
+ ];
227
+ CREDENTIAL_NAME = /(KEY|TOKEN|SECRET|PAT)$/;
228
+ PUBLIC_NAME = /(PUBLISHABLE|PUBLIC|ANON_KEY|SITE_KEY|_ID$)/;
229
+ byId = (id) => PROVIDERS.find((p) => p.id === id);
230
+ }
231
+ });
232
+
233
+ // src/dove.ts
234
+ var DOVE_LARGE, DOVE_SMALL;
235
+ var init_dove = __esm({
236
+ "src/dove.ts"() {
237
+ "use strict";
238
+ DOVE_LARGE = [
239
+ "\u2820\u28C4\u2858\u28B6\u28C4\u2840\u28A0\u2840",
240
+ "\u2830\u28CC\u28FB\u28F2\u28F3\u289F\u28E6\u28BD\u28D6\u28C4",
241
+ "\u2830\u28EC\u2873\u28FD\u28DE\u28DF\u28BE\u289D\u286E\u28DE\u28B5\u28C2",
242
+ "\u2800\u28A8\u28DD\u28D7\u28B7\u28BD\u28DD\u28F5\u286B\u286E\u28D3\u288E\u2897\u28A4\u2800\u28C0",
243
+ "\u2800\u2800\u28A8\u287A\u286F\u2877\u28F3\u28A7\u28AF\u28AF\u28AE\u2873\u28F1\u28B1\u288D\u289E\u28A6",
244
+ "\u2800\u2800\u2800\u2829\u287F\u28DD\u28D7\u28AF\u28EB\u2897\u28D7\u28BD\u2878\u28F8\u28B8\u28B8\u28B8\u28B8\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28C0\u2864\u28DE\u2804",
245
+ "\u2800\u2800\u2800\u2800\u2808\u289F\u28EE\u289F\u286E\u28EF\u28FA\u28B5\u28EB\u28AA\u286A\u286A\u286A\u286A\u2873\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28E0\u28E6\u287E\u28EF\u28EF\u286F\u2816",
246
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u282B\u28DF\u287E\u28D5\u28B7\u289D\u286E\u28E3\u2873\u2879\u2878\u2878\u2878\u2878\u2872\u28C4\u2800\u2800\u2800\u28A0\u28DE\u2857\u286E\u2883\u2800\u2800\u2800\u2800\u28C0\u28F4\u28FE\u28F3\u28BF\u289E\u28DF\u28FD\u28BE\u281A\u2801",
247
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u28AB\u28EF\u28BE\u289D\u28EE\u2873\u28D5\u2887\u2887\u2887\u2887\u2887\u2897\u289C\u289D\u28B7\u28FE\u28BF\u2873\u28F1\u28C1\u28C0\u28C0\u2864\u2874\u285E\u285F\u28DD\u28AE\u287A\u28EA\u28D7\u28FF\u281A\u2801",
248
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u2837\u28FB\u287C\u28FA\u286A\u28C7\u2897\u2895\u2895\u2895\u2895\u2895\u28F5\u28BF\u28DD\u2887\u288F\u28D6\u2887\u2897\u289C\u28DC\u289C\u28CE\u28D7\u2897\u28D7\u28EF\u2837\u280B",
249
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2809\u281A\u2833\u28AF\u28FA\u28EA\u28E3\u28B3\u28B1\u28F5\u28FF\u28BD\u286B\u284E\u286E\u28E3\u2897\u28B5\u2879\u28D5\u28F5\u28EB\u28DE\u287E\u287D\u2813\u2801",
250
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2841\u2851\u28E3\u28EF\u28FF\u28DF\u289E\u2855\u28C7\u28AF\u287A\u28D5\u28AF\u28F3\u28BD\u28FA\u287A\u281E\u280A\u2801",
251
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28A0\u28E4\u2896\u28D6\u28AE\u287A\u28EA\u28AB\u286A\u28EA\u2897\u28B5\u2857\u2847\u28D7\u28B5\u2833\u2819\u283A\u2819\u281D\u280E\u280B\u2808",
252
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28BE\u28FB\u28AE\u28D7\u28DD\u28AE\u286A\u287A\u28F8\u28B8\u28B8\u28B8\u28A8\u28B2\u2841",
253
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u283B\u28F3\u2897\u28D7\u2875\u28EB\u287A\u28F8\u28AA\u287A\u285C\u286E\u28FA\u287A\u28E6",
254
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u281B\u28DE\u28FD\u287A\u287C\u286E\u28F3\u28B5\u28EB\u28BE\u28B5\u28FB\u287A\u280B",
255
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u2819\u2839\u287D\u28B3\u28FB\u283A\u283D\u280B\u2803"
256
+ ];
257
+ DOVE_SMALL = [
258
+ "\u2890\u28AC\u28F2\u28C4\u2862\u2840",
259
+ "\u2828\u28DF\u28DE\u286E\u286F\u286F\u2872\u2840",
260
+ "\u2800\u2893\u287D\u287E\u28DD\u286E\u28CF\u288E\u2887\u2896\u2840",
261
+ "\u2800\u2800\u2819\u28FD\u28AE\u28AF\u287A\u28D5\u28B5\u28B1\u28B1\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28E0\u28E4\u2876\u2841",
262
+ "\u2800\u2800\u2800\u2808\u282F\u28D7\u28AF\u2873\u2875\u2871\u2871\u28D9\u2826\u28C4\u28C0\u28E4\u28BE\u2831\u2800\u2800\u28E0\u2874\u287E\u287B\u28FD\u287A\u2803",
263
+ "\u2800\u2800\u2800\u2800\u2800\u2819\u2897\u28EF\u2873\u285D\u285C\u2854\u286D\u28E2\u287F\u284E\u2867\u2873\u286A\u28DD\u28BC\u28DC\u287E\u283D\u2809",
264
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u2813\u289D\u28EE\u28FE\u28AF\u28B3\u2879\u28EA\u28F3\u28DD\u286E\u2817\u280B\u2808",
265
+ "\u2800\u2800\u2800\u2800\u2820\u28D6\u28D6\u28AE\u287A\u2878\u285D\u287A\u2871\u2815\u2803\u280B\u2803\u2803\u2801",
266
+ "\u2800\u2800\u2800\u2800\u2800\u2811\u28EF\u2897\u2875\u28E3\u2873\u28F1\u2895\u286F\u28C2",
267
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u281B\u289E\u28AE\u2837\u282F\u281B\u2809"
268
+ ];
269
+ }
270
+ });
271
+
272
+ // src/ui.ts
273
+ function step(s) {
274
+ process.stderr.write(`${c.accent("\u25A0")} ${s}
275
+ `);
276
+ }
277
+ function note(s) {
278
+ process.stderr.write(`${c.dim(" " + s)}
279
+ `);
280
+ }
281
+ function ok(s) {
282
+ process.stderr.write(`${c.ok("\u2713")} ${s}
283
+ `);
284
+ }
285
+ function warn(s) {
286
+ process.stderr.write(`${c.warn("!")} ${s}
287
+ `);
288
+ }
289
+ function table(rows) {
290
+ if (rows.length === 0) return "";
291
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => width(r[i] ?? ""))));
292
+ return rows.map((r) => r.map((cell, i) => i === r.length - 1 ? cell : pad(cell, widths[i])).join(" ")).join("\n") + "\n";
293
+ }
294
+ function headed(rows) {
295
+ if (!rows.length) return "";
296
+ const tty = process.stdout.isTTY && color;
297
+ return table(tty ? [rows[0].map(label), ...rows.slice(1)] : rows);
298
+ }
299
+ function when(ms) {
300
+ return new Date(ms).toISOString().replace("T", " ").slice(0, 19);
301
+ }
302
+ function ago(ms) {
303
+ if (!ms) return "never";
304
+ const s = Math.round((Date.now() - ms) / 1e3);
305
+ if (s < 60) return `${s}s ago`;
306
+ if (s < 3600) return `${Math.round(s / 60)}m ago`;
307
+ if (s < 86400) return `${Math.round(s / 3600)}h ago`;
308
+ return `${Math.round(s / 86400)}d ago`;
309
+ }
310
+ function parseDuration(s) {
311
+ const m = /^(\d+)([smhd]?)$/.exec(s.trim());
312
+ if (!m) throw new Error(`bad duration: ${s}`);
313
+ return Number(m[1]) * { "": 1, s: 1, m: 60, h: 3600, d: 86400 }[m[2]];
314
+ }
315
+ function banner(lines = [], size = "large") {
316
+ if (!color) return lines.length ? lines.join("\n") + "\n" : "";
317
+ const cols = process.stderr.columns ?? 80;
318
+ const dove = size === "large" && cols >= 92 ? DOVE_LARGE : DOVE_SMALL;
319
+ const dw = Math.max(...dove.map((l) => [...l].length));
320
+ if (cols < dw + 20) return lines.join("\n") + "\n";
321
+ const squares = /* @__PURE__ */ new Map([
322
+ [1, [dw + 4, "\u25A0"]],
323
+ [Math.floor(dove.length * 0.7), [dw - 6, "\u25AA"]],
324
+ [dove.length - 2, [dw + 9, "\u25AB"]]
325
+ ]);
326
+ const top = Math.max(0, Math.floor((dove.length - lines.length) / 2));
327
+ const out2 = [];
328
+ for (let i = 0; i < dove.length; i++) {
329
+ const d = dove[i];
330
+ let row = " " + d + " ".repeat(dw - [...d].length);
331
+ const text = lines[i - top];
332
+ const sq = squares.get(i);
333
+ if (text !== void 0) row += " " + text;
334
+ else if (sq) row = row.slice(0, 2 + sq[0]) + " ".repeat(Math.max(0, 2 + sq[0] - width(row))) + c.accent(sq[1]);
335
+ out2.push(row);
336
+ }
337
+ return "\n" + out2.join("\n") + "\n\n";
338
+ }
339
+ function spin(text) {
340
+ if (!color) {
341
+ process.stderr.write(`${text}
342
+ `);
343
+ return (final) => final && process.stderr.write(final + "\n");
344
+ }
345
+ const frames = "\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F";
346
+ let i = 0;
347
+ const draw = () => process.stderr.write(`\r\x1B[2K${c.accent(frames[i++ % frames.length])} ${text}`);
348
+ draw();
349
+ const t = setInterval(draw, 80);
350
+ return (final) => {
351
+ clearInterval(t);
352
+ process.stderr.write(`\r\x1B[2K${final ? final + "\n" : ""}`);
353
+ };
98
354
  }
355
+ async function task(label2, fn, done) {
356
+ const name = label2.padEnd(16);
357
+ const stop = color ? spin(name) : (final) => final && process.stderr.write(final + "\n");
358
+ try {
359
+ const r = await fn();
360
+ stop(`${c.ok("\u2713")} ${name}${c.dim(done ? done(r) : "")}`);
361
+ return r;
362
+ } catch (err) {
363
+ stop(`${c.bad("\u2717")} ${name}`);
364
+ const tail = err.stderr;
365
+ if (tail) {
366
+ const lines = tail.replace(/\x1b\[[0-9;]*m/g, "").split("\n").map((l) => l.trimEnd()).filter((l) => l.trim() && !/^[─┌└│├┐┘]/.test(l));
367
+ for (const l of lines.slice(-8)) process.stderr.write(c.dim(` ${l}
368
+ `));
369
+ }
370
+ throw err;
371
+ }
372
+ }
373
+ var env, color, truecolor, sgr, rgb, c, width, pad, label, wordmark;
374
+ var init_ui = __esm({
375
+ "src/ui.ts"() {
376
+ "use strict";
377
+ init_dove();
378
+ env = process.env;
379
+ color = Boolean(process.stderr.isTTY) && !env.NO_COLOR && env.TERM !== "dumb";
380
+ truecolor = color && /truecolor|24bit/i.test(env.COLORTERM ?? "");
381
+ sgr = (open, close = "\x1B[0m") => (s) => color ? `\x1B[${open}m${s}${close}` : s;
382
+ rgb = (r, g, b, fallback) => sgr(truecolor ? `38;2;${r};${g};${b}` : fallback, "\x1B[39m");
383
+ c = {
384
+ // Cobalt that reads on both light and dark terminals.
385
+ accent: rgb(96, 124, 240, "38;5;69"),
386
+ ok: rgb(111, 194, 141, "32"),
387
+ bad: rgb(232, 120, 100, "31"),
388
+ warn: rgb(222, 170, 90, "33"),
389
+ dim: sgr("2", "\x1B[22m"),
390
+ bold: sgr("1", "\x1B[22m"),
391
+ italic: sgr("3", "\x1B[23m")
392
+ };
393
+ width = (s) => s.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "").length;
394
+ pad = (s, n) => s + " ".repeat(Math.max(0, n - width(s)));
395
+ label = (s) => c.dim(s.toUpperCase());
396
+ wordmark = () => `${c.accent("\u25A0")} ${c.bold("keybox")}`;
397
+ }
398
+ });
99
399
 
100
400
  // src/prompt.ts
401
+ var prompt_exports = {};
402
+ __export(prompt_exports, {
403
+ ask: () => ask,
404
+ choose: () => choose,
405
+ confirm: () => confirm,
406
+ readSecret: () => readSecret,
407
+ width: () => width
408
+ });
101
409
  import { createInterface } from "node:readline/promises";
102
- async function readSecret(label) {
410
+ async function readSecret(labelText, name = "") {
103
411
  const stdin = process.stdin;
104
412
  if (!stdin.isTTY) {
105
413
  let data = "";
106
414
  for await (const chunk of stdin) data += chunk;
107
415
  return data.replace(/\r?\n$/, "");
108
416
  }
109
- process.stderr.write(`${label}: `);
417
+ const out2 = process.stderr;
418
+ let value = "";
419
+ let flash = [];
420
+ let timer;
421
+ const hint = () => {
422
+ const v = value.trim();
423
+ if (!v) return c.dim("paste or type \xB7 enter to save \xB7 esc to cancel");
424
+ const bits = [c.dim(`${v.length} chars`)];
425
+ if (/\s/.test(v)) bits.push(c.warn("has spaces"));
426
+ const d = detect(name, v);
427
+ if (d.provider) bits.push(d.via === "value" ? c.ok(`\u2713 ${d.provider.label}`) : c.dim(`${d.provider.label}?`));
428
+ if (d.mismatch) bits.push(c.warn(`name says ${d.mismatch.label}`));
429
+ if (d.adminHint) bits.push(c.warn("admin-grade key"));
430
+ return bits.join(c.dim(" \xB7 "));
431
+ };
432
+ const draw = () => {
433
+ const n = value.length;
434
+ const shown = Math.min(n, MAX_DOTS);
435
+ let dots = "";
436
+ for (let i = 0; i < shown; i++) {
437
+ const pos = n - shown + i;
438
+ dots += flash.includes(pos) ? c.accent(GLYPHS[(pos * 7 + Date.now()) % GLYPHS.length]) : "\u2022";
439
+ }
440
+ if (n > MAX_DOTS) dots = c.dim("\u2026") + dots.slice(0);
441
+ const line = `${c.accent("\u25A0")} ${labelText} ${c.dim("\u2595")}${dots}${c.dim("\u258F")} ${hint()}`;
442
+ out2.write(`\r\x1B[2K${line}`);
443
+ };
444
+ const settle = () => {
445
+ clearTimeout(timer);
446
+ timer = setTimeout(() => {
447
+ flash = [];
448
+ draw();
449
+ }, 140);
450
+ };
451
+ if (!color) out2.write(`${labelText} (hidden): `);
452
+ else {
453
+ out2.write("\x1B[?2004h\x1B[?25l");
454
+ draw();
455
+ }
110
456
  stdin.setRawMode(true);
111
457
  stdin.resume();
112
458
  stdin.setEncoding("utf8");
113
459
  return new Promise((resolve, reject) => {
114
- let value = "";
460
+ let pasting = false;
115
461
  const done = (err) => {
462
+ clearTimeout(timer);
116
463
  stdin.setRawMode(false);
117
464
  stdin.pause();
118
465
  stdin.off("data", onData);
119
- process.stderr.write("\n");
120
- err ? reject(err) : resolve(value);
466
+ if (color) {
467
+ out2.write("\x1B[?2004l\x1B[?25h");
468
+ flash = [];
469
+ if (!err) {
470
+ const v = value.trim();
471
+ const d = detect(name, v);
472
+ out2.write(`\r\x1B[2K${c.accent("\u25A0")} ${labelText} ${c.dim(`${v.length} chars`)}${d.provider ? c.dim(" \xB7 ") + d.provider.label : ""}
473
+ `);
474
+ } else out2.write(`\r\x1B[2K${c.dim(`${labelText}: cancelled`)}
475
+ `);
476
+ } else out2.write("\n");
477
+ err ? reject(err) : resolve(value.replace(/^\s+|\s+$/g, ""));
121
478
  };
122
- const onData = (s) => {
123
- for (const ch of s) {
479
+ const add = (s) => {
480
+ const start = value.length;
481
+ value += s;
482
+ for (let i = Math.max(start, value.length - 12); i < value.length; i++) flash.push(i);
483
+ settle();
484
+ };
485
+ const onData = (chunk) => {
486
+ let s = chunk;
487
+ while (s.length) {
488
+ if (s.startsWith("\x1B[200~")) {
489
+ pasting = true;
490
+ s = s.slice(6);
491
+ continue;
492
+ }
493
+ if (s.startsWith("\x1B[201~")) {
494
+ pasting = false;
495
+ s = s.slice(6);
496
+ continue;
497
+ }
498
+ if (pasting) {
499
+ const end = s.indexOf("\x1B[201~");
500
+ const part = end === -1 ? s : s.slice(0, end);
501
+ add(part.replace(/[\r\n]+$/g, "").replace(/[\r\n]/g, ""));
502
+ s = end === -1 ? "" : s.slice(end);
503
+ continue;
504
+ }
505
+ const ch = s[0];
506
+ if (ch === "\x1B") {
507
+ const seq = /^\x1b(\[[0-9;?]*[A-Za-z~]|O[A-Za-z])/.exec(s);
508
+ if (seq) {
509
+ s = s.slice(seq[0].length);
510
+ continue;
511
+ }
512
+ return done(new UserError("Cancelled."));
513
+ }
514
+ s = s.slice(1);
124
515
  if (ch === "\r" || ch === "\n") return done();
125
516
  if (ch === "") return done(new UserError("Cancelled."));
126
- if (ch === "\x7F" || ch === "\b") value = value.slice(0, -1);
127
- else value += ch;
517
+ if (ch === "") value = "";
518
+ else if (ch === "\x7F" || ch === "\b") value = value.slice(0, -1);
519
+ else if (ch >= " ") add(ch);
128
520
  }
521
+ if (color) draw();
129
522
  };
130
523
  stdin.on("data", onData);
131
524
  });
132
525
  }
133
- async function confirm(question) {
526
+ async function confirm(question, def = false) {
134
527
  if (!process.stdin.isTTY) return false;
135
528
  const rl = createInterface({ input: process.stdin, output: process.stderr });
136
- const answer = await rl.question(`${question} [y/N] `);
529
+ const answer = (await rl.question(`${c.accent("?")} ${question} ${c.dim(def ? "[Y/n]" : "[y/N]")} `)).trim();
137
530
  rl.close();
138
- return /^y(es)?$/i.test(answer.trim());
531
+ return answer ? /^y(es)?$/i.test(answer) : def;
139
532
  }
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
- `);
533
+ async function ask(question, def = "") {
534
+ if (!process.stdin.isTTY) return def;
535
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
536
+ const answer = (await rl.question(`${c.accent("?")} ${question}${def ? c.dim(` (${def})`) : ""} `)).trim();
537
+ rl.close();
538
+ return answer || def;
148
539
  }
149
- function note(s) {
150
- process.stderr.write(`${dim(" " + s)}
540
+ async function choose(question, options, def = 0) {
541
+ if (!process.stdin.isTTY || !color) return options[def].value;
542
+ const out2 = process.stderr;
543
+ let i = def;
544
+ const draw = (first = false) => {
545
+ if (!first) out2.write(`\x1B[${options.length}A`);
546
+ for (let k = 0; k < options.length; k++) {
547
+ const o = options[k];
548
+ const sel = k === i;
549
+ out2.write(`\r\x1B[2K ${sel ? c.accent("\u25A0") : c.dim("\u25A1")} ${sel ? o.label : c.dim(o.label)}${o.hint ? " " + c.dim(o.hint) : ""}
151
550
  `);
551
+ }
552
+ };
553
+ out2.write(`${c.accent("?")} ${question}
554
+ \x1B[?25l`);
555
+ draw(true);
556
+ process.stdin.setRawMode(true);
557
+ process.stdin.resume();
558
+ process.stdin.setEncoding("utf8");
559
+ return new Promise((resolve, reject) => {
560
+ const finish = (err) => {
561
+ process.stdin.setRawMode(false);
562
+ process.stdin.pause();
563
+ process.stdin.off("data", on);
564
+ out2.write(`\x1B[${options.length}A\x1B[J\x1B[?25h`);
565
+ if (err) return reject(err);
566
+ out2.write(` ${c.accent("\u25A0")} ${options[i].label}
567
+ `);
568
+ resolve(options[i].value);
569
+ };
570
+ const on = (s) => {
571
+ if (s === "" || s === "\x1B") return finish(new UserError("Cancelled."));
572
+ if (s === "\r" || s === "\n") return finish();
573
+ if (s === "\x1B[A" || s === "k") i = (i - 1 + options.length) % options.length;
574
+ if (s === "\x1B[B" || s === "j") i = (i + 1) % options.length;
575
+ const n = Number(s);
576
+ if (n >= 1 && n <= options.length) i = n - 1;
577
+ draw();
578
+ };
579
+ process.stdin.on("data", on);
580
+ });
152
581
  }
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
- }
582
+ var GLYPHS, MAX_DOTS;
583
+ var init_prompt = __esm({
584
+ "src/prompt.ts"() {
585
+ "use strict";
586
+ init_providers();
587
+ init_config();
588
+ init_ui();
589
+ GLYPHS = "\u2591\u2592\u2593\u2588#%&@$";
590
+ MAX_DOTS = 32;
591
+ }
592
+ });
166
593
 
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;
594
+ // src/migrate.ts
595
+ import { spawn, spawnSync } from "node:child_process";
596
+ import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2 } from "node:fs";
597
+ function has(bin2) {
598
+ return spawnSync(process.platform === "win32" ? "where" : "which", [bin2], { stdio: "ignore" }).status === 0;
173
599
  }
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
- `);
600
+ function capture(bin2, args) {
601
+ if (!has(bin2)) throw new UserError(`${bin2} is not installed or not on PATH.`);
602
+ return new Promise((resolve, reject) => {
603
+ const child = spawn(bin2, args, { stdio: ["inherit", "pipe", "inherit"] });
604
+ const chunks = [];
605
+ child.stdout.on("data", (d) => chunks.push(d));
606
+ child.on("error", (e) => reject(new UserError(`Could not run ${bin2}: ${e.message}`)));
607
+ child.on("close", (code) => {
608
+ if (code === 0) resolve(Buffer.concat(chunks).toString("utf8"));
609
+ else reject(new UserError(`${bin2} ${args[0] ?? ""} failed (exit ${code}). Check you are signed in to ${bin2}.`));
610
+ });
611
+ });
612
+ }
613
+ function fromObject(o, origin) {
614
+ return Object.entries(o).filter(([, v]) => typeof v === "string").map(([name, v]) => ({ name, value: v, origin: `${origin}/${name}` }));
191
615
  }
192
616
  function parseDotenv(text) {
193
- const out = [];
617
+ const out2 = [];
194
618
  for (const line of text.split(/\r?\n/)) {
195
619
  const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
196
620
  if (!m) continue;
@@ -198,118 +622,550 @@ function parseDotenv(text) {
198
622
  const q = v[0];
199
623
  if ((q === '"' || q === "'") && v.lastIndexOf(q) > 0) v = v.slice(1, v.lastIndexOf(q));
200
624
  else v = v.replace(/\s+#.*$/, "");
201
- out.push([m[1], v]);
625
+ out2.push([m[1], v]);
202
626
  }
203
- return out;
627
+ return out2;
204
628
  }
205
- var SECRET_NAME = /(KEY|TOKEN|SECRET|PAT)$/;
206
- var NOT_SECRET = /(PUBLISHABLE|PUBLIC)/;
207
- async function secretsImport(file, opts) {
208
- let text;
629
+ function pickField(fields) {
630
+ const named = fields.find((f) => /^(credential|api[ _-]?key|token|secret|password|key)$/i.test(f.label ?? f.name ?? f.id ?? "") && f.value);
631
+ return (named ?? fields.find((f) => (f.type === "CONCEALED" || f.type === 1) && f.value))?.value;
632
+ }
633
+ async function readRef(ref) {
634
+ const m = /^([a-z0-9-]+):\/\/(.+)$/.exec(ref);
635
+ if (!m) throw new UserError(`Not a reference: ${ref}. Try op://vault/item/field, vault://path#field, env://NAME \u2026`);
636
+ const [, scheme, rest] = m;
637
+ const [path, field] = rest.split("#");
638
+ const trim = (s) => s.replace(/\r?\n$/, "");
639
+ switch (scheme) {
640
+ case "op":
641
+ return trim(await capture("op", ["read", ref]));
642
+ case "bw":
643
+ return trim(await capture("bw", ["get", "password", path]));
644
+ case "bws":
645
+ return json(await capture("bws", ["secret", "get", path, "--output", "json"])).value;
646
+ case "doppler": {
647
+ const [project, config, name] = path.split("/");
648
+ return trim(await capture("doppler", ["secrets", "get", name, "--plain", "--project", project, "--config", config]));
649
+ }
650
+ case "infisical": {
651
+ const [env2, name] = path.split("/");
652
+ return trim(await capture("infisical", ["secrets", "get", name, "--env", env2, "--plain"]));
653
+ }
654
+ case "vault":
655
+ if (!field) throw new UserError("vault:// needs a #field, e.g. vault://secret/myapp#OPENAI_API_KEY");
656
+ return trim(await capture("vault", ["kv", "get", `-field=${field}`, path]));
657
+ case "aws-sm": {
658
+ const s = trim(await capture("aws", ["secretsmanager", "get-secret-value", "--secret-id", path, "--query", "SecretString", "--output", "text"]));
659
+ return field ? String(json(s)[field] ?? "") : s;
660
+ }
661
+ case "gcp-sm": {
662
+ const [project, secret, version = "latest"] = path.split("/");
663
+ return trim(await capture("gcloud", ["secrets", "versions", "access", version, `--secret=${secret}`, "--project", project]));
664
+ }
665
+ case "pass":
666
+ return (await capture("pass", ["show", path])).split("\n")[0];
667
+ case "keychain":
668
+ return trim(await capture("security", ["find-generic-password", "-s", path, "-w"]));
669
+ case "sops":
670
+ if (!field) throw new UserError("sops:// needs a #KEY, e.g. sops://secrets/app.env#OPENAI_API_KEY");
671
+ return trim(await capture("sops", ["-d", "--extract", `["${field}"]`, path]));
672
+ case "env": {
673
+ const v = process.env[path];
674
+ if (!v) throw new UserError(`${path} is not set in this shell.`);
675
+ return v;
676
+ }
677
+ case "file":
678
+ return trim(readFileSync2(path, "utf8"));
679
+ default:
680
+ throw new UserError(`Unknown reference scheme ${scheme}://`);
681
+ }
682
+ }
683
+ function classify(found, existing, opts = {}) {
684
+ const plans = [];
685
+ const skipped = [];
686
+ const unknown = [];
687
+ const seen = /* @__PURE__ */ new Set();
688
+ for (const f of found) {
689
+ if (opts.only?.length && !opts.only.includes(f.name)) continue;
690
+ if (seen.has(f.name)) continue;
691
+ seen.add(f.name);
692
+ const unsupported = UNSUPPORTED.find((u) => u.match.test(f.name));
693
+ const d = detect(f.name, f.value);
694
+ const looksLikeKey = f.explicit || CREDENTIAL_NAME.test(f.name) || d.via === "value";
695
+ if (!looksLikeKey || PUBLIC_NAME.test(f.name)) {
696
+ if (d.provider || unsupported) skipped.push({ name: f.name, why: "not a credential" });
697
+ continue;
698
+ }
699
+ if (unsupported) {
700
+ skipped.push({ name: f.name, why: unsupported.why });
701
+ continue;
702
+ }
703
+ if (f.value.trim().length < 8 || /^(x+|changeme|todo|your[-_].*|<.*>|\.\.\.)$/i.test(f.value.trim())) {
704
+ skipped.push({ name: f.name, why: "empty or placeholder" });
705
+ continue;
706
+ }
707
+ if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(f.name)) {
708
+ skipped.push({ name: f.name, why: "name must be UPPER_SNAKE_CASE" });
709
+ continue;
710
+ }
711
+ if (!d.provider) {
712
+ unknown.push(f);
713
+ continue;
714
+ }
715
+ const flags = [];
716
+ if (d.adminHint) flags.push("admin-grade");
717
+ if (d.mismatch) flags.push(`name says ${d.mismatch.label}`);
718
+ if (d.via === "name") flags.push("guessed from name");
719
+ plans.push({ ...f, provider: d.provider, hosts: d.provider.hosts, header: d.provider.header, format: d.provider.format, flags, replaces: existing.has(f.name) });
720
+ }
721
+ return { plans, skipped, unknown };
722
+ }
723
+ function dotenvFiles() {
209
724
  try {
210
- text = readFileSync2(file, "utf8");
725
+ return readdirSync(".").filter((f) => /^\.env(\..+)?$/.test(f) && !/\.(example|sample|template)$/.test(f));
211
726
  } catch {
212
- throw new UserError(`Cannot read ${file}.`);
727
+ return [];
213
728
  }
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"]);
729
+ }
730
+ async function pickSource() {
731
+ const options = [];
732
+ for (const f of dotenvFiles()) options.push({ value: `dotenv:${f}`, label: `${f}`, hint: "file in this folder" });
733
+ for (const s of SOURCES) if (s.bin && has(s.bin)) options.push({ value: s.id, label: s.label, hint: `${s.bin} found` });
734
+ options.push({ value: "env", label: "Current shell environment", hint: "variables ending in _KEY, _TOKEN\u2026" });
735
+ options.push({ value: "manual", label: "Type or paste keys one by one" });
736
+ if (!process.stdin.isTTY) throw new UserError(`Say where to migrate from: --from ${SOURCES.map((s) => s.id).join("|")}`);
737
+ return choose("Where are your keys now?", options);
738
+ }
739
+ async function migrate(opts) {
740
+ const from = opts.from ?? await pickSource();
741
+ if (from === "manual") {
742
+ note("Run `keybox secrets add NAME` for each key. It reads the value without echoing it.");
743
+ return;
744
+ }
745
+ const [id, ...rest] = from.split(":");
746
+ const arg = rest.join(":") || void 0;
747
+ if (NOT_READABLE[id]) throw new UserError(NOT_READABLE[id]);
748
+ const source = SOURCES.find((s) => s.id === id) ?? (existsSync2(from) ? SOURCES[0] : void 0);
749
+ if (!source) throw new UserError(`Unknown source ${id}. Sources: ${SOURCES.map((s) => s.id).join(", ")}.`);
750
+ const fileArg = source === SOURCES[0] && !arg ? from : arg;
751
+ const stop = spin(`Reading from ${source.label}`);
752
+ let found;
753
+ let existing;
754
+ try {
755
+ [found, existing] = await Promise.all([
756
+ source.fetch(fileArg, opts),
757
+ api("GET", "/secrets").then((r) => new Set(r.map((x) => x.name)))
758
+ ]);
759
+ } catch (err) {
760
+ stop();
761
+ throw err;
762
+ }
763
+ stop(`${c.accent("\u25A0")} Read ${found.length} entr${found.length === 1 ? "y" : "ies"} from ${source.label} ${c.dim("(names only below; values are never shown)")}`);
764
+ const { plans, skipped, unknown } = classify(found, existing, { only: opts.only });
765
+ for (const f of unknown) {
766
+ if (!process.stdin.isTTY || opts.yes || opts.dryRun) {
767
+ skipped.push({ name: f.name, why: "no preset; add it with --host" });
768
+ continue;
769
+ }
770
+ const pick = await choose(`Where may ${c.bold(f.name)} be sent?`, [
771
+ { value: "_skip", label: "Skip it" },
772
+ { value: "_custom", label: "A host I will type" },
773
+ ...PROVIDERS.map((p) => ({ value: p.id, label: p.label, hint: p.hosts[0] }))
774
+ ]);
775
+ if (pick === "_skip") {
776
+ skipped.push({ name: f.name, why: "skipped by you" });
221
777
  continue;
222
778
  }
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 });
779
+ if (pick === "_custom") {
780
+ const host = await ask("Hostname (e.g. api.example.com):");
781
+ const header = await ask("Header:", "authorization");
782
+ const format = await choose("Format:", [
783
+ { value: "bearer", label: "bearer", hint: "Authorization: Bearer <key>" },
784
+ { value: "raw", label: "raw", hint: "<header>: <key>" },
785
+ { value: "basic", label: "basic", hint: "user:pass, base64" }
786
+ ]);
787
+ plans.push({ ...f, hosts: [host.toLowerCase()], header, format, flags: ["custom host"], replaces: existing.has(f.name) });
788
+ } else {
789
+ const p = byId(pick);
790
+ plans.push({ ...f, provider: p, hosts: p.hosts, header: p.header, format: p.format, flags: ["chosen by you"], replaces: existing.has(f.name) });
791
+ }
226
792
  }
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}
793
+ if (plans.length) {
794
+ process.stdout.write(
795
+ headed([
796
+ ["NAME", "PROVIDER", "ONLY SENT TO", ""],
797
+ ...plans.map((p) => [
798
+ p.name,
799
+ p.provider?.label ?? "Custom",
800
+ p.hosts.join(","),
801
+ [p.replaces ? "replaces existing" : "new", ...p.flags].join(", ")
802
+ ])
803
+ ])
804
+ );
805
+ }
806
+ for (const s of skipped) process.stderr.write(`${c.dim(`skipped ${s.name}: ${s.why}`)}
230
807
  `);
231
- if (!rows.length) return note(`Nothing to import from ${file}.`);
808
+ for (const p of plans.filter((p2) => p2.flags.includes("admin-grade"))) {
809
+ warn(`${p.name} is an admin-grade key. ${p.provider?.adminHint ?? ""} Keybox blocks key-minting calls either way.`);
810
+ }
811
+ if (!plans.length) return note(`Nothing to migrate from ${source.label}.`);
232
812
  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?`)) {
813
+ if (!opts.yes && !await confirm(`Store ${plans.length} key${plans.length === 1 ? "" : "s"} in Keybox?`, true)) {
234
814
  throw new UserError("Cancelled. Re-run with --yes to skip the prompt.");
235
815
  }
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
- );
816
+ let stored = 0;
817
+ for (const p of plans) {
818
+ try {
819
+ const r = await api("PUT", `/secrets/${p.name}`, { hosts: p.hosts, header: p.header, format: p.format, value: p.value });
820
+ ok(`${p.name} ${c.dim(`\u2192 ${p.hosts.join(", ")}${r.fingerprint ? ` \xB7 fp ${r.fingerprint}` : ""}`)}`);
821
+ stored++;
822
+ } catch (err) {
823
+ warn(`${p.name}: ${err.message}`);
824
+ }
825
+ p.value = "";
826
+ }
827
+ found.forEach((f) => f.value = "");
828
+ process.stderr.write("\n");
829
+ step(`Stored ${stored}.`);
830
+ if (opts.quietNext) return;
831
+ if (source.id === "dotenv" || source.id === "env") {
832
+ note(`${fileArg ?? "Your shell"} still holds the original values. Once Keybox works, delete them there and rotate`);
833
+ note("each key at its provider: a key that sat in plaintext may have been copied elsewhere.");
834
+ } else {
835
+ note(`${source.label} still holds the originals. That is fine; Keybox is now what your agents use.`);
836
+ }
837
+ note('Next: keybox agents create NAME --allow "METHOD host/path" then keybox run NAME -- your command');
838
+ }
839
+ var json, SOURCES, NOT_READABLE;
840
+ var init_migrate = __esm({
841
+ "src/migrate.ts"() {
842
+ "use strict";
843
+ init_api();
844
+ init_config();
845
+ init_providers();
846
+ init_prompt();
847
+ init_ui();
848
+ json = (s) => {
849
+ try {
850
+ return JSON.parse(s);
851
+ } catch {
852
+ throw new UserError("The tool returned something that is not JSON.");
853
+ }
854
+ };
855
+ SOURCES = [
856
+ {
857
+ id: "dotenv",
858
+ label: ".env file",
859
+ usage: "keybox migrate --from dotenv:.env",
860
+ async fetch(file) {
861
+ if (!file) throw new UserError("Say which file: --from dotenv:path/to/.env");
862
+ let text;
863
+ try {
864
+ text = readFileSync2(file, "utf8");
865
+ } catch {
866
+ throw new UserError(`Cannot read ${file}.`);
867
+ }
868
+ return parseDotenv(text).map(([name, value]) => ({ name, value, origin: `${file}` }));
869
+ }
870
+ },
871
+ {
872
+ id: "env",
873
+ label: "Current shell environment",
874
+ usage: "keybox migrate --from env",
875
+ async fetch() {
876
+ return Object.entries(process.env).filter(([k, v]) => v && CREDENTIAL_NAME.test(k) && !k.startsWith("KEYBOX_")).map(([name, value]) => ({ name, value, origin: "environment" }));
877
+ }
878
+ },
879
+ {
880
+ id: "1password",
881
+ label: "1Password",
882
+ bin: "op",
883
+ usage: "keybox migrate --from 1password [--vault Private]",
884
+ async fetch(_arg, o) {
885
+ const args = ["item", "list", "--categories", "API Credential,Password", "--format", "json"];
886
+ if (o.vault) args.push("--vault", o.vault);
887
+ const items = json(await capture("op", args));
888
+ const out2 = [];
889
+ for (const it of items) {
890
+ const full = json(
891
+ await capture("op", ["item", "get", it.id, "--format", "json", "--reveal"])
892
+ );
893
+ const value = pickField(full.fields ?? []);
894
+ if (value) out2.push({ name: toSecretName(it.title), value, origin: `1password:${it.vault?.name ?? "?"}/${it.title}`, explicit: true });
895
+ }
896
+ return out2;
897
+ }
898
+ },
899
+ {
900
+ id: "bitwarden",
901
+ label: "Bitwarden (password manager)",
902
+ bin: "bw",
903
+ usage: "keybox migrate --from bitwarden [--item search-term] (needs BW_SESSION from `bw unlock`)",
904
+ async fetch(_arg, o) {
905
+ const args = ["list", "items"];
906
+ if (o.item?.[0]) args.push("--search", o.item[0]);
907
+ const items = json(
908
+ await capture("bw", args)
909
+ );
910
+ return items.map((it) => ({ name: toSecretName(it.name), value: pickField(it.fields ?? []) ?? it.login?.password ?? "", origin: `bitwarden:${it.name}`, explicit: true })).filter((f) => f.value);
911
+ }
912
+ },
913
+ {
914
+ id: "bws",
915
+ label: "Bitwarden Secrets Manager",
916
+ bin: "bws",
917
+ usage: "keybox migrate --from bws [--project PROJECT_ID] (needs BWS_ACCESS_TOKEN)",
918
+ async fetch(_arg, o) {
919
+ const args = ["secret", "list", ...o.project ? [o.project] : [], "--output", "json"];
920
+ return json(await capture("bws", args)).map((s) => ({ name: s.key, value: s.value, origin: `bws:${s.key}` }));
921
+ }
922
+ },
923
+ {
924
+ id: "doppler",
925
+ label: "Doppler",
926
+ bin: "doppler",
927
+ usage: "keybox migrate --from doppler [--project P --config dev]",
928
+ async fetch(_arg, o) {
929
+ const args = ["secrets", "download", "--no-file", "--format", "json"];
930
+ if (o.project) args.push("--project", o.project);
931
+ if (o.config) args.push("--config", o.config);
932
+ return fromObject(json(await capture("doppler", args)), "doppler").filter((f) => !f.name.startsWith("DOPPLER_"));
933
+ }
934
+ },
935
+ {
936
+ id: "infisical",
937
+ label: "Infisical",
938
+ bin: "infisical",
939
+ usage: "keybox migrate --from infisical [--env dev --path /]",
940
+ async fetch(_arg, o) {
941
+ const args = ["export", "--format", "json"];
942
+ if (o.env) args.push("--env", o.env);
943
+ if (o.path) args.push("--path", o.path);
944
+ if (o.project) args.push("--projectId", o.project);
945
+ return json(await capture("infisical", args)).map((s) => ({ name: s.key, value: s.value, origin: `infisical:${s.key}` }));
946
+ }
947
+ },
948
+ {
949
+ id: "vault",
950
+ label: "HashiCorp Vault (KV)",
951
+ bin: "vault",
952
+ usage: "keybox migrate --from vault:secret/myapp",
953
+ async fetch(path) {
954
+ if (!path) throw new UserError("Say which KV path: --from vault:secret/myapp");
955
+ const r = json(await capture("vault", ["kv", "get", "-format=json", path]));
956
+ return fromObject(r.data?.data ?? r.data ?? {}, `vault:${path}`);
957
+ }
958
+ },
959
+ {
960
+ id: "sops",
961
+ label: "sops-encrypted file",
962
+ bin: "sops",
963
+ usage: "keybox migrate --from sops:secrets/app.env",
964
+ async fetch(file) {
965
+ if (!file) throw new UserError("Say which file: --from sops:secrets/app.env");
966
+ const out2 = await capture("sops", ["-d", "--output-type", "json", file]);
967
+ return fromObject(json(out2), `sops:${file}`);
968
+ }
969
+ },
970
+ {
971
+ id: "aws",
972
+ label: "AWS Secrets Manager",
973
+ bin: "aws",
974
+ usage: "keybox migrate --from aws:prod/myapp",
975
+ async fetch(id) {
976
+ if (!id) throw new UserError("Say which secret: --from aws:prod/myapp");
977
+ const s = (await capture("aws", ["secretsmanager", "get-secret-value", "--secret-id", id, "--query", "SecretString", "--output", "text"])).replace(/\n$/, "");
978
+ try {
979
+ const o = JSON.parse(s);
980
+ if (o && typeof o === "object") return fromObject(o, `aws:${id}`);
981
+ } catch {
982
+ }
983
+ return [{ name: toSecretName(id.split("/").at(-1)), value: s, origin: `aws:${id}`, explicit: true }];
984
+ }
985
+ },
986
+ {
987
+ id: "gcp",
988
+ label: "Google Secret Manager",
989
+ bin: "gcloud",
990
+ usage: "keybox migrate --from gcp [--project my-project]",
991
+ async fetch(_arg, o) {
992
+ const p = o.project ? ["--project", o.project] : [];
993
+ const list = json(await capture("gcloud", ["secrets", "list", "--format=json", ...p]));
994
+ const out2 = [];
995
+ for (const s of list) {
996
+ const id = s.name.split("/").at(-1);
997
+ const value = (await capture("gcloud", ["secrets", "versions", "access", "latest", `--secret=${id}`, ...p])).replace(/\n$/, "");
998
+ out2.push({ name: toSecretName(id), value, origin: `gcp:${id}` });
999
+ }
1000
+ return out2;
1001
+ }
1002
+ },
1003
+ {
1004
+ id: "pass",
1005
+ label: "pass (password-store)",
1006
+ bin: "pass",
1007
+ usage: "keybox migrate --from pass --item api/openai --item api/github",
1008
+ async fetch(_arg, o) {
1009
+ if (!o.item?.length) throw new UserError("Name the entries: --item api/openai [--item \u2026]");
1010
+ const out2 = [];
1011
+ for (const p of o.item) out2.push({ name: toSecretName(p.split("/").at(-1)), value: (await capture("pass", ["show", p])).split("\n")[0], origin: `pass:${p}`, explicit: true });
1012
+ return out2;
1013
+ }
1014
+ },
1015
+ {
1016
+ id: "keychain",
1017
+ label: "macOS Keychain",
1018
+ bin: "security",
1019
+ usage: 'keybox migrate --from keychain --item "OpenAI API"',
1020
+ async fetch(_arg, o) {
1021
+ if (!o.item?.length) throw new UserError('Name the Keychain items (service names): --item "OpenAI API"');
1022
+ const out2 = [];
1023
+ for (const s of o.item) out2.push({ name: toSecretName(s), value: (await capture("security", ["find-generic-password", "-s", s, "-w"])).replace(/\n$/, ""), origin: `keychain:${s}`, explicit: true });
1024
+ return out2;
1025
+ }
1026
+ }
1027
+ ];
1028
+ NOT_READABLE = {
1029
+ github: "GitHub Actions secrets cannot be read back by anyone, by design. Copy each from where you created it, or rotate and add the new value with `keybox secrets add`.",
1030
+ vercel: "Use `vercel env pull` into a temporary file, run `keybox migrate --from dotenv:<file>`, then delete the file. Or add each with `keybox secrets add`.",
1031
+ netlify: "Run `netlify env:list --plain` piped into `keybox secrets add NAME` one at a time, or use the dashboard.",
1032
+ lastpass: "Use `lpass show --password ITEM | keybox secrets add NAME` for each key.",
1033
+ keepass: "Export is a plaintext file. Prefer `keepassxc-cli show -sa password DB ENTRY | keybox secrets add NAME` per key."
1034
+ };
1035
+ }
1036
+ });
1037
+
1038
+ // src/presets.ts
1039
+ function isKeyVar(name) {
1040
+ return EXTRA_KEY_VARS.includes(name) || CREDENTIAL_NAME.test(name) && byName(name) !== void 0;
1041
+ }
1042
+ function envFor(hosts, base, token2) {
1043
+ const out2 = { KEYBOX_URL: base, KEYBOX_TOKEN: token2 };
1044
+ for (const p of PROVIDERS) {
1045
+ if (!p.env || !p.hosts.some((h) => hosts.includes(h))) continue;
1046
+ for (const [k, v] of Object.entries(p.env)) out2[k] = v.replace("{base}", base).replace("{token}", token2);
1047
+ }
1048
+ return out2;
1049
+ }
1050
+ var PRESETS, EXTRA_KEY_VARS;
1051
+ var init_presets = __esm({
1052
+ "src/presets.ts"() {
1053
+ "use strict";
1054
+ init_providers();
1055
+ PRESETS = Object.fromEntries(PROVIDERS.map((p) => [p.id, p]));
1056
+ EXTRA_KEY_VARS = [
1057
+ "AWS_ACCESS_KEY_ID",
1058
+ "AWS_SECRET_ACCESS_KEY",
1059
+ "AWS_SESSION_TOKEN",
1060
+ "GOOGLE_API_KEY",
1061
+ "KEYBOX_ADMIN_TOKEN"
1062
+ ];
1063
+ }
1064
+ });
1065
+
1066
+ // src/commands.ts
1067
+ var commands_exports = {};
1068
+ __export(commands_exports, {
1069
+ agentsCreate: () => agentsCreate,
1070
+ agentsList: () => agentsList,
1071
+ agentsRm: () => agentsRm,
1072
+ agentsToken: () => agentsToken,
1073
+ audit: () => audit,
1074
+ blocked: () => blocked,
1075
+ buildGrants: () => buildGrants2,
1076
+ run: () => run,
1077
+ secretsAdd: () => secretsAdd,
1078
+ secretsImport: () => secretsImport,
1079
+ secretsList: () => secretsList,
1080
+ secretsRm: () => secretsRm,
1081
+ tokensRevoke: () => tokensRevoke
1082
+ });
1083
+ import { spawn as spawn2 } from "node:child_process";
1084
+ async function secretsAdd(name, opts) {
1085
+ if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(name)) throw new UserError("Secret names are UPPER_SNAKE_CASE, e.g. OPENAI_API_KEY.");
1086
+ let spec = null;
1087
+ if (opts.host?.length) {
1088
+ spec = { hosts: opts.host, header: opts.header ?? "authorization", format: opts.format ?? "bearer" };
1089
+ } else if (opts.preset) {
1090
+ spec = PRESETS[opts.preset] ?? null;
1091
+ if (!spec) throw new UserError(`Unknown preset ${opts.preset}. Known: ${Object.keys(PRESETS).join(", ")}.`);
1092
+ }
1093
+ const value = opts.from ? await readRef(opts.from) : await readSecret(`${name}`, name);
1094
+ if (!value) throw new UserError("No value given.");
1095
+ if (!spec) {
1096
+ const d = detect(name, value);
1097
+ if (d.mismatch) {
1098
+ const msg = `${name} looks like a ${d.mismatch.label} name, but the value looks like a ${d.provider.label} key.`;
1099
+ if (!process.stdin.isTTY || opts.from) throw new UserError(`${msg} Say which with --preset ${d.provider.id} or --preset ${d.mismatch.id}.`);
1100
+ const pick = await choose(msg + " Bind it to:", [
1101
+ { value: d.provider.id, label: d.provider.label, hint: d.provider.hosts.join(", ") },
1102
+ { value: d.mismatch.id, label: d.mismatch.label, hint: d.mismatch.hosts.join(", ") }
1103
+ ]);
1104
+ spec = byId(pick);
1105
+ } else if (d.provider) {
1106
+ spec = d.provider;
1107
+ note(`${d.via === "value" ? "Recognised" : "Guessed from the name"}: ${d.provider.label} \u2192 ${spec.hosts.join(", ")}, ${spec.header} (${spec.format}).`);
1108
+ } else {
1109
+ throw new UserError(`Say where ${name} may be sent: --preset ${Object.keys(PRESETS).slice(0, 6).join("|")}\u2026 or --host <hostname>.`);
1110
+ }
1111
+ if (d.adminHint) warn(d.adminHint);
1112
+ }
1113
+ const r = await api("PUT", `/secrets/${name}`, { hosts: spec.hosts, header: spec.header, format: spec.format, value });
1114
+ ok(`Stored ${r.name}. It will only ever be sent to ${r.hosts.join(", ")}.${r.fingerprint ? c.dim(` fp ${r.fingerprint}`) : ""}`);
1115
+ }
1116
+ async function secretsImport(file, opts) {
1117
+ return migrate({ from: `dotenv:${file}`, dryRun: opts.dryRun, yes: opts.yes });
241
1118
  }
242
1119
  async function secretsList() {
243
1120
  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)])]));
1121
+ if (!rows.length) return note("No secrets yet. Add one with `keybox secrets add NAME`, or bring them in with `keybox migrate`.");
1122
+ process.stdout.write(
1123
+ headed([
1124
+ ["NAME", "HOSTS", "HEADER", "FINGERPRINT", "LAST USED"],
1125
+ ...rows.map((s) => [s.name, s.hosts.join(","), `${s.header} (${s.format})`, s.fingerprint ?? "-", ago(s.last_used ?? null)])
1126
+ ])
1127
+ );
246
1128
  }
247
1129
  async function secretsRm(name) {
248
1130
  const r = await api("DELETE", `/secrets/${name}`);
249
- process.stderr.write(r.deleted ? `Deleted ${name}.
250
- ` : `No secret named ${name}.
251
- `);
1131
+ if (r.deleted) ok(`Deleted ${name}. Revoke it at the provider too if you are done with it.`);
1132
+ else note(`No secret named ${name}.`);
252
1133
  }
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);
1134
+ function buildGrants2(allow, deny, secrets) {
1135
+ try {
1136
+ return buildGrants(allow, deny, secrets);
1137
+ } catch (err) {
1138
+ throw new UserError(err.message);
280
1139
  }
281
- return [...grants.values()];
282
1140
  }
283
1141
  async function agentsCreate(name, opts) {
284
1142
  if (!opts.allow?.length) throw new UserError('Give at least one --allow rule, e.g. --allow "GET api.github.com/repos/**".');
285
1143
  const secrets = await api("GET", "/secrets");
286
- const grants = buildGrants(opts.allow, opts.deny ?? [], secrets);
1144
+ const grants = buildGrants2(opts.allow, opts.deny ?? [], secrets);
287
1145
  await api("PUT", `/agents/${name}`, { grants });
288
- process.stderr.write(`Agent ${name} can now:
289
- `);
1146
+ step(`Agent ${c.bold(name)} can now:`);
290
1147
  for (const g of grants) {
291
- for (const r of g.allow) process.stderr.write(` allow ${r} (with ${g.secret})
1148
+ for (const r of g.allow) process.stderr.write(` ${c.dim("allow")} ${r} ${c.dim(`(with ${g.secret})`)}
292
1149
  `);
293
- for (const r of g.deny ?? []) process.stderr.write(` deny ${r}
1150
+ for (const r of g.deny ?? []) process.stderr.write(` ${c.bad("deny ")} ${r}
294
1151
  `);
295
1152
  }
296
- process.stderr.write(`Everything else is denied. Start it with: keybox run ${name} -- <command>
297
- `);
1153
+ note(`Everything else is denied. Start it with: keybox run ${name} -- <command>`);
298
1154
  }
299
1155
  async function agentsList() {
300
1156
  const rows = await api("GET", "/agents");
301
1157
  if (!rows.length) return note("No agents yet. Create one with `keybox agents create NAME --allow RULE`.");
302
- const out = [["AGENT", "SECRET", "RULE", "TOKENS"]];
1158
+ const out2 = [["AGENT", "SECRET", "RULE", "TOKENS"]];
303
1159
  for (const a of rows) {
304
1160
  let first = true;
305
1161
  for (const g of a.grants) {
306
1162
  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) : ""]);
1163
+ out2.push([first ? a.name : "", g.secret, `${kind} ${r}`, first ? String(a.active_tokens) : ""]);
308
1164
  first = false;
309
1165
  }
310
1166
  }
311
1167
  }
312
- process.stdout.write(table(out));
1168
+ process.stdout.write(headed(out2));
313
1169
  }
314
1170
  async function agentsRm(name) {
315
1171
  await api("DELETE", `/agents/${name}`);
@@ -328,27 +1184,27 @@ async function tokensRevoke(id) {
328
1184
  ` : `No active token ${id}.
329
1185
  `);
330
1186
  }
331
- var BASE_ENV = ["PATH", "HOME", "USER", "LOGNAME", "SHELL", "TERM", "LANG", "LC_ALL", "TMPDIR", "TZ", "COLORTERM", "NO_COLOR", "FORCE_COLOR"];
332
1187
  async function run(name, cmd, opts) {
333
1188
  if (!cmd.length) throw new UserError("Nothing to run. Usage: keybox run AGENT -- command [args]");
334
- const c = requireConfig();
1189
+ const c2 = requireConfig();
335
1190
  const [agents, secrets] = await Promise.all([api("GET", "/agents"), api("GET", "/secrets")]);
336
1191
  const agent = agents.find((a) => a.name === name);
337
1192
  if (!agent) throw new UserError(`No agent named ${name}.`);
338
1193
  const hosts = secrets.filter((s) => agent.grants.some((g) => g.secret === s.name)).flatMap((s) => s.hosts);
339
1194
  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 };
1195
+ const env2 = opts.cleanEnv ? Object.fromEntries(BASE_ENV.filter((k) => process.env[k] !== void 0).map((k) => [k, process.env[k]])) : { ...process.env };
341
1196
  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];
1197
+ const stored = new Set(secrets.map((s) => s.name));
1198
+ for (const k of Object.keys(env2)) {
1199
+ if (isKeyVar(k) || stored.has(k)) {
1200
+ delete env2[k];
345
1201
  removed.push(k);
346
1202
  }
347
1203
  }
348
1204
  if (removed.length) note(`Removed ${removed.join(", ")} from ${name}'s environment.`);
349
- Object.assign(env, envFor(hosts, c.url.replace(/\/$/, ""), minted.token));
1205
+ Object.assign(env2, envFor(hosts, c2.url.replace(/\/$/, ""), minted.token));
350
1206
  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 });
1207
+ const child = spawn2(cmd[0], cmd.slice(1), { stdio: "inherit", env: env2 });
352
1208
  const ignore = () => {
353
1209
  };
354
1210
  process.on("SIGINT", ignore);
@@ -368,11 +1224,19 @@ function signalNumber(s) {
368
1224
  return { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGTERM: 15 }[s];
369
1225
  }
370
1226
  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 ?? ""];
1227
+ const tty = process.stdout.isTTY;
1228
+ const result = r.decision === "allow" ? String(r.status) : r.decision.toUpperCase();
1229
+ return [
1230
+ when(r.ts),
1231
+ r.agent ?? "-",
1232
+ tty ? r.decision === "allow" && r.status < 400 ? c.ok(result) : c.bad(result) : result,
1233
+ `${r.method} ${r.host ?? ""}${r.path ?? ""}`,
1234
+ r.secret ?? r.reason ?? ""
1235
+ ];
372
1236
  }
373
1237
  async function audit(opts) {
374
1238
  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)]));
1239
+ process.stdout.write(headed([["TIME (UTC)", "AGENT", "RESULT", "REQUEST", "SECRET / REASON"], ...rows.map(auditLine)]));
376
1240
  if (!opts.follow) return;
377
1241
  let last = rows.at(-1)?.id ?? 0;
378
1242
  for (; ; ) {
@@ -386,16 +1250,26 @@ async function audit(opts) {
386
1250
  }
387
1251
  async function blocked() {
388
1252
  const rows = await api("GET", "/blocked");
389
- process.stdout.write(table([["NEVER PROXIED", "WHY"], ...rows.map((r) => [r.rule, r.reason])]));
1253
+ process.stdout.write(headed([["NEVER PROXIED", "WHY"], ...rows.map((r) => [r.rule, r.reason])]));
390
1254
  }
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";
1255
+ var BASE_ENV;
1256
+ var init_commands = __esm({
1257
+ "src/commands.ts"() {
1258
+ "use strict";
1259
+ init_api();
1260
+ init_grants();
1261
+ init_config();
1262
+ init_providers();
1263
+ init_migrate();
1264
+ init_presets();
1265
+ init_prompt();
1266
+ init_ui();
1267
+ BASE_ENV = ["PATH", "HOME", "USER", "LOGNAME", "SHELL", "TERM", "LANG", "LC_ALL", "TMPDIR", "TZ", "COLORTERM", "NO_COLOR", "FORCE_COLOR"];
1268
+ }
1269
+ });
396
1270
 
397
1271
  // src/wrangler.ts
398
- import { spawn as spawn2 } from "node:child_process";
1272
+ import { spawn as spawn3 } from "node:child_process";
399
1273
  import { readFileSync as readFileSync3 } from "node:fs";
400
1274
  import { createRequire } from "node:module";
401
1275
  import { dirname, join as join2 } from "node:path";
@@ -404,33 +1278,282 @@ function bin() {
404
1278
  const pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
405
1279
  return join2(dirname(pkgPath), pkg.bin.wrangler);
406
1280
  }
1281
+ function useAccount(id) {
1282
+ accountId = id;
1283
+ }
407
1284
  function wrangler(args, opts = {}) {
1285
+ const quiet = opts.quiet && !verbose();
408
1286
  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" }
1287
+ const child = spawn3(process.execPath, [bin(), ...args], {
1288
+ stdio: [opts.input === void 0 ? "inherit" : "pipe", opts.capture || quiet ? "pipe" : "inherit", "pipe"],
1289
+ env: { ...process.env, WRANGLER_SEND_METRICS: "false", ...accountId ? { CLOUDFLARE_ACCOUNT_ID: accountId } : {} }
1290
+ });
1291
+ let out2 = "";
1292
+ let err = "";
1293
+ child.stdout?.on("data", (d) => out2 += d);
1294
+ child.stderr?.on("data", (d) => {
1295
+ if (!quiet) process.stderr.write(d);
1296
+ err += d;
412
1297
  });
413
- let out = "";
414
- child.stdout?.on("data", (d) => out += d);
415
1298
  if (opts.input !== void 0) child.stdin.end(opts.input);
416
1299
  child.on("error", reject);
417
1300
  child.on("close", (code) => {
418
- if (code === 0) resolve(out);
419
- else reject(new UserError(`wrangler ${args.slice(0, 2).join(" ")} failed (exit ${code}).`));
1301
+ if (code === 0) resolve(out2);
1302
+ else reject(new WranglerError(`wrangler ${args.slice(0, 2).join(" ")} failed (exit ${code}).`, err + out2));
420
1303
  });
421
1304
  });
422
1305
  }
423
- function parseJson(out) {
424
- const start = out.search(/[[{]/);
1306
+ function parseJson(out2) {
1307
+ const start = out2.search(/[[{]/);
425
1308
  if (start === -1) throw new UserError("Unexpected output from wrangler.");
426
- return JSON.parse(out.slice(start));
1309
+ return JSON.parse(out2.slice(start));
1310
+ }
1311
+ var WranglerError, accountId, currentAccount, verbose;
1312
+ var init_wrangler = __esm({
1313
+ "src/wrangler.ts"() {
1314
+ "use strict";
1315
+ init_config();
1316
+ WranglerError = class extends UserError {
1317
+ constructor(message, stderr) {
1318
+ super(message);
1319
+ this.stderr = stderr;
1320
+ }
1321
+ stderr;
1322
+ };
1323
+ currentAccount = () => accountId;
1324
+ verbose = () => process.env.KEYBOX_VERBOSE === "1";
1325
+ }
1326
+ });
1327
+
1328
+ // src/cloudflare.ts
1329
+ async function whoami() {
1330
+ try {
1331
+ const out2 = await wrangler(["whoami", "--json"], { capture: true, quiet: true });
1332
+ const w = parseJson(out2);
1333
+ if (w.loggedIn === false) return null;
1334
+ return { email: w.email, authType: w.authType, accounts: (w.accounts ?? []).map((a) => ({ id: a.id, name: a.name })) };
1335
+ } catch {
1336
+ return null;
1337
+ }
1338
+ }
1339
+ async function token() {
1340
+ if (process.env.CLOUDFLARE_API_TOKEN) return process.env.CLOUDFLARE_API_TOKEN;
1341
+ if (cached) return cached;
1342
+ const out2 = await wrangler(["auth", "token", "--json"], { capture: true, quiet: true }).catch(() => "");
1343
+ const t = out2 ? parseJson(out2).token : void 0;
1344
+ if (!t) throw new UserError("Not logged in to Cloudflare. Run: npx wrangler login");
1345
+ cached = t;
1346
+ return t;
1347
+ }
1348
+ async function cfRaw(path, account = currentAccount()) {
1349
+ if (!account) throw new UserError("No Cloudflare account selected.");
1350
+ const r = await fetch(`https://api.cloudflare.com/client/v4/accounts/${account}${path}`, {
1351
+ headers: { authorization: `Bearer ${await token()}` }
1352
+ });
1353
+ return r;
1354
+ }
1355
+ async function cf(path, account = currentAccount()) {
1356
+ const r = await cfRaw(path, account);
1357
+ const body = await r.json().catch(() => null);
1358
+ if (!r.ok || !body?.success) {
1359
+ const e = body?.errors?.[0];
1360
+ throw new CfError(r.status, e ? `${e.message} [code ${e.code}]` : `Cloudflare API returned HTTP ${r.status}`);
1361
+ }
1362
+ return body.result;
1363
+ }
1364
+ async function findWorker(name, accounts) {
1365
+ for (const a of accounts) {
1366
+ try {
1367
+ await cf(`/workers/scripts/${name}/settings`, a.id);
1368
+ return a;
1369
+ } catch {
1370
+ }
1371
+ }
1372
+ return null;
1373
+ }
1374
+ var cached, CfError;
1375
+ var init_cloudflare = __esm({
1376
+ "src/cloudflare.ts"() {
1377
+ "use strict";
1378
+ init_config();
1379
+ init_wrangler();
1380
+ cached = null;
1381
+ CfError = class extends UserError {
1382
+ constructor(status2, message) {
1383
+ super(message);
1384
+ this.status = status2;
1385
+ }
1386
+ status;
1387
+ };
1388
+ }
1389
+ });
1390
+
1391
+ // src/version.ts
1392
+ var VERSION;
1393
+ var init_version = __esm({
1394
+ "src/version.ts"() {
1395
+ "use strict";
1396
+ VERSION = true ? "0.2.0" : "0.0.0-dev";
1397
+ }
1398
+ });
1399
+
1400
+ // src/verify.ts
1401
+ var verify_exports = {};
1402
+ __export(verify_exports, {
1403
+ checks: () => checks,
1404
+ printChecks: () => printChecks,
1405
+ resolveAccount: () => resolveAccount,
1406
+ shippedWorkerHash: () => shippedWorkerHash,
1407
+ verify: () => verify
1408
+ });
1409
+ import { createHash } from "node:crypto";
1410
+ import { readFileSync as readFileSync4 } from "node:fs";
1411
+ function parts(body, contentType) {
1412
+ const boundary = /boundary="?([^";]+)"?/.exec(contentType)?.[1];
1413
+ const out2 = /* @__PURE__ */ new Map();
1414
+ if (!boundary) return out2;
1415
+ const buf = Buffer.from(body);
1416
+ const delim = Buffer.from(`--${boundary}`);
1417
+ let at = buf.indexOf(delim);
1418
+ while (at !== -1) {
1419
+ const next = buf.indexOf(delim, at + delim.length);
1420
+ if (next === -1) break;
1421
+ const part = buf.subarray(at + delim.length + 2, next - 2);
1422
+ const split = part.indexOf("\r\n\r\n");
1423
+ const head = part.subarray(0, split).toString();
1424
+ const name = /name="([^"]+)"/.exec(head)?.[1];
1425
+ if (name) out2.set(name, part.subarray(split + 4));
1426
+ at = next;
1427
+ }
1428
+ return out2;
1429
+ }
1430
+ async function resolveAccount(cfg) {
1431
+ if (cfg.accountId) {
1432
+ useAccount(cfg.accountId);
1433
+ return cfg.accountId;
1434
+ }
1435
+ const me = await whoami();
1436
+ if (!me) throw new UserError("Log in to Cloudflare first: npx wrangler login");
1437
+ const found = await findWorker(cfg.name, me.accounts);
1438
+ if (!found) throw new UserError(`No Worker named "${cfg.name}" in the Cloudflare accounts you are logged in to (${me.accounts.map((a) => a.name).join(", ")}).`);
1439
+ useAccount(found.id);
1440
+ if (cfg.d1Id) saveConfig({ ...cfg, accountId: found.id });
1441
+ return found.id;
1442
+ }
1443
+ async function checks(cfg) {
1444
+ const out2 = [];
1445
+ const name = cfg.name;
1446
+ const r = await cfRaw(`/workers/scripts/${name}/content/v2`);
1447
+ if (!r.ok) throw new UserError(`Could not read the deployed Worker "${name}" (HTTP ${r.status}).`);
1448
+ const modules = parts(new Uint8Array(await r.arrayBuffer()), r.headers.get("content-type") ?? "");
1449
+ const main2 = modules.get("worker.js");
1450
+ const want = shippedWorkerHash();
1451
+ const got = main2 ? shaHex(main2) : null;
1452
+ out2.push(
1453
+ got === want ? { ok: true, label: "Code", detail: `matches @keyboxed/cli ${VERSION} sha256 ${want.slice(0, 16)}\u2026` } : { ok: false, label: "Code", detail: `does not match this CLI
1454
+ deployed ${got ?? "(no worker.js module)"}
1455
+ expected ${want}` }
1456
+ );
1457
+ const extra = [...modules.keys()].filter((k) => k !== "worker.js");
1458
+ if (extra.length) out2.push({ ok: false, label: "Modules", detail: `unexpected extra modules: ${extra.join(", ")}` });
1459
+ const deps = await cf(`/workers/scripts/${name}/deployments`);
1460
+ const live = deps.deployments[0];
1461
+ if (!live) out2.push({ ok: false, label: "Traffic", detail: "no active deployment" });
1462
+ else if (live.versions.length === 1 && live.versions[0].percentage === 100) {
1463
+ const when2 = live.created_on.replace("T", " ").slice(0, 16);
1464
+ out2.push({ ok: true, label: "Traffic", detail: `one version serves 100% (${live.versions[0].version_id.slice(0, 8)}, ${when2} UTC${live.author_email ? `, by ${live.author_email}` : ""}${live.source ? ` via ${live.source}` : ""})` });
1465
+ } else {
1466
+ out2.push({ ok: false, label: "Traffic", detail: `split across ${live.versions.map((v) => `${v.version_id.slice(0, 8)} ${v.percentage}%`).join(", ")}; only one of them was checked` });
1467
+ }
1468
+ const s = await cf(`/workers/scripts/${name}/settings`);
1469
+ const names = s.bindings.map((b) => b.name);
1470
+ const unexpected = s.bindings.filter((b) => !EXPECTED_BINDINGS.has(b.name));
1471
+ out2.push(
1472
+ unexpected.length ? { ok: "warn", label: "Bindings", detail: `unexpected: ${unexpected.map((b) => `${b.name} (${b.type})`).join(", ")}` } : { ok: true, label: "Bindings", detail: names.join(", ") }
1473
+ );
1474
+ const tails = s.tail_consumers ?? [];
1475
+ out2.push(
1476
+ tails.length || s.logpush ? { ok: "warn", label: "Observers", detail: `${tails.length ? `tail workers: ${tails.map((t) => t.service).join(", ")}` : ""}${s.logpush ? " Logpush is on" : ""}`.trim() } : { ok: true, label: "Observers", detail: "no tail workers, no Logpush" }
1477
+ );
1478
+ try {
1479
+ const h = await (await fetch(`${cfg.url}/_keybox/health`)).json();
1480
+ out2.push(
1481
+ h.configured ? { ok: h.version === VERSION ? true : "warn", label: "Live", detail: `answering as v${h.version}${h.version === VERSION ? "" : ` (this CLI is v${VERSION})`}` } : { ok: false, label: "Live", detail: "answering, but missing its encryption key or admin token" }
1482
+ );
1483
+ } catch {
1484
+ out2.push({ ok: false, label: "Live", detail: `not reachable at ${cfg.url}` });
1485
+ }
1486
+ return out2;
427
1487
  }
1488
+ function printChecks(list) {
1489
+ for (const ch of list) {
1490
+ const mark = ch.ok === true ? c.ok("\u2713") : ch.ok === "warn" ? c.warn("!") : c.bad("\u2717");
1491
+ process.stderr.write(` ${mark} ${ch.label.padEnd(10)} ${ch.ok === true ? c.dim(ch.detail) : ch.detail}
1492
+ `);
1493
+ }
1494
+ return list.every((ch) => ch.ok !== false);
1495
+ }
1496
+ async function verify(opts) {
1497
+ const cfg = requireConfig();
1498
+ const account = await resolveAccount(cfg);
1499
+ const list = await checks(cfg);
1500
+ if (opts.json) {
1501
+ process.stdout.write(JSON.stringify({ account, worker: cfg.name, ok: list.every((c2) => c2.ok !== false), checks: list }, null, 2) + "\n");
1502
+ if (!list.every((c2) => c2.ok !== false)) process.exitCode = 1;
1503
+ return;
1504
+ }
1505
+ step(`Verifying ${c.bold(cfg.name)} in account ${account.slice(0, 8)}\u2026`);
1506
+ const good = printChecks(list);
1507
+ process.stderr.write("\n");
1508
+ if (good) {
1509
+ ok("This Keybox is running exactly the code in this CLI, and nothing else is watching its traffic.");
1510
+ note("Re-run this after anyone else touches your Cloudflare account.");
1511
+ return;
1512
+ }
1513
+ process.exitCode = 1;
1514
+ warn("This Keybox is not running the code this CLI ships.");
1515
+ note("If you just upgraded on another machine, update this CLI to the same version and verify again.");
1516
+ note("If nobody you trust deployed it, assume the stored keys are exposed: rotate them at each provider,");
1517
+ note("secure your Cloudflare account (hardware key, review members and API tokens), then run `keybox deploy`.");
1518
+ }
1519
+ var EXPECTED_BINDINGS, shaHex, shippedWorkerHash;
1520
+ var init_verify = __esm({
1521
+ "src/verify.ts"() {
1522
+ "use strict";
1523
+ init_cloudflare();
1524
+ init_config();
1525
+ init_ui();
1526
+ init_version();
1527
+ init_wrangler();
1528
+ EXPECTED_BINDINGS = /* @__PURE__ */ new Set(["DB", "KEYBOX_KEK", "KEYBOX_ADMIN_TOKEN_HASH", "KEYBOX_SCRIPT_NAME", "KEYBOX_D1_ID"]);
1529
+ shaHex = (b) => createHash("sha256").update(b).digest("hex");
1530
+ shippedWorkerHash = () => shaHex(readFileSync4(new URL("../assets/worker.js", import.meta.url)));
1531
+ }
1532
+ });
428
1533
 
429
1534
  // 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) {
1535
+ var deploy_exports = {};
1536
+ __export(deploy_exports, {
1537
+ deploy: () => deploy,
1538
+ init: () => init,
1539
+ status: () => status
1540
+ });
1541
+ import { spawn as spawn4 } from "node:child_process";
1542
+ import { createHash as createHash2, randomBytes } from "node:crypto";
1543
+ import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
1544
+ import { join as join3 } from "node:path";
1545
+ async function deployWorker(cfg) {
1546
+ for (let attempt = 1; ; attempt++) {
1547
+ try {
1548
+ return await wrangler(["deploy", "--config", cfg], { capture: true, quiet: true });
1549
+ } catch (err) {
1550
+ const racing = err instanceof WranglerError && /code: 10007|does not exist on your account/.test(err.stderr);
1551
+ if (!racing || attempt === 4) throw err;
1552
+ await new Promise((r) => setTimeout(r, attempt * 3e3));
1553
+ }
1554
+ }
1555
+ }
1556
+ function writeDeployFiles(name, d1Id, accountId2) {
434
1557
  const dir = deployDir();
435
1558
  mkdirSync2(join3(dir, "worker"), { recursive: true, mode: 448 });
436
1559
  copyFileSync(asset("worker.js"), join3(dir, "worker", "worker.js"));
@@ -441,10 +1564,12 @@ function writeDeployFiles(name, d1Id) {
441
1564
  JSON.stringify(
442
1565
  {
443
1566
  name,
1567
+ ...accountId2 ? { account_id: accountId2 } : {},
444
1568
  main: "worker/worker.js",
445
1569
  compatibility_date: COMPAT_DATE,
446
1570
  no_bundle: true,
447
1571
  workers_dev: true,
1572
+ preview_urls: false,
448
1573
  // Request logs would hold paths and headers; Keybox writes its own audit log instead.
449
1574
  observability: { enabled: false },
450
1575
  d1_databases: [{ binding: "DB", database_name: name, database_id: d1Id }],
@@ -457,134 +1582,771 @@ function writeDeployFiles(name, d1Id) {
457
1582
  return cfg;
458
1583
  }
459
1584
  async function findDb(name) {
460
- const dbs = parseJson(await wrangler(["d1", "list", "--json"], { capture: true }));
1585
+ const dbs = parseJson(await wrangler(["d1", "list", "--json"], { capture: true, quiet: true }));
461
1586
  return dbs.find((d) => d.name === name)?.uuid ?? null;
462
1587
  }
463
1588
  async function waitConfigured(url) {
464
1589
  for (let i = 0; i < 30; i++) {
465
1590
  try {
466
1591
  const r = await fetch(`${url}/_keybox/health`);
467
- if (r.ok && (await r.json()).configured) return true;
1592
+ const h = await r.json();
1593
+ if (r.ok && h.configured) return h.version;
468
1594
  } catch {
469
1595
  }
470
1596
  await new Promise((r) => setTimeout(r, 1e3));
471
1597
  }
472
- return false;
1598
+ return null;
1599
+ }
1600
+ async function pickAccount(accounts, wanted) {
1601
+ if (wanted) {
1602
+ const a = accounts.find((x) => x.id === wanted || x.name.toLowerCase() === wanted.toLowerCase());
1603
+ if (!a) throw new UserError(`You are not a member of account "${wanted}". Yours: ${accounts.map((x) => `${x.name} (${x.id})`).join(", ")}`);
1604
+ return a;
1605
+ }
1606
+ if (accounts.length === 1) return accounts[0];
1607
+ if (!accounts.length) throw new UserError("Your Cloudflare login has no accounts.");
1608
+ if (!process.stdin.isTTY) throw new UserError(`You can deploy to several accounts. Pick one with --account: ${accounts.map((a) => `${a.name} (${a.id})`).join(", ")}`);
1609
+ const id = await choose(
1610
+ "Which Cloudflare account should hold your Keybox?",
1611
+ accounts.map((a) => ({ value: a.id, label: a.name, hint: a.id }))
1612
+ );
1613
+ return accounts.find((a) => a.id === id);
473
1614
  }
474
1615
  async function init(opts) {
475
1616
  const { name } = opts;
476
1617
  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 })
1618
+ if (loadConfig()) throw new UserError(`Already set up (${configPath()}). Use \`keybox deploy\` to upgrade, or \`keybox verify\` to check it.`);
1619
+ process.stderr.write(banner([wordmark() + c.dim(` v${VERSION}`), c.dim("deploying to your own Cloudflare account"), "", c.dim("your keys never pass through keybox.space")], "small"));
1620
+ const major = Number(process.versions.node.split(".")[0]);
1621
+ if (major < 20) throw new UserError(`Keybox needs Node 20 or later (you have ${process.versions.node}).`);
1622
+ let me = await task("Cloudflare login", whoami, (w) => w ? `${w.email ?? "logged in"}${w.authType ? ` (${w.authType})` : ""}` : "not logged in");
1623
+ if (!me) {
1624
+ if (!process.stdin.isTTY) throw new UserError("Log in to Cloudflare first: npx wrangler login");
1625
+ note("Opening Cloudflare in your browser to log in\u2026");
1626
+ await wrangler(["login"]);
1627
+ me = await whoami();
1628
+ if (!me) throw new UserError("Still not logged in. Run `npx wrangler login`, then `keybox init` again.");
1629
+ }
1630
+ const account = await pickAccount(me.accounts, opts.account);
1631
+ useAccount(account.id);
1632
+ ok(`${"Account".padEnd(16)}${c.dim(`${account.name} ${account.id}`)}`);
1633
+ const sub = await cf("/workers/subdomain").catch(() => ({ subdomain: void 0 }));
1634
+ if (!sub.subdomain && !opts.url) {
1635
+ throw new UserError(
1636
+ `This account has no workers.dev subdomain yet. Pick one at https://dash.cloudflare.com/${account.id}/workers/onboarding, then run keybox init again.`
1637
+ );
1638
+ }
1639
+ const existingWorker = await cf(`/workers/scripts/${name}/settings`).then(
1640
+ () => true,
1641
+ () => false
501
1642
  );
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") });
1643
+ if (existingWorker) {
1644
+ warn(`There is already a Worker named "${name}" in this account.`);
1645
+ note("If it is a Keybox, its encryption key and stored keys are kept and you get a new admin token.");
1646
+ note("If it is something else, cancel and use --name to pick another name.");
1647
+ if (!opts.yes && !await confirm("Take it over as your Keybox?", false)) throw new UserError("Cancelled. Nothing was changed.");
1648
+ } else if (!opts.yes && process.stdin.isTTY) {
1649
+ process.stderr.write(c.dim(` This creates a Worker and a D1 database named "${name}" in ${account.name}.
1650
+ `));
1651
+ if (!await confirm("Continue?", true)) throw new UserError("Cancelled. Nothing was changed.");
506
1652
  }
1653
+ process.stderr.write("\n");
1654
+ const d1Id = await task(
1655
+ "Database",
1656
+ async () => {
1657
+ const found = await findDb(name);
1658
+ if (found) return { id: found, reused: true };
1659
+ await wrangler(["d1", "create", name], { capture: true, quiet: true });
1660
+ const id = await findDb(name);
1661
+ if (!id) throw new UserError("Could not find the D1 database after creating it.");
1662
+ return { id, reused: false };
1663
+ },
1664
+ (r) => `${r.reused ? "reusing" : "created"} ${name}`
1665
+ ).then((r) => r.id);
1666
+ const cfgPath = writeDeployFiles(name, d1Id, account.id);
1667
+ await task(
1668
+ "Schema",
1669
+ () => wrangler(["d1", "execute", name, "--remote", "--yes", "--file", join3(deployDir(), "schema.sql"), "--config", cfgPath], { capture: true, quiet: true }),
1670
+ () => "applied"
1671
+ );
1672
+ const url = await task(
1673
+ "Worker",
1674
+ async () => {
1675
+ const out2 = await deployWorker(cfgPath);
1676
+ const u = (opts.url ?? /https:\/\/[a-z0-9.-]+\.workers\.dev/.exec(out2)?.[0])?.replace(/\/$/, "");
1677
+ if (!u) throw new UserError("Deployed, but no workers.dev URL was printed. Re-run with --url https://\u2026");
1678
+ return u;
1679
+ },
1680
+ (u) => u
1681
+ );
1682
+ await task(
1683
+ "Encryption key",
1684
+ async () => {
1685
+ const secrets = parseJson(await wrangler(["secret", "list", "--config", cfgPath, "--format", "json"], { capture: true, quiet: true }));
1686
+ if (secrets.some((s) => s.name === "KEYBOX_KEK")) return "kept the existing one";
1687
+ await wrangler(["secret", "put", "KEYBOX_KEK", "--config", cfgPath], { input: randomBytes(32).toString("base64"), capture: true, quiet: true });
1688
+ return "generated and sent to Cloudflare; never written to disk";
1689
+ },
1690
+ (r) => r
1691
+ );
507
1692
  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`.");
1693
+ await task(
1694
+ "Admin token",
1695
+ async () => {
1696
+ const hash = createHash2("sha256").update(adminToken).digest("hex");
1697
+ await wrangler(["secret", "put", "KEYBOX_ADMIN_TOKEN_HASH", "--config", cfgPath], { input: hash, capture: true, quiet: true });
1698
+ saveConfig({ url, adminToken, name, d1Id, accountId: account.id });
1699
+ },
1700
+ () => `saved to ${configPath().replace(process.env.HOME ?? "~", "~")} (mode 600)`
1701
+ );
1702
+ const live = await task("Live", () => waitConfigured(url), (v) => v ? `answering as v${v}` : "not answering yet");
1703
+ if (live) await verifyStep();
1704
+ else note("Give it a minute, then run `keybox verify`.");
513
1705
  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
1706
+ ${c.accent("\u25A0")} Keybox is running at ${c.bold(url)}
521
1707
  `);
1708
+ await nextSteps();
1709
+ }
1710
+ async function verifyStep() {
1711
+ const cfg = requireConfig();
1712
+ try {
1713
+ const list = await task("Verify", () => checks(cfg), (l) => l.every((x) => x.ok === true) ? "deployed code matches this CLI" : "see below");
1714
+ if (!list.every((x) => x.ok === true)) printChecks(list);
1715
+ } catch {
1716
+ note("Could not verify yet; run `keybox verify` in a minute.");
1717
+ }
1718
+ }
1719
+ async function nextSteps() {
1720
+ const list = () => {
1721
+ process.stderr.write(`
1722
+ ${c.accent("\u25A0")} Next
1723
+ `);
1724
+ for (const [cmd, what] of LATER) process.stderr.write(` ${cmd.padEnd(38)} ${c.dim(what)}
1725
+ `);
1726
+ };
1727
+ if (!process.stdin.isTTY) return list();
1728
+ process.stderr.write("\n");
1729
+ const pick = await choose("What next?", [
1730
+ { value: "migrate", label: "Move my keys in", hint: "keybox migrate" },
1731
+ { value: "skill", label: "Set up my coding agent", hint: "keybox skill install" },
1732
+ { value: "ui", label: "Open the dashboard", hint: "keybox ui" },
1733
+ { value: "done", label: "Done for now" }
1734
+ ]);
1735
+ if (pick === "done") return list();
1736
+ const args = pick === "migrate" ? ["migrate"] : pick === "skill" ? ["skill", "install"] : ["ui"];
1737
+ await new Promise((resolve) => {
1738
+ const child = spawn4(process.execPath, [process.argv[1], ...args], { stdio: "inherit" });
1739
+ child.on("close", () => resolve());
1740
+ child.on("error", () => resolve());
1741
+ });
522
1742
  }
523
1743
  async function deploy(opts) {
524
- const c = requireConfig();
525
- if (!c.d1Id) throw new UserError("`keybox deploy` needs the config written by `keybox init`.");
1744
+ const cfg = requireConfig();
1745
+ if (!cfg.d1Id) throw new UserError("`keybox deploy` needs the config written by `keybox init`.");
1746
+ await resolveAccount(cfg);
526
1747
  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"));
1748
+ const current = existsSync3(join3(dir, "worker", "worker.js")) ? sha(join3(dir, "worker", "worker.js")) : null;
1749
+ const next = shippedWorkerHash();
529
1750
  if (current === next && !opts.force) {
530
- note("The deployed Worker already matches this CLI version.");
1751
+ ok("The deployed Worker already matches this CLI version. Run `keybox verify` to check what Cloudflare is serving.");
531
1752
  return;
532
1753
  }
533
1754
  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.
1755
+ ${c.accent("\u25A0")} This replaces the Worker that holds your keys.
1756
+ deployed ${c.dim(current ?? "(unknown)")}
1757
+ new ${next} ${c.dim(`@keyboxed/cli ${VERSION}`)}
1758
+ The new code comes from this copy of @keyboxed/cli. Only continue if you trust it.
1759
+
538
1760
  `);
539
1761
  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.");
1762
+ const fresh = requireConfig();
1763
+ const wranglerCfg = writeDeployFiles(fresh.name, fresh.d1Id, fresh.accountId);
1764
+ await task(
1765
+ "Schema",
1766
+ () => wrangler(["d1", "execute", fresh.name, "--remote", "--yes", "--file", join3(dir, "schema.sql"), "--config", wranglerCfg], { capture: true, quiet: true }),
1767
+ () => "applied"
1768
+ );
1769
+ await task("Worker", () => deployWorker(wranglerCfg), () => "deployed");
1770
+ const live = await task("Live", () => waitConfigured(fresh.url), (v) => v ? `answering as v${v}` : "not answering yet");
1771
+ if (live) await verifyStep();
546
1772
  }
547
1773
  async function status() {
548
- const c = requireConfig();
549
- const health = await (await fetch(`${c.url}/_keybox/health`)).json();
1774
+ const cfg = requireConfig();
1775
+ const health = await (await fetch(`${cfg.url}/_keybox/health`)).json();
550
1776
  const [secrets, agents] = await Promise.all([api("GET", "/secrets"), api("GET", "/agents")]);
1777
+ const row = (k, v) => `${c.dim(k.padEnd(11))} ${v}
1778
+ `;
1779
+ process.stdout.write(
1780
+ row("url", cfg.url) + row("dashboard", `${cfg.url.replace(/\/$/, "")}/_keybox/ui ${c.dim("(open with keybox ui)")}`) + (cfg.accountId ? row("account", cfg.accountId) : "") + row("worker", `v${health.version}${health.version === VERSION ? "" : c.warn(` (this CLI is v${VERSION}; run keybox update)`)}`) + row("configured", health.configured) + row("secrets", secrets.length) + row("agents", agents.length)
1781
+ );
1782
+ if (process.stdout.isTTY) step(`Run ${c.bold("keybox verify")} to check the deployed code against this CLI.`);
1783
+ }
1784
+ var COMPAT_DATE, asset, sha, LATER;
1785
+ var init_deploy = __esm({
1786
+ "src/deploy.ts"() {
1787
+ "use strict";
1788
+ init_api();
1789
+ init_cloudflare();
1790
+ init_config();
1791
+ init_prompt();
1792
+ init_ui();
1793
+ init_verify();
1794
+ init_version();
1795
+ init_wrangler();
1796
+ COMPAT_DATE = "2026-07-01";
1797
+ asset = (f) => new URL(`../assets/${f}`, import.meta.url).pathname;
1798
+ sha = (path) => createHash2("sha256").update(readFileSync5(path)).digest("hex");
1799
+ LATER = [
1800
+ ["keybox migrate", "bring keys in from .env, 1Password, Doppler, Vault\u2026"],
1801
+ ["keybox secrets add NAME", "add one key (hidden input)"],
1802
+ ['keybox agents create NAME --allow "\u2026"', "give an agent narrow access"],
1803
+ ["keybox run NAME -- your command", "run it through Keybox"],
1804
+ ["keybox skill install", "teach your coding agent to do this safely"],
1805
+ ["keybox ui", "open the dashboard"],
1806
+ ["keybox verify", "check what Cloudflare is actually running"]
1807
+ ];
1808
+ }
1809
+ });
1810
+
1811
+ // src/extra.ts
1812
+ var extra_exports = {};
1813
+ __export(extra_exports, {
1814
+ accessClear: () => accessClear,
1815
+ accessCloudflare: () => accessCloudflare,
1816
+ accessSet: () => accessSet,
1817
+ accessShow: () => accessShow,
1818
+ skill: () => skill,
1819
+ ui: () => ui
1820
+ });
1821
+ import { spawn as spawn5 } from "node:child_process";
1822
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "node:fs";
1823
+ import { homedir as homedir2 } from "node:os";
1824
+ import { dirname as dirname2, join as join4 } from "node:path";
1825
+ function openBrowser(url) {
1826
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1827
+ const args = process.platform === "win32" ? ["/c", "start", '""', url] : [url];
1828
+ try {
1829
+ const child = spawn5(cmd, args, { stdio: "ignore", detached: true });
1830
+ child.on("error", () => {
1831
+ });
1832
+ child.unref();
1833
+ return true;
1834
+ } catch {
1835
+ return false;
1836
+ }
1837
+ }
1838
+ async function ui(opts) {
1839
+ const cfg = requireConfig();
1840
+ const { code } = await api("POST", "/ui/link");
1841
+ const url = `${cfg.url.replace(/\/$/, "")}/_keybox/ui#code=${code}`;
1842
+ if (opts.print || !openBrowser(url)) {
1843
+ warn("One-time login link (valid 2 minutes, works once). Do not paste it anywhere else:");
1844
+ process.stdout.write(url + "\n");
1845
+ return;
1846
+ }
1847
+ ok(`Opened the dashboard for ${cfg.url} ${c.dim("(one-time link, valid 2 minutes)")}`);
1848
+ }
1849
+ async function accessShow() {
1850
+ const [p, me] = await Promise.all([api("GET", "/policy"), api("GET", "/whoami")]);
551
1851
  process.stdout.write(
552
- `url ${c.url}
553
- version ${health.version}
554
- configured ${health.configured}
555
- secrets ${secrets.length}
556
- agents ${agents.length}
557
- `
1852
+ headed([
1853
+ ["SCOPE", "WHO MAY CONNECT"],
1854
+ ["admin", describe(p.admin)],
1855
+ ["proxy", describe(p.proxy)],
1856
+ ...Object.entries(p.agents ?? {}).map(([n, r]) => [`agent:${n}`, describe(r)]),
1857
+ ["cloudflare access", p.access ? `${p.access.teamDomain} (aud ${p.access.aud.slice(0, 8)}\u2026)` : c.dim("off")]
1858
+ ])
558
1859
  );
1860
+ note(`You are calling from ${me.ip ?? "an unknown address"} (${me.country ?? "??"}).`);
1861
+ }
1862
+ function scopeOf(p, scope) {
1863
+ if (scope === "admin" || scope === "proxy") return { get: () => p[scope], set: (r) => r ? p[scope] = r : delete p[scope] };
1864
+ const m = /^agent:([a-z0-9][a-z0-9-]{0,63})$/.exec(scope);
1865
+ if (!m) throw new UserError("--scope is admin, proxy or agent:NAME.");
1866
+ return {
1867
+ get: () => p.agents?.[m[1]],
1868
+ set: (r) => {
1869
+ p.agents ??= {};
1870
+ if (r) p.agents[m[1]] = r;
1871
+ else delete p.agents[m[1]];
1872
+ }
1873
+ };
1874
+ }
1875
+ async function save(p, force) {
1876
+ try {
1877
+ await api("PUT", "/policy", { policy: p, force });
1878
+ } catch (err) {
1879
+ if (/would block you/.test(err.message) && !force && process.stdin.isTTY) {
1880
+ warn(err.message);
1881
+ if (await confirm("Save it anyway? You may lose access to the dashboard and CLI from here.")) return save(p, true);
1882
+ }
1883
+ throw err;
1884
+ }
1885
+ }
1886
+ async function accessSet(opts) {
1887
+ const p = await api("GET", "/policy");
1888
+ const s = scopeOf(p, opts.scope);
1889
+ const cur = opts.add ? { ...s.get() ?? {} } : {};
1890
+ const merge = (a, b) => b?.length ? [.../* @__PURE__ */ new Set([...a ?? [], ...b.flatMap((x) => x.split(","))])] : a;
1891
+ const next = {
1892
+ allowIps: merge(cur.allowIps, opts.allowIp),
1893
+ allowCountries: merge(cur.allowCountries, opts.allowCountry?.map((x) => x.toUpperCase())),
1894
+ denyCountries: merge(cur.denyCountries, opts.denyCountry?.map((x) => x.toUpperCase()))
1895
+ };
1896
+ for (const k of Object.keys(next)) if (!next[k]?.length) delete next[k];
1897
+ s.set(Object.keys(next).length ? next : void 0);
1898
+ await save(p, opts.force);
1899
+ ok(`${opts.scope}: ${describe(next)}`);
559
1900
  }
1901
+ async function accessClear(opts) {
1902
+ const p = await api("GET", "/policy");
1903
+ scopeOf(p, opts.scope).set(void 0);
1904
+ await save(p, false);
1905
+ ok(`${opts.scope}: any network`);
1906
+ }
1907
+ async function accessCloudflare(opts) {
1908
+ const p = await api("GET", "/policy");
1909
+ if (opts.off) delete p.access;
1910
+ else {
1911
+ if (!opts.team || !opts.aud) throw new UserError("Give --team myteam.cloudflareaccess.com and --aud <Application Audience tag>.");
1912
+ p.access = { teamDomain: opts.team, aud: opts.aud };
1913
+ }
1914
+ await save(p, false);
1915
+ if (opts.off) return ok("Cloudflare Access sign-in is off.");
1916
+ ok("Cloudflare Access sign-in is on.");
1917
+ note("In Zero Trust, add a self-hosted application for your Worker host with path /_keybox/ and copy its");
1918
+ note("Application Audience (AUD) tag here. Then the dashboard accepts your Access login.");
1919
+ }
1920
+ async function skill(opts) {
1921
+ const text = readFileSync6(skillAsset(), "utf8");
1922
+ if (opts.print) return void process.stdout.write(text);
1923
+ const base = opts.project ? process.cwd() : homedir2();
1924
+ const targets = {
1925
+ claude: join4(base, ".claude", "skills", "keybox", "SKILL.md"),
1926
+ codex: join4(opts.project ? join4(base, ".codex") : join4(homedir2(), ".codex"), "skills", "keybox", "SKILL.md"),
1927
+ agents: join4(base, ".agents", "skills", "keybox", "SKILL.md")
1928
+ };
1929
+ const pick = opts.target === "all" ? Object.keys(targets) : opts.target.split(",");
1930
+ for (const t of pick) {
1931
+ const path = targets[t];
1932
+ if (!path) throw new UserError(`Unknown target ${t}. Use claude, codex, agents or all (or --print).`);
1933
+ const existed = existsSync4(path);
1934
+ mkdirSync3(dirname2(path), { recursive: true });
1935
+ writeFileSync3(path, text);
1936
+ ok(`${existed ? "Updated" : "Installed"} ${path}`);
1937
+ }
1938
+ step("Agents that load skills now know how to set up Keybox, migrate keys and write narrow rules safely.");
1939
+ note('Ask yours: "set up keybox for this project".');
1940
+ }
1941
+ var describe, skillAsset;
1942
+ var init_extra = __esm({
1943
+ "src/extra.ts"() {
1944
+ "use strict";
1945
+ init_api();
1946
+ init_config();
1947
+ init_prompt();
1948
+ init_ui();
1949
+ describe = (r) => {
1950
+ if (!r || !Object.keys(r).length) return c.dim("any network");
1951
+ const parts2 = [];
1952
+ if (r.allowIps?.length) parts2.push(`ips ${r.allowIps.join(", ")}`);
1953
+ if (r.allowCountries?.length) parts2.push(`only ${r.allowCountries.join(", ")}`);
1954
+ if (r.denyCountries?.length) parts2.push(`never ${r.denyCountries.join(", ")}`);
1955
+ return parts2.join("; ");
1956
+ };
1957
+ skillAsset = () => new URL("../assets/skill/SKILL.md", import.meta.url).pathname;
1958
+ }
1959
+ });
560
1960
 
561
1961
  // src/index.ts
562
- var HELP = `keybox: give AI agents access to your APIs without giving them your keys.
1962
+ init_commands();
1963
+ init_config();
1964
+ init_deploy();
1965
+ init_extra();
1966
+ init_migrate();
1967
+ import { parseArgs } from "node:util";
563
1968
 
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
1969
+ // src/tui.ts
1970
+ init_api();
1971
+ init_config();
1972
+ init_dove();
1973
+ init_ui();
1974
+ import { spawn as spawn6 } from "node:child_process";
1975
+ import { existsSync as existsSync5 } from "node:fs";
1976
+ import { delimiter, join as join5 } from "node:path";
1977
+ var TABS = ["Activity", "Secrets", "Agents"];
1978
+ var out = process.stdout;
1979
+ var ago2 = (ms) => {
1980
+ if (!ms) return "never";
1981
+ const s = Math.round((Date.now() - ms) / 1e3);
1982
+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.round(s / 60)}m` : s < 86400 ? `${Math.round(s / 3600)}h` : `${Math.round(s / 86400)}d`;
1983
+ };
1984
+ function fit(s, n) {
1985
+ if (width(s) <= n) return s + " ".repeat(n - width(s));
1986
+ let vis = 0;
1987
+ let res = "";
1988
+ for (let i = 0; i < s.length && vis < n - 1; ) {
1989
+ const m = /^\x1b\[[0-9;]*m/.exec(s.slice(i));
1990
+ if (m) {
1991
+ res += m[0];
1992
+ i += m[0].length;
1993
+ continue;
1994
+ }
1995
+ res += s[i++];
1996
+ vis++;
1997
+ }
1998
+ return res + "\u2026\x1B[0m";
1999
+ }
2000
+ function nativeTui() {
2001
+ const explicit = process.env.KEYBOX_TUI;
2002
+ if (explicit && existsSync5(explicit)) return explicit;
2003
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
2004
+ for (const name of process.platform === "win32" ? ["keybox-tui.exe"] : ["keybox-tui"]) {
2005
+ const p = join5(dir, name);
2006
+ if (dir && existsSync5(p)) return p;
2007
+ }
2008
+ }
2009
+ return null;
2010
+ }
2011
+ async function tui(opts = {}) {
2012
+ if (!process.stdin.isTTY || !out.isTTY) throw new UserError("keybox tui needs an interactive terminal. Try `keybox status` or `keybox audit -f`.");
2013
+ const native = opts.basic ? null : nativeTui();
2014
+ if (native) {
2015
+ requireConfig();
2016
+ const code = await new Promise((resolve) => {
2017
+ const child = spawn6(native, [], { stdio: "inherit" });
2018
+ child.on("error", () => resolve(-1));
2019
+ child.on("close", (c2) => resolve(c2 ?? 1));
2020
+ });
2021
+ if (code !== -1) {
2022
+ process.exitCode = code;
2023
+ return;
2024
+ }
2025
+ }
2026
+ const cfg = requireConfig();
2027
+ const st = { tab: 0, sel: 0, secrets: [], agents: [], audit: [], stats: {}, status: "loading\u2026", confirm: null, filter: "all" };
2028
+ const load = async (full) => {
2029
+ try {
2030
+ if (full) {
2031
+ [st.secrets, st.agents, st.stats] = await Promise.all([
2032
+ api("GET", "/secrets"),
2033
+ api("GET", "/agents"),
2034
+ api("GET", "/stats")
2035
+ ]);
2036
+ st.audit = await api("GET", "/audit?limit=300");
2037
+ } else {
2038
+ const more = await api("GET", `/audit?after=${st.audit.at(-1)?.id ?? 0}&limit=500`);
2039
+ if (more.length) st.audit = [...st.audit, ...more].slice(-1e3);
2040
+ }
2041
+ st.status = "";
2042
+ } catch (err) {
2043
+ st.status = err.message;
2044
+ }
2045
+ draw();
2046
+ };
2047
+ const rows = () => {
2048
+ const w = out.columns ?? 80;
2049
+ if (st.tab === 0) {
2050
+ const list = st.audit.filter((r) => st.filter === "all" || r.decision !== "allow").slice().reverse();
2051
+ return list.map((r) => {
2052
+ const res = r.decision === "allow" ? String(r.status) : r.decision.toUpperCase();
2053
+ const col = r.decision === "allow" && r.status < 400 ? c.ok(res.padEnd(5)) : c.bad(res.padEnd(5));
2054
+ const req = `${r.method} ${r.host ?? ""}${r.path ?? ""}`;
2055
+ return `${c.dim(ago2(r.ts).padStart(4))} ${(r.agent ?? "-").padEnd(12).slice(0, 12)} ${col} ${fit(req, Math.max(10, w - 52))} ${c.dim(r.secret ?? r.reason ?? "")}`;
2056
+ });
2057
+ }
2058
+ if (st.tab === 1) {
2059
+ return st.secrets.map(
2060
+ (s) => `${c.bold(s.name.padEnd(26))} ${s.hosts.join(",").padEnd(30).slice(0, 30)} ${c.dim((s.fingerprint ?? "-").padEnd(13))} ${c.dim("used " + ago2(s.last_used))}`
2061
+ );
2062
+ }
2063
+ return st.agents.flatMap((a) => [
2064
+ `${c.bold(a.name)} ${c.accent(`${a.active_tokens} token${a.active_tokens === 1 ? "" : "s"}`)}`,
2065
+ ...a.grants.flatMap((g) => [
2066
+ ...g.allow.map((r) => ` ${c.dim("allow")} ${r} ${c.dim("\xB7 " + g.secret)}`),
2067
+ ...(g.deny ?? []).map((r) => ` ${c.bad("deny ")} ${r}`)
2068
+ ]),
2069
+ ""
2070
+ ]);
2071
+ };
2072
+ function draw() {
2073
+ const w = out.columns ?? 80;
2074
+ const h = out.rows ?? 24;
2075
+ const lines = [];
2076
+ const dw = Math.max(...DOVE_SMALL.slice(0, 4).map((l) => [...l].length));
2077
+ const dove = w >= 100 ? DOVE_SMALL.slice(0, 4).map((l) => l + " ".repeat(dw - [...l].length)) : [];
2078
+ const head = [
2079
+ `${c.accent("\u25A0")} ${c.bold("keybox")} ${c.dim(cfg.url)}`,
2080
+ `${st.secrets.length} secret${st.secrets.length === 1 ? "" : "s"} \xB7 ${st.agents.length} agent${st.agents.length === 1 ? "" : "s"} \xB7 ${c.dim("24h")} ${c.ok(String(st.stats.allow ?? 0))} allowed ${c.bad(String((st.stats.deny ?? 0) + (st.stats.error ?? 0)))} refused`,
2081
+ "",
2082
+ TABS.map((t, i) => i === st.tab ? `${c.accent("\u25A0")} ${c.bold(t)}` : c.dim(`\u25A1 ${t}`)).join(" ") + (st.tab === 0 ? c.dim(` filter: ${st.filter}`) : "")
2083
+ ];
2084
+ for (let i = 0; i < Math.max(head.length, dove.length); i++) {
2085
+ const left = head[i] ?? "";
2086
+ const right = dove[i] ? c.dim(dove[i]) : "";
2087
+ lines.push(right ? fit(left, w - width(right) - 2) + " " + right : left);
2088
+ }
2089
+ lines.push(c.dim("\u2500".repeat(w)));
2090
+ const body = rows();
2091
+ const room = h - lines.length - 2;
2092
+ st.sel = Math.max(0, Math.min(st.sel, body.length - 1));
2093
+ const start = Math.max(0, Math.min(st.sel - Math.floor(room / 2), body.length - room));
2094
+ for (let i = start; i < Math.min(body.length, start + room); i++) {
2095
+ const line = fit(body[i], w - 2);
2096
+ lines.push(st.tab === 1 && i === st.sel ? `${c.accent("\u258C")}${line}` : ` ${line}`);
2097
+ }
2098
+ if (!body.length) lines.push(c.dim(st.tab === 1 ? " No secrets yet. Press a to add one, or run keybox migrate." : st.tab === 2 ? " No agents yet." : " No activity yet."));
2099
+ while (lines.length < h - 1) lines.push("");
2100
+ const keys = st.confirm ? c.warn(`${st.confirm.text} [y/N]`) : st.status ? c.dim(st.status) : c.dim(
2101
+ ["tab/1-3 switch", "\u2191\u2193 move", st.tab === 0 ? "f filter" : "", st.tab === 1 ? "a add \xB7 d delete" : "", "w web ui", "r refresh", "q quit"].filter(Boolean).join(" \xB7 ")
2102
+ );
2103
+ lines.push(fit(keys, w));
2104
+ out.write("\x1B[H" + lines.map((l) => l + "\x1B[K").join("\n"));
2105
+ }
2106
+ const leave = () => {
2107
+ out.write("\x1B[?25h\x1B[?1049l");
2108
+ process.stdin.setRawMode(false);
2109
+ };
2110
+ const enter = () => {
2111
+ out.write("\x1B[?1049h\x1B[?25l\x1B[2J");
2112
+ process.stdin.setRawMode(true);
2113
+ process.stdin.resume();
2114
+ process.stdin.setEncoding("utf8");
2115
+ };
2116
+ const suspend = async (fn) => {
2117
+ process.stdin.off("data", onKey);
2118
+ leave();
2119
+ try {
2120
+ await fn();
2121
+ } catch (err) {
2122
+ process.stderr.write(`keybox: ${err.message}
2123
+ `);
2124
+ }
2125
+ process.stderr.write(c.dim("\nPress enter to go back."));
2126
+ process.stdin.setRawMode(true);
2127
+ process.stdin.resume();
2128
+ await new Promise((r) => process.stdin.once("data", () => r()));
2129
+ enter();
2130
+ process.stdin.on("data", onKey);
2131
+ await load(true);
2132
+ };
2133
+ let resolveDone;
2134
+ const finished = new Promise((r) => resolveDone = r);
2135
+ const onKey = (k) => {
2136
+ if (st.confirm) {
2137
+ const cf2 = st.confirm;
2138
+ st.confirm = null;
2139
+ if (k === "y" || k === "Y") void cf2.run().then(() => load(true));
2140
+ else draw();
2141
+ return;
2142
+ }
2143
+ if (k === "q" || k === "") return resolveDone();
2144
+ if (k === " ") st.tab = (st.tab + 1) % TABS.length;
2145
+ else if (k === "\x1B[Z") st.tab = (st.tab + TABS.length - 1) % TABS.length;
2146
+ else if (k >= "1" && k <= "3") st.tab = Number(k) - 1;
2147
+ else if (k === "\x1B[A" || k === "k") st.sel--;
2148
+ else if (k === "\x1B[B" || k === "j") st.sel++;
2149
+ else if (k === "f" && st.tab === 0) st.filter = st.filter === "all" ? "refused" : "all";
2150
+ else if (k === "r") return void load(true);
2151
+ else if (k === "w") {
2152
+ return void suspend(async () => {
2153
+ const { ui: ui2 } = await Promise.resolve().then(() => (init_extra(), extra_exports));
2154
+ await ui2({ print: false });
2155
+ });
2156
+ } else if (k === "a" && st.tab === 1) {
2157
+ return void suspend(async () => {
2158
+ const { ask: ask2 } = await Promise.resolve().then(() => (init_prompt(), prompt_exports));
2159
+ const { secretsAdd: secretsAdd2 } = await Promise.resolve().then(() => (init_commands(), commands_exports));
2160
+ const name = (await ask2("Name (UPPER_SNAKE_CASE):")).toUpperCase();
2161
+ if (name) await secretsAdd2(name, {});
2162
+ });
2163
+ } else if (k === "d" && st.tab === 1 && st.secrets[st.sel]) {
2164
+ const s = st.secrets[st.sel];
2165
+ st.confirm = {
2166
+ text: `Delete ${s.name}? Agents using it will fail.`,
2167
+ run: async () => {
2168
+ await api("DELETE", `/secrets/${s.name}`);
2169
+ st.status = `Deleted ${s.name}.`;
2170
+ }
2171
+ };
2172
+ }
2173
+ if (st.tab !== 1) st.sel = 0;
2174
+ draw();
2175
+ };
2176
+ enter();
2177
+ process.stdin.on("data", onKey);
2178
+ const onResize = () => draw();
2179
+ out.on("resize", onResize);
2180
+ draw();
2181
+ await load(true);
2182
+ const timer = setInterval(() => void load(false), 2e3);
2183
+ const statsTimer = setInterval(() => void load(true), 3e4);
2184
+ try {
2185
+ await finished;
2186
+ } finally {
2187
+ clearInterval(timer);
2188
+ clearInterval(statsTimer);
2189
+ out.off("resize", onResize);
2190
+ process.stdin.off("data", onKey);
2191
+ leave();
2192
+ process.stdin.pause();
2193
+ }
2194
+ }
2195
+
2196
+ // src/update.ts
2197
+ init_config();
2198
+ init_prompt();
2199
+ init_ui();
2200
+ init_verify();
2201
+ init_version();
2202
+ import { spawn as spawn7, spawnSync as spawnSync2 } from "node:child_process";
2203
+ import { existsSync as existsSync6, realpathSync } from "node:fs";
2204
+ import { dirname as dirname3, join as join6 } from "node:path";
2205
+ import { fileURLToPath } from "node:url";
2206
+ function howInstalled() {
2207
+ const self = realpathSync(fileURLToPath(import.meta.url));
2208
+ if (self.includes(`${join6("_npx", "")}`) || self.includes("/_npx/")) return { kind: "npx" };
2209
+ const root = dirname3(dirname3(dirname3(self)));
2210
+ if (existsSync6(join6(root, ".git")) && existsSync6(join6(root, "cli", "package.json"))) return { kind: "checkout", root };
2211
+ if (self.includes(join6("node_modules", "@keyboxed", "cli"))) return { kind: "npm-global" };
2212
+ return { kind: "unknown", path: self };
2213
+ }
2214
+ function newer(a, b) {
2215
+ const parse = (v) => {
2216
+ const [main2, pre] = v.split("-", 2);
2217
+ return { nums: main2.split(".").map((n) => Number(n) || 0), pre };
2218
+ };
2219
+ const x = parse(a);
2220
+ const y = parse(b);
2221
+ for (let i = 0; i < 3; i++) if ((x.nums[i] ?? 0) !== (y.nums[i] ?? 0)) return (x.nums[i] ?? 0) > (y.nums[i] ?? 0);
2222
+ return !x.pre && !!y.pre;
2223
+ }
2224
+ async function latest() {
2225
+ try {
2226
+ const r = await fetch("https://registry.npmjs.org/@keyboxed%2fcli/latest", { signal: AbortSignal.timeout(8e3), headers: { accept: "application/json" } });
2227
+ if (r.status === 404) return null;
2228
+ if (!r.ok) throw new Error(`npm registry returned HTTP ${r.status}`);
2229
+ return (await r.json()).version;
2230
+ } catch (err) {
2231
+ throw new UserError(`Could not check for a newer version: ${err.message}`);
2232
+ }
2233
+ }
2234
+ function run2(cmd, args, cwd) {
2235
+ return new Promise((resolve) => {
2236
+ const child = spawn7(cmd, args, { stdio: "inherit", cwd, shell: process.platform === "win32" });
2237
+ child.on("close", (code) => resolve(code ?? 1));
2238
+ child.on("error", () => resolve(127));
2239
+ });
2240
+ }
2241
+ async function update(opts) {
2242
+ const install = howInstalled();
2243
+ step(`keybox ${VERSION}`);
2244
+ let cliUpdated = false;
2245
+ if (install.kind === "checkout") {
2246
+ note(`Running from a git checkout (${install.root}).`);
2247
+ const dirty = spawnSync2("git", ["status", "--porcelain"], { cwd: install.root, encoding: "utf8" }).stdout.trim();
2248
+ if (opts.check) note("Update it with: git pull && npm install && npm run build");
2249
+ else if (dirty) warn("The checkout has local changes; skipping git pull. Update it yourself, then run keybox update again.");
2250
+ else if (opts.yes || await confirm("Pull and rebuild the checkout?", true)) {
2251
+ if (await run2("git", ["pull", "--ff-only"], install.root) !== 0) throw new UserError("git pull failed.");
2252
+ if (await run2("npm", ["install", "--no-audit", "--no-fund"], install.root) !== 0) throw new UserError("npm install failed.");
2253
+ if (await run2("npm", ["run", "build"], install.root) !== 0) throw new UserError("npm run build failed.");
2254
+ cliUpdated = true;
2255
+ }
2256
+ } else {
2257
+ const v = await task("Latest release", latest, (v2) => v2 ? `@keyboxed/cli ${v2}` : "not published on npm yet");
2258
+ if (v && newer(v, VERSION)) {
2259
+ if (opts.check) note(`Update with: ${install.kind === "npx" ? `npx @keyboxed/cli@${v}` : `npm install -g @keyboxed/cli@${v}`}`);
2260
+ else if (install.kind === "npx") note(`You run Keybox through npx. Use npx @keyboxed/cli@${v} \u2026 from now on.`);
2261
+ else if (install.kind === "unknown") note(`Installed somewhere unusual (${install.path}). Install ${v} the way you installed this one.`);
2262
+ else if (opts.yes || await confirm(`Install @keyboxed/cli ${v}?`, true)) {
2263
+ if (await run2("npm", ["install", "-g", `@keyboxed/cli@${v}`]) !== 0) throw new UserError("npm install failed. You may need to fix npm permissions, or use npx.");
2264
+ cliUpdated = true;
2265
+ }
2266
+ } else if (v) ok(`${"CLI".padEnd(16)}${c.dim("up to date")}`);
2267
+ }
2268
+ if (cliUpdated) {
2269
+ ok("CLI updated. Continuing with the new version.");
2270
+ const bin2 = install.kind === "checkout" ? [process.execPath, join6(install.root, "cli", "dist", "keybox.js")] : ["keybox"];
2271
+ const code = await run2(bin2[0], [...bin2.slice(1), "update", "--worker-only", ...opts.yes ? ["--yes"] : []]);
2272
+ process.exitCode = code;
2273
+ return;
2274
+ }
2275
+ await updateWorker(opts);
2276
+ }
2277
+ async function updateWorker(opts) {
2278
+ const cfg = loadConfig();
2279
+ if (!cfg) return note("No Keybox set up on this machine yet. Run `keybox init`.");
2280
+ let deployedVersion = "?";
2281
+ try {
2282
+ deployedVersion = (await (await fetch(`${cfg.url}/_keybox/health`)).json()).version;
2283
+ } catch {
2284
+ }
2285
+ const { deploy: deploy2 } = await Promise.resolve().then(() => (init_deploy(), deploy_exports));
2286
+ const { checks: checks2, printChecks: printChecks2, resolveAccount: resolveAccount2 } = await Promise.resolve().then(() => (init_verify(), verify_exports));
2287
+ await resolveAccount2(cfg);
2288
+ const list = await task("Worker", () => checks2(cfg), () => `v${deployedVersion} deployed, this CLI ships v${VERSION}`);
2289
+ const code = list.find((x) => x.label === "Code");
2290
+ if (code?.ok === true) {
2291
+ if (!list.every((x) => x.ok === true)) printChecks2(list);
2292
+ return ok(`${"Up to date".padEnd(16)}${c.dim(`Worker matches this CLI (sha256 ${shippedWorkerHash().slice(0, 16)}\u2026)`)}`);
2293
+ }
2294
+ if (opts.check) return note("The Worker differs from this CLI. Run `keybox update` (or `keybox deploy`) to replace it.");
2295
+ await deploy2({ yes: opts.yes, force: true });
2296
+ }
2297
+
2298
+ // src/index.ts
2299
+ init_verify();
2300
+ init_ui();
2301
+ init_version();
2302
+ var HELP_BODY = `Setup
2303
+ keybox init [--account ID] [--name keybox] Deploy Keybox to your Cloudflare account
2304
+ keybox update [--check] [--yes] Update the CLI, then the deployed Worker, then verify
2305
+ keybox verify [--json] Check Cloudflare is running exactly this CLI's code
2306
+ keybox deploy [--yes] Replace the deployed Worker with this CLI's version
567
2307
  keybox status
2308
+ keybox ui [--print] Open the web dashboard (one-time login link)
2309
+ keybox tui [--basic] Live console (uses keybox-tui, the Rust console, when installed)
568
2310
 
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
2311
+ Moving keys in (values are never printed, logged or put on a command line)
2312
+ keybox migrate [--from SOURCE] [--dry-run] [--yes] [--only A,B]
2313
+ SOURCE: dotenv:FILE | env | 1password [--vault V] | bitwarden | bws [--project ID]
2314
+ doppler [--project P --config C] | infisical [--env E --path P]
2315
+ vault:PATH | sops:FILE | aws:SECRET_ID | gcp [--project P]
2316
+ pass --item PATH | keychain --item SERVICE
2317
+ keybox secrets add NAME [--from op://vault/item/field | vault://path#field | env://VAR \u2026]
2318
+ [--preset openai|anthropic|github|\u2026] [--host HOST \u2026 --header H --format bearer|raw|basic]
2319
+ keybox secrets list | rm NAME
575
2320
 
576
2321
  Agents
577
2322
  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
2323
+ keybox agents list | rm NAME
2324
+ keybox agents token NAME [--ttl 30d] Long-lived token for a deployed agent
581
2325
  keybox tokens revoke ID
582
2326
 
2327
+ Access (who may reach your Keybox)
2328
+ keybox access Show network rules
2329
+ keybox access set --scope admin|proxy|agent:NAME [--allow-ip CIDR \u2026] [--allow-country US \u2026]
2330
+ [--deny-country T1 \u2026] [--add] [--force]
2331
+ keybox access clear --scope \u2026
2332
+ keybox access cloudflare --team T.cloudflareaccess.com --aud TAG | --off
2333
+
583
2334
  Running
584
2335
  keybox run AGENT [--ttl 12h] [--clean-env] -- command [args]
585
2336
  keybox audit [--follow] [--limit 50]
586
- keybox blocked Calls Keybox never proxies
2337
+ keybox blocked Calls Keybox never proxies
2338
+
2339
+ For coding agents
2340
+ keybox skill install [--target claude|codex|agents|all] [--local] | --print
587
2341
  `;
2342
+ function help() {
2343
+ const tag = "give agents access, not your keys.";
2344
+ const top = banner([wordmark() + c.dim(` v${VERSION}`), c.dim(tag), "", c.dim("keybox.space/docs")]);
2345
+ const body = color ? HELP_BODY.replace(/^(\S.*)$/gm, (l) => c.accent("\u25A0 ") + c.bold(l)).replace(/^( {2}keybox)/gm, " " + c.accent("keybox")) : HELP_BODY;
2346
+ return (top || `keybox: ${tag}
2347
+
2348
+ `) + body;
2349
+ }
588
2350
  async function main(argv) {
589
2351
  const dash = argv.indexOf("--");
590
2352
  const args = dash === -1 ? argv : argv.slice(0, dash);
@@ -606,6 +2368,32 @@ async function main(argv) {
606
2368
  deny: { type: "string", multiple: true },
607
2369
  ttl: { type: "string" },
608
2370
  "clean-env": { type: "boolean", default: false },
2371
+ from: { type: "string" },
2372
+ only: { type: "string" },
2373
+ vault: { type: "string" },
2374
+ project: { type: "string", multiple: false },
2375
+ config: { type: "string" },
2376
+ env: { type: "string" },
2377
+ path: { type: "string" },
2378
+ item: { type: "string", multiple: true },
2379
+ print: { type: "boolean", default: false },
2380
+ scope: { type: "string", default: "admin" },
2381
+ "allow-ip": { type: "string", multiple: true },
2382
+ "allow-country": { type: "string", multiple: true },
2383
+ "deny-country": { type: "string", multiple: true },
2384
+ add: { type: "boolean", default: false },
2385
+ team: { type: "string" },
2386
+ aud: { type: "string" },
2387
+ off: { type: "boolean", default: false },
2388
+ target: { type: "string", default: "claude" },
2389
+ local: { type: "boolean", default: false },
2390
+ basic: { type: "boolean", default: false },
2391
+ account: { type: "string" },
2392
+ check: { type: "boolean", default: false },
2393
+ "worker-only": { type: "boolean", default: false },
2394
+ json: { type: "boolean", default: false },
2395
+ verbose: { type: "boolean", default: false },
2396
+ version: { type: "boolean", short: "v", default: false },
609
2397
  follow: { type: "boolean", short: "f", default: false },
610
2398
  limit: { type: "string", default: "50" },
611
2399
  help: { type: "boolean", short: "h", default: false }
@@ -616,16 +2404,39 @@ async function main(argv) {
616
2404
  if (!v) throw new UserError(`Missing ${what}. See keybox --help.`);
617
2405
  return v;
618
2406
  };
619
- if (o.help || !group) return void process.stdout.write(HELP);
620
- switch (`${group} ${["secrets", "agents", "tokens"].includes(group) ? sub ?? "" : ""}`.trim()) {
2407
+ if (o.version) return void process.stdout.write(VERSION + "\n");
2408
+ if (o.verbose) process.env.KEYBOX_VERBOSE = "1";
2409
+ if (o.help || !group) return void process.stdout.write(help());
2410
+ switch (`${group} ${["secrets", "agents", "tokens", "access", "skill"].includes(group) ? sub ?? "" : ""}`.trim()) {
621
2411
  case "init":
622
- return init({ name: o.name, url: o.url });
2412
+ return init({ name: o.name, url: o.url, account: o.account, yes: o.yes });
2413
+ case "verify":
2414
+ return verify({ json: o.json });
2415
+ case "update":
2416
+ return o["worker-only"] ? updateWorker({ yes: o.yes, check: o.check }) : update({ yes: o.yes, check: o.check });
623
2417
  case "deploy":
624
2418
  return deploy({ yes: o.yes, force: o.force });
625
2419
  case "status":
626
2420
  return status();
2421
+ case "ui":
2422
+ return ui({ print: o.print });
2423
+ case "tui":
2424
+ return tui({ basic: o.basic });
2425
+ case "migrate":
2426
+ return migrate({
2427
+ from: o.from ?? sub,
2428
+ dryRun: o["dry-run"],
2429
+ yes: o.yes,
2430
+ only: o.only?.split(","),
2431
+ vault: o.vault,
2432
+ project: o.project,
2433
+ config: o.config,
2434
+ env: o.env,
2435
+ path: o.path,
2436
+ item: o.item
2437
+ });
627
2438
  case "secrets add":
628
- return secretsAdd(need(arg, "secret name"), { preset: o.preset, host: o.host, header: o.header, format: o.format });
2439
+ return secretsAdd(need(arg, "secret name"), { preset: o.preset, host: o.host, header: o.header, format: o.format, from: o.from });
629
2440
  case "secrets import":
630
2441
  return secretsImport(need(arg, "file"), { dryRun: o["dry-run"], yes: o.yes });
631
2442
  case "secrets list":
@@ -648,6 +2459,18 @@ async function main(argv) {
648
2459
  return audit({ follow: o.follow, limit: o.limit });
649
2460
  case "blocked":
650
2461
  return blocked();
2462
+ case "access":
2463
+ case "access show":
2464
+ return accessShow();
2465
+ case "access set":
2466
+ return accessSet({ scope: o.scope, allowIp: o["allow-ip"], allowCountry: o["allow-country"], denyCountry: o["deny-country"], add: o.add, force: o.force });
2467
+ case "access clear":
2468
+ return accessClear({ scope: o.scope });
2469
+ case "access cloudflare":
2470
+ return accessCloudflare({ team: o.team, aud: o.aud, off: o.off });
2471
+ case "skill":
2472
+ case "skill install":
2473
+ return skill({ target: o.target, project: o.local, print: o.print });
651
2474
  default:
652
2475
  throw new UserError(`Unknown command: ${p.join(" ")}. See keybox --help.`);
653
2476
  }