slatebox 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.
@@ -0,0 +1,204 @@
1
+ // Kubernetes objects for one Slatebox, rendered in code (one source of truth
2
+ // for `install k8s`, `export --format manifests` and `export --format helm`).
3
+ //
4
+ // One pod, one replica: MongoDB runs inside it. Data on a ReadWriteOnce
5
+ // volume. Backups by a sidecar that shares the pod's network and /run/slatebox
6
+ // with Slatebox, runs the image's own `slatebox backup` once a day and keeps
7
+ // the last N on a second volume. No liveness probe: a restore pauses the app on
8
+ // purpose, and the image's supervisor already ends the container when any of
9
+ // its services dies.
10
+ import { createHash } from 'node:crypto'
11
+ import { hasRegistry, isTag } from '../image.mjs'
12
+
13
+ export const MANAGER = 'slatebox-installer'
14
+
15
+ export function labels(answers) {
16
+ return {
17
+ 'app.kubernetes.io/name': 'slatebox',
18
+ 'app.kubernetes.io/instance': answers.name,
19
+ 'app.kubernetes.io/managed-by': MANAGER,
20
+ 'slatebox.com/install': answers.name,
21
+ }
22
+ }
23
+
24
+ const selector = answers => ({ 'app.kubernetes.io/name': 'slatebox', 'app.kubernetes.io/instance': answers.name })
25
+
26
+ export const names = answers => ({
27
+ set: answers.name,
28
+ service: answers.name,
29
+ config: `${answers.name}-config`,
30
+ secret: `${answers.name}-env`,
31
+ script: `${answers.name}-backup-script`,
32
+ backups: `${answers.name}-backups`,
33
+ record: `${answers.name}-install`,
34
+ tls: `${answers.name}-tls`,
35
+ pod: `${answers.name}-0`,
36
+ })
37
+
38
+ const meta = (answers, name, extra = {}) => ({ name, namespace: answers.k8s.namespace, labels: labels(answers), ...extra })
39
+
40
+ export const BACKUP_SCRIPT = `#!/bin/bash
41
+ # Daily backups of the Slatebox in this pod, kept on the backups volume.
42
+ # backup-loop.sh wait for BACKUP_AT (HH:MM, UTC) every day
43
+ # backup-loop.sh --once one backup now, then exit
44
+ set -u
45
+ dir=/backups
46
+ keep=\${BACKUP_KEEP:-14}
47
+ once() {
48
+ local file="$dir/slatebox-$(date -u +%Y%m%d-%H%M%S).gz"
49
+ if /opt/slatebox/bin/slatebox backup > "$file.part"; then
50
+ mv "$file.part" "$file"
51
+ echo "[backups] $(date -u +%FT%TZ) wrote $file"
52
+ else
53
+ rm -f "$file.part"
54
+ echo "[backups] $(date -u +%FT%TZ) the backup failed; the previous ones are kept" >&2
55
+ fi
56
+ ls -1t "$dir"/slatebox-*.gz 2>/dev/null | tail -n +$((keep + 1)) | xargs -r rm -f
57
+ }
58
+ if [[ \${1:-} == --once ]]; then once; exit; fi
59
+ while :; do
60
+ now=$(date -u +%s)
61
+ next=$(date -u -d "today \${BACKUP_AT:-03:00}" +%s)
62
+ ((next > now)) || next=$(date -u -d "tomorrow \${BACKUP_AT:-03:00}" +%s)
63
+ sleep $((next - now))
64
+ once
65
+ done
66
+ `
67
+
68
+ function backupAt(schedule) {
69
+ const [minute, hour] = schedule.split(' ')
70
+ return `${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`
71
+ }
72
+
73
+ /**
74
+ * @param {object} answers resolved answers (target k8s, or export with manifests/helm)
75
+ * @param {{image: string, env: Record<string,string>, secretsHash?: string, record: string}} options
76
+ */
77
+ export function renderK8s(answers, { image, env, secretsHash = '', record }) {
78
+ // A digest is the same bytes on every node. A registry tag can move, and with IfNotPresent each
79
+ // node would keep whichever build it pulled first: pull a tag every start instead. A local tag
80
+ // (loaded into kind or minikube, no registry) can only be used as it is.
81
+ const imagePullPolicy = isTag(image) && hasRegistry(image) ? 'Always' : 'IfNotPresent'
82
+ const n = names(answers)
83
+ const backups = answers.backups.to !== 'off'
84
+ const objects = []
85
+ objects.push({ apiVersion: 'v1', kind: 'Namespace', metadata: { name: answers.k8s.namespace, labels: labels(answers) } })
86
+ objects.push({ apiVersion: 'v1', kind: 'ConfigMap', metadata: meta(answers, n.config), data: { ...env } })
87
+ if (backups) {
88
+ objects.push({ apiVersion: 'v1', kind: 'ConfigMap', metadata: meta(answers, n.script), data: { 'backup-loop.sh': BACKUP_SCRIPT } })
89
+ objects.push({
90
+ apiVersion: 'v1', kind: 'PersistentVolumeClaim', metadata: meta(answers, n.backups),
91
+ spec: {
92
+ accessModes: ['ReadWriteOnce'],
93
+ ...(answers.k8s.storageClass ? { storageClassName: answers.k8s.storageClass } : {}),
94
+ resources: { requests: { storage: answers.size.storage } },
95
+ },
96
+ })
97
+ }
98
+ const configHash = createHash('sha256').update(JSON.stringify(env)).update(secretsHash).digest('hex').slice(0, 16)
99
+ const restricted = { allowPrivilegeEscalation: false, capabilities: { drop: ['ALL'] } }
100
+ const health = { exec: { command: ['/opt/slatebox/bin/slatebox', 'health'] }, timeoutSeconds: 10 }
101
+ const app = {
102
+ name: 'slatebox',
103
+ image,
104
+ imagePullPolicy,
105
+ ports: [{ name: 'http', containerPort: 7070 }],
106
+ envFrom: [{ configMapRef: { name: n.config } }, { secretRef: { name: n.secret } }],
107
+ volumeMounts: [{ name: 'data', mountPath: '/data' }, { name: 'run', mountPath: '/run/slatebox' }],
108
+ startupProbe: { ...health, periodSeconds: 5, failureThreshold: 120 },
109
+ readinessProbe: { ...health, periodSeconds: 10, failureThreshold: 3 },
110
+ resources: { requests: { memory: answers.size.memory, cpu: answers.size.cpu }, limits: { memory: answers.size.memory } },
111
+ securityContext: restricted,
112
+ }
113
+ const containers = [app]
114
+ const volumes = [{ name: 'run', emptyDir: {} }]
115
+ if (backups) {
116
+ containers.push({
117
+ name: 'backups',
118
+ image,
119
+ imagePullPolicy,
120
+ command: ['/bin/bash', '/opt/slatebox-backup/backup-loop.sh'],
121
+ env: [{ name: 'BACKUP_AT', value: backupAt(answers.backups.schedule) }, { name: 'BACKUP_KEEP', value: String(answers.backups.keep) }],
122
+ volumeMounts: [
123
+ { name: 'data', mountPath: '/data' }, { name: 'run', mountPath: '/run/slatebox' },
124
+ { name: 'backups', mountPath: '/backups' }, { name: 'backup-script', mountPath: '/opt/slatebox-backup', readOnly: true },
125
+ ],
126
+ resources: { requests: { memory: '64Mi', cpu: '10m' }, limits: { memory: '1Gi' } },
127
+ securityContext: restricted,
128
+ })
129
+ volumes.push({ name: 'backups', persistentVolumeClaim: { claimName: n.backups } })
130
+ volumes.push({ name: 'backup-script', configMap: { name: n.script, defaultMode: 365 } })
131
+ }
132
+ objects.push({
133
+ apiVersion: 'apps/v1', kind: 'StatefulSet', metadata: meta(answers, n.set),
134
+ spec: {
135
+ serviceName: n.service,
136
+ replicas: 1,
137
+ selector: { matchLabels: selector(answers) },
138
+ template: {
139
+ metadata: { labels: labels(answers), annotations: { 'slatebox.com/config-hash': configHash } },
140
+ spec: {
141
+ // Service links would add SLATEBOX_SERVICE_HOST and the like, which the
142
+ // image refuses as unknown settings.
143
+ enableServiceLinks: false,
144
+ terminationGracePeriodSeconds: 60,
145
+ securityContext: { runAsUser: 10001, runAsGroup: 10001, fsGroup: 10001, runAsNonRoot: true, seccompProfile: { type: 'RuntimeDefault' } },
146
+ containers,
147
+ volumes,
148
+ },
149
+ },
150
+ volumeClaimTemplates: [{
151
+ metadata: { name: 'data', labels: labels(answers) },
152
+ spec: {
153
+ accessModes: ['ReadWriteOnce'],
154
+ ...(answers.k8s.storageClass ? { storageClassName: answers.k8s.storageClass } : {}),
155
+ resources: { requests: { storage: answers.size.storage } },
156
+ },
157
+ }],
158
+ },
159
+ })
160
+ objects.push({
161
+ apiVersion: 'v1', kind: 'Service', metadata: meta(answers, n.service),
162
+ spec: { type: 'ClusterIP', selector: selector(answers), ports: [{ name: 'http', port: 7070, targetPort: 'http' }] },
163
+ })
164
+ const host = answers.address.url ? new URL(answers.address.url).hostname : null
165
+ if (answers.k8s.route === 'ingress') {
166
+ const annotations = {}
167
+ if (answers.k8s.tlsIssuer) {
168
+ annotations[answers.k8s.tlsIssuer.kind === 'Issuer' ? 'cert-manager.io/issuer' : 'cert-manager.io/cluster-issuer'] = answers.k8s.tlsIssuer.name
169
+ }
170
+ if (/nginx/.test(answers.k8s.ingressClass || '')) {
171
+ // Live editing keeps one WebSocket open for as long as a slate is open.
172
+ annotations['nginx.ingress.kubernetes.io/proxy-read-timeout'] = '3600'
173
+ annotations['nginx.ingress.kubernetes.io/proxy-send-timeout'] = '3600'
174
+ annotations['nginx.ingress.kubernetes.io/proxy-body-size'] = '50m'
175
+ }
176
+ objects.push({
177
+ apiVersion: 'networking.k8s.io/v1', kind: 'Ingress', metadata: meta(answers, answers.name, { annotations }),
178
+ spec: {
179
+ ...(answers.k8s.ingressClass ? { ingressClassName: answers.k8s.ingressClass } : {}),
180
+ ...(answers.k8s.tlsIssuer ? { tls: [{ hosts: [host], secretName: n.tls }] } : {}),
181
+ rules: [{ host, http: { paths: [{ path: '/', pathType: 'Prefix', backend: { service: { name: n.service, port: { number: 7070 } } } }] } }],
182
+ },
183
+ })
184
+ } else if (answers.k8s.route === 'gateway') {
185
+ const [namespace, name] = answers.k8s.gatewayRef.split('/')
186
+ objects.push({
187
+ apiVersion: 'gateway.networking.k8s.io/v1', kind: 'HTTPRoute', metadata: meta(answers, answers.name),
188
+ spec: {
189
+ parentRefs: [{ name, namespace }],
190
+ hostnames: [host],
191
+ rules: [{ matches: [{ path: { type: 'PathPrefix', value: '/' } }], backendRefs: [{ name: n.service, port: 7070 }] }],
192
+ },
193
+ })
194
+ }
195
+ objects.push({ apiVersion: 'v1', kind: 'ConfigMap', metadata: meta(answers, n.record), data: { 'install.yaml': record } })
196
+ return objects
197
+ }
198
+
199
+ /** The Secret, with every secret value. Only ever sent to `kubectl apply -f -` on standard input. */
200
+ export function renderSecret(answers, values) {
201
+ return {
202
+ apiVersion: 'v1', kind: 'Secret', metadata: meta(answers, names(answers).secret), type: 'Opaque', stringData: { ...values },
203
+ }
204
+ }
@@ -0,0 +1,59 @@
1
+ // The image's settings for a set of answers: plain settings (env, safe to
2
+ // show and to keep in a ConfigMap or slatebox.env) and secret references
3
+ // (secrets, resolved only when the secrets file or Secret is written).
4
+ // Settings the image does not list are left out with a warning, or refused
5
+ // when the person asked for what they turn on.
6
+ import { EXIT, InstallError } from '../errors.mjs'
7
+ import { aiEnv } from '../ai/settings-adapter.mjs'
8
+
9
+ /**
10
+ * @param {object} answers resolved answers
11
+ * @param {{settings: string[]}} caps what the image accepts
12
+ * @returns {{env: Record<string,string>, secrets: Record<string,string>, warnings: string[], notes: string[], hostGateway: boolean}}
13
+ */
14
+ export function settingsFor(answers, caps) {
15
+ const known = new Set(caps?.settings || [])
16
+ const env = {}
17
+ const secrets = {}
18
+ const warnings = []
19
+ const notes = []
20
+ const require = (name, what) => {
21
+ if (!known.has(name)) throw new InstallError(EXIT.PRECONDITION, `This Slatebox image does not support ${what} (it does not accept ${name}). Use a newer image, or leave ${what} off.`)
22
+ }
23
+ const k8s = answers.target === 'k8s' || Boolean(answers.k8s)
24
+
25
+ env.SLATEBOX_URL = answers.address.url
26
+ // Behind an Ingress or a Gateway, HTTPS ends at the edge.
27
+ if (k8s && answers.k8s?.route !== 'none' && answers.address.url?.startsWith('https:')) env.SLATEBOX_HTTPS = 'off'
28
+ if (answers.acmeCa) { require('SLATEBOX_ACME_CA', 'a custom certificate authority'); env.SLATEBOX_ACME_CA = answers.acmeCa }
29
+
30
+ if (answers.mail?.urlFrom) {
31
+ require('SLATEBOX_MAIL_URL', 'mail')
32
+ if (answers.mail.from) env.SLATEBOX_MAIL_FROM = answers.mail.from
33
+ }
34
+
35
+ if (answers.sso?.enabled) {
36
+ require('SLATEBOX_SSO', 'single sign-on')
37
+ env.SLATEBOX_SSO = 'keycloak'
38
+ if (answers.sso.only) { require('SLATEBOX_SSO_ONLY', 'single sign-on only'); env.SLATEBOX_SSO_ONLY = 'true' }
39
+ if (answers.sso.adminConsole === 'closed') { require('SLATEBOX_SSO_ADMIN', 'closing the Keycloak admin console'); env.SLATEBOX_SSO_ADMIN = 'closed' }
40
+ }
41
+
42
+ const ai = aiEnv(answers.ai, caps, { target: k8s ? 'k8s' : answers.target })
43
+ // A multi-provider image names one key variable per provider; those are not in its list.
44
+ for (const name of [...Object.keys(ai.env), ...Object.keys(ai.secrets).filter(name => !name.startsWith('SLATEBOX_AI_KEY_'))]) require(name, 'this AI setup')
45
+ Object.assign(env, ai.env)
46
+ notes.push(...ai.notes)
47
+
48
+ if (answers.settings && Object.keys(answers.settings).length) {
49
+ require('SLATEBOX_SETTINGS', 'extra settings')
50
+ env.SLATEBOX_SETTINGS = JSON.stringify(answers.settings)
51
+ }
52
+
53
+ if (known.has('SLATEBOX_KEY_ENCRYPTION_KEY')) secrets.SLATEBOX_KEY_ENCRYPTION_KEY = 'generate'
54
+ else warnings.push('This image does not accept SLATEBOX_KEY_ENCRYPTION_KEY, so people cannot save their own AI and call keys on it. A newer image can.')
55
+ Object.assign(secrets, ai.secrets)
56
+ if (answers.mail?.urlFrom) secrets.SLATEBOX_MAIL_URL = answers.mail.urlFrom
57
+
58
+ return { env, secrets, warnings, notes, hostGateway: ai.hostGateway }
59
+ }
package/src/runner.mjs ADDED
@@ -0,0 +1,50 @@
1
+ // Runs programs (docker, ssh, kubectl, crontab). Arguments never carry a
2
+ // secret, because anyone on the machine can read them with ps: secrets travel
3
+ // on standard input or in files with mode 0600.
4
+ import { spawn } from 'node:child_process'
5
+ import { createReadStream, createWriteStream } from 'node:fs'
6
+
7
+ /**
8
+ * @returns {(cmd: string, args: string[], options?: {input?: string|Buffer, inputFile?: string, outputFile?: string, timeout?: number, env?: object}) => Promise<{code: number, stdout: string, stderr: string}>}
9
+ */
10
+ export function makeRunner(out) {
11
+ return function run(cmd, args, { input, inputFile, outputFile, timeout = 15 * 60_000, env } = {}) {
12
+ out?.debug(`$ ${cmd} ${args.map(arg => (/^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`)).join(' ')}${inputFile ? ` < ${inputFile}` : ''}${outputFile ? ` > ${outputFile}` : ''}`)
13
+ return new Promise(resolve => {
14
+ let child
15
+ try {
16
+ child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'], env: env ? { ...process.env, ...env } : process.env })
17
+ } catch (error) {
18
+ resolve({ code: 127, stdout: '', stderr: String(error.message) })
19
+ return
20
+ }
21
+ const stdout = [], stderr = []
22
+ let sink = null
23
+ let failed = null
24
+ if (outputFile) {
25
+ sink = createWriteStream(outputFile, { mode: 0o600 })
26
+ child.stdout.pipe(sink)
27
+ } else {
28
+ child.stdout.on('data', chunk => stdout.push(chunk))
29
+ }
30
+ child.stderr.on('data', chunk => stderr.push(chunk))
31
+ const timer = setTimeout(() => { failed = 'timed out'; child.kill('SIGKILL') }, timeout)
32
+ child.on('error', error => { failed = error.code === 'ENOENT' ? `${cmd} is not installed` : error.message })
33
+ child.on('close', async code => {
34
+ clearTimeout(timer)
35
+ if (sink) await new Promise(done => (sink.closed ? done() : sink.on('close', done)))
36
+ const err = Buffer.concat(stderr).toString('utf8')
37
+ resolve({ code: failed ? (failed.endsWith('not installed') ? 127 : 124) : (code ?? 1), stdout: Buffer.concat(stdout).toString('utf8'), stderr: failed ? `${err}${failed}` : err })
38
+ })
39
+ child.stdin.on('error', () => {})
40
+ if (inputFile) createReadStream(inputFile).on('error', () => child.stdin.end()).pipe(child.stdin)
41
+ else child.stdin.end(input ?? '')
42
+ })
43
+ }
44
+ }
45
+
46
+ /** Quote one argument for a POSIX shell (the remote side of ssh joins its arguments into one command line). */
47
+ export function shq(value) {
48
+ const text = String(value)
49
+ return /^[\w@%+=:,./-]+$/.test(text) ? text : `'${text.replace(/'/g, `'\\''`)}'`
50
+ }
@@ -0,0 +1,40 @@
1
+ // Turn the secrets an install needs (variable -> reference) into values, once,
2
+ // right before they are written to the secrets file or the Kubernetes Secret.
3
+ // A value already stored for the install is kept unless its reference can be
4
+ // read now (so an upgrade never needs the admin's environment again), and the
5
+ // key encryption key is never generated twice.
6
+ import { EXIT, InstallError } from './errors.mjs'
7
+ import { generateKek, looksLikeKey, resolveRef } from './secrets.mjs'
8
+
9
+ // A reference is printed in messages, unless it looks like a key typed in its place.
10
+ const shown = ref => (ref.startsWith('env:') && looksLikeKey(ref.slice(4)) ? 'a variable name that looks like a key' : ref)
11
+
12
+ /**
13
+ * @param {Record<string,string>} wanted variable -> reference or 'generate'
14
+ * @param {Record<string,string>} stored values already stored for this install
15
+ * @returns {Promise<{values: Record<string,string>, generated: string[]}>}
16
+ */
17
+ export async function secretValues(ctx, wanted, stored = {}) {
18
+ const values = {}
19
+ const generated = []
20
+ const missing = []
21
+ for (const [name, ref] of Object.entries(wanted)) {
22
+ if (ref === 'generate') {
23
+ if (stored[name]) values[name] = stored[name]
24
+ else {
25
+ values[name] = generateKek()
26
+ generated.push(name)
27
+ }
28
+ } else {
29
+ const ask = ctx.interactive && ctx.prompt ? () => ctx.prompt.secret(`Value for ${name} (not shown)`) : undefined
30
+ const value = (ref === 'prompt' && stored[name]) ? stored[name] : (await resolveRef(ref, { env: ctx.env, ask })) ?? stored[name]
31
+ if (value) values[name] = value
32
+ else missing.push({ field: name, question: `${name} comes from ${shown(ref)}, which is empty or unreadable`, flag: ref.startsWith('env:') && shown(ref) === ref ? `export ${ref.slice(4)}=…` : shown(ref), default: null })
33
+ }
34
+ ctx.redactor.add(values[name])
35
+ }
36
+ if (missing.length) {
37
+ throw new InstallError(EXIT.NEEDS_INPUT, `Some keys could not be read: ${missing.map(item => `${item.field} (${shown(wanted[item.field])})`).join(', ')}. Set them and run again.`, { missing })
38
+ }
39
+ return { values, generated }
40
+ }
@@ -0,0 +1,119 @@
1
+ // Secrets: the key encryption key the installer generates, references to keys
2
+ // the admin supplies (env:NAME, file:/path, prompt), env files compose reads
3
+ // literally, and the redaction filter every line of output passes through.
4
+ import { randomBytes } from 'node:crypto'
5
+ import { readFile } from 'node:fs/promises'
6
+ import { InstallError } from './errors.mjs'
7
+
8
+ /** SLATEBOX_KEY_ENCRYPTION_KEY: 32 random bytes in standard base64, as `openssl rand -base64 32` prints. */
9
+ export function generateKek() {
10
+ return randomBytes(32).toString('base64')
11
+ }
12
+
13
+ export const REF = /^(env:[A-Za-z_][A-Za-z0-9_]*|file:.+|prompt|none|stored)$/
14
+
15
+ // Prefixes that API keys and tokens start with (and AWS access key IDs).
16
+ const KEY_PREFIX = /^(gsk_|ghp_|gho_|ghu_|ghs_|ghr_|github_pat_|glpat|hf_|r8_|xox[abprs]|sk_|rk_|pk_live|pk_test|nvapi|AKIA[0-9A-Z]{12}|ASIA[0-9A-Z]{12})/
17
+
18
+ /**
19
+ * Does something given as the NAME of an environment variable look like a key
20
+ * pasted by mistake? Variable names are words; keys are long runs of mixed case
21
+ * and digits. Callers never repeat the value in their message.
22
+ */
23
+ export function looksLikeKey(name) {
24
+ const text = String(name)
25
+ if (KEY_PREFIX.test(text)) return true
26
+ if (text.length >= 20 && /[a-z]/.test(text) && /[A-Z]/.test(text) && /[0-9]/.test(text)) return true
27
+ if (text.length >= 40 && !text.includes('_')) return true
28
+ return false
29
+ }
30
+
31
+ export function isRef(value) {
32
+ return typeof value === 'string' && REF.test(value)
33
+ }
34
+
35
+ /**
36
+ * The value a reference points at, or undefined when it cannot be read now
37
+ * (unset variable, missing file, nobody to ask). A literal is refused: secrets
38
+ * are given by reference so that answers files and records never hold them.
39
+ */
40
+ export async function resolveRef(ref, { env = process.env, ask } = {}) {
41
+ if (!isRef(ref)) throw new InstallError(2, 'A key must be given as a reference (env:NAME, file:/path or prompt), never as its value.')
42
+ if (ref === 'none' || ref === 'stored') return undefined
43
+ if (ref === 'prompt') return ask ? ask() : undefined
44
+ if (ref.startsWith('env:')) {
45
+ const value = env[ref.slice(4)]
46
+ return value ? value : undefined
47
+ }
48
+ const path = ref.slice(5).replace(/^~(?=\/)/, env.HOME || '')
49
+ try {
50
+ const value = (await readFile(path, 'utf8')).replace(/\r?\n$/, '')
51
+ return value || undefined
52
+ } catch {
53
+ return undefined
54
+ }
55
+ }
56
+
57
+ // ------------------------------------------------------------ env files
58
+ // Values are single-quoted, which Docker Compose reads literally (no $
59
+ // interpolation, no escapes). A value compose cannot hold that way is refused.
60
+
61
+ export function envFileText(values, header = '') {
62
+ const lines = header ? header.split('\n').map(line => `# ${line}`) : []
63
+ for (const [name, value] of Object.entries(values)) {
64
+ if (value === undefined || value === null) continue
65
+ const text = String(value)
66
+ if (text.includes("'") || /[\r\n]/.test(text)) {
67
+ throw new InstallError(2, `${name} contains a single quote or a line break, which an env file cannot hold literally. Percent-encode it (a quote is %27 in a URL).`)
68
+ }
69
+ lines.push(`${name}='${text}'`)
70
+ }
71
+ return lines.join('\n') + '\n'
72
+ }
73
+
74
+ export function parseEnvFile(text) {
75
+ const out = {}
76
+ for (const line of String(text).split(/\r?\n/)) {
77
+ if (!line.trim() || line.trimStart().startsWith('#')) continue
78
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line.trim())
79
+ if (!match) continue
80
+ let value = match[2]
81
+ if (value.startsWith("'") && value.endsWith("'") && value.length >= 2) value = value.slice(1, -1)
82
+ else if (value.startsWith('"') && value.endsWith('"') && value.length >= 2) value = JSON.parse(value)
83
+ out[match[1]] = value
84
+ }
85
+ return out
86
+ }
87
+
88
+ // ------------------------------------------------------------ redaction
89
+
90
+ const MIN_SECRET = 6
91
+
92
+ /** Every secret the installer has seen is replaced by *** in anything it prints or logs. */
93
+ export class Redactor {
94
+ constructor() {
95
+ this.values = new Set()
96
+ }
97
+
98
+ add(value) {
99
+ if (typeof value !== 'string' || value.length < MIN_SECRET) return
100
+ for (const form of [value, encodeURIComponent(value), JSON.stringify(value).slice(1, -1), Buffer.from(value).toString('base64')]) {
101
+ if (form.length >= MIN_SECRET) this.values.add(form)
102
+ }
103
+ // A URL's password on its own (mail URLs carry one).
104
+ try {
105
+ const url = new URL(value)
106
+ if (url.password) this.add(decodeURIComponent(url.password))
107
+ if (url.password) this.add(url.password)
108
+ } catch { /* not a URL */ }
109
+ }
110
+
111
+ redact(text) {
112
+ let out = String(text)
113
+ // Longest first, so a value that contains another is removed whole.
114
+ for (const value of [...this.values].sort((a, b) => b.length - a.length)) {
115
+ if (out.includes(value)) out = out.split(value).join('***')
116
+ }
117
+ return out
118
+ }
119
+ }