Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

secrets.ts

150 lines4.5 KB

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. `VITE_*` variables are
21 * consumed at build time, so pushing runtime bindings cannot configure them.
22 * Pull still writes these values —
23 * local JWT audiences are origin-bound to `http://localhost:3100`.
24 */
25export const PUSH_REMOVE_LIST: ReadonlyArray<RegExp> = [
26 ...REMOVE_LIST,
27 /^BETTER_AUTH_URL$/,
28 /^VITE_/,
30​
31/** Only explicitly public Vite configuration belongs in a browser build. */
32export function publicBuildEnv(
33 secrets: Record<string, string>,
34): Record<string, string> {
35 return Object.fromEntries(
36 Object.entries(secrets).filter(
37 ([name, value]) => name.startsWith('VITE_PUBLIC_') && value !== '',
38 ),
39 )
41​
42export function isRemoved(
43 name: string,
44 list: ReadonlyArray<RegExp> = REMOVE_LIST,
45): boolean {
46 return list.some((pattern) => pattern.test(name))
48​
49/** Drop remove-listed names and empty values. */
50export function withoutRemoved(
51 secrets: Record<string, string>,
52 list: ReadonlyArray<RegExp> = REMOVE_LIST,
53): Record<string, string> {
54 const kept: Record<string, string> = {}
55 for (const [name, value] of Object.entries(secrets)) {
56 if (!isRemoved(name, list) && value !== '') kept[name] = value
57 }
58 return kept
60​
61export function parseConfigFlag(argv: Array<string>, fallback: string): string {
62 const index = argv.indexOf('--config')
63 if (index === -1) return fallback
64 return argv[index + 1] ?? fallback
66​
67export function run(
68 command: string,
69 commandArgs: Array<string>,
70 stdin?: string,
71): string {
72 const result = spawnSync(command, commandArgs, {
73 input: stdin,
74 encoding: 'utf8',
75 // Inherit stderr so auth prompts and errors are visible, but capture
76 // stdout so secret payloads never reach the terminal.
77 stdio: ['pipe', 'pipe', 'inherit'],
78 })
79 if (result.status !== 0) {
80 throw new Error(`${command} ${commandArgs[0] ?? ''} failed`)
81 }
82 return result.stdout
84​
85/** Every secret in the Doppler config. Held in memory; never persisted. */
86export function dopplerSecrets(config: string): Record<string, string> {
87 const raw = run('doppler', [
88 'secrets',
89 'download',
90 '--no-file',
91 '--format',
92 'json',
93 '--config',
94 config,
95 ])
96 return JSON.parse(raw) as Record<string, string>
98​
99export function parseEnvFile(text: string): Record<string, string> {
100 const out: Record<string, string> = {}
101 for (const rawLine of text.split(/\r?\n/)) {
102 const line = rawLine.trim()
103 if (line === '' || line.startsWith('#')) continue
104 const eq = line.indexOf('=')
105 if (eq <= 0) continue
106 const key = line.slice(0, eq)
107 if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue
108 out[key] = decodeEnvValue(line.slice(eq + 1))
109 }
110 return out
112​
113export function formatEnvFile(
114 secrets: Record<string, string>,
115 header: Array<string>,
116): string {
117 const lines = header.map((line) => `# ${line}`)
118 if (lines.length > 0) lines.push('')
119 for (const name of Object.keys(secrets).sort()) {
120 const value = secrets[name]
121 if (value === undefined) continue
122 lines.push(`${name}=${encodeEnvValue(value)}`)
123 }
124 return lines.join('\n') + '\n'
126​
127function encodeEnvValue(value: string): string {
128 if (/^[A-Za-z0-9_./:@%+=-]*$/.test(value)) return value
129 if (!value.includes("'")) return `'${value}'`
130 return `"${value
131 .replace(/\\/g, '\\\\')
132 .replace(/"/g, '\\"')
133 .replace(/\n/g, '\\n')
134 .replace(/\$/g, '\\$')}"`
136​
137function decodeEnvValue(raw: string): string {
138 if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) {
139 return raw.slice(1, -1)
140 }
141 if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) {
142 return raw
143 .slice(1, -1)
144 .replace(/\\n/g, '\n')
145 .replace(/\\\$/g, '$')
146 .replace(/\\"/g, '"')
147 .replace(/\\\\/g, '\\')
148 }
149 return raw