@keyboxed/cli 0.2.6 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/keybox.js CHANGED
@@ -41,56 +41,401 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
41
41
  mod
42
42
  ));
43
43
 
44
+ // src/dove.ts
45
+ var DOVE_LARGE, DOVE_SMALL;
46
+ var init_dove = __esm({
47
+ "src/dove.ts"() {
48
+ "use strict";
49
+ DOVE_LARGE = [
50
+ "\u2820\u28C4\u2858\u28B6\u28C4\u2840\u28A0\u2840",
51
+ "\u2830\u28CC\u28FB\u28F2\u28F3\u289F\u28E6\u28BD\u28D6\u28C4",
52
+ "\u2830\u28EC\u2873\u28FD\u28DE\u28DF\u28BE\u289D\u286E\u28DE\u28B5\u28C2",
53
+ "\u2800\u28A8\u28DD\u28D7\u28B7\u28BD\u28DD\u28F5\u286B\u286E\u28D3\u288E\u2897\u28A4\u2800\u28C0",
54
+ "\u2800\u2800\u28A8\u287A\u286F\u2877\u28F3\u28A7\u28AF\u28AF\u28AE\u2873\u28F1\u28B1\u288D\u289E\u28A6",
55
+ "\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",
56
+ "\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",
57
+ "\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",
58
+ "\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",
59
+ "\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",
60
+ "\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",
61
+ "\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",
62
+ "\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",
63
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28BE\u28FB\u28AE\u28D7\u28DD\u28AE\u286A\u287A\u28F8\u28B8\u28B8\u28B8\u28A8\u28B2\u2841",
64
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u283B\u28F3\u2897\u28D7\u2875\u28EB\u287A\u28F8\u28AA\u287A\u285C\u286E\u28FA\u287A\u28E6",
65
+ "\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",
66
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u2819\u2839\u287D\u28B3\u28FB\u283A\u283D\u280B\u2803"
67
+ ];
68
+ DOVE_SMALL = [
69
+ "\u2890\u28AC\u28F2\u28C4\u2862\u2840",
70
+ "\u2828\u28DF\u28DE\u286E\u286F\u286F\u2872\u2840",
71
+ "\u2800\u2893\u287D\u287E\u28DD\u286E\u28CF\u288E\u2887\u2896\u2840",
72
+ "\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",
73
+ "\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",
74
+ "\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",
75
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u2813\u289D\u28EE\u28FE\u28AF\u28B3\u2879\u28EA\u28F3\u28DD\u286E\u2817\u280B\u2808",
76
+ "\u2800\u2800\u2800\u2800\u2820\u28D6\u28D6\u28AE\u287A\u2878\u285D\u287A\u2871\u2815\u2803\u280B\u2803\u2803\u2801",
77
+ "\u2800\u2800\u2800\u2800\u2800\u2811\u28EF\u2897\u2875\u28E3\u2873\u28F1\u2895\u286F\u28C2",
78
+ "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u281B\u289E\u28AE\u2837\u282F\u281B\u2809"
79
+ ];
80
+ }
81
+ });
82
+
83
+ // src/ui.ts
84
+ function step(s) {
85
+ process.stderr.write(`${c.accent("\u25A0")} ${s}
86
+ `);
87
+ }
88
+ function note(s) {
89
+ process.stderr.write(`${c.dim(" " + s)}
90
+ `);
91
+ }
92
+ function ok(s) {
93
+ process.stderr.write(`${c.ok("\u2713")} ${s}
94
+ `);
95
+ }
96
+ function warn(s) {
97
+ process.stderr.write(`${c.warn("!")} ${s}
98
+ `);
99
+ }
100
+ function table(rows) {
101
+ if (rows.length === 0) return "";
102
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => width(r[i] ?? ""))));
103
+ return rows.map((r) => r.map((cell, i) => i === r.length - 1 ? cell : pad(cell, widths[i])).join(" ")).join("\n") + "\n";
104
+ }
105
+ function headed(rows) {
106
+ if (!rows.length) return "";
107
+ const tty = process.stdout.isTTY && color;
108
+ return table(tty ? [rows[0].map(label), ...rows.slice(1)] : rows);
109
+ }
110
+ function when(ms) {
111
+ return new Date(ms).toISOString().replace("T", " ").slice(0, 19);
112
+ }
113
+ function ago(ms) {
114
+ if (!ms) return "never";
115
+ const s = Math.round((Date.now() - ms) / 1e3);
116
+ if (s < 60) return `${s}s ago`;
117
+ if (s < 3600) return `${Math.round(s / 60)}m ago`;
118
+ if (s < 86400) return `${Math.round(s / 3600)}h ago`;
119
+ return `${Math.round(s / 86400)}d ago`;
120
+ }
121
+ function parseDuration(s) {
122
+ const m = /^(\d+)([smhd]?)$/.exec(s.trim());
123
+ if (!m) throw new Error(`bad duration: ${s}`);
124
+ return Number(m[1]) * { "": 1, s: 1, m: 60, h: 3600, d: 86400 }[m[2]];
125
+ }
126
+ function banner(lines = [], size = "large") {
127
+ if (!color) return lines.length ? lines.join("\n") + "\n" : "";
128
+ const cols = process.stderr.columns ?? 80;
129
+ const dove = size === "large" && cols >= 92 ? DOVE_LARGE : DOVE_SMALL;
130
+ const dw = Math.max(...dove.map((l) => [...l].length));
131
+ if (cols < dw + 20) return lines.join("\n") + "\n";
132
+ const squares = /* @__PURE__ */ new Map([
133
+ [1, [dw + 4, "\u25A0"]],
134
+ [Math.floor(dove.length * 0.7), [dw - 6, "\u25AA"]],
135
+ [dove.length - 2, [dw + 9, "\u25AB"]]
136
+ ]);
137
+ const top = Math.max(0, Math.floor((dove.length - lines.length) / 2));
138
+ const out2 = [];
139
+ for (let i = 0; i < dove.length; i++) {
140
+ const d = dove[i];
141
+ let row = " " + d + " ".repeat(dw - [...d].length);
142
+ const text = lines[i - top];
143
+ const sq = squares.get(i);
144
+ if (text !== void 0) row += " " + text;
145
+ else if (sq) row = row.slice(0, 2 + sq[0]) + " ".repeat(Math.max(0, 2 + sq[0] - width(row))) + c.accent(sq[1]);
146
+ out2.push(row);
147
+ }
148
+ return "\n" + out2.join("\n") + "\n\n";
149
+ }
150
+ function spin(text) {
151
+ if (!color) {
152
+ process.stderr.write(`${text}
153
+ `);
154
+ return (final) => final && process.stderr.write(final + "\n");
155
+ }
156
+ const frames = "\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F";
157
+ let i = 0;
158
+ const draw = () => process.stderr.write(`\r\x1B[2K${c.accent(frames[i++ % frames.length])} ${text}`);
159
+ draw();
160
+ const t = setInterval(draw, 80);
161
+ return (final) => {
162
+ clearInterval(t);
163
+ process.stderr.write(`\r\x1B[2K${final ? final + "\n" : ""}`);
164
+ };
165
+ }
166
+ async function task(label2, fn, done) {
167
+ const name = label2.padEnd(16);
168
+ const stop = color ? spin(name) : (final) => final && process.stderr.write(final + "\n");
169
+ try {
170
+ const r = await fn();
171
+ stop(`${c.ok("\u2713")} ${name}${c.dim(done ? done(r) : "")}`);
172
+ return r;
173
+ } catch (err) {
174
+ stop(`${c.bad("\u2717")} ${name}`);
175
+ const tail = err.stderr;
176
+ if (tail) {
177
+ const lines = tail.replace(/\x1b\[[0-9;]*m/g, "").split("\n").map((l) => l.trimEnd()).filter((l) => l.trim() && !/^[─┌└│├┐┘]/.test(l));
178
+ for (const l of lines.slice(-8)) process.stderr.write(c.dim(` ${l}
179
+ `));
180
+ }
181
+ throw err;
182
+ }
183
+ }
184
+ var env, color, truecolor, sgr, rgb, c, width, pad, label, wordmark;
185
+ var init_ui = __esm({
186
+ "src/ui.ts"() {
187
+ "use strict";
188
+ init_dove();
189
+ env = process.env;
190
+ color = Boolean(process.stderr.isTTY) && !env.NO_COLOR && env.TERM !== "dumb";
191
+ truecolor = color && /truecolor|24bit/i.test(env.COLORTERM ?? "");
192
+ sgr = (open, close = "\x1B[0m") => (s) => color ? `\x1B[${open}m${s}${close}` : s;
193
+ rgb = (r, g, b, fallback) => sgr(truecolor ? `38;2;${r};${g};${b}` : fallback, "\x1B[39m");
194
+ c = {
195
+ // Cobalt that reads on both light and dark terminals.
196
+ accent: rgb(96, 124, 240, "38;5;69"),
197
+ ok: rgb(111, 194, 141, "32"),
198
+ bad: rgb(232, 120, 100, "31"),
199
+ warn: rgb(222, 170, 90, "33"),
200
+ dim: sgr("2", "\x1B[22m"),
201
+ bold: sgr("1", "\x1B[22m"),
202
+ italic: sgr("3", "\x1B[23m")
203
+ };
204
+ width = (s) => s.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "").length;
205
+ pad = (s, n) => s + " ".repeat(Math.max(0, n - width(s)));
206
+ label = (s) => c.dim(s.toUpperCase());
207
+ wordmark = () => `${c.accent("\u25A0")} ${c.bold("keybox")}`;
208
+ }
209
+ });
210
+
44
211
  // src/config.ts
