@keyboxed/cli 0.3.2 → 0.3.4

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
@@ -389,6 +389,12 @@ var init_config = __esm({
389
389
  PROFILE = /^[a-z0-9][a-z0-9-]{0,30}$/;
390
390
  PIN_FILE = ".keybox.json";
391
391
  UserError = class extends Error {
392
+ /** Process exit code: 1 by default; 3 still waiting for approval, 4 denied or expired. */
393
+ constructor(message, exitCode = 1) {
394
+ super(message);
395
+ this.exitCode = exitCode;
396
+ }
397
+ exitCode;
392
398
  };
393
399
  configPath = () => join(configDir(), "config.json");
394
400
  sameUrl = (a, b) => a.replace(/\/+$/, "").toLowerCase() === b.replace(/\/+$/, "").toLowerCase();
@@ -445,13 +451,135 @@ async function api(method, path, body, config = requireConfig()) {
445
451
  }
446
452
  const data = await res.json().catch(() => null);
447
453
  if (!res.ok) throw new UserError(data?.error?.message ?? `Keybox returned HTTP ${res.status}.`);
454
+ if (res.status === 202 && data && typeof data.approval === "string") return waitForApproval(data, config);
448
455
  return data;
449
456
  }
457
+ function setApprovalWait(on) {
458
+ wait = on;
459
+ }
460
+ async function waitForApproval(p, config) {
461
+ const out2 = process.stderr;
462
+ out2.write(`Needs approval on your phone: ${p.summary.text}
463
+ `);
464
+ for (const f of p.summary.flags ?? []) out2.write(` ! ${f}
465
+ `);
466
+ if (!wait) throw new UserError(`Waiting for approval: ${p.approval}. Check with \`keybox approvals show ${p.approval}\`.`, STILL_PENDING);
467
+ out2.write(`Waiting for ${p.approval}\u2026 (Ctrl-C leaves it pending)
468
+ `);
469
+ const until = Math.min(p.expires_at, Date.now() + 5 * 6e4);
470
+ while (Date.now() < until + 2e3) {
471
+ await sleep(2e3);
472
+ let v;
473
+ try {
474
+ v = await api("GET", `/approvals/${encodeURIComponent(p.approval)}`, void 0, config);
475
+ } catch {
476
+ continue;
477
+ }
478
+ if (v.status === "executed") {
479
+ out2.write(`Approved by ${v.decided_by ?? "an approver"}.
480
+ `);
481
+ return v.result;
482
+ }
483
+ if (v.status === "failed") throw new UserError(`Approved, but it did not run: ${v.note ?? `HTTP ${v.result_status}`}`);
484
+ if (["denied", "cancelled", "expired"].includes(v.status)) throw new UserError(`Not done: the request was ${v.status}.`, NOT_APPROVED);
485
+ }
486
+ throw new UserError(`Still waiting for approval: ${p.approval}. Check with \`keybox approvals show ${p.approval}\`.`, STILL_PENDING);
487
+ }
488
+ var wait, STILL_PENDING, NOT_APPROVED, sleep;
450
489
  var init_api = __esm({
451
490
  "src/api.ts"() {
452
491
  "use strict";
453
492
  init_config();
454
493
  init_device();
494
+ wait = true;
495
+ STILL_PENDING = 3;
496
+ NOT_APPROVED = 4;
497
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms));
498
+ }
499
+ });
500
+
501
+ // src/approvals.ts
502
+ async function approvalsList(all) {
503
+ const list2 = await api("GET", `/approvals${all ? "" : "?status=pending"}`);
504
+ if (!list2.length) {
505
+ note(all ? "No approval requests yet." : "Nothing is waiting for approval. `keybox approvals list --all` shows past requests.");
506
+ return;
507
+ }
508
+ process.stdout.write(
509
+ headed([
510
+ ["ID", "STATUS", "WHAT", "FROM", "WHEN"],
511
+ ...list2.map((a) => [a.id, statusOf(a), a.summary.text, who(a), ago(a.created_at)])
512
+ ])
513
+ );
514
+ if (list2.some((a) => a.status === "pending")) note("Approve or deny in the Keybox app on your phone. `keybox approvals cancel ID` withdraws your own request.");
515
+ }
516
+ async function approvalsShow(id) {
517
+ const a = await api("GET", `/approvals/${encodeURIComponent(id)}`);
518
+ const row = (k, v) => `${c.dim(k.padEnd(10))} ${v}
519
+ `;
520
+ let out2 = row("request", a.summary.text) + row("status", statusOf(a)) + row("call", `${a.method} ${a.path}`) + row("from", `${who(a)}${a.ip ? ` ${a.ip}` : ""}${a.country ? ` (${a.country})` : ""}`) + row("asked", when(a.created_at)) + (a.status === "pending" ? row("expires", when(a.expires_at)) : "") + (a.decided_by ? row("decided", `${a.decided_by}, ${a.decided_at ? when(a.decided_at) : ""}`) : "") + (a.summary.fingerprint ? row("key", `fingerprint ${a.summary.fingerprint}`) : "") + (a.note ? row("note", a.note) : "");
521
+ for (const r of a.summary.rules ?? []) out2 += row("rule", r);
522
+ for (const f of a.summary.flags ?? []) out2 += row("warning", c.warn(f));
523
+ process.stdout.write(out2);
524
+ if (a.result !== void 0) note("This request ran. Its result was handed to the command that asked for it, once; it is not shown again.");
525
+ }
526
+ async function approvalsCancel(id) {
527
+ await api("DELETE", `/approvals/${encodeURIComponent(id)}`);
528
+ ok(`Cancelled ${id}. Nothing was changed.`);
529
+ }
530
+ function statusOf(a) {
531
+ if (a.status === "pending") return c.accent("waiting");
532
+ if (a.status === "executed") return "done";
533
+ if (a.status === "failed") return c.warn("failed");
534
+ return c.dim(a.status);
535
+ }
536
+ function who(a) {
537
+ return [a.requester.member, a.requester.device].filter(Boolean).join(" / ") || a.requester.via;
538
+ }
539
+ async function approversList() {
540
+ const list2 = await api("GET", "/approvers");
541
+ if (!list2.length) {
542
+ note("No approvers yet. In the Keybox app on your phone, open Approvals and add this phone. That also turns approvals on.");
543
+ return;
544
+ }
545
+ process.stdout.write(headed([["ID", "NAME", "PERSON", "ADDED"], ...list2.map((a) => [a.id, a.name, a.member ?? "owner", when(a.created_at)])]));
546
+ if (list2.length === 1) note("One approver. Add a second phone or a spare, so losing this one does not lock you out of changes.");
547
+ }
548
+ async function approversRm(id) {
549
+ const r = await api("DELETE", `/approvers/${encodeURIComponent(id)}`);
550
+ if (!r.removed) throw new UserError(`No approver ${id}.`);
551
+ ok(`Removed approver ${id}.`);
552
+ }
553
+ async function stepupShow() {
554
+ const s = await api("GET", "/stepup");
555
+ const row = (k, v) => `${c.dim(k.padEnd(10))} ${v}
556
+ `;
557
+ process.stdout.write(
558
+ row("approvals", s.on ? c.accent("on") : "off") + row("approvers", s.approvers) + row("expire", `${s.ttl_minutes} minutes`) + (s.break_glass ? row("warning", c.warn("KEYBOX_STEPUP_OFF is set on the Worker, so approvals are off regardless.")) : "")
559
+ );
560
+ if (!s.on) {
561
+ step("With approvals off, anything holding this machine\u2019s admin credential can rebind a key to another host and so disclose it.");
562
+ note(s.approvers ? "Turn them on with `keybox stepup on`." : "Add your phone as an approver in the Keybox app; that turns them on.");
563
+ }
564
+ }
565
+ async function stepupSet(on) {
566
+ const s = await api("PUT", "/stepup", { on });
567
+ ok(s.on ? "Approvals are on. Adding access or moving a key now needs your phone." : "Approvals are off.");
568
+ }
569
+ async function stepupLine() {
570
+ try {
571
+ const s = await api("GET", "/stepup");
572
+ return s.on ? `on (${s.approvers} approver${s.approvers === 1 ? "" : "s"})` : c.warn("off (keybox stepup)");
573
+ } catch {
574
+ return null;
575
+ }
576
+ }
577
+ var init_approvals = __esm({
578
+ "src/approvals.ts"() {
579
+ "use strict";
580
+ init_api();
581
+ init_config();
582
+ init_ui();
455
583
  }
456
584
  });
