slatebox 0.0.0-stage → 0.2.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.
- package/LICENSE.md +21 -0
- package/README.md +231 -2
- package/bin/slatebox.mjs +9 -0
- package/package.json +44 -4
- package/src/agent-prompt.mjs +79 -0
- package/src/ai/settings-adapter.mjs +198 -0
- package/src/answers.mjs +513 -0
- package/src/cli.mjs +711 -0
- package/src/cloud.mjs +261 -0
- package/src/errors.mjs +23 -0
- package/src/image.mjs +141 -0
- package/src/interview.mjs +199 -0
- package/src/move.mjs +447 -0
- package/src/output.mjs +51 -0
- package/src/plan.mjs +51 -0
- package/src/prompt.mjs +87 -0
- package/src/record.mjs +46 -0
- package/src/render/compose.mjs +47 -0
- package/src/render/helm.mjs +78 -0
- package/src/render/k8s.mjs +204 -0
- package/src/render/settings.mjs +67 -0
- package/src/runner.mjs +50 -0
- package/src/secret-values.mjs +45 -0
- package/src/secrets.mjs +124 -0
- package/src/setup-link.mjs +88 -0
- package/src/targets/address.mjs +281 -0
- package/src/targets/docker.mjs +797 -0
- package/src/targets/export.mjs +73 -0
- package/src/targets/hosts.mjs +202 -0
- package/src/targets/k8s.mjs +405 -0
- package/src/yaml.mjs +293 -0
package/src/record.mjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// The install record: the resolved answers of a successful install (secret
|
|
2
|
+
// references stay references), plus what the installer needs for upgrades.
|
|
3
|
+
// On this computer it lives in ~/.slatebox/installs/<name>/install.yaml; an
|
|
4
|
+
// SSH install keeps the same file on the server, and Kubernetes keeps it in a
|
|
5
|
+
// ConfigMap. Every target also keeps a copy here, so `slatebox status` and
|
|
6
|
+
// `upgrade` know where each install is.
|
|
7
|
+
import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
8
|
+
import { homedir } from 'node:os'
|
|
9
|
+
import { join } from 'node:path'
|
|
10
|
+
import { parse, stringify } from './yaml.mjs'
|
|
11
|
+
|
|
12
|
+
export function slateboxHome(env = process.env, flag) {
|
|
13
|
+
return flag || env.SLATEBOX_INSTALL_HOME || join(env.HOME || homedir(), '.slatebox')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const installDir = (home, name) => join(home, 'installs', name)
|
|
17
|
+
export const recordPath = (home, name) => join(installDir(home, name), 'install.yaml')
|
|
18
|
+
|
|
19
|
+
export function readRecord(home, name) {
|
|
20
|
+
const path = recordPath(home, name)
|
|
21
|
+
if (!existsSync(path)) return null
|
|
22
|
+
return parse(readFileSync(path, 'utf8'))
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function recordText(record) {
|
|
26
|
+
return `# The slatebox installer's record of the install "${record.name}". It holds no secrets.\n${stringify(record)}`
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Write atomically, readable only by this user (it names where the secrets are). */
|
|
30
|
+
export function writeRecord(home, record) {
|
|
31
|
+
const dir = installDir(home, record.name)
|
|
32
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
33
|
+
const path = recordPath(home, record.name)
|
|
34
|
+
writeFileSync(`${path}.tmp`, recordText(record), { mode: 0o600 })
|
|
35
|
+
renameSync(`${path}.tmp`, path)
|
|
36
|
+
chmodSync(path, 0o600)
|
|
37
|
+
return path
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function listRecords(home) {
|
|
41
|
+
const dir = join(home, 'installs')
|
|
42
|
+
if (!existsSync(dir)) return []
|
|
43
|
+
return readdirSync(dir).sort().map(name => {
|
|
44
|
+
try { return readRecord(home, name) } catch { return { name, state: 'unreadable' } }
|
|
45
|
+
}).filter(Boolean)
|
|
46
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// The Docker Compose file for this computer and for a server over SSH. It is
|
|
2
|
+
// also what `slatebox install export --format compose` writes.
|
|
3
|
+
import { stringify } from '../yaml.mjs'
|
|
4
|
+
|
|
5
|
+
export const COMPOSE_FILE = 'compose.yaml'
|
|
6
|
+
export const SETTINGS_FILE = 'slatebox.env'
|
|
7
|
+
export const SECRETS_FILE = 'secrets.env'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Published ports. This computer publishes on 127.0.0.1 unless --listen says
|
|
11
|
+
* otherwise: Docker's port rules go around host firewalls such as ufw, so a
|
|
12
|
+
* bare "7070:7070" on a VPS would put the first-account page on the internet.
|
|
13
|
+
*/
|
|
14
|
+
export function ports(answers) {
|
|
15
|
+
if (answers.address.port === null) return ['80:80', '443:443']
|
|
16
|
+
const listen = answers.address.listen && !['0.0.0.0', '::'].includes(answers.address.listen) ? `${answers.address.listen.includes(':') ? `[${answers.address.listen}]` : answers.address.listen}:` : ''
|
|
17
|
+
return [`${listen}${answers.address.port}:7070`]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The host port of a published mapping ("127.0.0.1:7070:7070" -> 7070). */
|
|
21
|
+
export const hostPort = mapping => Number(mapping.split(':').at(-2))
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {object} answers
|
|
25
|
+
* @param {{image: string, hostGateway?: boolean, pullPolicy?: string|null}} options image: an immutable
|
|
26
|
+
* reference (repo@sha256:… or an image ID). pullPolicy null for exported files, where compose must pull.
|
|
27
|
+
*/
|
|
28
|
+
export function renderCompose(answers, { image, hostGateway = false, pullPolicy = 'never' }) {
|
|
29
|
+
const service = {
|
|
30
|
+
image,
|
|
31
|
+
container_name: answers.name,
|
|
32
|
+
restart: 'unless-stopped',
|
|
33
|
+
// The installer pulls (or loads) the image itself before it starts anything,
|
|
34
|
+
// so an upgrade never fetches behind its back. Exported files leave it out.
|
|
35
|
+
...(pullPolicy ? { pull_policy: pullPolicy } : {}),
|
|
36
|
+
ports: ports(answers),
|
|
37
|
+
volumes: ['data:/data'],
|
|
38
|
+
env_file: [SETTINGS_FILE, SECRETS_FILE],
|
|
39
|
+
labels: { 'com.slatebox.install': answers.name, 'app.kubernetes.io/managed-by': 'slatebox-installer' },
|
|
40
|
+
}
|
|
41
|
+
if (hostGateway) service.extra_hosts = ['host.docker.internal:host-gateway']
|
|
42
|
+
const compose = { name: answers.name, services: { slatebox: service }, volumes: { data: { name: `${answers.name}-data` } } }
|
|
43
|
+
return `# Written by the slatebox installer for the install "${answers.name}".
|
|
44
|
+
# Change it with \`npx slatebox install --name ${answers.name} ...\` (or \`slatebox ai ...\`) rather than by hand:
|
|
45
|
+
# the installer keeps its answers in install.yaml and writes this file again.
|
|
46
|
+
${stringify(compose)}`
|
|
47
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// `export --format helm`: the same objects renderK8s makes, wrapped as a chart
|
|
2
|
+
// for GitOps. The objects are rendered once with marker values, and each
|
|
3
|
+
// marker becomes a template expression, so the chart cannot drift from what
|
|
4
|
+
// `install k8s` applies. The Secret is not in the chart: it names an existing
|
|
5
|
+
// one (create it with your secret manager, or from secret.example.yaml).
|
|
6
|
+
import { names, renderK8s } from './k8s.mjs'
|
|
7
|
+
import { stringify } from '../yaml.mjs'
|
|
8
|
+
|
|
9
|
+
const MARK = {
|
|
10
|
+
image: '__SBX_IMAGE__', namespace: '__SBX_NAMESPACE__', memory: '__SBX_MEMORY__', cpu: '__SBX_CPU__',
|
|
11
|
+
storage: '__SBX_STORAGE__', host: '__sbx-host__.invalid', secret: '__SBX_SECRET__', storageClass: '__SBX_STORAGE_CLASS__',
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const EXPR = {
|
|
15
|
+
[MARK.image]: '{{ .Values.image | quote }}',
|
|
16
|
+
[MARK.namespace]: '{{ .Release.Namespace | quote }}',
|
|
17
|
+
[MARK.memory]: '{{ .Values.resources.memory | quote }}',
|
|
18
|
+
[MARK.cpu]: '{{ .Values.resources.cpu | quote }}',
|
|
19
|
+
[MARK.storage]: '{{ .Values.storage.size | quote }}',
|
|
20
|
+
[MARK.host]: '{{ .Values.host | quote }}',
|
|
21
|
+
[MARK.secret]: '{{ .Values.existingSecret | quote }}',
|
|
22
|
+
[MARK.storageClass]: '{{ .Values.storage.className | quote }}',
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function templated(object) {
|
|
26
|
+
let text = stringify(object)
|
|
27
|
+
for (const [mark, expression] of Object.entries(EXPR)) text = text.split(mark).join(expression)
|
|
28
|
+
return text
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @returns {Record<string, string>} chart files by path, relative to the chart directory
|
|
33
|
+
*/
|
|
34
|
+
export function renderHelmChart(answers, { image, env, version, appVersion }) {
|
|
35
|
+
const n = names(answers)
|
|
36
|
+
const host = answers.address.url ? new URL(answers.address.url).hostname : null
|
|
37
|
+
const marked = structuredClone(answers)
|
|
38
|
+
marked.k8s = { ...marked.k8s, namespace: MARK.namespace, storageClass: answers.k8s.storageClass ? MARK.storageClass : null }
|
|
39
|
+
marked.size = { memory: MARK.memory, cpu: MARK.cpu, storage: MARK.storage }
|
|
40
|
+
if (answers.k8s.route !== 'none') marked.address = { url: `https://${MARK.host}` }
|
|
41
|
+
const objects = renderK8s(marked, { image: MARK.image, env: {}, record: '' })
|
|
42
|
+
.filter(object => object.kind !== 'Namespace' && object.metadata.name !== n.record && object.metadata.name !== n.config)
|
|
43
|
+
const files = {}
|
|
44
|
+
files['Chart.yaml'] = stringify({
|
|
45
|
+
apiVersion: 'v2', name: 'slatebox', description: 'Slatebox: the app, live collaboration and its database in one pod.',
|
|
46
|
+
type: 'application', version, appVersion: String(appVersion),
|
|
47
|
+
})
|
|
48
|
+
const values = {
|
|
49
|
+
image,
|
|
50
|
+
host,
|
|
51
|
+
existingSecret: n.secret,
|
|
52
|
+
resources: { memory: answers.size.memory, cpu: answers.size.cpu },
|
|
53
|
+
storage: { size: answers.size.storage, className: answers.k8s.storageClass || '' },
|
|
54
|
+
settings: { ...env },
|
|
55
|
+
}
|
|
56
|
+
files['values.yaml'] = `# Values for the Slatebox chart, written by \`slatebox install export --format helm\`.\n# The Secret "${n.secret}" must exist: see secret.example.yaml next to this chart.\n${stringify(values)}`
|
|
57
|
+
files['templates/configmap.yaml'] = `apiVersion: v1
|
|
58
|
+
kind: ConfigMap
|
|
59
|
+
metadata:
|
|
60
|
+
name: ${n.config}
|
|
61
|
+
namespace: {{ .Release.Namespace | quote }}
|
|
62
|
+
labels:
|
|
63
|
+
${Object.entries(objects[0].metadata.labels).map(([key, value]) => ` ${key}: ${value}`).join('\n')}
|
|
64
|
+
data:
|
|
65
|
+
{{- range $key, $value := .Values.settings }}
|
|
66
|
+
{{ $key }}: {{ $value | quote }}
|
|
67
|
+
{{- end }}
|
|
68
|
+
`
|
|
69
|
+
for (const object of objects) {
|
|
70
|
+
let text = templated(object)
|
|
71
|
+
if (object.kind === 'StatefulSet') {
|
|
72
|
+
text = text.replace(/slatebox\.com\/config-hash: \S+/, `slatebox.com/config-hash: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum | trunc 16 | quote }}`)
|
|
73
|
+
text = text.replace(`name: ${n.secret}`, `name: ${EXPR[MARK.secret]}`)
|
|
74
|
+
}
|
|
75
|
+
files[`templates/${object.kind.toLowerCase()}-${object.metadata.name}.yaml`] = text
|
|
76
|
+
}
|
|
77
|
+
return files
|
|
78
|
+
}
|
|
@@ -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,67 @@
|
|
|
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
|
+
// A team address: Cloudflare ends HTTPS and the container's cloudflared connects out with the
|
|
29
|
+
// tunnel token, which is a secret like any other (never in slatebox.env or a ConfigMap).
|
|
30
|
+
if (answers.address.team) {
|
|
31
|
+
require('SLATEBOX_TUNNEL_TOKEN', 'a team address (https://<name>.slatebox.team)')
|
|
32
|
+
env.SLATEBOX_HTTPS = 'off'
|
|
33
|
+
notes.push(`${answers.address.url} reaches Slatebox through an outbound Cloudflare Tunnel from the container: no DNS, no open ports, no certificates. Only 127.0.0.1 is published here.`)
|
|
34
|
+
}
|
|
35
|
+
if (answers.acmeCa) { require('SLATEBOX_ACME_CA', 'a custom certificate authority'); env.SLATEBOX_ACME_CA = answers.acmeCa }
|
|
36
|
+
|
|
37
|
+
if (answers.mail?.urlFrom) {
|
|
38
|
+
require('SLATEBOX_MAIL_URL', 'mail')
|
|
39
|
+
if (answers.mail.from) env.SLATEBOX_MAIL_FROM = answers.mail.from
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (answers.sso?.enabled) {
|
|
43
|
+
require('SLATEBOX_SSO', 'single sign-on')
|
|
44
|
+
env.SLATEBOX_SSO = 'keycloak'
|
|
45
|
+
if (answers.sso.only) { require('SLATEBOX_SSO_ONLY', 'single sign-on only'); env.SLATEBOX_SSO_ONLY = 'true' }
|
|
46
|
+
if (answers.sso.adminConsole === 'closed') { require('SLATEBOX_SSO_ADMIN', 'closing the Keycloak admin console'); env.SLATEBOX_SSO_ADMIN = 'closed' }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const ai = aiEnv(answers.ai, caps, { target: k8s ? 'k8s' : answers.target })
|
|
50
|
+
// A multi-provider image names one key variable per provider; those are not in its list.
|
|
51
|
+
for (const name of [...Object.keys(ai.env), ...Object.keys(ai.secrets).filter(name => !name.startsWith('SLATEBOX_AI_KEY_'))]) require(name, 'this AI setup')
|
|
52
|
+
Object.assign(env, ai.env)
|
|
53
|
+
notes.push(...ai.notes)
|
|
54
|
+
|
|
55
|
+
if (answers.settings && Object.keys(answers.settings).length) {
|
|
56
|
+
require('SLATEBOX_SETTINGS', 'extra settings')
|
|
57
|
+
env.SLATEBOX_SETTINGS = JSON.stringify(answers.settings)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (known.has('SLATEBOX_KEY_ENCRYPTION_KEY')) secrets.SLATEBOX_KEY_ENCRYPTION_KEY = 'generate'
|
|
61
|
+
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.')
|
|
62
|
+
Object.assign(secrets, ai.secrets)
|
|
63
|
+
if (answers.address.team) secrets.SLATEBOX_TUNNEL_TOKEN = 'tunnel'
|
|
64
|
+
if (answers.mail?.urlFrom) secrets.SLATEBOX_MAIL_URL = answers.mail.urlFrom
|
|
65
|
+
|
|
66
|
+
return { env, secrets, warnings, notes, hostGateway: ai.hostGateway }
|
|
67
|
+
}
|
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,45 @@
|
|
|
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 === 'tunnel') {
|
|
23
|
+
// The team address's tunnel token: fetched from Slatebox Cloud for this run, or the one stored.
|
|
24
|
+
const value = ctx.tunnelToken ?? stored[name]
|
|
25
|
+
if (value) values[name] = value
|
|
26
|
+
else missing.push({ field: name, question: 'the team address has no tunnel token yet: run slatebox install to sign in and fetch it', flag: '--team-address <name>', default: null })
|
|
27
|
+
} else if (ref === 'generate') {
|
|
28
|
+
if (stored[name]) values[name] = stored[name]
|
|
29
|
+
else {
|
|
30
|
+
values[name] = generateKek()
|
|
31
|
+
generated.push(name)
|
|
32
|
+
}
|
|
33
|
+
} else {
|
|
34
|
+
const ask = ctx.interactive && ctx.prompt ? () => ctx.prompt.secret(`Value for ${name} (not shown)`) : undefined
|
|
35
|
+
const value = (ref === 'prompt' && stored[name]) ? stored[name] : (await resolveRef(ref, { env: ctx.env, ask })) ?? stored[name]
|
|
36
|
+
if (value) values[name] = value
|
|
37
|
+
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 })
|
|
38
|
+
}
|
|
39
|
+
ctx.redactor.add(values[name])
|
|
40
|
+
}
|
|
41
|
+
if (missing.length) {
|
|
42
|
+
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 })
|
|
43
|
+
}
|
|
44
|
+
return { values, generated }
|
|
45
|
+
}
|
package/src/secrets.mjs
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
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|tunnel)$/
|
|
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' || ref === 'tunnel') 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
|
+
// Shapes that are secrets whatever their value: a team-address install credential, a
|
|
92
|
+
// Cloudflare tunnel connector token (base64 of {"a":…,"t":…,"s":…}), and a setup link's token.
|
|
93
|
+
// A self-hosted server's one-time setup link (/setup/<32 bytes base64url>) is as good as an admin password.
|
|
94
|
+
export const SECRET_SHAPES = [/sbxi_[A-Za-z0-9]+_[A-Za-z0-9_-]+/g, /eyJhIjoi[A-Za-z0-9+/_-]{16,}={0,2}/g, /(?<=\/setup\/)[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g]
|
|
95
|
+
|
|
96
|
+
/** Every secret the installer has seen is replaced by *** in anything it prints or logs. */
|
|
97
|
+
export class Redactor {
|
|
98
|
+
constructor() {
|
|
99
|
+
this.values = new Set()
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
add(value) {
|
|
103
|
+
if (typeof value !== 'string' || value.length < MIN_SECRET) return
|
|
104
|
+
for (const form of [value, encodeURIComponent(value), JSON.stringify(value).slice(1, -1), Buffer.from(value).toString('base64')]) {
|
|
105
|
+
if (form.length >= MIN_SECRET) this.values.add(form)
|
|
106
|
+
}
|
|
107
|
+
// A URL's password on its own (mail URLs carry one).
|
|
108
|
+
try {
|
|
109
|
+
const url = new URL(value)
|
|
110
|
+
if (url.password) this.add(decodeURIComponent(url.password))
|
|
111
|
+
if (url.password) this.add(url.password)
|
|
112
|
+
} catch { /* not a URL */ }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
redact(text) {
|
|
116
|
+
let out = String(text)
|
|
117
|
+
for (const shape of SECRET_SHAPES) out = out.replace(shape, '***')
|
|
118
|
+
// Longest first, so a value that contains another is removed whole.
|
|
119
|
+
for (const value of [...this.values].sort((a, b) => b.length - a.length)) {
|
|
120
|
+
if (out.includes(value)) out = out.split(value).join('***')
|
|
121
|
+
}
|
|
122
|
+
return out
|
|
123
|
+
}
|
|
124
|
+
}
|