45
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
212
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
46
213
  import { homedir } from "node:os";
47
- import { join } from "node:path";
214
+ import { dirname, join } from "node:path";
48
215
  function configDir() {
49
216
  return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "keybox");
50
217
  }
51
- function loadConfig() {
218
+ function deployDir(key) {
219
+ return join(configDir(), key ?? current()?.config.deploy ?? "deploy");
220
+ }
221
+ function nameFromUrl(url) {
222
+ let host = "";
223
+ try {
224
+ host = new URL(url).hostname;
225
+ } catch {
226
+ }
227
+ const parts2 = host.split(".");
228
+ const first = parts2[0] === "keybox" && parts2.length > 2 ? parts2[1] : parts2[0];
229
+ const n = (first ?? "").toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^-+|-+$/g, "").slice(0, 31);
230
+ return PROFILE.test(n) ? n : "default";
231
+ }
232
+ function readStore() {
233
+ if (!existsSync(configPath())) return { profiles: {} };
234
+ let raw;
235
+ try {
236
+ raw = JSON.parse(readFileSync(configPath(), "utf8"));
237
+ } catch {
238
+ throw new UserError(`${configPath()} is not valid JSON. Fix or remove it.`);
239
+ }
240
+ if (raw && typeof raw.profiles === "object" && raw.profiles) return { current: raw.current, profiles: raw.profiles };
241
+ if (raw && typeof raw.url === "string") {
242
+ const name = nameFromUrl(raw.url);
243
+ return { current: name, profiles: { [name]: { ...raw, deploy: raw.deploy ?? "deploy" } } };
244
+ }
245
+ return { profiles: {} };
246
+ }
247
+ function writeStore(s) {
248
+ mkdirSync(configDir(), { recursive: true, mode: 448 });
249
+ const tmp = `${configPath()}.tmp`;
250
+ writeFileSync(tmp, JSON.stringify(s, null, 2) + "\n", { mode: 384 });
251
+ chmodSync(tmp, 384);
252
+ renameSync(tmp, configPath());
253
+ }
254
+ function useProfile(name) {
255
+ flagProfile = name;
256
+ }
257
+ function projectPin(cwd) {
258
+ let dir = cwd;
259
+ for (let i = 0; i < 40; i++) {
260
+ const file = join(dir, PIN_FILE);
261
+ try {
262
+ if (existsSync(file) && statSync(file).size < 4096) {
263
+ const url = JSON.parse(readFileSync(file, "utf8")).url;
264
+ if (typeof url === "string" && /^https?:\/\/[^/\s]+$/.test(url.replace(/\/+$/, ""))) return { url, file };
265
+ }
266
+ } catch {
267
+ }
268
+ const up = dirname(dir);
269
+ if (up === dir) break;
270
+ dir = up;
271
+ }
272
+ return null;
273
+ }
274
+ function resolveProfile(cwd = process.cwd()) {
52
275
  const env2 = process.env;
276
+ const store = readStore();
277
+ const named = (name, source) => {
278
+ const config = store.profiles[name];
279
+ if (!config) throw new UserError(`No connection called ${name}. See \`keybox profiles\`.`);
280
+ return { name, config, source };
281
+ };
282
+ if (flagProfile) return named(flagProfile, "flag");
283
+ if (env2.KEYBOX_PROFILE) return named(env2.KEYBOX_PROFILE, "env");
284
+ if (env2.KEYBOX_URL && env2.KEYBOX_DEVICE_ID && env2.KEYBOX_DEVICE_KEY) {
285
+ return {
286
+ name: "(environment)",
287
+ source: "environment",
288
+ config: { url: env2.KEYBOX_URL, deviceId: env2.KEYBOX_DEVICE_ID, deviceKey: env2.KEYBOX_DEVICE_KEY, name: env2.KEYBOX_NAME ?? "keybox", d1Id: "" }
289
+ };
290
+ }
53
291
  if (env2.KEYBOX_URL && env2.KEYBOX_ADMIN_TOKEN) {
54
292
  return {
55
- url: env2.KEYBOX_URL,
56
- adminToken: env2.KEYBOX_ADMIN_TOKEN,
57
- name: env2.KEYBOX_NAME ?? "keybox",
58
- d1Id: "",
59
- accountId: env2.KEYBOX_ACCOUNT_ID ?? env2.CLOUDFLARE_ACCOUNT_ID
293
+ name: "(environment)",
294
+ source: "environment",
295
+ config: { url: env2.KEYBOX_URL, adminToken: env2.KEYBOX_ADMIN_TOKEN, name: env2.KEYBOX_NAME ?? "keybox", d1Id: "", accountId: env2.KEYBOX_ACCOUNT_ID ?? env2.CLOUDFLARE_ACCOUNT_ID }
60
296
  };
61
297
  }
62
- if (!existsSync(configPath())) return null;
63
- return JSON.parse(readFileSync(configPath(), "utf8"));
298
+ const pin = projectPin(cwd);
299
+ if (pin) {
300
+ const hit = Object.entries(store.profiles).find(([, p]) => sameUrl(p.url, pin.url));
301
+ if (!hit) {
302
+ throw new UserError(`This folder uses ${pin.url} (from ${pin.file}), and this machine is not connected to it. Run \`keybox login ${pin.url}\`.`);
303
+ }
304
+ return { ...named(hit[0], "project"), file: pin.file };
305
+ }
306
+ const names = Object.keys(store.profiles);
307
+ if (!names.length) return null;
308
+ if (store.current && store.profiles[store.current]) return named(store.current, "current");
309
+ if (names.length === 1) return named(names[0], "current");
310
+ throw new UserError(`Several Keyboxes are saved (${names.join(", ")}). Pick one with \`keybox use NAME\`, or --profile NAME.`);
311
+ }
312
+ function current() {
313
+ try {
314
+ return resolveProfile();
315
+ } catch {
316
+ return null;
317
+ }
318
+ }
319
+ function loadConfig() {
320
+ return resolveProfile()?.config ?? null;
64
321
  }
65
322
  function requireConfig() {
66
- const c2 = loadConfig();
67
- if (!c2) throw new UserError("Not set up yet. Run `keybox init` first.");
68
- return c2;
323
+ const r = resolveProfile();
324
+ if (!r) throw new UserError("Not set up yet. Run `keybox init` to deploy one, or `keybox login` to connect to one.");
325
+ if (!announced && r.source !== "environment" && process.stderr.isTTY && Object.keys(readStore().profiles).length > 1) {
326
+ announced = true;
327
+ const why = { flag: "--profile", env: "KEYBOX_PROFILE", project: r.file ?? PIN_FILE, current: "default", environment: "" }[r.source];
328
+ process.stderr.write(c.dim(`using ${r.name} (${r.config.url}) \xB7 ${why}`) + "\n");
329
+ }
330
+ return r.config;
69
331
  }