457
585
 
@@ -639,6 +767,11 @@ var init_providers = __esm({
639
767
  },
640
768
  { id: "cloudflare", label: "Cloudflare", hosts: ["api.cloudflare.com"], header: "authorization", format: "bearer", prefixes: ["CLOUDFLARE_", "CF_"], pattern: "^cf[a-z]t_" },
641
769
  { id: "gemini", label: "Google Gemini", hosts: ["generativelanguage.googleapis.com"], header: "x-goog-api-key", format: "raw", prefixes: ["GEMINI_", "GOOGLE_AI_", "GOOGLE_GENERATIVE_AI_", "GOOGLE_API_"], pattern: "^AIza[0-9A-Za-z_-]{35}$" },
770
+ // Keys that go outside a header. The ones with fields hold several values, so they have no prefixes:
771
+ // migration never picks them for a single variable, only `--preset` does.
772
+ { id: "google-maps", label: "Google Maps Platform", hosts: ["maps.googleapis.com"], header: "query:key", format: "raw", prefixes: [] },
773
+ { id: "sapling", label: "Sapling", hosts: ["api.sapling.ai"], header: "body:key", format: "raw", prefixes: ["SAPLING_"] },
774
+ { id: "sightengine", label: "Sightengine", hosts: ["api.sightengine.com"], header: "query:api_user=user,query:api_secret=secret", format: "raw", prefixes: [] },
642
775
  { id: "groq", label: "Groq", hosts: ["api.groq.com"], header: "authorization", format: "bearer", prefixes: ["GROQ_"], pattern: "^gsk_" },
643
776
  { id: "mistral", label: "Mistral", hosts: ["api.mistral.ai"], header: "authorization", format: "bearer", prefixes: ["MISTRAL_"] },
644
777
  { id: "xai", label: "xAI", hosts: ["api.x.ai"], header: "authorization", format: "bearer", prefixes: ["XAI_", "GROK_"], pattern: "^xai-" },
@@ -757,6 +890,67 @@ var init_suggest = __esm({
757
890
  }
758
891
  });
