@keyboxed/cli 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,618 @@
1
+ // src/crypto.ts
2
+ var enc = new TextEncoder();
3
+ var dec = new TextDecoder();
4
+ function b64(bytes) {
5
+ let s = "";
6
+ for (const b of bytes) s += String.fromCharCode(b);
7
+ return btoa(s);
8
+ }
9
+ function unb64(s) {
10
+ const bin = atob(s);
11
+ const out = new Uint8Array(bin.length);
12
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
13
+ return out;
14
+ }
15
+ function b64url(bytes) {
16
+ return b64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
17
+ }
18
+ function randomToken(prefix) {
19
+ return prefix + b64url(crypto.getRandomValues(new Uint8Array(32)));
20
+ }
21
+ async function sha256Hex(s) {
22
+ const d = new Uint8Array(await crypto.subtle.digest("SHA-256", enc.encode(s)));
23
+ return Array.from(d, (b) => b.toString(16).padStart(2, "0")).join("");
24
+ }
25
+ function constEq(a, b) {
26
+ if (a.length !== b.length) return false;
27
+ let diff = 0;
28
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
29
+ return diff === 0;
30
+ }
31
+ async function importKek(raw) {
32
+ if (!raw) return null;
33
+ const bytes = unb64(raw.trim());
34
+ if (bytes.length !== 32) return null;
35
+ return crypto.subtle.importKey("raw", bytes, "AES-GCM", false, ["encrypt", "decrypt"]);
36
+ }
37
+ function aad(m) {
38
+ return enc.encode(`keybox/v1
39
+ ${m.name}
40
+ ${[...m.hosts].sort().join(",")}
41
+ ${m.header.toLowerCase()}
42
+ ${m.format}`);
43
+ }
44
+ async function seal(kek, meta, value) {
45
+ const iv = crypto.getRandomValues(new Uint8Array(12));
46
+ const ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: aad(meta) }, kek, enc.encode(value));
47
+ return { iv: b64(iv), ciphertext: b64(new Uint8Array(ct)) };
48
+ }
49
+ async function open(kek, meta, iv, ciphertext) {
50
+ const pt = await crypto.subtle.decrypt(
51
+ { name: "AES-GCM", iv: unb64(iv), additionalData: aad(meta) },
52
+ kek,
53
+ unb64(ciphertext)
54
+ );
55
+ return dec.decode(pt);
56
+ }
57
+ function headerValue(format, value) {
58
+ if (format === "bearer") return `Bearer ${value}`;
59
+ if (format === "basic") return `Basic ${b64(enc.encode(value))}`;
60
+ return value;
61
+ }
62
+ function needles(format, value) {
63
+ const out = [enc.encode(value)];
64
+ if (format === "basic") out.push(enc.encode(b64(enc.encode(value))));
65
+ return out;
66
+ }
67
+
68
+ // src/policy.ts
69
+ var RULE = /^([A-Za-z*]+(?:,[A-Za-z]+)*)\s+([a-z0-9*.-]+)(\/\S*)?$/;
70
+ function parseRule(source, opts = {}) {
71
+ const m = RULE.exec(source.trim());
72
+ if (!m) throw new Error(`bad rule: ${source}`);
73
+ const [, method, host, path = "/**"] = m;
74
+ const methods = method === "*" ? null : new Set(method.toUpperCase().split(","));
75
+ return {
76
+ source,
77
+ methods,
78
+ host: host === "*" ? /^.+$/ : new RegExp(`^${host.split("*").map(escape).join("[a-z0-9-]+")}$`),
79
+ path: globToRegExp(path, opts.caseInsensitive)
80
+ };
81
+ }
82
+ function ruleHost(source) {
83
+ const m = RULE.exec(source.trim());
84
+ return m && !m[2].includes("*") ? m[2] : null;
85
+ }
86
+ function matches(rule, method, host, path) {
87
+ return (!rule.methods || rule.methods.has(method)) && rule.host.test(host) && rule.path.test(path);
88
+ }
89
+ function globToRegExp(glob, caseInsensitive = false) {
90
+ let re = "";
91
+ for (let i = 0; i < glob.length; ) {
92
+ if (glob.startsWith("/**/", i)) {
93
+ re += "(?:/|/.*/)";
94
+ i += 4;
95
+ } else if (glob.startsWith("/**", i) && i + 3 === glob.length) {
96
+ re += "(?:/.*)?";
97
+ i += 3;
98
+ } else if (glob.startsWith("**", i)) {
99
+ re += ".*";
100
+ i += 2;
101
+ } else if (glob[i] === "*") {
102
+ re += "[^/]*";
103
+ i += 1;
104
+ } else {
105
+ re += escape(glob[i]);
106
+ i += 1;
107
+ }
108
+ }
109
+ return new RegExp(`^${re}$`, caseInsensitive ? "i" : "");
110
+ }
111
+ function escape(s) {
112
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
113
+ }
114
+ function canonicalPath(raw) {
115
+ if (/\\|%2f|%5c|%00/i.test(raw)) throw new Error("ambiguous path");
116
+ let p = raw.replace(/%([0-9a-f]{2})/gi, (m, h) => {
117
+ const c = String.fromCharCode(parseInt(h, 16));
118
+ return /[A-Za-z0-9\-._~]/.test(c) ? c : m.toUpperCase();
119
+ });
120
+ p = p.replace(/\/{2,}/g, "/");
121
+ p = new URL(p, "https://keybox.invalid").pathname;
122
+ return p.replace(/\/{2,}/g, "/");
123
+ }
124
+ var HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
125
+ function isHostname(h) {
126
+ return HOSTNAME.test(h);
127
+ }
128
+
129
+ // src/denylist.ts
130
+ var W = "POST,PUT,PATCH,DELETE";
131
+ var BUILTIN = [
132
+ // Generic credential minting on any host.
133
+ [`${W} */**/api_keys/**`, "creates or edits API keys"],
134
+ [`${W} */**/api-keys/**`, "creates or edits API keys"],
135
+ [`${W} */**/apikeys/**`, "creates or edits API keys"],
136
+ [`${W} */**/access_tokens/**`, "mints access tokens"],
137
+ [`${W} */**/access-tokens/**`, "mints access tokens"],
138
+ [`${W} */**/personal_access_tokens/**`, "mints access tokens"],
139
+ // OpenAI
140
+ ["* api.openai.com/v1/organization/admin_api_keys/**", "OpenAI admin keys"],
141
+ ["* api.openai.com/v1/organization/projects/*/api_keys/**", "OpenAI project keys"],
142
+ [`${W} api.openai.com/v1/organization/projects/*/service_accounts/**`, "service accounts return a new key"],
143
+ [`${W} api.openai.com/v1/organization/invites/**`, "invites a user to the organisation"],
144
+ [`${W} api.openai.com/v1/organization/users/**`, "changes organisation membership"],
145
+ [`${W} api.openai.com/v1/organization/projects/*/users/**`, "changes project membership"],
146
+ ["POST api.openai.com/v1/realtime/client_secrets", "mints a client secret"],
147
+ ["POST api.openai.com/v1/realtime/sessions", "mints a client secret"],
148
+ ["POST api.openai.com/v1/realtime/transcription_sessions", "mints a client secret"],
149
+ // Anthropic
150
+ ["* api.anthropic.com/v1/organizations/api_keys/**", "Anthropic API keys"],
151
+ [`${W} api.anthropic.com/v1/organizations/invites/**`, "invites a user to the organisation"],
152
+ [`${W} api.anthropic.com/v1/organizations/users/**`, "changes organisation membership"],
153
+ [`${W} api.anthropic.com/v1/organizations/workspaces/*/members/**`, "changes workspace membership"],
154
+ // GitHub
155
+ [`${W} api.github.com/user/keys/**`, "adds an SSH key to the account"],
156
+ [`${W} api.github.com/user/gpg_keys/**`, "adds a signing key to the account"],
157
+ [`${W} api.github.com/user/ssh_signing_keys/**`, "adds a signing key to the account"],
158
+ [`${W} api.github.com/repos/*/*/keys/**`, "adds a deploy key"],
159
+ [`${W} api.github.com/repos/*/*/collaborators/**`, "grants repository access"],
160
+ [`${W} api.github.com/repos/*/*/invitations/**`, "grants repository access"],
161
+ [`${W} api.github.com/orgs/*/invitations/**`, "invites an organisation member"],
162
+ [`${W} api.github.com/orgs/*/memberships/**`, "changes organisation membership"],
163
+ [`${W} api.github.com/orgs/*/members/**`, "changes organisation membership"],
164
+ [`${W} api.github.com/orgs/*/outside_collaborators/**`, "grants organisation access"],
165
+ [`${W} api.github.com/teams/*/memberships/**`, "changes team membership"],
166
+ [`${W} api.github.com/orgs/*/teams/*/memberships/**`, "changes team membership"],
167
+ [`${W} api.github.com/repos/*/*/actions/secrets/**`, "writes Actions secrets"],
168
+ [`${W} api.github.com/orgs/*/actions/secrets/**`, "writes Actions secrets"],
169
+ [`${W} api.github.com/app/installations/*/access_tokens`, "mints an installation token"],
170
+ ["* api.github.com/applications/**", "OAuth app token management"],
171
+ ["* api.github.com/authorizations/**", "OAuth authorisations"],
172
+ // Stripe
173
+ ["POST api.stripe.com/v1/ephemeral_keys", "mints an ephemeral key"],
174
+ ["* api.stripe.com/v1/apps/secrets/**", "reads or writes the Stripe secret store"],
175
+ ["POST api.stripe.com/v1/account_links", "creates an account access link"],
176
+ ["POST api.stripe.com/v1/accounts/*/login_links", "creates a dashboard login link"],
177
+ // Cloudflare
178
+ ["* api.cloudflare.com/client/v4/user/tokens/**", "Cloudflare API tokens"],
179
+ ["* api.cloudflare.com/client/v4/accounts/*/tokens/**", "Cloudflare API tokens"],
180
+ [`${W} api.cloudflare.com/client/v4/accounts/*/members/**`, "changes account membership"],
181
+ ["* api.cloudflare.com/client/v4/accounts/*/access/service_tokens/**", "Access service tokens"]
182
+ ];
183
+ var compiled = BUILTIN.map(([src, reason]) => ({ rule: parseRule(src, { caseInsensitive: true }), reason }));
184
+ function denyRules(self) {
185
+ const own = [];
186
+ const cf = "api.cloudflare.com/client/v4/accounts/*";
187
+ if (self.KEYBOX_SCRIPT_NAME) {
188
+ const n = self.KEYBOX_SCRIPT_NAME;
189
+ for (const p of [`workers/scripts/${n}/**`, `workers/services/${n}/**`, `workers/workers/${n}/**`]) {
190
+ own.push({ rule: parseRule(`* ${cf}/${p}`, { caseInsensitive: true }), reason: "modifies this Keybox deployment" });
191
+ }
192
+ }
193
+ if (self.KEYBOX_D1_ID) {
194
+ own.push({
195
+ rule: parseRule(`* ${cf}/d1/database/${self.KEYBOX_D1_ID}/**`, { caseInsensitive: true }),
196
+ reason: "touches the Keybox database"
197
+ });
198
+ }
199
+ return [...compiled, ...own];
200
+ }
201
+ function denied(rules, method, host, path) {
202
+ const bare = path.replace(/;[^/]*/g, "");
203
+ for (const d of rules) {
204
+ if (matches(d.rule, method, host, path) || matches(d.rule, method, host, bare)) return d;
205
+ }
206
+ return null;
207
+ }
208
+
209
+ // src/types.ts
210
+ var VERSION = "0.1.0";
211
+ function keyboxError(status, code, message) {
212
+ return Response.json({ type: "error", error: { type: "keybox_error", code, message } }, { status });
213
+ }
214
+ function audit(env, ctx, e) {
215
+ ctx.waitUntil(
216
+ env.DB.prepare(
217
+ "INSERT INTO audit (ts, agent, token_id, method, host, path, secret, decision, reason, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
218
+ ).bind(Date.now(), e.agent, e.token_id, e.method, e.host, e.path, e.secret, e.decision, e.reason, e.status).run().catch(() => {
219
+ })
220
+ );
221
+ }
222
+
223
+ // src/admin.ts
224
+ var SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
225
+ var AGENT_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
226
+ var HEADER = /^[A-Za-z0-9-]{1,64}$/;
227
+ var FORBIDDEN_HEADERS = /* @__PURE__ */ new Set(["host", "content-length", "transfer-encoding", "connection", "cookie", "x-keybox-token"]);
228
+ var FORMATS = /* @__PURE__ */ new Set(["bearer", "raw", "basic"]);
229
+ var MAX_TTL = 365 * 24 * 3600;
230
+ var Bad = class extends Error {
231
+ };
232
+ function check(ok, msg) {
233
+ if (!ok) throw new Bad(msg);
234
+ }
235
+ async function isAdmin(req, env) {
236
+ const m = /^Bearer (kb_adm_\S+)$/.exec(req.headers.get("authorization") ?? "");
237
+ if (!m || !env.KEYBOX_ADMIN_TOKEN_HASH) return false;
238
+ return constEq(await sha256Hex(m[1]), env.KEYBOX_ADMIN_TOKEN_HASH);
239
+ }
240
+ async function admin(req, env, path) {
241
+ if (!await isAdmin(req, env)) return keyboxError(401, "unauthorized", "Admin token required.");
242
+ try {
243
+ return await route(req, env, path);
244
+ } catch (err) {
245
+ if (err instanceof Bad) return keyboxError(400, "bad_request", err.message);
246
+ throw err;
247
+ }
248
+ }
249
+ async function body(req) {
250
+ try {
251
+ const b = await req.json();
252
+ check(b && typeof b === "object", "expected a JSON object");
253
+ return b;
254
+ } catch (err) {
255
+ if (err instanceof Bad) throw err;
256
+ throw new Bad("expected a JSON object");
257
+ }
258
+ }
259
+ async function route(req, env, path) {
260
+ const seg = path.split("/").filter(Boolean);
261
+ const m = req.method;
262
+ const [a, b, c] = seg;
263
+ if (a === "secrets" && !b && m === "GET") {
264
+ const { results } = await env.DB.prepare("SELECT name, hosts, header, format, created_at FROM secrets ORDER BY name").all();
265
+ return Response.json(results.map((r) => ({ ...r, hosts: JSON.parse(r.hosts) })));
266
+ }
267
+ if (a === "secrets" && b && !c && m === "PUT") return putSecret(req, env, b);
268
+ if (a === "secrets" && b && !c && m === "DELETE") {
269
+ const r = await env.DB.prepare("DELETE FROM secrets WHERE name = ?").bind(b).run();
270
+ return Response.json({ deleted: r.meta.changes > 0 });
271
+ }
272
+ if (a === "agents" && !b && m === "GET") {
273
+ const { results } = await env.DB.prepare(
274
+ `SELECT a.name, a.grants, a.created_at,
275
+ (SELECT COUNT(*) FROM tokens t WHERE t.agent = a.name AND t.revoked_at IS NULL AND t.expires_at > ?) AS active_tokens
276
+ FROM agents a ORDER BY a.name`
277
+ ).bind(Date.now()).all();
278
+ return Response.json(results.map((r) => ({ ...r, grants: JSON.parse(r.grants) })));
279
+ }
280
+ if (a === "agents" && b && !c && m === "PUT") return putAgent(req, env, b);
281
+ if (a === "agents" && b && !c && m === "DELETE") {
282
+ await env.DB.batch([
283
+ env.DB.prepare("DELETE FROM tokens WHERE agent = ?").bind(b),
284
+ env.DB.prepare("DELETE FROM agents WHERE name = ?").bind(b)
285
+ ]);
286
+ return Response.json({ deleted: true });
287
+ }
288
+ if (a === "agents" && b && c === "tokens" && m === "POST") return mintToken(req, env, b);
289
+ if (a === "agents" && b && c === "tokens" && m === "GET") {
290
+ const { results } = await env.DB.prepare(
291
+ "SELECT id, created_at, expires_at, revoked_at FROM tokens WHERE agent = ? ORDER BY created_at DESC"
292
+ ).bind(b).all();
293
+ return Response.json(results);
294
+ }
295
+ if (a === "tokens" && b && !c && m === "DELETE") {
296
+ const r = await env.DB.prepare("UPDATE tokens SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL").bind(Date.now(), b).run();
297
+ return Response.json({ revoked: r.meta.changes > 0 });
298
+ }
299
+ if (a === "audit" && !b && m === "GET") {
300
+ const q = new URL(req.url).searchParams;
301
+ const after = Number(q.get("after") ?? 0);
302
+ const limit = Math.min(Math.max(Number(q.get("limit") ?? 100), 1), 500);
303
+ const stmt = after > 0 ? env.DB.prepare("SELECT * FROM audit WHERE id > ? ORDER BY id ASC LIMIT ?").bind(after, limit) : env.DB.prepare("SELECT * FROM (SELECT * FROM audit ORDER BY id DESC LIMIT ?) ORDER BY id ASC").bind(limit);
304
+ return Response.json((await stmt.all()).results);
305
+ }
306
+ if (a === "blocked" && !b && m === "GET") {
307
+ return Response.json(denyRules(env).map((d) => ({ rule: d.rule.source, reason: d.reason })));
308
+ }
309
+ return keyboxError(404, "not_found", `No admin route ${m} /${seg.join("/")}.`);
310
+ }
311
+ async function putSecret(req, env, name) {
312
+ const kek = await importKek(env.KEYBOX_KEK);
313
+ if (!kek) return keyboxError(503, "not_configured", "KEYBOX_KEK is not set.");
314
+ const b = await body(req);
315
+ check(SECRET_NAME.test(name), "secret names are UPPER_SNAKE_CASE, up to 64 characters");
316
+ check(Array.isArray(b.hosts) && b.hosts.length > 0 && b.hosts.length <= 16, "hosts must list 1-16 hostnames");
317
+ const hosts = [...new Set(b.hosts.map((h) => String(h).toLowerCase()))].sort();
318
+ for (const h of hosts) check(isHostname(h), `not a public hostname: ${h}`);
319
+ check(typeof b.header === "string" && HEADER.test(b.header), "header must be a plain header name");
320
+ const header = b.header.toLowerCase();
321
+ check(!FORBIDDEN_HEADERS.has(header), `cannot inject into ${header}`);
322
+ check(FORMATS.has(b.format), "format must be bearer, raw or basic");
323
+ check(typeof b.value === "string", "value is required");
324
+ const value = b.value;
325
+ check(value.length >= 8 && value.length <= 8192, "value must be 8-8192 characters");
326
+ check(!/[\r\n\0]/.test(value), "value cannot contain line breaks");
327
+ const meta = { name, hosts, header, format: b.format };
328
+ const { iv, ciphertext } = await seal(kek, meta, value);
329
+ await env.DB.prepare(
330
+ `INSERT INTO secrets (name, hosts, header, format, iv, ciphertext, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)
331
+ ON CONFLICT(name) DO UPDATE SET hosts = excluded.hosts, header = excluded.header, format = excluded.format,
332
+ iv = excluded.iv, ciphertext = excluded.ciphertext`
333
+ ).bind(name, JSON.stringify(hosts), header, meta.format, iv, ciphertext, Date.now()).run();
334
+ return Response.json({ name, hosts, header, format: meta.format });
335
+ }
336
+ async function putAgent(req, env, name) {
337
+ check(AGENT_NAME.test(name), "agent names are lowercase letters, digits and dashes");
338
+ const b = await body(req);
339
+ check(Array.isArray(b.grants) && b.grants.length > 0, "grants must be a non-empty list");
340
+ const { results } = await env.DB.prepare("SELECT name, hosts FROM secrets").all();
341
+ const hostsOf = new Map(results.map((r) => [r.name, JSON.parse(r.hosts)]));
342
+ const grants = [];
343
+ for (const g of b.grants) {
344
+ const secret = String(g?.secret ?? "");
345
+ const hosts = hostsOf.get(secret);
346
+ check(hosts, `unknown secret: ${secret}`);
347
+ check(Array.isArray(g.allow) && g.allow.length > 0, `grant for ${secret} needs at least one allow rule`);
348
+ const allow = g.allow.map(String);
349
+ const deny = Array.isArray(g.deny) ? g.deny.map(String) : [];
350
+ for (const r of [...allow, ...deny]) {
351
+ try {
352
+ parseRule(r);
353
+ } catch {
354
+ throw new Bad(`bad rule: ${r} (expected e.g. "GET api.github.com/repos/**")`);
355
+ }
356
+ }
357
+ for (const r of allow) {
358
+ const h = ruleHost(r);
359
+ check(h && hosts.includes(h), `${secret} is bound to ${hosts.join(", ")}; rule "${r}" must name one of those hosts`);
360
+ }
361
+ grants.push(deny.length ? { secret, allow, deny } : { secret, allow });
362
+ }
363
+ await env.DB.prepare(
364
+ `INSERT INTO agents (name, grants, created_at) VALUES (?, ?, ?)
365
+ ON CONFLICT(name) DO UPDATE SET grants = excluded.grants`
366
+ ).bind(name, JSON.stringify(grants), Date.now()).run();
367
+ return Response.json({ name, grants });
368
+ }
369
+ async function mintToken(req, env, agent) {
370
+ const b = await body(req);
371
+ const ttl = Number(b.ttl);
372
+ check(Number.isInteger(ttl) && ttl >= 60 && ttl <= MAX_TTL, "ttl must be 60 seconds to 365 days");
373
+ const exists = await env.DB.prepare("SELECT 1 FROM agents WHERE name = ?").bind(agent).first();
374
+ check(exists, `unknown agent: ${agent}`);
375
+ const token = randomToken("kb_agt_");
376
+ const id = crypto.randomUUID();
377
+ const now = Date.now();
378
+ const expires_at = now + ttl * 1e3;
379
+ await env.DB.prepare("INSERT INTO tokens (id, agent, hash, expires_at, created_at) VALUES (?, ?, ?, ?, ?)").bind(id, agent, await sha256Hex(token), expires_at, now).run();
380
+ return Response.json({ id, agent, token, expires_at });
381
+ }
382
+
383
+ // src/scrub.ts
384
+ var REDACTED = "[keybox:redacted]";
385
+ var redactedBytes = new TextEncoder().encode(REDACTED);
386
+ function scrubber(needles2) {
387
+ const list = needles2.filter((n) => n.length > 0);
388
+ if (list.length === 0) return new TransformStream();
389
+ const max = Math.max(...list.map((n) => n.length));
390
+ const firsts = [...new Set(list.map((n) => n[0]))];
391
+ let carry = new Uint8Array(0);
392
+ const run = (buf, final, c) => {
393
+ const hold = final ? buf.length : holdFrom(buf, list, max);
394
+ let start = 0;
395
+ let i = next(buf, 0, hold, firsts);
396
+ while (i < hold) {
397
+ const hit = list.find((n) => startsWith(buf, i, n));
398
+ if (hit) {
399
+ if (i > start) c.enqueue(buf.slice(start, i));
400
+ c.enqueue(redactedBytes);
401
+ i += hit.length;
402
+ start = i;
403
+ } else {
404
+ i += 1;
405
+ }
406
+ i = next(buf, i, hold, firsts);
407
+ }
408
+ const keep = Math.max(start, hold);
409
+ if (keep > start) c.enqueue(buf.slice(start, keep));
410
+ carry = buf.slice(keep);
411
+ };
412
+ return new TransformStream({
413
+ transform(chunk, c) {
414
+ const buf = new Uint8Array(carry.length + chunk.length);
415
+ buf.set(carry);
416
+ buf.set(chunk, carry.length);
417
+ run(buf, false, c);
418
+ },
419
+ flush(c) {
420
+ run(carry, true, c);
421
+ }
422
+ });
423
+ }
424
+ function holdFrom(buf, list, max) {
425
+ for (let p = Math.max(0, buf.length - max + 1); p < buf.length; p++) {
426
+ const rest = buf.length - p;
427
+ if (list.some((n) => n.length > rest && startsWith(n, 0, buf.subarray(p)))) return p;
428
+ }
429
+ return buf.length;
430
+ }
431
+ function next(buf, from, limit, firsts) {
432
+ let best = limit;
433
+ for (const b of firsts) {
434
+ const at = buf.indexOf(b, from);
435
+ if (at !== -1 && at < best) best = at;
436
+ }
437
+ return best;
438
+ }
439
+ function startsWith(buf, at, n) {
440
+ if (at + n.length > buf.length) return false;
441
+ for (let j = 0; j < n.length; j++) if (buf[at + j] !== n[j]) return false;
442
+ return true;
443
+ }
444
+ function scrubString(s, values) {
445
+ for (const v of values) if (v) s = s.split(v).join(REDACTED);
446
+ return s;
447
+ }
448
+
449
+ // src/proxy.ts
450
+ var STRIP = /* @__PURE__ */ new Set([
451
+ "host",
452
+ "authorization",
453
+ "proxy-authorization",
454
+ "x-api-key",
455
+ "cookie",
456
+ "forwarded",
457
+ "x-forwarded-for",
458
+ "x-forwarded-host",
459
+ "x-forwarded-proto",
460
+ "x-real-ip",
461
+ "true-client-ip",
462
+ "x-http-method-override",
463
+ "x-http-method",
464
+ "x-method-override",
465
+ "connection",
466
+ "keep-alive",
467
+ "te",
468
+ "upgrade"
469
+ ]);
470
+ function agentToken(h) {
471
+ const direct = h.get("x-keybox-token") ?? h.get("x-api-key");
472
+ if (direct?.startsWith("kb_agt_")) return direct;
473
+ const auth = h.get("authorization") ?? "";
474
+ const bearer = /^Bearer\s+(kb_agt_\S+)$/i.exec(auth);
475
+ if (bearer) return bearer[1];
476
+ const basic = /^Basic\s+(\S+)$/i.exec(auth);
477
+ if (basic) {
478
+ try {
479
+ const found = atob(basic[1]).split(":").find((p) => p.startsWith("kb_agt_"));
480
+ if (found) return found;
481
+ } catch {
482
+ }
483
+ }
484
+ return null;
485
+ }
486
+ async function proxy(req, env, ctx) {
487
+ const url = new URL(req.url);
488
+ const method = req.method.toUpperCase();
489
+ const e = {
490
+ agent: null,
491
+ token_id: null,
492
+ method,
493
+ host: null,
494
+ path: null,
495
+ secret: null,
496
+ decision: "deny",
497
+ reason: null,
498
+ status: 0
499
+ };
500
+ const deny = (status, code, message) => {
501
+ e.reason = code;
502
+ e.status = status;
503
+ audit(env, ctx, e);
504
+ return keyboxError(status, code, message);
505
+ };
506
+ const kek = await importKek(env.KEYBOX_KEK);
507
+ if (!kek) return keyboxError(503, "not_configured", "This Keybox has no encryption key yet. Run `keybox init`.");
508
+ const token = agentToken(req.headers);
509
+ if (!token) return keyboxError(401, "missing_token", "Send a Keybox agent token (kb_agt_\u2026) as your API key.");
510
+ const now = Date.now();
511
+ const auth = await env.DB.prepare(
512
+ `SELECT t.id, t.agent, a.grants FROM tokens t JOIN agents a ON a.name = t.agent
513
+ WHERE t.hash = ? AND t.revoked_at IS NULL AND t.expires_at > ?`
514
+ ).bind(await sha256Hex(token), now).first();
515
+ if (!auth) return keyboxError(401, "invalid_token", "This agent token is unknown, expired or revoked.");
516
+ e.agent = auth.agent;
517
+ e.token_id = auth.id;
518
+ const target = /^\/([^/]+)(\/.*)?$/.exec(url.pathname);
519
+ const host = target?.[1].toLowerCase() ?? "";
520
+ if (!isHostname(host)) return deny(400, "bad_host", "Call Keybox as https://<keybox>/<api host>/<path>.");
521
+ e.host = host;
522
+ let path;
523
+ try {
524
+ path = canonicalPath(target?.[2] ?? "/");
525
+ } catch {
526
+ return deny(400, "bad_path", "Encoded slashes and backslashes are not allowed in proxied paths.");
527
+ }
528
+ e.path = path;
529
+ const blocked = denied(denyRules(env), method, host, path);
530
+ if (blocked) return deny(403, "blocked", `Keybox never proxies this call: ${blocked.reason}.`);
531
+ const grants = JSON.parse(auth.grants);
532
+ const names = [...new Set(grants.map((g) => g.secret))];
533
+ const rows = names.length ? (await env.DB.prepare(`SELECT * FROM secrets WHERE name IN (${names.map(() => "?").join(",")})`).bind(...names).all()).results : [];
534
+ const bound = new Map(rows.filter((r) => JSON.parse(r.hosts).includes(host)).map((r) => [r.name, r]));
535
+ const candidates = /* @__PURE__ */ new Set();
536
+ for (const g of grants) {
537
+ if (!bound.has(g.secret)) continue;
538
+ const hit = (src) => matches(parseRule(src), method, host, path);
539
+ if (g.deny?.some(hit)) continue;
540
+ if (g.allow.some(hit)) candidates.add(g.secret);
541
+ }
542
+ if (candidates.size === 0) {
543
+ return deny(403, "not_allowed", `Agent ${auth.agent} has no rule allowing ${method} ${host}${path}.`);
544
+ }
545
+ let pick = [...candidates][0];
546
+ if (candidates.size > 1) {
547
+ const want = req.headers.get("x-keybox-secret");
548
+ if (!want || !candidates.has(want)) {
549
+ return deny(409, "ambiguous_secret", `Several secrets match; set x-keybox-secret to one of: ${[...candidates].join(", ")}.`);
550
+ }
551
+ pick = want;
552
+ }
553
+ const row = bound.get(pick);
554
+ e.secret = row.name;
555
+ const meta = { name: row.name, hosts: JSON.parse(row.hosts), header: row.header, format: row.format };
556
+ let value;
557
+ try {
558
+ value = await open(kek, meta, row.iv, row.ciphertext);
559
+ } catch {
560
+ e.decision = "error";
561
+ return deny(500, "decrypt_failed", `Secret ${row.name} could not be decrypted; it may have been tampered with.`);
562
+ }
563
+ const headers = new Headers();
564
+ for (const [k, v] of req.headers) {
565
+ if (STRIP.has(k) || k.startsWith("cf-") || k.startsWith("x-keybox-") || k === row.header.toLowerCase()) continue;
566
+ headers.append(k, v);
567
+ }
568
+ headers.set(row.header, headerValue(row.format, value));
569
+ let upstream;
570
+ try {
571
+ upstream = await fetch(`https://${host}${path}${url.search}`, {
572
+ method,
573
+ headers,
574
+ body: method === "GET" || method === "HEAD" ? null : req.body,
575
+ // Never follow: a redirect must not carry the credential to another URL.
576
+ redirect: "manual"
577
+ });
578
+ } catch {
579
+ e.decision = "error";
580
+ return deny(502, "upstream_unreachable", `Could not reach ${host}.`);
581
+ }
582
+ const raw = needles(row.format, value);
583
+ const plain = raw.map((n) => new TextDecoder().decode(n));
584
+ const out = new Headers();
585
+ for (const [k, v] of upstream.headers) {
586
+ if (k === "content-length") continue;
587
+ out.append(k, scrubString(v, plain));
588
+ }
589
+ e.decision = "allow";
590
+ e.status = upstream.status;
591
+ audit(env, ctx, e);
592
+ return new Response(upstream.body ? upstream.body.pipeThrough(scrubber(raw)) : null, {
593
+ status: upstream.status,
594
+ statusText: upstream.statusText,
595
+ headers: out
596
+ });
597
+ }
598
+
599
+ // src/index.ts
600
+ var index_default = {
601
+ async fetch(req, env, ctx) {
602
+ const { pathname } = new URL(req.url);
603
+ if (pathname === "/_keybox/health") {
604
+ const configured = Boolean(env.KEYBOX_KEK && env.KEYBOX_ADMIN_TOKEN_HASH);
605
+ return Response.json({ ok: true, version: VERSION, configured });
606
+ }
607
+ if (pathname.startsWith("/_keybox/admin/")) {
608
+ return admin(req, env, pathname.slice("/_keybox/admin".length));
609
+ }
610
+ if (pathname === "/" || pathname === "/favicon.ico") {
611
+ return new Response("keybox: keys stay in the box.\n", { headers: { "content-type": "text/plain" } });
612
+ }
613
+ return proxy(req, env, ctx);
614
+ }
615
+ };
616
+ export {
617
+ index_default as default
618
+ };