70
- function saveConfig(c2) {
71
- mkdirSync(configDir(), { recursive: true, mode: 448 });
72
- writeFileSync(configPath(), JSON.stringify(c2, null, 2) + "\n", { mode: 384 });
73
- chmodSync(configPath(), 384);
332
+ function listProfiles() {
333
+ return { store: readStore(), resolved: current() };
74
334
  }
75
- var configPath, deployDir, UserError;
335
+ function saveConfig(cfg, opts = {}) {
336
+ const s = readStore();
337
+ const existing = Object.entries(s.profiles).find(([, p]) => sameUrl(p.url, cfg.url))?.[0];
338
+ let name = existing;
339
+ const wanted = opts.as?.toLowerCase();
340
+ if (wanted && !PROFILE.test(wanted)) throw new UserError("A name is lowercase letters, digits and dashes (up to 31 characters).");
341
+ if (!name) {
342
+ name = wanted ?? nameFromUrl(cfg.url);
343
+ if (s.profiles[name]) {
344
+ if (wanted) throw new UserError(`There is already a connection called ${wanted}, for ${s.profiles[name].url}. Pick another name with --as.`);
345
+ for (let i = 2; s.profiles[name]; i++) name = `${nameFromUrl(cfg.url)}-${i}`;
346
+ }
347
+ s.current = name;
348
+ } else if (wanted && wanted !== name) {
349
+ if (s.profiles[wanted]) throw new UserError(`There is already a connection called ${wanted}, for ${s.profiles[wanted].url}.`);
350
+ delete s.profiles[name];
351
+ if (s.current === name) s.current = wanted;
352
+ name = wanted;
353
+ }
354
+ s.profiles[name] = cfg;
355
+ if (!s.current || !s.profiles[s.current]) s.current = name;
356
+ writeStore(s);
357
+ return name;
358
+ }
359
+ function setCurrent(name) {
360
+ const s = readStore();
361
+ const p = s.profiles[name];
362
+ if (!p) throw new UserError(`No connection called ${name}. See \`keybox profiles\`.`);
363
+ s.current = name;
364
+ writeStore(s);
365
+ return p;
366
+ }
367
+ function removeProfile(name) {
368
+ const s = readStore();
369
+ const p = s.profiles[name];
370
+ if (!p) throw new UserError(`No connection called ${name}. See \`keybox profiles\`.`);
371
+ delete s.profiles[name];
372
+ if (s.current === name) s.current = Object.keys(s.profiles).length === 1 ? Object.keys(s.profiles)[0] : void 0;
373
+ writeStore(s);
374
+ return p;
375
+ }
376
+ function pinFolder(dir, url) {
377
+ const file = join(dir, PIN_FILE);
378
+ writeFileSync(file, JSON.stringify({ url: url.replace(/\/+$/, "") }, null, 2) + "\n");
379
+ return file;
380
+ }
381
+ var PROFILE, PIN_FILE, UserError, configPath, sameUrl, flagProfile, announced, isOwnDeployment;
76
382
  var init_config = __esm({
77
383
  "src/config.ts"() {
78
384
  "use strict";
79
- configPath = () => join(configDir(), "config.json");
80
- deployDir = () => join(configDir(), "deploy");
385
+ init_ui();
386
+ PROFILE = /^[a-z0-9][a-z0-9-]{0,30}$/;
387
+ PIN_FILE = ".keybox.json";
81
388
  UserError = class extends Error {
82
389
  };
390
+ configPath = () => join(configDir(), "config.json");
391
+ sameUrl = (a, b) => a.replace(/\/+$/, "").toLowerCase() === b.replace(/\/+$/, "").toLowerCase();
392
+ announced = false;
393
+ isOwnDeployment = (cfg) => Boolean(cfg.name && cfg.d1Id);
394
+ }
395
+ });
396
+
397
+ // src/device.ts
398
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign } from "node:crypto";
399
+ import { hostname } from "node:os";
400
+ function newDeviceKey() {
401
+ const { privateKey, publicKey } = generateKeyPairSync("ed25519");
402
+ return {
403
+ privateKey: privateKey.export({ format: "der", type: "pkcs8" }).toString("base64url"),
404
+ publicKey: publicKey.export({ format: "jwk" }).x
405
+ };
406
+ }
407
+ function deviceName() {
408
+ return hostname().replace(/\.local$/, "").slice(0, 48) || "device";
409
+ }
410
+ function signRequest(device, method, fullUrl, body, now = Date.now()) {
411
+ const u = new URL(fullUrl);
412
+ const ts = String(now);
413
+ const nonce = randomBytes(16).toString("base64url");
414
+ const text = ["KEYBOX-SIG-1", method.toUpperCase(), u.host, u.pathname + u.search, ts, nonce, createHash("sha256").update(body).digest("hex")].join("\n");
415
+ const key = createPrivateKey({ key: Buffer.from(device.privateKey, "base64url"), format: "der", type: "pkcs8" });
416
+ const sig = sign(null, Buffer.from(text), key).toString("base64url");
417
+ return `Keybox-Sig id=${device.id}, ts=${ts}, nonce=${nonce}, sig=${sig}`;
418
+ }
419
+ var init_device = __esm({
420
+ "src/device.ts"() {
421
+ "use strict";
83
422
  }
84
423
  });
85
424
 
86
425
  // src/api.ts
87
426
  async function api(method, path, body, config = requireConfig()) {
88
427
  let res;
428
+ const url = `${config.url.replace(/\/$/, "")}/_keybox/admin${path}`;
429
+ const text = body === void 0 ? "" : JSON.stringify(body);
430
+ let authorization;
431
+ if (config.deviceId && config.deviceKey) authorization = signRequest({ id: config.deviceId, privateKey: config.deviceKey }, method, url, text);
432
+ else if (config.adminToken) authorization = `Bearer ${config.adminToken}`;
433
+ else throw new UserError("No credentials for this Keybox. Run `keybox login`.");
89
434
  try {
90
- res = await fetch(`${config.url.replace(/\/$/, "")}/_keybox/admin${path}`, {
435
+ res = await fetch(url, {
91
436
  method,
92
- headers: { authorization: `Bearer ${config.adminToken}`, "content-type": "application/json" },
93
- body: body === void 0 ? void 0 : JSON.stringify(body)
437
+ headers: { authorization, "content-type": "application/json" },
438
+ body: body === void 0 ? void 0 : text
94
439
  });
95
440
  } catch {
96
441
  throw new UserError(`Could not reach ${config.url}.`);
@@ -103,6 +448,7 @@ var init_api = __esm({
103
448
  "src/api.ts"() {
104
449
  "use strict";
105
450
  init_config();
451
+ init_device();
106
452
  }
107
453
  });
108
454
 
@@ -262,173 +608,6 @@ var init_providers = __esm({
262
608
  }
263
609
  });
264
610
 
265
- // src/dove.ts
266
- var DOVE_LARGE, DOVE_SMALL;
267
- var init_dove = __esm({
268
- "src/dove.ts"() {
269
- "use strict";
270
- DOVE_LARGE = [
271
- "\u2820\u28C4\u2858\u28B6\u28C4\u2840\u28A0\u2840",
272
- "\u2830\u28CC\u28FB\u28F2\u28F3\u289F\u28E6\u28BD\u28D6\u28C4",
273
- "\u2830\u28EC\u2873\u28FD\u28DE\u28DF\u28BE\u289D\u286E\u28DE\u28B5\u28C2",
274
- "\u2800\u28A8\u28DD\u28D7\u28B7\u28BD\u28DD\u28F5\u286B\u286E\u28D3\u288E\u2897\u28A4\u2800\u28C0",
275
- "\u2800\u2800\u28A8\u287A\u286F\u2877\u28F3\u28A7\u28AF\u28AF\u28AE\u2873\u28F1\u28B1\u288D\u289E\u28A6",
276
- "\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",
277
- "\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",
278
- "\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",
279
- "\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",
280
- "\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",
281
- "\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",
282
- "\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",
283
- "\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",
284
- "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28BE\u28FB\u28AE\u28D7\u28DD\u28AE\u286A\u287A\u28F8\u28B8\u28B8\u28B8\u28A8\u28B2\u2841",
285
- "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u283B\u28F3\u2897\u28D7\u2875\u28EB\u287A\u28F8\u28AA\u287A\u285C\u286E\u28FA\u287A\u28E6",
286
- "\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",
287
- "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u2819\u2839\u287D\u28B3\u28FB\u283A\u283D\u280B\u2803"
288
- ];
289
- DOVE_SMALL = [
290
- "\u2890\u28AC\u28F2\u28C4\u2862\u2840",
291
- "\u2828\u28DF\u28DE\u286E\u286F\u286F\u2872\u2840",
292
- "\u2800\u2893\u287D\u287E\u28DD\u286E\u28CF\u288E\u2887\u2896\u2840",
293
- "\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",
294
- "\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",
295
- "\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",
296
- "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u2813\u289D\u28EE\u28FE\u28AF\u28B3\u2879\u28EA\u28F3\u28DD\u286E\u2817\u280B\u2808",
297
- "\u2800\u2800\u2800\u2800\u2820\u28D6\u28D6\u28AE\u287A\u2878\u285D\u287A\u2871\u2815\u2803\u280B\u2803\u2803\u2801",
298
- "\u2800\u2800\u2800\u2800\u2800\u2811\u28EF\u2897\u2875\u28E3\u2873\u28F1\u2895\u286F\u28C2",
299
- "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u281B\u289E\u28AE\u2837\u282F\u281B\u2809"
300
- ];
301
- }
302
- });
303
-
304
- // src/ui.ts
305
- function step(s) {
306
- process.stderr.write(`${c.accent("\u25A0")} ${s}
307
- `);
308
- }
309
- function note(s) {
310
- process.stderr.write(`${c.dim(" " + s)}
311
- `);
312
- }
313
- function ok(s) {
314
- process.stderr.write(`${c.ok("\u2713")} ${s}
315
- `);
316
- }
317
- function warn(s) {
318
- process.stderr.write(`${c.warn("!")} ${s}
319
- `);
320
- }
321
- function table(rows) {
322
- if (rows.length === 0) return "";
323
- const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => width(r[i] ?? ""))));
324
- return rows.map((r) => r.map((cell, i) => i === r.length - 1 ? cell : pad(cell, widths[i])).join(" ")).join("\n") + "\n";
325
- }
326
- function headed(rows) {
327
- if (!rows.length) return "";
328
- const tty = process.stdout.isTTY && color;
329
- return table(tty ? [rows[0].map(label), ...rows.slice(1)] : rows);
330
- }
331
- function when(ms) {
332
- return new Date(ms).toISOString().replace("T", " ").slice(0, 19);
333
- }
334
- function ago(ms) {
335
- if (!ms) return "never";
336
- const s = Math.round((Date.now() - ms) / 1e3);
337
- if (s < 60) return `${s}s ago`;
338
- if (s < 3600) return `${Math.round(s / 60)}m ago`;
339
- if (s < 86400) return `${Math.round(s / 3600)}h ago`;
340
- return `${Math.round(s / 86400)}d ago`;
341
- }
342
- function parseDuration(s) {
343
- const m = /^(\d+)([smhd]?)$/.exec(s.trim());
344
- if (!m) throw new Error(`bad duration: ${s}`);
345
- return Number(m[1]) * { "": 1, s: 1, m: 60, h: 3600, d: 86400 }[m[2]];
346
- }
347
- function banner(lines = [], size = "large") {
348
- if (!color) return lines.length ? lines.join("\n") + "\n" : "";
349
- const cols = process.stderr.columns ?? 80;
350
- const dove = size === "large" && cols >= 92 ? DOVE_LARGE : DOVE_SMALL;
351
- const dw = Math.max(...dove.map((l) => [...l].length));
352
- if (cols < dw + 20) return lines.join("\n") + "\n";
353
- const squares = /* @__PURE__ */ new Map([
354
- [1, [dw + 4, "\u25A0"]],
355
- [Math.floor(dove.length * 0.7), [dw - 6, "\u25AA"]],
356
- [dove.length - 2, [dw + 9, "\u25AB"]]
357
- ]);
358
- const top = Math.max(0, Math.floor((dove.length - lines.length) / 2));
359
- const out2 = [];
360
- for (let i = 0; i < dove.length; i++) {
361
- const d = dove[i];
362
- let row = " " + d + " ".repeat(dw - [...d].length);
363
- const text = lines[i - top];
364
- const sq = squares.get(i);
365
- if (text !== void 0) row += " " + text;
366
- else if (sq) row = row.slice(0, 2 + sq[0]) + " ".repeat(Math.max(0, 2 + sq[0] - width(row))) + c.accent(sq[1]);
367
- out2.push(row);
368
- }
369
- return "\n" + out2.join("\n") + "\n\n";
370
- }
371
- function spin(text) {
372
- if (!color) {
373
- process.stderr.write(`${text}
374
- `);
375
- return (final) => final && process.stderr.write(final + "\n");
376
- }
377
- const frames = "\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F";
378
- let i = 0;
379
- const draw = () => process.stderr.write(`\r\x1B[2K${c.accent(frames[i++ % frames.length])} ${text}`);
380
- draw();
381
- const t = setInterval(draw, 80);
382
- return (final) => {
383
- clearInterval(t);
384
- process.stderr.write(`\r\x1B[2K${final ? final + "\n" : ""}`);
385
- };
386
- }
387
- async function task(label2, fn, done) {
388
- const name = label2.padEnd(16);
389
- const stop = color ? spin(name) : (final) => final && process.stderr.write(final + "\n");
390
- try {
391
- const r = await fn();
392
- stop(`${c.ok("\u2713")} ${name}${c.dim(done ? done(r) : "")}`);
393
- return r;
394
- } catch (err) {
395
- stop(`${c.bad("\u2717")} ${name}`);
396
- const tail = err.stderr;
397
- if (tail) {
398
- const lines = tail.replace(/\x1b\[[0-9;]*m/g, "").split("\n").map((l) => l.trimEnd()).filter((l) => l.trim() && !/^[─┌└│├┐┘]/.test(l));
399
- for (const l of lines.slice(-8)) process.stderr.write(c.dim(` ${l}
400
- `));
401
- }
402
- throw err;
403
- }
404
- }
405
- var env, color, truecolor, sgr, rgb, c, width, pad, label, wordmark;
406
- var init_ui = __esm({
407
- "src/ui.ts"() {
408
- "use strict";
409
- init_dove();
410
- env = process.env;
411
- color = Boolean(process.stderr.isTTY) && !env.NO_COLOR && env.TERM !== "dumb";
412
- truecolor = color && /truecolor|24bit/i.test(env.COLORTERM ?? "");
413
- sgr = (open, close = "\x1B[0m") => (s) => color ? `\x1B[${open}m${s}${close}` : s;
414
- rgb = (r, g, b, fallback) => sgr(truecolor ? `38;2;${r};${g};${b}` : fallback, "\x1B[39m");
415
- c = {
416
- // Cobalt that reads on both light and dark terminals.
417
- accent: rgb(96, 124, 240, "38;5;69"),
418
- ok: rgb(111, 194, 141, "32"),
419
- bad: rgb(232, 120, 100, "31"),
420
- warn: rgb(222, 170, 90, "33"),
421
- dim: sgr("2", "\x1B[22m"),
422
- bold: sgr("1", "\x1B[22m"),
423
- italic: sgr("3", "\x1B[23m")
424
- };
425
- width = (s) => s.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "").length;
426
- pad = (s, n) => s + " ".repeat(Math.max(0, n - width(s)));
427
- label = (s) => c.dim(s.toUpperCase());
428
- wordmark = () => `${c.accent("\u25A0")} ${c.bold("keybox")}`;
429
- }
430
- });
431
-
432
611
  // src/prompt.ts