759
892
 
893
+ // ../shared/inject.ts
894
+ function parseInjection(spec) {
895
+ const s = spec.trim();
896
+ if (!s || s.length > 512) throw new Error("say where the key goes: a header name, query:NAME or body:NAME");
897
+ if (HEADER.test(s)) return [checkHeader({ where: "header", name: s.toLowerCase() })];
898
+ const out2 = [];
899
+ for (const part of s.split(",")) {
900
+ const m = /^(header|query|body):([^=\s]+)(?:=([^=\s]+))?$/.exec(part.trim());
901
+ if (!m) throw new Error(`not a place for a key: "${part.trim()}" (use header:NAME, query:NAME or body:NAME, optionally =FIELD)`);
902
+ const [, where, rawName, field] = m;
903
+ if (field !== void 0 && !FIELD.test(field)) throw new Error(`field names are lowercase letters, digits and _: "${field}"`);
904
+ let inj = { where, name: rawName, ...field ? { field } : {} };
905
+ if (where === "header") inj = checkHeader({ ...inj, name: rawName.toLowerCase() });
906
+ else if (!PARAM.test(rawName)) throw new Error(`not a plain ${where === "query" ? "parameter" : "field"} name: "${rawName}"`);
907
+ out2.push(inj);
908
+ }
909
+ if (out2.length > MAX_PLACES) throw new Error(`a key can go in at most ${MAX_PLACES} places`);
910
+ const seen = new Set(out2.map((i) => `${i.where}:${i.name}`));
911
+ if (seen.size !== out2.length) throw new Error("the same place is named twice");
912
+ const withField = out2.filter((i) => i.field).length;
913
+ if (withField && withField !== out2.length) throw new Error("name a field for every place, or for none");
914
+ if (!withField && out2.length > 1) throw new Error("to send a key to several places, give each a field: header:a=id,header:b=secret");
915
+ return out2;
916
+ }
917
+ function checkHeader(i) {
918
+ if (!HEADER.test(i.name)) throw new Error(`not a plain header name: "${i.name}"`);
919
+ if (FORBIDDEN_HEADERS.has(i.name)) throw new Error(`cannot put a key in ${i.name}`);
920
+ return i;
921
+ }
922
+ function formatInjection(list2) {
923
+ if (list2.length === 1 && list2[0].where === "header" && !list2[0].field) return list2[0].name;
924
+ return list2.map((i) => `${i.where}:${i.name}${i.field ? `=${i.field}` : ""}`).join(",");
925
+ }
926
+ function fieldsOf(list2) {
927
+ return [...new Set(list2.flatMap((i) => i.field ? [i.field] : []))];
928
+ }
929
+ function describeInjection(spec, format) {
930
+ let list2;
931
+ try {
932
+ list2 = parseInjection(spec);
933
+ } catch {
934
+ return spec;
935
+ }
936
+ const one = (i) => {
937
+ const at = i.where === "header" ? i.name : i.where === "query" ? `?${i.name}` : `body.${i.name}`;
938
+ return i.field ? `${at}\u2190${i.field}` : at;
939
+ };
940
+ const places = list2.map(one).join(" ");
941
+ return list2.every((i) => i.where === "header") ? `${places} (${format})` : places;
942
+ }
943
+ var HEADER, PARAM, FIELD, FORBIDDEN_HEADERS, MAX_PLACES;
944
+ var init_inject = __esm({
945
+ "../shared/inject.ts"() {
946
+ HEADER = /^[A-Za-z0-9-]{1,64}$/;
947
+ PARAM = /^[A-Za-z0-9_.\-[\]]{1,64}$/;
948
+ FIELD = /^[a-z][a-z0-9_]{0,31}$/;
949
+ FORBIDDEN_HEADERS = /* @__PURE__ */ new Set(["host", "content-length", "content-type", "transfer-encoding", "connection", "cookie", "upgrade", "x-keybox-token", "x-keybox-secret"]);
950
+ MAX_PLACES = 8;
951
+ }
952
+ });
953
+
760
954
  // ../worker/src/policy.ts
