@keyboxed/cli 0.3.1 → 0.3.2

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.
@@ -15,7 +15,7 @@ Docs: https://keybox.space/docs
15
15
 
16
16
  1. **Never see a key value.** Do not `cat`, `grep`, `head`, `source` or open `.env` files or anything that may hold a credential. To see what a file holds, list names only: `cut -d= -f1 .env`. Do not print environment variables (`env`, `printenv`, `echo $X`).
17
17
  2. **Never put a key on a command line.** Values go in only through `keybox migrate`, `keybox secrets add` (hidden prompt, pipe, or `--from` reference), or the dashboard. Never write `keybox secrets add X <<< "sk-…"` with a value you typed.
18
- 3. **Never read `~/.config/keybox/config.json`.** It holds the admin token.
18
+ 3. **Never read `~/.config/keybox/config.json`.** It holds this machine's device key. Inside `keybox run` it is hidden on purpose, and Keybox admin commands fail there; do not try to get around that.
19
19
  4. **Ask before** you change the user's Cloudflare account, edit a file that holds secrets, delete anything, or widen access. Show the exact command first.
20
20
  5. **Do not work around a refusal.** If Keybox returns `blocked`, `not_allowed` or `network_denied`, report it and propose a narrower rule. Never suggest putting the key back in the environment to "make it work".
21
21
  6. **Do not run `keybox ui --print`** or open login links yourself. Ask the user to run `keybox ui`.
@@ -130,7 +130,7 @@ Confirm the expected calls show as allowed and nothing is refused by mistake. Co
130
130
 
131
131
  | Code | Meaning | What to do |
132
132
  | --- | --- | --- |
133
- | `not_allowed` | No rule allows this method/host/path | Propose the narrowest rule that covers it; ask first |
133
+ | `not_allowed` | No rule allows this method/host/path | The message names the fix. Show the user `keybox agents suggest NAME` (reviews every refused call) or the narrowest `keybox agents allow NAME 'RULE'`; ask first. Never propose `**` to silence it |
134
134
  | `blocked` | Built-in list: the call would mint a key or grant access | Explain; there is no override |
135
135
  | `network_denied` | The caller's IP or country is outside the access rules | Show `keybox access`; let the user decide |
136
136
  | `ambiguous_secret` | Several keys could apply | Send header `x-keybox-secret: NAME` or prefix rules |
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.1";
49
+ var VERSION = "0.3.2";
50
50
  function keyboxError(status, code, message) {
51
51
  return Response.json({ type: "error", error: { type: "keybox_error", code, message } }, { status });
52
52
  }
@@ -948,7 +948,17 @@ async function route(req, env, path, policy, who) {
948
948
  const q = new URL(req.url).searchParams;
949
949
  const after = Number(q.get("after") ?? 0);
950
950
  const limit = Math.min(Math.max(Number(q.get("limit") ?? 100), 1), 500);
951
- const stmt = after > 0 ? env.DB.prepare("SELECT * FROM audit WHERE id > ? ORDER BY id ASC LIMIT ?").bind(after, limit) : env.DB.prepare("SELECT * FROM (SELECT * FROM audit ORDER BY id DESC LIMIT ?) ORDER BY id ASC").bind(limit);
951
+ const where = [];
952
+ const binds = [];
953
+ for (const col of ["agent", "reason"]) {
954
+ const v = q.get(col);
955
+ if (v) {
956
+ where.push(`${col} = ?`);
957
+ binds.push(v.slice(0, 64));
958
+ }
959
+ }
960
+ const filter = where.length ? ` AND ${where.join(" AND ")}` : "";
961
+ const stmt = after > 0 ? env.DB.prepare(`SELECT * FROM audit WHERE id > ?${filter} ORDER BY id ASC LIMIT ?`).bind(after, ...binds, limit) : env.DB.prepare(`SELECT * FROM (SELECT * FROM audit WHERE 1=1${filter} ORDER BY id DESC LIMIT ?) ORDER BY id ASC`).bind(...binds, limit);
952
962
  return Response.json((await stmt.all()).results);
953
963
  }
