@keyboxed/cli 0.2.1 → 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 +2322 -107
- package/package.json +3 -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 = [
|