761
955
  function parseRule(source, opts = {}) {
762
956
  const m = RULE.exec(source.trim());
@@ -1889,25 +2083,69 @@ __export(commands_exports, {
1889
2083
  audit: () => audit,
1890
2084
  blocked: () => blocked,
1891
2085
  buildGrants: () => buildGrants2,
2086
+ placesFrom: () => placesFrom,
1892
2087
  run: () => run,
1893
2088
  secretsAdd: () => secretsAdd,
1894
2089
  secretsBind: () => secretsBind,
2090
+ secretsCombine: () => secretsCombine,
1895
2091
  secretsImport: () => secretsImport,
1896
2092
  secretsList: () => secretsList,
1897
2093
  secretsRm: () => secretsRm,
1898
2094
  tokensRevoke: () => tokensRevoke
1899
2095
  });
1900
2096
  import { spawn as spawn2 } from "node:child_process";
2097
+ function placesFrom(opts) {
2098
+ const parts2 = [
2099
+ ...(opts.header ?? []).map((h) => `header:${h}`),
2100
+ ...(opts.param ?? []).map((q) => `query:${q}`),
2101
+ ...(opts.bodyField ?? []).map((b) => `body:${b}`)
2102
+ ];
2103
+ if (!parts2.length) return null;
2104
+ let places;
2105
+ try {
2106
+ places = parseInjection(parts2.length === 1 && opts.header?.length === 1 && !opts.header[0].includes("=") ? opts.header[0] : parts2.join(","));
2107
+ } catch (err) {
2108
+ throw new UserError(err.message);
2109
+ }
2110
+ const headerOnly = places.every((i) => i.where === "header");
2111
+ const format = opts.format ?? (headerOnly ? "bearer" : "raw");
2112
+ if (!headerOnly && format !== "raw") throw new UserError("A key sent in the query or body goes as it is; drop --format or use --format raw.");
2113
+ return { header: formatInjection(places), format, places };
2114
+ }
2115
+ async function readFields(name, fields) {
2116
+ if (!process.stdin.isTTY) {
2117
+ const raw = await readSecret(name, name);
2118
+ try {
2119
+ const obj = JSON.parse(raw);
2120
+ if (obj && typeof obj === "object" && !Array.isArray(obj)) return JSON.stringify(obj);
2121
+ } catch {
2122
+ }
2123
+ throw new UserError(`${name} has fields (${fields.join(", ")}). Pipe a JSON object such as {"${fields[0]}":"\u2026"}, or run this at a terminal to be asked for each.`);
2124
+ }
2125
+ const out2 = {};
2126
+ for (const f of fields) {
2127
+ out2[f] = await readSecret(`${name}.${f}`, "");
2128
+ if (!out2[f]) throw new UserError(`No value given for ${f}.`);
2129
+ }
2130
+ return JSON.stringify(out2);
2131
+ }
1901
2132
  async function secretsAdd(name, opts) {
1902
2133
  if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(name)) throw new UserError("Secret names are UPPER_SNAKE_CASE, e.g. OPENAI_API_KEY.");
1903
2134
  let spec = null;
1904
- if (opts.host?.length) {
1905
- spec = { hosts: opts.host, header: opts.header ?? "authorization", format: opts.format ?? "bearer" };
1906
- } else if (opts.preset) {
2135
+ const placed = placesFrom(opts);
2136
+ if (opts.preset) {
1907
2137
  spec = PRESETS[opts.preset] ?? null;
1908
2138
  if (!spec) throw new UserError(`Unknown preset ${opts.preset}. Known: ${Object.keys(PRESETS).join(", ")}.`);
1909
- }
1910
- const value = opts.from ? await readRef(opts.from) : await readSecret(`${name}`, name);
2139
+ if (opts.host?.length) spec = { ...spec, hosts: opts.host };
2140
+ if (placed) spec = { ...spec, header: placed.header, format: placed.format };
2141
+ } else if (opts.host?.length) {
2142
+ spec = { hosts: opts.host, header: placed?.header ?? "authorization", format: placed?.format ?? (opts.format ?? "bearer") };
2143
+ } else if (placed) {
2144
+ throw new UserError("Say which host it goes to as well: --host HOST.");
2145
+ }
2146
+ const fields = spec ? fieldsOf(parseInjection(spec.header)) : [];
2147
+ if (fields.length && opts.from) throw new UserError(`${name} has fields (${fields.join(", ")}); --from reads one value. Store each part as its own key, then join them with keybox secrets combine.`);
2148
+ const value = fields.length ? await readFields(name, fields) : opts.from ? await readRef(opts.from) : await readSecret(`${name}`, name);
1911
2149
  if (!value) throw new UserError("No value given.");
1912
2150
  if (!spec) {
1913
2151
  const d = detect(name, value);
@@ -1928,7 +2166,23 @@ async function secretsAdd(name, opts) {
1928
2166
  if (d.adminHint) warn(d.adminHint);
1929
2167
  }
1930
2168
  const r = await api("PUT", `/secrets/${name}`, { hosts: spec.hosts, header: spec.header, format: spec.format, value });
1931
- ok(`Stored ${r.name}. It will only ever be sent to ${r.hosts.join(", ")}.${r.fingerprint ? c.dim(` fp ${r.fingerprint}`) : ""}`);
2169
+ ok(`Stored ${r.name}. It will only ever be sent to ${r.hosts.join(", ")}, as ${describeInjection(r.header, r.format)}.${r.fingerprint ? c.dim(` fp ${r.fingerprint}`) : ""}`);
2170
+ }
2171
+ async function secretsCombine(name, pairs, opts) {
2172
+ if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(name)) throw new UserError("Secret names are UPPER_SNAKE_CASE, e.g. CF_ACCESS.");
2173
+ const combine = {};
2174
+ for (const p of pairs) {
2175
+ const m = /^([a-z][a-z0-9_]{0,31})=([A-Z][A-Z0-9_]{0,63})$/.exec(p);
2176
+ if (!m) throw new UserError(`Expected field=STORED_SECRET, got "${p}".`);
2177
+ combine[m[1]] = m[2];
2178
+ }
2179
+ if (Object.keys(combine).length < 2) throw new UserError("Combine at least two keys: keybox secrets combine NAME field=SECRET field=SECRET --host HOST --header H=field \u2026");
2180
+ if (!opts.host?.length) throw new UserError("Say which host it goes to: --host HOST.");
2181
+ const placed = placesFrom(opts);
2182
+ if (!placed) throw new UserError("Say where each field goes: --header NAME=FIELD, --param NAME=FIELD or --body-field NAME=FIELD.");
2183
+ const r = await api("PUT", `/secrets/${name}`, { hosts: opts.host, header: placed.header, format: placed.format, combine });
2184
+ ok(`Stored ${r.name} from ${Object.values(combine).join(" + ")}. It will only ever be sent to ${r.hosts.join(", ")}, as ${describeInjection(r.header, r.format)}.`);
2185
+ note(`The originals are still stored. Remove them once nothing uses them: keybox secrets rm ${Object.values(combine).join(" ")}`);
1932
2186
  }
