Open History to see the last commit
1/**
2 * Shared Doppler I/O and the remove list used by pull-secrets / push-secrets.
3 *
4 * Doppler is the source of truth. Every name in a config is synced except
5 * those matching {@link REMOVE_LIST} — today just the `DOPPLER_*` context
6 * vars Doppler injects to describe itself. Those are not application
7 * secrets; pushing them is how the deployed Worker ended up with three
8 * junk bindings.
9 *
10 * Values stay in memory in this module. Callers decide whether they ever
11 * hit disk (pull writes `.env.local`; push never does).
12 */
13import { spawnSync } from 'node:child_process'
14
15/** Names matching any of these are never pulled or pushed. */
16export const REMOVE_LIST: ReadonlyArray<RegExp> = [/^DOPPLER_/]
17
18/**
19 * Extra names push skips. `BETTER_AUTH_URL` is already a wrangler `vars`
20 * binding; a secret of the same name is rejected. Pull still writes it —
21 * local JWT audiences are origin-bound to `http://localhost:3100`.
22 */
23export const PUSH_REMOVE_LIST: ReadonlyArray<RegExp> = [
24 ...REMOVE_LIST,
25 /^BETTER_AUTH_URL$/,
26]
27
28export function isRemoved(
29 name: string,
30 list: ReadonlyArray<RegExp> = REMOVE_LIST,
31): boolean {
32 return list.some((pattern) => pattern.test(name))
33}
34
35/** Drop remove-listed names and empty values. */
36export function withoutRemoved(
37 secrets: Record<string, string>,
38 list: ReadonlyArray<RegExp> = REMOVE_LIST,
39): Record<string, string> {
40 const kept: Record<string, string> = {}
41 for (const [name, value] of Object.entries(secrets)) {
42 if (!isRemoved(name, list) && value !== '') kept[name] = value
43 }
44 return kept
45}
46
47export function parseConfigFlag(argv: Array<string>, fallback: string): string {
48 const index = argv.indexOf('--config')
49 if (index === -1) return fallback
50 return argv[index + 1] ?? fallback
51}
52
53export function run(
54 command: string,
55 commandArgs: Array<string>,
56 stdin?: string,
57): string {
58 const result = spawnSync(command, commandArgs, {
59 input: stdin,
60 encoding: 'utf8',
61 // Inherit stderr so auth prompts and errors are visible, but capture
62 // stdout so secret payloads never reach the terminal.
63 stdio: ['pipe', 'pipe', 'inherit'],
64 })
65 if (result.status !== 0) {
66 throw new Error(`${command} ${commandArgs[0] ?? ''} failed`)
67 }
68 return result.stdout
69}
70
71/** Every secret in the Doppler config. Held in memory; never persisted. */
72export function dopplerSecrets(config: string): Record<string, string> {
73 const raw = run('doppler', [
74 'secrets',
75 'download',
76 '--no-file',
77 '--format',
78 'json',
79 '--config',
80 config,
81 ])
82 return JSON.parse(raw) as Record<string, string>
83}
84
85export function parseEnvFile(text: string): Record<string, string> {
86 const out: Record<string, string> = {}
87 for (const rawLine of text.split(/\r?\n/)) {
88 const line = rawLine.trim()
89 if (line === '' || line.startsWith('#')) continue
90 const eq = line.indexOf('=')
91 if (eq <= 0) continue
92 const key = line.slice(0, eq)
93 if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue
94 out[key] = decodeEnvValue(line.slice(eq + 1))
95 }
96 return out
97}
98
99export function formatEnvFile(
100 secrets: Record<string, string>,
101 header: Array<string>,
102): string {
103 const lines = header.map((line) => `# ${line}`)
104 if (lines.length > 0) lines.push('')
105 for (const name of Object.keys(secrets).sort()) {
106 const value = secrets[name]
107 if (value === undefined) continue
108 lines.push(`${name}=${encodeEnvValue(value)}`)
109 }
110 return lines.join('\n') + '\n'
111}
112
113function encodeEnvValue(value: string): string {
114 if (/^[A-Za-z0-9_./:@%+=-]*$/.test(value)) return value
115 if (!value.includes("'")) return `'${value}'`
116 return `"${value
117 .replace(/\\/g, '\\\\')
118 .replace(/"/g, '\\"')
119 .replace(/\n/g, '\\n')
120 .replace(/\$/g, '\\$')}"`
121}
122
123function decodeEnvValue(raw: string): string {
124 if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) {
125 return raw.slice(1, -1)
126 }
127 if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) {
128 return raw
129 .slice(1, -1)
130 .replace(/\\n/g, '\n')
131 .replace(/\\\$/g, '$')
132 .replace(/\\"/g, '"')
133 .replace(/\\\\/g, '\\')
134 }
135 return raw
136}