954
964
  if (a === "blocked" && !b && m === "GET") {
@@ -1294,7 +1304,10 @@ async function proxy(req, env, ctx) {
1294
1304
  if (g.allow.some(hit)) candidates.add(g.secret);
1295
1305
  }
1296
1306
  if (candidates.size === 0) {
1297
- return deny(403, "not_allowed", `Agent ${auth.agent} has no rule allowing ${method} ${host}${path}.`);
1307
+ const pasteable = /^[A-Za-z0-9._~\-/%:@,+=]*$/.test(path);
1308
+ const review = `keybox agents suggest ${auth.agent}`;
1309
+ const fix = auth.share ? "This share does not cover that call." : pasteable ? `To allow it, a Keybox admin runs: keybox agents allow ${auth.agent} '${method} ${host}${path}' (or \`${review}\` to review every refused call).` : `A Keybox admin can review refused calls with \`${review}\`.`;
1310
+ return deny(403, "not_allowed", `Agent ${auth.agent} has no rule allowing ${method} ${host}${path}. ${fix}`);
1298
1311
  }
1299
1312
  let pick = [...candidates][0];
1300
1313
  if (candidates.size > 1) {
package/dist/keybox.js CHANGED
@@ -321,6 +321,9 @@ function loadConfig() {
321
321
  }
322
322
  function requireConfig() {
323
323
  const r = resolveProfile();
324
+ if (!r && process.env.KEYBOX_ISOLATED === "1") {
325
+ throw new UserError("This runs inside `keybox run`, which hides Keybox credentials from the agent on purpose. Run Keybox admin commands in your own terminal.");
326
+ }
324
327
  if (!r) throw new UserError("Not set up yet. Run `keybox init` to deploy one, or `keybox login` to connect to one.");
325
328
  if (!announced && r.source !== "environment" && process.stderr.isTTY && Object.keys(readStore().profiles).length > 1) {
326
329
  announced = true;
@@ -488,6 +491,79 @@ var init_grants = __esm({
488
491
  }
489
492
  });
490
493
 
494
+ // src/isolate.ts
495
+ import { spawnSync } from "node:child_process";
496
+ import { existsSync as existsSync2, realpathSync } from "node:fs";
497
+ import { delimiter, join as join2 } from "node:path";
498
+ function onPath(bin2) {
499
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
500
+ const p = join2(dir, bin2);
501
+ if (dir && existsSync2(p)) return p;
502
+ }
503
+ return null;
504
+ }
505
+ function real(dirs) {
506
+ return [...new Set(dirs.filter((d) => existsSync2(d)).map((d) => realpathSync(d)))];
507
+ }
508
+ function bwrapArgs(hide, cwd, cmd, args) {
509
+ return [
510
+ "--dev-bind",
511
+ "/",
512
+ "/",
513
+ // A fresh /proc in its own pid namespace: otherwise /proc/<pid>/environ of keybox itself, or of the
514
+ // shell that started it, would hand back a KEYBOX_DEVICE_KEY set in the environment.
515
+ "--unshare-pid",
516
+ "--proc",
517
+ "/proc",
518
+ ...hide.flatMap((d) => ["--tmpfs", d, "--remount-ro", d]),
519
+ "--die-with-parent",
520
+ "--chdir",
521
+ cwd,
522
+ "--",
523
+ cmd,
524
+ ...args
525
+ ];
526
+ }
527
+ function sandboxProfile(hide) {
528
+ return ["(version 1)", "(allow default)", ...hide.map((d) => `(deny file-read* file-write* (subpath ${sbpl(d)}))`)].join("\n");
529
+ }
530
+ function isolate(cmd, args, hideDirs, platform = process.platform) {
531
+ const hide = real(hideDirs);
532
+ if (!hide.length) return { ok: true, cmd, args, how: "nothing to hide" };
533
+ if (platform === "linux") {
534
+ const bwrap = onPath("bwrap");
535
+ if (!bwrap) {
536
+ return {
537
+ ok: false,
538
+ why: "bubblewrap (bwrap) is not installed",
539
+ hint: "Install it (apt install bubblewrap \xB7 dnf install bubblewrap \xB7 pacman -S bubblewrap \xB7 emerge sys-apps/bubblewrap)."
540
+ };
541
+ }
542
+ const probe = spawnSync(bwrap, bwrapArgs(hide, "/", "true", []), { stdio: "ignore", timeout: 5e3 });
543
+ if (probe.status !== 0) {
544
+ return {
545
+ ok: false,
546
+ why: "bubblewrap could not create a sandbox here (unprivileged user namespaces are off?)",
547
+ hint: "Run the agent in a container or as another OS user instead."
548
+ };
549
+ }
550
+ return { ok: true, cmd: bwrap, args: bwrapArgs(hide, process.cwd(), cmd, args), how: "bubblewrap" };
551
+ }
552
+ if (platform === "darwin") {
553
+ const se = "/usr/bin/sandbox-exec";
554
+ if (!existsSync2(se)) return { ok: false, why: "sandbox-exec is missing" };
555
+ return { ok: true, cmd: se, args: ["-p", sandboxProfile(hide), cmd, ...args], how: "sandbox-exec" };
556
+ }
557
+ return { ok: false, why: `hiding files is not supported on ${platform}`, hint: "Run the agent in a container or as another OS user." };
558
+ }
559
+ var sbpl;
560
+ var init_isolate = __esm({
561
+ "src/isolate.ts"() {
562
+ "use strict";
563
+ sbpl = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
564
+ }
565
+ });
566
+
491
567
  // ../shared/providers.ts
492
568
  function byName(name) {
493
569
  const n = name.toUpperCase();
@@ -608,6 +684,128 @@ var init_providers = __esm({
608
684
  }
609
685
  });
610
686
 
687
+ // ../shared/suggest.ts
688
+ function idLike(segment) {
689
+ return segment.includes("*") || ID_LIKE.some((re) => re.test(segment));
690
+ }
691
+ function suggestRules(refusals) {
692
+ const byKey = /* @__PURE__ */ new Map();
693
+ const add = (p) => {
694
+ const key = `${p.method} ${p.host}/${p.segs.join("/")}`;
695
+ const prev = byKey.get(key);
696
+ if (prev) prev.calls += p.calls;
697
+ else byKey.set(key, { ...p, segs: [...p.segs] });
698
+ };
699
+ for (const r of refusals) {
700
+ if (!r.host || !r.path) continue;
701
+ const segs = r.path.split("/").slice(1).map((s) => idLike(s) ? "*" : s);
702
+ add({ method: r.method.toUpperCase(), host: r.host, segs, calls: 1, example: `${r.method.toUpperCase()} ${r.host}${r.path}` });
703
+ }
704
+ for (let changed = true; changed; ) {
705
+ changed = false;
706
+ const patterns = [...byKey.values()];
707
+ const maxLen = Math.max(0, ...patterns.map((p) => p.segs.length));
708
+ for (let i = 0; i < maxLen && !changed; i++) {
709
+ const groups = /* @__PURE__ */ new Map();
710
+ for (const p of patterns) {
711
+ if (p.segs.length <= i || p.segs[i] === "*") continue;
712
+ const shape = `${p.method} ${p.host} ${p.segs.length} ${p.segs.map((s, j) => j === i ? "\0" : s).join("/")}`;
713
+ groups.set(shape, [...groups.get(shape) ?? [], p]);
714
+ }
715
+ for (const group of groups.values()) {
716
+ if (new Set(group.map((p) => p.segs[i])).size < MERGE_AT) continue;
717
+ for (const p of group) {
718
+ byKey.delete(`${p.method} ${p.host}/${p.segs.join("/")}`);
719
+ p.segs[i] = "*";
720
+ add(p);
721
+ }
722
+ changed = true;
723
+ }
724
+ }
725
+ }
726
+ const byPath = /* @__PURE__ */ new Map();
727
+ for (const p of byKey.values()) {
728
+ const target = `${p.host}/${p.segs.join("/")}`;
729
+ const prev = byPath.get(target);
730
+ if (prev) {
731
+ prev.methods.add(p.method);
732
+ prev.calls += p.calls;
733
+ } else byPath.set(target, { methods: /* @__PURE__ */ new Set([p.method]), calls: p.calls, example: p.example });
734
+ }
735
+ return [...byPath.entries()].map(([target, v]) => ({ rule: `${[...v.methods].sort().join(",")} ${target}`, calls: v.calls, example: v.example })).sort((a, b) => b.calls - a.calls || a.rule.localeCompare(b.rule));
736
+ }
737
+ var ID_LIKE, MERGE_AT;
738
+ var init_suggest = __esm({
739
+ "../shared/suggest.ts"() {
740
+ ID_LIKE = [
741
+ /^\d+$/,
742
+ // 12345
743
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
744
+ // uuid
745
+ /^(?=.*\d)[0-9a-f]{7,}$/i,
746
+ // commit sha, hex id
747
+ /^(?=.*\d)(?=.*[a-z])[A-Za-z0-9_-]{20,}$/i,
748
+ // long opaque id (base64url, ulid, ...)
749
+ /^[a-z]{2,8}_(?=.*\d)[A-Za-z0-9]{8,}$/,
750
+ // prefixed ids: cus_9s8d7f6g, msg_01abc...
751
+ /^\d{4}-\d{2}-\d{2}/,
752
+ // dates
753
+ /@/
754
+ // emails, user@host
755
+ ];
756
+ MERGE_AT = 3;
757
+ }
758
+ });
759
+
760
+ // ../worker/src/policy.ts
761
+ function parseRule(source, opts = {}) {
762
+ const m = RULE.exec(source.trim());
763
+ if (!m) throw new Error(`bad rule: ${source}`);
764
+ const [, method, host, path = "/**"] = m;
765
+ const methods = method === "*" ? null : new Set(method.toUpperCase().split(","));
766
+ return {
767
+ source,
768
+ methods,
769
+ host: host === "*" ? /^.+$/ : new RegExp(`^${host.split("*").map(escape).join("[a-z0-9-]+")}$`),
770
+ path: globToRegExp(path, opts.caseInsensitive)
771
+ };
772
+ }
773
+ function matches(rule, method, host, path) {
774
+ return (!rule.methods || rule.methods.has(method)) && rule.host.test(host) && rule.path.test(path);
775
+ }
776
+ function globToRegExp(glob, caseInsensitive = false) {
777
+ let re = "";
778
+ for (let i = 0; i < glob.length; ) {
779
+ if (glob.startsWith("/**/", i)) {
780
+ re += "(?:/|/.*/)";
781
+ i += 4;
782
+ } else if (glob.startsWith("/**", i) && i + 3 === glob.length) {
783
+ re += "(?:/.*)?";
784
+ i += 3;
785
+ } else if (glob.startsWith("**", i)) {
786
+ re += ".*";
787
+ i += 2;
788
+ } else if (glob[i] === "*") {
789
+ re += "[^/]*";
790
+ i += 1;
791
+ } else {
792
+ re += escape(glob[i]);
793
+ i += 1;
794
+ }
795
+ }
796
+ return new RegExp(`^${re}$`, caseInsensitive ? "i" : "");
797
+ }
798
+ function escape(s) {
799
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
800
+ }
801
+ var RULE;
802
+ var init_policy = __esm({
803
+ "../worker/src/policy.ts"() {
804
+ "use strict";
805
+ RULE = /^([A-Za-z*]+(?:,[A-Za-z]+)*)\s+([a-z0-9*.-]+)(\/\S*)?$/;
806
+ }
807
+ });
808
+
611
809
  // src/prompt.ts
612
810
  var prompt_exports = {};
613
811
  __export(prompt_exports, {
@@ -909,12 +1107,12 @@ var init_prompt = __esm({
909
1107
  });
910
1108
 
911
1109
  // src/migrate.ts
912
- import { spawn, spawnSync } from "node:child_process";
913
- import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2 } from "node:fs";
1110
+ import { spawn, spawnSync as spawnSync2 } from "node:child_process";
1111
+ import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync2 } from "node:fs";
914
1112
  import { homedir as homedir2 } from "node:os";
915
- import { join as join2 } from "node:path";
1113
+ import { join as join3 } from "node:path";
916
1114
  function has(bin2) {
917
- return spawnSync(process.platform === "win32" ? "where" : "which", [bin2], { stdio: "ignore" }).status === 0;
1115
+ return spawnSync2(process.platform === "win32" ? "where" : "which", [bin2], { stdio: "ignore" }).status === 0;
918
1116
  }
919
1117
  function capture(bin2, args) {
920
1118
  if (!has(bin2)) throw new UserError(`${bin2} is not installed or not on PATH.`);
@@ -953,7 +1151,7 @@ function infisicalBase() {
953
1151
  const fromEnv = process.env.INFISICAL_DOMAIN?.replace(/\/+$/, "");
954
1152
  if (fromEnv) return /\/api$/.test(fromEnv) ? fromEnv : `${fromEnv}/api`;
955
1153
  try {
956
- const cfg = JSON.parse(readFileSync2(join2(homedir2(), ".infisical", "infisical-config.json"), "utf8"));
1154
+ const cfg = JSON.parse(readFileSync2(join3(homedir2(), ".infisical", "infisical-config.json"), "utf8"));
957
1155
  const p = cfg.profiles?.find((x) => x.name === cfg.activeProfile) ?? cfg.profiles?.[0];
958
1156
  if (p?.domain) return p.domain.replace(/\/+$/, "");
959
1157
  } catch {
@@ -1310,7 +1508,7 @@ async function migrate(opts) {
1310
1508
  const [id, ...rest] = from.split(":");
1311
1509
  const arg = rest.join(":") || void 0;
1312
1510
  if (NOT_READABLE[id]) throw new UserError(NOT_READABLE[id]);
1313
- const source = SOURCES.find((s) => s.id === id) ?? (existsSync2(from) ? SOURCES[0] : void 0);
1511
+ const source = SOURCES.find((s) => s.id === id) ?? (existsSync3(from) ? SOURCES[0] : void 0);
1314
1512
  if (!source) throw new UserError(`Unknown source ${id}. Sources: ${SOURCES.map((s) => s.id).join(", ")}.`);
1315
1513
  const fileArg = source === SOURCES[0] && !arg ? from : arg;
1316
1514
  const interactive = Boolean(process.stdin.isTTY) && !opts.yes && !opts.dryRun;
@@ -1682,9 +1880,11 @@ var init_presets = __esm({
1682
1880
  // src/commands.ts
1683
1881
  var commands_exports = {};
1684
1882
  __export(commands_exports, {
1883
+ agentsAdd: () => agentsAdd,
1685
1884
  agentsCreate: () => agentsCreate,
1686
1885
  agentsList: () => agentsList,
1687
1886
  agentsRm: () => agentsRm,
1887
+ agentsSuggest: () => agentsSuggest,
1688
1888
  agentsToken: () => agentsToken,
1689
1889
  audit: () => audit,
1690
1890
  blocked: () => blocked,
@@ -1815,6 +2015,90 @@ async function agentsCreate(name, opts) {
1815
2015
  }
1816
2016
  note(`Everything else is denied. Start it with: keybox run ${name} -- <command>`);
1817
2017
  }
2018
+ function namedRules(grants) {
2019
+ return {
2020
+ allow: grants.flatMap((g) => g.allow.map((r) => `${g.secret}=${r}`)),
2021
+ deny: grants.flatMap((g) => (g.deny ?? []).map((r) => `${g.secret}=${r}`))
2022
+ };
2023
+ }
2024
+ async function agentsAdd(name, opts) {
2025
+ const allow = opts.allow ?? [];
2026
+ const deny = opts.deny ?? [];
2027
+ if (!allow.length && !deny.length) throw new UserError(`Give a rule, e.g. keybox agents allow ${name} "GET api.github.com/repos/acme/**".`);
2028
+ const [agents, secrets] = await Promise.all([api("GET", "/agents"), api("GET", "/secrets")]);
2029
+ const agent = agents.find((a) => a.name === name);
2030
+ if (!agent && !allow.length) throw new UserError(`No agent named ${name}. Create it with an allow rule first.`);
2031
+ const had = namedRules(agent?.grants ?? []);
2032
+ const grants = buildGrants2([...had.allow, ...allow], [...had.deny, ...deny], secrets).map((g) => ({
2033
+ ...g,
2034
+ allow: [...new Set(g.allow)],
2035
+ ...g.deny ? { deny: [...new Set(g.deny)] } : {}
2036
+ }));
2037
+ const before = /* @__PURE__ */ new Set([...had.allow, ...had.deny.map((r) => `deny ${r}`)]);
2038
+ await api("PUT", `/agents/${name}`, { grants });
2039
+ let added = 0;
2040
+ for (const g of grants) {
2041
+ for (const r of g.allow) {
2042
+ if (before.has(`${g.secret}=${r}`)) continue;
2043
+ process.stderr.write(` ${c.ok("+ allow")} ${r} ${c.dim(`(with ${g.secret})`)}
2044
+ `);
2045
+ added++;
2046
+ }
2047
+ for (const r of g.deny ?? []) {
2048
+ if (before.has(`deny ${g.secret}=${r}`)) continue;
2049
+ process.stderr.write(` ${c.bad("+ deny ")} ${r}
2050
+ `);
2051
+ added++;
2052
+ }
2053
+ }
2054
+ if (!added) return note(`${name} already had ${allow.length + deny.length === 1 ? "that rule" : "those rules"}.`);
2055
+ ok(`${agent ? "Updated" : "Created"} ${name}. It applies on the next call; running tokens keep working.`);
2056
+ }
2057
+ function shellArg(s) {
2058
+ return /^[A-Za-z0-9._~\-/%:@,+=* ]*$/.test(s) ? `'${s}'` : null;
2059
+ }
2060
+ async function agentsSuggest(name, opts) {
2061
+ const [agents, secrets, log] = await Promise.all([
2062
+ api("GET", "/agents"),
2063
+ api("GET", "/secrets"),
2064
+ api("GET", `/audit?agent=${encodeURIComponent(name)}&reason=not_allowed&limit=${Math.min(Number(opts.limit) || 500, 500)}`)
2065
+ ]);
2066
+ const agent = agents.find((a) => a.name === name);
2067
+ if (!agent) throw new UserError(`No agent named ${name}.`);
2068
+ const rules = agent.grants.flatMap((g) => g.allow.map((r) => parseRule(r)));
2069
+ const refused = log.filter(
2070
+ (r) => r.agent === name && r.reason === "not_allowed" && r.host && r.path && !rules.some((rule) => matches(rule, r.method, r.host, r.path))
2071
+ );
2072
+ if (!refused.length) return note(`No refused calls for ${name} that its rules do not already cover.`);
2073
+ const bound = new Set(secrets.flatMap((s) => s.hosts));
2074
+ const all = suggestRules(refused.map((r) => ({ method: r.method, host: r.host, path: r.path })));
2075
+ const usable = all.filter((s) => bound.has(s.rule.split(" ")[1].split("/")[0]));
2076
+ const unbound = [...new Set(all.filter((s) => !usable.includes(s)).map((s) => s.rule.split(" ")[1].split("/")[0]))];
2077
+ if (unbound.length) note(`No stored key is bound to ${unbound.join(", ")}, so no rule for ${unbound.length === 1 ? "it" : "them"} would help. Add or bind a key first.`);
2078
+ if (!usable.length) return;
2079
+ step(`${refused.length} refused call${refused.length === 1 ? "" : "s"} by ${c.bold(name)}. Suggested rules (ids replaced by *):`);
2080
+ process.stderr.write(
2081
+ table(usable.map((s) => [` ${s.rule}`, c.dim(`${s.calls} call${s.calls === 1 ? "" : "s"}`), c.dim(s.example.length > 70 ? s.example.slice(0, 69) + "\u2026" : s.example)]))
2082
+ );
2083
+ let picked;
2084
+ if (opts.yes) picked = usable.map((s) => s.rule);
2085
+ else if (process.stdin.isTTY && process.stderr.isTTY) {
2086
+ picked = await checklist(
2087
+ "Allow which? (space toggles, a picks all, enter applies)",
2088
+ usable.map((s) => ({ value: s.rule, label: s.rule, hint: `${s.calls}\xD7` })),
2089
+ () => false
2090
+ );
2091
+ } else {
2092
+ const args = usable.map((s) => shellArg(s.rule));
2093
+ const safe = args.filter((a) => a !== null);
2094
+ if (safe.length) process.stdout.write(`keybox agents allow ${name} ${safe.join(" ")}
2095
+ `);
2096
+ if (safe.length < args.length) note(`${args.length - safe.length} suggestion(s) hold characters unsafe to paste into a shell; review them at a terminal.`);
2097
+ return note("Nothing applied. Run the command above, or re-run at a terminal to pick.");
2098
+ }
2099
+ if (!picked.length) return note("Nothing applied.");
2100
+ await agentsAdd(name, { allow: picked });
2101
+ }
1818
2102
  async function agentsList() {
1819
2103
  const rows = await api("GET", "/agents");
1820
2104
  if (!rows.length) return note("No agents yet. Create one with `keybox agents create NAME --allow RULE`.");
@@ -1859,15 +2143,26 @@ async function run(name, cmd, opts) {
1859
2143
  const removed = [];
1860
2144
  const stored = new Set(secrets.map((s) => s.name));
1861
2145
  for (const k of Object.keys(env2)) {
1862
- if (isKeyVar(k) || stored.has(k)) {
2146
+ if (isKeyVar(k) || stored.has(k) || k.startsWith("KEYBOX_")) {
1863
2147
  delete env2[k];
1864
2148
  removed.push(k);
1865
2149
  }
1866
2150
  }
1867
2151
  if (removed.length) note(`Removed ${removed.join(", ")} from ${name}'s environment.`);
1868
2152
  Object.assign(env2, envFor(hosts, c2.url.replace(/\/$/, ""), minted.token));
2153
+ let launch = { cmd: cmd[0], args: cmd.slice(1) };
2154
+ if (opts.isolate) {
2155
+ const iso = isolate(cmd[0], cmd.slice(1), [configDir()]);
2156
+ if (iso.ok) {
2157
+ launch = { cmd: iso.cmd, args: iso.args };
2158
+ env2.KEYBOX_ISOLATED = "1";
2159
+ } else {
2160
+ warn(`Could not hide this machine's Keybox credentials from ${cmd[0]}: ${iso.why}. It can read ${configDir()}.`);
2161
+ if (iso.hint) note(iso.hint);
2162
+ }
2163
+ }
1869
2164
  const revoke = () => api("DELETE", `/tokens/${minted.id}`).catch(() => note(`Could not revoke token ${minted.id}; it expires ${when(minted.expires_at)} UTC.`));
1870
- const child = spawn2(cmd[0], cmd.slice(1), { stdio: "inherit", env: env2 });
2165
+ const child = spawn2(launch.cmd, launch.args, { stdio: "inherit", env: env2 });
1871
2166
  const ignore = () => {
1872
2167
  };
1873
2168
  process.on("SIGINT", ignore);
@@ -1922,7 +2217,10 @@ var init_commands = __esm({
1922
2217
  init_api();
1923
2218
  init_grants();
1924
2219
  init_config();
2220
+ init_isolate();
1925
2221
  init_providers();
2222
+ init_suggest();
2223
+ init_policy();
1926
2224
  init_migrate();
1927
2225
  init_presets();
1928
2226
  init_prompt();
@@ -1935,11 +2233,11 @@ var init_commands = __esm({
1935
2233
  import { spawn as spawn3 } from "node:child_process";
1936
2234
  import { readFileSync as readFileSync3 } from "node:fs";
1937
2235
  import { createRequire } from "node:module";
1938
- import { dirname as dirname2, join as join3 } from "node:path";
2236
+ import { dirname as dirname2, join as join4 } from "node:path";
1939
2237
  function bin() {
1940
2238
  const pkgPath = createRequire(import.meta.url).resolve("wrangler/package.json");
1941
2239
  const pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
1942
- return join3(dirname2(pkgPath), pkg.bin.wrangler);
2240
+ return join4(dirname2(pkgPath), pkg.bin.wrangler);
1943
2241
  }
1944
2242
  function useAccount(id) {
1945
2243
  accountId = id;
@@ -2073,7 +2371,7 @@ var VERSION;
2073
2371
  var init_version = __esm({
2074
2372
  "src/version.ts"() {
2075
2373
  "use strict";
2076
- VERSION = true ? "0.3.1" : "0.0.0-dev";
2374
+ VERSION = true ? "0.3.2" : "0.0.0-dev";
2077
2375
  }
2078
2376
  });
2079
2377
 
@@ -2250,8 +2548,8 @@ __export(deploy_exports, {
2250
2548
  });
2251
2549
  import { spawn as spawn4 } from "node:child_process";
2252
2550
  import { createHash as createHash3, randomBytes as randomBytes2 } from "node:crypto";
2253
- import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
2254
- import { join as join4 } from "node:path";
2551
+ import { copyFileSync, existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
2552
+ import { join as join5 } from "node:path";
2255
2553
  async function deployWorker(cfg) {
2256
2554
  for (let attempt = 1; ; attempt++) {
2257
2555
  try {
@@ -2265,10 +2563,10 @@ async function deployWorker(cfg) {
2265
2563
  }
2266
2564
  function writeDeployFiles(name, d1Id, accountId2, key) {
2267
2565
  const dir = deployDir(key);
2268
- mkdirSync2(join4(dir, "worker"), { recursive: true, mode: 448 });
2269
- copyFileSync(asset("worker.js"), join4(dir, "worker", "worker.js"));
2270
- copyFileSync(asset("schema.sql"), join4(dir, "schema.sql"));
2271
- const cfg = join4(dir, "wrangler.json");
2566
+ mkdirSync2(join5(dir, "worker"), { recursive: true, mode: 448 });
2567
+ copyFileSync(asset("worker.js"), join5(dir, "worker", "worker.js"));
2568
+ copyFileSync(asset("schema.sql"), join5(dir, "schema.sql"));
2569
+ const cfg = join5(dir, "wrangler.json");
2272
2570
  writeFileSync2(
2273
2571
  cfg,
2274
2572
  JSON.stringify(
@@ -2371,7 +2669,7 @@ async function init(opts) {
2371
2669
  const cfgPath = writeDeployFiles(name, d1Id, account.id, deployKey);
2372
2670
  await task(
2373
2671
  "Schema",
2374
- () => wrangler(["d1", "execute", name, "--remote", "--yes", "--file", join4(deployDir(), "schema.sql"), "--config", cfgPath], { capture: true, quiet: true }),
2672
+ () => wrangler(["d1", "execute", name, "--remote", "--yes", "--file", join5(deployDir(), "schema.sql"), "--config", cfgPath], { capture: true, quiet: true }),
2375
2673
  () => "applied"
2376
2674
  );
2377
2675
  const url = await task(
@@ -2450,7 +2748,7 @@ async function deploy(opts) {
2450
2748
  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).`);
2451
2749
  await resolveAccount(cfg);
2452
2750
  const dir = deployDir();
2453
- const current2 = existsSync3(join4(dir, "worker", "worker.js")) ? sha(join4(dir, "worker", "worker.js")) : null;
2751
+ const current2 = existsSync4(join5(dir, "worker", "worker.js")) ? sha(join5(dir, "worker", "worker.js")) : null;
2454
2752
  const next = shippedWorkerHash();
2455
2753
  if (current2 === next && !opts.force) {
2456
2754
  ok("The deployed Worker already matches this CLI version. Run `keybox verify` to check what Cloudflare is serving.");
@@ -2470,7 +2768,7 @@ ${c.accent("\u25A0")} This updates the Worker's code. Your stored keys, agents a
2470
2768
  const wranglerCfg = writeDeployFiles(fresh.name, fresh.d1Id, fresh.accountId, fresh.deploy);
2471
2769
  await task(
2472
2770
  "Schema",
2473
- () => wrangler(["d1", "execute", fresh.name, "--remote", "--yes", "--file", join4(dir, "schema.sql"), "--config", wranglerCfg], { capture: true, quiet: true }),
2771
+ () => wrangler(["d1", "execute", fresh.name, "--remote", "--yes", "--file", join5(dir, "schema.sql"), "--config", wranglerCfg], { capture: true, quiet: true }),
2474
2772
  () => "applied"
2475
2773
  );
2476
2774
  await task("Worker", () => deployWorker(wranglerCfg), () => "deployed");
@@ -4351,9 +4649,9 @@ __export(extra_exports, {
4351
4649
  use: () => use
4352
4650
  });
4353
4651
  import { spawn as spawn5 } from "node:child_process";
4354
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "node:fs";
4652
+ import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "node:fs";
4355
4653
  import { homedir as homedir3 } from "node:os";
4356
- import { dirname as dirname3, join as join5 } from "node:path";
4654
+ import { dirname as dirname3, join as join6 } from "node:path";
4357
4655
  async function login(urlArg, opts = {}) {
4358
4656
  const url = checkUrl(urlArg ?? await ask("Keybox address (https://\u2026)"));
4359
4657
  const code = (opts.code ?? process.env.KEYBOX_JOIN_CODE ?? "").trim();
@@ -4648,15 +4946,15 @@ async function skill(opts) {
4648
4946
  if (opts.print) return void process.stdout.write(text);
4649
4947
  const base = opts.project ? process.cwd() : homedir3();
4650
4948
  const targets = {
4651
- claude: join5(base, ".claude", "skills", "keybox", "SKILL.md"),
4652
- codex: join5(opts.project ? join5(base, ".codex") : join5(homedir3(), ".codex"), "skills", "keybox", "SKILL.md"),
4653
- agents: join5(base, ".agents", "skills", "keybox", "SKILL.md")
4949
+ claude: join6(base, ".claude", "skills", "keybox", "SKILL.md"),
4950
+ codex: join6(opts.project ? join6(base, ".codex") : join6(homedir3(), ".codex"), "skills", "keybox", "SKILL.md"),
4951
+ agents: join6(base, ".agents", "skills", "keybox", "SKILL.md")
4654
4952
  };
4655
4953
  const pick = opts.target === "all" ? Object.keys(targets) : opts.target.split(",");
4656
4954
  for (const t of pick) {
4657
4955
  const path = targets[t];
4658
4956
  if (!path) throw new UserError(`Unknown target ${t}. Use claude, codex, agents or all (or --print).`);
4659
- const existed = existsSync4(path);
4957
+ const existed = existsSync5(path);
4660
4958
  mkdirSync3(dirname3(path), { recursive: true });
4661
4959
  writeFileSync3(path, text);
4662
4960
  ok(`${existed ? "Updated" : "Installed"} ${path}`);
@@ -4834,8 +5132,8 @@ init_config();
4834
5132
  init_dove();
4835
5133
  init_ui();
4836
5134
  import { spawn as spawn6 } from "node:child_process";
4837
- import { existsSync as existsSync5 } from "node:fs";
4838
- import { delimiter, join as join6 } from "node:path";
5135
+ import { existsSync as existsSync6 } from "node:fs";
5136
+ import { delimiter as delimiter2, join as join7 } from "node:path";
4839
5137
  var TABS = ["Activity", "Secrets", "Agents"];
4840
5138
  var out = process.stdout;
4841
5139
  var ago3 = (ms) => {
@@ -4861,11 +5159,11 @@ function fit(s, n) {
4861
5159
  }
4862
5160
  function nativeTui() {
4863
5161
  const explicit = process.env.KEYBOX_TUI;
4864
- if (explicit && existsSync5(explicit)) return explicit;
4865
- for (const dir of (process.env.PATH ?? "").split(delimiter)) {
5162
+ if (explicit && existsSync6(explicit)) return explicit;
5163
+ for (const dir of (process.env.PATH ?? "").split(delimiter2)) {
4866
5164
  for (const name of process.platform === "win32" ? ["keybox-tui.exe"] : ["keybox-tui"]) {
4867
- const p = join6(dir, name);
4868
- if (dir && existsSync5(p)) return p;
5165
+ const p = join7(dir, name);
5166
+ if (dir && existsSync6(p)) return p;
4869
5167
  }
4870
5168
  }
4871
5169
  return null;
@@ -5060,16 +5358,23 @@ init_prompt();
5060
5358
  init_ui();
5061
5359
  init_verify();
5062
5360
  init_version();
5063
- import { spawn as spawn7, spawnSync as spawnSync2 } from "node:child_process";
5064
- import { existsSync as existsSync6, realpathSync } from "node:fs";
5065
- import { dirname as dirname4, join as join7 } from "node:path";
5361
+ import { spawn as spawn7, spawnSync as spawnSync3 } from "node:child_process";
5362
+ import { existsSync as existsSync7, realpathSync as realpathSync2 } from "node:fs";
5363
+ import { dirname as dirname4, join as join8 } from "node:path";
5066
5364
  import { fileURLToPath } from "node:url";
5365
+ function npmPrefix(self, platform = process.platform) {
5366
+ if (platform === "win32") return void 0;
5367
+ const i = self.lastIndexOf("/node_modules/@keyboxed/cli/");
5368
+ if (i < 0) return void 0;
5369
+ const lib = self.slice(0, i);
5370
+ return lib.endsWith("/lib") ? lib.slice(0, -4) || "/" : void 0;
5371
+ }
5067
5372
  function howInstalled() {
5068
- const self = realpathSync(fileURLToPath(import.meta.url));
5069
- if (self.includes(`${join7("_npx", "")}`) || self.includes("/_npx/")) return { kind: "npx" };
5373
+ const self = realpathSync2(fileURLToPath(import.meta.url));
5374
+ if (self.includes(`${join8("_npx", "")}`) || self.includes("/_npx/")) return { kind: "npx" };
5070
5375
  const root = dirname4(dirname4(dirname4(self)));
5071
- if (existsSync6(join7(root, ".git")) && existsSync6(join7(root, "cli", "package.json"))) return { kind: "checkout", root };
5072
- if (self.includes(join7("node_modules", "@keyboxed", "cli"))) return { kind: "npm-global" };
5376
+ if (existsSync7(join8(root, ".git")) && existsSync7(join8(root, "cli", "package.json"))) return { kind: "checkout", root };
5377
+ if (self.includes(join8("node_modules", "@keyboxed", "cli"))) return { kind: "npm-global", prefix: npmPrefix(self) };
5073
5378
  return { kind: "unknown", path: self };
5074
5379
  }
5075
5380
  function newer(a, b) {
@@ -5105,7 +5410,7 @@ async function update(opts) {
5105
5410
  let cliUpdated = false;
5106
5411
  if (install.kind === "checkout") {
5107
5412
  note(`Running from a git checkout (${install.root}).`);
5108
- const dirty = spawnSync2("git", ["status", "--porcelain"], { cwd: install.root, encoding: "utf8" }).stdout.trim();
5413
+ const dirty = spawnSync3("git", ["status", "--porcelain"], { cwd: install.root, encoding: "utf8" }).stdout.trim();
5109
5414
  if (opts.check) note("Update it with: git pull && npm install && npm run build");
5110
5415
  else if (dirty) warn("The checkout has local changes; skipping git pull. Update it yourself, then run keybox update again.");
5111
5416
  else if (opts.yes || await confirm("Pull and rebuild the checkout?", true)) {
@@ -5121,7 +5426,8 @@ async function update(opts) {
5121
5426
  else if (install.kind === "npx") note(`You run Keybox through npx. Use npx @keyboxed/cli@${v} \u2026 from now on.`);
5122
5427
  else if (install.kind === "unknown") note(`Installed somewhere unusual (${install.path}). Install ${v} the way you installed this one.`);
5123
5428
  else if (opts.yes || await confirm(`Install @keyboxed/cli ${v}?`, true)) {
5124
- const args = ["install", "-g", "--prefer-online", `@keyboxed/cli@${v}`];
5429
+ const prefix = install.kind === "npm-global" ? install.prefix : void 0;
5430
+ const args = ["install", "-g", "--prefer-online", ...prefix ? ["--prefix", prefix] : [], `@keyboxed/cli@${v}`];
5125
5431
  let code = await run2("npm", args);
5126
5432
  if (code !== 0) {
5127
5433
  note("Retrying in 20 seconds in case the release has not reached every npm mirror yet\u2026");
@@ -5135,7 +5441,7 @@ async function update(opts) {
5135
5441
  }
5136
5442
  if (cliUpdated) {
5137
5443
  ok("CLI updated. Continuing with the new version.");
5138
- const bin2 = install.kind === "checkout" ? [process.execPath, join7(install.root, "cli", "dist", "keybox.js")] : ["keybox"];
5444
+ const bin2 = install.kind === "checkout" ? [process.execPath, join8(install.root, "cli", "dist", "keybox.js")] : ["keybox"];
5139
5445
  const code = await run2(bin2[0], [...bin2.slice(1), "update", "--worker-only", ...opts.yes ? ["--yes"] : []]);
5140
5446
  process.exitCode = code;
5141
5447
  return;
@@ -5204,6 +5510,10 @@ Moving keys in (values are never printed, logged or put on a command line)
5204
5510
 
5205
5511
  Agents
5206
5512
  keybox agents create NAME --allow "GET api.github.com/repos/**" [--allow \u2026] [--deny \u2026]
5513
+ keybox agents allow NAME RULE [RULE \u2026] [--deny RULE]
5514
+ Add rules to an agent; keeps the ones it has
5515
+ keybox agents deny NAME RULE [RULE \u2026] Add deny rules to an agent
5516
+ keybox agents suggest NAME [--yes] Turn the calls it was refused into tight rules to pick from
5207
5517
  keybox agents list | rm NAME
5208
5518
  keybox agents token NAME [--ttl 30d] Long-lived token for a deployed agent
5209
5519
  keybox tokens revoke ID
@@ -5221,7 +5531,8 @@ Sharing (access to a key, never the key)
5221
5531
  keybox share list | rm ID
5222
5532
 
5223
5533
  Running
5224
- keybox run AGENT [--ttl 12h] [--clean-env] -- command [args]
5534
+ keybox run AGENT [--ttl 12h] [--clean-env] [--no-isolate] -- command [args]
5535
+ Hides this machine's Keybox credentials from the command
5225
5536
  keybox audit [--follow] [--limit 50]
5226
5537
  keybox blocked Calls Keybox never proxies
5227
5538
 
@@ -5258,6 +5569,7 @@ async function main(argv) {
5258
5569
  deny: { type: "string", multiple: true },
5259
5570
  ttl: { type: "string" },
5260
5571
  "clean-env": { type: "boolean", default: false },
5572
+ "no-isolate": { type: "boolean", default: false },
5261
5573
  from: { type: "string" },
5262
5574
  only: { type: "string" },
5263
5575
  vault: { type: "string" },
@@ -5384,6 +5696,12 @@ async function main(argv) {
5384
5696
  return secretsRm(need(arg, "secret name"));
5385
5697
  case "agents create":
5386
5698
  return agentsCreate(need(arg, "agent name"), { allow: o.allow, deny: o.deny });
5699
+ case "agents allow":
5700
+ return agentsAdd(need(arg, "agent name"), { allow: [...p.slice(3), ...o.allow ?? []], deny: o.deny });
5701
+ case "agents deny":
5702
+ return agentsAdd(need(arg, "agent name"), { deny: [...p.slice(3), ...o.deny ?? []] });
5703
+ case "agents suggest":
5704
+ return agentsSuggest(need(arg, "agent name"), { yes: o.yes, limit: o.limit === "50" ? "500" : o.limit });
5387
5705
  case "agents list":
5388
5706
  return agentsList();
5389
5707
  case "agents rm":
@@ -5397,7 +5715,7 @@ async function main(argv) {
5397
5715
  if (sub === "rm" || sub === "revoke") return shareRm(need(arg, "share id"));
5398
5716
  return shareCreate(sub, { allow: o.allow, deny: o.deny, uses: o.uses, ip: o.ip, country: o.country, expires: o.expires, label: o.label });
5399
5717
  case "run":
5400
- return run(need(sub, "agent name"), rest, { ttl: o.ttl ?? "12h", cleanEnv: o["clean-env"] });
5718
+ return run(need(sub, "agent name"), rest, { ttl: o.ttl ?? "12h", cleanEnv: o["clean-env"], isolate: !o["no-isolate"] });
5401
5719
  case "audit":
5402
5720
  return audit({ follow: o.follow, limit: o.limit });
5403
5721
  case "blocked":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keyboxed/cli",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
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",