1933
2187
  async function secretsImport(file, opts) {
1934
2188
  return migrate({ from: `dotenv:${file}`, dryRun: opts.dryRun, yes: opts.yes });
@@ -1938,8 +2192,8 @@ async function secretsList() {
1938
2192
  if (!rows.length) return note("No secrets yet. Add one with `keybox secrets add NAME`, or bring them in with `keybox migrate`.");
1939
2193
  process.stdout.write(
1940
2194
  headed([
1941
- ["NAME", "HOSTS", "HEADER", "FINGERPRINT", "LAST USED"],
1942
- ...rows.map((s) => [s.name, s.hosts.join(",") || c.warn("parked"), `${s.header} (${s.format})`, s.fingerprint ?? "-", ago(s.last_used ?? null)])
2195
+ ["NAME", "HOSTS", "SENT AS", "FINGERPRINT", "LAST USED"],
2196
+ ...rows.map((s) => [s.name, s.hosts.join(",") || c.warn("parked"), describeInjection(s.header, s.format), s.fingerprint ?? "-", ago(s.last_used ?? null)])
1943
2197
  ])
1944
2198
  );
1945
2199
  const parked = rows.filter((s) => !s.hosts.length).length;
@@ -1949,18 +2203,19 @@ async function secretsBind(name, opts) {
1949
2203
  const rows = await api("GET", "/secrets");
1950
2204
  const bind = async (n2, d) => {
1951
2205
  const r = await api("PATCH", `/secrets/${n2}`, { hosts: d.hosts, header: d.header, format: d.format });
1952
- ok(`${n2} ${c.dim(`\u2192 ${r.hosts.join(", ") || "parked"} \xB7 ${r.header} (${r.format})${r.fingerprint ? ` \xB7 fp ${r.fingerprint}` : ""}`)}`);
2206
+ ok(`${n2} ${c.dim(`\u2192 ${r.hosts.join(", ") || "parked"} \xB7 ${describeInjection(r.header, r.format)}${r.fingerprint ? ` \xB7 fp ${r.fingerprint}` : ""}`)}`);
1953
2207
  };
1954
2208
  if (name) {
1955
2209
  const row = rows.find((s) => s.name === name);
1956
2210
  if (!row) throw new UserError(`No secret named ${name}. See keybox secrets list.`);
1957
- if (opts.host?.length || opts.preset) {
2211
+ const where = placesFrom(opts);
2212
+ if (opts.host?.length || opts.preset || where) {
1958
2213
  const p = opts.preset ? PRESETS[opts.preset] : void 0;
1959
2214
  if (opts.preset && !p) throw new UserError(`Unknown preset ${opts.preset}. Known: ${Object.keys(PRESETS).join(", ")}.`);
1960
2215
  return bind(name, {
1961
- hosts: opts.host?.length ? opts.host.map((h) => h.toLowerCase()) : p.hosts,
1962
- header: opts.header ?? p?.header ?? row.header,
1963
- format: opts.format ?? p?.format ?? row.format,
2216
+ hosts: opts.host?.length ? opts.host.map((h) => h.toLowerCase()) : p?.hosts ?? row.hosts,
2217
+ header: where?.header ?? p?.header ?? row.header,
2218
+ format: where?.format ?? opts.format ?? p?.format ?? row.format,
1964
2219
  flag: "bound"
1965
2220
  });
1966
2221
  }
@@ -2148,8 +2403,13 @@ async function run(name, cmd, opts) {
2148
2403
  removed.push(k);
2149
2404
  }
2150
2405
  }
2151
- if (removed.length) note(`Removed ${removed.join(", ")} from ${name}'s environment.`);
2406
+ const granted = secrets.filter((s) => agent.grants.some((g) => g.secret === s.name) && !s.header.includes("=")).map((s) => s.name);
2407
+ const gone = removed.filter((k) => !granted.includes(k));
2408
+ if (gone.length) note(`Removed ${gone.join(", ")} from ${name}'s environment.`);
2409
+ const swapped = removed.filter((k) => granted.includes(k));
2410
+ if (swapped.length) note(`${swapped.join(", ")} now hold${swapped.length === 1 ? "s" : ""} ${name}'s Keybox token, not the key.`);
2152
2411
  Object.assign(env2, envFor(hosts, c2.url.replace(/\/$/, ""), minted.token));
2412
+ for (const k of granted) env2[k] = minted.token;
2153
2413
  let launch = { cmd: cmd[0], args: cmd.slice(1) };
2154
2414
  if (opts.isolate) {
2155
2415
  const iso = isolate(cmd[0], cmd.slice(1), [configDir()]);
@@ -2220,6 +2480,7 @@ var init_commands = __esm({
2220
2480
  init_isolate();
2221
2481
  init_providers();
2222
2482
  init_suggest();
2483
+ init_inject();
2223
2484
  init_policy();
2224
2485
  init_migrate();
2225
2486
  init_presets();
@@ -2371,7 +2632,7 @@ var VERSION;
2371
2632
  var init_version = __esm({
2372
2633
  "src/version.ts"() {
2373
2634
  "use strict";
2374
- VERSION = true ? "0.3.2" : "0.0.0-dev";
2635
+ VERSION = true ? "0.3.4" : "0.0.0-dev";
2375
2636
  }
2376
2637
  });
2377
2638
 
@@ -2778,11 +3039,11 @@ ${c.accent("\u25A0")} This updates the Worker's code. Your stored keys, agents a
2778
3039
  async function status() {
2779
3040
  const cfg = requireConfig();
2780
3041
  const health = await (await fetch(`${cfg.url}/_keybox/health`)).json();
2781
- const [secrets, agents] = await Promise.all([api("GET", "/secrets"), api("GET", "/agents")]);
3042
+ const [secrets, agents, approvals] = await Promise.all([api("GET", "/secrets"), api("GET", "/agents"), stepupLine()]);
2782
3043
  const row = (k, v) => `${c.dim(k.padEnd(11))} ${v}
2783
3044
  `;
2784
3045
  process.stdout.write(
2785
- row("url", cfg.url) + row("dashboard", `${cfg.url.replace(/\/$/, "")}/_keybox/ui ${c.dim("(open with keybox ui)")}`) + (cfg.accountId ? row("account", cfg.accountId) : "") + row("worker", `v${health.version}${health.version === shippedWorkerVersion() ? "" : c.warn(` (this CLI ships v${shippedWorkerVersion()}; run keybox update)`)}`) + row("configured", health.configured) + row("secrets", secrets.length) + row("agents", agents.length)
3046
+ row("url", cfg.url) + row("dashboard", `${cfg.url.replace(/\/$/, "")}/_keybox/ui ${c.dim("(open with keybox ui)")}`) + (cfg.accountId ? row("account", cfg.accountId) : "") + row("worker", `v${health.version}${health.version === shippedWorkerVersion() ? "" : c.warn(` (this CLI ships v${shippedWorkerVersion()}; run keybox update)`)}`) + row("configured", health.configured) + row("secrets", secrets.length) + row("agents", agents.length) + (approvals ? row("approvals", approvals) : "")
2786
3047
  );
2787
3048
  if (process.stdout.isTTY) step(`Run ${c.bold("keybox verify")} to check the deployed code against this CLI.`);
2788
3049
  }
@@ -2790,6 +3051,7 @@ var COMPAT_DATE, asset, sha, LATER;
2790
3051
  var init_deploy = __esm({
2791
3052
  "src/deploy.ts"() {
2792
3053
  "use strict";
3054
+ init_approvals();
2793
3055
  init_api();
2794
3056
  init_cloudflare();
2795
3057
  init_config();
@@ -4982,19 +5244,19 @@ async function membersAdd(name, opts) {
4982
5244
  `);
4983
5245
  note("Valid 24 hours, works once. Their machine then waits for you: `keybox devices` shows it, `keybox devices approve ID` lets it in.");
4984
5246
  }
4985
- async function membersRole(who, role) {
5247
+ async function membersRole(who2, role) {
4986
5248
  if (role !== "admin" && role !== "member") throw new UserError("Usage: keybox members role NAME admin|member");
4987
5249
  const list2 = await api("GET", "/members");
4988
- const m = list2.find((x) => x.id === who || x.name.toLowerCase() === who.toLowerCase());
4989
- if (!m) throw new UserError(`No member called ${who}. See \`keybox members\`.`);
5250
+ const m = list2.find((x) => x.id === who2 || x.name.toLowerCase() === who2.toLowerCase());
5251
+ if (!m) throw new UserError(`No member called ${who2}. See \`keybox members\`.`);
4990
5252
  await api("PATCH", `/members/${encodeURIComponent(m.id)}`, { role });
4991
5253
  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"}.`);
4992
5254
  note("Their open dashboard sessions ended; they sign in again with `keybox ui`.");
4993
5255
  }
4994
- async function membersRm(who) {
5256
+ async function membersRm(who2) {
4995
5257
  const list2 = await api("GET", "/members");
4996
- const m = list2.find((x) => x.id === who || x.name.toLowerCase() === who.toLowerCase());
4997
- if (!m) throw new UserError(`No member called ${who}. See \`keybox members\`.`);
5258
+ const m = list2.find((x) => x.id === who2 || x.name.toLowerCase() === who2.toLowerCase());
5259
+ if (!m) throw new UserError(`No member called ${who2}. See \`keybox members\`.`);
4998
5260
  await api("DELETE", `/members/${encodeURIComponent(m.id)}`);
4999
5261
  ok(`Removed ${m.name}. Their machines and dashboard sessions are revoked.`);
5000
5262
  }
@@ -5042,6 +5304,8 @@ var init_extra = __esm({
5042
5304
  });
5043
5305
 
5044
5306
  // src/index.ts
5307
+ init_api();
5308
+ init_approvals();
5045
5309
  init_commands();
5046
5310
  init_config();
5047
5311
  init_deploy();
@@ -5488,6 +5752,11 @@ var HELP_BODY = `Setup
5488
5752
  keybox devices [list|add|approve ID|revoke ID]
5489
5753
  Machines that can manage this Keybox; add one with a one-time code
5490
5754
  keybox token off [--yes] Turn the shared admin token off; only device keys work after
5755
+ keybox stepup [on|off] Approvals: adding access or moving a key needs your phone
5756
+ keybox approvals [list [--all] | show ID | cancel ID]
5757
+ Requests waiting for your phone
5758
+ keybox approvers [list | rm ID] Phones that can approve (add one in the Keybox app)
5759
+ (any change) --no-wait Don't wait for the phone; exit 3 with the approval id
5491
5760
  keybox update [--check] [--yes] Update the CLI, then the deployed Worker, then verify
5492
5761
  keybox verify [--json] Check Cloudflare is running exactly this CLI's code
5493
5762
  keybox deploy [--yes] Replace the deployed Worker with this CLI's version
@@ -5504,7 +5773,12 @@ Moving keys in (values are never printed, logged or put on a command line)
5504
5773
  pass --item PATH | keychain --item SERVICE
5505
5774
  keybox secrets add NAME [--from op://vault/item/field | vault://path#field | env://VAR \u2026]
5506
5775
  [--preset openai|anthropic|github|\u2026] [--host HOST \u2026 --header H --format bearer|raw|basic]
5507
- keybox secrets bind [NAME] [--preset P | --host HOST \u2026 --header H --format F]
5776
+ [--param NAME] the key goes in a query parameter (Google key=, Moodle wstoken=)
5777
+ [--body-field NAME] the key goes in a JSON or form body field (Sapling, Turnstile)
5778
+ NAME=FIELD on any of these makes a key with several values, asked for one by one
5779
+ keybox secrets combine NAME field=SECRET field=SECRET --host HOST --header H=field | --param P=field \u2026
5780
+ Join stored keys into one with several values (Cloudflare Access id + secret)
5781
+ keybox secrets bind [NAME] [--preset P | --host HOST \u2026 --header H | --param P | --body-field F --format F]
5508
5782
  Give a parked key a host, or change where a key may go, without re-sending it
5509
5783
  keybox secrets list | rm NAME
5510
5784
 
@@ -5563,7 +5837,9 @@ async function main(argv) {
5563
5837
  force: { type: "boolean", default: false },
5564
5838
  preset: { type: "string" },
5565
5839
  host: { type: "string", multiple: true },
5566
- header: { type: "string" },
5840
+ header: { type: "string", multiple: true },
5841
+ param: { type: "string", multiple: true },
5842
+ "body-field": { type: "string", multiple: true },
5567
5843
  format: { type: "string" },
5568
5844
  allow: { type: "string", multiple: true },
5569
5845
  deny: { type: "string", multiple: true },
@@ -5608,7 +5884,9 @@ async function main(argv) {
5608
5884
  profile: { type: "string", short: "p" },
5609
5885
  as: { type: "string" },
5610
5886
  here: { type: "boolean", default: false },
5611
- help: { type: "boolean", short: "h", default: false }
5887
+ help: { type: "boolean", short: "h", default: false },
5888
+ "no-wait": { type: "boolean", default: false },
5889
+ all: { type: "boolean", default: false }
5612
5890
  }
5613
5891
  });
5614
5892
  const [group, sub, arg] = p;
@@ -5619,8 +5897,9 @@ async function main(argv) {
5619
5897
  if (o.version) return void process.stdout.write(VERSION + "\n");
5620
5898
  useProfile(o.profile);
5621
5899
  if (o.verbose) process.env.KEYBOX_VERBOSE = "1";
5900
+ if (o["no-wait"]) setApprovalWait(false);
5622
5901
  if (o.help || !group) return void process.stdout.write(help());
5623
- switch (`${group} ${["secrets", "agents", "tokens", "access", "skill", "devices", "token", "members", "profiles"].includes(group) ? sub ?? "" : ""}`.trim()) {
5902
+ switch (`${group} ${["secrets", "agents", "tokens", "access", "skill", "devices", "token", "members", "profiles", "approvals", "approvers", "stepup"].includes(group) ? sub ?? "" : ""}`.trim()) {
5624
5903
  case "init":
5625
5904
  return init({ name: o.name, url: o.url, account: o.account, yes: o.yes, as: o.as });
5626
5905
  case "verify":
@@ -5662,6 +5941,24 @@ async function main(argv) {
5662
5941
  return devicesRevoke(need(arg, "device id"));
5663
5942
  case "token off":
5664
5943
  return tokenOff({ yes: o.yes });
5944
+ case "approvals":
5945
+ case "approvals list":
5946
+ return approvalsList(o.all);
5947
+ case "approvals show":
5948
+ return approvalsShow(need(arg, "approval id"));
5949
+ case "approvals cancel":
5950
+ return approvalsCancel(need(arg, "approval id"));
5951
+ case "approvers":
5952
+ case "approvers list":
5953
+ return approversList();
5954
+ case "approvers rm":
5955
+ return approversRm(need(arg, "approver id"));
5956
+ case "stepup":
5957
+ return stepupShow();
5958
+ case "stepup on":
5959
+ return stepupSet(true);
5960
+ case "stepup off":
5961
+ return stepupSet(false);
5665
5962
  case "status":
5666
5963
  return status();
5667
5964
  case "ui":
@@ -5685,11 +5982,13 @@ async function main(argv) {
5685
5982
  park: o.park
5686
5983
  });
5687
5984
  case "secrets add":
5688
- return secretsAdd(need(arg, "secret name"), { preset: o.preset, host: o.host, header: o.header, format: o.format, from: o.from });
5985
+ return secretsAdd(need(arg, "secret name"), { preset: o.preset, host: o.host, header: o.header, param: o.param, bodyField: o["body-field"], format: o.format, from: o.from });
5986
+ case "secrets combine":
5987
+ return secretsCombine(need(arg, "secret name"), p.slice(3), { host: o.host, header: o.header, param: o.param, bodyField: o["body-field"], format: o.format });
5689
5988
  case "secrets import":
5690
5989
  return secretsImport(need(arg, "file"), { dryRun: o["dry-run"], yes: o.yes });
5691
5990
  case "secrets bind":
5692
- return secretsBind(arg, { preset: o.preset, host: o.host, header: o.header, format: o.format });
5991
+ return secretsBind(arg, { preset: o.preset, host: o.host, header: o.header, param: o.param, bodyField: o["body-field"], format: o.format });
5693
5992
  case "secrets list":
5694
5993
  return secretsList();
5695
5994
  case "secrets rm":
@@ -5745,5 +6044,5 @@ main(process.argv.slice(2)).catch((err) => {
5745
6044
  ${err instanceof Error ? err.stack : String(err)}
5746
6045
  `);
5747
6046
  }
5748
- process.exitCode = 1;
6047
+ process.exitCode = err instanceof UserError ? err.exitCode : 1;
5749
6048
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keyboxed/cli",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
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",