@keyboxed/cli 0.1.1 → 0.2.0
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/README.md +7 -1
- package/assets/schema.sql +3 -0
- package/assets/skill/SKILL.md +173 -0
- package/assets/worker.js +447 -37
- package/dist/keybox.js +2128 -305
- package/package.json +1 -1
package/assets/worker.js
CHANGED
|
@@ -1,3 +1,50 @@
|
|
|
1
|
+
// src/access.ts
|
|
2
|
+
var cache = null;
|
|
3
|
+
async function keys(team, refresh = false) {
|
|
4
|
+
if (!refresh && cache && cache.team === team && Date.now() - cache.at < 36e5) return cache.keys;
|
|
5
|
+
const r = await fetch(`https://${team}/cdn-cgi/access/certs`);
|
|
6
|
+
if (!r.ok) return [];
|
|
7
|
+
const body2 = await r.json();
|
|
8
|
+
cache = { team, at: Date.now(), keys: body2.keys ?? [] };
|
|
9
|
+
return cache.keys;
|
|
10
|
+
}
|
|
11
|
+
function b64urlBytes(s) {
|
|
12
|
+
const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "="));
|
|
13
|
+
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
14
|
+
}
|
|
15
|
+
async function verifyAccess(jwt, cfg) {
|
|
16
|
+
if (!jwt || !cfg) return null;
|
|
17
|
+
const parts = jwt.split(".");
|
|
18
|
+
if (parts.length !== 3) return null;
|
|
19
|
+
let header;
|
|
20
|
+
let claims;
|
|
21
|
+
try {
|
|
22
|
+
header = JSON.parse(new TextDecoder().decode(b64urlBytes(parts[0])));
|
|
23
|
+
claims = JSON.parse(new TextDecoder().decode(b64urlBytes(parts[1])));
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
if (header.alg !== "RS256" || !header.kid) return null;
|
|
28
|
+
let jwk = (await keys(cfg.teamDomain)).find((k) => k.kid === header.kid);
|
|
29
|
+
if (!jwk) jwk = (await keys(cfg.teamDomain, true)).find((k) => k.kid === header.kid);
|
|
30
|
+
if (!jwk) return null;
|
|
31
|
+
const key = await crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
|
|
32
|
+
const ok = await crypto.subtle.verify(
|
|
33
|
+
"RSASSA-PKCS1-v1_5",
|
|
34
|
+
key,
|
|
35
|
+
b64urlBytes(parts[2]),
|
|
36
|
+
new TextEncoder().encode(`${parts[0]}.${parts[1]}`)
|
|
37
|
+
);
|
|
38
|
+
if (!ok) return null;
|
|
39
|
+
const now = Date.now() / 1e3;
|
|
40
|
+
const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
41
|
+
if (!aud.includes(cfg.aud)) return null;
|
|
42
|
+
if (!claims.exp || claims.exp < now - 30) return null;
|
|
43
|
+
if (claims.nbf && claims.nbf > now + 30) return null;
|
|
44
|
+
if (claims.iss !== `https://${cfg.teamDomain}`) return null;
|
|
45
|
+
return claims.email ?? claims.sub ?? "access-user";
|
|
46
|
+
}
|
|
47
|
+
|
|
1
48
|
// src/crypto.ts
|
|
2
49
|
var enc = new TextEncoder();
|
|
3
50
|
var dec = new TextDecoder();
|
|
@@ -60,9 +107,19 @@ function headerValue(format, value) {
|
|
|
60
107
|
return value;
|
|
61
108
|
}
|
|
62
109
|
function needles(format, value) {
|
|
63
|
-
const
|
|
64
|
-
if (format === "basic")
|
|
65
|
-
|
|
110
|
+
const forms = /* @__PURE__ */ new Set([value, value.replace(/\//g, "\\/"), encodeURIComponent(value)]);
|
|
111
|
+
if (format === "basic") {
|
|
112
|
+
const basic = b64(enc.encode(value));
|
|
113
|
+
forms.add(basic);
|
|
114
|
+
forms.add(basic.replace(/\//g, "\\/"));
|
|
115
|
+
}
|
|
116
|
+
return [...forms].map((f) => enc.encode(f));
|
|
117
|
+
}
|
|
118
|
+
async function fingerprint(rawKek, value) {
|
|
119
|
+
const key = await crypto.subtle.importKey("raw", unb64(rawKek.trim()), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
120
|
+
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(`keybox/fp
|
|
121
|
+
${value}`)));
|
|
122
|
+
return Array.from(mac.subarray(0, 6), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
66
123
|
}
|
|
67
124
|
|
|
68
125
|
// src/policy.ts
|
|
@@ -136,6 +193,8 @@ var BUILTIN = [
|
|
|
136
193
|
[`${W} */**/access_tokens/**`, "mints access tokens"],
|
|
137
194
|
[`${W} */**/access-tokens/**`, "mints access tokens"],
|
|
138
195
|
[`${W} */**/personal_access_tokens/**`, "mints access tokens"],
|
|
196
|
+
["POST */**/registration-token", "mints a runner registration token"],
|
|
197
|
+
["POST */**/remove-token", "mints a runner removal token"],
|
|
139
198
|
// OpenAI
|
|
140
199
|
["* api.openai.com/v1/organization/admin_api_keys/**", "OpenAI admin keys"],
|
|
141
200
|
["* api.openai.com/v1/organization/projects/*/api_keys/**", "OpenAI project keys"],
|
|
@@ -166,6 +225,14 @@ var BUILTIN = [
|
|
|
166
225
|
[`${W} api.github.com/orgs/*/teams/*/memberships/**`, "changes team membership"],
|
|
167
226
|
[`${W} api.github.com/repos/*/*/actions/secrets/**`, "writes Actions secrets"],
|
|
168
227
|
[`${W} api.github.com/orgs/*/actions/secrets/**`, "writes Actions secrets"],
|
|
228
|
+
[`${W} api.github.com/repos/*/*/environments/*/secrets/**`, "writes environment secrets"],
|
|
229
|
+
[`${W} api.github.com/repos/*/*/dependabot/secrets/**`, "writes Dependabot secrets"],
|
|
230
|
+
[`${W} api.github.com/orgs/*/dependabot/secrets/**`, "writes Dependabot secrets"],
|
|
231
|
+
[`${W} api.github.com/repos/*/*/codespaces/secrets/**`, "writes Codespaces secrets"],
|
|
232
|
+
[`${W} api.github.com/orgs/*/codespaces/secrets/**`, "writes Codespaces secrets"],
|
|
233
|
+
[`${W} api.github.com/user/codespaces/secrets/**`, "writes Codespaces secrets"],
|
|
234
|
+
["POST api.github.com/repos/*/*/actions/runners/generate-jitconfig", "mints a runner credential"],
|
|
235
|
+
["POST api.github.com/orgs/*/actions/runners/generate-jitconfig", "mints a runner credential"],
|
|
169
236
|
[`${W} api.github.com/app/installations/*/access_tokens`, "mints an installation token"],
|
|
170
237
|
["* api.github.com/applications/**", "OAuth app token management"],
|
|
171
238
|
["* api.github.com/authorizations/**", "OAuth authorisations"],
|
|
@@ -178,7 +245,9 @@ var BUILTIN = [
|
|
|
178
245
|
["* api.cloudflare.com/client/v4/user/tokens/**", "Cloudflare API tokens"],
|
|
179
246
|
["* api.cloudflare.com/client/v4/accounts/*/tokens/**", "Cloudflare API tokens"],
|
|
180
247
|
[`${W} api.cloudflare.com/client/v4/accounts/*/members/**`, "changes account membership"],
|
|
181
|
-
["* api.cloudflare.com/client/v4/accounts/*/access/service_tokens/**", "Access service tokens"]
|
|
248
|
+
["* api.cloudflare.com/client/v4/accounts/*/access/service_tokens/**", "Access service tokens"],
|
|
249
|
+
["GET api.cloudflare.com/client/v4/accounts/*/cfd_tunnel/*/token", "returns a tunnel credential"],
|
|
250
|
+
["GET api.cloudflare.com/client/v4/accounts/*/warp_connector/*/token", "returns a connector credential"]
|
|
182
251
|
];
|
|
183
252
|
var compiled = BUILTIN.map(([src, reason]) => ({ rule: parseRule(src, { caseInsensitive: true }), reason }));
|
|
184
253
|
function denyRules(self) {
|
|
@@ -206,8 +275,132 @@ function denied(rules, method, host, path) {
|
|
|
206
275
|
return null;
|
|
207
276
|
}
|
|
208
277
|
|
|
278
|
+
// src/network.ts
|
|
279
|
+
function caller(req) {
|
|
280
|
+
const cf = req.cf;
|
|
281
|
+
return { ip: req.headers.get("cf-connecting-ip"), country: cf?.country?.toUpperCase() ?? null };
|
|
282
|
+
}
|
|
283
|
+
function check(rule, c) {
|
|
284
|
+
if (!rule) return null;
|
|
285
|
+
if (rule.denyCountries?.length && c.country && rule.denyCountries.includes(c.country)) {
|
|
286
|
+
return `requests from ${c.country} are blocked`;
|
|
287
|
+
}
|
|
288
|
+
if (rule.allowCountries?.length && (!c.country || !rule.allowCountries.includes(c.country))) {
|
|
289
|
+
return `requests from ${c.country ?? "an unknown country"} are not allowed`;
|
|
290
|
+
}
|
|
291
|
+
if (rule.allowIps?.length && (!c.ip || !rule.allowIps.some((cidr) => inCidr(c.ip, cidr)))) {
|
|
292
|
+
return `${c.ip ?? "this address"} is not in an allowed range`;
|
|
293
|
+
}
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
var COUNTRY = /^([A-Z]{2}|T1|XX)$/;
|
|
297
|
+
function validRule(r, where) {
|
|
298
|
+
if (r === void 0 || r === null) return {};
|
|
299
|
+
if (typeof r !== "object" || Array.isArray(r)) throw new Error(`${where} must be an object`);
|
|
300
|
+
const o = r;
|
|
301
|
+
const list = (k, test, what, map = (s) => s) => {
|
|
302
|
+
const v = o[k];
|
|
303
|
+
if (v === void 0) return void 0;
|
|
304
|
+
if (!Array.isArray(v) || v.length > 256) throw new Error(`${where}.${k} must be a list of up to 256 ${what}`);
|
|
305
|
+
const out = v.map((x) => map(String(x).trim()));
|
|
306
|
+
for (const x of out) if (!test(x)) throw new Error(`${where}.${k}: not a valid ${what}: ${x}`);
|
|
307
|
+
return out.length ? [...new Set(out)] : void 0;
|
|
308
|
+
};
|
|
309
|
+
const up = (s) => s.toUpperCase();
|
|
310
|
+
const rule = {
|
|
311
|
+
allowIps: list("allowIps", (s) => parseCidr(s) !== null, "IP or CIDR"),
|
|
312
|
+
allowCountries: list("allowCountries", (s) => COUNTRY.test(s), "country code", up),
|
|
313
|
+
denyCountries: list("denyCountries", (s) => COUNTRY.test(s), "country code", up)
|
|
314
|
+
};
|
|
315
|
+
for (const k of Object.keys(rule)) if (!rule[k]) delete rule[k];
|
|
316
|
+
return rule;
|
|
317
|
+
}
|
|
318
|
+
function validPolicy(p) {
|
|
319
|
+
if (!p || typeof p !== "object" || Array.isArray(p)) throw new Error("policy must be an object");
|
|
320
|
+
const o = p;
|
|
321
|
+
const out = {};
|
|
322
|
+
const admin2 = validRule(o.admin, "admin");
|
|
323
|
+
const proxy2 = validRule(o.proxy, "proxy");
|
|
324
|
+
if (Object.keys(admin2).length) out.admin = admin2;
|
|
325
|
+
if (Object.keys(proxy2).length) out.proxy = proxy2;
|
|
326
|
+
if (o.agents !== void 0) {
|
|
327
|
+
if (!o.agents || typeof o.agents !== "object") throw new Error("agents must be an object");
|
|
328
|
+
const agents = {};
|
|
329
|
+
for (const [name, r] of Object.entries(o.agents)) {
|
|
330
|
+
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(name)) throw new Error(`not an agent name: ${name}`);
|
|
331
|
+
const rule = validRule(r, `agents.${name}`);
|
|
332
|
+
if (Object.keys(rule).length) agents[name] = rule;
|
|
333
|
+
}
|
|
334
|
+
if (Object.keys(agents).length) out.agents = agents;
|
|
335
|
+
}
|
|
336
|
+
if (o.access !== void 0 && o.access !== null) {
|
|
337
|
+
const a = o.access;
|
|
338
|
+
const team = String(a.teamDomain ?? "").trim().toLowerCase().replace(/^https:\/\//, "").replace(/\/.*$/, "");
|
|
339
|
+
const aud = String(a.aud ?? "").trim();
|
|
340
|
+
if (!/^[a-z0-9-]+\.cloudflareaccess\.com$/.test(team)) throw new Error("access.teamDomain must look like myteam.cloudflareaccess.com");
|
|
341
|
+
if (!/^[a-f0-9]{64}$/.test(aud)) throw new Error("access.aud must be the 64-character Application Audience tag");
|
|
342
|
+
out.access = { teamDomain: team, aud };
|
|
343
|
+
}
|
|
344
|
+
return out;
|
|
345
|
+
}
|
|
346
|
+
function parseIp(s) {
|
|
347
|
+
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(s)) {
|
|
348
|
+
const parts = s.split(".").map(Number);
|
|
349
|
+
if (parts.some((n) => n > 255)) return null;
|
|
350
|
+
return { v6: false, bytes: Uint8Array.from(parts) };
|
|
351
|
+
}
|
|
352
|
+
if (!/^[0-9a-f:.]+$/i.test(s) || !s.includes(":")) return null;
|
|
353
|
+
let tail = [];
|
|
354
|
+
const m = /^(.*:)(\d{1,3}(?:\.\d{1,3}){3})$/.exec(s);
|
|
355
|
+
if (m) {
|
|
356
|
+
const v4 = parseIp(m[2]);
|
|
357
|
+
if (!v4) return null;
|
|
358
|
+
tail = [v4.bytes[0] << 8 | v4.bytes[1], v4.bytes[2] << 8 | v4.bytes[3]];
|
|
359
|
+
s = m[1].endsWith("::") ? m[1] : m[1].slice(0, -1);
|
|
360
|
+
}
|
|
361
|
+
const halves = s.split("::");
|
|
362
|
+
if (halves.length > 2) return null;
|
|
363
|
+
const words = (h) => h ? h.split(":").map((w) => /^[0-9a-f]{1,4}$/i.test(w) ? parseInt(w, 16) : NaN) : [];
|
|
364
|
+
const head = words(halves[0]);
|
|
365
|
+
const rest = halves.length === 2 ? words(halves[1]) : [];
|
|
366
|
+
const total = head.length + rest.length + tail.length;
|
|
367
|
+
if (head.some(isNaN) || rest.some(isNaN)) return null;
|
|
368
|
+
if (halves.length === 1 ? total !== 8 : total > 7) return null;
|
|
369
|
+
const all = [...head, ...Array(8 - total).fill(0), ...rest, ...tail];
|
|
370
|
+
const bytes = new Uint8Array(16);
|
|
371
|
+
all.forEach((w, i) => {
|
|
372
|
+
bytes[i * 2] = w >> 8;
|
|
373
|
+
bytes[i * 2 + 1] = w & 255;
|
|
374
|
+
});
|
|
375
|
+
return { v6: true, bytes };
|
|
376
|
+
}
|
|
377
|
+
function parseCidr(s) {
|
|
378
|
+
const [addr, len, extra] = s.split("/");
|
|
379
|
+
if (extra !== void 0) return null;
|
|
380
|
+
const ip = parseIp(addr);
|
|
381
|
+
if (!ip) return null;
|
|
382
|
+
const max = ip.v6 ? 128 : 32;
|
|
383
|
+
const bits = len === void 0 ? max : /^\d{1,3}$/.test(len) ? Number(len) : NaN;
|
|
384
|
+
if (!(bits >= 0 && bits <= max)) return null;
|
|
385
|
+
return { ...ip, bits };
|
|
386
|
+
}
|
|
387
|
+
function inCidr(ip, cidr) {
|
|
388
|
+
const a = parseIp(ip);
|
|
389
|
+
const c = parseCidr(cidr);
|
|
390
|
+
if (!a || !c) return false;
|
|
391
|
+
let bytes = a.bytes;
|
|
392
|
+
if (a.v6 && !c.v6 && bytes.subarray(0, 12).every((b, i) => b === (i >= 10 ? 255 : 0))) bytes = bytes.subarray(12);
|
|
393
|
+
else if (a.v6 !== c.v6) return false;
|
|
394
|
+
let bits = c.bits;
|
|
395
|
+
for (let i = 0; bits > 0; i++, bits -= 8) {
|
|
396
|
+
const mask = bits >= 8 ? 255 : 255 << 8 - bits & 255;
|
|
397
|
+
if ((bytes[i] & mask) !== (c.bytes[i] & mask)) return false;
|
|
398
|
+
}
|
|
399
|
+
return true;
|
|
400
|
+
}
|
|
401
|
+
|
|
209
402
|
// src/types.ts
|
|
210
|
-
var VERSION = "0.
|
|
403
|
+
var VERSION = "0.2.0";
|
|
211
404
|
function keyboxError(status, code, message) {
|
|
212
405
|
return Response.json({ type: "error", error: { type: "keybox_error", code, message } }, { status });
|
|
213
406
|
}
|
|
@@ -229,40 +422,162 @@ var FORMATS = /* @__PURE__ */ new Set(["bearer", "raw", "basic"]);
|
|
|
229
422
|
var MAX_TTL = 365 * 24 * 3600;
|
|
230
423
|
var Bad = class extends Error {
|
|
231
424
|
};
|
|
232
|
-
function
|
|
425
|
+
function check2(ok, msg) {
|
|
233
426
|
if (!ok) throw new Bad(msg);
|
|
234
427
|
}
|
|
235
|
-
|
|
428
|
+
var SESSION_COOKIE = "kb_session";
|
|
429
|
+
var SESSION_TTL = 12 * 3600 * 1e3;
|
|
430
|
+
var LOGIN_TTL = 120 * 1e3;
|
|
431
|
+
async function loadPolicy(env) {
|
|
432
|
+
const row = await env.DB.prepare("SELECT value FROM settings WHERE key = 'policy'").first();
|
|
433
|
+
if (!row) return {};
|
|
434
|
+
try {
|
|
435
|
+
return JSON.parse(row.value);
|
|
436
|
+
} catch {
|
|
437
|
+
return {};
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
function sessionCookie(req) {
|
|
441
|
+
const m = new RegExp(`(?:^|;\\s*)${SESSION_COOKIE}=([A-Za-z0-9_-]+)`).exec(req.headers.get("cookie") ?? "");
|
|
442
|
+
return m ? m[1] : null;
|
|
443
|
+
}
|
|
444
|
+
function setSessionCookie(value, maxAge) {
|
|
445
|
+
return `${SESSION_COOKIE}=${value}; Path=/_keybox/; Max-Age=${maxAge}; Secure; HttpOnly; SameSite=Strict`;
|
|
446
|
+
}
|
|
447
|
+
async function authenticate(req, env, policy) {
|
|
236
448
|
const m = /^Bearer (kb_adm_\S+)$/.exec(req.headers.get("authorization") ?? "");
|
|
237
|
-
if (
|
|
238
|
-
|
|
449
|
+
if (m) {
|
|
450
|
+
if (!env.KEYBOX_ADMIN_TOKEN_HASH) return null;
|
|
451
|
+
return constEq(await sha256Hex(m[1]), env.KEYBOX_ADMIN_TOKEN_HASH) ? { via: "token" } : null;
|
|
452
|
+
}
|
|
453
|
+
if (req.headers.get("x-keybox-ui") !== "1") return null;
|
|
454
|
+
const cookie = sessionCookie(req);
|
|
455
|
+
if (cookie) {
|
|
456
|
+
const row = await env.DB.prepare("SELECT 1 FROM sessions WHERE hash = ? AND kind = 'ui' AND expires_at > ?").bind(await sha256Hex(cookie), Date.now()).first();
|
|
457
|
+
if (row) return { via: "session" };
|
|
458
|
+
}
|
|
459
|
+
const email = await verifyAccess(req.headers.get("cf-access-jwt-assertion"), policy.access);
|
|
460
|
+
return email ? { via: "access", email } : null;
|
|
239
461
|
}
|
|
240
462
|
async function admin(req, env, path) {
|
|
241
|
-
|
|
463
|
+
const policy = await loadPolicy(env);
|
|
464
|
+
const blocked = check(policy.admin, caller(req));
|
|
465
|
+
if (blocked) return keyboxError(403, "network_denied", `Admin access refused: ${blocked}.`);
|
|
466
|
+
const who = await authenticate(req, env, policy);
|
|
467
|
+
if (!who) return keyboxError(401, "unauthorized", "Admin token required.");
|
|
242
468
|
try {
|
|
243
|
-
return await route(req, env, path);
|
|
469
|
+
return await route(req, env, path, policy, who);
|
|
244
470
|
} catch (err) {
|
|
245
471
|
if (err instanceof Bad) return keyboxError(400, "bad_request", err.message);
|
|
246
472
|
throw err;
|
|
247
473
|
}
|
|
248
474
|
}
|
|
475
|
+
async function exchangeLogin(req, env) {
|
|
476
|
+
const policy = await loadPolicy(env);
|
|
477
|
+
const blocked = check(policy.admin, caller(req));
|
|
478
|
+
if (blocked) return keyboxError(403, "network_denied", `Admin access refused: ${blocked}.`);
|
|
479
|
+
if (req.headers.get("x-keybox-ui") !== "1") return keyboxError(400, "bad_request", "Missing x-keybox-ui header.");
|
|
480
|
+
let code = "";
|
|
481
|
+
try {
|
|
482
|
+
code = String((await req.json()).code ?? "");
|
|
483
|
+
} catch {
|
|
484
|
+
}
|
|
485
|
+
if (!/^kb_lnk_[A-Za-z0-9_-]{20,}$/.test(code)) return keyboxError(400, "bad_request", "Missing login code.");
|
|
486
|
+
const now = Date.now();
|
|
487
|
+
const used = await env.DB.prepare("DELETE FROM sessions WHERE hash = ? AND kind = 'login' AND expires_at > ? RETURNING hash").bind(await sha256Hex(code), now).first();
|
|
488
|
+
if (!used) return keyboxError(401, "unauthorized", "This login link has expired or was already used. Run `keybox ui` again.");
|
|
489
|
+
const session = randomToken("");
|
|
490
|
+
await env.DB.batch([
|
|
491
|
+
env.DB.prepare("DELETE FROM sessions WHERE expires_at < ?").bind(now),
|
|
492
|
+
env.DB.prepare("INSERT INTO sessions (hash, kind, expires_at, created_at) VALUES (?, 'ui', ?, ?)").bind(
|
|
493
|
+
await sha256Hex(session),
|
|
494
|
+
now + SESSION_TTL,
|
|
495
|
+
now
|
|
496
|
+
)
|
|
497
|
+
]);
|
|
498
|
+
return Response.json(
|
|
499
|
+
{ ok: true, expires_at: now + SESSION_TTL },
|
|
500
|
+
{ headers: { "set-cookie": setSessionCookie(session, SESSION_TTL / 1e3), "cache-control": "no-store" } }
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
async function logout(req, env) {
|
|
504
|
+
const cookie = sessionCookie(req);
|
|
505
|
+
if (cookie && req.headers.get("x-keybox-ui") === "1") {
|
|
506
|
+
await env.DB.prepare("DELETE FROM sessions WHERE hash = ?").bind(await sha256Hex(cookie)).run();
|
|
507
|
+
}
|
|
508
|
+
return Response.json({ ok: true }, { headers: { "set-cookie": setSessionCookie("", 0) } });
|
|
509
|
+
}
|
|
249
510
|
async function body(req) {
|
|
250
511
|
try {
|
|
251
512
|
const b = await req.json();
|
|
252
|
-
|
|
513
|
+
check2(b && typeof b === "object", "expected a JSON object");
|
|
253
514
|
return b;
|
|
254
515
|
} catch (err) {
|
|
255
516
|
if (err instanceof Bad) throw err;
|
|
256
517
|
throw new Bad("expected a JSON object");
|
|
257
518
|
}
|
|
258
519
|
}
|
|
259
|
-
async function route(req, env, path) {
|
|
520
|
+
async function route(req, env, path, policy, who) {
|
|
260
521
|
const seg = path.split("/").filter(Boolean);
|
|
261
522
|
const m = req.method;
|
|
262
523
|
const [a, b, c] = seg;
|
|
524
|
+
if (a === "whoami" && !b && m === "GET") {
|
|
525
|
+
return Response.json({ ...who, ...caller(req) });
|
|
526
|
+
}
|
|
527
|
+
if (a === "policy" && !b && m === "GET") return Response.json(policy);
|
|
528
|
+
if (a === "policy" && !b && m === "PUT") {
|
|
529
|
+
const raw = await body(req);
|
|
530
|
+
let next2;
|
|
531
|
+
try {
|
|
532
|
+
next2 = validPolicy(raw.policy);
|
|
533
|
+
} catch (err) {
|
|
534
|
+
throw new Bad(err.message);
|
|
535
|
+
}
|
|
536
|
+
const lockout = check(next2.admin, caller(req));
|
|
537
|
+
if (lockout && raw.force !== true) {
|
|
538
|
+
throw new Bad(`This admin rule would block you (${lockout}). Fix it, or send force: true if you mean it.`);
|
|
539
|
+
}
|
|
540
|
+
await env.DB.prepare(
|
|
541
|
+
`INSERT INTO settings (key, value, updated_at) VALUES ('policy', ?, ?)
|
|
542
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`
|
|
543
|
+
).bind(JSON.stringify(next2), Date.now()).run();
|
|
544
|
+
return Response.json(next2);
|
|
545
|
+
}
|
|
546
|
+
if (a === "ui" && b === "link" && m === "POST") {
|
|
547
|
+
if (who.via !== "token") throw new Bad("Login links are created with the admin token (`keybox ui`).");
|
|
548
|
+
const code = randomToken("kb_lnk_");
|
|
549
|
+
const now = Date.now();
|
|
550
|
+
await env.DB.prepare("INSERT INTO sessions (hash, kind, expires_at, created_at) VALUES (?, 'login', ?, ?)").bind(await sha256Hex(code), now + LOGIN_TTL, now).run();
|
|
551
|
+
return Response.json({ code, expires_at: now + LOGIN_TTL });
|
|
552
|
+
}
|
|
553
|
+
if (a === "sessions" && !b && m === "DELETE") {
|
|
554
|
+
const r = await env.DB.prepare("DELETE FROM sessions WHERE kind = 'ui'").run();
|
|
555
|
+
return Response.json({ revoked: r.meta.changes });
|
|
556
|
+
}
|
|
557
|
+
if (a === "stats" && !b && m === "GET") {
|
|
558
|
+
const since = Date.now() - 24 * 3600 * 1e3;
|
|
559
|
+
const { results } = await env.DB.prepare("SELECT decision, COUNT(*) AS n FROM audit WHERE ts > ? GROUP BY decision").bind(since).all();
|
|
560
|
+
return Response.json(Object.fromEntries(results.map((r) => [r.decision, r.n])));
|
|
561
|
+
}
|
|
263
562
|
if (a === "secrets" && !b && m === "GET") {
|
|
264
|
-
const { results } = await env.DB.prepare(
|
|
265
|
-
|
|
563
|
+
const { results } = await env.DB.prepare(
|
|
564
|
+
`SELECT s.*, (SELECT MAX(ts) FROM audit WHERE audit.secret = s.name AND decision = 'allow') AS last_used
|
|
565
|
+
FROM secrets s ORDER BY s.name`
|
|
566
|
+
).all();
|
|
567
|
+
const kek = await importKek(env.KEYBOX_KEK);
|
|
568
|
+
const out = [];
|
|
569
|
+
for (const r of results) {
|
|
570
|
+
const meta = { name: r.name, hosts: JSON.parse(r.hosts), header: r.header, format: r.format };
|
|
571
|
+
let fp = null;
|
|
572
|
+
if (kek && env.KEYBOX_KEK) {
|
|
573
|
+
try {
|
|
574
|
+
fp = await fingerprint(env.KEYBOX_KEK, await open(kek, meta, r.iv, r.ciphertext));
|
|
575
|
+
} catch {
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
out.push({ ...meta, created_at: r.created_at, last_used: r.last_used, fingerprint: fp });
|
|
579
|
+
}
|
|
580
|
+
return Response.json(out);
|
|
266
581
|
}
|
|
267
582
|
if (a === "secrets" && b && !c && m === "PUT") return putSecret(req, env, b);
|
|
268
583
|
if (a === "secrets" && b && !c && m === "DELETE") {
|
|
@@ -279,6 +594,10 @@ async function route(req, env, path) {
|
|
|
279
594
|
}
|
|
280
595
|
if (a === "agents" && b && !c && m === "PUT") return putAgent(req, env, b);
|
|
281
596
|
if (a === "agents" && b && !c && m === "DELETE") {
|
|
597
|
+
if (policy.agents?.[b]) {
|
|
598
|
+
delete policy.agents[b];
|
|
599
|
+
await env.DB.prepare("UPDATE settings SET value = ?, updated_at = ? WHERE key = 'policy'").bind(JSON.stringify(policy), Date.now()).run();
|
|
600
|
+
}
|
|
282
601
|
await env.DB.batch([
|
|
283
602
|
env.DB.prepare("DELETE FROM tokens WHERE agent = ?").bind(b),
|
|
284
603
|
env.DB.prepare("DELETE FROM agents WHERE name = ?").bind(b)
|
|
@@ -312,39 +631,40 @@ async function putSecret(req, env, name) {
|
|
|
312
631
|
const kek = await importKek(env.KEYBOX_KEK);
|
|
313
632
|
if (!kek) return keyboxError(503, "not_configured", "KEYBOX_KEK is not set.");
|
|
314
633
|
const b = await body(req);
|
|
315
|
-
|
|
316
|
-
|
|
634
|
+
check2(SECRET_NAME.test(name), "secret names are UPPER_SNAKE_CASE, up to 64 characters");
|
|
635
|
+
check2(Array.isArray(b.hosts) && b.hosts.length > 0 && b.hosts.length <= 16, "hosts must list 1-16 hostnames");
|
|
317
636
|
const hosts = [...new Set(b.hosts.map((h) => String(h).toLowerCase()))].sort();
|
|
318
|
-
for (const h of hosts)
|
|
319
|
-
|
|
637
|
+
for (const h of hosts) check2(isHostname(h), `not a public hostname: ${h}`);
|
|
638
|
+
check2(typeof b.header === "string" && HEADER.test(b.header), "header must be a plain header name");
|
|
320
639
|
const header = b.header.toLowerCase();
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
640
|
+
check2(!FORBIDDEN_HEADERS.has(header), `cannot inject into ${header}`);
|
|
641
|
+
check2(FORMATS.has(b.format), "format must be bearer, raw or basic");
|
|
642
|
+
check2(typeof b.value === "string", "value is required");
|
|
324
643
|
const value = b.value;
|
|
325
|
-
|
|
326
|
-
|
|
644
|
+
check2(value.length >= 8 && value.length <= 8192, "value must be 8-8192 characters");
|
|
645
|
+
check2(!/[\r\n\0]/.test(value), "value cannot contain line breaks");
|
|
327
646
|
const meta = { name, hosts, header, format: b.format };
|
|
328
647
|
const { iv, ciphertext } = await seal(kek, meta, value);
|
|
648
|
+
const fp = await fingerprint(env.KEYBOX_KEK, value);
|
|
329
649
|
await env.DB.prepare(
|
|
330
650
|
`INSERT INTO secrets (name, hosts, header, format, iv, ciphertext, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
331
651
|
ON CONFLICT(name) DO UPDATE SET hosts = excluded.hosts, header = excluded.header, format = excluded.format,
|
|
332
652
|
iv = excluded.iv, ciphertext = excluded.ciphertext`
|
|
333
653
|
).bind(name, JSON.stringify(hosts), header, meta.format, iv, ciphertext, Date.now()).run();
|
|
334
|
-
return Response.json({ name, hosts, header, format: meta.format });
|
|
654
|
+
return Response.json({ name, hosts, header, format: meta.format, fingerprint: fp });
|
|
335
655
|
}
|
|
336
656
|
async function putAgent(req, env, name) {
|
|
337
|
-
|
|
657
|
+
check2(AGENT_NAME.test(name), "agent names are lowercase letters, digits and dashes");
|
|
338
658
|
const b = await body(req);
|
|
339
|
-
|
|
659
|
+
check2(Array.isArray(b.grants) && b.grants.length > 0, "grants must be a non-empty list");
|
|
340
660
|
const { results } = await env.DB.prepare("SELECT name, hosts FROM secrets").all();
|
|
341
661
|
const hostsOf = new Map(results.map((r) => [r.name, JSON.parse(r.hosts)]));
|
|
342
662
|
const grants = [];
|
|
343
663
|
for (const g of b.grants) {
|
|
344
664
|
const secret = String(g?.secret ?? "");
|
|
345
665
|
const hosts = hostsOf.get(secret);
|
|
346
|
-
|
|
347
|
-
|
|
666
|
+
check2(hosts, `unknown secret: ${secret}`);
|
|
667
|
+
check2(Array.isArray(g.allow) && g.allow.length > 0, `grant for ${secret} needs at least one allow rule`);
|
|
348
668
|
const allow = g.allow.map(String);
|
|
349
669
|
const deny = Array.isArray(g.deny) ? g.deny.map(String) : [];
|
|
350
670
|
for (const r of [...allow, ...deny]) {
|
|
@@ -356,7 +676,7 @@ async function putAgent(req, env, name) {
|
|
|
356
676
|
}
|
|
357
677
|
for (const r of allow) {
|
|
358
678
|
const h = ruleHost(r);
|
|
359
|
-
|
|
679
|
+
check2(h && hosts.includes(h), `${secret} is bound to ${hosts.join(", ")}; rule "${r}" must name one of those hosts`);
|
|
360
680
|
}
|
|
361
681
|
grants.push(deny.length ? { secret, allow, deny } : { secret, allow });
|
|
362
682
|
}
|
|
@@ -369,9 +689,9 @@ async function putAgent(req, env, name) {
|
|
|
369
689
|
async function mintToken(req, env, agent) {
|
|
370
690
|
const b = await body(req);
|
|
371
691
|
const ttl = Number(b.ttl);
|
|
372
|
-
|
|
692
|
+
check2(Number.isInteger(ttl) && ttl >= 60 && ttl <= MAX_TTL, "ttl must be 60 seconds to 365 days");
|
|
373
693
|
const exists = await env.DB.prepare("SELECT 1 FROM agents WHERE name = ?").bind(agent).first();
|
|
374
|
-
|
|
694
|
+
check2(exists, `unknown agent: ${agent}`);
|
|
375
695
|
const token = randomToken("kb_agt_");
|
|
376
696
|
const id = crypto.randomUUID();
|
|
377
697
|
const now = Date.now();
|
|
@@ -465,8 +785,18 @@ var STRIP = /* @__PURE__ */ new Set([
|
|
|
465
785
|
"connection",
|
|
466
786
|
"keep-alive",
|
|
467
787
|
"te",
|
|
468
|
-
"upgrade"
|
|
788
|
+
"upgrade",
|
|
789
|
+
// The runtime negotiates compression itself; forwarding the agent's choice could hand us a body
|
|
790
|
+
// the scrubber cannot read.
|
|
791
|
+
"accept-encoding"
|
|
469
792
|
]);
|
|
793
|
+
var policyCache = null;
|
|
794
|
+
async function cachedPolicy(env) {
|
|
795
|
+
if (policyCache && Date.now() - policyCache.at < 5e3) return policyCache.policy;
|
|
796
|
+
const policy = await loadPolicy(env);
|
|
797
|
+
policyCache = { at: Date.now(), policy };
|
|
798
|
+
return policy;
|
|
799
|
+
}
|
|
470
800
|
function agentToken(h) {
|
|
471
801
|
const direct = h.get("x-keybox-token") ?? h.get("x-api-key");
|
|
472
802
|
if (direct?.startsWith("kb_agt_")) return direct;
|
|
@@ -515,6 +845,10 @@ async function proxy(req, env, ctx) {
|
|
|
515
845
|
if (!auth) return keyboxError(401, "invalid_token", "This agent token is unknown, expired or revoked.");
|
|
516
846
|
e.agent = auth.agent;
|
|
517
847
|
e.token_id = auth.id;
|
|
848
|
+
const policy = await cachedPolicy(env);
|
|
849
|
+
const who = caller(req);
|
|
850
|
+
const netBlocked = check(policy.proxy, who) ?? check(policy.agents?.[auth.agent], who);
|
|
851
|
+
if (netBlocked) return deny(403, "network_denied", `Keybox refused this call: ${netBlocked}.`);
|
|
518
852
|
const target = /^\/([^/]+)(\/.*)?$/.exec(url.pathname);
|
|
519
853
|
const host = target?.[1].toLowerCase() ?? "";
|
|
520
854
|
if (!isHostname(host)) return deny(400, "bad_host", "Call Keybox as https://<keybox>/<api host>/<path>.");
|
|
@@ -532,11 +866,16 @@ async function proxy(req, env, ctx) {
|
|
|
532
866
|
const names = [...new Set(grants.map((g) => g.secret))];
|
|
533
867
|
const rows = names.length ? (await env.DB.prepare(`SELECT * FROM secrets WHERE name IN (${names.map(() => "?").join(",")})`).bind(...names).all()).results : [];
|
|
534
868
|
const bound = new Map(rows.filter((r) => JSON.parse(r.hosts).includes(host)).map((r) => [r.name, r]));
|
|
869
|
+
const bare = path.replace(/;[^/]*/g, "");
|
|
535
870
|
const candidates = /* @__PURE__ */ new Set();
|
|
536
871
|
for (const g of grants) {
|
|
537
872
|
if (!bound.has(g.secret)) continue;
|
|
538
873
|
const hit = (src) => matches(parseRule(src), method, host, path);
|
|
539
|
-
|
|
874
|
+
const blocks = (src) => {
|
|
875
|
+
const r = parseRule(src, { caseInsensitive: true });
|
|
876
|
+
return matches(r, method, host, path) || matches(r, method, host, bare);
|
|
877
|
+
};
|
|
878
|
+
if (g.deny?.some(blocks)) continue;
|
|
540
879
|
if (g.allow.some(hit)) candidates.add(g.secret);
|
|
541
880
|
}
|
|
542
881
|
if (candidates.size === 0) {
|
|
@@ -583,9 +922,11 @@ async function proxy(req, env, ctx) {
|
|
|
583
922
|
const plain = raw.map((n) => new TextDecoder().decode(n));
|
|
584
923
|
const out = new Headers();
|
|
585
924
|
for (const [k, v] of upstream.headers) {
|
|
586
|
-
if (k === "content-length") continue;
|
|
925
|
+
if (k === "content-length" || k === "set-cookie") continue;
|
|
587
926
|
out.append(k, scrubString(v, plain));
|
|
588
927
|
}
|
|
928
|
+
out.set("content-security-policy", "sandbox; default-src 'none'");
|
|
929
|
+
out.set("x-content-type-options", "nosniff");
|
|
589
930
|
e.decision = "allow";
|
|
590
931
|
e.status = upstream.status;
|
|
591
932
|
audit(env, ctx, e);
|
|
@@ -596,6 +937,61 @@ async function proxy(req, env, ctx) {
|
|
|
596
937
|
});
|
|
597
938
|
}
|
|
598
939
|
|
|
940
|
+
// src/ui/app.css
|
|
941
|
+
var app_default = ":root {\n --paper: #efe4d3;\n --paper-hi: #f5ede0;\n --veil: rgb(245 237 224 / 0.6);\n --ink: #2b2824;\n --ink-strong: #000;\n --ink-soft: #4a4640;\n --ink-mute: #8a8176;\n --accent: #2f4fc4;\n --on-accent: #f5ede0;\n --line: rgb(43 39 35 / 0.11);\n --rule: rgb(43 39 35 / 0.16);\n --wash: rgb(43 39 35 / 0.045);\n --danger: #b4412f;\n --ok: #2f7a4a;\n --sans: 'Inter Variable', Inter, system-ui, sans-serif;\n --mono: 'JetBrains Mono Variable', 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;\n color-scheme: light;\n}\n@media (prefers-color-scheme: dark) {\n :root:not([data-theme='light']) {\n --paper: #15130f; --paper-hi: #1d1a16; --veil: rgb(33 30 25 / 0.6); --ink: #ece4d6; --ink-strong: #fff;\n --ink-soft: #c2b8a8; --ink-mute: #8d8476; --accent: #7d97ff; --on-accent: #15130f; --line: rgb(236 228 214 / 0.1);\n --rule: rgb(236 228 214 / 0.15); --wash: rgb(236 228 214 / 0.05); --danger: #ee7a64; --ok: #6fc28d; color-scheme: dark;\n }\n}\n:root[data-theme='dark'] {\n --paper: #15130f; --paper-hi: #1d1a16; --veil: rgb(33 30 25 / 0.6); --ink: #ece4d6; --ink-strong: #fff;\n --ink-soft: #c2b8a8; --ink-mute: #8d8476; --accent: #7d97ff; --on-accent: #15130f; --line: rgb(236 228 214 / 0.1);\n --rule: rgb(236 228 214 / 0.15); --wash: rgb(236 228 214 / 0.05); --danger: #ee7a64; --ok: #6fc28d; color-scheme: dark;\n}\n*, *::before, *::after { box-sizing: border-box; }\nhtml, body { margin: 0; background: var(--paper); color: var(--ink); font: 15px/1.5 var(--sans); -webkit-font-smoothing: antialiased; }\nbody {\n min-height: 100svh;\n background-image:\n linear-gradient(90deg, var(--line) 1px, transparent 1px),\n linear-gradient(180deg, var(--line) 1px, transparent 1px);\n background-size: 128px 128px;\n background-position: -1px -1px;\n}\nbody::before { content: ''; position: fixed; inset: 0; z-index: -1; background: var(--paper); opacity: 0.86; }\n::selection { background: var(--accent); color: var(--on-accent); }\n:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }\na { color: inherit; }\n.mono { font-family: var(--mono); }\n.dim { color: var(--ink-mute); }\n.boot { display: grid; place-items: center; min-height: 100svh; }\n\n.shell { max-width: 1180px; margin: 0 auto; padding: 20px 20px 80px; }\n.top {\n position: sticky; top: 12px; z-index: 10; display: flex; align-items: center; gap: 24px;\n padding: 10px 12px 10px 18px; border: 1px solid var(--line); border-radius: 4px;\n background: color-mix(in srgb, var(--paper) 80%, transparent); backdrop-filter: blur(10px);\n}\n.mark { display: inline-flex; align-items: center; gap: 10px; font: 600 15px var(--mono); letter-spacing: -0.02em; text-decoration: none; }\n.mark i { width: 12px; height: 12px; background: var(--accent); display: inline-block; }\n.tabs { display: flex; gap: 4px; flex: 1; overflow-x: auto; scrollbar-width: none; }\n.tabs button { border: 0; background: none; color: var(--ink-soft); font: 14px var(--sans); padding: 8px 12px; border-radius: 3px; cursor: pointer; white-space: nowrap; }\n.tabs button[aria-current='page'] { color: var(--ink); background: var(--wash); box-shadow: inset 0 -2px 0 var(--accent); }\n.top-end { display: flex; align-items: center; gap: 6px; }\n.icon { display: grid; place-items: center; width: 36px; height: 36px; border: 0; background: none; color: var(--ink-soft); cursor: pointer; border-radius: 3px; }\n.icon:hover { color: var(--ink); background: var(--wash); }\n\nh1 { font-size: clamp(32px, 4vw, 52px); font-weight: 560; letter-spacing: -0.04em; line-height: 1.04; margin: 48px 0 8px; }\nh1 .muted, h2 .muted { color: var(--ink-mute); }\nh2 { font-size: 22px; font-weight: 560; letter-spacing: -0.025em; margin: 0; }\nh3 { font-size: 16px; font-weight: 600; margin: 0; }\n.lede { color: var(--ink-soft); max-width: 62ch; margin: 0 0 32px; }\n.eyebrow { font: 12px var(--mono); letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-mute); margin: 0 0 10px; }\n\n.grid { display: grid; gap: 16px; }\n.stats { grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); margin-bottom: 24px; }\n.card { border: 1px solid var(--rule); background: var(--veil); padding: 20px; }\n.card.accent { box-shadow: inset 0 3px 0 var(--accent); }\n.stat b { display: block; font: 560 34px/1.1 var(--sans); letter-spacing: -0.03em; }\n.stat span { font: 12px var(--mono); color: var(--ink-mute); text-transform: uppercase; letter-spacing: 0.08em; }\n.row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }\n.spread { justify-content: space-between; }\n.stack { display: grid; gap: 14px; }\n\n.btn {\n display: inline-flex; align-items: center; justify-content: center; gap: 8px; height: 40px; padding: 0 16px;\n border: 1.25px solid var(--ink); border-radius: 3px; background: none; color: var(--ink);\n font: 500 14px var(--sans); cursor: pointer; white-space: nowrap; text-decoration: none;\n}\n.btn:hover { background: var(--ink); color: var(--paper); }\n.btn.primary { background: var(--ink); color: var(--paper); }\n.btn.primary:hover { background: var(--ink-strong); }\n.btn.ghost { border-color: var(--rule); }\n.btn.danger { border-color: var(--danger); color: var(--danger); }\n.btn.danger:hover { background: var(--danger); color: var(--paper); }\n.btn.sm { height: 32px; padding: 0 11px; font-size: 13px; }\n.btn:disabled { opacity: 0.5; cursor: progress; }\n\n.field { display: grid; gap: 6px; }\n.field > span { font: 11.5px var(--mono); letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-mute); }\n.field small { color: var(--ink-mute); font-size: 13px; }\ninput, select, textarea {\n width: 100%; min-height: 42px; padding: 9px 12px; border: 1.25px solid var(--rule); border-radius: 3px;\n background: var(--paper-hi); color: var(--ink); font: 15px var(--sans);\n}\ntextarea, input.mono { font: 14px/1.6 var(--mono); }\ntextarea { min-height: 120px; resize: vertical; }\ninput:focus, select:focus, textarea:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 18%, transparent); }\n.cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 14px; }\nlabel.check { display: flex; gap: 8px; align-items: center; font-size: 14px; color: var(--ink-soft); }\nlabel.check input { width: auto; min-height: 0; }\n\n.keyfield { position: relative; }\n.keyfield input { padding-right: 44px; letter-spacing: 0.18em; font-family: var(--mono); }\n.keyfield .meter { position: absolute; right: 12px; top: 50%; translate: 0 -50%; font: 11px var(--mono); color: var(--ink-mute); letter-spacing: 0; }\n.chip { display: inline-flex; align-items: center; gap: 6px; padding: 3px 9px; border: 1px solid var(--rule); border-radius: 99px; font: 12px var(--mono); color: var(--ink-soft); }\n.chip.ok { border-color: color-mix(in srgb, var(--ok) 50%, transparent); color: var(--ok); }\n.chip.warn { border-color: color-mix(in srgb, var(--danger) 50%, transparent); color: var(--danger); }\n.chip.accent { border-color: color-mix(in srgb, var(--accent) 50%, transparent); color: var(--accent); }\n\n.table { width: 100%; border-collapse: collapse; font-size: 14px; }\n.table th { text-align: left; font: 11.5px var(--mono); letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-mute); font-weight: 400; padding: 10px 12px; border-bottom: 1px solid var(--rule); }\n.table td { padding: 12px; border-bottom: 1px solid var(--line); vertical-align: top; }\n.table tr:last-child td { border-bottom: 0; }\n.table .mono { font-size: 13px; overflow-wrap: anywhere; }\n.scroll { overflow-x: auto; border: 1px solid var(--rule); background: var(--veil); }\n.ok-t { color: var(--ok); } .bad-t { color: var(--danger); }\n\n.rules { margin: 0; padding: 0; list-style: none; font: 13px/1.9 var(--mono); }\n.rules .k { display: inline-block; width: 52px; color: var(--ink-mute); }\n.rules .deny .k { color: var(--danger); }\n.agent { display: grid; gap: 14px; }\n\n.notice { padding: 12px 14px; border-left: 3px solid var(--accent); background: var(--wash); font-size: 14px; }\n.notice.warn { border-color: var(--danger); }\n.secret-once { display: flex; gap: 8px; align-items: center; padding: 12px; border: 1px dashed var(--accent); font: 13px var(--mono); overflow-wrap: anywhere; }\n.toast { position: fixed; left: 50%; bottom: 24px; translate: -50% 0; padding: 10px 16px; background: var(--ink); color: var(--paper); border-radius: 3px; font-size: 14px; z-index: 50; max-width: calc(100vw - 32px); }\n.toast.err { background: var(--danger); }\ndialog { border: 1px solid var(--rule); background: var(--paper-hi); color: var(--ink); padding: 24px; width: min(560px, calc(100vw - 32px)); border-radius: 4px; }\ndialog::backdrop { background: rgb(0 0 0 / 0.35); backdrop-filter: blur(2px); }\n\n.login { max-width: 560px; margin: 14vh auto 0; padding: 0 20px; }\n.login pre { padding: 14px 16px; background: var(--wash); border: 1px solid var(--line); font: 14px var(--mono); }\n\n@media (max-width: 760px) {\n .shell { padding: 12px 12px 64px; }\n .top { flex-wrap: wrap; gap: 8px; padding: 8px 8px 8px 14px; top: 8px; }\n .tabs { order: 3; flex-basis: 100%; }\n .top-end { margin-left: auto; }\n h1 { margin-top: 32px; }\n .table.cards thead { display: none; }\n .table.cards tr { display: grid; gap: 4px; padding: 12px; border-bottom: 1px solid var(--line); }\n .table.cards td { padding: 0; border: 0; }\n .table.cards td[data-l]::before { content: attr(data-l) ' '; font: 11px var(--mono); color: var(--ink-mute); text-transform: uppercase; }\n}\n";
|
|
942
|
+
|
|
943
|
+
// src/ui/index.html
|
|
944
|
+
var ui_default = `<!doctype html>
|
|
945
|
+
<html lang="en">
|
|
946
|
+
<head>
|
|
947
|
+
<meta charset="utf-8" />
|
|
948
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
949
|
+
<meta name="robots" content="noindex" />
|
|
950
|
+
<meta name="color-scheme" content="light dark" />
|
|
951
|
+
<title>Keybox</title>
|
|
952
|
+
<link rel="stylesheet" href="/_keybox/ui/app.css" />
|
|
953
|
+
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect x='2' y='2' width='12' height='12' fill='%232f4fc4'/%3E%3C/svg%3E" />
|
|
954
|
+
<script src="/_keybox/ui/app.js" defer></script>
|
|
955
|
+
</head>
|
|
956
|
+
<body>
|
|
957
|
+
<div id="app" class="boot"><p class="mono dim">keybox \xB7 loading</p></div>
|
|
958
|
+
</body>
|
|
959
|
+
</html>
|
|
960
|
+
`;
|
|
961
|
+
|
|
962
|
+
// 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';
|
|
964
|
+
|
|
965
|
+
// src/ui.ts
|
|
966
|
+
var CSP = [
|
|
967
|
+
"default-src 'none'",
|
|
968
|
+
"script-src 'self'",
|
|
969
|
+
"style-src 'self'",
|
|
970
|
+
"img-src 'self' data:",
|
|
971
|
+
"connect-src 'self'",
|
|
972
|
+
"base-uri 'none'",
|
|
973
|
+
"form-action 'none'",
|
|
974
|
+
"frame-ancestors 'none'"
|
|
975
|
+
].join("; ");
|
|
976
|
+
var common = {
|
|
977
|
+
"content-security-policy": CSP,
|
|
978
|
+
"x-content-type-options": "nosniff",
|
|
979
|
+
"x-frame-options": "DENY",
|
|
980
|
+
"referrer-policy": "no-referrer",
|
|
981
|
+
"cross-origin-opener-policy": "same-origin",
|
|
982
|
+
"cache-control": "no-store",
|
|
983
|
+
"x-robots-tag": "noindex"
|
|
984
|
+
};
|
|
985
|
+
var UI_FILES = {
|
|
986
|
+
"/_keybox/ui": { body: ui_default, type: "text/html; charset=utf-8" },
|
|
987
|
+
"/_keybox/ui/app.js": { body: ui_bundle_default, type: "text/javascript; charset=utf-8" },
|
|
988
|
+
"/_keybox/ui/app.css": { body: app_default, type: "text/css; charset=utf-8" }
|
|
989
|
+
};
|
|
990
|
+
function uiResponse(path) {
|
|
991
|
+
const f = UI_FILES[path === "/_keybox/ui/" ? "/_keybox/ui" : path];
|
|
992
|
+
return f ? new Response(f.body, { headers: { ...common, "content-type": f.type } }) : null;
|
|
993
|
+
}
|
|
994
|
+
|
|
599
995
|
// src/index.ts
|
|
600
996
|
var index_default = {
|
|
601
997
|
async fetch(req, env, ctx) {
|
|
@@ -607,8 +1003,22 @@ var index_default = {
|
|
|
607
1003
|
if (pathname.startsWith("/_keybox/admin/")) {
|
|
608
1004
|
return admin(req, env, pathname.slice("/_keybox/admin".length));
|
|
609
1005
|
}
|
|
610
|
-
if (
|
|
611
|
-
|
|
1006
|
+
if (req.method === "GET" && (pathname === "/_keybox/ui" || pathname.startsWith("/_keybox/ui/"))) {
|
|
1007
|
+
const page = uiResponse(pathname);
|
|
1008
|
+
if (page) {
|
|
1009
|
+
const blocked = check((await loadPolicy(env)).admin, caller(req));
|
|
1010
|
+
if (blocked) return keyboxError(403, "network_denied", `Admin access refused: ${blocked}.`);
|
|
1011
|
+
return page;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
if (pathname === "/_keybox/ui/session" && req.method === "POST") return exchangeLogin(req, env);
|
|
1015
|
+
if (pathname === "/_keybox/ui/logout" && req.method === "POST") return logout(req, env);
|
|
1016
|
+
if (pathname.startsWith("/_keybox/")) return keyboxError(404, "not_found", "Unknown Keybox path.");
|
|
1017
|
+
if (pathname === "/" || pathname === "/favicon.ico" || pathname === "/robots.txt") {
|
|
1018
|
+
return new Response(pathname === "/robots.txt" ? "User-agent: *\nDisallow: /\n" : "Not found\n", {
|
|
1019
|
+
status: pathname === "/robots.txt" ? 200 : 404,
|
|
1020
|
+
headers: { "content-type": "text/plain", "x-robots-tag": "noindex" }
|
|
1021
|
+
});
|
|
612
1022
|
}
|
|
613
1023
|
return proxy(req, env, ctx);
|
|
614
1024
|
}
|