433
612
  var prompt_exports = {};
434
613
  __export(prompt_exports, {
@@ -1756,11 +1935,11 @@ var init_commands = __esm({
1756
1935
  import { spawn as spawn3 } from "node:child_process";
1757
1936
  import { readFileSync as readFileSync3 } from "node:fs";
1758
1937
  import { createRequire } from "node:module";
1759
- import { dirname, join as join3 } from "node:path";
1938
+ import { dirname as dirname2, join as join3 } from "node:path";
1760
1939
  function bin() {
1761
1940
  const pkgPath = createRequire(import.meta.url).resolve("wrangler/package.json");
1762
1941
  const pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
1763
- return join3(dirname(pkgPath), pkg.bin.wrangler);
1942
+ return join3(dirname2(pkgPath), pkg.bin.wrangler);
1764
1943
  }
1765
1944
  function useAccount(id) {
1766
1945
  accountId = id;
@@ -1894,7 +2073,7 @@ var VERSION;
1894
2073
  var init_version = __esm({
1895
2074
  "src/version.ts"() {
1896
2075
  "use strict";
1897
- VERSION = true ? "0.2.6" : "0.0.0-dev";
2076
+ VERSION = true ? "0.3.1" : "0.0.0-dev";
1898
2077
  }
1899
2078
  });
1900
2079
 
@@ -1909,7 +2088,7 @@ __export(verify_exports, {
1909
2088
  shippedWorkerVersion: () => shippedWorkerVersion,
1910
2089
  verify: () => verify
1911
2090
  });
1912
- import { createHash } from "node:crypto";
2091
+ import { createHash as createHash2 } from "node:crypto";
1913
2092
  import { readFileSync as readFileSync4 } from "node:fs";
1914
2093
  async function liveHealth(url, want, seconds = 30) {
1915
2094
  let last = null;
@@ -2024,6 +2203,7 @@ function printChecks(list2) {
2024
2203
  }
2025
2204
  async function verify(opts) {
2026
2205
  const cfg = requireConfig();
2206
+ if (!isOwnDeployment(cfg)) throw new UserError(`\`keybox verify\` checks the Worker in your own Cloudflare account. ${cfg.url} is run by someone else (for a hosted team, the operator updates it).`);
2027
2207
  const account = await resolveAccount(cfg);
2028
2208
  const list2 = await checks(cfg);
2029
2209
  if (opts.json) {
@@ -2055,7 +2235,7 @@ var init_verify = __esm({
2055
2235
  init_version();
2056
2236
  init_wrangler();
2057
2237
  EXPECTED_BINDINGS = /* @__PURE__ */ new Set(["DB", "KEYBOX_KEK", "KEYBOX_ADMIN_TOKEN_HASH", "KEYBOX_SCRIPT_NAME", "KEYBOX_D1_ID"]);
2058
- shaHex = (b) => createHash("sha256").update(b).digest("hex");
2238
+ shaHex = (b) => createHash2("sha256").update(b).digest("hex");
2059
2239
  shippedWorkerHash = () => shaHex(readFileSync4(new URL("../assets/worker.js", import.meta.url)));
2060
2240
  shippedWorkerVersion = () => /VERSION = "([^"]+)"/.exec(readFileSync4(new URL("../assets/worker.js", import.meta.url), "utf8"))?.[1] ?? VERSION;
2061
2241
  }
@@ -2069,7 +2249,7 @@ __export(deploy_exports, {
2069
2249
  status: () => status
2070
2250
  });
2071
2251
  import { spawn as spawn4 } from "node:child_process";
2072
- import { createHash as createHash2, randomBytes } from "node:crypto";
2252
+ import { createHash as createHash3, randomBytes as randomBytes2 } from "node:crypto";
2073
2253
  import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
2074
2254
  import { join as join4 } from "node:path";
2075
2255
  async function deployWorker(cfg) {
@@ -2083,8 +2263,8 @@ async function deployWorker(cfg) {
2083
2263
  }
2084
2264
  }
2085
2265
  }
2086
- function writeDeployFiles(name, d1Id, accountId2) {
2087
- const dir = deployDir();
2266
+ function writeDeployFiles(name, d1Id, accountId2, key) {
2267
+ const dir = deployDir(key);
2088
2268
  mkdirSync2(join4(dir, "worker"), { recursive: true, mode: 448 });
2089
2269
  copyFileSync(asset("worker.js"), join4(dir, "worker", "worker.js"));
2090
2270
  copyFileSync(asset("schema.sql"), join4(dir, "schema.sql"));
@@ -2137,7 +2317,6 @@ async function pickAccount(accounts, wanted) {
2137
2317
  async function init(opts) {
2138
2318
  const { name } = opts;
2139
2319
  if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name)) throw new UserError("--name must be lowercase letters, digits and dashes.");
2140
- if (loadConfig()) throw new UserError(`Already set up (${configPath()}). Use \`keybox deploy\` to upgrade, or \`keybox verify\` to check it.`);
2141
2320
  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"));
2142
2321
  const major = Number(process.versions.node.split(".")[0]);
2143
2322
  if (major < 20) throw new UserError(`Keybox needs Node 20 or later (you have ${process.versions.node}).`);
@@ -2151,6 +2330,10 @@ async function init(opts) {
2151
2330
  }
2152
2331
  const account = await pickAccount(me.accounts, opts.account);
2153
2332
  useAccount(account.id);
2333
+ const { store } = listProfiles();
2334
+ const dup = Object.entries(store.profiles).find(([, p]) => p.name === name && p.accountId === account.id);
2335
+ if (dup) throw new UserError(`Already set up as "${dup[0]}" (${dup[1].url}). Use \`keybox deploy\` to upgrade, or \`keybox verify\` to check it.`);
2336
+ const deployKey = Object.keys(store.profiles).length ? `deploy-${name}-${account.id.slice(0, 8)}` : "deploy";
2154
2337
  ok(`${"Account".padEnd(16)}${c.dim(`${account.name} ${account.id}`)}`);
2155
2338
  const sub = await cf("/workers/subdomain").catch(() => ({ subdomain: void 0 }));
2156
2339
  if (!sub.subdomain && !opts.url) {
@@ -2185,7 +2368,7 @@ async function init(opts) {
2185
2368
  },
2186
2369
  (r) => `${r.reused ? "reusing" : "created"} ${name}`
2187
2370
  ).then((r) => r.id);
2188
- const cfgPath = writeDeployFiles(name, d1Id, account.id);
2371
+ const cfgPath = writeDeployFiles(name, d1Id, account.id, deployKey);
2189
2372
  await task(
2190
2373
  "Schema",
2191
2374
  () => wrangler(["d1", "execute", name, "--remote", "--yes", "--file", join4(deployDir(), "schema.sql"), "--config", cfgPath], { capture: true, quiet: true }),
@@ -2206,18 +2389,18 @@ async function init(opts) {
2206
2389
  async () => {
2207
2390
  const secrets = parseJson(await wrangler(["secret", "list", "--config", cfgPath, "--format", "json"], { capture: true, quiet: true }));
2208
2391
  if (secrets.some((s) => s.name === "KEYBOX_KEK")) return "kept the existing one";
2209
- await wrangler(["secret", "put", "KEYBOX_KEK", "--config", cfgPath], { input: randomBytes(32).toString("base64"), capture: true, quiet: true });
2392
+ await wrangler(["secret", "put", "KEYBOX_KEK", "--config", cfgPath], { input: randomBytes2(32).toString("base64"), capture: true, quiet: true });
2210
2393
  return "generated and sent to Cloudflare; never written to disk";
2211
2394
  },
2212
2395
  (r) => r
2213
2396
  );
2214
- const adminToken = "kb_adm_" + randomBytes(32).toString("base64url");
2397
+ const adminToken = "kb_adm_" + randomBytes2(32).toString("base64url");
2215
2398
  await task(
2216
2399
  "Admin token",
2217
2400
  async () => {
2218
- const hash = createHash2("sha256").update(adminToken).digest("hex");
2401
+ const hash = createHash3("sha256").update(adminToken).digest("hex");
2219
2402
  await wrangler(["secret", "put", "KEYBOX_ADMIN_TOKEN_HASH", "--config", cfgPath], { input: hash, capture: true, quiet: true });
2220
- saveConfig({ url, adminToken, name, d1Id, accountId: account.id });
2403
+ saveConfig({ url, adminToken, name, d1Id, accountId: account.id, deploy: deployKey }, { as: opts.as });
2221
2404
  },
2222
2405
  () => `saved to ${configPath().replace(process.env.HOME ?? "~", "~")} (mode 600)`
2223
2406
  );
@@ -2264,12 +2447,12 @@ ${c.accent("\u25A0")} Next
2264
2447
  }
2265
2448
  async function deploy(opts) {
2266
2449
  const cfg = requireConfig();
2267
- if (!cfg.d1Id) throw new UserError("`keybox deploy` needs the config written by `keybox init`.");
2450
+ if (!isOwnDeployment(cfg)) throw new UserError(`\`keybox deploy\` replaces a Worker in your own Cloudflare account. ${cfg.url} is run by someone else (for a hosted team, the operator updates it).`);
2268
2451
  await resolveAccount(cfg);
2269
2452
  const dir = deployDir();
2270
- const current = existsSync3(join4(dir, "worker", "worker.js")) ? sha(join4(dir, "worker", "worker.js")) : null;
2453
+ const current2 = existsSync3(join4(dir, "worker", "worker.js")) ? sha(join4(dir, "worker", "worker.js")) : null;
2271
2454
  const next = shippedWorkerHash();
2272
- if (current === next && !opts.force) {
2455
+ if (current2 === next && !opts.force) {
2273
2456
  ok("The deployed Worker already matches this CLI version. Run `keybox verify` to check what Cloudflare is serving.");
2274
2457
  return;
2275
2458
  }
@@ -2277,14 +2460,14 @@ async function deploy(opts) {
2277
2460
  ${c.accent("\u25A0")} This updates the Worker's code. Your stored keys, agents and logs are not touched.
2278
2461
  They live in your D1 database and under your encryption key, and a deploy changes neither.
2279
2462
  The only thing that changes is the code that runs.
2280
- deployed ${c.dim(current ?? "(unknown)")}
2463
+ deployed ${c.dim(current2 ?? "(unknown)")}
2281
2464
  new ${next} ${c.dim(`@keyboxed/cli ${VERSION}`)}
2282
2465
  The new code comes from this copy of @keyboxed/cli. Only continue if you trust it.
2283
2466
 
2284
2467
  `);
2285
2468
  if (!opts.yes && !await confirm("Deploy?")) throw new UserError("Cancelled.");
2286
2469
  const fresh = requireConfig();
2287
- const wranglerCfg = writeDeployFiles(fresh.name, fresh.d1Id, fresh.accountId);
2470
+ const wranglerCfg = writeDeployFiles(fresh.name, fresh.d1Id, fresh.accountId, fresh.deploy);
2288
2471
  await task(
2289
2472
  "Schema",
2290
2473
  () => wrangler(["d1", "execute", fresh.name, "--remote", "--yes", "--file", join4(dir, "schema.sql"), "--config", wranglerCfg], { capture: true, quiet: true }),
@@ -2319,7 +2502,7 @@ var init_deploy = __esm({
2319
2502
  init_wrangler();
2320
2503
  COMPAT_DATE = "2026-07-01";
2321
2504
  asset = (f) => new URL(`../assets/${f}`, import.meta.url).pathname;
2322
- sha = (path) => createHash2("sha256").update(readFileSync5(path)).digest("hex");
2505
+ sha = (path) => createHash3("sha256").update(readFileSync5(path)).digest("hex");
2323
2506
  LATER = [
2324
2507
  ["keybox migrate", "bring keys in from .env, 1Password, Doppler, Vault\u2026"],
2325
2508
  ["keybox secrets add NAME", "add one key (hidden input)"],
@@ -4147,19 +4330,34 @@ __export(extra_exports, {
4147
4330
  accessCloudflare: () => accessCloudflare,
4148
4331
  accessSet: () => accessSet,
4149
4332
  accessShow: () => accessShow,
4333
+ claim: () => claim,
4334
+ devicesAdd: () => devicesAdd,
4335
+ devicesApprove: () => devicesApprove,
4336
+ devicesList: () => devicesList,
4337
+ devicesRevoke: () => devicesRevoke,
4150
4338
  login: () => login,
4339
+ membersAdd: () => membersAdd,
4340
+ membersList: () => membersList,
4341
+ membersLog: () => membersLog,
4342
+ membersRm: () => membersRm,
4343
+ membersRole: () => membersRole,
4151
4344
  pair: () => pair,
4345
+ profilesList: () => profilesList,
4346
+ profilesRm: () => profilesRm,
4152
4347
  qrBlocks: () => qrBlocks,
4153
4348
  skill: () => skill,
4154
- ui: () => ui
4349
+ tokenOff: () => tokenOff,
4350
+ ui: () => ui,
4351
+ use: () => use
4155
4352
  });
4156
4353
  import { spawn as spawn5 } from "node:child_process";
4157
4354
  import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "node:fs";
4158
4355
  import { homedir as homedir3 } from "node:os";
4159
- import { dirname as dirname2, join as join5 } from "node:path";
4160
- async function login(urlArg) {
4161
- const url = (urlArg ?? await ask("Keybox address (https://\u2026)")).trim().replace(/\/+$/, "");
4162
- if (!/^https:\/\/[^/\s]+$/.test(url)) throw new UserError("Give the https:// address of your Keybox, for example https://yourteam.keybox.space.");
4356
+ import { dirname as dirname3, join as join5 } from "node:path";
4357
+ async function login(urlArg, opts = {}) {
4358
+ const url = checkUrl(urlArg ?? await ask("Keybox address (https://\u2026)"));
4359
+ const code = (opts.code ?? process.env.KEYBOX_JOIN_CODE ?? "").trim();
4360
+ if (code) return joinWithCode(url, code, opts.as);
4163
4361
  const token2 = (process.env.KEYBOX_ADMIN_TOKEN ?? await readSecret("Admin token")).trim();
4164
4362
  if (!token2.startsWith("kb_adm_")) throw new UserError("That does not look like an admin token (they start with kb_adm_).");
4165
4363
  let res;
@@ -4170,10 +4368,156 @@ async function login(urlArg) {
4170
4368
  }
4171
4369
  if (res.status === 401 || res.status === 403) throw new UserError("That token was not accepted by this Keybox.");
4172
4370
  if (!res.ok) throw new UserError(`${url} answered HTTP ${res.status}. Is that a Keybox?`);
4173
- saveConfig({ url, adminToken: token2, name: "", d1Id: "" });
4174
- ok(`Connected to ${url}. The token is saved in ~/.config/keybox (mode 600).`);
4371
+ const profile = saveConfig({ url, adminToken: token2, name: "", d1Id: "" }, { as: opts.as });
4372
+ ok(`Connected to ${url} as ${c.bold(profile)}. The token is saved in ~/.config/keybox (mode 600).`);
4373
+ afterConnect(profile);
4374
+ note("Next: `keybox claim` gives this machine its own key, so the shared token can be turned off.");
4375
+ }
4376
+ async function joinWithCode(url, code, as) {
4377
+ const kind = /^kb_(pair|inv|clm)_[A-Za-z0-9_-]{20,}$/.exec(code)?.[1];
4378
+ if (!kind) throw new UserError("That does not look like a join code (they start with kb_pair_, kb_inv_ or kb_clm_).");
4379
+ const memberName = kind === "clm" && process.stdin.isTTY ? await ask("Your name", "owner") : void 0;
4380
+ const key = newDeviceKey();
4381
+ let res;
4382
+ try {
4383
+ res = await fetch(`${url}/_keybox/join`, {
4384
+ method: "POST",
4385
+ headers: { "content-type": "application/json" },
4386
+ body: JSON.stringify({ code, pubkey: key.publicKey, device_name: deviceName(), member_name: memberName })
4387
+ });
4388
+ } catch {
4389
+ throw new UserError(`Could not reach ${url}.`);
4390
+ }
4391
+ const data = await res.json().catch(() => null);
4392
+ if (!res.ok || !data?.device) throw new UserError(data?.error?.message ?? `${url} answered HTTP ${res.status}. Is that a Keybox?`);
4393
+ const profile = saveConfig({ url, deviceId: data.device, deviceKey: key.privateKey, name: "", d1Id: "" }, { as });
4394
+ if (data.pending) {
4395
+ ok(`Joined ${url} as ${c.bold(deviceName())}, saved as ${c.bold(profile)}. This machine's key never left it.`);
4396
+ afterConnect(profile);
4397
+ warn(`Waiting for approval. Ask an owner or admin to run: keybox devices approve ${data.device}`);
4398
+ note("Until then every command here will say the machine is waiting.");
4399
+ return;
4400
+ }
4401
+ ok(`Connected to ${url} as ${c.bold(deviceName())}, saved as ${c.bold(profile)}. This machine's key never left it.`);
4402
+ afterConnect(profile);
4175
4403
  note("Try `keybox ui` for the dashboard, or `keybox secrets add NAME`.");
4176
4404
  }
4405
+ function afterConnect(profile) {
4406
+ const { store } = listProfiles();
4407
+ const others = Object.keys(store.profiles).filter((n) => n !== profile);
4408
+ if (!others.length) return;
4409
+ note(`${c.bold(profile)} is now the default. \`keybox use ${others[0]}\` switches back; \`--profile NAME\` picks one for a single command.`);
4410
+ }
4411
+ async function claim() {
4412
+ const cfg = requireConfig();
4413
+ if (cfg.deviceId) throw new UserError("This machine already has a device key. See `keybox devices`.");
4414
+ if (!cfg.adminToken) throw new UserError("Claiming starts from the admin token. Run `keybox login` first.");
4415
+ const key = newDeviceKey();
4416
+ const name = deviceName();
4417
+ const r = await api("POST", "/claim", { pubkey: key.publicKey, device_name: name });
4418
+ const keepToken = process.env.KEYBOX_ADMIN_TOKEN ? void 0 : cfg.adminToken;
4419
+ saveConfig({ ...cfg, adminToken: keepToken, deviceId: r.device, deviceKey: key.privateKey });
4420
+ ok(`This machine (${c.bold(name)}) is now the owner of ${cfg.url}. Requests are signed with a key that never leaves it.`);
4421
+ note("The shared admin token still works. When you are ready, `keybox token off` turns it off for good.");
4422
+ note("Add a second machine with `keybox devices add`, so losing this one does not lock you out.");
4423
+ }
4424
+ async function devicesList() {
4425
+ const r = await api("GET", "/devices");
4426
+ if (!r.devices.length) {
4427
+ note("No devices yet. `keybox claim` enrols this machine as the owner.");
4428
+ } else {
4429
+ process.stdout.write(
4430
+ headed([
4431
+ ["ID", "MACHINE", "PERSON", "ROLE", "LAST SEEN", ""],
4432
+ ...r.devices.map((d) => [
4433
+ d.id,
4434
+ d.name,
4435
+ d.member,
4436
+ d.role,
4437
+ ago2(d.last_seen),
4438
+ d.revoked_at ? c.dim("revoked") : d.pending ? c.accent("waiting for approval") : d.current ? c.accent("this machine") : ""
4439
+ ])
4440
+ ])
4441
+ );
4442
+ if (r.devices.some((d) => d.pending && !d.revoked_at)) note("Check the machine name and person before approving: `keybox devices approve ID`.");
4443
+ }
4444
+ note(r.legacy_token ? "The shared admin token is still accepted. `keybox token off` turns it off." : "The shared admin token is off.");
4445
+ }
4446
+ async function devicesAdd() {
4447
+ if (!process.stderr.isTTY) throw new UserError("keybox devices add shows a one-time code that enrols a machine as you; run it yourself in a terminal.");
4448
+ const cfg = requireConfig();
4449
+ const { code } = await api("POST", "/devices/pair", {});
4450
+ step("On the other machine, run:");
4451
+ process.stderr.write(`
4452
+ keybox login ${cfg.url} --code ${code}
4453
+
4454
+ `);
4455
+ note("Works once, for 10 minutes. Anyone who has it in that time can enrol a machine as you, so type it yourself.");
4456
+ }
4457
+ async function devicesApprove(id) {
4458
+ await api("POST", `/devices/${encodeURIComponent(id)}/approve`, {});
4459
+ ok(`Approved ${id}. That machine can now use this Keybox with its person's role.`);
4460
+ }
4461
+ async function devicesRevoke(id) {
4462
+ await api("DELETE", `/devices/${encodeURIComponent(id)}`);
4463
+ ok(`Revoked ${id}. That machine can no longer reach this Keybox.`);
4464
+ }
4465
+ async function tokenOff(opts) {
4466
+ const cfg = requireConfig();
4467
+ if (!cfg.deviceId) throw new UserError("Run `keybox claim` first, so this machine has its own key.");
4468
+ note("After this, only device keys work. Anything still using the shared token stops, including the Rust terminal console (`keybox-tui`).");
4469
+ if (!opts.yes && !await confirm("Turn the shared admin token off?", false)) return;
4470
+ await api("POST", "/token/disable", {});
4471
+ if (!process.env.KEYBOX_ADMIN_TOKEN && cfg.adminToken) saveConfig({ ...cfg, adminToken: void 0 });
4472
+ ok("The shared admin token is off, and removed from this machine.");
4473
+ note("To bring it back (break-glass), set the Worker secret KEYBOX_ALLOW_ADMIN_TOKEN to 1.");
4474
+ }
4475
+ function profilesList() {
4476
+ const { store, resolved } = listProfiles();
4477
+ const names = Object.keys(store.profiles).sort();
4478
+ if (!names.length) return note("No connections yet. `keybox init` deploys a Keybox, `keybox login URL` connects to one.");
4479
+ process.stdout.write(
4480
+ headed([
4481
+ ["", "NAME", "ADDRESS", "SIGNED IN WITH", "RUNS ON"],
4482
+ ...names.map((n) => {
4483
+ const p = store.profiles[n];
4484
+ return [n === resolved?.name ? c.accent("\u2192") : "", n, p.url, signedInWith(p), isOwnDeployment(p) ? "your Cloudflare account" : "someone else"];
4485
+ })
4486
+ ])
4487
+ );
4488
+ if (resolved?.source === "project") note(`This folder pins ${resolved.name} (${resolved.file}).`);
4489
+ else if (resolved?.source === "flag" || resolved?.source === "env") note(`${resolved.name} is chosen for this command by ${resolved.source === "flag" ? "--profile" : "KEYBOX_PROFILE"}.`);
4490
+ else note("\u2192 is the default. `keybox use NAME` changes it, `keybox use --here` pins this folder, `--profile NAME` picks one for one command.");
4491
+ }
4492
+ function use(name, opts) {
4493
+ const { store, resolved } = listProfiles();
4494
+ const pick = name ?? (opts.here ? resolved?.name : void 0);
4495
+ if (!pick || !store.profiles[pick]) {
4496
+ if (pick) throw new UserError(`No connection called ${pick}. See \`keybox profiles\`.`);
4497
+ throw new UserError("Usage: keybox use NAME (or keybox use --here NAME to pin this folder)");
4498
+ }
4499
+ const p = store.profiles[pick];
4500
+ if (opts.here) {
4501
+ const file = pinFolder(process.cwd(), p.url);
4502
+ ok(`This folder uses ${c.bold(pick)} (${p.url}).`);
4503
+ note(`Written to ${file}. It holds only the address, so commit it and everyone who is connected to that Keybox gets the same one here. It can never connect anyone to a new Keybox.`);
4504
+ return;
4505
+ }
4506
+ setCurrent(pick);
4507
+ ok(`Using ${c.bold(pick)} (${p.url}) everywhere except folders that pin another.`);
4508
+ }
4509
+ async function profilesRm(name, yes) {
4510
+ if (!name) throw new UserError("Usage: keybox profiles rm NAME");
4511
+ const { store } = listProfiles();
4512
+ const p = store.profiles[name];
4513
+ if (!p) throw new UserError(`No connection called ${name}. See \`keybox profiles\`.`);
4514
+ if (!yes) {
4515
+ warn(`This forgets ${p.url} on this machine. The ${p.deviceKey ? "device key" : "admin token"} saved for it may exist nowhere else. The Keybox itself is not touched.`);
4516
+ if (!process.stdin.isTTY || !await confirm(`Forget ${name}?`, false)) throw new UserError("Nothing changed. Use --yes to forget it without asking.");
4517
+ }
4518
+ removeProfile(name);
4519
+ ok(`Forgot ${name}.`);
4520
+ }
4177
4521
  function openBrowser(url) {
4178
4522
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
4179
4523
  const args = process.platform === "win32" ? ["/c", "start", '""', url] : [url];
@@ -4201,7 +4545,7 @@ async function ui(opts) {
4201
4545
  function qrBlocks(text) {
4202
4546
  const qr = (0, import_qrcode.create)(text, { errorCorrectionLevel: "M" });
4203
4547
  const n = qr.modules.size;
4204
- const q = 2;
4548
+ const q = 4;
4205
4549
  const dark = (x, y) => x >= 0 && y >= 0 && x < n && y < n && Boolean(qr.modules.get(y, x));
4206
4550
  const out2 = [];
4207
4551
  for (let y = -q; y < n + q; y += 2) {
@@ -4225,6 +4569,7 @@ async function pair() {
4225
4569
  step(`Scan this with the Keybox app ${c.dim("(Pair \u203A Scan QR code)")}`);
4226
4570
  process.stderr.write("\n" + qrBlocks(url) + "\n");
4227
4571
  note("Works once, for 2 minutes. The app gets a 12-hour session; your admin token stays on this machine.");
4572
+ note("Camera will not read it? Make the terminal window bigger or zoom out, or run `keybox ui --print` and paste that link into the app.");
4228
4573
  note("To end every dashboard and app session: Access \u203A Sign out every dashboard session.");
4229
4574
  }
4230
4575
  async function accessShow() {
@@ -4312,22 +4657,80 @@ async function skill(opts) {
4312
4657
  const path = targets[t];
4313
4658
  if (!path) throw new UserError(`Unknown target ${t}. Use claude, codex, agents or all (or --print).`);
4314
4659
  const existed = existsSync4(path);
4315
- mkdirSync3(dirname2(path), { recursive: true });
4660
+ mkdirSync3(dirname3(path), { recursive: true });
4316
4661
  writeFileSync3(path, text);
4317
4662
  ok(`${existed ? "Updated" : "Installed"} ${path}`);
4318
4663
  }
4319
4664
  step("Agents that load skills now know how to set up Keybox, migrate keys and write narrow rules safely.");
4320
4665
  note('Ask yours: "set up keybox for this project".');
4321
4666
  }
4322
- var import_qrcode, describe, skillAsset;
4667
+ async function membersList() {
4668
+ const r = await api("GET", "/members");
4669
+ process.stdout.write(
4670
+ headed([
4671
+ ["ID", "NAME", "ROLE", "MACHINES", ""],
4672
+ ...r.map((m) => [m.id, m.name, m.role, String(m.devices), [m.pending ? c.accent(`${m.pending} waiting for approval`) : "", m.invited ? c.dim("invited, not joined") : ""].filter(Boolean).join(", ")])
4673
+ ])
4674
+ );
4675
+ note("Roles: owner runs everything. admin runs keys and policy. member runs their own agents and tokens, and cannot change keys.");
4676
+ }
4677
+ async function membersAdd(name, opts) {
4678
+ const cfg = requireConfig();
4679
+ const r = await api("POST", "/members", { name, role: opts.role ?? "member" });
4680
+ step(`Invited ${c.bold(name)} as ${r.role}. They run:`);
4681
+ process.stderr.write(`
4682
+ keybox login ${cfg.url} --code ${r.code}
4683
+
4684
+ `);
4685
+ note("Valid 24 hours, works once. Their machine then waits for you: `keybox devices` shows it, `keybox devices approve ID` lets it in.");
4686
+ }
4687
+ async function membersRole(who, role) {
4688
+ if (role !== "admin" && role !== "member") throw new UserError("Usage: keybox members role NAME admin|member");
4689
+ const list2 = await api("GET", "/members");
4690
+ const m = list2.find((x) => x.id === who || x.name.toLowerCase() === who.toLowerCase());
4691
+ if (!m) throw new UserError(`No member called ${who}. See \`keybox members\`.`);
4692
+ await api("PATCH", `/members/${encodeURIComponent(m.id)}`, { role });
4693
+ ok(`${m.name} is now ${role === "admin" ? "an admin: can add and change keys and policy" : "a member: can run their own agents and tokens, not change keys"}.`);
4694
+ note("Their open dashboard sessions ended; they sign in again with `keybox ui`.");
4695
+ }
4696
+ async function membersRm(who) {
4697
+ const list2 = await api("GET", "/members");
4698
+ const m = list2.find((x) => x.id === who || x.name.toLowerCase() === who.toLowerCase());
4699
+ if (!m) throw new UserError(`No member called ${who}. See \`keybox members\`.`);
4700
+ await api("DELETE", `/members/${encodeURIComponent(m.id)}`);
4701
+ ok(`Removed ${m.name}. Their machines and dashboard sessions are revoked.`);
4702
+ }
4703
+ async function membersLog(limit) {
4704
+ const r = await api("GET", `/events?limit=${limit}`);
4705
+ if (!r.length) return note("Nothing yet.");
4706
+ process.stdout.write(
4707
+ headed([
4708
+ ["WHEN", "WHO", "MACHINE", "WHAT"],
4709
+ ...r.map((e) => [ago2(e.ts), e.member ?? (e.via === "token" ? c.dim("shared token") : c.dim(e.via)), e.device ?? "", e.action])
4710
+ ])
4711
+ );
4712
+ }
4713
+ var import_qrcode, checkUrl, ago2, signedInWith, describe, skillAsset;
4323
4714
  var init_extra = __esm({
4324
4715
  "src/extra.ts"() {
4325
4716
  "use strict";
4326
4717
  import_qrcode = __toESM(require_qrcode(), 1);
4327
4718
  init_api();
4328
4719
  init_config();
4720
+ init_device();
4329
4721
  init_prompt();
4330
4722
  init_ui();
4723
+ checkUrl = (u) => {
4724
+ const url = u.trim().replace(/\/+$/, "");
4725
+ if (!/^https:\/\/[^/\s]+$/.test(url)) throw new UserError("Give the https:// address of your Keybox, for example https://yourteam.keybox.space.");
4726
+ return url;
4727
+ };
4728
+ ago2 = (ms) => {
4729
+ if (!ms) return "never";
4730
+ const s = Math.round((Date.now() - ms) / 1e3);
4731
+ return s < 60 ? "just now" : s < 3600 ? `${Math.round(s / 60)}m ago` : s < 86400 ? `${Math.round(s / 3600)}h ago` : `${Math.round(s / 86400)}d ago`;
4732
+ };
4733
+ signedInWith = (p) => p.deviceKey ? "device key" : p.adminToken ? "admin token" : c.dim("nothing saved");
4331
4734
  describe = (r) => {
4332
4735
  if (!r || !Object.keys(r).length) return c.dim("any network");
4333
4736
  const parts2 = [];
@@ -4435,7 +4838,7 @@ import { existsSync as existsSync5 } from "node:fs";
4435
4838
  import { delimiter, join as join6 } from "node:path";
4436
4839
  var TABS = ["Activity", "Secrets", "Agents"];
4437
4840
  var out = process.stdout;
4438
- var ago2 = (ms) => {
4841
+ var ago3 = (ms) => {
4439
4842
  if (!ms) return "never";
4440
4843
  const s = Math.round((Date.now() - ms) / 1e3);
4441
4844
  return s < 60 ? `${s}s` : s < 3600 ? `${Math.round(s / 60)}m` : s < 86400 ? `${Math.round(s / 3600)}h` : `${Math.round(s / 86400)}d`;
@@ -4469,11 +4872,10 @@ function nativeTui() {
4469
4872
  }
4470
4873
  async function tui(opts = {}) {
4471
4874
  if (!process.stdin.isTTY || !out.isTTY) throw new UserError("keybox tui needs an interactive terminal. Try `keybox status` or `keybox audit -f`.");
4472
- const native = opts.basic ? null : nativeTui();
4875
+ const native = opts.basic || !requireConfig().adminToken ? null : nativeTui();
4473
4876
  if (native) {
4474
- requireConfig();
4475
4877
  const code = await new Promise((resolve) => {
4476
- const child = spawn6(native, [], { stdio: "inherit" });
4878
+ const child = spawn6(native, [], { stdio: "inherit", env: { ...process.env, KEYBOX_PROFILE: resolveProfile()?.name ?? "" } });
4477
4879
  child.on("error", () => resolve(-1));
4478
4880
  child.on("close", (c2) => resolve(c2 ?? 1));
4479
4881
  });
@@ -4511,12 +4913,12 @@ async function tui(opts = {}) {
4511
4913
  const res = r.decision === "allow" ? String(r.status) : r.decision.toUpperCase();
4512
4914
  const col = r.decision === "allow" && r.status < 400 ? c.ok(res.padEnd(5)) : c.bad(res.padEnd(5));
4513
4915
  const req = `${r.method} ${r.host ?? ""}${r.path ?? ""}`;
4514
- 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 ?? "")}`;
4916
+ return `${c.dim(ago3(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 ?? "")}`;
4515
4917
  });
4516
4918
  }
4517
4919
  if (st.tab === 1) {
4518
4920
  return st.secrets.map(
4519
- (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))}`
4921
+ (s) => `${c.bold(s.name.padEnd(26))} ${s.hosts.join(",").padEnd(30).slice(0, 30)} ${c.dim((s.fingerprint ?? "-").padEnd(13))} ${c.dim("used " + ago3(s.last_used))}`
4520
4922
  );
4521
4923
  }
4522
4924
  return st.agents.flatMap((a) => [
@@ -4660,12 +5062,12 @@ init_verify();
4660
5062
  init_version();
4661
5063
  import { spawn as spawn7, spawnSync as spawnSync2 } from "node:child_process";
4662
5064
  import { existsSync as existsSync6, realpathSync } from "node:fs";
4663
- import { dirname as dirname3, join as join7 } from "node:path";
5065
+ import { dirname as dirname4, join as join7 } from "node:path";
4664
5066
  import { fileURLToPath } from "node:url";
4665
5067
  function howInstalled() {
4666
5068
  const self = realpathSync(fileURLToPath(import.meta.url));
4667
5069
  if (self.includes(`${join7("_npx", "")}`) || self.includes("/_npx/")) return { kind: "npx" };
4668
- const root = dirname3(dirname3(dirname3(self)));
5070
+ const root = dirname4(dirname4(dirname4(self)));
4669
5071
  if (existsSync6(join7(root, ".git")) && existsSync6(join7(root, "cli", "package.json"))) return { kind: "checkout", root };
4670
5072
  if (self.includes(join7("node_modules", "@keyboxed", "cli"))) return { kind: "npm-global" };
4671
5073
  return { kind: "unknown", path: self };
@@ -4743,6 +5145,7 @@ async function update(opts) {
4743
5145
  async function updateWorker(opts) {
4744
5146
  const cfg = loadConfig();
4745
5147
  if (!cfg) return note("No Keybox set up on this machine yet. Run `keybox init`.");
5148
+ if (!isOwnDeployment(cfg)) return note(`${cfg.url} is run by someone else, so there is no Worker of yours to update (for a hosted team, the operator updates it). \`keybox profiles\` lists the others.`);
4746
5149
  let deployedVersion = "?";
4747
5150
  try {
4748
5151
  deployedVersion = (await (await fetch(`${cfg.url}/_keybox/health`)).json()).version;
@@ -4766,8 +5169,19 @@ init_verify();
4766
5169
  init_ui();
4767
5170
  init_version();
4768
5171
  var HELP_BODY = `Setup
4769
- keybox init [--account ID] [--name keybox] Deploy Keybox to your Cloudflare account
4770
- keybox login [URL] Connect to a Keybox someone else runs (a hosted team)
5172
+ keybox init [--account ID] [--name keybox] [--as NAME]
5173
+ Deploy Keybox to your Cloudflare account
5174
+ keybox login [URL] [--code CODE] [--as NAME]
5175
+ Connect to a Keybox someone else runs (a hosted team)
5176
+ keybox profiles [rm NAME] The Keyboxes this machine knows; \u2192 marks the default
5177
+ keybox use NAME | --here [NAME] Switch the default, or pin this folder to one (.keybox.json)
5178
+ (any command) --profile NAME Use another Keybox for just that command
5179
+ keybox claim Give this machine its own key (becomes the owner)
5180
+ keybox members [add NAME [--role member|admin] | role NAME admin|member | rm NAME | log]
5181
+ People on this Keybox: invite, remove, and who changed what
5182
+ keybox devices [list|add|approve ID|revoke ID]
5183
+ Machines that can manage this Keybox; add one with a one-time code
5184
+ keybox token off [--yes] Turn the shared admin token off; only device keys work after
4771
5185
  keybox update [--check] [--yes] Update the CLI, then the deployed Worker, then verify
4772
5186
  keybox verify [--json] Check Cloudflare is running exactly this CLI's code
4773
5187
  keybox deploy [--yes] Replace the deployed Worker with this CLI's version
@@ -4877,6 +5291,11 @@ async function main(argv) {
4877
5291
  version: { type: "boolean", short: "v", default: false },
4878
5292
  follow: { type: "boolean", short: "f", default: false },
4879
5293
  limit: { type: "string", default: "50" },
5294
+ code: { type: "string" },
5295
+ role: { type: "string" },
5296
+ profile: { type: "string", short: "p" },
5297
+ as: { type: "string" },
5298
+ here: { type: "boolean", default: false },
4880
5299
  help: { type: "boolean", short: "h", default: false }
4881
5300
  }
4882
5301
  });
@@ -4886,11 +5305,12 @@ async function main(argv) {
4886
5305
  return v;
4887
5306
  };
4888
5307
  if (o.version) return void process.stdout.write(VERSION + "\n");
5308
+ useProfile(o.profile);
4889
5309
  if (o.verbose) process.env.KEYBOX_VERBOSE = "1";
4890
5310
  if (o.help || !group) return void process.stdout.write(help());
4891
- switch (`${group} ${["secrets", "agents", "tokens", "access", "skill"].includes(group) ? sub ?? "" : ""}`.trim()) {
5311
+ switch (`${group} ${["secrets", "agents", "tokens", "access", "skill", "devices", "token", "members", "profiles"].includes(group) ? sub ?? "" : ""}`.trim()) {
4892
5312
  case "init":
4893
- return init({ name: o.name, url: o.url, account: o.account, yes: o.yes });
5313
+ return init({ name: o.name, url: o.url, account: o.account, yes: o.yes, as: o.as });
4894
5314
  case "verify":
4895
5315
  return verify({ json: o.json });
4896
5316
  case "update":
@@ -4898,7 +5318,38 @@ async function main(argv) {
4898
5318
  case "deploy":
4899
5319
  return deploy({ yes: o.yes, force: o.force });
4900
5320
  case "login":
4901
- return login(sub);
5321
+ return login(sub, { code: o.code, as: o.as });
5322
+ case "profiles":
5323
+ case "profiles list":
5324
+ return profilesList();
5325
+ case "profiles rm":
5326
+ return profilesRm(arg, o.yes);
5327
+ case "use":
5328
+ return use(sub, { here: o.here });
5329
+ case "claim":
5330
+ return claim();
5331
+ case "devices":
5332
+ case "devices list":
5333
+ return devicesList();
5334
+ case "devices add":
5335
+ return devicesAdd();
5336
+ case "devices approve":
5337
+ return devicesApprove(need(arg, "device id"));
5338
+ case "members":
5339
+ case "members list":
5340
+ return membersList();
5341
+ case "members add":
5342
+ return membersAdd(need(arg, "name"), { role: o.role });
5343
+ case "members role":
5344
+ return membersRole(need(arg, "name"), p[3]);
5345
+ case "members rm":
5346
+ return membersRm(need(arg, "name or id"));
5347
+ case "members log":
5348
+ return membersLog(Number(o.limit));
5349
+ case "devices revoke":
5350
+ return devicesRevoke(need(arg, "device id"));
5351
+ case "token off":
5352
+ return tokenOff({ yes: o.yes });
4902
5353
  case "status":
4903
5354
  return status();
4904
5355
  case "ui":