-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.ts
More file actions
593 lines (553 loc) · 18.6 KB
/
Copy pathmain.ts
File metadata and controls
593 lines (553 loc) · 18.6 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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
import { config } from 'dotenv'
// Load env files in Next.js precedence order. dotenv's default behavior is to
// not overwrite vars that are already set, so loading .env.local first means
// its values win over .env for the same keys. Users can still set anything in
// the real environment to override both.
//
// `quiet: true` suppresses dotenv v17's `injected env (N) from …` banner,
// which it now prints to stdout on every `config()` call. Without it the CLI
// emits four noisy, non-deterministic banner lines (with rotating tips) ahead
// of its own output on every invocation — restoring the silent behaviour of
// dotenv v16.
config({ path: '.env.local', quiet: true })
config({ path: '.env.development.local', quiet: true })
config({ path: '.env.development', quiet: true })
config({ path: '.env', quiet: true })
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import * as p from '@clack/prompts'
import { CliExit } from '../cli/exit.js'
import { renderCommandHelp } from '../cli/help.js'
// Commands that depend on @cipherstash/stack are lazy-loaded in the switch below.
import {
authCommand,
dbStatusCommand,
envCommand,
implCommand,
initCommand,
installCommand,
manifestCommand,
planCommand,
statusCommand,
telemetryCommand,
testConnectionCommand,
upgradeCommand,
wizardCommand,
} from '../commands/index.js'
import { messages } from '../messages.js'
import { pinnedSpec } from '../runtime-versions.js'
import {
classifyCommand,
classifyErrorType,
} from '../telemetry/classify-command.js'
import {
initTelemetry,
maybeShowFirstRunNotice,
shutdownTelemetry,
trackCommand,
} from '../telemetry/index.js'
function isModuleNotFound(err: unknown): boolean {
return (
err instanceof Error &&
'code' in err &&
(err as { code: string }).code === 'ERR_MODULE_NOT_FOUND'
)
}
import {
detectPackageManager,
prodInstallCommand,
runnerCommand,
} from '../commands/init/utils.js'
const __dirname = dirname(fileURLToPath(import.meta.url))
const pkg = JSON.parse(
readFileSync(join(__dirname, '../../package.json'), 'utf-8'),
)
// Detect once, share across help rendering and the requireStack hint.
// Detection reads `npm_config_user_agent` (when the user invoked via
// `bunx`/`pnpm dlx`/`yarn dlx`) and falls back to the lockfile in cwd.
const PM = detectPackageManager()
const STASH = runnerCommand(PM, 'stash')
async function requireStack<T>(importFn: () => Promise<T>): Promise<T> {
try {
return await importFn()
} catch (err: unknown) {
if (isModuleNotFound(err)) {
p.log.error(
`@cipherstash/stack is required for this command.
Install it with: ${prodInstallCommand(PM, pinnedSpec('@cipherstash/stack'))}
Or run: ${STASH} init`,
)
throw new CliExit(1)
}
throw err
}
}
const HELP = `
${messages.cli.versionBannerPrefix}${pkg.version}
${messages.cli.usagePrefix}${STASH} <command> [options]
Commands:
init Initialize CipherStash for your project
plan Draft a reviewable encryption plan at .cipherstash/plan.md
impl Execute the plan with a local agent
status Displays implementation status
auth <subcommand> Authenticate with CipherStash
wizard AI-guided encryption setup (reads your codebase)
doctor Diagnose install problems (native binaries, runtime)
manifest Print the structured, versioned command surface (--json for docs/agents)
telemetry <sub> Manage anonymous usage analytics (status, enable, disable)
eql install Scaffold stash.config.ts (if missing) and install EQL extensions
eql migration Generate an EQL v3 install migration for your ORM (Drizzle)
eql upgrade Upgrade EQL extensions to the latest version
eql status Show EQL installation status
db push (EQL v2 + Proxy) Push encryption schema to eql_v2_configuration
db activate (EQL v2 + Proxy) Promote pending → active without renames
db validate Validate encryption schema
db migrate Run pending encrypt config migrations
db test-connection Test database connectivity
schema build Build an encryption schema from your database
encrypt status Show per-column migration status (phase, progress, drift)
encrypt plan Diff intent (.cipherstash/migrations.json) vs observed state
encrypt backfill Resumably encrypt plaintext into the encrypted column
encrypt cutover Rename swap encrypted → primary column (EQL v2 only)
encrypt drop Generate a migration to drop the plaintext column
env Mint deployment credentials and print them as env vars
Options:
--help, -h Show help
--version, -v Show version
Run \`${STASH} <command> --help\` for a command's flags and examples
(e.g. \`${STASH} eql install --help\`, \`${STASH} auth login --help\`).
Examples:
${STASH} init # set up CipherStash in this project
${STASH} auth login # authenticate
${STASH} eql install # install EQL extensions
${STASH} manifest --json # structured command surface for docs / agents
`.trim()
interface ParsedArgs {
command: string | undefined
subcommand: string | undefined
commandArgs: string[]
flags: Record<string, boolean>
values: Record<string, string>
}
function parseArgs(argv: string[]): ParsedArgs {
const args = argv.slice(2)
const command = args[0]
const subcommand = args[1] && !args[1].startsWith('-') ? args[1] : undefined
const rest = args.slice(subcommand ? 2 : 1)
const flags: Record<string, boolean> = {}
const values: Record<string, string> = {}
const commandArgs: string[] = []
for (let i = 0; i < rest.length; i++) {
const arg = rest[i]
if (arg.startsWith('--')) {
const key = arg.slice(2)
const nextArg = rest[i + 1]
if (nextArg !== undefined && !nextArg.startsWith('-')) {
values[key] = nextArg
i++
} else {
flags[key] = true
}
} else if (arg === '-h') {
// Short aliases for the two global boolean flags, normalized to their
// long-form keys so downstream `flags.help` / `flags.version` checks catch
// `stash <command> -h` too (not just a bare `stash -h`).
flags.help = true
} else if (arg === '-v') {
flags.version = true
} else {
commandArgs.push(arg)
}
}
return { command, subcommand, commandArgs, flags, values }
}
async function runInstall(
flags: Record<string, boolean>,
values: Record<string, string>,
) {
await installCommand({
force: flags.force,
dryRun: flags['dry-run'],
supabase: flags.supabase,
excludeOperatorFamily: flags['exclude-operator-family'],
drizzle: flags.drizzle,
latest: flags.latest,
name: values.name,
out: values.out,
migration: flags.migration,
direct: flags.direct,
migrationsDir: values['migrations-dir'],
eqlVersion: values['eql-version'],
databaseUrl: values['database-url'],
// An explicit `--database-url` is a one-shot install against that DB — leave
// the project untouched. Otherwise offer to scaffold a config for later.
scaffoldConfig: values['database-url'] !== undefined ? 'skip' : 'offer',
})
}
async function runUpgrade(
flags: Record<string, boolean>,
values: Record<string, string>,
) {
await upgradeCommand({
dryRun: flags['dry-run'],
supabase: flags.supabase,
excludeOperatorFamily: flags['exclude-operator-family'],
latest: flags.latest,
eqlVersion: values['eql-version'],
databaseUrl: values['database-url'],
})
}
async function runEqlCommand(
sub: string | undefined,
flags: Record<string, boolean>,
values: Record<string, string>,
) {
switch (sub) {
case 'install':
await runInstall(flags, values)
break
case 'migration': {
const { eqlMigrationCommand } = await import(
'../commands/eql/migration.js'
)
await eqlMigrationCommand({
drizzle: flags.drizzle,
prisma: flags.prisma,
supabase: flags.supabase,
name: values.name,
out: values.out,
dryRun: flags['dry-run'],
})
break
}
case 'upgrade':
await runUpgrade(flags, values)
break
case 'status':
await dbStatusCommand({ databaseUrl: values['database-url'] })
break
default:
p.log.error(`${messages.eql.unknownSubcommand}: ${sub ?? '(none)'}`)
console.log()
console.log(HELP)
throw new CliExit(1)
}
}
async function runDbCommand(
sub: string | undefined,
flags: Record<string, boolean>,
values: Record<string, string>,
) {
// Plumbed through every db subcommand so the URL resolver can use it as
// an explicit override. See packages/cli/src/config/database-url.ts.
const databaseUrl = values['database-url']
switch (sub) {
// Deprecated aliases — these commands moved to the `eql` group. Keep the
// old spellings working so existing scripts and published docs don't
// break.
case 'install':
p.log.warn(messages.db.aliasDeprecated(STASH, 'install'))
await runInstall(flags, values)
break
case 'upgrade':
p.log.warn(messages.db.aliasDeprecated(STASH, 'upgrade'))
await runUpgrade(flags, values)
break
case 'push': {
const { pushCommand } = await requireStack(
() => import('../commands/db/push.js'),
)
await pushCommand({ dryRun: flags['dry-run'], databaseUrl })
break
}
case 'activate': {
const { activateCommand } = await requireStack(
() => import('../commands/db/activate.js'),
)
await activateCommand({ databaseUrl })
break
}
case 'validate': {
const { validateCommand } = await requireStack(
() => import('../commands/db/validate.js'),
)
await validateCommand({
supabase: flags.supabase,
excludeOperatorFamily: flags['exclude-operator-family'],
databaseUrl,
})
break
}
case 'status':
p.log.warn(messages.db.aliasDeprecated(STASH, 'status'))
await dbStatusCommand({ databaseUrl })
break
case 'test-connection':
await testConnectionCommand({ databaseUrl })
break
case 'migrate':
p.log.warn(messages.db.migrateNotImplemented(STASH))
break
default:
p.log.error(`${messages.db.unknownSubcommand}: ${sub ?? '(none)'}`)
console.log()
console.log(HELP)
throw new CliExit(1)
}
}
async function runEncryptCommand(
sub: string | undefined,
flags: Record<string, boolean>,
values: Record<string, string>,
) {
switch (sub) {
case 'status': {
const { statusCommand } = await requireStack(
() => import('../commands/encrypt/status.js'),
)
await statusCommand()
break
}
case 'plan': {
const { planCommand } = await requireStack(
() => import('../commands/encrypt/plan.js'),
)
await planCommand()
break
}
case 'backfill': {
const table = requireValue(values, 'table')
const column = requireValue(values, 'column')
const { backfillCommand } = await requireStack(
() => import('../commands/encrypt/backfill.js'),
)
await backfillCommand({
table,
column,
pkColumn: values['pk-column'],
chunkSize: values['chunk-size']
? Number(values['chunk-size'])
: undefined,
encryptedColumn: values['encrypted-column'],
schemaColumnKey: values['schema-column-key'],
confirmDualWritesDeployed: flags['confirm-dual-writes-deployed'],
force: flags.force,
})
break
}
case 'cutover': {
const table = requireValue(values, 'table')
const column = requireValue(values, 'column')
const { cutoverCommand } = await requireStack(
() => import('../commands/encrypt/cutover.js'),
)
await cutoverCommand({
table,
column,
proxyUrl: values['proxy-url'],
migrationsDir: values['migrations-dir'],
})
break
}
case 'drop': {
const table = requireValue(values, 'table')
const column = requireValue(values, 'column')
const { dropCommand } = await requireStack(
() => import('../commands/encrypt/drop.js'),
)
await dropCommand({
table,
column,
migrationsDir: values['migrations-dir'],
})
break
}
default:
p.log.error(`Unknown encrypt subcommand: ${sub ?? '(none)'}`)
console.log()
console.log(HELP)
throw new CliExit(1)
}
}
function requireValue(values: Record<string, string>, key: string): string {
const v = values[key]
if (!v) {
p.log.error(`Missing required --${key} value.`)
throw new CliExit(1)
}
return v
}
async function runSchemaCommand(
sub: string | undefined,
flags: Record<string, boolean>,
values: Record<string, string>,
) {
switch (sub) {
case 'build': {
const { builderCommand } = await requireStack(
() => import('../commands/schema/build.js'),
)
await builderCommand({
supabase: flags.supabase,
databaseUrl: values['database-url'],
})
break
}
default:
p.log.error(`Unknown schema subcommand: ${sub ?? '(none)'}`)
console.log()
console.log(HELP)
throw new CliExit(1)
}
}
// The CLI body. Loaded by the thin launcher in stash.ts via dynamic import so
// that a missing native binary (evaluated when this module's command graph
// loads) surfaces as friendly guidance rather than a raw stack trace.
export async function run() {
const { command, subcommand, commandArgs, flags, values } = parseArgs(
process.argv,
)
if (!command || command === '--help' || command === '-h') {
console.log(HELP)
return
}
if (command === '--version' || command === '-v' || flags.version) {
console.log(pkg.version)
return
}
// `stash <command> --help` / `-h`: render command-specific help from the
// descriptor registry (e.g. `stash eql --help`, `stash eql install --help`).
// Falls back to the global banner when the command path matches no descriptor.
if (flags.help) {
const path = subcommand ? `${command} ${subcommand}` : command
console.log(renderCommandHelp(path, STASH) ?? HELP)
return
}
// Anonymous, opt-out usage analytics. The notice shows once (to stderr) and
// the run that shows it sends nothing; both are no-ops when telemetry is off.
initTelemetry(pkg.version)
maybeShowFirstRunNotice(STASH)
const startedAt = Date.now()
let success = true
let errorType: string | undefined
let exitCode: number | undefined
// Outcomes are tracked for commands that RETURN, THROW, or throw CliExit (the
// cooperative exit used by main.ts's own helpers and the outermost cancel
// handlers — see cli/exit.ts). Deep `process.exit()` calls terminate without
// an event by design: intercepting them globally proved unsafe (clack exits
// from keypress handlers; broad catches swallowed the signal).
try {
await dispatch(command, subcommand, commandArgs, flags, values)
} catch (err) {
if (err instanceof CliExit) {
exitCode = err.code
success = err.code === 0
} else {
success = false
errorType = classifyErrorType(err)
// Rethrow to bootstrap's handler ("Fatal error" + exit 1). The finally
// below still runs — including the awaited flush — before propagation.
throw err
}
} finally {
// Coerce command/subcommand to a known vocabulary before emit so a free-text
// positional (e.g. a `stash wizard "<prompt>"` description) never leaves.
const safe = classifyCommand(command, subcommand)
trackCommand({
command: safe.command,
subcommand: safe.subcommand,
success,
durationMs: Date.now() - startedAt,
errorType,
})
await shutdownTelemetry()
}
if (exitCode !== undefined) process.exit(exitCode)
}
async function dispatch(
command: string,
subcommand: string | undefined,
commandArgs: string[],
flags: Record<string, boolean>,
values: Record<string, string>,
) {
switch (command) {
case 'init':
await initCommand(flags, values)
break
case 'plan':
await planCommand(flags, values)
break
case 'impl':
await implCommand(flags, values)
break
case 'status':
await statusCommand({
quest: flags.quest,
plain: flags.plain,
json: flags.json,
})
break
case 'auth': {
const authArgs = subcommand ? [subcommand, ...commandArgs] : commandArgs
await authCommand(authArgs, flags, values)
break
}
case 'eql':
await runEqlCommand(subcommand, flags, values)
break
case 'db':
await runDbCommand(subcommand, flags, values)
break
case 'encrypt':
await runEncryptCommand(subcommand, flags, values)
break
case 'schema':
await runSchemaCommand(subcommand, flags, values)
break
case 'env':
await envCommand({
// parseArgs puts `--write path/x` in values and bare `--write` in
// flags — accept both so a path after --write targets that file
// instead of silently printing secrets to stdout.
write: values.write ?? flags.write,
json: flags.json,
name: values.name,
// `--name` followed by another flag (or nothing) is booleanised by
// parseArgs; surface it as its own error instead of missing_name.
nameMissingValue: flags.name === true,
// `stash env my-app` would otherwise vanish into `subcommand`.
unexpectedArg: subcommand ?? commandArgs[0],
})
break
case 'manifest':
// Pure metadata (no native code) — safe to run anywhere, including when
// the native binary is missing.
manifestCommand({ json: flags.json, version: pkg.version })
break
case 'telemetry':
await telemetryCommand(subcommand)
break
case 'wizard': {
// Forward everything after `stash wizard` verbatim. The wizard package
// owns its own flag parsing; we don't try to interpret its surface
// here so it can evolve independently.
const wizardArgs = process.argv.slice(3)
await wizardCommand(wizardArgs)
break
}
case 'doctor': {
// Normally intercepted by the launcher before this module loads (so it
// works even when the native binary is missing); handled here too so the
// command still runs if run() is invoked directly.
const { doctorCommand } = await import('../commands/doctor/index.js')
await doctorCommand()
break
}
default:
console.error(`${messages.cli.unknownCommand}: ${command}\n`)
console.log(HELP)
throw new CliExit(1)
}
}