@keyboxed/cli 0.3.0 → 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/assets/worker.js CHANGED
@@ -46,7 +46,7 @@ async function verifyAccess(jwt, cfg) {
46
46
  }
47
47
 
48
48
  // src/types.ts
49
- var VERSION = "0.3.0";
49
+ var VERSION = "0.3.1";
50
50
  function keyboxError(status, code, message) {
51
51
  return Response.json({ type: "error", error: { type: "keybox_error", code, message } }, { status });
52
52
  }
@@ -510,6 +510,20 @@ async function removeMember(env, who, id) {
510
510
  ]);
511
511
  return Response.json({ removed: true });
512
512
  }
513
+ async function setRole(req, env, who, id) {
514
+ check(roleOf(who) === "owner", "Only an owner can change a role.");
515
+ const b = await body(req);
516
+ check(b.role === "admin" || b.role === "member", "role is admin or member");
517
+ const m = await env.DB.prepare("SELECT id AS member_id, role FROM members WHERE id = ? AND role != 'removed'").bind(id).first();
518
+ check(m, "No such member.");
519
+ check(m.role !== "owner", "An owner keeps the owner role. Remove them to change that.");
520
+ check(m.member_id !== who.member, "You cannot change your own role.");
521
+ await env.DB.batch([
522
+ env.DB.prepare("UPDATE members SET role = ? WHERE id = ?").bind(b.role, id),
523
+ env.DB.prepare("DELETE FROM sessions WHERE kind LIKE '%:' || ?").bind(id)
524
+ ]);
525
+ return Response.json({ id, role: b.role });
526
+ }
513
527
  async function logEvent(env, who, method, path) {
514
528
  await env.DB.prepare("INSERT INTO events (ts, member_id, device_id, via, action) VALUES (?, ?, ?, ?, ?)").bind(Date.now(), who.member ?? null, who.device ?? null, who.via, `${method} ${path}`.slice(0, 200)).run().catch(() => {
515
529
  });
@@ -831,6 +845,7 @@ async function route(req, env, path, policy, who) {
831
845
  if (a === "members" && !b && m === "GET") return listMembers(env);
832
846
  if (a === "members" && !b && m === "POST") return invite(req, env, who);
833
847
  if (a === "members" && b && !c && m === "DELETE") return removeMember(env, who, b);
848
+ if (a === "members" && b && !c && m === "PATCH") return setRole(req, env, who, b);
834
849
  if (a === "events" && !b && m === "GET") return listEvents(req, env);
835
850
  if (a === "policy" && !b && m === "GET") return Response.json(policy);
836
851
  if (a === "policy" && !b && m === "PUT") {
package/dist/keybox.js CHANGED
@@ -41,48 +41,356 @@ 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");
53
284
  if (env2.KEYBOX_URL && env2.KEYBOX_DEVICE_ID && env2.KEYBOX_DEVICE_KEY) {
54
- return { url: env2.KEYBOX_URL, deviceId: env2.KEYBOX_DEVICE_ID, deviceKey: env2.KEYBOX_DEVICE_KEY, name: env2.KEYBOX_NAME ?? "keybox", d1Id: "" };
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
+ };
55
290
  }
56
291
  if (env2.KEYBOX_URL && env2.KEYBOX_ADMIN_TOKEN) {
57
292
  return {
58
- url: env2.KEYBOX_URL,
59
- adminToken: env2.KEYBOX_ADMIN_TOKEN,
60
- name: env2.KEYBOX_NAME ?? "keybox",
61
- d1Id: "",
62
- 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 }
63
296
  };
64
297
  }
65
- if (!existsSync(configPath())) return null;
66
- 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.`);
67
311
  }
68
- function requireConfig() {
69
- const c2 = loadConfig();
70
- if (!c2) throw new UserError("Not set up yet. Run `keybox init` first.");
71
- return c2;
312
+ function current() {
313
+ try {
314
+ return resolveProfile();
315
+ } catch {
316
+ return null;
317
+ }
72
318
  }
73
- function saveConfig(c2) {
74
- mkdirSync(configDir(), { recursive: true, mode: 448 });
75
- writeFileSync(configPath(), JSON.stringify(c2, null, 2) + "\n", { mode: 384 });
76
- chmodSync(configPath(), 384);
319
+ function loadConfig() {
320
+ return resolveProfile()?.config ?? null;
77
321
  }
78
- var configPath, deployDir, UserError;
322
+ function requireConfig() {
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;
331
+ }
332
+ function listProfiles() {
333
+ return { store: readStore(), resolved: current() };
334
+ }
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;
79
382
  var init_config = __esm({
80
383
  "src/config.ts"() {
81
384
  "use strict";
82
- configPath = () => join(configDir(), "config.json");
83
- deployDir = () => join(configDir(), "deploy");
385
+ init_ui();
386
+ PROFILE = /^[a-z0-9][a-z0-9-]{0,30}$/;
387
+ PIN_FILE = ".keybox.json";
84
388
  UserError = class extends Error {
85
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);
86
394
  }
87
395
  });
88
396
 
@@ -300,173 +608,6 @@ var init_providers = __esm({
300
608
  }
301
609
  });
302
610
 
303
- // src/dove.ts
304
- var DOVE_LARGE, DOVE_SMALL;
305
- var init_dove = __esm({
306
- "src/dove.ts"() {
307
- "use strict";
308
- DOVE_LARGE = [
309
- "\u2820\u28C4\u2858\u28B6\u28C4\u2840\u28A0\u2840",
310
- "\u2830\u28CC\u28FB\u28F2\u28F3\u289F\u28E6\u28BD\u28D6\u28C4",
311
- "\u2830\u28EC\u2873\u28FD\u28DE\u28DF\u28BE\u289D\u286E\u28DE\u28B5\u28C2",
312
- "\u2800\u28A8\u28DD\u28D7\u28B7\u28BD\u28DD\u28F5\u286B\u286E\u28D3\u288E\u2897\u28A4\u2800\u28C0",
313
- "\u2800\u2800\u28A8\u287A\u286F\u2877\u28F3\u28A7\u28AF\u28AF\u28AE\u2873\u28F1\u28B1\u288D\u289E\u28A6",
314
- "\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",
315
- "\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",
316
- "\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",
317
- "\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",
318
- "\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",
319
- "\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",
320
- "\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",
321
- "\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",
322
- "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28BE\u28FB\u28AE\u28D7\u28DD\u28AE\u286A\u287A\u28F8\u28B8\u28B8\u28B8\u28A8\u28B2\u2841",
323
- "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u283B\u28F3\u2897\u28D7\u2875\u28EB\u287A\u28F8\u28AA\u287A\u285C\u286E\u28FA\u287A\u28E6",
324
- "\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",
325
- "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u2819\u2839\u287D\u28B3\u28FB\u283A\u283D\u280B\u2803"
326
- ];
327
- DOVE_SMALL = [
328
- "\u2890\u28AC\u28F2\u28C4\u2862\u2840",
329
- "\u2828\u28DF\u28DE\u286E\u286F\u286F\u2872\u2840",
330
- "\u2800\u2893\u287D\u287E\u28DD\u286E\u28CF\u288E\u2887\u2896\u2840",
331
- "\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",
332
- "\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",
333
- "\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",
334
- "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u2813\u289D\u28EE\u28FE\u28AF\u28B3\u2879\u28EA\u28F3\u28DD\u286E\u2817\u280B\u2808",
335
- "\u2800\u2800\u2800\u2800\u2820\u28D6\u28D6\u28AE\u287A\u2878\u285D\u287A\u2871\u2815\u2803\u280B\u2803\u2803\u2801",
336
- "\u2800\u2800\u2800\u2800\u2800\u2811\u28EF\u2897\u2875\u28E3\u2873\u28F1\u2895\u286F\u28C2",
337
- "\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u281B\u289E\u28AE\u2837\u282F\u281B\u2809"
338
- ];
339
- }
340
- });
341
-
342
- // src/ui.ts
343
- function step(s) {
344
- process.stderr.write(`${c.accent("\u25A0")} ${s}
345
- `);
346
- }
347
- function note(s) {
348
- process.stderr.write(`${c.dim(" " + s)}
349
- `);
350
- }
351
- function ok(s) {
352
- process.stderr.write(`${c.ok("\u2713")} ${s}
353
- `);
354
- }
355
- function warn(s) {
356
- process.stderr.write(`${c.warn("!")} ${s}
357
- `);
358
- }
359
- function table(rows) {
360
- if (rows.length === 0) return "";
361
- const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => width(r[i] ?? ""))));
362
- return rows.map((r) => r.map((cell, i) => i === r.length - 1 ? cell : pad(cell, widths[i])).join(" ")).join("\n") + "\n";
363
- }
364
- function headed(rows) {
365
- if (!rows.length) return "";
366
- const tty = process.stdout.isTTY && color;
367
- return table(tty ? [rows[0].map(label), ...rows.slice(1)] : rows);
368
- }
369
- function when(ms) {
370
- return new Date(ms).toISOString().replace("T", " ").slice(0, 19);
371
- }
372
- function ago(ms) {
373
- if (!ms) return "never";
374
- const s = Math.round((Date.now() - ms) / 1e3);
375
- if (s < 60) return `${s}s ago`;
376
- if (s < 3600) return `${Math.round(s / 60)}m ago`;
377
- if (s < 86400) return `${Math.round(s / 3600)}h ago`;
378
- return `${Math.round(s / 86400)}d ago`;
379
- }
380
- function parseDuration(s) {
381
- const m = /^(\d+)([smhd]?)$/.exec(s.trim());
382
- if (!m) throw new Error(`bad duration: ${s}`);
383
- return Number(m[1]) * { "": 1, s: 1, m: 60, h: 3600, d: 86400 }[m[2]];
384
- }
385
- function banner(lines = [], size = "large") {
386
- if (!color) return lines.length ? lines.join("\n") + "\n" : "";
387
- const cols = process.stderr.columns ?? 80;
388
- const dove = size === "large" && cols >= 92 ? DOVE_LARGE : DOVE_SMALL;
389
- const dw = Math.max(...dove.map((l) => [...l].length));
390
- if (cols < dw + 20) return lines.join("\n") + "\n";
391
- const squares = /* @__PURE__ */ new Map([
392
- [1, [dw + 4, "\u25A0"]],
393
- [Math.floor(dove.length * 0.7), [dw - 6, "\u25AA"]],
394
- [dove.length - 2, [dw + 9, "\u25AB"]]
395
- ]);
396
- const top = Math.max(0, Math.floor((dove.length - lines.length) / 2));
397
- const out2 = [];
398
- for (let i = 0; i < dove.length; i++) {
399
- const d = dove[i];
400
- let row = " " + d + " ".repeat(dw - [...d].length);
401
- const text = lines[i - top];
402
- const sq = squares.get(i);
403
- if (text !== void 0) row += " " + text;
404
- else if (sq) row = row.slice(0, 2 + sq[0]) + " ".repeat(Math.max(0, 2 + sq[0] - width(row))) + c.accent(sq[1]);
405
- out2.push(row);
406
- }
407
- return "\n" + out2.join("\n") + "\n\n";
408
- }
409
- function spin(text) {
410
- if (!color) {
411
- process.stderr.write(`${text}
412
- `);
413
- return (final) => final && process.stderr.write(final + "\n");
414
- }
415
- const frames = "\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F";
416
- let i = 0;
417
- const draw = () => process.stderr.write(`\r\x1B[2K${c.accent(frames[i++ % frames.length])} ${text}`);
418
- draw();
419
- const t = setInterval(draw, 80);
420
- return (final) => {
421
- clearInterval(t);
422
- process.stderr.write(`\r\x1B[2K${final ? final + "\n" : ""}`);
423
- };
424
- }
425
- async function task(label2, fn, done) {
426
- const name = label2.padEnd(16);
427
- const stop = color ? spin(name) : (final) => final && process.stderr.write(final + "\n");
428
- try {
429
- const r = await fn();
430
- stop(`${c.ok("\u2713")} ${name}${c.dim(done ? done(r) : "")}`);
431
- return r;
432
- } catch (err) {
433
- stop(`${c.bad("\u2717")} ${name}`);
434
- const tail = err.stderr;
435
- if (tail) {
436
- const lines = tail.replace(/\x1b\[[0-9;]*m/g, "").split("\n").map((l) => l.trimEnd()).filter((l) => l.trim() && !/^[─┌└│├┐┘]/.test(l));
437
- for (const l of lines.slice(-8)) process.stderr.write(c.dim(` ${l}
438
- `));
439
- }
440
- throw err;
441
- }
442
- }
443
- var env, color, truecolor, sgr, rgb, c, width, pad, label, wordmark;
444
- var init_ui = __esm({
445
- "src/ui.ts"() {
446
- "use strict";
447
- init_dove();
448
- env = process.env;
449
- color = Boolean(process.stderr.isTTY) && !env.NO_COLOR && env.TERM !== "dumb";
450
- truecolor = color && /truecolor|24bit/i.test(env.COLORTERM ?? "");
451
- sgr = (open, close = "\x1B[0m") => (s) => color ? `\x1B[${open}m${s}${close}` : s;
452
- rgb = (r, g, b, fallback) => sgr(truecolor ? `38;2;${r};${g};${b}` : fallback, "\x1B[39m");
453
- c = {
454
- // Cobalt that reads on both light and dark terminals.
455
- accent: rgb(96, 124, 240, "38;5;69"),
456
- ok: rgb(111, 194, 141, "32"),
457
- bad: rgb(232, 120, 100, "31"),
458
- warn: rgb(222, 170, 90, "33"),
459
- dim: sgr("2", "\x1B[22m"),
460
- bold: sgr("1", "\x1B[22m"),
461
- italic: sgr("3", "\x1B[23m")
462
- };
463
- width = (s) => s.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "").length;
464
- pad = (s, n) => s + " ".repeat(Math.max(0, n - width(s)));
465
- label = (s) => c.dim(s.toUpperCase());
466
- wordmark = () => `${c.accent("\u25A0")} ${c.bold("keybox")}`;
467
- }
468
- });
469
-
470
611
  // src/prompt.ts
471
612
  var prompt_exports = {};
472
613
  __export(prompt_exports, {
@@ -1794,11 +1935,11 @@ var init_commands = __esm({
1794
1935
  import { spawn as spawn3 } from "node:child_process";
1795
1936
  import { readFileSync as readFileSync3 } from "node:fs";
1796
1937
  import { createRequire } from "node:module";
1797
- import { dirname, join as join3 } from "node:path";
1938
+ import { dirname as dirname2, join as join3 } from "node:path";
1798
1939
  function bin() {
1799
1940
  const pkgPath = createRequire(import.meta.url).resolve("wrangler/package.json");
1800
1941
  const pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
1801
- return join3(dirname(pkgPath), pkg.bin.wrangler);
1942
+ return join3(dirname2(pkgPath), pkg.bin.wrangler);
1802
1943
  }
1803
1944
  function useAccount(id) {
1804
1945
  accountId = id;
@@ -1932,7 +2073,7 @@ var VERSION;
1932
2073
  var init_version = __esm({
1933
2074
  "src/version.ts"() {
1934
2075
  "use strict";
1935
- VERSION = true ? "0.3.0" : "0.0.0-dev";
2076
+ VERSION = true ? "0.3.1" : "0.0.0-dev";
1936
2077
  }
1937
2078
  });
1938
2079
 
@@ -2062,6 +2203,7 @@ function printChecks(list2) {
2062
2203
  }
2063
2204
  async function verify(opts) {
2064
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).`);
2065
2207
  const account = await resolveAccount(cfg);
2066
2208
  const list2 = await checks(cfg);
2067
2209
  if (opts.json) {
@@ -2121,8 +2263,8 @@ async function deployWorker(cfg) {
2121
2263
  }
2122
2264
  }
2123
2265
  }
2124
- function writeDeployFiles(name, d1Id, accountId2) {
2125
- const dir = deployDir();
2266
+ function writeDeployFiles(name, d1Id, accountId2, key) {
2267
+ const dir = deployDir(key);
2126
2268
  mkdirSync2(join4(dir, "worker"), { recursive: true, mode: 448 });
2127
2269
  copyFileSync(asset("worker.js"), join4(dir, "worker", "worker.js"));
2128
2270
  copyFileSync(asset("schema.sql"), join4(dir, "schema.sql"));
@@ -2175,7 +2317,6 @@ async function pickAccount(accounts, wanted) {
2175
2317
  async function init(opts) {
2176
2318
  const { name } = opts;
2177
2319
  if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name)) throw new UserError("--name must be lowercase letters, digits and dashes.");
2178
- if (loadConfig()) throw new UserError(`Already set up (${configPath()}). Use \`keybox deploy\` to upgrade, or \`keybox verify\` to check it.`);
2179
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"));
2180
2321
  const major = Number(process.versions.node.split(".")[0]);
2181
2322
  if (major < 20) throw new UserError(`Keybox needs Node 20 or later (you have ${process.versions.node}).`);
@@ -2189,6 +2330,10 @@ async function init(opts) {
2189
2330
  }
2190
2331
  const account = await pickAccount(me.accounts, opts.account);
2191
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";
2192
2337
  ok(`${"Account".padEnd(16)}${c.dim(`${account.name} ${account.id}`)}`);
2193
2338
  const sub = await cf("/workers/subdomain").catch(() => ({ subdomain: void 0 }));
2194
2339
  if (!sub.subdomain && !opts.url) {
@@ -2223,7 +2368,7 @@ async function init(opts) {
2223
2368
  },
2224
2369
  (r) => `${r.reused ? "reusing" : "created"} ${name}`
2225
2370
  ).then((r) => r.id);
2226
- const cfgPath = writeDeployFiles(name, d1Id, account.id);
2371
+ const cfgPath = writeDeployFiles(name, d1Id, account.id, deployKey);
2227
2372
  await task(
2228
2373
  "Schema",
2229
2374
  () => wrangler(["d1", "execute", name, "--remote", "--yes", "--file", join4(deployDir(), "schema.sql"), "--config", cfgPath], { capture: true, quiet: true }),
@@ -2255,7 +2400,7 @@ async function init(opts) {
2255
2400
  async () => {
2256
2401
  const hash = createHash3("sha256").update(adminToken).digest("hex");
2257
2402
  await wrangler(["secret", "put", "KEYBOX_ADMIN_TOKEN_HASH", "--config", cfgPath], { input: hash, capture: true, quiet: true });
2258
- saveConfig({ url, adminToken, name, d1Id, accountId: account.id });
2403
+ saveConfig({ url, adminToken, name, d1Id, accountId: account.id, deploy: deployKey }, { as: opts.as });
2259
2404
  },
2260
2405
  () => `saved to ${configPath().replace(process.env.HOME ?? "~", "~")} (mode 600)`
2261
2406
  );
@@ -2302,12 +2447,12 @@ ${c.accent("\u25A0")} Next
2302
2447
  }
2303
2448
  async function deploy(opts) {
2304
2449
  const cfg = requireConfig();
2305
- 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).`);
2306
2451
  await resolveAccount(cfg);
2307
2452
  const dir = deployDir();
2308
- 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;
2309
2454
  const next = shippedWorkerHash();
2310
- if (current === next && !opts.force) {
2455
+ if (current2 === next && !opts.force) {
2311
2456
  ok("The deployed Worker already matches this CLI version. Run `keybox verify` to check what Cloudflare is serving.");
2312
2457
  return;
2313
2458
  }
@@ -2315,14 +2460,14 @@ async function deploy(opts) {
2315
2460
  ${c.accent("\u25A0")} This updates the Worker's code. Your stored keys, agents and logs are not touched.
2316
2461
  They live in your D1 database and under your encryption key, and a deploy changes neither.
2317
2462
  The only thing that changes is the code that runs.
2318
- deployed ${c.dim(current ?? "(unknown)")}
2463
+ deployed ${c.dim(current2 ?? "(unknown)")}
2319
2464
  new ${next} ${c.dim(`@keyboxed/cli ${VERSION}`)}
2320
2465
  The new code comes from this copy of @keyboxed/cli. Only continue if you trust it.
2321
2466
 
2322
2467
  `);
2323
2468
  if (!opts.yes && !await confirm("Deploy?")) throw new UserError("Cancelled.");
2324
2469
  const fresh = requireConfig();
2325
- const wranglerCfg = writeDeployFiles(fresh.name, fresh.d1Id, fresh.accountId);
2470
+ const wranglerCfg = writeDeployFiles(fresh.name, fresh.d1Id, fresh.accountId, fresh.deploy);
2326
2471
  await task(
2327
2472
  "Schema",
2328
2473
  () => wrangler(["d1", "execute", fresh.name, "--remote", "--yes", "--file", join4(dir, "schema.sql"), "--config", wranglerCfg], { capture: true, quiet: true }),
@@ -4195,20 +4340,24 @@ __export(extra_exports, {
4195
4340
  membersList: () => membersList,
4196
4341
  membersLog: () => membersLog,
4197
4342
  membersRm: () => membersRm,
4343
+ membersRole: () => membersRole,
4198
4344
  pair: () => pair,
4345
+ profilesList: () => profilesList,
4346
+ profilesRm: () => profilesRm,
4199
4347
  qrBlocks: () => qrBlocks,
4200
4348
  skill: () => skill,
4201
4349
  tokenOff: () => tokenOff,
4202
- ui: () => ui
4350
+ ui: () => ui,
4351
+ use: () => use
4203
4352
  });
4204
4353
  import { spawn as spawn5 } from "node:child_process";
4205
4354
  import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "node:fs";
4206
4355
  import { homedir as homedir3 } from "node:os";
4207
- import { dirname as dirname2, join as join5 } from "node:path";
4356
+ import { dirname as dirname3, join as join5 } from "node:path";
4208
4357
  async function login(urlArg, opts = {}) {
4209
4358
  const url = checkUrl(urlArg ?? await ask("Keybox address (https://\u2026)"));
4210
4359
  const code = (opts.code ?? process.env.KEYBOX_JOIN_CODE ?? "").trim();
4211
- if (code) return joinWithCode(url, code);
4360
+ if (code) return joinWithCode(url, code, opts.as);
4212
4361
  const token2 = (process.env.KEYBOX_ADMIN_TOKEN ?? await readSecret("Admin token")).trim();
4213
4362
  if (!token2.startsWith("kb_adm_")) throw new UserError("That does not look like an admin token (they start with kb_adm_).");
4214
4363
  let res;
@@ -4219,11 +4368,12 @@ async function login(urlArg, opts = {}) {
4219
4368
  }
4220
4369
  if (res.status === 401 || res.status === 403) throw new UserError("That token was not accepted by this Keybox.");
4221
4370
  if (!res.ok) throw new UserError(`${url} answered HTTP ${res.status}. Is that a Keybox?`);
4222
- saveConfig({ url, adminToken: token2, name: "", d1Id: "" });
4223
- 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);
4224
4374
  note("Next: `keybox claim` gives this machine its own key, so the shared token can be turned off.");
4225
4375
  }
4226
- async function joinWithCode(url, code) {
4376
+ async function joinWithCode(url, code, as) {
4227
4377
  const kind = /^kb_(pair|inv|clm)_[A-Za-z0-9_-]{20,}$/.exec(code)?.[1];
4228
4378
  if (!kind) throw new UserError("That does not look like a join code (they start with kb_pair_, kb_inv_ or kb_clm_).");
4229
4379
  const memberName = kind === "clm" && process.stdin.isTTY ? await ask("Your name", "owner") : void 0;
@@ -4240,16 +4390,24 @@ async function joinWithCode(url, code) {
4240
4390
  }
4241
4391
  const data = await res.json().catch(() => null);
4242
4392
  if (!res.ok || !data?.device) throw new UserError(data?.error?.message ?? `${url} answered HTTP ${res.status}. Is that a Keybox?`);
4243
- saveConfig({ url, deviceId: data.device, deviceKey: key.privateKey, name: "", d1Id: "" });
4393
+ const profile = saveConfig({ url, deviceId: data.device, deviceKey: key.privateKey, name: "", d1Id: "" }, { as });
4244
4394
  if (data.pending) {
4245
- ok(`Joined ${url} as ${c.bold(deviceName())}. This machine's key never left it.`);
4395
+ ok(`Joined ${url} as ${c.bold(deviceName())}, saved as ${c.bold(profile)}. This machine's key never left it.`);
4396
+ afterConnect(profile);
4246
4397
  warn(`Waiting for approval. Ask an owner or admin to run: keybox devices approve ${data.device}`);
4247
4398
  note("Until then every command here will say the machine is waiting.");
4248
4399
  return;
4249
4400
  }
4250
- ok(`Connected to ${url} as ${c.bold(deviceName())}. This machine's key never left it.`);
4401
+ ok(`Connected to ${url} as ${c.bold(deviceName())}, saved as ${c.bold(profile)}. This machine's key never left it.`);
4402
+ afterConnect(profile);
4251
4403
  note("Try `keybox ui` for the dashboard, or `keybox secrets add NAME`.");
4252
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
+ }
4253
4411
  async function claim() {
4254
4412
  const cfg = requireConfig();
4255
4413
  if (cfg.deviceId) throw new UserError("This machine already has a device key. See `keybox devices`.");
@@ -4314,6 +4472,52 @@ async function tokenOff(opts) {
4314
4472
  ok("The shared admin token is off, and removed from this machine.");
4315
4473
  note("To bring it back (break-glass), set the Worker secret KEYBOX_ALLOW_ADMIN_TOKEN to 1.");
4316
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
+ }
4317
4521
  function openBrowser(url) {
4318
4522
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
4319
4523
  const args = process.platform === "win32" ? ["/c", "start", '""', url] : [url];
@@ -4453,7 +4657,7 @@ async function skill(opts) {
4453
4657
  const path = targets[t];
4454
4658
  if (!path) throw new UserError(`Unknown target ${t}. Use claude, codex, agents or all (or --print).`);
4455
4659
  const existed = existsSync4(path);
4456
- mkdirSync3(dirname2(path), { recursive: true });
4660
+ mkdirSync3(dirname3(path), { recursive: true });
4457
4661
  writeFileSync3(path, text);
4458
4662
  ok(`${existed ? "Updated" : "Installed"} ${path}`);
4459
4663
  }
@@ -4480,6 +4684,15 @@ async function membersAdd(name, opts) {
4480
4684
  `);
4481
4685
  note("Valid 24 hours, works once. Their machine then waits for you: `keybox devices` shows it, `keybox devices approve ID` lets it in.");
4482
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
+ }
4483
4696
  async function membersRm(who) {
4484
4697
  const list2 = await api("GET", "/members");
4485
4698
  const m = list2.find((x) => x.id === who || x.name.toLowerCase() === who.toLowerCase());
@@ -4497,7 +4710,7 @@ async function membersLog(limit) {
4497
4710
  ])
4498
4711
  );
4499
4712
  }
4500
- var import_qrcode, checkUrl, ago2, describe, skillAsset;
4713
+ var import_qrcode, checkUrl, ago2, signedInWith, describe, skillAsset;
4501
4714
  var init_extra = __esm({
4502
4715
  "src/extra.ts"() {
4503
4716
  "use strict";
@@ -4517,6 +4730,7 @@ var init_extra = __esm({
4517
4730
  const s = Math.round((Date.now() - ms) / 1e3);
4518
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`;
4519
4732
  };
4733
+ signedInWith = (p) => p.deviceKey ? "device key" : p.adminToken ? "admin token" : c.dim("nothing saved");
4520
4734
  describe = (r) => {
4521
4735
  if (!r || !Object.keys(r).length) return c.dim("any network");
4522
4736
  const parts2 = [];
@@ -4661,7 +4875,7 @@ async function tui(opts = {}) {
4661
4875
  const native = opts.basic || !requireConfig().adminToken ? null : nativeTui();
4662
4876
  if (native) {
4663
4877
  const code = await new Promise((resolve) => {
4664
- const child = spawn6(native, [], { stdio: "inherit" });
4878
+ const child = spawn6(native, [], { stdio: "inherit", env: { ...process.env, KEYBOX_PROFILE: resolveProfile()?.name ?? "" } });
4665
4879
  child.on("error", () => resolve(-1));
4666
4880
  child.on("close", (c2) => resolve(c2 ?? 1));
4667
4881
  });
@@ -4848,12 +5062,12 @@ init_verify();
4848
5062
  init_version();
4849
5063
  import { spawn as spawn7, spawnSync as spawnSync2 } from "node:child_process";
4850
5064
  import { existsSync as existsSync6, realpathSync } from "node:fs";
4851
- import { dirname as dirname3, join as join7 } from "node:path";
5065
+ import { dirname as dirname4, join as join7 } from "node:path";
4852
5066
  import { fileURLToPath } from "node:url";
4853
5067
  function howInstalled() {
4854
5068
  const self = realpathSync(fileURLToPath(import.meta.url));
4855
5069
  if (self.includes(`${join7("_npx", "")}`) || self.includes("/_npx/")) return { kind: "npx" };
4856
- const root = dirname3(dirname3(dirname3(self)));
5070
+ const root = dirname4(dirname4(dirname4(self)));
4857
5071
  if (existsSync6(join7(root, ".git")) && existsSync6(join7(root, "cli", "package.json"))) return { kind: "checkout", root };
4858
5072
  if (self.includes(join7("node_modules", "@keyboxed", "cli"))) return { kind: "npm-global" };
4859
5073
  return { kind: "unknown", path: self };
@@ -4931,6 +5145,7 @@ async function update(opts) {
4931
5145
  async function updateWorker(opts) {
4932
5146
  const cfg = loadConfig();
4933
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.`);
4934
5149
  let deployedVersion = "?";
4935
5150
  try {
4936
5151
  deployedVersion = (await (await fetch(`${cfg.url}/_keybox/health`)).json()).version;
@@ -4954,10 +5169,15 @@ init_verify();
4954
5169
  init_ui();
4955
5170
  init_version();
4956
5171
  var HELP_BODY = `Setup
4957
- keybox init [--account ID] [--name keybox] Deploy Keybox to your Cloudflare account
4958
- keybox login [URL] [--code kb_pair_\u2026] 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
4959
5179
  keybox claim Give this machine its own key (becomes the owner)
4960
- keybox members [add NAME [--role member|admin] | rm NAME | log]
5180
+ keybox members [add NAME [--role member|admin] | role NAME admin|member | rm NAME | log]
4961
5181
  People on this Keybox: invite, remove, and who changed what
4962
5182
  keybox devices [list|add|approve ID|revoke ID]
4963
5183
  Machines that can manage this Keybox; add one with a one-time code
@@ -5073,6 +5293,9 @@ async function main(argv) {
5073
5293
  limit: { type: "string", default: "50" },
5074
5294
  code: { type: "string" },
5075
5295
  role: { type: "string" },
5296
+ profile: { type: "string", short: "p" },
5297
+ as: { type: "string" },
5298
+ here: { type: "boolean", default: false },
5076
5299
  help: { type: "boolean", short: "h", default: false }
5077
5300
  }
5078
5301
  });
@@ -5082,11 +5305,12 @@ async function main(argv) {
5082
5305
  return v;
5083
5306
  };
5084
5307
  if (o.version) return void process.stdout.write(VERSION + "\n");
5308
+ useProfile(o.profile);
5085
5309
  if (o.verbose) process.env.KEYBOX_VERBOSE = "1";
5086
5310
  if (o.help || !group) return void process.stdout.write(help());
5087
- switch (`${group} ${["secrets", "agents", "tokens", "access", "skill", "devices", "token", "members"].includes(group) ? sub ?? "" : ""}`.trim()) {
5311
+ switch (`${group} ${["secrets", "agents", "tokens", "access", "skill", "devices", "token", "members", "profiles"].includes(group) ? sub ?? "" : ""}`.trim()) {
5088
5312
  case "init":
5089
- 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 });
5090
5314
  case "verify":
5091
5315
  return verify({ json: o.json });
5092
5316
  case "update":
@@ -5094,7 +5318,14 @@ async function main(argv) {
5094
5318
  case "deploy":
5095
5319
  return deploy({ yes: o.yes, force: o.force });
5096
5320
  case "login":
5097
- return login(sub, { code: o.code });
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 });
5098
5329
  case "claim":
5099
5330
  return claim();
5100
5331
  case "devices":
@@ -5109,6 +5340,8 @@ async function main(argv) {
5109
5340
  return membersList();
5110
5341
  case "members add":
5111
5342
  return membersAdd(need(arg, "name"), { role: o.role });
5343
+ case "members role":
5344
+ return membersRole(need(arg, "name"), p[3]);
5112
5345
  case "members rm":
5113
5346
  return membersRm(need(arg, "name or id"));
5114
5347
  case "members log":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keyboxed/cli",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Give AI agents access to your APIs without giving them your keys.",
5
5
  "homepage": "https://keybox.space",
6
6
  "license": "FSL-1.1-ALv2",