@keyboxed/cli 0.0.0-stage → 0.1.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 +19 -2
- package/assets/schema.sql +6 -0
- package/assets/worker.js +618 -0
- package/dist/keybox.js +610 -0
- package/package.json +31 -4
package/README.md
CHANGED
|
@@ -1,3 +1,20 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @keybox/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Give AI agents access to your APIs without giving them your keys.
|
|
4
|
+
|
|
5
|
+
Keybox is a Cloudflare Worker that you deploy to your own account. Agents get a scoped Keybox token. The real key is attached on the way out, bound to the hosts it belongs to, and scrubbed from responses.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -g @keybox/cli
|
|
9
|
+
npx wrangler login
|
|
10
|
+
keybox init
|
|
11
|
+
|
|
12
|
+
keybox secrets add OPENAI_API_KEY
|
|
13
|
+
keybox agents create writer --allow "POST api.openai.com/v1/responses"
|
|
14
|
+
keybox run writer -- python agent.py
|
|
15
|
+
keybox audit --follow
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Calls that would mint a new key or grant lasting access (OpenAI admin keys, GitHub deploy keys and collaborators, Cloudflare API tokens, and others) are always blocked. See them with `keybox blocked`.
|
|
19
|
+
|
|
20
|
+
Read the security model before storing production keys. It also covers what Keybox does not protect against, such as an agent running as your user being able to read your Keybox admin token.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS secrets (name TEXT PRIMARY KEY, hosts TEXT NOT NULL, header TEXT NOT NULL, format TEXT NOT NULL, iv TEXT NOT NULL, ciphertext TEXT NOT NULL, created_at INTEGER NOT NULL);
|
|
2
|
+
CREATE TABLE IF NOT EXISTS agents (name TEXT PRIMARY KEY, grants TEXT NOT NULL, created_at INTEGER NOT NULL);
|
|
3
|
+
CREATE TABLE IF NOT EXISTS tokens (id TEXT PRIMARY KEY, agent TEXT NOT NULL, hash TEXT NOT NULL UNIQUE, expires_at INTEGER NOT NULL, revoked_at INTEGER, created_at INTEGER NOT NULL);
|
|
4
|
+
CREATE INDEX IF NOT EXISTS tokens_agent ON tokens (agent);
|
|
5
|
+
CREATE TABLE IF NOT EXISTS audit (id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER NOT NULL, agent TEXT, token_id TEXT, method TEXT NOT NULL, host TEXT, path TEXT, secret TEXT, decision TEXT NOT NULL, reason TEXT, status INTEGER NOT NULL);
|
|
6
|
+
CREATE INDEX IF NOT EXISTS audit_ts ON audit (ts);
|
package/assets/worker.js
ADDED
|
@@ -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
|
+
};
|
package/dist/keybox.js
ADDED
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
|
|
6
|
+
// src/commands.ts
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
|
|
9
|
+
// src/config.ts
|
|
10
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
function configDir() {
|
|
14
|
+
return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "keybox");
|
|
15
|
+
}
|
|
16
|
+
var configPath = () => join(configDir(), "config.json");
|
|
17
|
+
var deployDir = () => join(configDir(), "deploy");
|
|
18
|
+
function loadConfig() {
|
|
19
|
+
const env = process.env;
|
|
20
|
+
if (env.KEYBOX_URL && env.KEYBOX_ADMIN_TOKEN) {
|
|
21
|
+
return { url: env.KEYBOX_URL, adminToken: env.KEYBOX_ADMIN_TOKEN, name: env.KEYBOX_NAME ?? "keybox", d1Id: "" };
|
|
22
|
+
}
|
|
23
|
+
if (!existsSync(configPath())) return null;
|
|
24
|
+
return JSON.parse(readFileSync(configPath(), "utf8"));
|
|
25
|
+
}
|
|
26
|
+
function requireConfig() {
|
|
27
|
+
const c = loadConfig();
|
|
28
|
+
if (!c) throw new UserError("Not set up yet. Run `keybox init` first.");
|
|
29
|
+
return c;
|
|
30
|
+
}
|
|
31
|
+
function saveConfig(c) {
|
|
32
|
+
mkdirSync(configDir(), { recursive: true, mode: 448 });
|
|
33
|
+
writeFileSync(configPath(), JSON.stringify(c, null, 2) + "\n", { mode: 384 });
|
|
34
|
+
chmodSync(configPath(), 384);
|
|
35
|
+
}
|
|
36
|
+
var UserError = class extends Error {
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// src/api.ts
|
|
40
|
+
async function api(method, path, body, config = requireConfig()) {
|
|
41
|
+
let res;
|
|
42
|
+
try {
|
|
43
|
+
res = await fetch(`${config.url.replace(/\/$/, "")}/_keybox/admin${path}`, {
|
|
44
|
+
method,
|
|
45
|
+
headers: { authorization: `Bearer ${config.adminToken}`, "content-type": "application/json" },
|
|
46
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
47
|
+
});
|
|
48
|
+
} catch {
|
|
49
|
+
throw new UserError(`Could not reach ${config.url}.`);
|
|
50
|
+
}
|
|
51
|
+
const data = await res.json().catch(() => null);
|
|
52
|
+
if (!res.ok) throw new UserError(data?.error?.message ?? `Keybox returned HTTP ${res.status}.`);
|
|
53
|
+
return data;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// src/presets.ts
|
|
57
|
+
var PRESETS = {
|
|
58
|
+
openai: {
|
|
59
|
+
hosts: ["api.openai.com"],
|
|
60
|
+
header: "authorization",
|
|
61
|
+
format: "bearer",
|
|
62
|
+
env: (base, token) => ({ OPENAI_BASE_URL: `${base}/api.openai.com/v1`, OPENAI_API_KEY: token })
|
|
63
|
+
},
|
|
64
|
+
anthropic: {
|
|
65
|
+
hosts: ["api.anthropic.com"],
|
|
66
|
+
header: "x-api-key",
|
|
67
|
+
format: "raw",
|
|
68
|
+
env: (base, token) => ({ ANTHROPIC_BASE_URL: `${base}/api.anthropic.com`, ANTHROPIC_API_KEY: token })
|
|
69
|
+
},
|
|
70
|
+
github: { hosts: ["api.github.com"], header: "authorization", format: "bearer" },
|
|
71
|
+
stripe: { hosts: ["api.stripe.com"], header: "authorization", format: "bearer" },
|
|
72
|
+
cloudflare: { hosts: ["api.cloudflare.com"], header: "authorization", format: "bearer" }
|
|
73
|
+
};
|
|
74
|
+
var KEY_VARS = [
|
|
75
|
+
"OPENAI_API_KEY",
|
|
76
|
+
"ANTHROPIC_API_KEY",
|
|
77
|
+
"GITHUB_TOKEN",
|
|
78
|
+
"GH_TOKEN",
|
|
79
|
+
"STRIPE_API_KEY",
|
|
80
|
+
"STRIPE_SECRET_KEY",
|
|
81
|
+
"CLOUDFLARE_API_TOKEN",
|
|
82
|
+
"CLOUDFLARE_API_KEY",
|
|
83
|
+
"AWS_ACCESS_KEY_ID",
|
|
84
|
+
"AWS_SECRET_ACCESS_KEY",
|
|
85
|
+
"AWS_SESSION_TOKEN",
|
|
86
|
+
"GOOGLE_API_KEY",
|
|
87
|
+
"GEMINI_API_KEY",
|
|
88
|
+
"HF_TOKEN",
|
|
89
|
+
"KEYBOX_ADMIN_TOKEN"
|
|
90
|
+
];
|
|
91
|
+
function envFor(hosts, base, token) {
|
|
92
|
+
const out = { KEYBOX_URL: base, KEYBOX_TOKEN: token };
|
|
93
|
+
for (const p of Object.values(PRESETS)) {
|
|
94
|
+
if (p.env && p.hosts.some((h) => hosts.includes(h))) Object.assign(out, p.env(base, token));
|
|
95
|
+
}
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// src/prompt.ts
|
|
100
|
+
import { createInterface } from "node:readline/promises";
|
|
101
|
+
async function readSecret(label) {
|
|
102
|
+
const stdin = process.stdin;
|
|
103
|
+
if (!stdin.isTTY) {
|
|
104
|
+
let data = "";
|
|
105
|
+
for await (const chunk of stdin) data += chunk;
|
|
106
|
+
return data.replace(/\r?\n$/, "");
|
|
107
|
+
}
|
|
108
|
+
process.stderr.write(`${label}: `);
|
|
109
|
+
stdin.setRawMode(true);
|
|
110
|
+
stdin.resume();
|
|
111
|
+
stdin.setEncoding("utf8");
|
|
112
|
+
return new Promise((resolve, reject) => {
|
|
113
|
+
let value = "";
|
|
114
|
+
const done = (err) => {
|
|
115
|
+
stdin.setRawMode(false);
|
|
116
|
+
stdin.pause();
|
|
117
|
+
stdin.off("data", onData);
|
|
118
|
+
process.stderr.write("\n");
|
|
119
|
+
err ? reject(err) : resolve(value);
|
|
120
|
+
};
|
|
121
|
+
const onData = (s) => {
|
|
122
|
+
for (const ch of s) {
|
|
123
|
+
if (ch === "\r" || ch === "\n") return done();
|
|
124
|
+
if (ch === "") return done(new UserError("Cancelled."));
|
|
125
|
+
if (ch === "\x7F" || ch === "\b") value = value.slice(0, -1);
|
|
126
|
+
else value += ch;
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
stdin.on("data", onData);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
async function confirm(question) {
|
|
133
|
+
if (!process.stdin.isTTY) return false;
|
|
134
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
135
|
+
const answer = await rl.question(`${question} [y/N] `);
|
|
136
|
+
rl.close();
|
|
137
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// src/ui.ts
|
|
141
|
+
var tty = process.stderr.isTTY && !process.env.NO_COLOR;
|
|
142
|
+
var dim = (s) => tty ? `\x1B[2m${s}\x1B[0m` : s;
|
|
143
|
+
var blue = (s) => tty ? `\x1B[34m${s}\x1B[0m` : s;
|
|
144
|
+
function step(s) {
|
|
145
|
+
process.stderr.write(`${blue("\u25A0")} ${s}
|
|
146
|
+
`);
|
|
147
|
+
}
|
|
148
|
+
function note(s) {
|
|
149
|
+
process.stderr.write(`${dim(" " + s)}
|
|
150
|
+
`);
|
|
151
|
+
}
|
|
152
|
+
function table(rows) {
|
|
153
|
+
if (rows.length === 0) return "";
|
|
154
|
+
const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => (r[i] ?? "").length)));
|
|
155
|
+
return rows.map((r) => r.map((c, i) => i === r.length - 1 ? c : c.padEnd(widths[i])).join(" ")).join("\n") + "\n";
|
|
156
|
+
}
|
|
157
|
+
function when(ms) {
|
|
158
|
+
return new Date(ms).toISOString().replace("T", " ").slice(0, 19);
|
|
159
|
+
}
|
|
160
|
+
function parseDuration(s) {
|
|
161
|
+
const m = /^(\d+)([smhd]?)$/.exec(s.trim());
|
|
162
|
+
if (!m) throw new Error(`bad duration: ${s}`);
|
|
163
|
+
return Number(m[1]) * { "": 1, s: 1, m: 60, h: 3600, d: 86400 }[m[2]];
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/commands.ts
|
|
167
|
+
function guessPreset(name) {
|
|
168
|
+
const prefix = name.split("_")[0];
|
|
169
|
+
if (prefix === "GH") return "github";
|
|
170
|
+
const p = prefix.toLowerCase();
|
|
171
|
+
return p in PRESETS ? p : null;
|
|
172
|
+
}
|
|
173
|
+
async function secretsAdd(name, opts) {
|
|
174
|
+
let spec;
|
|
175
|
+
if (opts.host?.length) {
|
|
176
|
+
spec = { hosts: opts.host, header: opts.header ?? "authorization", format: opts.format ?? "bearer" };
|
|
177
|
+
} else {
|
|
178
|
+
const preset = opts.preset ?? guessPreset(name);
|
|
179
|
+
if (!preset || !PRESETS[preset]) {
|
|
180
|
+
throw new UserError(`Say where ${name} may be sent: --preset ${Object.keys(PRESETS).join("|")} or --host <hostname>.`);
|
|
181
|
+
}
|
|
182
|
+
spec = PRESETS[preset];
|
|
183
|
+
if (!opts.preset) note(`Using preset ${preset}: ${spec.hosts.join(", ")}, ${spec.header} (${spec.format}).`);
|
|
184
|
+
}
|
|
185
|
+
const value = await readSecret(`Value for ${name} (hidden)`);
|
|
186
|
+
if (!value) throw new UserError("No value given.");
|
|
187
|
+
const r = await api("PUT", `/secrets/${name}`, { ...spec, value });
|
|
188
|
+
process.stderr.write(`Stored ${r.name}. It will only ever be sent to ${r.hosts.join(", ")}.
|
|
189
|
+
`);
|
|
190
|
+
}
|
|
191
|
+
async function secretsList() {
|
|
192
|
+
const rows = await api("GET", "/secrets");
|
|
193
|
+
if (!rows.length) return note("No secrets yet. Add one with `keybox secrets add NAME`.");
|
|
194
|
+
process.stdout.write(table([["NAME", "HOSTS", "HEADER", "ADDED"], ...rows.map((s) => [s.name, s.hosts.join(","), `${s.header} (${s.format})`, when(s.created_at)])]));
|
|
195
|
+
}
|
|
196
|
+
async function secretsRm(name) {
|
|
197
|
+
const r = await api("DELETE", `/secrets/${name}`);
|
|
198
|
+
process.stderr.write(r.deleted ? `Deleted ${name}.
|
|
199
|
+
` : `No secret named ${name}.
|
|
200
|
+
`);
|
|
201
|
+
}
|
|
202
|
+
function buildGrants(allow, deny, secrets) {
|
|
203
|
+
const grants = /* @__PURE__ */ new Map();
|
|
204
|
+
const hostOf = (rule) => /^\S+\s+([^/\s]+)/.exec(rule)?.[1] ?? "";
|
|
205
|
+
const resolve = (raw) => {
|
|
206
|
+
const named = /^([A-Z][A-Z0-9_]*)=(.+)$/.exec(raw);
|
|
207
|
+
if (named) return [named[1], named[2].trim()];
|
|
208
|
+
const host = hostOf(raw);
|
|
209
|
+
const bound = secrets.filter((s) => s.hosts.includes(host));
|
|
210
|
+
if (bound.length === 1) return [bound[0].name, raw];
|
|
211
|
+
if (bound.length === 0) throw new UserError(`No stored secret is bound to ${host || "that host"} (rule "${raw}").`);
|
|
212
|
+
throw new UserError(`Several secrets are bound to ${host}; prefix the rule: "${bound[0].name}=${raw}".`);
|
|
213
|
+
};
|
|
214
|
+
for (const raw of allow) {
|
|
215
|
+
const [secret, rule] = resolve(raw);
|
|
216
|
+
const g = grants.get(secret) ?? { secret, allow: [] };
|
|
217
|
+
g.allow.push(rule);
|
|
218
|
+
grants.set(secret, g);
|
|
219
|
+
}
|
|
220
|
+
for (const raw of deny) {
|
|
221
|
+
const named = /^([A-Z][A-Z0-9_]*)=(.+)$/.exec(raw);
|
|
222
|
+
const targets = named ? [grants.get(named[1])] : [...grants.values()].filter((g) => {
|
|
223
|
+
const host = hostOf(raw);
|
|
224
|
+
return host.includes("*") || secrets.find((s) => s.name === g.secret)?.hosts.includes(host);
|
|
225
|
+
});
|
|
226
|
+
const rule = named ? named[2].trim() : raw;
|
|
227
|
+
if (!targets.length || targets.some((t) => !t)) throw new UserError(`Deny rule "${raw}" does not apply to any allowed secret.`);
|
|
228
|
+
for (const g of targets) (g.deny ??= []).push(rule);
|
|
229
|
+
}
|
|
230
|
+
return [...grants.values()];
|
|
231
|
+
}
|
|
232
|
+
async function agentsCreate(name, opts) {
|
|
233
|
+
if (!opts.allow?.length) throw new UserError('Give at least one --allow rule, e.g. --allow "GET api.github.com/repos/**".');
|
|
234
|
+
const secrets = await api("GET", "/secrets");
|
|
235
|
+
const grants = buildGrants(opts.allow, opts.deny ?? [], secrets);
|
|
236
|
+
await api("PUT", `/agents/${name}`, { grants });
|
|
237
|
+
process.stderr.write(`Agent ${name} can now:
|
|
238
|
+
`);
|
|
239
|
+
for (const g of grants) {
|
|
240
|
+
for (const r of g.allow) process.stderr.write(` allow ${r} (with ${g.secret})
|
|
241
|
+
`);
|
|
242
|
+
for (const r of g.deny ?? []) process.stderr.write(` deny ${r}
|
|
243
|
+
`);
|
|
244
|
+
}
|
|
245
|
+
process.stderr.write(`Everything else is denied. Start it with: keybox run ${name} -- <command>
|
|
246
|
+
`);
|
|
247
|
+
}
|
|
248
|
+
async function agentsList() {
|
|
249
|
+
const rows = await api("GET", "/agents");
|
|
250
|
+
if (!rows.length) return note("No agents yet. Create one with `keybox agents create NAME --allow RULE`.");
|
|
251
|
+
const out = [["AGENT", "SECRET", "RULE", "TOKENS"]];
|
|
252
|
+
for (const a of rows) {
|
|
253
|
+
let first = true;
|
|
254
|
+
for (const g of a.grants) {
|
|
255
|
+
for (const [kind, r] of [...g.allow.map((r2) => ["allow", r2]), ...(g.deny ?? []).map((r2) => ["deny", r2])]) {
|
|
256
|
+
out.push([first ? a.name : "", g.secret, `${kind} ${r}`, first ? String(a.active_tokens) : ""]);
|
|
257
|
+
first = false;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
process.stdout.write(table(out));
|
|
262
|
+
}
|
|
263
|
+
async function agentsRm(name) {
|
|
264
|
+
await api("DELETE", `/agents/${name}`);
|
|
265
|
+
process.stderr.write(`Removed ${name} and revoked its tokens.
|
|
266
|
+
`);
|
|
267
|
+
}
|
|
268
|
+
async function agentsToken(name, opts) {
|
|
269
|
+
const m = await api("POST", `/agents/${name}/tokens`, { ttl: parseDuration(opts.ttl) });
|
|
270
|
+
process.stderr.write(`Token ${m.id} for ${name}, expires ${when(m.expires_at)} UTC. It is shown once.
|
|
271
|
+
`);
|
|
272
|
+
process.stdout.write(m.token + "\n");
|
|
273
|
+
}
|
|
274
|
+
async function tokensRevoke(id) {
|
|
275
|
+
const r = await api("DELETE", `/tokens/${id}`);
|
|
276
|
+
process.stderr.write(r.revoked ? `Revoked ${id}.
|
|
277
|
+
` : `No active token ${id}.
|
|
278
|
+
`);
|
|
279
|
+
}
|
|
280
|
+
var BASE_ENV = ["PATH", "HOME", "USER", "LOGNAME", "SHELL", "TERM", "LANG", "LC_ALL", "TMPDIR", "TZ", "COLORTERM", "NO_COLOR", "FORCE_COLOR"];
|
|
281
|
+
async function run(name, cmd, opts) {
|
|
282
|
+
if (!cmd.length) throw new UserError("Nothing to run. Usage: keybox run AGENT -- command [args]");
|
|
283
|
+
const c = requireConfig();
|
|
284
|
+
const [agents, secrets] = await Promise.all([api("GET", "/agents"), api("GET", "/secrets")]);
|
|
285
|
+
const agent = agents.find((a) => a.name === name);
|
|
286
|
+
if (!agent) throw new UserError(`No agent named ${name}.`);
|
|
287
|
+
const hosts = secrets.filter((s) => agent.grants.some((g) => g.secret === s.name)).flatMap((s) => s.hosts);
|
|
288
|
+
const minted = await api("POST", `/agents/${name}/tokens`, { ttl: parseDuration(opts.ttl) });
|
|
289
|
+
const env = opts.cleanEnv ? Object.fromEntries(BASE_ENV.filter((k) => process.env[k] !== void 0).map((k) => [k, process.env[k]])) : { ...process.env };
|
|
290
|
+
const removed = [];
|
|
291
|
+
for (const k of /* @__PURE__ */ new Set([...KEY_VARS, ...secrets.map((s) => s.name)])) {
|
|
292
|
+
if (env[k] !== void 0) {
|
|
293
|
+
delete env[k];
|
|
294
|
+
removed.push(k);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
if (removed.length) note(`Removed ${removed.join(", ")} from ${name}'s environment.`);
|
|
298
|
+
Object.assign(env, envFor(hosts, c.url.replace(/\/$/, ""), minted.token));
|
|
299
|
+
const revoke = () => api("DELETE", `/tokens/${minted.id}`).catch(() => note(`Could not revoke token ${minted.id}; it expires ${when(minted.expires_at)} UTC.`));
|
|
300
|
+
const child = spawn(cmd[0], cmd.slice(1), { stdio: "inherit", env });
|
|
301
|
+
const ignore = () => {
|
|
302
|
+
};
|
|
303
|
+
process.on("SIGINT", ignore);
|
|
304
|
+
process.on("SIGTERM", () => child.kill("SIGTERM"));
|
|
305
|
+
const code = await new Promise((resolve) => {
|
|
306
|
+
child.on("error", (err) => {
|
|
307
|
+
note(`Could not start ${cmd[0]}: ${err.message}`);
|
|
308
|
+
resolve(127);
|
|
309
|
+
});
|
|
310
|
+
child.on("close", (code2, signal) => resolve(code2 ?? (signal ? 128 + (signalNumber(signal) ?? 1) : 1)));
|
|
311
|
+
});
|
|
312
|
+
await revoke();
|
|
313
|
+
process.off("SIGINT", ignore);
|
|
314
|
+
process.exitCode = code;
|
|
315
|
+
}
|
|
316
|
+
function signalNumber(s) {
|
|
317
|
+
return { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGTERM: 15 }[s];
|
|
318
|
+
}
|
|
319
|
+
function auditLine(r) {
|
|
320
|
+
return [when(r.ts), r.agent ?? "-", r.decision === "allow" ? String(r.status) : r.decision.toUpperCase(), `${r.method} ${r.host ?? ""}${r.path ?? ""}`, r.secret ?? r.reason ?? ""];
|
|
321
|
+
}
|
|
322
|
+
async function audit(opts) {
|
|
323
|
+
let rows = await api("GET", `/audit?limit=${Number(opts.limit) || 50}`);
|
|
324
|
+
process.stdout.write(table([["TIME (UTC)", "AGENT", "RESULT", "REQUEST", "SECRET / REASON"], ...rows.map(auditLine)]));
|
|
325
|
+
if (!opts.follow) return;
|
|
326
|
+
let last = rows.at(-1)?.id ?? 0;
|
|
327
|
+
for (; ; ) {
|
|
328
|
+
await new Promise((r) => setTimeout(r, 2e3));
|
|
329
|
+
rows = await api("GET", `/audit?after=${last}&limit=500`);
|
|
330
|
+
if (rows.length) {
|
|
331
|
+
process.stdout.write(table(rows.map(auditLine)));
|
|
332
|
+
last = rows.at(-1).id;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
async function blocked() {
|
|
337
|
+
const rows = await api("GET", "/blocked");
|
|
338
|
+
process.stdout.write(table([["NEVER PROXIED", "WHY"], ...rows.map((r) => [r.rule, r.reason])]));
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// src/deploy.ts
|
|
342
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
343
|
+
import { copyFileSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
|
|
344
|
+
import { join as join3 } from "node:path";
|
|
345
|
+
|
|
346
|
+
// src/wrangler.ts
|
|
347
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
348
|
+
import { readFileSync as readFileSync2 } from "node:fs";
|
|
349
|
+
import { createRequire } from "node:module";
|
|
350
|
+
import { dirname, join as join2 } from "node:path";
|
|
351
|
+
function bin() {
|
|
352
|
+
const pkgPath = createRequire(import.meta.url).resolve("wrangler/package.json");
|
|
353
|
+
const pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
|
|
354
|
+
return join2(dirname(pkgPath), pkg.bin.wrangler);
|
|
355
|
+
}
|
|
356
|
+
function wrangler(args, opts = {}) {
|
|
357
|
+
return new Promise((resolve, reject) => {
|
|
358
|
+
const child = spawn2(process.execPath, [bin(), ...args], {
|
|
359
|
+
stdio: [opts.input === void 0 ? "inherit" : "pipe", opts.capture ? "pipe" : "inherit", "inherit"],
|
|
360
|
+
env: { ...process.env, WRANGLER_SEND_METRICS: "false" }
|
|
361
|
+
});
|
|
362
|
+
let out = "";
|
|
363
|
+
child.stdout?.on("data", (d) => out += d);
|
|
364
|
+
if (opts.input !== void 0) child.stdin.end(opts.input);
|
|
365
|
+
child.on("error", reject);
|
|
366
|
+
child.on("close", (code) => {
|
|
367
|
+
if (code === 0) resolve(out);
|
|
368
|
+
else reject(new UserError(`wrangler ${args.slice(0, 2).join(" ")} failed (exit ${code}).`));
|
|
369
|
+
});
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
function parseJson(out) {
|
|
373
|
+
const start = out.search(/[[{]/);
|
|
374
|
+
if (start === -1) throw new UserError("Unexpected output from wrangler.");
|
|
375
|
+
return JSON.parse(out.slice(start));
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// src/deploy.ts
|
|
379
|
+
var COMPAT_DATE = "2026-07-01";
|
|
380
|
+
var asset = (f) => new URL(`../assets/${f}`, import.meta.url).pathname;
|
|
381
|
+
var sha = (path) => createHash("sha256").update(readFileSync3(path)).digest("hex");
|
|
382
|
+
function writeDeployFiles(name, d1Id) {
|
|
383
|
+
const dir = deployDir();
|
|
384
|
+
mkdirSync2(join3(dir, "worker"), { recursive: true, mode: 448 });
|
|
385
|
+
copyFileSync(asset("worker.js"), join3(dir, "worker", "worker.js"));
|
|
386
|
+
copyFileSync(asset("schema.sql"), join3(dir, "schema.sql"));
|
|
387
|
+
const cfg = join3(dir, "wrangler.json");
|
|
388
|
+
writeFileSync2(
|
|
389
|
+
cfg,
|
|
390
|
+
JSON.stringify(
|
|
391
|
+
{
|
|
392
|
+
name,
|
|
393
|
+
main: "worker/worker.js",
|
|
394
|
+
compatibility_date: COMPAT_DATE,
|
|
395
|
+
no_bundle: true,
|
|
396
|
+
workers_dev: true,
|
|
397
|
+
// Request logs would hold paths and headers; Keybox writes its own audit log instead.
|
|
398
|
+
observability: { enabled: false },
|
|
399
|
+
d1_databases: [{ binding: "DB", database_name: name, database_id: d1Id }],
|
|
400
|
+
vars: { KEYBOX_SCRIPT_NAME: name, KEYBOX_D1_ID: d1Id }
|
|
401
|
+
},
|
|
402
|
+
null,
|
|
403
|
+
2
|
|
404
|
+
) + "\n"
|
|
405
|
+
);
|
|
406
|
+
return cfg;
|
|
407
|
+
}
|
|
408
|
+
async function findDb(name) {
|
|
409
|
+
const dbs = parseJson(await wrangler(["d1", "list", "--json"], { capture: true }));
|
|
410
|
+
return dbs.find((d) => d.name === name)?.uuid ?? null;
|
|
411
|
+
}
|
|
412
|
+
async function waitConfigured(url) {
|
|
413
|
+
for (let i = 0; i < 30; i++) {
|
|
414
|
+
try {
|
|
415
|
+
const r = await fetch(`${url}/_keybox/health`);
|
|
416
|
+
if (r.ok && (await r.json()).configured) return true;
|
|
417
|
+
} catch {
|
|
418
|
+
}
|
|
419
|
+
await new Promise((r) => setTimeout(r, 1e3));
|
|
420
|
+
}
|
|
421
|
+
return false;
|
|
422
|
+
}
|
|
423
|
+
async function init(opts) {
|
|
424
|
+
const { name } = opts;
|
|
425
|
+
if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name)) throw new UserError("--name must be lowercase letters, digits and dashes.");
|
|
426
|
+
if (loadConfig()) throw new UserError(`Already set up (${configPath()}). Use \`keybox deploy\` to upgrade.`);
|
|
427
|
+
step("Checking your Cloudflare login");
|
|
428
|
+
await wrangler(["whoami"]).catch(() => {
|
|
429
|
+
throw new UserError("Log in to Cloudflare first: npx wrangler login");
|
|
430
|
+
});
|
|
431
|
+
step(`Creating D1 database "${name}"`);
|
|
432
|
+
let d1Id = await findDb(name);
|
|
433
|
+
if (d1Id) note("Database already exists; reusing it.");
|
|
434
|
+
else {
|
|
435
|
+
await wrangler(["d1", "create", name]);
|
|
436
|
+
d1Id = await findDb(name);
|
|
437
|
+
}
|
|
438
|
+
if (!d1Id) throw new UserError("Could not find the D1 database after creating it.");
|
|
439
|
+
const cfg = writeDeployFiles(name, d1Id);
|
|
440
|
+
step("Applying schema");
|
|
441
|
+
await wrangler(["d1", "execute", name, "--remote", "--file", join3(deployDir(), "schema.sql"), "--config", cfg]);
|
|
442
|
+
step(`Deploying Worker "${name}"`);
|
|
443
|
+
const out = await wrangler(["deploy", "--config", cfg], { capture: true });
|
|
444
|
+
process.stderr.write(out);
|
|
445
|
+
const url = (opts.url ?? /https:\/\/[a-z0-9.-]+\.workers\.dev/.exec(out)?.[0])?.replace(/\/$/, "");
|
|
446
|
+
if (!url) throw new UserError("Deployed, but no workers.dev URL was printed. Re-run with --url https://\u2026");
|
|
447
|
+
step("Setting encryption key and admin token");
|
|
448
|
+
const existing = parseJson(
|
|
449
|
+
await wrangler(["secret", "list", "--config", cfg, "--format", "json"], { capture: true })
|
|
450
|
+
);
|
|
451
|
+
if (existing.some((s) => s.name === "KEYBOX_KEK")) {
|
|
452
|
+
note("This Worker already has an encryption key; keeping it.");
|
|
453
|
+
} else {
|
|
454
|
+
await wrangler(["secret", "put", "KEYBOX_KEK", "--config", cfg], { input: randomBytes(32).toString("base64") });
|
|
455
|
+
}
|
|
456
|
+
const adminToken = "kb_adm_" + randomBytes(32).toString("base64url");
|
|
457
|
+
const hash = createHash("sha256").update(adminToken).digest("hex");
|
|
458
|
+
await wrangler(["secret", "put", "KEYBOX_ADMIN_TOKEN_HASH", "--config", cfg], { input: hash });
|
|
459
|
+
saveConfig({ url, adminToken, name, d1Id });
|
|
460
|
+
step("Waiting for the new version to go live");
|
|
461
|
+
if (!await waitConfigured(url)) note("Not answering as configured yet; give it a minute, then run `keybox status`.");
|
|
462
|
+
process.stderr.write(`
|
|
463
|
+
Keybox is running at ${url}
|
|
464
|
+
The encryption key exists only inside the Worker. Your admin token is in ${configPath()} (mode 600).
|
|
465
|
+
|
|
466
|
+
Next:
|
|
467
|
+
keybox secrets add OPENAI_API_KEY
|
|
468
|
+
keybox agents create my-agent --allow "POST api.openai.com/v1/**"
|
|
469
|
+
keybox run my-agent -- python agent.py
|
|
470
|
+
`);
|
|
471
|
+
}
|
|
472
|
+
async function deploy(opts) {
|
|
473
|
+
const c = requireConfig();
|
|
474
|
+
if (!c.d1Id) throw new UserError("`keybox deploy` needs the config written by `keybox init`.");
|
|
475
|
+
const dir = deployDir();
|
|
476
|
+
const current = existsSync2(join3(dir, "worker", "worker.js")) ? sha(join3(dir, "worker", "worker.js")) : null;
|
|
477
|
+
const next = sha(asset("worker.js"));
|
|
478
|
+
if (current === next && !opts.force) {
|
|
479
|
+
note("The deployed Worker already matches this CLI version.");
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
process.stderr.write(`
|
|
483
|
+
This replaces the Worker that holds your keys.
|
|
484
|
+
deployed ${current ?? "(unknown)"}
|
|
485
|
+
new ${next}
|
|
486
|
+
The new code comes from this copy of @keybox/cli. Only continue if you trust it.
|
|
487
|
+
`);
|
|
488
|
+
if (!opts.yes && !await confirm("Deploy?")) throw new UserError("Cancelled.");
|
|
489
|
+
const cfg = writeDeployFiles(c.name, c.d1Id);
|
|
490
|
+
step("Applying schema");
|
|
491
|
+
await wrangler(["d1", "execute", c.name, "--remote", "--file", join3(dir, "schema.sql"), "--config", cfg]);
|
|
492
|
+
step("Deploying");
|
|
493
|
+
await wrangler(["deploy", "--config", cfg]);
|
|
494
|
+
note("Done.");
|
|
495
|
+
}
|
|
496
|
+
async function status() {
|
|
497
|
+
const c = requireConfig();
|
|
498
|
+
const health = await (await fetch(`${c.url}/_keybox/health`)).json();
|
|
499
|
+
const [secrets, agents] = await Promise.all([api("GET", "/secrets"), api("GET", "/agents")]);
|
|
500
|
+
process.stdout.write(
|
|
501
|
+
`url ${c.url}
|
|
502
|
+
version ${health.version}
|
|
503
|
+
configured ${health.configured}
|
|
504
|
+
secrets ${secrets.length}
|
|
505
|
+
agents ${agents.length}
|
|
506
|
+
`
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// src/index.ts
|
|
511
|
+
var HELP = `keybox: give AI agents access to your APIs without giving them your keys.
|
|
512
|
+
|
|
513
|
+
Setup
|
|
514
|
+
keybox init [--name keybox] [--url URL] Deploy Keybox to your Cloudflare account
|
|
515
|
+
keybox deploy [--yes] Upgrade the deployed Worker to this CLI's version
|
|
516
|
+
keybox status
|
|
517
|
+
|
|
518
|
+
Secrets (values are read from stdin or a hidden prompt, never from arguments)
|
|
519
|
+
keybox secrets add NAME [--preset openai|anthropic|github|stripe|cloudflare]
|
|
520
|
+
[--host HOST ... --header NAME --format bearer|raw|basic]
|
|
521
|
+
keybox secrets list
|
|
522
|
+
keybox secrets rm NAME
|
|
523
|
+
|
|
524
|
+
Agents
|
|
525
|
+
keybox agents create NAME --allow "GET api.github.com/repos/**" [--allow \u2026] [--deny \u2026]
|
|
526
|
+
keybox agents list
|
|
527
|
+
keybox agents rm NAME
|
|
528
|
+
keybox agents token NAME [--ttl 30d] Long-lived token for a deployed agent
|
|
529
|
+
keybox tokens revoke ID
|
|
530
|
+
|
|
531
|
+
Running
|
|
532
|
+
keybox run AGENT [--ttl 12h] [--clean-env] -- command [args]
|
|
533
|
+
keybox audit [--follow] [--limit 50]
|
|
534
|
+
keybox blocked Calls Keybox never proxies
|
|
535
|
+
`;
|
|
536
|
+
async function main(argv) {
|
|
537
|
+
const dash = argv.indexOf("--");
|
|
538
|
+
const args = dash === -1 ? argv : argv.slice(0, dash);
|
|
539
|
+
const rest = dash === -1 ? [] : argv.slice(dash + 1);
|
|
540
|
+
const { values: o, positionals: p } = parseArgs({
|
|
541
|
+
args,
|
|
542
|
+
allowPositionals: true,
|
|
543
|
+
options: {
|
|
544
|
+
name: { type: "string", default: "keybox" },
|
|
545
|
+
url: { type: "string" },
|
|
546
|
+
yes: { type: "boolean", short: "y", default: false },
|
|
547
|
+
force: { type: "boolean", default: false },
|
|
548
|
+
preset: { type: "string" },
|
|
549
|
+
host: { type: "string", multiple: true },
|
|
550
|
+
header: { type: "string" },
|
|
551
|
+
format: { type: "string" },
|
|
552
|
+
allow: { type: "string", multiple: true },
|
|
553
|
+
deny: { type: "string", multiple: true },
|
|
554
|
+
ttl: { type: "string" },
|
|
555
|
+
"clean-env": { type: "boolean", default: false },
|
|
556
|
+
follow: { type: "boolean", short: "f", default: false },
|
|
557
|
+
limit: { type: "string", default: "50" },
|
|
558
|
+
help: { type: "boolean", short: "h", default: false }
|
|
559
|
+
}
|
|
560
|
+
});
|
|
561
|
+
const [group, sub, arg] = p;
|
|
562
|
+
const need = (v, what) => {
|
|
563
|
+
if (!v) throw new UserError(`Missing ${what}. See keybox --help.`);
|
|
564
|
+
return v;
|
|
565
|
+
};
|
|
566
|
+
if (o.help || !group) return void process.stdout.write(HELP);
|
|
567
|
+
switch (`${group} ${["secrets", "agents", "tokens"].includes(group) ? sub ?? "" : ""}`.trim()) {
|
|
568
|
+
case "init":
|
|
569
|
+
return init({ name: o.name, url: o.url });
|
|
570
|
+
case "deploy":
|
|
571
|
+
return deploy({ yes: o.yes, force: o.force });
|
|
572
|
+
case "status":
|
|
573
|
+
return status();
|
|
574
|
+
case "secrets add":
|
|
575
|
+
return secretsAdd(need(arg, "secret name"), { preset: o.preset, host: o.host, header: o.header, format: o.format });
|
|
576
|
+
case "secrets list":
|
|
577
|
+
return secretsList();
|
|
578
|
+
case "secrets rm":
|
|
579
|
+
return secretsRm(need(arg, "secret name"));
|
|
580
|
+
case "agents create":
|
|
581
|
+
return agentsCreate(need(arg, "agent name"), { allow: o.allow, deny: o.deny });
|
|
582
|
+
case "agents list":
|
|
583
|
+
return agentsList();
|
|
584
|
+
case "agents rm":
|
|
585
|
+
return agentsRm(need(arg, "agent name"));
|
|
586
|
+
case "agents token":
|
|
587
|
+
return agentsToken(need(arg, "agent name"), { ttl: o.ttl ?? "30d" });
|
|
588
|
+
case "tokens revoke":
|
|
589
|
+
return tokensRevoke(need(arg, "token id"));
|
|
590
|
+
case "run":
|
|
591
|
+
return run(need(sub, "agent name"), rest, { ttl: o.ttl ?? "12h", cleanEnv: o["clean-env"] });
|
|
592
|
+
case "audit":
|
|
593
|
+
return audit({ follow: o.follow, limit: o.limit });
|
|
594
|
+
case "blocked":
|
|
595
|
+
return blocked();
|
|
596
|
+
default:
|
|
597
|
+
throw new UserError(`Unknown command: ${p.join(" ")}. See keybox --help.`);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
main(process.argv.slice(2)).catch((err) => {
|
|
601
|
+
if (err instanceof UserError || err instanceof Error && err.name === "TypeError" && "code" in err) {
|
|
602
|
+
process.stderr.write(`keybox: ${err.message}
|
|
603
|
+
`);
|
|
604
|
+
} else {
|
|
605
|
+
process.stderr.write(`keybox: unexpected error
|
|
606
|
+
${err instanceof Error ? err.stack : String(err)}
|
|
607
|
+
`);
|
|
608
|
+
}
|
|
609
|
+
process.exitCode = 1;
|
|
610
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@keyboxed/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Give AI agents access to your APIs without giving them your keys.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"keybox": "dist/keybox.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"assets"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "node build.mjs",
|
|
19
|
+
"test": "vitest run",
|
|
20
|
+
"typecheck": "tsc --noEmit",
|
|
21
|
+
"prepublishOnly": "npm run build -w @keybox/worker --prefix .. && npm run build"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"wrangler": "4.164.0"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@types/node": "26.6.6",
|
|
28
|
+
"esbuild": "0.28.2",
|
|
29
|
+
"miniflare": "4.20260730.0",
|
|
30
|
+
"typescript": "6.0.3",
|
|
31
|
+
"vitest": "5.1.1"
|
|
32
|
+
}
|
|
33
|
+
}
|