@keyboxed/cli 0.2.2 → 0.2.3
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/skill/SKILL.md +3 -1
- package/assets/worker.js +38 -14
- package/dist/keybox.js +376 -77
- package/package.json +1 -1
package/assets/skill/SKILL.md
CHANGED
|
@@ -63,7 +63,7 @@ Prefer `keybox migrate`. It reads values itself, shows a table of names and host
|
|
|
63
63
|
| Bitwarden | user runs `bw unlock` and exports `BW_SESSION` themselves; then `keybox migrate --from bitwarden --item <search>` |
|
|
64
64
|
| Bitwarden Secrets Manager | `keybox migrate --from bws --project <id>` (needs `BWS_ACCESS_TOKEN` set by the user) |
|
|
65
65
|
| Doppler | `keybox migrate --from doppler --project <p> --config <c>` |
|
|
66
|
-
| Infisical | `keybox migrate --from infisical --
|
|
66
|
+
| Infisical | `keybox migrate --from infisical --dry-run` reads every project, environment and folder; narrow with `--project A,B --env dev` |
|
|
67
67
|
| HashiCorp Vault KV | `keybox migrate --from vault:secret/<path>` |
|
|
68
68
|
| sops | `keybox migrate --from sops:<file>` |
|
|
69
69
|
| AWS Secrets Manager | `keybox migrate --from aws:<secret-id>` |
|
|
@@ -76,6 +76,8 @@ Prefer `keybox migrate`. It reads values itself, shows a table of names and host
|
|
|
76
76
|
|
|
77
77
|
Running `keybox migrate` with no `--from` in a real terminal shows a picker of the sources it found. You usually do not have a real terminal, so pass `--from`.
|
|
78
78
|
|
|
79
|
+
Keys with no preset are left out of a non-interactive run. If the user wants them stored before deciding where they go, add `--park`: parked keys are encrypted but unusable until bound with `keybox secrets bind NAME --host HOST`. Never suggest a wildcard host; Keybox has none on purpose.
|
|
80
|
+
|
|
79
81
|
Keys Keybox does not recognise are skipped with a reason. For a custom API:
|
|
80
82
|
|
|
81
83
|
```bash
|
package/assets/worker.js
CHANGED
|
@@ -400,7 +400,7 @@ function inCidr(ip, cidr) {
|
|
|
400
400
|
}
|
|
401
401
|
|
|
402
402
|
// src/types.ts
|
|
403
|
-
var VERSION = "0.2.
|
|
403
|
+
var VERSION = "0.2.3";
|
|
404
404
|
function keyboxError(status, code, message) {
|
|
405
405
|
return Response.json({ type: "error", error: { type: "keybox_error", code, message } }, { status });
|
|
406
406
|
}
|
|
@@ -580,6 +580,7 @@ async function route(req, env, path, policy, who) {
|
|
|
580
580
|
return Response.json(out);
|
|
581
581
|
}
|
|
582
582
|
if (a === "secrets" && b && !c && m === "PUT") return putSecret(req, env, b);
|
|
583
|
+
if (a === "secrets" && b && !c && m === "PATCH") return bindSecret(req, env, b);
|
|
583
584
|
if (a === "secrets" && b && !c && m === "DELETE") {
|
|
584
585
|
const r = await env.DB.prepare("DELETE FROM secrets WHERE name = ?").bind(b).run();
|
|
585
586
|
return Response.json({ deleted: r.meta.changes > 0 });
|
|
@@ -627,31 +628,53 @@ async function route(req, env, path, policy, who) {
|
|
|
627
628
|
}
|
|
628
629
|
return keyboxError(404, "not_found", `No admin route ${m} /${seg.join("/")}.`);
|
|
629
630
|
}
|
|
630
|
-
|
|
631
|
-
const kek = await importKek(env.KEYBOX_KEK);
|
|
632
|
-
if (!kek) return keyboxError(503, "not_configured", "KEYBOX_KEK is not set.");
|
|
633
|
-
const b = await body(req);
|
|
631
|
+
function parseMeta(name, b) {
|
|
634
632
|
check2(SECRET_NAME.test(name), "secret names are UPPER_SNAKE_CASE, up to 64 characters");
|
|
635
|
-
check2(Array.isArray(b.hosts) && b.hosts.length
|
|
633
|
+
check2(Array.isArray(b.hosts) && b.hosts.length <= 16, "hosts must list up to 16 hostnames (an empty list parks the key)");
|
|
636
634
|
const hosts = [...new Set(b.hosts.map((h) => String(h).toLowerCase()))].sort();
|
|
637
635
|
for (const h of hosts) check2(isHostname(h), `not a public hostname: ${h}`);
|
|
638
636
|
check2(typeof b.header === "string" && HEADER.test(b.header), "header must be a plain header name");
|
|
639
637
|
const header = b.header.toLowerCase();
|
|
640
638
|
check2(!FORBIDDEN_HEADERS.has(header), `cannot inject into ${header}`);
|
|
641
639
|
check2(FORMATS.has(b.format), "format must be bearer, raw or basic");
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
check2(!/[\r\n\0]/.test(value), "value cannot contain line breaks");
|
|
646
|
-
const meta = { name, hosts, header, format: b.format };
|
|
640
|
+
return { name, hosts, header, format: b.format };
|
|
641
|
+
}
|
|
642
|
+
async function store(env, kek, meta, value) {
|
|
647
643
|
const { iv, ciphertext } = await seal(kek, meta, value);
|
|
648
644
|
const fp = await fingerprint(env.KEYBOX_KEK, value);
|
|
649
645
|
await env.DB.prepare(
|
|
650
646
|
`INSERT INTO secrets (name, hosts, header, format, iv, ciphertext, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
651
647
|
ON CONFLICT(name) DO UPDATE SET hosts = excluded.hosts, header = excluded.header, format = excluded.format,
|
|
652
648
|
iv = excluded.iv, ciphertext = excluded.ciphertext`
|
|
653
|
-
).bind(name, JSON.stringify(hosts), header, meta.format, iv, ciphertext, Date.now()).run();
|
|
654
|
-
return Response.json({
|
|
649
|
+
).bind(meta.name, JSON.stringify(meta.hosts), meta.header, meta.format, iv, ciphertext, Date.now()).run();
|
|
650
|
+
return Response.json({ ...meta, fingerprint: fp });
|
|
651
|
+
}
|
|
652
|
+
async function putSecret(req, env, name) {
|
|
653
|
+
const kek = await importKek(env.KEYBOX_KEK);
|
|
654
|
+
if (!kek) return keyboxError(503, "not_configured", "KEYBOX_KEK is not set.");
|
|
655
|
+
const b = await body(req);
|
|
656
|
+
const meta = parseMeta(name, b);
|
|
657
|
+
check2(typeof b.value === "string", "value is required");
|
|
658
|
+
const value = b.value;
|
|
659
|
+
check2(value.length >= 8 && value.length <= 8192, "value must be 8-8192 characters");
|
|
660
|
+
check2(!/[\r\n\0]/.test(value), "value cannot contain line breaks");
|
|
661
|
+
return store(env, kek, meta, value);
|
|
662
|
+
}
|
|
663
|
+
async function bindSecret(req, env, name) {
|
|
664
|
+
const kek = await importKek(env.KEYBOX_KEK);
|
|
665
|
+
if (!kek) return keyboxError(503, "not_configured", "KEYBOX_KEK is not set.");
|
|
666
|
+
const row = await env.DB.prepare("SELECT * FROM secrets WHERE name = ?").bind(name).first();
|
|
667
|
+
if (!row) return keyboxError(404, "not_found", `No secret named ${name}.`);
|
|
668
|
+
const old = { name, hosts: JSON.parse(row.hosts), header: row.header, format: row.format };
|
|
669
|
+
const b = await body(req);
|
|
670
|
+
const meta = parseMeta(name, { hosts: b.hosts ?? old.hosts, header: b.header ?? old.header, format: b.format ?? old.format });
|
|
671
|
+
let value;
|
|
672
|
+
try {
|
|
673
|
+
value = await open(kek, old, row.iv, row.ciphertext);
|
|
674
|
+
} catch {
|
|
675
|
+
return keyboxError(409, "undecryptable", `${name} cannot be decrypted with this Worker's key. Add it again with keybox secrets add.`);
|
|
676
|
+
}
|
|
677
|
+
return store(env, kek, meta, value);
|
|
655
678
|
}
|
|
656
679
|
async function putAgent(req, env, name) {
|
|
657
680
|
check2(AGENT_NAME.test(name), "agent names are lowercase letters, digits and dashes");
|
|
@@ -664,6 +687,7 @@ async function putAgent(req, env, name) {
|
|
|
664
687
|
const secret = String(g?.secret ?? "");
|
|
665
688
|
const hosts = hostsOf.get(secret);
|
|
666
689
|
check2(hosts, `unknown secret: ${secret}`);
|
|
690
|
+
check2(hosts.length, `${secret} is parked (no host yet). Bind one first: keybox secrets bind ${secret} --host HOST`);
|
|
667
691
|
check2(Array.isArray(g.allow) && g.allow.length > 0, `grant for ${secret} needs at least one allow rule`);
|
|
668
692
|
const allow = g.allow.map(String);
|
|
669
693
|
const deny = Array.isArray(g.deny) ? g.deny.map(String) : [];
|
|
@@ -960,7 +984,7 @@ var ui_default = `<!doctype html>
|
|
|
960
984
|
`;
|
|
961
985
|
|
|
962
986
|
// dist/ui.bundle.txt
|
|
963
|
-
var ui_bundle_default = '"use strict";(()=>{function C(t,a,o){let s=new Map,n=i=>/^\\S+\\s+([^/\\s]+)/.exec(i)?.[1]??"",r=i=>{let l=/^([A-Z][A-Z0-9_]*)=(.+)$/.exec(i);if(l)return[l[1],l[2].trim()];let d=n(i),u=o.filter(c=>c.hosts.includes(d));if(u.length===1)return[u[0].name,i];throw u.length===0?new Error(`No stored secret is bound to ${d||"that host"} (rule "${i}").`):new Error(`Several secrets are bound to ${d}; prefix the rule: "${u[0].name}=${i}".`)};for(let i of t){let[l,d]=r(i),u=s.get(l)??{secret:l,allow:[]};u.allow.push(d),s.set(l,u)}for(let i of a){let l=/^([A-Z][A-Z0-9_]*)=(.+)$/.exec(i),d=l?[s.get(l[1])]:[...s.values()].filter(c=>{let h=n(i);return h.includes("*")||o.find(p=>p.name===c.secret)?.hosts.includes(h)}),u=l?l[2].trim():i;if(!d.length||d.some(c=>!c))throw new Error(`Deny rule "${i}" does not apply to any allowed secret.`);for(let c of d)(c.deny??=[]).push(u)}return[...s.values()]}function R(t){let a=[],o=[];for(let s of t.split(/\\r?\\n/)){let n=s.replace(/#.*$/,"").trim();if(!n)continue;let r=/^(allow|deny)\\s+(.+)$/i.exec(n);r&&r[1].toLowerCase()==="deny"?o.push(r[2].trim()):a.push(r?r[2].trim():n)}return{allow:a,deny:o}}var k=[{id:"openrouter",label:"OpenRouter",hosts:["openrouter.ai"],header:"authorization",format:"bearer",prefixes:["OPENROUTER_"],pattern:"^sk-or-"},{id:"anthropic",label:"Anthropic",hosts:["api.anthropic.com"],header:"x-api-key",format:"raw",prefixes:["ANTHROPIC_","CLAUDE_"],pattern:"^sk-ant-",admin:"^sk-ant-admin",adminHint:"This is an Admin API key. Use a workspace API key for agents.",env:{ANTHROPIC_BASE_URL:"{base}/api.anthropic.com",ANTHROPIC_API_KEY:"{token}"}},{id:"openai",label:"OpenAI",hosts:["api.openai.com"],header:"authorization",format:"bearer",prefixes:["OPENAI_"],pattern:"^sk-(proj-|svcacct-|None-)?[A-Za-z0-9_-]{16,}",admin:"^sk-admin-",adminHint:"This is an organisation admin key. Use a project key for agents.",env:{OPENAI_BASE_URL:"{base}/api.openai.com/v1",OPENAI_API_KEY:"{token}"}},{id:"github",label:"GitHub",hosts:["api.github.com"],header:"authorization",format:"bearer",prefixes:["GITHUB_","GH_"],pattern:"^(ghp_|github_pat_|gho_|ghu_|ghs_)",admin:"^ghp_",adminHint:"Classic tokens reach every repo you can. Prefer a fine-grained token (github_pat_)."},{id:"stripe",label:"Stripe",hosts:["api.stripe.com"],header:"authorization",format:"bearer",prefixes:["STRIPE_"],pattern:"^(sk|rk)_(live|test)_",admin:"^sk_live_",adminHint:"This is a full live secret key. Prefer a restricted key (rk_live_)."},{id:"cloudflare",label:"Cloudflare",hosts:["api.cloudflare.com"],header:"authorization",format:"bearer",prefixes:["CLOUDFLARE_","CF_"]},{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}$"},{id:"groq",label:"Groq",hosts:["api.groq.com"],header:"authorization",format:"bearer",prefixes:["GROQ_"],pattern:"^gsk_"},{id:"mistral",label:"Mistral",hosts:["api.mistral.ai"],header:"authorization",format:"bearer",prefixes:["MISTRAL_"]},{id:"xai",label:"xAI",hosts:["api.x.ai"],header:"authorization",format:"bearer",prefixes:["XAI_","GROK_"],pattern:"^xai-"},{id:"deepseek",label:"DeepSeek",hosts:["api.deepseek.com"],header:"authorization",format:"bearer",prefixes:["DEEPSEEK_"]},{id:"perplexity",label:"Perplexity",hosts:["api.perplexity.ai"],header:"authorization",format:"bearer",prefixes:["PERPLEXITY_","PPLX_"],pattern:"^pplx-"},{id:"together",label:"Together",hosts:["api.together.xyz"],header:"authorization",format:"bearer",prefixes:["TOGETHER_"]},{id:"fireworks",label:"Fireworks",hosts:["api.fireworks.ai"],header:"authorization",format:"bearer",prefixes:["FIREWORKS_"],pattern:"^fw_"},{id:"cohere",label:"Cohere",hosts:["api.cohere.com"],header:"authorization",format:"bearer",prefixes:["COHERE_","CO_API_"]},{id:"huggingface",label:"Hugging Face",hosts:["huggingface.co","router.huggingface.co","api-inference.huggingface.co"],header:"authorization",format:"bearer",prefixes:["HF_","HUGGINGFACE_","HUGGING_FACE_"],pattern:"^hf_"},{id:"replicate",label:"Replicate",hosts:["api.replicate.com"],header:"authorization",format:"bearer",prefixes:["REPLICATE_"],pattern:"^r8_"},{id:"voyage",label:"Voyage AI",hosts:["api.voyageai.com"],header:"authorization",format:"bearer",prefixes:["VOYAGE_"]},{id:"elevenlabs",label:"ElevenLabs",hosts:["api.elevenlabs.io"],header:"xi-api-key",format:"raw",prefixes:["ELEVENLABS_","ELEVEN_","XI_"]},{id:"pinecone",label:"Pinecone",hosts:["api.pinecone.io"],header:"api-key",format:"raw",prefixes:["PINECONE_"],pattern:"^pcsk_"},{id:"tavily",label:"Tavily",hosts:["api.tavily.com"],header:"authorization",format:"bearer",prefixes:["TAVILY_"],pattern:"^tvly-"},{id:"exa",label:"Exa",hosts:["api.exa.ai"],header:"x-api-key",format:"raw",prefixes:["EXA_"]},{id:"firecrawl",label:"Firecrawl",hosts:["api.firecrawl.dev"],header:"authorization",format:"bearer",prefixes:["FIRECRAWL_"],pattern:"^fc-"},{id:"brave",label:"Brave Search",hosts:["api.search.brave.com"],header:"x-subscription-token",format:"raw",prefixes:["BRAVE_"]},{id:"resend",label:"Resend",hosts:["api.resend.com"],header:"authorization",format:"bearer",prefixes:["RESEND_"],pattern:"^re_"},{id:"sendgrid",label:"SendGrid",hosts:["api.sendgrid.com"],header:"authorization",format:"bearer",prefixes:["SENDGRID_"],pattern:"^SG\\\\."},{id:"postmark",label:"Postmark",hosts:["api.postmarkapp.com"],header:"x-postmark-server-token",format:"raw",prefixes:["POSTMARK_"]},{id:"slack",label:"Slack",hosts:["slack.com"],header:"authorization",format:"bearer",prefixes:["SLACK_"],pattern:"^xox[bpae]-"},{id:"linear",label:"Linear",hosts:["api.linear.app"],header:"authorization",format:"raw",prefixes:["LINEAR_"],pattern:"^lin_api_"},{id:"notion",label:"Notion",hosts:["api.notion.com"],header:"authorization",format:"bearer",prefixes:["NOTION_"],pattern:"^(ntn_|secret_)"},{id:"vercel",label:"Vercel",hosts:["api.vercel.com"],header:"authorization",format:"bearer",prefixes:["VERCEL_"]},{id:"netlify",label:"Netlify",hosts:["api.netlify.com"],header:"authorization",format:"bearer",prefixes:["NETLIFY_"]},{id:"digitalocean",label:"DigitalOcean",hosts:["api.digitalocean.com"],header:"authorization",format:"bearer",prefixes:["DIGITALOCEAN_","DO_"],pattern:"^dop_v1_"},{id:"sentry",label:"Sentry",hosts:["sentry.io"],header:"authorization",format:"bearer",prefixes:["SENTRY_"],pattern:"^sntry[us]_"}];var M=t=>k.find(a=>a.id===t);function Y(t){let a=t.toUpperCase();return k.find(o=>o.prefixes.some(s=>a.startsWith(s)))}function F(t){return k.find(a=>a.pattern&&new RegExp(a.pattern).test(t))}function O(t,a){let o=F(a),s=t?Y(t):void 0,n=o??s,r=n?{provider:n,via:o?"value":"name"}:{};return o&&s&&o.id!==s.id&&(r.mismatch=s),n?.admin&&new RegExp(n.admin).test(a)&&(r.adminHint=n.adminHint),r}function e(t,a={},...o){let s=document.createElement(t);for(let[n,r]of Object.entries(a))r===void 0||r===!1||(n.startsWith("on")&&typeof r=="function"?s.addEventListener(n.slice(2),r):n==="class"?s.className=String(r):n==="style"?s.style.cssText=String(r):n==="value"?s.value=String(r):s.setAttribute(n,r===!0?"":String(r)));for(let n of o)n!=null&&n!==!1&&s.append(n);return s}var x=class extends Error{constructor(o,s){super(s);this.status=o}status};async function m(t,a,o){let s=await fetch(`/_keybox/admin${a}`,{method:t,credentials:"same-origin",headers:{"x-keybox-ui":"1","content-type":"application/json"},body:o===void 0?void 0:JSON.stringify(o)}),n=await s.json().catch(()=>null);if(!s.ok)throw new x(s.status,n?.error?.message??`HTTP ${s.status}`);return n}var L=document.getElementById("app"),S=t=>t?new Date(t).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):"\\u2014";function z(t){if(!t)return"never";let a=Math.round((Date.now()-t)/1e3);return a<60?`${a}s ago`:a<3600?`${Math.round(a/60)}m ago`:a<86400?`${Math.round(a/3600)}h ago`:`${Math.round(a/86400)}d ago`}function g(t,a=!1){let o=e("div",{class:`toast${a?" err":""}`,role:"status"},t);document.body.append(o),setTimeout(()=>o.remove(),a?6e3:2800)}async function v(t,a){t&&(t.disabled=!0);try{await a()}catch(o){g(o.message,!0)}finally{t&&(t.disabled=!1)}}function j(t){return k.find(a=>a.hosts.some(o=>t.includes(o)))?.label??"Custom"}var b=t=>t.split(/[\\s,]+/).map(a=>a.trim()).filter(Boolean);function N(t,a,o){let s=e("dialog",{},e("div",{class:"stack"},e("h2",{},t),a,e("div",{class:"row"},...o)));return s.addEventListener("close",()=>s.remove()),document.body.append(s),s.showModal(),s}function K(t,a,o,s){let n=e("input",{class:"mono",placeholder:o,autocomplete:"off",spellcheck:"false"}),r=e("button",{class:"btn danger",type:"button",disabled:!0},"Delete");n.addEventListener("input",()=>r.disabled=n.value!==o);let i=N(t,e("div",{class:"stack"},e("p",{},a),e("label",{class:"field"},e("span",{},`Type ${o} to confirm`),n)),[r,e("button",{class:"btn ghost",type:"button",onclick:()=>i.close()},"Cancel")]);r.addEventListener("click",()=>v(r,async()=>{await s(),i.close()}))}try{let t=localStorage.getItem("kb-theme");(t==="light"||t==="dark")&&(document.documentElement.dataset.theme=t)}catch{}function W(){let t=document.documentElement,a=t.dataset.theme?t.dataset.theme==="dark":matchMedia("(prefers-color-scheme: dark)").matches;t.dataset.theme=a?"light":"dark";try{localStorage.setItem("kb-theme",t.dataset.theme)}catch{}}var U=()=>{let t=e("button",{class:"icon",type:"button",title:"Theme","aria-label":"Toggle dark theme",onclick:W});return t.innerHTML=\'<svg viewBox="0 0 20 20" width="18" height="18" aria-hidden="true"><circle cx="10" cy="10" r="7.25" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M10 2.75a7.25 7.25 0 0 1 0 14.5z" fill="currentColor"/></svg>\',t};async function V(){let t=/[#&]code=(kb_lnk_[A-Za-z0-9_-]+)/.exec(location.hash);if(!t)return;history.replaceState(null,"",location.pathname);let a=await fetch("/_keybox/ui/session",{method:"POST",credentials:"same-origin",headers:{"x-keybox-ui":"1","content-type":"application/json"},body:JSON.stringify({code:t[1]})});if(!a.ok){let o=await a.json().catch(()=>null);throw new Error(o?.error?.message??"Login failed.")}}function _(t){L.className="",L.replaceChildren(e("div",{class:"login stack"},e("div",{class:"row spread"},e("span",{class:"mark"},e("i"),"keybox"),U()),e("h1",{},"Sign in to ",e("span",{class:"muted"},"this Keybox.")),t?e("p",{class:"notice warn"},t):null,e("p",{class:"lede"},"Run this on the machine where you set up Keybox. It opens this page with a one-time link; your admin token never enters the browser."),e("pre",{},"keybox ui"),e("p",{class:"dim"},"If your team uses Cloudflare Access, put an Access application in front of /_keybox/ and add its audience tag under Access in the dashboard. Signing in through Access then works too.")))}var $=["Overview","Secrets","Agents","Activity","Access","Blocked"],f,T="Overview",H=null,A=e("main");function Z(){let t=e("nav",{class:"tabs","aria-label":"Sections"}),a=()=>{t.replaceChildren(...$.map(r=>e("button",{type:"button","aria-current":r===T?"page":void 0,onclick:()=>o(r)},r)))},o=r=>{T=r,location.hash=r.toLowerCase(),a(),y()},s=$.find(r=>r.toLowerCase()===location.hash.slice(1));s&&(T=s),a();let n=e("button",{class:"btn sm ghost",type:"button",onclick:async()=>{await fetch("/_keybox/ui/logout",{method:"POST",credentials:"same-origin",headers:{"x-keybox-ui":"1"}}),_("Signed out.")}},"Sign out");L.className="",L.replaceChildren(e("div",{class:"shell"},e("header",{class:"top"},e("a",{class:"mark",href:"#overview",onclick:()=>o("Overview")},e("i"),"keybox"),t,e("div",{class:"top-end"},U(),f.via==="token"?null:n)),A)),window.addEventListener("hashchange",()=>{let r=$.find(i=>i.toLowerCase()===location.hash.slice(1));r&&r!==T&&o(r)})}async function y(){H?.(),H=null,A.replaceChildren(e("p",{class:"mono dim",style:"margin-top:48px"},"loading\\u2026"));try{let t={Overview:q,Secrets:J,Agents:ae,Activity:ne,Access:oe,Blocked:re}[T];A.replaceChildren(await t())}catch(t){if(t instanceof x&&t.status===401)return _("Your session has ended.");A.replaceChildren(e("p",{class:"notice warn",style:"margin-top:48px"},t.message))}}var w=(t,a,o)=>[e("h1",{},t," ",e("span",{class:"muted"},a)),e("p",{class:"lede"},o)];async function q(){let[t,a,o,s]=await Promise.all([m("GET","/secrets"),m("GET","/agents"),m("GET","/stats"),m("GET","/policy")]),n=(i,l)=>e("div",{class:"card stat"},e("b",{},String(i)),e("span",{},l)),r=i=>i&&Object.keys(i).length?"restricted":"open to any network";return e("section",{},...w("Keys stay","in the box.","Agents call APIs through this Worker. They hold Keybox tokens; the real keys never leave it."),e("div",{class:"grid stats"},n(t.length,"secrets"),n(a.length,"agents"),n(o.allow??0,"allowed \\xB7 24h"),n((o.deny??0)+(o.error??0),"refused \\xB7 24h")),e("div",{class:"grid",style:"grid-template-columns:repeat(auto-fit,minmax(280px,1fr))"},e("div",{class:"card accent stack"},e("p",{class:"eyebrow"},"You"),e("p",{class:"mono",style:"margin:0"},`${f.ip??"unknown address"} \\xB7 ${f.country??"??"}`),e("p",{class:"dim",style:"margin:0"},f.via==="access"?`Signed in with Cloudflare Access as ${f.email}`:f.via==="session"?"Signed in with a one-time link from `keybox ui`.":"Using the admin token.")),e("div",{class:"card stack"},e("p",{class:"eyebrow"},"Network"),e("p",{style:"margin:0"},`Dashboard and admin API: ${r(s.admin)}.`),e("p",{style:"margin:0"},`Agent calls: ${r(s.proxy)}.`),e("div",{},e("button",{class:"btn sm",type:"button",onclick:()=>location.hash="access"},"Review access rules")))))}function X(t,a){let o=e("input",{type:"password",autocomplete:"off",spellcheck:"false","data-1p-ignore":!0,"data-lpignore":"true",placeholder:"Paste the key","aria-describedby":"key-detect"}),s=e("span",{class:"meter"},""),n=e("div",{class:"row",id:"key-detect","aria-live":"polite"}),r=()=>{let i=o.value.trim();if(s.textContent=i?`${i.length}`:"",n.replaceChildren(),!i)return a(null);/\\s/.test(i)&&n.append(e("span",{class:"chip warn"},"contains whitespace")),i.length<8&&n.append(e("span",{class:"chip warn"},"too short"));let l=O(t.value,i);l.provider?n.append(e("span",{class:l.via==="value"?"chip ok":"chip"},l.via==="value"?`\\u2713 looks like ${l.provider.label}`:`${l.provider.label} (from the name)`)):n.append(e("span",{class:"chip"},"unknown provider \\xB7 set hosts below")),l.mismatch&&n.append(e("span",{class:"chip warn"},`name says ${l.mismatch.label}`)),l.adminHint&&n.append(e("span",{class:"chip warn"},l.adminHint)),a(l.provider?.id??null)};return o.addEventListener("input",r),t.addEventListener("input",r),{el:e("div",{class:"stack"},e("div",{class:"keyfield"},o,s),n),input:o}}function G(t,a){let o=e("input",{class:"mono",placeholder:"OPENAI_API_KEY",autocomplete:"off",spellcheck:"false",value:t?.name??"",readonly:!!t}),s=e("select",{},e("option",{value:""},"Custom host\\u2026"),...k.map(p=>e("option",{value:p.id},`${p.label} \\xB7 ${p.hosts[0]}`))),n=e("input",{class:"mono",placeholder:"api.example.com",value:t?.hosts.join(", ")??""}),r=e("input",{class:"mono",value:t?.header??"authorization"}),i=e("select",{},...["bearer","raw","basic"].map(p=>e("option",{value:p},p)));i.value=t?.format??"bearer";let l=!!t,d=p=>{let E=M(p);E&&(s.value=p,n.value=E.hosts.join(", "),r.value=E.header,i.value=E.format)};s.addEventListener("change",()=>{l=!0,d(s.value)});let u=X(o,p=>{p&&!l&&d(p)}),c=e("button",{class:"btn primary",type:"submit"},t?"Rotate key":"Store key"),h=e("form",{class:"card accent stack",autocomplete:"off"},e("p",{class:"eyebrow"},t?`Rotate ${t.name}`:"Add a key"),e("div",{class:"cols"},e("label",{class:"field"},e("span",{},"Name"),o),e("label",{class:"field"},e("span",{},"Provider"),s)),e("label",{class:"field"},e("span",{},"Value"),u.el,e("small",{},"Sent once to this Worker and encrypted. It is never shown again, here or anywhere.")),e("div",{class:"cols"},e("label",{class:"field"},e("span",{},"Only sent to"),n),e("label",{class:"field"},e("span",{},"Header"),r),e("label",{class:"field"},e("span",{},"Format"),i)),e("div",{class:"row"},c,a?e("button",{class:"btn ghost",type:"button",onclick:a},"Cancel"):null));return h.addEventListener("submit",p=>{p.preventDefault(),v(c,async()=>{let E=u.input.value.trim(),I=o.value.trim().toUpperCase();if(!/^[A-Z][A-Z0-9_]{0,63}$/.test(I))throw new Error("Names are UPPER_SNAKE_CASE.");let B=await m("PUT",`/secrets/${I}`,{hosts:b(n.value),header:r.value.trim(),format:i.value,value:E});u.input.value="",g(`Stored ${I} \\xB7 fingerprint ${B.fingerprint}`),a?.(),y()})}),h}async function J(){let t=await m("GET","/secrets"),a=e("div"),o=e("button",{class:"btn primary",type:"button",onclick:()=>a.replaceChildren(G(void 0,()=>a.replaceChildren()))},"Add key"),s=e("table",{class:"table cards"},e("thead",{},e("tr",{},...["Name","Only sent to","Header","Fingerprint","Last used",""].map(n=>e("th",{},n)))),e("tbody",{},...t.map(n=>e("tr",{},e("td",{},e("b",{class:"mono"},n.name),e("div",{class:"dim"},j(n.hosts))),e("td",{class:"mono","data-l":"hosts"},n.hosts.join(", ")),e("td",{class:"mono","data-l":"header"},`${n.header} (${n.format})`),e("td",{class:"mono","data-l":"fp",title:"HMAC of the value. Same key, same fingerprint."},n.fingerprint??"\\u2014"),e("td",{"data-l":"used",title:S(n.last_used)},z(n.last_used)),e("td",{},e("div",{class:"row"},e("button",{class:"btn sm",type:"button",onclick:()=>a.replaceChildren(G(n,()=>a.replaceChildren()))},"Rotate"),e("button",{class:"btn sm danger",type:"button",onclick:()=>K(`Delete ${n.name}?`,"Agents that use it will start failing. Revoke the key at the provider too.",n.name,async()=>{await m("DELETE",`/secrets/${n.name}`),g(`Deleted ${n.name}.`),y()})},"Delete")))))));return e("section",{class:"stack"},...w("Secrets","write-only.","You can add, rotate and delete keys here. You cannot read one back: not here, not with the admin token, not through an agent. The fingerprint tells you which key is stored."),e("div",{class:"row"},o),a,t.length?e("div",{class:"scroll"},s):e("p",{class:"notice"},"No keys yet. Add one, or run `keybox migrate` to bring them in from a .env file or a password manager."))}function Q(t){if(!t)return"";let a=new Set(t.grants.map(o=>o.secret)).size>1;return t.grants.flatMap(o=>[...o.allow.map(s=>`allow ${a?`${o.secret}=`:""}${s}`),...(o.deny??[]).map(s=>`deny ${a?`${o.secret}=`:""}${s}`)]).join(`\n`)}function D(t,a,o){let s=e("input",{class:"mono",placeholder:"writer",value:a?.name??"",readonly:!!a,autocomplete:"off"}),n=e("textarea",{spellcheck:"false",placeholder:`allow POST api.openai.com/v1/responses\nallow GET api.github.com/repos/acme/**\ndeny * api.github.com/repos/acme/secrets/**`});n.value=Q(a);let r=e("div",{class:"dim mono",style:"font-size:13px"}),i=()=>{try{let{allow:u,deny:c}=R(n.value);if(!u.length)return void r.replaceChildren("Add at least one allow rule.");let h=C(u,c,t);r.replaceChildren(...h.map(p=>e("div",{},`\\u2713 ${p.allow.length} allow${p.deny?.length?`, ${p.deny.length} deny`:""} with ${p.secret}`)))}catch(u){r.replaceChildren(e("span",{class:"bad-t"},u.message))}};n.addEventListener("input",i),i();let l=e("button",{class:"btn primary",type:"submit"},a?"Save rules":"Create agent"),d=e("form",{class:"card accent stack"},e("p",{class:"eyebrow"},a?`Edit ${a.name}`:"New agent"),e("label",{class:"field"},e("span",{},"Name"),s),e("label",{class:"field"},e("span",{},"Rules"),n,e("small",{},"One per line: METHOD host/path. * is one path segment, ** is any. Prefix SECRET= when several keys share a host. Everything else is denied.")),r,e("div",{class:"row"},l,o?e("button",{class:"btn ghost",type:"button",onclick:o},"Cancel"):null));return d.addEventListener("submit",u=>{u.preventDefault(),v(l,async()=>{let{allow:c,deny:h}=R(n.value),p=C(c,h,t);await m("PUT",`/agents/${s.value.trim()}`,{grants:p}),g(`Saved ${s.value.trim()}.`),o?.(),y()})}),d}function ee(t){let a=e("select",{},...[["1h",3600],["12h",43200],["7d",604800],["30d",2592e3],["90d",7776e3]].map(([r,i])=>e("option",{value:String(i)},String(r))));a.value="2592000";let o=e("div",{class:"stack"}),s=e("button",{class:"btn primary",type:"button"},"Create token"),n=N(`Token for ${t}`,e("div",{class:"stack"},e("p",{class:"dim",style:"margin:0"},"For servers and CI. Store it in that platform\\u2019s secret store. It is shown once."),e("label",{class:"field"},e("span",{},"Expires after"),a),o),[s,e("button",{class:"btn ghost",type:"button",onclick:()=>n.close()},"Close")]);s.addEventListener("click",()=>v(s,async()=>{let r=await m("POST",`/agents/${t}/tokens`,{ttl:Number(a.value)}),i=e("code",{},r.token),l=e("button",{class:"btn sm",type:"button"},"Copy");l.addEventListener("click",async()=>{await navigator.clipboard.writeText(r.token),l.textContent="Copied"}),o.replaceChildren(e("div",{class:"secret-once"},i,l),e("p",{class:"dim",style:"margin:0"},`id ${r.id} \\xB7 expires ${S(r.expires_at)}`)),s.remove(),n.addEventListener("close",()=>{y()})}))}async function te(t){let o=(await m("GET",`/agents/${t}/tokens`)).filter(r=>!r.revoked_at&&r.expires_at>Date.now()),s=e("div",{class:"stack"},...o.length?o.map(r=>{let i=e("button",{class:"btn sm danger",type:"button"},"Revoke"),l=e("div",{class:"row spread"},e("span",{class:"mono",style:"font-size:13px"},`${r.id.slice(0,8)} \\xB7 expires ${S(r.expires_at)}`),i);return i.addEventListener("click",()=>v(i,async()=>{await m("DELETE",`/tokens/${r.id}`),l.remove(),g("Revoked.")})),l}):[e("p",{class:"dim"},"No active tokens.")]),n=N(`Active tokens \\xB7 ${t}`,s,[e("button",{class:"btn ghost",type:"button",onclick:()=>n.close()},"Close")]);n.addEventListener("close",()=>{y()})}async function ae(){let[t,a,o]=await Promise.all([m("GET","/agents"),m("GET","/secrets"),m("GET","/policy")]),s=e("div"),n=e("button",{class:"btn primary",type:"button",onclick:()=>s.replaceChildren(D(a,void 0,()=>s.replaceChildren()))},"New agent"),r=t.map(i=>{let l=o.agents?.[i.name];return e("article",{class:"card agent"},e("div",{class:"row spread"},e("h3",{class:"mono"},i.name),e("span",{class:"chip accent"},`${i.active_tokens} active token${i.active_tokens===1?"":"s"}`)),e("ul",{class:"rules"},...i.grants.flatMap(d=>[...d.allow.map(u=>e("li",{},e("span",{class:"k"},"allow"),u,e("span",{class:"dim"},` \\xB7 ${d.secret}`))),...(d.deny??[]).map(u=>e("li",{class:"deny"},e("span",{class:"k"},"deny"),u))])),l?e("p",{class:"dim",style:"margin:0;font-size:13px"},`Network: ${se(l)}`):null,e("div",{class:"row"},e("button",{class:"btn sm",type:"button",onclick:()=>s.replaceChildren(D(a,i,()=>s.replaceChildren()))},"Edit rules"),e("button",{class:"btn sm",type:"button",onclick:()=>ee(i.name)},"New token"),e("button",{class:"btn sm ghost",type:"button",onclick:()=>{te(i.name)}},"Tokens"),e("button",{class:"btn sm danger",type:"button",onclick:()=>K(`Delete ${i.name}?`,"Its tokens stop working immediately.",i.name,async()=>{await m("DELETE",`/agents/${i.name}`),g(`Deleted ${i.name}.`),y()})},"Delete")))});return e("section",{class:"stack"},...w("Agents","and their rules.","Each agent can make exactly the calls its rules allow, with the key bound to that host. Key-minting calls are always blocked, whatever the rules say."),e("div",{class:"row"},n),s,t.length?e("div",{class:"grid",style:"grid-template-columns:repeat(auto-fit,minmax(min(100%,420px),1fr))"},...r):e("p",{class:"notice"},"No agents yet."))}async function ne(){let t=await m("GET","/audit?limit=200"),a=e("select",{},e("option",{value:""},"All results"),e("option",{value:"allow"},"Allowed"),e("option",{value:"deny"},"Refused"),e("option",{value:"error"},"Errors")),o=e("input",{placeholder:"Filter by agent, host or path",class:"mono"}),s=e("input",{type:"checkbox",checked:!0}),n=e("tbody"),r=()=>{let d=o.value.trim().toLowerCase(),u=t.filter(c=>!a.value||c.decision===a.value).filter(c=>!d||`${c.agent} ${c.host}${c.path} ${c.secret} ${c.reason}`.toLowerCase().includes(d)).slice(-300).reverse();n.replaceChildren(...u.map(c=>e("tr",{},e("td",{"data-l":"time",title:S(c.ts)},z(c.ts)),e("td",{class:"mono","data-l":"agent"},c.agent??"\\u2014"),e("td",{class:`mono ${c.decision==="allow"?"ok-t":"bad-t"}`,"data-l":"result"},c.decision==="allow"?String(c.status):c.decision.toUpperCase()),e("td",{class:"mono","data-l":"request"},`${c.method} ${c.host??""}${c.path??""}`),e("td",{class:"mono dim","data-l":"detail"},c.secret??c.reason??""))))};a.addEventListener("change",r),o.addEventListener("input",r),r();let i=0,l=async()=>{if(s.checked&&document.visibilityState==="visible")try{let d=await m("GET",`/audit?after=${t.at(-1)?.id??0}&limit=500`);d.length&&(t=[...t,...d].slice(-2e3),r())}catch{}i=window.setTimeout(l,3e3)};return i=window.setTimeout(l,3e3),H=()=>clearTimeout(i),e("section",{class:"stack"},...w("Activity","every call, on the record.","Each request an agent makes, whether Keybox allowed it, and which key it used. Stored in your own D1 database."),e("div",{class:"row"},e("div",{style:"flex:1;min-width:200px"},o),e("div",{style:"width:170px"},a),e("label",{class:"check"},s,"Live")),e("div",{class:"scroll"},e("table",{class:"table cards"},e("thead",{},e("tr",{},...["When","Agent","Result","Request","Key / reason"].map(d=>e("th",{},d)))),n)))}function se(t){if(!t||!Object.keys(t).length)return"any network";let a=[];return t.allowIps?.length&&a.push(`from ${t.allowIps.join(", ")}`),t.allowCountries?.length&&a.push(`in ${t.allowCountries.join(", ")}`),t.denyCountries?.length&&a.push(`never from ${t.denyCountries.join(", ")}`),a.join("; ")}function P(t,a,o){let s=e("textarea",{spellcheck:"false",placeholder:`203.0.113.0/24\n2001:db8::/32`,style:"min-height:90px"});s.value=(o?.allowIps??[]).join(`\n`);let n=e("input",{class:"mono",placeholder:"US, CA",value:(o?.allowCountries??[]).join(", ")}),r=e("input",{class:"mono",placeholder:"T1 (Tor)",value:(o?.denyCountries??[]).join(", ")});return{el:e("div",{class:"card stack"},e("div",{},e("h3",{},t),e("p",{class:"dim",style:"margin:4px 0 0"},a)),e("label",{class:"field"},e("span",{},"Allowed IPs and ranges"),s,e("small",{},"Empty means any address.")),e("div",{class:"cols"},e("label",{class:"field"},e("span",{},"Only these countries"),n),e("label",{class:"field"},e("span",{},"Never these countries"),r))),value:()=>{let d={};return b(s.value).length&&(d.allowIps=b(s.value)),b(n.value).length&&(d.allowCountries=b(n.value).map(u=>u.toUpperCase())),b(r.value).length&&(d.denyCountries=b(r.value).map(u=>u.toUpperCase())),d}}}async function oe(){let[t,a]=await Promise.all([m("GET","/policy"),m("GET","/agents")]),o=P("Dashboard and admin API","Who can manage this Keybox, including the CLI.",t.admin),s=P("Agent calls","Where agents may call from. Applies to every agent token.",t.proxy),n=a.map(h=>({name:h.name,ed:P(`Agent \\xB7 ${h.name}`,"Extra limits for this agent only, on top of the rule above.",t.agents?.[h.name])})),r=e("input",{class:"mono",placeholder:"myteam.cloudflareaccess.com",value:t.access?.teamDomain??""}),i=e("input",{class:"mono",placeholder:"64-character Application Audience (AUD) tag",value:t.access?.aud??""}),l=e("input",{type:"checkbox"}),d=e("label",{class:"check",hidden:!0},l,"Save anyway. I know this may lock me out of the dashboard."),u=e("button",{class:"btn primary",type:"button"},"Save rules");u.addEventListener("click",()=>v(u,async()=>{let h={admin:o.value(),proxy:s.value(),agents:Object.fromEntries(n.map(p=>[p.name,p.ed.value()]))};(r.value.trim()||i.value.trim())&&(h.access={teamDomain:r.value.trim(),aud:i.value.trim()});try{await m("PUT","/policy",{policy:h,force:l.checked}),g("Saved. Rules apply within a few seconds."),d.hidden=!0,l.checked=!1}catch(p){throw/lock out|would block you/.test(p.message)&&(d.hidden=!1),p}}));let c=e("button",{class:"btn sm danger",type:"button"},"Sign out every dashboard session");return c.addEventListener("click",()=>v(c,async()=>{let h=await m("DELETE","/sessions");g(`Ended ${h.revoked} session${h.revoked===1?"":"s"}.`)})),e("section",{class:"stack"},...w("Access","by network and identity.","Limit who can reach this Keybox. Rules are enforced in the Worker, before any key is decrypted."),e("p",{class:"notice"},`You are calling from ${f.ip??"an unknown address"} (${f.country??"??"}). Keybox will not save an admin rule that blocks you unless you insist. If you do lock yourself out, delete the rule with wrangler: npx wrangler d1 execute <name> --remote --command "DELETE FROM settings WHERE key = \'policy\'"`),o.el,s.el,...n.map(h=>h.ed.el),e("div",{class:"card stack"},e("div",{},e("h3",{},"Cloudflare Access"),e("p",{class:"dim",style:"margin:4px 0 0"},"Put an Access application in front of this Worker\\u2019s /_keybox/ path (SSO, passkeys, device posture), then paste its details here. A valid Access login then signs you in to the dashboard.")),e("div",{class:"cols"},e("label",{class:"field"},e("span",{},"Team domain"),r),e("label",{class:"field"},e("span",{},"Audience tag"),i))),d,e("div",{class:"row spread"},u,c))}async function re(){let t=await m("GET","/blocked");return e("section",{class:"stack"},...w("Never","proxied.","Calls that would mint a new key or grant lasting access. No agent rule can allow them."),e("div",{class:"scroll"},e("table",{class:"table cards"},e("thead",{},e("tr",{},e("th",{},"Rule"),e("th",{},"Why"))),e("tbody",{},...t.map(a=>e("tr",{},e("td",{class:"mono"},a.rule),e("td",{},a.reason)))))))}(async()=>{try{await V()}catch(t){return _(t.message)}try{f=await m("GET","/whoami")}catch(t){return t instanceof x&&t.status===403?_(t.message):_()}Z(),y()})();})();\n';
|
|
987
|
+
var ui_bundle_default = '"use strict";(()=>{function C(t,a,o){let s=new Map,n=i=>/^\\S+\\s+([^/\\s]+)/.exec(i)?.[1]??"",r=i=>{let l=/^([A-Z][A-Z0-9_]*)=(.+)$/.exec(i);if(l)return[l[1],l[2].trim()];let d=n(i),p=o.filter(c=>c.hosts.includes(d));if(p.length===1)return[p[0].name,i];throw p.length===0?new Error(`No stored secret is bound to ${d||"that host"} (rule "${i}").`):new Error(`Several secrets are bound to ${d}; prefix the rule: "${p[0].name}=${i}".`)};for(let i of t){let[l,d]=r(i),p=s.get(l)??{secret:l,allow:[]};p.allow.push(d),s.set(l,p)}for(let i of a){let l=/^([A-Z][A-Z0-9_]*)=(.+)$/.exec(i),d=l?[s.get(l[1])]:[...s.values()].filter(c=>{let h=n(i);return h.includes("*")||o.find(u=>u.name===c.secret)?.hosts.includes(h)}),p=l?l[2].trim():i;if(!d.length||d.some(c=>!c))throw new Error(`Deny rule "${i}" does not apply to any allowed secret.`);for(let c of d)(c.deny??=[]).push(p)}return[...s.values()]}function R(t){let a=[],o=[];for(let s of t.split(/\\r?\\n/)){let n=s.replace(/#.*$/,"").trim();if(!n)continue;let r=/^(allow|deny)\\s+(.+)$/i.exec(n);r&&r[1].toLowerCase()==="deny"?o.push(r[2].trim()):a.push(r?r[2].trim():n)}return{allow:a,deny:o}}var k=[{id:"openrouter",label:"OpenRouter",hosts:["openrouter.ai"],header:"authorization",format:"bearer",prefixes:["OPENROUTER_"],pattern:"^sk-or-"},{id:"anthropic",label:"Anthropic",hosts:["api.anthropic.com"],header:"x-api-key",format:"raw",prefixes:["ANTHROPIC_","CLAUDE_"],pattern:"^sk-ant-",admin:"^sk-ant-admin",adminHint:"This is an Admin API key. Use a workspace API key for agents.",env:{ANTHROPIC_BASE_URL:"{base}/api.anthropic.com",ANTHROPIC_API_KEY:"{token}"}},{id:"openai",label:"OpenAI",hosts:["api.openai.com"],header:"authorization",format:"bearer",prefixes:["OPENAI_"],pattern:"^sk-(proj-|svcacct-|None-)?[A-Za-z0-9_-]{16,}",admin:"^sk-admin-",adminHint:"This is an organisation admin key. Use a project key for agents.",env:{OPENAI_BASE_URL:"{base}/api.openai.com/v1",OPENAI_API_KEY:"{token}"}},{id:"github",label:"GitHub",hosts:["api.github.com"],header:"authorization",format:"bearer",prefixes:["GITHUB_","GH_"],pattern:"^(ghp_|github_pat_|gho_|ghu_|ghs_)",admin:"^ghp_",adminHint:"Classic tokens reach every repo you can. Prefer a fine-grained token (github_pat_)."},{id:"stripe",label:"Stripe",hosts:["api.stripe.com"],header:"authorization",format:"bearer",prefixes:["STRIPE_"],pattern:"^(sk|rk)_(live|test)_",admin:"^sk_live_",adminHint:"This is a full live secret key. Prefer a restricted key (rk_live_)."},{id:"cloudflare",label:"Cloudflare",hosts:["api.cloudflare.com"],header:"authorization",format:"bearer",prefixes:["CLOUDFLARE_","CF_"],pattern:"^cf[a-z]t_"},{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}$"},{id:"groq",label:"Groq",hosts:["api.groq.com"],header:"authorization",format:"bearer",prefixes:["GROQ_"],pattern:"^gsk_"},{id:"mistral",label:"Mistral",hosts:["api.mistral.ai"],header:"authorization",format:"bearer",prefixes:["MISTRAL_"]},{id:"xai",label:"xAI",hosts:["api.x.ai"],header:"authorization",format:"bearer",prefixes:["XAI_","GROK_"],pattern:"^xai-"},{id:"deepseek",label:"DeepSeek",hosts:["api.deepseek.com"],header:"authorization",format:"bearer",prefixes:["DEEPSEEK_"]},{id:"perplexity",label:"Perplexity",hosts:["api.perplexity.ai"],header:"authorization",format:"bearer",prefixes:["PERPLEXITY_","PPLX_"],pattern:"^pplx-"},{id:"together",label:"Together",hosts:["api.together.xyz"],header:"authorization",format:"bearer",prefixes:["TOGETHER_"]},{id:"fireworks",label:"Fireworks",hosts:["api.fireworks.ai"],header:"authorization",format:"bearer",prefixes:["FIREWORKS_"],pattern:"^fw_"},{id:"cohere",label:"Cohere",hosts:["api.cohere.com"],header:"authorization",format:"bearer",prefixes:["COHERE_","CO_API_"]},{id:"huggingface",label:"Hugging Face",hosts:["huggingface.co","router.huggingface.co","api-inference.huggingface.co"],header:"authorization",format:"bearer",prefixes:["HF_","HUGGINGFACE_","HUGGING_FACE_"],pattern:"^hf_"},{id:"replicate",label:"Replicate",hosts:["api.replicate.com"],header:"authorization",format:"bearer",prefixes:["REPLICATE_"],pattern:"^r8_"},{id:"voyage",label:"Voyage AI",hosts:["api.voyageai.com"],header:"authorization",format:"bearer",prefixes:["VOYAGE_"]},{id:"elevenlabs",label:"ElevenLabs",hosts:["api.elevenlabs.io"],header:"xi-api-key",format:"raw",prefixes:["ELEVENLABS_","ELEVEN_","XI_"]},{id:"pinecone",label:"Pinecone",hosts:["api.pinecone.io"],header:"api-key",format:"raw",prefixes:["PINECONE_"],pattern:"^pcsk_"},{id:"tavily",label:"Tavily",hosts:["api.tavily.com"],header:"authorization",format:"bearer",prefixes:["TAVILY_"],pattern:"^tvly-"},{id:"exa",label:"Exa",hosts:["api.exa.ai"],header:"x-api-key",format:"raw",prefixes:["EXA_"]},{id:"firecrawl",label:"Firecrawl",hosts:["api.firecrawl.dev"],header:"authorization",format:"bearer",prefixes:["FIRECRAWL_"],pattern:"^fc-"},{id:"brave",label:"Brave Search",hosts:["api.search.brave.com"],header:"x-subscription-token",format:"raw",prefixes:["BRAVE_"]},{id:"resend",label:"Resend",hosts:["api.resend.com"],header:"authorization",format:"bearer",prefixes:["RESEND_"],pattern:"^re_"},{id:"sendgrid",label:"SendGrid",hosts:["api.sendgrid.com"],header:"authorization",format:"bearer",prefixes:["SENDGRID_"],pattern:"^SG\\\\."},{id:"postmark",label:"Postmark",hosts:["api.postmarkapp.com"],header:"x-postmark-server-token",format:"raw",prefixes:["POSTMARK_"]},{id:"slack",label:"Slack",hosts:["slack.com"],header:"authorization",format:"bearer",prefixes:["SLACK_"],pattern:"^xox[bpae]-"},{id:"linear",label:"Linear",hosts:["api.linear.app"],header:"authorization",format:"raw",prefixes:["LINEAR_"],pattern:"^lin_api_"},{id:"notion",label:"Notion",hosts:["api.notion.com"],header:"authorization",format:"bearer",prefixes:["NOTION_"],pattern:"^(ntn_|secret_)"},{id:"vercel",label:"Vercel",hosts:["api.vercel.com"],header:"authorization",format:"bearer",prefixes:["VERCEL_"]},{id:"netlify",label:"Netlify",hosts:["api.netlify.com"],header:"authorization",format:"bearer",prefixes:["NETLIFY_"]},{id:"digitalocean",label:"DigitalOcean",hosts:["api.digitalocean.com"],header:"authorization",format:"bearer",prefixes:["DIGITALOCEAN_","DO_"],pattern:"^dop_v1_"},{id:"workos",label:"WorkOS",hosts:["api.workos.com"],header:"authorization",format:"bearer",prefixes:["WORKOS_"]},{id:"retell",label:"Retell AI",hosts:["api.retellai.com"],header:"authorization",format:"bearer",prefixes:["RETELL_"]},{id:"nvidia",label:"NVIDIA NIM",hosts:["integrate.api.nvidia.com"],header:"authorization",format:"bearer",prefixes:["NVIDIA_","NVAPI","NIM_"],pattern:"^nvapi-"},{id:"plane",label:"Plane",hosts:["api.plane.so"],header:"x-api-key",format:"raw",prefixes:["PLANE_"],pattern:"^plane_api_"},{id:"crates",label:"crates.io",hosts:["crates.io"],header:"authorization",format:"raw",prefixes:["CRATES_IO_","CARGO_REGISTRY_TOKEN"],pattern:"^cio[A-Za-z0-9]{30,}$"},{id:"sentry",label:"Sentry",hosts:["sentry.io"],header:"authorization",format:"bearer",prefixes:["SENTRY_"],pattern:"^sntry[us]_"}];var M=t=>k.find(a=>a.id===t);function F(t){let a=t.toUpperCase();return k.find(o=>o.prefixes.some(s=>a.startsWith(s)))}function W(t){return k.find(a=>a.pattern&&new RegExp(a.pattern).test(t))}function G(t,a){let o=W(a),s=t?F(t):void 0,n=o??s,r=n?{provider:n,via:o?"value":"name"}:{};return o&&s&&o.id!==s.id&&(r.mismatch=s),n?.admin&&new RegExp(n.admin).test(a)&&(r.adminHint=n.adminHint),r}function e(t,a={},...o){let s=document.createElement(t);for(let[n,r]of Object.entries(a))r===void 0||r===!1||(n.startsWith("on")&&typeof r=="function"?s.addEventListener(n.slice(2),r):n==="class"?s.className=String(r):n==="style"?s.style.cssText=String(r):n==="value"?s.value=String(r):s.setAttribute(n,r===!0?"":String(r)));for(let n of o)n!=null&&n!==!1&&s.append(n);return s}var A=class extends Error{constructor(o,s){super(s);this.status=o}status};async function m(t,a,o){let s=await fetch(`/_keybox/admin${a}`,{method:t,credentials:"same-origin",headers:{"x-keybox-ui":"1","content-type":"application/json"},body:o===void 0?void 0:JSON.stringify(o)}),n=await s.json().catch(()=>null);if(!s.ok)throw new A(s.status,n?.error?.message??`HTTP ${s.status}`);return n}var S=document.getElementById("app"),L=t=>t?new Date(t).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):"\\u2014";function K(t){if(!t)return"never";let a=Math.round((Date.now()-t)/1e3);return a<60?`${a}s ago`:a<3600?`${Math.round(a/60)}m ago`:a<86400?`${Math.round(a/3600)}h ago`:`${Math.round(a/86400)}d ago`}function y(t,a=!1){let o=e("div",{class:`toast${a?" err":""}`,role:"status"},t);document.body.append(o),setTimeout(()=>o.remove(),a?6e3:2800)}async function E(t,a){t&&(t.disabled=!0);try{await a()}catch(o){y(o.message,!0)}finally{t&&(t.disabled=!1)}}function j(t){return t.length?k.find(a=>a.hosts.some(o=>t.includes(o)))?.label??"Custom":"Parked"}var v=t=>t.split(/[\\s,]+/).map(a=>a.trim()).filter(Boolean);function H(t,a,o){let s=e("dialog",{},e("div",{class:"stack"},e("h2",{},t),a,e("div",{class:"row"},...o)));return s.addEventListener("close",()=>s.remove()),document.body.append(s),s.showModal(),s}function U(t,a,o,s){let n=e("input",{class:"mono",placeholder:o,autocomplete:"off",spellcheck:"false"}),r=e("button",{class:"btn danger",type:"button",disabled:!0},"Delete");n.addEventListener("input",()=>r.disabled=n.value!==o);let i=H(t,e("div",{class:"stack"},e("p",{},a),e("label",{class:"field"},e("span",{},`Type ${o} to confirm`),n)),[r,e("button",{class:"btn ghost",type:"button",onclick:()=>i.close()},"Cancel")]);r.addEventListener("click",()=>E(r,async()=>{await s(),i.close()}))}try{let t=localStorage.getItem("kb-theme");(t==="light"||t==="dark")&&(document.documentElement.dataset.theme=t)}catch{}function V(){let t=document.documentElement,a=t.dataset.theme?t.dataset.theme==="dark":matchMedia("(prefers-color-scheme: dark)").matches;t.dataset.theme=a?"light":"dark";try{localStorage.setItem("kb-theme",t.dataset.theme)}catch{}}var B=()=>{let t=e("button",{class:"icon",type:"button",title:"Theme","aria-label":"Toggle dark theme",onclick:V});return t.innerHTML=\'<svg viewBox="0 0 20 20" width="18" height="18" aria-hidden="true"><circle cx="10" cy="10" r="7.25" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M10 2.75a7.25 7.25 0 0 1 0 14.5z" fill="currentColor"/></svg>\',t};async function Z(){let t=/[#&]code=(kb_lnk_[A-Za-z0-9_-]+)/.exec(location.hash);if(!t)return;history.replaceState(null,"",location.pathname);let a=await fetch("/_keybox/ui/session",{method:"POST",credentials:"same-origin",headers:{"x-keybox-ui":"1","content-type":"application/json"},body:JSON.stringify({code:t[1]})});if(!a.ok){let o=await a.json().catch(()=>null);throw new Error(o?.error?.message??"Login failed.")}}function T(t){S.className="",S.replaceChildren(e("div",{class:"login stack"},e("div",{class:"row spread"},e("span",{class:"mark"},e("i"),"keybox"),B()),e("h1",{},"Sign in to ",e("span",{class:"muted"},"this Keybox.")),t?e("p",{class:"notice warn"},t):null,e("p",{class:"lede"},"Run this on the machine where you set up Keybox. It opens this page with a one-time link; your admin token never enters the browser."),e("pre",{},"keybox ui"),e("p",{class:"dim"},"If your team uses Cloudflare Access, put an Access application in front of /_keybox/ and add its audience tag under Access in the dashboard. Signing in through Access then works too.")))}var $=["Overview","Secrets","Agents","Activity","Access","Blocked"],f,_="Overview",N=null,I=e("main");function q(){let t=e("nav",{class:"tabs","aria-label":"Sections"}),a=()=>{t.replaceChildren(...$.map(r=>e("button",{type:"button","aria-current":r===_?"page":void 0,onclick:()=>o(r)},r)))},o=r=>{_=r,location.hash=r.toLowerCase(),a(),b()},s=$.find(r=>r.toLowerCase()===location.hash.slice(1));s&&(_=s),a();let n=e("button",{class:"btn sm ghost",type:"button",onclick:async()=>{await fetch("/_keybox/ui/logout",{method:"POST",credentials:"same-origin",headers:{"x-keybox-ui":"1"}}),T("Signed out.")}},"Sign out");S.className="",S.replaceChildren(e("div",{class:"shell"},e("header",{class:"top"},e("a",{class:"mark",href:"#overview",onclick:()=>o("Overview")},e("i"),"keybox"),t,e("div",{class:"top-end"},B(),f.via==="token"?null:n)),I)),window.addEventListener("hashchange",()=>{let r=$.find(i=>i.toLowerCase()===location.hash.slice(1));r&&r!==_&&o(r)})}async function b(){N?.(),N=null,I.replaceChildren(e("p",{class:"mono dim",style:"margin-top:48px"},"loading\\u2026"));try{let t={Overview:X,Secrets:Q,Agents:ne,Activity:se,Access:re,Blocked:ie}[_];I.replaceChildren(await t())}catch(t){if(t instanceof A&&t.status===401)return T("Your session has ended.");I.replaceChildren(e("p",{class:"notice warn",style:"margin-top:48px"},t.message))}}var w=(t,a,o)=>[e("h1",{},t," ",e("span",{class:"muted"},a)),e("p",{class:"lede"},o)];async function X(){let[t,a,o,s]=await Promise.all([m("GET","/secrets"),m("GET","/agents"),m("GET","/stats"),m("GET","/policy")]),n=(i,l)=>e("div",{class:"card stat"},e("b",{},String(i)),e("span",{},l)),r=i=>i&&Object.keys(i).length?"restricted":"open to any network";return e("section",{},...w("Keys stay","in the box.","Agents call APIs through this Worker. They hold Keybox tokens; the real keys never leave it."),e("div",{class:"grid stats"},n(t.length,"secrets"),n(a.length,"agents"),n(o.allow??0,"allowed \\xB7 24h"),n((o.deny??0)+(o.error??0),"refused \\xB7 24h")),e("div",{class:"grid",style:"grid-template-columns:repeat(auto-fit,minmax(280px,1fr))"},e("div",{class:"card accent stack"},e("p",{class:"eyebrow"},"You"),e("p",{class:"mono",style:"margin:0"},`${f.ip??"unknown address"} \\xB7 ${f.country??"??"}`),e("p",{class:"dim",style:"margin:0"},f.via==="access"?`Signed in with Cloudflare Access as ${f.email}`:f.via==="session"?"Signed in with a one-time link from `keybox ui`.":"Using the admin token.")),e("div",{class:"card stack"},e("p",{class:"eyebrow"},"Network"),e("p",{style:"margin:0"},`Dashboard and admin API: ${r(s.admin)}.`),e("p",{style:"margin:0"},`Agent calls: ${r(s.proxy)}.`),e("div",{},e("button",{class:"btn sm",type:"button",onclick:()=>location.hash="access"},"Review access rules")))))}function J(t,a){let o=e("input",{type:"password",autocomplete:"off",spellcheck:"false","data-1p-ignore":!0,"data-lpignore":"true",placeholder:"Paste the key","aria-describedby":"key-detect"}),s=e("span",{class:"meter"},""),n=e("div",{class:"row",id:"key-detect","aria-live":"polite"}),r=()=>{let i=o.value.trim();if(s.textContent=i?`${i.length}`:"",n.replaceChildren(),!i)return a(null);/\\s/.test(i)&&n.append(e("span",{class:"chip warn"},"contains whitespace")),i.length<8&&n.append(e("span",{class:"chip warn"},"too short"));let l=G(t.value,i);l.provider?n.append(e("span",{class:l.via==="value"?"chip ok":"chip"},l.via==="value"?`\\u2713 looks like ${l.provider.label}`:`${l.provider.label} (from the name)`)):n.append(e("span",{class:"chip"},"unknown provider \\xB7 set hosts below")),l.mismatch&&n.append(e("span",{class:"chip warn"},`name says ${l.mismatch.label}`)),l.adminHint&&n.append(e("span",{class:"chip warn"},l.adminHint)),a(l.provider?.id??null)};return o.addEventListener("input",r),t.addEventListener("input",r),{el:e("div",{class:"stack"},e("div",{class:"keyfield"},o,s),n),input:o}}function D(t,a){let o=e("input",{class:"mono",placeholder:"OPENAI_API_KEY",autocomplete:"off",spellcheck:"false",value:t?.name??"",readonly:!!t}),s=e("select",{},e("option",{value:""},"Custom host\\u2026"),...k.map(u=>e("option",{value:u.id},`${u.label} \\xB7 ${u.hosts[0]}`))),n=e("input",{class:"mono",placeholder:"api.example.com",value:t?.hosts.join(", ")??""}),r=e("input",{class:"mono",value:t?.header??"authorization"}),i=e("select",{},...["bearer","raw","basic"].map(u=>e("option",{value:u},u)));i.value=t?.format??"bearer";let l=!!t,d=u=>{let g=M(u);g&&(s.value=u,n.value=g.hosts.join(", "),r.value=g.header,i.value=g.format)};s.addEventListener("change",()=>{l=!0,d(s.value)});let p=J(o,u=>{u&&!l&&d(u)}),c=e("button",{class:"btn primary",type:"submit"},t?"Save":"Store key"),h=e("form",{class:"card accent stack",autocomplete:"off"},e("p",{class:"eyebrow"},t?`Edit ${t.name}`:"Add a key"),e("div",{class:"cols"},e("label",{class:"field"},e("span",{},"Name"),o),e("label",{class:"field"},e("span",{},"Provider"),s)),e("label",{class:"field"},e("span",{},t?"New value (optional)":"Value"),p.el,e("small",{},t?"Leave empty to keep the stored key and only change where it may go.":"Sent once to this Worker and encrypted. It is never shown again, here or anywhere.")),e("div",{class:"cols"},e("label",{class:"field"},e("span",{},"Only sent to"),n),e("label",{class:"field"},e("span",{},"Header"),r),e("label",{class:"field"},e("span",{},"Format"),i)),e("div",{class:"row"},c,a?e("button",{class:"btn ghost",type:"button",onclick:a},"Cancel"):null));return h.addEventListener("submit",u=>{u.preventDefault(),E(c,async()=>{let g=p.input.value.trim(),x=o.value.trim().toUpperCase();if(!/^[A-Z][A-Z0-9_]{0,63}$/.test(x))throw new Error("Names are UPPER_SNAKE_CASE.");let O={hosts:v(n.value),header:r.value.trim(),format:i.value},Y=t&&!g?await m("PATCH",`/secrets/${x}`,O):await m("PUT",`/secrets/${x}`,{...O,value:g});p.input.value="",y(`${t&&!g?"Updated":"Stored"} ${x} \\xB7 fingerprint ${Y.fingerprint}`),a?.(),b()})}),h}async function Q(){let t=await m("GET","/secrets"),a=e("div"),o=e("button",{class:"btn primary",type:"button",onclick:()=>a.replaceChildren(D(void 0,()=>a.replaceChildren()))},"Add key"),s=e("table",{class:"table cards"},e("thead",{},e("tr",{},...["Name","Only sent to","Header","Fingerprint","Last used",""].map(n=>e("th",{},n)))),e("tbody",{},...t.map(n=>e("tr",{},e("td",{},e("b",{class:"mono"},n.name),e("div",{class:"dim"},j(n.hosts))),e("td",{class:"mono","data-l":"hosts"},n.hosts.length?n.hosts.join(", "):e("span",{class:"chip warn",title:"Stored, but no agent can use it until you give it a host."},"parked \\xB7 no host yet")),e("td",{class:"mono","data-l":"header"},`${n.header} (${n.format})`),e("td",{class:"mono","data-l":"fp",title:"HMAC of the value. Same key, same fingerprint."},n.fingerprint??"\\u2014"),e("td",{"data-l":"used",title:L(n.last_used)},K(n.last_used)),e("td",{},e("div",{class:"row"},e("button",{class:"btn sm",type:"button",onclick:()=>a.replaceChildren(D(n,()=>a.replaceChildren()))},n.hosts.length?"Edit":"Set host"),e("button",{class:"btn sm danger",type:"button",onclick:()=>U(`Delete ${n.name}?`,"Agents that use it will start failing. Revoke the key at the provider too.",n.name,async()=>{await m("DELETE",`/secrets/${n.name}`),y(`Deleted ${n.name}.`),b()})},"Delete")))))));return e("section",{class:"stack"},...w("Secrets","write-only.","You can add, rotate and delete keys here. You cannot read one back: not here, not with the admin token, not through an agent. The fingerprint tells you which key is stored."),e("div",{class:"row"},o),a,t.length?e("div",{class:"scroll"},s):e("p",{class:"notice"},"No keys yet. Add one, or run `keybox migrate` to bring them in from a .env file or a password manager."))}function ee(t){if(!t)return"";let a=new Set(t.grants.map(o=>o.secret)).size>1;return t.grants.flatMap(o=>[...o.allow.map(s=>`allow ${a?`${o.secret}=`:""}${s}`),...(o.deny??[]).map(s=>`deny ${a?`${o.secret}=`:""}${s}`)]).join(`\n`)}function z(t,a,o){let s=e("input",{class:"mono",placeholder:"writer",value:a?.name??"",readonly:!!a,autocomplete:"off"}),n=e("textarea",{spellcheck:"false",placeholder:`allow POST api.openai.com/v1/responses\nallow GET api.github.com/repos/acme/**\ndeny * api.github.com/repos/acme/secrets/**`});n.value=ee(a);let r=e("div",{class:"dim mono",style:"font-size:13px"}),i=()=>{try{let{allow:p,deny:c}=R(n.value);if(!p.length)return void r.replaceChildren("Add at least one allow rule.");let h=C(p,c,t);r.replaceChildren(...h.map(u=>e("div",{},`\\u2713 ${u.allow.length} allow${u.deny?.length?`, ${u.deny.length} deny`:""} with ${u.secret}`)))}catch(p){r.replaceChildren(e("span",{class:"bad-t"},p.message))}};n.addEventListener("input",i),i();let l=e("button",{class:"btn primary",type:"submit"},a?"Save rules":"Create agent"),d=e("form",{class:"card accent stack"},e("p",{class:"eyebrow"},a?`Edit ${a.name}`:"New agent"),e("label",{class:"field"},e("span",{},"Name"),s),e("label",{class:"field"},e("span",{},"Rules"),n,e("small",{},"One per line: METHOD host/path. * is one path segment, ** is any. Prefix SECRET= when several keys share a host. Everything else is denied.")),r,e("div",{class:"row"},l,o?e("button",{class:"btn ghost",type:"button",onclick:o},"Cancel"):null));return d.addEventListener("submit",p=>{p.preventDefault(),E(l,async()=>{let{allow:c,deny:h}=R(n.value),u=C(c,h,t);await m("PUT",`/agents/${s.value.trim()}`,{grants:u}),y(`Saved ${s.value.trim()}.`),o?.(),b()})}),d}function te(t){let a=e("select",{},...[["1h",3600],["12h",43200],["7d",604800],["30d",2592e3],["90d",7776e3]].map(([r,i])=>e("option",{value:String(i)},String(r))));a.value="2592000";let o=e("div",{class:"stack"}),s=e("button",{class:"btn primary",type:"button"},"Create token"),n=H(`Token for ${t}`,e("div",{class:"stack"},e("p",{class:"dim",style:"margin:0"},"For servers and CI. Store it in that platform\\u2019s secret store. It is shown once."),e("label",{class:"field"},e("span",{},"Expires after"),a),o),[s,e("button",{class:"btn ghost",type:"button",onclick:()=>n.close()},"Close")]);s.addEventListener("click",()=>E(s,async()=>{let r=await m("POST",`/agents/${t}/tokens`,{ttl:Number(a.value)}),i=e("code",{},r.token),l=e("button",{class:"btn sm",type:"button"},"Copy");l.addEventListener("click",async()=>{await navigator.clipboard.writeText(r.token),l.textContent="Copied"}),o.replaceChildren(e("div",{class:"secret-once"},i,l),e("p",{class:"dim",style:"margin:0"},`id ${r.id} \\xB7 expires ${L(r.expires_at)}`)),s.remove(),n.addEventListener("close",()=>{b()})}))}async function ae(t){let o=(await m("GET",`/agents/${t}/tokens`)).filter(r=>!r.revoked_at&&r.expires_at>Date.now()),s=e("div",{class:"stack"},...o.length?o.map(r=>{let i=e("button",{class:"btn sm danger",type:"button"},"Revoke"),l=e("div",{class:"row spread"},e("span",{class:"mono",style:"font-size:13px"},`${r.id.slice(0,8)} \\xB7 expires ${L(r.expires_at)}`),i);return i.addEventListener("click",()=>E(i,async()=>{await m("DELETE",`/tokens/${r.id}`),l.remove(),y("Revoked.")})),l}):[e("p",{class:"dim"},"No active tokens.")]),n=H(`Active tokens \\xB7 ${t}`,s,[e("button",{class:"btn ghost",type:"button",onclick:()=>n.close()},"Close")]);n.addEventListener("close",()=>{b()})}async function ne(){let[t,a,o]=await Promise.all([m("GET","/agents"),m("GET","/secrets"),m("GET","/policy")]),s=e("div"),n=e("button",{class:"btn primary",type:"button",onclick:()=>s.replaceChildren(z(a,void 0,()=>s.replaceChildren()))},"New agent"),r=t.map(i=>{let l=o.agents?.[i.name];return e("article",{class:"card agent"},e("div",{class:"row spread"},e("h3",{class:"mono"},i.name),e("span",{class:"chip accent"},`${i.active_tokens} active token${i.active_tokens===1?"":"s"}`)),e("ul",{class:"rules"},...i.grants.flatMap(d=>[...d.allow.map(p=>e("li",{},e("span",{class:"k"},"allow"),p,e("span",{class:"dim"},` \\xB7 ${d.secret}`))),...(d.deny??[]).map(p=>e("li",{class:"deny"},e("span",{class:"k"},"deny"),p))])),l?e("p",{class:"dim",style:"margin:0;font-size:13px"},`Network: ${oe(l)}`):null,e("div",{class:"row"},e("button",{class:"btn sm",type:"button",onclick:()=>s.replaceChildren(z(a,i,()=>s.replaceChildren()))},"Edit rules"),e("button",{class:"btn sm",type:"button",onclick:()=>te(i.name)},"New token"),e("button",{class:"btn sm ghost",type:"button",onclick:()=>{ae(i.name)}},"Tokens"),e("button",{class:"btn sm danger",type:"button",onclick:()=>U(`Delete ${i.name}?`,"Its tokens stop working immediately.",i.name,async()=>{await m("DELETE",`/agents/${i.name}`),y(`Deleted ${i.name}.`),b()})},"Delete")))});return e("section",{class:"stack"},...w("Agents","and their rules.","Each agent can make exactly the calls its rules allow, with the key bound to that host. Key-minting calls are always blocked, whatever the rules say."),e("div",{class:"row"},n),s,t.length?e("div",{class:"grid",style:"grid-template-columns:repeat(auto-fit,minmax(min(100%,420px),1fr))"},...r):e("p",{class:"notice"},"No agents yet."))}async function se(){let t=await m("GET","/audit?limit=200"),a=e("select",{},e("option",{value:""},"All results"),e("option",{value:"allow"},"Allowed"),e("option",{value:"deny"},"Refused"),e("option",{value:"error"},"Errors")),o=e("input",{placeholder:"Filter by agent, host or path",class:"mono"}),s=e("input",{type:"checkbox",checked:!0}),n=e("tbody"),r=()=>{let d=o.value.trim().toLowerCase(),p=t.filter(c=>!a.value||c.decision===a.value).filter(c=>!d||`${c.agent} ${c.host}${c.path} ${c.secret} ${c.reason}`.toLowerCase().includes(d)).slice(-300).reverse();n.replaceChildren(...p.map(c=>e("tr",{},e("td",{"data-l":"time",title:L(c.ts)},K(c.ts)),e("td",{class:"mono","data-l":"agent"},c.agent??"\\u2014"),e("td",{class:`mono ${c.decision==="allow"?"ok-t":"bad-t"}`,"data-l":"result"},c.decision==="allow"?String(c.status):c.decision.toUpperCase()),e("td",{class:"mono","data-l":"request"},`${c.method} ${c.host??""}${c.path??""}`),e("td",{class:"mono dim","data-l":"detail"},c.secret??c.reason??""))))};a.addEventListener("change",r),o.addEventListener("input",r),r();let i=0,l=async()=>{if(s.checked&&document.visibilityState==="visible")try{let d=await m("GET",`/audit?after=${t.at(-1)?.id??0}&limit=500`);d.length&&(t=[...t,...d].slice(-2e3),r())}catch{}i=window.setTimeout(l,3e3)};return i=window.setTimeout(l,3e3),N=()=>clearTimeout(i),e("section",{class:"stack"},...w("Activity","every call, on the record.","Each request an agent makes, whether Keybox allowed it, and which key it used. Stored in your own D1 database."),e("div",{class:"row"},e("div",{style:"flex:1;min-width:200px"},o),e("div",{style:"width:170px"},a),e("label",{class:"check"},s,"Live")),e("div",{class:"scroll"},e("table",{class:"table cards"},e("thead",{},e("tr",{},...["When","Agent","Result","Request","Key / reason"].map(d=>e("th",{},d)))),n)))}function oe(t){if(!t||!Object.keys(t).length)return"any network";let a=[];return t.allowIps?.length&&a.push(`from ${t.allowIps.join(", ")}`),t.allowCountries?.length&&a.push(`in ${t.allowCountries.join(", ")}`),t.denyCountries?.length&&a.push(`never from ${t.denyCountries.join(", ")}`),a.join("; ")}function P(t,a,o){let s=e("textarea",{spellcheck:"false",placeholder:`203.0.113.0/24\n2001:db8::/32`,style:"min-height:90px"});s.value=(o?.allowIps??[]).join(`\n`);let n=e("input",{class:"mono",placeholder:"US, CA",value:(o?.allowCountries??[]).join(", ")}),r=e("input",{class:"mono",placeholder:"T1 (Tor)",value:(o?.denyCountries??[]).join(", ")});return{el:e("div",{class:"card stack"},e("div",{},e("h3",{},t),e("p",{class:"dim",style:"margin:4px 0 0"},a)),e("label",{class:"field"},e("span",{},"Allowed IPs and ranges"),s,e("small",{},"Empty means any address.")),e("div",{class:"cols"},e("label",{class:"field"},e("span",{},"Only these countries"),n),e("label",{class:"field"},e("span",{},"Never these countries"),r))),value:()=>{let d={};return v(s.value).length&&(d.allowIps=v(s.value)),v(n.value).length&&(d.allowCountries=v(n.value).map(p=>p.toUpperCase())),v(r.value).length&&(d.denyCountries=v(r.value).map(p=>p.toUpperCase())),d}}}async function re(){let[t,a]=await Promise.all([m("GET","/policy"),m("GET","/agents")]),o=P("Dashboard and admin API","Who can manage this Keybox, including the CLI.",t.admin),s=P("Agent calls","Where agents may call from. Applies to every agent token.",t.proxy),n=a.map(h=>({name:h.name,ed:P(`Agent \\xB7 ${h.name}`,"Extra limits for this agent only, on top of the rule above.",t.agents?.[h.name])})),r=e("input",{class:"mono",placeholder:"myteam.cloudflareaccess.com",value:t.access?.teamDomain??""}),i=e("input",{class:"mono",placeholder:"64-character Application Audience (AUD) tag",value:t.access?.aud??""}),l=e("input",{type:"checkbox"}),d=e("label",{class:"check",hidden:!0},l,"Save anyway. I know this may lock me out of the dashboard."),p=e("button",{class:"btn primary",type:"button"},"Save rules");p.addEventListener("click",()=>E(p,async()=>{let h={admin:o.value(),proxy:s.value(),agents:Object.fromEntries(n.map(u=>[u.name,u.ed.value()]))};(r.value.trim()||i.value.trim())&&(h.access={teamDomain:r.value.trim(),aud:i.value.trim()});try{await m("PUT","/policy",{policy:h,force:l.checked}),y("Saved. Rules apply within a few seconds."),d.hidden=!0,l.checked=!1}catch(u){throw/lock out|would block you/.test(u.message)&&(d.hidden=!1),u}}));let c=e("button",{class:"btn sm danger",type:"button"},"Sign out every dashboard session");return c.addEventListener("click",()=>E(c,async()=>{let h=await m("DELETE","/sessions");y(`Ended ${h.revoked} session${h.revoked===1?"":"s"}.`)})),e("section",{class:"stack"},...w("Access","by network and identity.","Limit who can reach this Keybox. Rules are enforced in the Worker, before any key is decrypted."),e("p",{class:"notice"},`You are calling from ${f.ip??"an unknown address"} (${f.country??"??"}). Keybox will not save an admin rule that blocks you unless you insist. If you do lock yourself out, delete the rule with wrangler: npx wrangler d1 execute <name> --remote --command "DELETE FROM settings WHERE key = \'policy\'"`),o.el,s.el,...n.map(h=>h.ed.el),e("div",{class:"card stack"},e("div",{},e("h3",{},"Cloudflare Access"),e("p",{class:"dim",style:"margin:4px 0 0"},"Put an Access application in front of this Worker\\u2019s /_keybox/ path (SSO, passkeys, device posture), then paste its details here. A valid Access login then signs you in to the dashboard.")),e("div",{class:"cols"},e("label",{class:"field"},e("span",{},"Team domain"),r),e("label",{class:"field"},e("span",{},"Audience tag"),i))),d,e("div",{class:"row spread"},p,c))}async function ie(){let t=await m("GET","/blocked");return e("section",{class:"stack"},...w("Never","proxied.","Calls that would mint a new key or grant lasting access. No agent rule can allow them."),e("div",{class:"scroll"},e("table",{class:"table cards"},e("thead",{},e("tr",{},e("th",{},"Rule"),e("th",{},"Why"))),e("tbody",{},...t.map(a=>e("tr",{},e("td",{class:"mono"},a.rule),e("td",{},a.reason)))))))}(async()=>{try{await Z()}catch(t){return T(t.message)}try{f=await m("GET","/whoami")}catch(t){return t instanceof A&&t.status===403?T(t.message):T()}q(),b()})();})();\n';
|
|
964
988
|
|
|
965
989
|
// src/ui.ts
|
|
966
990
|
var CSP = [
|
package/dist/keybox.js
CHANGED
|
@@ -215,7 +215,7 @@ var init_providers = __esm({
|
|
|
215
215
|
admin: "^sk_live_",
|
|
216
216
|
adminHint: "This is a full live secret key. Prefer a restricted key (rk_live_)."
|
|
217
217
|
},
|
|
218
|
-
{ id: "cloudflare", label: "Cloudflare", hosts: ["api.cloudflare.com"], header: "authorization", format: "bearer", prefixes: ["CLOUDFLARE_", "CF_"] },
|
|
218
|
+
{ id: "cloudflare", label: "Cloudflare", hosts: ["api.cloudflare.com"], header: "authorization", format: "bearer", prefixes: ["CLOUDFLARE_", "CF_"], pattern: "^cf[a-z]t_" },
|
|
219
219
|
{ 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}$" },
|
|
220
220
|
{ id: "groq", label: "Groq", hosts: ["api.groq.com"], header: "authorization", format: "bearer", prefixes: ["GROQ_"], pattern: "^gsk_" },
|
|
221
221
|
{ id: "mistral", label: "Mistral", hosts: ["api.mistral.ai"], header: "authorization", format: "bearer", prefixes: ["MISTRAL_"] },
|
|
@@ -243,6 +243,11 @@ var init_providers = __esm({
|
|
|
243
243
|
{ id: "vercel", label: "Vercel", hosts: ["api.vercel.com"], header: "authorization", format: "bearer", prefixes: ["VERCEL_"] },
|
|
244
244
|
{ id: "netlify", label: "Netlify", hosts: ["api.netlify.com"], header: "authorization", format: "bearer", prefixes: ["NETLIFY_"] },
|
|
245
245
|
{ id: "digitalocean", label: "DigitalOcean", hosts: ["api.digitalocean.com"], header: "authorization", format: "bearer", prefixes: ["DIGITALOCEAN_", "DO_"], pattern: "^dop_v1_" },
|
|
246
|
+
{ id: "workos", label: "WorkOS", hosts: ["api.workos.com"], header: "authorization", format: "bearer", prefixes: ["WORKOS_"] },
|
|
247
|
+
{ id: "retell", label: "Retell AI", hosts: ["api.retellai.com"], header: "authorization", format: "bearer", prefixes: ["RETELL_"] },
|
|
248
|
+
{ id: "nvidia", label: "NVIDIA NIM", hosts: ["integrate.api.nvidia.com"], header: "authorization", format: "bearer", prefixes: ["NVIDIA_", "NVAPI", "NIM_"], pattern: "^nvapi-" },
|
|
249
|
+
{ id: "plane", label: "Plane", hosts: ["api.plane.so"], header: "x-api-key", format: "raw", prefixes: ["PLANE_"], pattern: "^plane_api_" },
|
|
250
|
+
{ id: "crates", label: "crates.io", hosts: ["crates.io"], header: "authorization", format: "raw", prefixes: ["CRATES_IO_", "CARGO_REGISTRY_TOKEN"], pattern: "^cio[A-Za-z0-9]{30,}$" },
|
|
246
251
|
{ id: "sentry", label: "Sentry", hosts: ["sentry.io"], header: "authorization", format: "bearer", prefixes: ["SENTRY_"], pattern: "^sntry[us]_" }
|
|
247
252
|
];
|
|
248
253
|
UNSUPPORTED = [
|
|
@@ -584,8 +589,8 @@ function list(question, options, o) {
|
|
|
584
589
|
let cur = Math.min(o.def, options.length - 1);
|
|
585
590
|
let top = 0;
|
|
586
591
|
let drawn = 0;
|
|
587
|
-
const cols = () => Math.max(24, (out2.columns
|
|
588
|
-
const rows = () => Math.max(3, Math.min(12, (out2.rows
|
|
592
|
+
const cols = () => Math.max(24, (out2.columns || 80) - 1);
|
|
593
|
+
const rows = () => Math.max(3, Math.min(12, (out2.rows || 24) - 6, options.length));
|
|
589
594
|
const help2 = () => {
|
|
590
595
|
const pos = shown.length > rows() ? `${cur + 1}/${shown.length} \xB7 ` : "";
|
|
591
596
|
if (o.multi) return `${pos}\u2191\u2193 move \xB7 space pick \xB7 a all \xB7 n none \xB7 enter done \xB7 ${checked.size} picked`;
|
|
@@ -700,17 +705,17 @@ function list(question, options, o) {
|
|
|
700
705
|
});
|
|
701
706
|
}
|
|
702
707
|
async function choose(question, options, def = 0) {
|
|
703
|
-
if (!
|
|
708
|
+
if (!canList()) return options[def].value;
|
|
704
709
|
const [k] = await list(question, options, { multi: false, def, checked: /* @__PURE__ */ new Set() });
|
|
705
710
|
return options[k].value;
|
|
706
711
|
}
|
|
707
712
|
async function checklist(question, options, preselected) {
|
|
708
713
|
const checked = new Set(options.flatMap((opt, k) => preselected(opt.value) ? [k] : []));
|
|
709
|
-
if (!
|
|
714
|
+
if (!canList() || !options.length) return [...checked].map((k) => options[k].value);
|
|
710
715
|
const picked = await list(question, options, { multi: true, def: 0, checked });
|
|
711
716
|
return picked.map((k) => options[k].value);
|
|
712
717
|
}
|
|
713
|
-
var GLYPHS, MAX_DOTS, clip;
|
|
718
|
+
var GLYPHS, MAX_DOTS, clip, canList;
|
|
714
719
|
var init_prompt = __esm({
|
|
715
720
|
"src/prompt.ts"() {
|
|
716
721
|
"use strict";
|
|
@@ -720,12 +725,15 @@ var init_prompt = __esm({
|
|
|
720
725
|
GLYPHS = "\u2591\u2592\u2593\u2588#%&@$";
|
|
721
726
|
MAX_DOTS = 32;
|
|
722
727
|
clip = (s, n) => n <= 0 ? "" : s.length <= n ? s : n === 1 ? "\u2026" : `${s.slice(0, n - 1)}\u2026`;
|
|
728
|
+
canList = () => Boolean(process.stdin.isTTY && process.stderr.isTTY) && process.env.TERM !== "dumb";
|
|
723
729
|
}
|
|
724
730
|
});
|
|
725
731
|
|
|
726
732
|
// src/migrate.ts
|
|
727
733
|
import { spawn, spawnSync } from "node:child_process";
|
|
728
734
|
import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2 } from "node:fs";
|
|
735
|
+
import { homedir as homedir2 } from "node:os";
|
|
736
|
+
import { join as join2 } from "node:path";
|
|
729
737
|
function has(bin2) {
|
|
730
738
|
return spawnSync(process.platform === "win32" ? "where" : "which", [bin2], { stdio: "ignore" }).status === 0;
|
|
731
739
|
}
|
|
@@ -762,6 +770,150 @@ function pickField(fields) {
|
|
|
762
770
|
const named = fields.find((f) => /^(credential|api[ _-]?key|token|secret|password|key)$/i.test(f.label ?? f.name ?? f.id ?? "") && f.value);
|
|
763
771
|
return (named ?? fields.find((f) => (f.type === "CONCEALED" || f.type === 1) && f.value))?.value;
|
|
764
772
|
}
|
|
773
|
+
function infisicalBase() {
|
|
774
|
+
const fromEnv = process.env.INFISICAL_DOMAIN?.replace(/\/+$/, "");
|
|
775
|
+
if (fromEnv) return /\/api$/.test(fromEnv) ? fromEnv : `${fromEnv}/api`;
|
|
776
|
+
try {
|
|
777
|
+
const cfg = JSON.parse(readFileSync2(join2(homedir2(), ".infisical", "infisical-config.json"), "utf8"));
|
|
778
|
+
const p = cfg.profiles?.find((x) => x.name === cfg.activeProfile) ?? cfg.profiles?.[0];
|
|
779
|
+
if (p?.domain) return p.domain.replace(/\/+$/, "");
|
|
780
|
+
} catch {
|
|
781
|
+
}
|
|
782
|
+
return "https://app.infisical.com/api";
|
|
783
|
+
}
|
|
784
|
+
async function fetchInfisical(_arg, o) {
|
|
785
|
+
let token2 = process.env.INFISICAL_TOKEN?.trim() ?? "";
|
|
786
|
+
if (!token2) {
|
|
787
|
+
try {
|
|
788
|
+
token2 = (await capture("infisical", ["user", "get", "token", "--plain", "--silent"])).trim();
|
|
789
|
+
} catch {
|
|
790
|
+
throw new UserError("Sign in to Infisical first: infisical login");
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
const base = infisicalBase();
|
|
794
|
+
const get = async (path2) => {
|
|
795
|
+
let r;
|
|
796
|
+
try {
|
|
797
|
+
r = await fetch(base + path2, { headers: { authorization: `Bearer ${token2}` } });
|
|
798
|
+
} catch {
|
|
799
|
+
throw new UserError(`Cannot reach Infisical at ${base}.`);
|
|
800
|
+
}
|
|
801
|
+
if (r.status === 401 || r.status === 403) throw new UserError("Infisical refused the session. Run infisical login and try again.");
|
|
802
|
+
if (!r.ok) throw new UserError(`Infisical returned HTTP ${r.status} for ${path2.split("?")[0]}.`);
|
|
803
|
+
return await r.json();
|
|
804
|
+
};
|
|
805
|
+
const wanted = (list2) => list2?.split(",").map((x) => x.trim().toLowerCase()).filter(Boolean);
|
|
806
|
+
const onlyProjects = wanted(o.project);
|
|
807
|
+
const onlyEnvs = wanted(o.env);
|
|
808
|
+
const { workspaces = [] } = await get("/v1/workspace");
|
|
809
|
+
const projects = workspaces.filter(
|
|
810
|
+
(p) => p.environments?.length && (!p.type || p.type === "secret-manager") && (!onlyProjects || onlyProjects.includes(p.id.toLowerCase()) || onlyProjects.includes(p.name.toLowerCase()))
|
|
811
|
+
);
|
|
812
|
+
if (!projects.length) throw new UserError(onlyProjects ? `No Infisical project named ${o.project}.` : "This Infisical login has no secret projects.");
|
|
813
|
+
const path = o.path ?? "/";
|
|
814
|
+
const parts2 = projects.flatMap(
|
|
815
|
+
(p) => p.environments.filter((e) => !onlyEnvs || onlyEnvs.includes(e.slug.toLowerCase())).map((e) => ({ project: p, env: e, secrets: [] }))
|
|
816
|
+
);
|
|
817
|
+
await Promise.all(
|
|
818
|
+
parts2.map(async (part) => {
|
|
819
|
+
const q = new URLSearchParams({
|
|
820
|
+
workspaceId: part.project.id,
|
|
821
|
+
environment: part.env.slug,
|
|
822
|
+
secretPath: path,
|
|
823
|
+
recursive: "true",
|
|
824
|
+
include_imports: "true",
|
|
825
|
+
expandSecretReferences: "true"
|
|
826
|
+
});
|
|
827
|
+
const r = await get(`/v3/secrets/raw?${q}`);
|
|
828
|
+
const own = [...r.secrets ?? []].sort((a, b) => Number(b.type === "personal") - Number(a.type === "personal"));
|
|
829
|
+
const imported = (r.imports ?? []).flatMap((i) => (i.secrets ?? []).map((x) => ({ ...x, secretPath: x.secretPath ?? i.secretPath ?? "/" })));
|
|
830
|
+
const seen = /* @__PURE__ */ new Set();
|
|
831
|
+
for (const x of [...own, ...imported]) {
|
|
832
|
+
const id = `${x.secretPath ?? "/"}
|
|
833
|
+
${x.secretKey}`;
|
|
834
|
+
if (seen.has(id)) continue;
|
|
835
|
+
seen.add(id);
|
|
836
|
+
part.secrets.push(x);
|
|
837
|
+
}
|
|
838
|
+
})
|
|
839
|
+
);
|
|
840
|
+
const full = parts2.filter((x) => x.secrets.length);
|
|
841
|
+
const many = projects.length > 1;
|
|
842
|
+
const label2 = (x) => `${many ? `${x.project.name} \xB7 ` : ""}${x.env.name}`;
|
|
843
|
+
let chosen = full;
|
|
844
|
+
if (o.interactive && full.length > 1) {
|
|
845
|
+
const folders = (x) => new Set(x.secrets.map((s) => s.secretPath ?? "/").filter((f) => f !== "/")).size;
|
|
846
|
+
const keep = new Set(
|
|
847
|
+
await checklist(
|
|
848
|
+
"Read which projects and environments?",
|
|
849
|
+
full.map((x, i) => ({
|
|
850
|
+
value: i,
|
|
851
|
+
label: label2(x),
|
|
852
|
+
hint: `${x.secrets.length} entr${x.secrets.length === 1 ? "y" : "ies"}${folders(x) ? `, ${folders(x)} folder${folders(x) === 1 ? "" : "s"}` : ""}`
|
|
853
|
+
})),
|
|
854
|
+
() => true
|
|
855
|
+
)
|
|
856
|
+
);
|
|
857
|
+
chosen = full.filter((_, i) => keep.has(i));
|
|
858
|
+
}
|
|
859
|
+
const empty = parts2.filter((x) => !x.secrets.length);
|
|
860
|
+
if (empty.length) note(`Empty: ${empty.map(label2).join(", ")}`);
|
|
861
|
+
return chosen.flatMap(
|
|
862
|
+
(x) => x.secrets.map((sec) => {
|
|
863
|
+
const folder = (sec.secretPath ?? "/").replace(/^\/+|\/+$/g, "");
|
|
864
|
+
return {
|
|
865
|
+
name: sec.secretKey,
|
|
866
|
+
value: sec.secretValue ?? "",
|
|
867
|
+
origin: `infisical:${x.project.name}/${x.env.slug}${folder ? `/${folder}` : ""}/${sec.secretKey}`,
|
|
868
|
+
scope: [
|
|
869
|
+
...folder ? [{ part: folder.split("/").at(-1), at: "prefix" }] : [],
|
|
870
|
+
...many ? [{ part: x.project.name, at: "prefix" }] : [],
|
|
871
|
+
{ part: x.env.slug, at: "suffix" }
|
|
872
|
+
]
|
|
873
|
+
};
|
|
874
|
+
})
|
|
875
|
+
);
|
|
876
|
+
}
|
|
877
|
+
function disambiguate(found) {
|
|
878
|
+
const norm = (n) => /^[A-Z][A-Z0-9_]{0,63}$/.test(n) ? n : toSecretName(n);
|
|
879
|
+
const taken = /* @__PURE__ */ new Map();
|
|
880
|
+
const out2 = [];
|
|
881
|
+
let merged = 0;
|
|
882
|
+
for (const f of found) {
|
|
883
|
+
const base = norm(f.name);
|
|
884
|
+
const holder = taken.get(base);
|
|
885
|
+
if (!holder) {
|
|
886
|
+
taken.set(base, f);
|
|
887
|
+
out2.push(f);
|
|
888
|
+
continue;
|
|
889
|
+
}
|
|
890
|
+
if (holder.value === f.value) {
|
|
891
|
+
merged++;
|
|
892
|
+
continue;
|
|
893
|
+
}
|
|
894
|
+
const theirs = new Set((holder.scope ?? []).map((q) => toSecretName(q.part)));
|
|
895
|
+
let name = base;
|
|
896
|
+
for (const q of f.scope ?? []) {
|
|
897
|
+
const part = toSecretName(q.part).replace(/^KEY_/, "");
|
|
898
|
+
if (theirs.has(part) || name.startsWith(`${part}_`) || name.endsWith(`_${part}`)) continue;
|
|
899
|
+
name = toSecretName(q.at === "prefix" ? `${part}_${name}` : `${name}_${part}`);
|
|
900
|
+
if (!taken.has(name) || taken.get(name).value === f.value) break;
|
|
901
|
+
}
|
|
902
|
+
if (taken.get(name)?.value === f.value) {
|
|
903
|
+
merged++;
|
|
904
|
+
continue;
|
|
905
|
+
}
|
|
906
|
+
if (taken.has(name)) {
|
|
907
|
+
let i = 2;
|
|
908
|
+
while (taken.has(`${name}_${i}`)) i++;
|
|
909
|
+
name = `${name}_${i}`;
|
|
910
|
+
}
|
|
911
|
+
const renamed = { ...f, name };
|
|
912
|
+
taken.set(name, renamed);
|
|
913
|
+
out2.push(renamed);
|
|
914
|
+
}
|
|
915
|
+
return { found: out2, merged };
|
|
916
|
+
}
|
|
765
917
|
async function readRef(ref) {
|
|
766
918
|
const m = /^([a-z0-9-]+):\/\/(.+)$/.exec(ref);
|
|
767
919
|
if (!m) throw new UserError(`Not a reference: ${ref}. Try op://vault/item/field, vault://path#field, env://NAME \u2026`);
|
|
@@ -841,11 +993,14 @@ function classify(found, existing, opts = {}) {
|
|
|
841
993
|
const d = detect(name, f.value);
|
|
842
994
|
const looksLikeKey = f.explicit || CREDENTIAL_NAME.test(name) || d.via === "value";
|
|
843
995
|
const isPublic = PUBLIC_NAME.test(name);
|
|
996
|
+
if (d.provider && d.mismatch) {
|
|
997
|
+
unknown.push({ ...item, why: [`name says ${d.mismatch.label}, value looks like ${d.provider.label}`, renamed].filter(Boolean).join(" \xB7 "), guess: d.mismatch });
|
|
998
|
+
continue;
|
|
999
|
+
}
|
|
844
1000
|
if (d.provider && looksLikeKey && !isPublic && v.length >= 8) {
|
|
845
1001
|
const flags = [];
|
|
846
1002
|
if (renamed) flags.push(renamed);
|
|
847
1003
|
if (d.adminHint) flags.push("admin-grade");
|
|
848
|
-
if (d.mismatch) flags.push(`name says ${d.mismatch.label}`);
|
|
849
1004
|
if (d.via === "name") flags.push("guessed from name");
|
|
850
1005
|
plans.push({ ...item, provider: d.provider, hosts: d.provider.hosts, header: d.provider.header, format: d.provider.format, flags, replaces: existing.has(name) });
|
|
851
1006
|
continue;
|
|
@@ -856,40 +1011,49 @@ function classify(found, existing, opts = {}) {
|
|
|
856
1011
|
].filter(Boolean).join(" \xB7 ");
|
|
857
1012
|
unknown.push({ ...item, why, guess: d.provider });
|
|
858
1013
|
}
|
|
859
|
-
const rank = (o) => o.why?.startsWith("no preset") ?
|
|
1014
|
+
const rank = (o) => o.why?.startsWith("name says") ? 0 : o.why?.startsWith("no preset") ? 1 : o.why?.startsWith("very short") ? 2 : 3;
|
|
860
1015
|
unknown.sort((a, b) => rank(a) - rank(b));
|
|
861
1016
|
return { plans, skipped, unknown };
|
|
862
1017
|
}
|
|
863
1018
|
function printSkipped(skipped) {
|
|
864
1019
|
const byWhy = /* @__PURE__ */ new Map();
|
|
865
|
-
for (const s of skipped)
|
|
1020
|
+
for (const s of skipped) {
|
|
1021
|
+
const why = s.why.replace(/ · stored as [A-Z0-9_]+/, "");
|
|
1022
|
+
byWhy.set(why, [...byWhy.get(why) ?? [], s.name]);
|
|
1023
|
+
}
|
|
866
1024
|
for (const [why, names] of byWhy) {
|
|
867
1025
|
const list2 = names.length > 6 ? `${names.slice(0, 6).join(", ")} +${names.length - 6} more` : names.join(", ");
|
|
868
1026
|
process.stderr.write(` ${c.dim(`${why}: ${list2}`)}
|
|
869
1027
|
`);
|
|
870
1028
|
}
|
|
871
1029
|
}
|
|
872
|
-
async function
|
|
873
|
-
const pick = await choose(`${c.dim(progress)}
|
|
874
|
-
...
|
|
1030
|
+
async function pickDestination(name, o) {
|
|
1031
|
+
const pick = await choose(`${o.progress ? c.dim(o.progress) + " " : ""}Where may ${c.bold(name)} be sent?`, [
|
|
1032
|
+
...o.guess ? [{ value: o.guess.id, label: o.guess.label, hint: `${o.guess.hosts[0]} \xB7 guessed from the name` }] : [],
|
|
875
1033
|
{ value: "_custom", label: "A host I will type", hint: "e.g. api.example.com" },
|
|
876
|
-
|
|
877
|
-
|
|
1034
|
+
...o.park ? [
|
|
1035
|
+
{ value: "_park", label: "Not sure yet: park it", hint: "stored, unusable until you give it a host" },
|
|
1036
|
+
{ value: "_park_rest", label: "Park this and all the rest", hint: "decide later with keybox secrets bind" }
|
|
1037
|
+
] : [],
|
|
1038
|
+
{ value: "_skip", label: o.skipLabel ?? "Skip this one" },
|
|
1039
|
+
...PROVIDERS.filter((p) => p !== o.guess).map((p) => ({ value: p.id, label: p.label, hint: p.hosts[0] }))
|
|
878
1040
|
]);
|
|
879
|
-
if (pick === "_skip") return
|
|
1041
|
+
if (pick === "_skip") return "skip";
|
|
1042
|
+
if (pick === "_park") return PARKED;
|
|
1043
|
+
if (pick === "_park_rest") return "park-rest";
|
|
880
1044
|
if (pick !== "_custom") {
|
|
881
1045
|
const p = byId(pick);
|
|
882
|
-
return {
|
|
1046
|
+
return { hosts: p.hosts, header: p.header, format: p.format, provider: p, flag: "chosen by you" };
|
|
883
1047
|
}
|
|
884
1048
|
let host = "";
|
|
885
1049
|
for (let tries = 0; tries < 3 && !host; tries++) {
|
|
886
1050
|
const raw = (await ask("Hostname it may be sent to (empty to skip):")).trim().toLowerCase();
|
|
887
|
-
if (!raw) return
|
|
1051
|
+
if (!raw) return "skip";
|
|
888
1052
|
const h = raw.replace(/^[a-z]+:\/\//, "").replace(/[/?#].*$/, "").replace(/:\d+$/, "");
|
|
889
1053
|
if (/^[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,63}$/.test(h)) host = h;
|
|
890
1054
|
else warn(`${raw} is not a hostname. Example: api.example.com`);
|
|
891
1055
|
}
|
|
892
|
-
if (!host) return
|
|
1056
|
+
if (!host) return "skip";
|
|
893
1057
|
const how = await choose(`How does ${host} expect the key?`, [
|
|
894
1058
|
{ value: "bearer", label: "Authorization: Bearer <key>", hint: "most APIs" },
|
|
895
1059
|
{ value: "x-api-key", label: "x-api-key: <key>" },
|
|
@@ -898,7 +1062,45 @@ async function placeUnknown(f, progress, replaces) {
|
|
|
898
1062
|
]);
|
|
899
1063
|
const header = how === "x-api-key" ? "x-api-key" : how === "header" ? (await ask("Header name:", "x-api-key")).toLowerCase() : "authorization";
|
|
900
1064
|
const format = how === "bearer" ? "bearer" : how === "basic" ? "basic" : "raw";
|
|
901
|
-
return {
|
|
1065
|
+
return { hosts: [host], header, format, flag: "custom host" };
|
|
1066
|
+
}
|
|
1067
|
+
function prefixes(name) {
|
|
1068
|
+
const parts2 = name.split("_");
|
|
1069
|
+
const out2 = [];
|
|
1070
|
+
for (let n = Math.min(parts2.length - 1, 3); n >= 1; n--) if (parts2.slice(0, n).join("_").length >= 3) out2.push(parts2.slice(0, n).join("_") + "_");
|
|
1071
|
+
return out2;
|
|
1072
|
+
}
|
|
1073
|
+
async function placeMany(items, o) {
|
|
1074
|
+
const out2 = /* @__PURE__ */ new Map();
|
|
1075
|
+
const queue = [...items];
|
|
1076
|
+
let n = 0;
|
|
1077
|
+
while (queue.length) {
|
|
1078
|
+
const item = queue.shift();
|
|
1079
|
+
n++;
|
|
1080
|
+
const a = await pickDestination(item.name, { guess: item.guess, progress: `(${n}/${n + queue.length})`, park: o.park, skipLabel: o.skipLabel });
|
|
1081
|
+
if (a === "park-rest") {
|
|
1082
|
+
for (const x of [item, ...queue]) out2.set(x.name, PARKED);
|
|
1083
|
+
break;
|
|
1084
|
+
}
|
|
1085
|
+
const dest = a === "skip" ? null : a;
|
|
1086
|
+
out2.set(item.name, dest);
|
|
1087
|
+
if (!dest) continue;
|
|
1088
|
+
const family = prefixes(item.name).map((p) => queue.filter((x) => x.name.startsWith(p))).find((xs) => xs.length);
|
|
1089
|
+
if (!family?.length) continue;
|
|
1090
|
+
const where = dest.hosts.length ? `to ${dest.hosts.join(", ")}` : "parked as well";
|
|
1091
|
+
const same = new Set(
|
|
1092
|
+
await checklist(
|
|
1093
|
+
`Send ${family.length === 1 ? "this one" : `these ${family.length}`} ${where} too?`,
|
|
1094
|
+
family.map((x) => ({ value: x.name, label: x.name })),
|
|
1095
|
+
() => true
|
|
1096
|
+
)
|
|
1097
|
+
);
|
|
1098
|
+
for (const x of family.filter((x2) => same.has(x2.name))) {
|
|
1099
|
+
out2.set(x.name, dest);
|
|
1100
|
+
queue.splice(queue.indexOf(x), 1);
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
return out2;
|
|
902
1104
|
}
|
|
903
1105
|
function dotenvFiles() {
|
|
904
1106
|
try {
|
|
@@ -928,25 +1130,38 @@ async function migrate(opts) {
|
|
|
928
1130
|
const source = SOURCES.find((s) => s.id === id) ?? (existsSync2(from) ? SOURCES[0] : void 0);
|
|
929
1131
|
if (!source) throw new UserError(`Unknown source ${id}. Sources: ${SOURCES.map((s) => s.id).join(", ")}.`);
|
|
930
1132
|
const fileArg = source === SOURCES[0] && !arg ? from : arg;
|
|
931
|
-
const
|
|
1133
|
+
const interactive = Boolean(process.stdin.isTTY) && !opts.yes && !opts.dryRun;
|
|
932
1134
|
let found;
|
|
933
1135
|
let existing;
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
1136
|
+
{
|
|
1137
|
+
const existingP = api("GET", "/secrets").then((r) => new Set(r.map((x) => x.name)));
|
|
1138
|
+
existingP.catch(() => {
|
|
1139
|
+
});
|
|
1140
|
+
const raw = await source.fetch(fileArg, { ...opts, interactive: !!process.stdin.isTTY && !opts.yes });
|
|
1141
|
+
const stop = spin(`Reading from ${source.label}`);
|
|
1142
|
+
try {
|
|
1143
|
+
existing = await existingP;
|
|
1144
|
+
} catch (err) {
|
|
1145
|
+
stop();
|
|
1146
|
+
throw err;
|
|
1147
|
+
}
|
|
1148
|
+
const d = disambiguate(raw);
|
|
1149
|
+
found = d.found;
|
|
1150
|
+
const kept = new Set(found);
|
|
1151
|
+
for (const f of raw) if (!kept.has(f)) f.value = "";
|
|
1152
|
+
stop(
|
|
1153
|
+
`${c.accent("\u25A0")} Read ${found.length} entr${found.length === 1 ? "y" : "ies"} from ${source.label}${d.merged ? c.dim(` (${d.merged} duplicate${d.merged === 1 ? "" : "s"} with the same value merged)`) : ""} ${c.dim("\xB7 names only; values are never shown")}`
|
|
1154
|
+
);
|
|
942
1155
|
}
|
|
943
|
-
stop(`${c.accent("\u25A0")} Read ${found.length} entr${found.length === 1 ? "y" : "ies"} from ${source.label} ${c.dim("(names only below; values are never shown)")}`);
|
|
944
1156
|
const { plans: matched, skipped, unknown } = classify(found, existing, { only: opts.only });
|
|
945
|
-
const interactive = Boolean(process.stdin.isTTY) && !opts.yes && !opts.dryRun;
|
|
946
1157
|
const count = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
947
1158
|
const tally = [
|
|
948
1159
|
[matched.length, "recognised", "known provider, destination filled in"],
|
|
949
|
-
[
|
|
1160
|
+
[
|
|
1161
|
+
unknown.length,
|
|
1162
|
+
"to pick",
|
|
1163
|
+
interactive ? "no preset: you pick which to store, then a host or park them" : opts.park ? "no preset: stored parked (no host yet)" : "not stored; add --park to store them without a host"
|
|
1164
|
+
],
|
|
950
1165
|
[skipped.length, "skipped", "empty, placeholders, or not usable as an API header (reasons below)"]
|
|
951
1166
|
];
|
|
952
1167
|
for (const [n, label2, why] of tally) if (n) process.stderr.write(` ${c.bold(String(n).padStart(3))} ${label2.padEnd(11)}${c.dim(why)}
|
|
@@ -965,20 +1180,42 @@ async function migrate(opts) {
|
|
|
965
1180
|
plans = matched.filter((p) => keep.has(p.name));
|
|
966
1181
|
}
|
|
967
1182
|
const later = [];
|
|
968
|
-
|
|
1183
|
+
const asPlan = (f, d) => ({
|
|
1184
|
+
...f,
|
|
1185
|
+
provider: d.provider,
|
|
1186
|
+
hosts: d.hosts,
|
|
1187
|
+
header: d.header,
|
|
1188
|
+
format: d.format,
|
|
1189
|
+
flags: [d.flag],
|
|
1190
|
+
replaces: existing.has(f.name)
|
|
1191
|
+
});
|
|
1192
|
+
if (unknown.length && !interactive) {
|
|
1193
|
+
for (const f of unknown) {
|
|
1194
|
+
if (opts.park) plans.push(asPlan(f, PARKED));
|
|
1195
|
+
else later.push({ name: f.name, why: `not stored (${f.why})` });
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
969
1198
|
if (unknown.length && interactive) {
|
|
970
1199
|
const pick = new Set(
|
|
971
1200
|
await checklist(
|
|
972
|
-
`${count(unknown.length, "more entry", "more entries")}
|
|
1201
|
+
`${count(unknown.length, "more entry", "more entries")} have no preset. Which should Keybox hold? (space toggles, a = all)`,
|
|
973
1202
|
unknown.map((f) => ({ value: f.name, label: f.name, hint: f.why ?? f.origin })),
|
|
974
|
-
() =>
|
|
1203
|
+
(n) => /^(no preset|name says)/.test(unknown.find((f) => f.name === n)?.why ?? "")
|
|
975
1204
|
)
|
|
976
1205
|
);
|
|
977
1206
|
const chosen = unknown.filter((f) => pick.has(f.name));
|
|
978
1207
|
for (const f of unknown) if (!pick.has(f.name)) later.push({ name: f.name, why: "not picked" });
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
1208
|
+
let how = chosen.length > 1 ? "" : "each";
|
|
1209
|
+
if (chosen.length > 1) {
|
|
1210
|
+
how = await choose(`Where may these ${chosen.length} go?`, [
|
|
1211
|
+
{ value: "each", label: "Choose now", hint: "keys that share a prefix share the answer" },
|
|
1212
|
+
{ value: "park", label: "Park them all, decide later", hint: "stored encrypted; no agent can use one until you run keybox secrets bind" }
|
|
1213
|
+
]);
|
|
1214
|
+
}
|
|
1215
|
+
const placed = how === "park" ? new Map(chosen.map((f) => [f.name, PARKED])) : await placeMany(chosen, { park: true });
|
|
1216
|
+
for (const f of chosen) {
|
|
1217
|
+
const d = placed.get(f.name);
|
|
1218
|
+
if (d) plans.push(asPlan(f, d));
|
|
982
1219
|
else later.push({ name: f.name, why: "skipped by you" });
|
|
983
1220
|
}
|
|
984
1221
|
}
|
|
@@ -986,11 +1223,17 @@ async function migrate(opts) {
|
|
|
986
1223
|
process.stdout.write(
|
|
987
1224
|
headed([
|
|
988
1225
|
["NAME", "PROVIDER", "ONLY SENT TO", ""],
|
|
989
|
-
...plans.map((p) => [
|
|
1226
|
+
...plans.map((p) => [
|
|
1227
|
+
p.name,
|
|
1228
|
+
p.hosts.length ? p.provider?.label ?? "Custom" : "Parked",
|
|
1229
|
+
p.hosts.join(",") || c.dim("nowhere yet"),
|
|
1230
|
+
[p.replaces ? "replaces existing" : "new", ...p.flags.filter((x) => x !== "parked")].join(", ")
|
|
1231
|
+
])
|
|
990
1232
|
])
|
|
991
1233
|
);
|
|
992
1234
|
}
|
|
993
1235
|
if (!interactive) printSkipped(later);
|
|
1236
|
+
if (!interactive && later.length) note("To keep those too: re-run with --park (stored, no host yet), or run keybox migrate at a terminal to pick hosts.");
|
|
994
1237
|
for (const p of plans.filter((p2) => p2.flags.includes("admin-grade"))) {
|
|
995
1238
|
warn(`${p.name} is an admin-grade key. ${p.provider?.adminHint ?? ""} Keybox blocks key-minting calls either way.`);
|
|
996
1239
|
}
|
|
@@ -1000,19 +1243,27 @@ async function migrate(opts) {
|
|
|
1000
1243
|
throw new UserError("Cancelled. Re-run with --yes to skip the prompt.");
|
|
1001
1244
|
}
|
|
1002
1245
|
let stored = 0;
|
|
1246
|
+
let oldWorker = false;
|
|
1003
1247
|
for (const p of plans) {
|
|
1248
|
+
if (oldWorker && !p.hosts.length) continue;
|
|
1004
1249
|
try {
|
|
1005
1250
|
const r = await api("PUT", `/secrets/${p.name}`, { hosts: p.hosts, header: p.header, format: p.format, value: p.value });
|
|
1006
|
-
ok(`${p.name} ${c.dim(`\u2192 ${p.hosts.join(", ")}${r.fingerprint ? ` \xB7 fp ${r.fingerprint}` : ""}`)}`);
|
|
1251
|
+
ok(`${p.name} ${c.dim(`\u2192 ${p.hosts.join(", ") || "parked"}${r.fingerprint ? ` \xB7 fp ${r.fingerprint}` : ""}`)}`);
|
|
1007
1252
|
stored++;
|
|
1008
1253
|
} catch (err) {
|
|
1009
|
-
|
|
1254
|
+
const msg = err.message;
|
|
1255
|
+
if (!p.hosts.length && /hosts must list 1-16/.test(msg)) {
|
|
1256
|
+
oldWorker = true;
|
|
1257
|
+
warn("Your Worker is older than 0.2.3 and cannot hold parked keys. Run keybox update, then migrate again for those.");
|
|
1258
|
+
} else warn(`${p.name}: ${msg}`);
|
|
1010
1259
|
}
|
|
1011
1260
|
p.value = "";
|
|
1012
1261
|
}
|
|
1013
1262
|
found.forEach((f) => f.value = "");
|
|
1014
1263
|
process.stderr.write("\n");
|
|
1264
|
+
const parked = plans.filter((p) => !p.hosts.length).length;
|
|
1015
1265
|
step(`Stored ${stored}.`);
|
|
1266
|
+
if (parked && !oldWorker) note(`${parked} parked. Give them hosts when you know: keybox secrets bind (or Set host in keybox ui)`);
|
|
1016
1267
|
if (opts.quietNext) return;
|
|
1017
1268
|
if (source.id === "dotenv" || source.id === "env") {
|
|
1018
1269
|
note(`${fileArg ?? "Your shell"} still holds the original values. Once Keybox works, delete them there and rotate`);
|
|
@@ -1022,7 +1273,7 @@ async function migrate(opts) {
|
|
|
1022
1273
|
}
|
|
1023
1274
|
note('Next: keybox agents create NAME --allow "METHOD host/path" then keybox run NAME -- your command');
|
|
1024
1275
|
}
|
|
1025
|
-
var json, SOURCES, NOT_READABLE, PLACEHOLDER;
|
|
1276
|
+
var json, SOURCES, NOT_READABLE, PLACEHOLDER, PARKED;
|
|
1026
1277
|
var init_migrate = __esm({
|
|
1027
1278
|
"src/migrate.ts"() {
|
|
1028
1279
|
"use strict";
|
|
@@ -1122,14 +1373,8 @@ var init_migrate = __esm({
|
|
|
1122
1373
|
id: "infisical",
|
|
1123
1374
|
label: "Infisical",
|
|
1124
1375
|
bin: "infisical",
|
|
1125
|
-
usage: "keybox migrate --from infisical [--env dev --path /]",
|
|
1126
|
-
|
|
1127
|
-
const args = ["export", "--format", "json"];
|
|
1128
|
-
if (o.env) args.push("--env", o.env);
|
|
1129
|
-
if (o.path) args.push("--path", o.path);
|
|
1130
|
-
if (o.project) args.push("--projectId", o.project);
|
|
1131
|
-
return json(await capture("infisical", args)).map((s) => ({ name: s.key, value: s.value, origin: `infisical:${s.key}` }));
|
|
1132
|
-
}
|
|
1376
|
+
usage: "keybox migrate --from infisical [--project NAME,\u2026] [--env dev,prod] [--path /]",
|
|
1377
|
+
fetch: fetchInfisical
|
|
1133
1378
|
},
|
|
1134
1379
|
{
|
|
1135
1380
|
id: "vault",
|
|
@@ -1219,6 +1464,7 @@ var init_migrate = __esm({
|
|
|
1219
1464
|
keepass: "Export is a plaintext file. Prefer `keepassxc-cli show -sa password DB ENTRY | keybox secrets add NAME` per key."
|
|
1220
1465
|
};
|
|
1221
1466
|
PLACEHOLDER = /^(x+|changeme|todo|tbd|none|null|your[-_ ].*|<.*>|\.\.\.|\*+)$/i;
|
|
1467
|
+
PARKED = { hosts: [], header: "authorization", format: "bearer", flag: "parked" };
|
|
1222
1468
|
}
|
|
1223
1469
|
});
|
|
1224
1470
|
|
|
@@ -1262,6 +1508,7 @@ __export(commands_exports, {
|
|
|
1262
1508
|
buildGrants: () => buildGrants2,
|
|
1263
1509
|
run: () => run,
|
|
1264
1510
|
secretsAdd: () => secretsAdd,
|
|
1511
|
+
secretsBind: () => secretsBind,
|
|
1265
1512
|
secretsImport: () => secretsImport,
|
|
1266
1513
|
secretsList: () => secretsList,
|
|
1267
1514
|
secretsRm: () => secretsRm,
|
|
@@ -1309,9 +1556,55 @@ async function secretsList() {
|
|
|
1309
1556
|
process.stdout.write(
|
|
1310
1557
|
headed([
|
|
1311
1558
|
["NAME", "HOSTS", "HEADER", "FINGERPRINT", "LAST USED"],
|
|
1312
|
-
...rows.map((s) => [s.name, s.hosts.join(","), `${s.header} (${s.format})`, s.fingerprint ?? "-", ago(s.last_used ?? null)])
|
|
1559
|
+
...rows.map((s) => [s.name, s.hosts.join(",") || c.warn("parked"), `${s.header} (${s.format})`, s.fingerprint ?? "-", ago(s.last_used ?? null)])
|
|
1313
1560
|
])
|
|
1314
1561
|
);
|
|
1562
|
+
const parked = rows.filter((s) => !s.hosts.length).length;
|
|
1563
|
+
if (parked) note(`${parked} parked: stored, but no agent can use ${parked === 1 ? "it" : "them"} until bound to a host. Run keybox secrets bind.`);
|
|
1564
|
+
}
|
|
1565
|
+
async function secretsBind(name, opts) {
|
|
1566
|
+
const rows = await api("GET", "/secrets");
|
|
1567
|
+
const bind = async (n2, d) => {
|
|
1568
|
+
const r = await api("PATCH", `/secrets/${n2}`, { hosts: d.hosts, header: d.header, format: d.format });
|
|
1569
|
+
ok(`${n2} ${c.dim(`\u2192 ${r.hosts.join(", ") || "parked"} \xB7 ${r.header} (${r.format})${r.fingerprint ? ` \xB7 fp ${r.fingerprint}` : ""}`)}`);
|
|
1570
|
+
};
|
|
1571
|
+
if (name) {
|
|
1572
|
+
const row = rows.find((s) => s.name === name);
|
|
1573
|
+
if (!row) throw new UserError(`No secret named ${name}. See keybox secrets list.`);
|
|
1574
|
+
if (opts.host?.length || opts.preset) {
|
|
1575
|
+
const p = opts.preset ? PRESETS[opts.preset] : void 0;
|
|
1576
|
+
if (opts.preset && !p) throw new UserError(`Unknown preset ${opts.preset}. Known: ${Object.keys(PRESETS).join(", ")}.`);
|
|
1577
|
+
return bind(name, {
|
|
1578
|
+
hosts: opts.host?.length ? opts.host.map((h) => h.toLowerCase()) : p.hosts,
|
|
1579
|
+
header: opts.header ?? p?.header ?? row.header,
|
|
1580
|
+
format: opts.format ?? p?.format ?? row.format,
|
|
1581
|
+
flag: "bound"
|
|
1582
|
+
});
|
|
1583
|
+
}
|
|
1584
|
+
if (!process.stdin.isTTY) throw new UserError(`Say where: keybox secrets bind ${name} --host HOST (or --preset NAME).`);
|
|
1585
|
+
const placed2 = await placeMany([{ name, guess: detect(name, "").provider }], { park: false, skipLabel: "Leave it as it is" });
|
|
1586
|
+
const d = placed2.get(name);
|
|
1587
|
+
return d ? bind(name, d) : note(`${name} unchanged.`);
|
|
1588
|
+
}
|
|
1589
|
+
const parked = rows.filter((s) => !s.hosts.length);
|
|
1590
|
+
if (!parked.length) return note("No parked keys. To move one: keybox secrets bind NAME --host HOST");
|
|
1591
|
+
if (!process.stdin.isTTY) throw new UserError(`${parked.length} parked: ${parked.map((s) => s.name).join(", ")}. Bind each with keybox secrets bind NAME --host HOST.`);
|
|
1592
|
+
step(`${parked.length} parked key${parked.length === 1 ? "" : "s"}. Pick a host for each, or leave it parked.`);
|
|
1593
|
+
const placed = await placeMany(
|
|
1594
|
+
parked.map((s) => ({ name: s.name, guess: detect(s.name, "").provider })),
|
|
1595
|
+
{ park: false, skipLabel: "Leave it parked" }
|
|
1596
|
+
);
|
|
1597
|
+
let n = 0;
|
|
1598
|
+
for (const [k, d] of placed) {
|
|
1599
|
+
if (!d) continue;
|
|
1600
|
+
try {
|
|
1601
|
+
await bind(k, d);
|
|
1602
|
+
n++;
|
|
1603
|
+
} catch (err) {
|
|
1604
|
+
warn(`${k}: ${err.message}`);
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
note(n ? `Bound ${n}. Grant them to an agent: keybox agents create NAME --allow "GET host/**"` : "Nothing changed.");
|
|
1315
1608
|
}
|
|
1316
1609
|
async function secretsRm(name) {
|
|
1317
1610
|
const r = await api("DELETE", `/secrets/${name}`);
|
|
@@ -1459,11 +1752,11 @@ var init_commands = __esm({
|
|
|
1459
1752
|
import { spawn as spawn3 } from "node:child_process";
|
|
1460
1753
|
import { readFileSync as readFileSync3 } from "node:fs";
|
|
1461
1754
|
import { createRequire } from "node:module";
|
|
1462
|
-
import { dirname, join as
|
|
1755
|
+
import { dirname, join as join3 } from "node:path";
|
|
1463
1756
|
function bin() {
|
|
1464
1757
|
const pkgPath = createRequire(import.meta.url).resolve("wrangler/package.json");
|
|
1465
1758
|
const pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
|
|
1466
|
-
return
|
|
1759
|
+
return join3(dirname(pkgPath), pkg.bin.wrangler);
|
|
1467
1760
|
}
|
|
1468
1761
|
function useAccount(id) {
|
|
1469
1762
|
accountId = id;
|
|
@@ -1597,7 +1890,7 @@ var VERSION;
|
|
|
1597
1890
|
var init_version = __esm({
|
|
1598
1891
|
"src/version.ts"() {
|
|
1599
1892
|
"use strict";
|
|
1600
|
-
VERSION = true ? "0.2.
|
|
1893
|
+
VERSION = true ? "0.2.3" : "0.0.0-dev";
|
|
1601
1894
|
}
|
|
1602
1895
|
});
|
|
1603
1896
|
|
|
@@ -1757,7 +2050,7 @@ __export(deploy_exports, {
|
|
|
1757
2050
|
import { spawn as spawn4 } from "node:child_process";
|
|
1758
2051
|
import { createHash as createHash2, randomBytes } from "node:crypto";
|
|
1759
2052
|
import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
|
|
1760
|
-
import { join as
|
|
2053
|
+
import { join as join4 } from "node:path";
|
|
1761
2054
|
async function deployWorker(cfg) {
|
|
1762
2055
|
for (let attempt = 1; ; attempt++) {
|
|
1763
2056
|
try {
|
|
@@ -1771,10 +2064,10 @@ async function deployWorker(cfg) {
|
|
|
1771
2064
|
}
|
|
1772
2065
|
function writeDeployFiles(name, d1Id, accountId2) {
|
|
1773
2066
|
const dir = deployDir();
|
|
1774
|
-
mkdirSync2(
|
|
1775
|
-
copyFileSync(asset("worker.js"),
|
|
1776
|
-
copyFileSync(asset("schema.sql"),
|
|
1777
|
-
const cfg =
|
|
2067
|
+
mkdirSync2(join4(dir, "worker"), { recursive: true, mode: 448 });
|
|
2068
|
+
copyFileSync(asset("worker.js"), join4(dir, "worker", "worker.js"));
|
|
2069
|
+
copyFileSync(asset("schema.sql"), join4(dir, "schema.sql"));
|
|
2070
|
+
const cfg = join4(dir, "wrangler.json");
|
|
1778
2071
|
writeFileSync2(
|
|
1779
2072
|
cfg,
|
|
1780
2073
|
JSON.stringify(
|
|
@@ -1882,7 +2175,7 @@ async function init(opts) {
|
|
|
1882
2175
|
const cfgPath = writeDeployFiles(name, d1Id, account.id);
|
|
1883
2176
|
await task(
|
|
1884
2177
|
"Schema",
|
|
1885
|
-
() => wrangler(["d1", "execute", name, "--remote", "--yes", "--file",
|
|
2178
|
+
() => wrangler(["d1", "execute", name, "--remote", "--yes", "--file", join4(deployDir(), "schema.sql"), "--config", cfgPath], { capture: true, quiet: true }),
|
|
1886
2179
|
() => "applied"
|
|
1887
2180
|
);
|
|
1888
2181
|
const url = await task(
|
|
@@ -1961,7 +2254,7 @@ async function deploy(opts) {
|
|
|
1961
2254
|
if (!cfg.d1Id) throw new UserError("`keybox deploy` needs the config written by `keybox init`.");
|
|
1962
2255
|
await resolveAccount(cfg);
|
|
1963
2256
|
const dir = deployDir();
|
|
1964
|
-
const current = existsSync3(
|
|
2257
|
+
const current = existsSync3(join4(dir, "worker", "worker.js")) ? sha(join4(dir, "worker", "worker.js")) : null;
|
|
1965
2258
|
const next = shippedWorkerHash();
|
|
1966
2259
|
if (current === next && !opts.force) {
|
|
1967
2260
|
ok("The deployed Worker already matches this CLI version. Run `keybox verify` to check what Cloudflare is serving.");
|
|
@@ -1979,7 +2272,7 @@ ${c.accent("\u25A0")} This replaces the Worker that holds your keys.
|
|
|
1979
2272
|
const wranglerCfg = writeDeployFiles(fresh.name, fresh.d1Id, fresh.accountId);
|
|
1980
2273
|
await task(
|
|
1981
2274
|
"Schema",
|
|
1982
|
-
() => wrangler(["d1", "execute", fresh.name, "--remote", "--yes", "--file",
|
|
2275
|
+
() => wrangler(["d1", "execute", fresh.name, "--remote", "--yes", "--file", join4(dir, "schema.sql"), "--config", wranglerCfg], { capture: true, quiet: true }),
|
|
1983
2276
|
() => "applied"
|
|
1984
2277
|
);
|
|
1985
2278
|
await task("Worker", () => deployWorker(wranglerCfg), () => "deployed");
|
|
@@ -3846,8 +4139,8 @@ __export(extra_exports, {
|
|
|
3846
4139
|
});
|
|
3847
4140
|
import { spawn as spawn5 } from "node:child_process";
|
|
3848
4141
|
import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "node:fs";
|
|
3849
|
-
import { homedir as
|
|
3850
|
-
import { dirname as dirname2, join as
|
|
4142
|
+
import { homedir as homedir3 } from "node:os";
|
|
4143
|
+
import { dirname as dirname2, join as join5 } from "node:path";
|
|
3851
4144
|
function openBrowser(url) {
|
|
3852
4145
|
const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
|
|
3853
4146
|
const args = process.platform === "win32" ? ["/c", "start", '""', url] : [url];
|
|
@@ -3975,11 +4268,11 @@ async function accessCloudflare(opts) {
|
|
|
3975
4268
|
async function skill(opts) {
|
|
3976
4269
|
const text = readFileSync6(skillAsset(), "utf8");
|
|
3977
4270
|
if (opts.print) return void process.stdout.write(text);
|
|
3978
|
-
const base = opts.project ? process.cwd() :
|
|
4271
|
+
const base = opts.project ? process.cwd() : homedir3();
|
|
3979
4272
|
const targets = {
|
|
3980
|
-
claude:
|
|
3981
|
-
codex:
|
|
3982
|
-
agents:
|
|
4273
|
+
claude: join5(base, ".claude", "skills", "keybox", "SKILL.md"),
|
|
4274
|
+
codex: join5(opts.project ? join5(base, ".codex") : join5(homedir3(), ".codex"), "skills", "keybox", "SKILL.md"),
|
|
4275
|
+
agents: join5(base, ".agents", "skills", "keybox", "SKILL.md")
|
|
3983
4276
|
};
|
|
3984
4277
|
const pick = opts.target === "all" ? Object.keys(targets) : opts.target.split(",");
|
|
3985
4278
|
for (const t of pick) {
|
|
@@ -4029,7 +4322,7 @@ init_dove();
|
|
|
4029
4322
|
init_ui();
|
|
4030
4323
|
import { spawn as spawn6 } from "node:child_process";
|
|
4031
4324
|
import { existsSync as existsSync5 } from "node:fs";
|
|
4032
|
-
import { delimiter, join as
|
|
4325
|
+
import { delimiter, join as join6 } from "node:path";
|
|
4033
4326
|
var TABS = ["Activity", "Secrets", "Agents"];
|
|
4034
4327
|
var out = process.stdout;
|
|
4035
4328
|
var ago2 = (ms) => {
|
|
@@ -4058,7 +4351,7 @@ function nativeTui() {
|
|
|
4058
4351
|
if (explicit && existsSync5(explicit)) return explicit;
|
|
4059
4352
|
for (const dir of (process.env.PATH ?? "").split(delimiter)) {
|
|
4060
4353
|
for (const name of process.platform === "win32" ? ["keybox-tui.exe"] : ["keybox-tui"]) {
|
|
4061
|
-
const p =
|
|
4354
|
+
const p = join6(dir, name);
|
|
4062
4355
|
if (dir && existsSync5(p)) return p;
|
|
4063
4356
|
}
|
|
4064
4357
|
}
|
|
@@ -4257,14 +4550,14 @@ init_verify();
|
|
|
4257
4550
|
init_version();
|
|
4258
4551
|
import { spawn as spawn7, spawnSync as spawnSync2 } from "node:child_process";
|
|
4259
4552
|
import { existsSync as existsSync6, realpathSync } from "node:fs";
|
|
4260
|
-
import { dirname as dirname3, join as
|
|
4553
|
+
import { dirname as dirname3, join as join7 } from "node:path";
|
|
4261
4554
|
import { fileURLToPath } from "node:url";
|
|
4262
4555
|
function howInstalled() {
|
|
4263
4556
|
const self = realpathSync(fileURLToPath(import.meta.url));
|
|
4264
|
-
if (self.includes(`${
|
|
4557
|
+
if (self.includes(`${join7("_npx", "")}`) || self.includes("/_npx/")) return { kind: "npx" };
|
|
4265
4558
|
const root = dirname3(dirname3(dirname3(self)));
|
|
4266
|
-
if (existsSync6(
|
|
4267
|
-
if (self.includes(
|
|
4559
|
+
if (existsSync6(join7(root, ".git")) && existsSync6(join7(root, "cli", "package.json"))) return { kind: "checkout", root };
|
|
4560
|
+
if (self.includes(join7("node_modules", "@keyboxed", "cli"))) return { kind: "npm-global" };
|
|
4268
4561
|
return { kind: "unknown", path: self };
|
|
4269
4562
|
}
|
|
4270
4563
|
function newer(a, b) {
|
|
@@ -4330,7 +4623,7 @@ async function update(opts) {
|
|
|
4330
4623
|
}
|
|
4331
4624
|
if (cliUpdated) {
|
|
4332
4625
|
ok("CLI updated. Continuing with the new version.");
|
|
4333
|
-
const bin2 = install.kind === "checkout" ? [process.execPath,
|
|
4626
|
+
const bin2 = install.kind === "checkout" ? [process.execPath, join7(install.root, "cli", "dist", "keybox.js")] : ["keybox"];
|
|
4334
4627
|
const code = await run2(bin2[0], [...bin2.slice(1), "update", "--worker-only", ...opts.yes ? ["--yes"] : []]);
|
|
4335
4628
|
process.exitCode = code;
|
|
4336
4629
|
return;
|
|
@@ -4373,13 +4666,15 @@ var HELP_BODY = `Setup
|
|
|
4373
4666
|
keybox tui [--basic] Live console (uses keybox-tui, the Rust console, when installed)
|
|
4374
4667
|
|
|
4375
4668
|
Moving keys in (values are never printed, logged or put on a command line)
|
|
4376
|
-
keybox migrate [--from SOURCE] [--dry-run] [--yes] [--only A,B]
|
|
4669
|
+
keybox migrate [--from SOURCE] [--dry-run] [--yes] [--park] [--only A,B]
|
|
4377
4670
|
SOURCE: dotenv:FILE | env | 1password [--vault V] | bitwarden | bws [--project ID]
|
|
4378
|
-
doppler [--project P --config C] | infisical [--env
|
|
4671
|
+
doppler [--project P --config C] | infisical [--project A,B --env dev,prod --path P]
|
|
4379
4672
|
vault:PATH | sops:FILE | aws:SECRET_ID | gcp [--project P]
|
|
4380
4673
|
pass --item PATH | keychain --item SERVICE
|
|
4381
4674
|
keybox secrets add NAME [--from op://vault/item/field | vault://path#field | env://VAR \u2026]
|
|
4382
4675
|
[--preset openai|anthropic|github|\u2026] [--host HOST \u2026 --header H --format bearer|raw|basic]
|
|
4676
|
+
keybox secrets bind [NAME] [--preset P | --host HOST \u2026 --header H --format F]
|
|
4677
|
+
Give a parked key a host, or change where a key may go, without re-sending it
|
|
4383
4678
|
keybox secrets list | rm NAME
|
|
4384
4679
|
|
|
4385
4680
|
Agents
|
|
@@ -4423,6 +4718,7 @@ async function main(argv) {
|
|
|
4423
4718
|
url: { type: "string" },
|
|
4424
4719
|
yes: { type: "boolean", short: "y", default: false },
|
|
4425
4720
|
"dry-run": { type: "boolean", default: false },
|
|
4721
|
+
park: { type: "boolean", default: false },
|
|
4426
4722
|
force: { type: "boolean", default: false },
|
|
4427
4723
|
preset: { type: "string" },
|
|
4428
4724
|
host: { type: "string", multiple: true },
|
|
@@ -4499,12 +4795,15 @@ async function main(argv) {
|
|
|
4499
4795
|
config: o.config,
|
|
4500
4796
|
env: o.env,
|
|
4501
4797
|
path: o.path,
|
|
4502
|
-
item: o.item
|
|
4798
|
+
item: o.item,
|
|
4799
|
+
park: o.park
|
|
4503
4800
|
});
|
|
4504
4801
|
case "secrets add":
|
|
4505
4802
|
return secretsAdd(need(arg, "secret name"), { preset: o.preset, host: o.host, header: o.header, format: o.format, from: o.from });
|
|
4506
4803
|
case "secrets import":
|
|
4507
4804
|
return secretsImport(need(arg, "file"), { dryRun: o["dry-run"], yes: o.yes });
|
|
4805
|
+
case "secrets bind":
|
|
4806
|
+
return secretsBind(arg, { preset: o.preset, host: o.host, header: o.header, format: o.format });
|
|
4508
4807
|
case "secrets list":
|
|
4509
4808
|
return secretsList();
|
|
4510
4809
|
case "secrets rm":
|