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