-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
393 lines (355 loc) Β· 13.8 KB
/
index.ts
File metadata and controls
393 lines (355 loc) Β· 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#!/usr/bin/env node
import { Command } from "commander";
import { readFileSync } from "fs";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
import { runInit, killActiveChild } from "./commands/init.js";
import { runLogin } from "./commands/login.js";
import {
runProjectsList,
runProjectsCreate,
runProjectsDelete,
} from "./commands/projects.js";
import {
runEnvironmentsList,
runEnvironmentsCreate,
runEnvironmentsDelete,
} from "./commands/environments.js";
import {
runSecretsList,
runSecretsGet,
runSecretsSet,
runSecretsDelete,
runUpload,
runDownload,
runRun,
killActiveRunChild,
} from "./commands/secrets.js";
import {
runKeysList,
runKeysCreate,
runKeysRevoke,
runKeysUpdate,
} from "./commands/keys.js";
import { readConfig } from "./config.js";
import { error, warn } from "./output/log.js";
import { makeDebug } from "./debug.js";
const program = new Command();
const debug = makeDebug("index");
let cachedDefaultConfig: ReturnType<typeof readConfig> | undefined;
function readDefaultConfig(): ReturnType<typeof readConfig> {
if (!cachedDefaultConfig) {
cachedDefaultConfig = readConfig();
}
return cachedDefaultConfig;
}
debug("argv=%o", process.argv.slice(2));
debug("DEBUG=%s", process.env.DEBUG ?? "<unset>");
const __dirname = dirname(fileURLToPath(import.meta.url));
const pkg = JSON.parse(
readFileSync(join(__dirname, "..", "package.json"), "utf-8"),
);
program
.name("kfl")
.description("Keyflare β open-source secrets manager on Cloudflare")
.version(pkg.version)
.allowExcessArguments(false)
.showHelpAfterError(true);
// βββ kfl init ββββββββββββββββββββββββββββββββββββββββββββββββ
program
.command("init")
.description(
"Bootstrap a new Keyflare deployment on Cloudflare. " +
"Supports OAuth (browser) and API token authentication."
)
.option("-y, --yes", "Skip confirmation prompts (auto-accept)")
.option(
"--name <name>",
"Worker and database name (default: keyflare). Must be alphanumeric with hyphens, max 63 chars."
)
.option(
"--d1id <uuid>",
"Bind to an existing D1 database by UUID. If not provided, a new database is created automatically."
)
.option(
"--master-key <key>",
"Custom master key (base64-encoded 256-bit key). If not provided, a random key is generated. " +
"Example: K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols="
)
.action(async (opts) => {
await runInit(opts).catch(handleError);
});
// βββ kfl login βββββββββββββββββββββββββββββββββββββββββββββββ
program
.command("login")
.description(
"Log in to an existing Keyflare deployment. " +
"Prompts for the API URL and your API key."
)
.action(async () => {
await runLogin().catch(handleError);
});
// βββ kfl projects ββββββββββββββββββββββββββββββββββββββββββββ
const projects = program
.command("projects")
.description("Manage projects")
.action(() => projects.help());
projects
.command("list")
.description("List all projects")
.action(async () => {
await runProjectsList().catch(handleError);
});
projects
.command("create <name>")
.description("Create a new project")
.option(
"--environmentless",
"Create project without default dev/prod environments",
)
.action(async (name: string, opts) => {
await runProjectsCreate(name, opts).catch(handleError);
});
projects
.command("delete <name>")
.description("Delete a project and all its environments and secrets")
.option("--force", "Skip confirmation prompt")
.action(async (name: string, opts) => {
await runProjectsDelete(name, opts).catch(handleError);
});
// βββ kfl environments (alias: env) βββββββββββββββββββββββββββββ
const environments = program
.command("environments")
.alias("env")
.description("Manage environments within a project")
.action(() => environments.help());
environments
.command("list")
.description("List all environments in a project")
.requiredOption("--project <name>", "Project name", resolveProject())
.action(async (opts) => {
await runEnvironmentsList(opts.project).catch(handleError);
});
environments
.command("create <name>")
.description("Create a new environment in a project")
.requiredOption("--project <name>", "Project name", resolveProject())
.action(async (name: string, opts) => {
await runEnvironmentsCreate(name, opts.project).catch(handleError);
});
environments
.command("delete <name>")
.description("Delete an environment and all its secrets")
.requiredOption("--project <name>", "Project name", resolveProject())
.option("--force", "Skip confirmation prompt")
.action(async (name: string, opts) => {
await runEnvironmentsDelete(name, opts.project, opts).catch(handleError);
});
// βββ kfl secrets βββββββββββββββββββββββββββββββββββββββββββββ
const secrets = program
.command("secrets")
.description("Manage secrets within an environment")
.action(() => secrets.help());
secrets
.command("list")
.description("List secret keys (values hidden)")
.requiredOption("--project <name>", "Project name", resolveProject())
.requiredOption("--env <name>", "Environment name", resolveEnvironment())
.action(async (opts) => {
await runSecretsList(opts.project, opts.env).catch(handleError);
});
secrets
.command("get <key>")
.description("Print a single secret value to stdout")
.requiredOption("--project <name>", "Project name", resolveProject())
.requiredOption("--env <name>", "Environment name", resolveEnvironment())
.action(async (key: string, opts) => {
await runSecretsGet(key, opts.project, opts.env).catch(handleError);
});
secrets
.command("set <pairs...>")
.description("Set one or more secrets (KEY=VALUE ...)")
.requiredOption("--project <name>", "Project name", resolveProject())
.requiredOption("--env <name>", "Environment name", resolveEnvironment())
.action(async (pairs: string[], opts) => {
await runSecretsSet(pairs, opts.project, opts.env).catch(handleError);
});
secrets
.command("delete <key>")
.description("Delete a secret")
.requiredOption("--project <name>", "Project name", resolveProject())
.requiredOption("--env <name>", "Environment name", resolveEnvironment())
.action(async (key: string, opts) => {
await runSecretsDelete(key, opts.project, opts.env).catch(handleError);
});
secrets
.command("upload <file>")
.description(
"Upload a .env file β REPLACES all secrets in the target environment"
)
.requiredOption("--project <name>", "Project name", resolveProject())
.requiredOption("--env <name>", "Environment name", resolveEnvironment())
.option("--force", "Skip confirmation prompt")
.action(async (file: string, opts) => {
await runUpload(file, opts.project, opts.env, opts).catch(handleError);
});
secrets
.command("download")
.description("Download secrets to stdout or a file")
.requiredOption("--project <name>", "Project name", resolveProject())
.requiredOption("--env <name>", "Environment name", resolveEnvironment())
.option("--format <fmt>", "Output format: env, json, yaml, shell", "env")
.option("--output <file>", "Write to file instead of stdout")
.action(async (opts) => {
await runDownload(opts.project, opts.env, opts).catch(handleError);
});
// βββ Deprecated aliases: kfl upload/download ββββββββββββββββ
program
.command("upload <file>", { hidden: true })
.description(
"Upload a .env file β REPLACES all secrets in the target environment"
)
.requiredOption("--project <name>", "Project name", resolveProject())
.requiredOption("--env <name>", "Environment name", resolveEnvironment())
.option("--force", "Skip confirmation prompt")
.action(async (file: string, opts: { project: string; env: string; force?: boolean }) => {
warn("`kfl upload` is deprecated; use `kfl secrets upload`");
await runUpload(file, opts.project, opts.env, opts).catch(handleError);
});
program
.command("download", { hidden: true })
.description("Download secrets to stdout or a file")
.requiredOption("--project <name>", "Project name", resolveProject())
.requiredOption("--env <name>", "Environment name", resolveEnvironment())
.option("--format <fmt>", "Output format: env, json, yaml, shell", "env")
.option("--output <file>", "Write to file instead of stdout")
.action(async (opts: { project: string; env: string; format?: string; output?: string }) => {
warn("`kfl download` is deprecated; use `kfl secrets download`");
await runDownload(opts.project, opts.env, opts).catch(handleError);
});
// βββ kfl run βββββββββββββββββββββββββββββββββββββββββββββββββ
program
.command("run")
.description(
"Run a command with secrets injected as environment variables.\n\n" +
" The command is executed via the shell, so $VAR references, pipes,\n" +
" redirects, and && chains all work as expected.\n\n" +
" Example:\n" +
" kfl run --project my-api --env Prod -- echo $MYSECRET"
)
.requiredOption("--project <name>", "Project name", resolveProject())
.requiredOption("--env <name>", "Environment name", resolveEnvironment())
.allowUnknownOption()
.argument("[cmd...]", "Command and arguments (after --)")
.action(async (cmd: string[], opts: { project: string; env: string }) => {
await runRun(opts.project, opts.env, cmd).catch(handleError);
});
// βββ kfl keys ββββββββββββββββββββββββββββββββββββββββββββββββ
const keys = program
.command("keys")
.description("Manage API keys")
.action(() => keys.help());
keys
.command("list")
.description("List all API keys")
.action(async () => {
await runKeysList().catch(handleError);
});
keys
.command("create")
.description(
"Create a new API key.\n\n" +
"USER KEYS (kfl_user_*) β Full admin access.\n" +
" - Can manage all projects, environments, secrets, and other API keys.\n" +
" - No scoping required β has access to everything.\n" +
" - Required flags: --type user --label <label>\n\n" +
"SYSTEM KEYS (kfl_sys_*) β Scoped access for CI/CD and automation.\n" +
" - Can only access specific project/environment combinations.\n" +
" - Required flags: --type system --label <label> --scope <project:env> --permission <read|readwrite>\n" +
" - Use --scope multiple times for multiple project:env pairs.\n" +
' - Use * as environment wildcard (e.g., --scope "my-api:*")'
)
.requiredOption("--type <type>", "Key type: user or system")
.requiredOption("--label <label>", "Human-readable label")
.option(
"--scope <scope>",
"Scope for system keys: project:environment (repeatable). Required for system keys.",
collect,
[]
)
.option(
"--permission <perm>",
"Permission for system keys: read or readwrite. Required for system keys."
)
.action(async (opts) => {
await runKeysCreate(opts).catch(handleError);
});
keys
.command("revoke <prefix>")
.description("Revoke an API key by its prefix")
.action(async (prefix: string) => {
await runKeysRevoke(prefix).catch(handleError);
});
keys
.command("put <prefix>")
.description(
"Update the scopes and permission of a system key.\n\n" +
"This replaces ALL existing scopes with the new set. Use `kfl keys list` to see current scopes.\n\n" +
"Examples:\n" +
' kfl keys put kfl_sys_abc123 --scope "my-api:production" --permission read\n' +
' kfl keys put kfl_sys_abc123 --scope "my-api:*" --scope "frontend:*" --permission readwrite'
)
.requiredOption(
"--scope <scope>",
"Scope: project:environment (repeatable). Replaces all existing scopes.",
collect,
[]
)
.requiredOption(
"--permission <perm>",
"Permission: read or readwrite"
)
.action(async (prefix: string, opts) => {
await runKeysUpdate(prefix, opts).catch(handleError);
});
// βββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββ
/** Read project default from env or config file (used as Commander default). */
function resolveProject(): string | undefined {
if (process.env.KEYFLARE_PROJECT) return process.env.KEYFLARE_PROJECT;
return readDefaultConfig().project;
}
/** Read environment default from env or config file. */
function resolveEnvironment(): string | undefined {
if (process.env.KEYFLARE_ENV) return process.env.KEYFLARE_ENV;
return readDefaultConfig().environment;
}
/** Collector for repeatable options (--scope a --scope b β [a, b]). */
function collect(val: string, prev: string[]): string[] {
return prev.concat(val);
}
function handleError(err: unknown) {
debug("command failed: %o", err);
if (err instanceof Error) {
error(err.message);
} else {
error(String(err));
}
process.exit(1);
}
// Clean exit on Ctrl+C.
//
// When run via `pnpm kfl β¦`, pnpm/tsx intercept SIGINT before our
// process.on("SIGINT") handler ever fires. Work around this by killing
// active child processes directly.
process.on("SIGINT", () => {
killActiveChild();
killActiveRunChild();
// Show cursor (ora hides it)
process.stderr.write("\x1B[?25h");
process.exit(130);
});
// Show help (exit 0) when no arguments are provided
if (process.argv.length <= 2) {
program.help();
}
program.parse();