@basaltkit/deploy 0.4.1 → 0.5.1
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/README.md +284 -23
- package/dist/answers.d.ts +70 -0
- package/dist/answers.js +196 -0
- package/dist/apache.js +11 -2
- package/dist/audit.d.ts +20 -0
- package/dist/audit.js +26 -0
- package/dist/backup.d.ts +17 -1
- package/dist/backup.js +56 -1
- package/dist/bin.js +9 -1
- package/dist/bootstrap.d.ts +68 -18
- package/dist/bootstrap.js +177 -45
- package/dist/caddy.js +2 -1
- package/dist/check.js +18 -5
- package/dist/checks.js +1 -1
- package/dist/cli.d.ts +22 -1
- package/dist/cli.js +498 -57
- package/dist/compose.d.ts +1 -1
- package/dist/compose.js +6 -1
- package/dist/config.d.ts +25 -2
- package/dist/config.js +65 -3
- package/dist/context.d.ts +43 -13
- package/dist/context.js +50 -7
- package/dist/detach.d.ts +23 -0
- package/dist/detach.js +105 -0
- package/dist/env-step.d.ts +16 -1
- package/dist/env-step.js +61 -5
- package/dist/events.d.ts +168 -0
- package/dist/events.js +477 -0
- package/dist/host.d.ts +179 -7
- package/dist/host.js +317 -42
- package/dist/index.d.ts +10 -5
- package/dist/index.js +7 -3
- package/dist/init.d.ts +2 -0
- package/dist/init.js +2 -1
- package/dist/install-plan.d.ts +40 -0
- package/dist/install-plan.js +437 -0
- package/dist/json-host.d.ts +32 -0
- package/dist/json-host.js +106 -0
- package/dist/lock.d.ts +45 -0
- package/dist/lock.js +128 -0
- package/dist/pipeline.d.ts +51 -3
- package/dist/pipeline.js +339 -173
- package/dist/protocol.d.ts +364 -0
- package/dist/protocol.js +134 -0
- package/dist/runs.d.ts +75 -0
- package/dist/runs.js +287 -0
- package/dist/state.d.ts +26 -13
- package/dist/state.js +68 -4
- package/dist/trust.d.ts +63 -0
- package/dist/trust.js +159 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +10 -0
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
One deploy pipeline for a Basalt app on a single Linux server: the `.env`,
|
|
4
4
|
dedicated Docker infra (Postgres, Redis, MinIO), PM2, Apache, a database dump
|
|
5
5
|
before migrating, a health check, and a rollback when the new release does not
|
|
6
|
-
answer. Design and decisions: [RFC 0006](
|
|
6
|
+
answer. Design and decisions: [RFC 0006](https://github.com/basaltkit/basalt/blob/main/docs/rfcs/0006-basalt-deploy.md)
|
|
7
|
+
and [RFC 0007](https://github.com/basaltkit/basalt/blob/main/docs/rfcs/0007-deploy-zero-scripts.md).
|
|
7
8
|
|
|
8
9
|
```sh
|
|
9
10
|
pnpm add -D @basaltkit/deploy
|
|
@@ -86,33 +87,50 @@ CI catches them too.
|
|
|
86
87
|
|
|
87
88
|
## On a new server
|
|
88
89
|
|
|
89
|
-
A fresh Ubuntu or Debian with Node, three commands
|
|
90
|
+
A fresh Ubuntu or Debian with Node, three commands. Root runs **its own copy**
|
|
91
|
+
of the tool, pinned to the exact version your lockfile records (here `0.5.0`),
|
|
92
|
+
from outside the checkout — never the checkout's `node_modules`, which the app
|
|
93
|
+
user can change ([who runs what](#who-runs-what-the-trust-boundary)):
|
|
90
94
|
|
|
91
95
|
```sh
|
|
92
|
-
git clone <repo> /srv/myapp
|
|
93
|
-
sudo npx
|
|
94
|
-
node node_modules/@basaltkit/deploy/dist/bin.js run
|
|
96
|
+
sudo adduser --disabled-password myapp && sudo git clone <repo> /srv/myapp
|
|
97
|
+
cd / && sudo -H npx --yes --package=@basaltkit/deploy@0.5.0 -- basalt-deploy bootstrap --dir=/srv/myapp --user=myapp # --dry-run first
|
|
98
|
+
sudo -u myapp -H sh -c 'cd /srv/myapp && node node_modules/@basaltkit/deploy/dist/bin.js run' # as myapp, from then on
|
|
95
99
|
```
|
|
96
100
|
|
|
97
101
|
`bootstrap` installs only what is missing — base packages, Docker with compose,
|
|
98
|
-
Node at `engines.node` (NodeSource), the pnpm the lockfile records
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
102
|
+
Node at `engines.node` (NodeSource), the pnpm the lockfile records — gives the
|
|
103
|
+
checkout and the `docker` group to the user (said plainly: that group is root on
|
|
104
|
+
the machine; rootless Docker is a later step), then, **as the user, in the
|
|
105
|
+
checkout**: `pnpm install`, `env` (it asks what it cannot generate) and
|
|
106
|
+
`install-plan`. From that plan (data, validated) it adds swap when RAM is under
|
|
107
|
+
6 GB (`bootstrap.swapGb`), ufw with SSH and 80/443 (turned on only when nothing
|
|
108
|
+
else listens; `--no-firewall`), Caddy when the proxy is `caddy()`, and runs
|
|
109
|
+
`install`. It never loads `deploy.config.ts` itself. A step that fails stops it;
|
|
110
|
+
running it again redoes nothing done. It warns when the lockfile records
|
|
111
|
+
another `@basaltkit/deploy` version than the one running.
|
|
112
|
+
|
|
113
|
+
`--dir` is required and is never taken from the working directory (root runs
|
|
114
|
+
from `cd /`): it must be an absolute path with no link in it, holding
|
|
115
|
+
`package.json` and `.git`, and not a system directory (`/`, `/etc`, `/home`,
|
|
116
|
+
`/srv`, `/usr/…`, `/var/lib/…`). Giving the checkout to the user (`chown -R`)
|
|
117
|
+
asks first. The user's steps never run on root's terminal: `pnpm install` and
|
|
118
|
+
`install-plan` in a new session (`setsid -w`, no controlling terminal), `env`
|
|
119
|
+
in a terminal of its own (`script`, which root runs). Without that, on sudo
|
|
120
|
+
< 1.9.14 with a kernel < 6.2 (Debian 12, Ubuntu 22.04) a postinstall script
|
|
121
|
+
could type into root's shell (TIOCSTI). A Ctrl-C stops bootstrap, not a step
|
|
122
|
+
already running in its own session.
|
|
105
123
|
|
|
106
124
|
By hand, the same thing:
|
|
107
125
|
|
|
108
126
|
```sh
|
|
109
127
|
# as the app user (never root), in the checkout:
|
|
110
128
|
pnpm install
|
|
111
|
-
node node_modules/@basaltkit/deploy/dist/bin.js env
|
|
129
|
+
node node_modules/@basaltkit/deploy/dist/bin.js env # writes the .env (asks once), starts the containers, validates
|
|
130
|
+
node node_modules/@basaltkit/deploy/dist/bin.js install-plan # writes the install plan (data) and prints the root command
|
|
112
131
|
|
|
113
|
-
# once, as an administrator — the
|
|
114
|
-
|
|
115
|
-
sudo "$(command -v node)" node_modules/@basaltkit/deploy/dist/bin.js install --user="$USER"
|
|
132
|
+
# once, as an administrator — the command install-plan printed, e.g.:
|
|
133
|
+
cd / && sudo -H npx --yes --package=@basaltkit/deploy@0.5.0 -- basalt-deploy install --plan=/srv/myapp/.basalt/install-plan.json --user=myapp
|
|
116
134
|
|
|
117
135
|
# then, every deploy, as the app user:
|
|
118
136
|
node node_modules/@basaltkit/deploy/dist/bin.js run
|
|
@@ -145,17 +163,183 @@ back. Deploys diff the site and never rewrite it; C1, C2 (not imported) and C8
|
|
|
145
163
|
|
|
146
164
|
## Commands
|
|
147
165
|
|
|
166
|
+
As the app user, in the checkout (`node node_modules/@basaltkit/deploy/dist/bin.js <command>`):
|
|
167
|
+
|
|
148
168
|
| | |
|
|
149
169
|
|---|---|
|
|
170
|
+
| `init --domain=<host>` | writes `deploy.config.ts` from the project (`--server`: also from this server), then `check` |
|
|
150
171
|
| `check` | the config is valid and types check (your `tsc`). No server needed — for CI. |
|
|
151
172
|
| `plan` | every check, then what `run` would do. Writes nothing, asks nothing. |
|
|
152
173
|
| `run` | preflight → fetch → env → infra → build → validate → backup → migrate → release → health → record |
|
|
153
174
|
| `env` | the `.env` and the containers only |
|
|
154
|
-
| `rollback [--to=<sha>]` | the last healthy release. Code only — the database keeps its migrations. |
|
|
155
|
-
| `status` | the last releases
|
|
156
|
-
| `install --
|
|
175
|
+
| `rollback [--to=<sha>]` | the last healthy release. Code only — the database keeps its migrations. Holds the commit it left. |
|
|
176
|
+
| `status` | the last releases (who, from where), the process, the deploy lock, a hold |
|
|
177
|
+
| `install-plan [--out=<file>\|-]` | what `install` needs, as JSON (default `<state dir>/install-plan.json`, 0600), and the root command to run |
|
|
178
|
+
| `attach <runId> --json [--from-seq=<n>] [--follow]` | the events of a run, from any point (machine mode, below) |
|
|
179
|
+
| `cancel <runId> [--first-only]` | SIGTERM to a detached run; a second `cancel` stops it at once (`--first-only` refuses instead) |
|
|
180
|
+
| `ui` | prints how to start the local UI ([`@basaltkit/deploy-ui`](../deploy-ui#readme)) — on your machine, never on the server |
|
|
181
|
+
|
|
182
|
+
As root, with a copy of the tool root owns (`cd / && sudo -H npx --yes --package=@basaltkit/deploy@<version> -- basalt-deploy <command>`):
|
|
183
|
+
|
|
184
|
+
| | |
|
|
185
|
+
|---|---|
|
|
186
|
+
| `bootstrap --user=<name> --dir=<checkout> [--dry-run]` | a fresh server, once (above); `--dir` is required |
|
|
187
|
+
| `install --plan=<file> --user=<name>` | once per server: the state directory, the proxy site, the env files' owner |
|
|
188
|
+
|
|
189
|
+
Options: `--skip=fetch,backup,tls`, `--config=<file>`, `--overrides=<file>`,
|
|
190
|
+
`--actor=<name>` (recorded with the release; default `$BASALT_DEPLOY_ACTOR`,
|
|
191
|
+
else `$USER`), `run --unhold`, `--allow-root`, `--unsafe-tool`, and the
|
|
192
|
+
machine-mode flags below (`--json`, `--answers=stdin`, `--answer-timeout`,
|
|
193
|
+
`--detach`, `--via=ui`).
|
|
194
|
+
|
|
195
|
+
Exit codes: `0` done · `1` failed or refused · `3` another deploy holds the
|
|
196
|
+
lock · `130` stopped by a signal (a second signal ends the process at once:
|
|
197
|
+
`130`/`129`/`143`).
|
|
198
|
+
|
|
199
|
+
### One deploy at a time
|
|
200
|
+
|
|
201
|
+
`run`, `env`, `rollback` and `install` take `<state dir>/deploy.lock` (created
|
|
202
|
+
exclusively, 0600) with the pid, host, start time, actor and command. A second
|
|
203
|
+
deploy is refused with exit code 3 and says who holds it; a lock whose process
|
|
204
|
+
is gone (same host) is taken over — for a detached run, once no process it
|
|
205
|
+
started is left. `status` shows it.
|
|
206
|
+
|
|
207
|
+
The first Ctrl-C (or SIGTERM/SIGHUP) stops `run`/`env` at the end of the
|
|
208
|
+
current step: `run` puts the code back and records the release as `aborted`.
|
|
209
|
+
From the release on — and during `rollback` and `install` — the command
|
|
210
|
+
finishes first; a second signal stops it at once, and with it the step's
|
|
211
|
+
processes when the deploy leads its process group (started from a shell, or
|
|
212
|
+
detached).
|
|
213
|
+
|
|
214
|
+
### Releases, rollbacks and holds
|
|
215
|
+
|
|
216
|
+
Every release in `releases.json` records the sha, the status, the migrations it
|
|
217
|
+
applied, the dump taken before them, the OS user and the actor, the SSH client
|
|
218
|
+
address (`$SSH_CONNECTION`) and how it ran (`ssh`, `ci`, `terminal`, `batch`).
|
|
219
|
+
`audit: { syslog: true }` also sends one line per release to `logger -t
|
|
220
|
+
basalt-deploy`.
|
|
221
|
+
|
|
222
|
+
A rollback onto a commit that does not answer either exits 1 and records it as
|
|
223
|
+
`rollback-unhealthy`; the next rollback never picks it. A manual rollback
|
|
224
|
+
refuses a checkout with local edits and **holds** the commit it left: a
|
|
225
|
+
scheduled `run` will not deploy that commit again until the branch moves on,
|
|
226
|
+
or `run --unhold`.
|
|
227
|
+
|
|
228
|
+
## Machine mode (`--json`)
|
|
229
|
+
|
|
230
|
+
For a program that drives the deploy — the local UI
|
|
231
|
+
([`@basaltkit/deploy-ui`](../deploy-ui#readme), RFC 0009), a script — over the
|
|
232
|
+
system `ssh`, as the app user, exactly as a person would type it.
|
|
233
|
+
There is no daemon, no listener and no new credential: the program can do what
|
|
234
|
+
the SSH account can, nothing more. Design and threat model:
|
|
235
|
+
[RFC 0008](https://github.com/basaltkit/basalt/blob/main/docs/rfcs/0008-deploy-machine-protocol.md)
|
|
236
|
+
(it builds on [RFC 0006](https://github.com/basaltkit/basalt/blob/main/docs/rfcs/0006-basalt-deploy.md)).
|
|
237
|
+
|
|
238
|
+
`--json` (or `--json=1`; any other version is refused) works on `status`,
|
|
239
|
+
`check`, `plan`, `run`, `env`, `rollback`, `install-plan`, `attach` and
|
|
240
|
+
`cancel`. `init`, `install` and `bootstrap` refuse it. stdout then carries
|
|
241
|
+
only NDJSON events, one per line:
|
|
242
|
+
|
|
243
|
+
```json
|
|
244
|
+
{"v":1,"ts":"2026-10-13T10:00:00.000Z","seq":0,"runId":"20261013T100000Z-5f2c9a1b3d4e","type":"hello","tool":"@basaltkit/deploy","version":"0.5.0","protocol":1,"command":"run","pid":4100,"host":"server-1"}
|
|
245
|
+
{"v":1,"ts":"…","seq":1,"runId":"…","type":"step-start","id":"lock","title":"lock"}
|
|
246
|
+
{"v":1,"ts":"…","seq":2,"runId":"…","type":"step-end","id":"lock","status":"ok","durationMs":3}
|
|
247
|
+
{"v":1,"ts":"…","seq":9,"runId":"…","type":"log","stream":"child","level":"info","text":"Done in 4.1s","redacted":false,"step":"build","source":"pnpm"}
|
|
248
|
+
{"v":1,"ts":"…","seq":40,"runId":"…","type":"result","command":"run","data":{"sha":"…","previous":"…","status":"ok","migrations":[],"url":"https://myapp.example.com"}}
|
|
249
|
+
{"v":1,"ts":"…","seq":41,"runId":"…","type":"done","exitCode":0}
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
- Every stream starts with `hello` and ends with `done`; `seq` counts up by
|
|
253
|
+
one. A stream that ends without `done` ended abnormally (a second signal,
|
|
254
|
+
a kill) — never treat it as success.
|
|
255
|
+
- `type` is one of `hello`, `step-start`, `step-end`, `log`, `finding`,
|
|
256
|
+
`prompt`, `result`, `error`, `done` (and `event`, from `attach`). `error`
|
|
257
|
+
carries a `code` (`locked`, `aborted`, `preflight`, `held`,
|
|
258
|
+
`release-failed`, `answer-missing`, …); the exit codes are the ones above.
|
|
259
|
+
- What a build, a hook, a migration or `deploy.config.ts` prints (on stdout
|
|
260
|
+
or stderr) is always the `text` of a `log` event (`stream: "child"` or
|
|
261
|
+
`"foreign"`), stripped of terminal escapes, redacted, then cut at 8 KiB —
|
|
262
|
+
data, never interpreted. Every other string of every event is stripped of
|
|
263
|
+
escapes too.
|
|
264
|
+
- **No event carries a secret.** Every string is redacted before it is
|
|
265
|
+
written: the values of generated, asked-secret and secret-named `.env` keys,
|
|
266
|
+
passwords inside URLs, the infra passwords, secret-named variables of the
|
|
267
|
+
deploy's own environment, every secret answer — raw and URL-encoded —
|
|
268
|
+
become `[redacted:KEY]`. What the config prints while it loads waits until
|
|
269
|
+
its `.env` has been read. A bare origin in a `*_URL` key
|
|
270
|
+
(`APP_URL=https://app.example.com`) is the app's address and is not
|
|
271
|
+
redacted. A value shorter than 6 characters cannot be matched; a
|
|
272
|
+
`secret-short` warning names its key.
|
|
273
|
+
- Types and a validating parser for a program written in TypeScript:
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
import { parseEvent, type DeployEvent } from '@basaltkit/deploy/protocol'
|
|
277
|
+
|
|
278
|
+
for (const line of output.split('\n').filter(Boolean)) {
|
|
279
|
+
const parsed = parseEvent(line)
|
|
280
|
+
if (!parsed.ok) throw new Error(`corrupt stream: ${parsed.error}`) // stop: never guess
|
|
281
|
+
if (parsed.known) handle(parsed.value) // a type this version does not know is skipped
|
|
282
|
+
}
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
The subpath is pure (no CLI, no Node API at load).
|
|
286
|
+
|
|
287
|
+
**Answers.** `run` and `env` ask the `env.ask` questions. `plan --json` lists
|
|
288
|
+
them in its result (`questions`, never with a value; a secret never with a
|
|
289
|
+
default). Send the answers on stdin with `--answers=stdin`, one line each:
|
|
290
|
+
|
|
291
|
+
```sh
|
|
292
|
+
printf '%s\n' '{"v":1,"type":"answer","id":"env.SMTP_URL","value":"smtps://user:pass@smtp.example.com:465"}' |
|
|
293
|
+
ssh -T deploy@192.0.2.10 -- 'cd /srv/myapp && node node_modules/@basaltkit/deploy/dist/bin.js run --json=1 --answers=stdin'
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
An unknown id, a duplicate, a malformed or oversized line fails the command
|
|
297
|
+
before the lock is taken. A required question nobody answers fails
|
|
298
|
+
(`answer-missing`); an unanswered optional secret is left out of the `.env`.
|
|
299
|
+
With stdin kept open, a refused answer is asked again (`prompt` with
|
|
300
|
+
`attempt: 2`); a prompt waits `--answer-timeout` seconds (default 600). The
|
|
301
|
+
deploy's own environment still answers first. No child process ever reads
|
|
302
|
+
stdin.
|
|
303
|
+
|
|
304
|
+
**Detached runs.** `run --detach --json` (and `rollback --detach --json`)
|
|
305
|
+
checks every answer first, starts the deploy in its own session — it survives
|
|
306
|
+
the SSH connection — and returns `{runId, pid, log}` once that run holds the
|
|
307
|
+
deploy lock:
|
|
157
308
|
|
|
158
|
-
|
|
309
|
+
```sh
|
|
310
|
+
node node_modules/@basaltkit/deploy/dist/bin.js run --json=1 --detach --answers=stdin --via=ui --actor=alice < answers.ndjson
|
|
311
|
+
node node_modules/@basaltkit/deploy/dist/bin.js attach 20261013T100000Z-5f2c9a1b3d4e --json --follow --from-seq=0
|
|
312
|
+
node node_modules/@basaltkit/deploy/dist/bin.js cancel 20261013T100000Z-5f2c9a1b3d4e --json
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
- Every JSON-mode `run`, `env` and `rollback` writes its events to
|
|
316
|
+
`<state dir>/runs/<runId>.ndjson` (0600, in a 0700 directory, created
|
|
317
|
+
exclusively, never through a link). `attach` replays one, wrapped as
|
|
318
|
+
`{"type":"event","event":{…}}`, from `--from-seq` (the inner `seq`), and
|
|
319
|
+
with `--follow` waits for its `done`; a run gone without one is
|
|
320
|
+
`run-vanished`. The newest 50 logs are kept, none older than 30 days; a log
|
|
321
|
+
stops taking output lines at 64 MiB.
|
|
322
|
+
- `cancel` sends SIGTERM only to the process holding the lock for that run,
|
|
323
|
+
checked by its own command line (Linux). It stops at the next safe point,
|
|
324
|
+
as Ctrl-C does; a second `cancel` stops it at once, with the step it was
|
|
325
|
+
running (its process group). The lock is taken over by the next deploy
|
|
326
|
+
once no process of that run is left. `cancel --first-only` sends only a
|
|
327
|
+
first signal: when the run was already cancelled once, from any client, it
|
|
328
|
+
is refused (`already-cancelled`) and nothing is signalled. A client that
|
|
329
|
+
asked for the mild cancel never sends the immediate one by surprise.
|
|
330
|
+
- `status --json` reports the lock, the active run and the last run.
|
|
331
|
+
- `--via=ui` records `via: "ui"` with the release; like `--actor`, it
|
|
332
|
+
attributes, it does not authenticate.
|
|
333
|
+
|
|
334
|
+
## The local UI
|
|
335
|
+
|
|
336
|
+
[`@basaltkit/deploy-ui`](../deploy-ui#readme) is a browser UI for all of the
|
|
337
|
+
above that runs on **your** machine (`npx @basaltkit/deploy-ui@<exact version>`),
|
|
338
|
+
listens on `127.0.0.1` only and drives each server over your own `ssh` with the
|
|
339
|
+
machine mode — status, plan, the `.env` questions, a detached run with its live
|
|
340
|
+
log, cancel, rollback, history. Never add it to the app's `package.json`: this
|
|
341
|
+
package installs the app's devDependencies on the server. Design and security
|
|
342
|
+
model: [RFC 0009](https://github.com/basaltkit/basalt/blob/main/docs/rfcs/0009-deploy-local-ui.md).
|
|
159
343
|
|
|
160
344
|
## Docker Compose apps
|
|
161
345
|
|
|
@@ -182,9 +366,18 @@ runtime: compose({
|
|
|
182
366
|
- Image tags must be `<app>` or `<app>-…` (C4).
|
|
183
367
|
|
|
184
368
|
**The env file outside the checkout:** `env: { file: '/etc/myapp/api.env', mirror: ['/etc/myapp/worker.env'] }`.
|
|
185
|
-
Mirrors are rewritten as exact copies; one that differs is a C10 error.
|
|
186
|
-
|
|
187
|
-
|
|
369
|
+
Mirrors are rewritten as exact copies; one that differs is a C10 error. Outside
|
|
370
|
+
the checkout an env file lives directly in `/etc/<app>/` — nowhere else (never
|
|
371
|
+
`/etc/environment`). `install` gives `/etc/<app>` (0700) and the files (0600)
|
|
372
|
+
to the deploy user, through descriptors opened without following links: a
|
|
373
|
+
symlink or a hard link planted there is refused. The app name picks that
|
|
374
|
+
directory, so `install` never takes one that is not the app's: names such as
|
|
375
|
+
`systemd`, `ssh`, `apt`, `docker` or `basalt` cannot keep env files in `/etc`
|
|
376
|
+
(keep the env in the checkout, or rename the app); a directory a Debian
|
|
377
|
+
package ships, one with subdirectories, or one another account owns is
|
|
378
|
+
refused; one root created by hand is shown and given only after a "yes". The
|
|
379
|
+
state directory `/var/lib/basalt/<app>` is refused too when another account
|
|
380
|
+
owns it.
|
|
188
381
|
|
|
189
382
|
**Migrations by command**, with values that override the `.env` for them and for
|
|
190
383
|
the pre-migration dump (a container name the host cannot resolve):
|
|
@@ -280,6 +473,22 @@ checks C2 and C1 on each vhost on every deploy and never writes them.
|
|
|
280
473
|
- The dump before migrating — when something is migrated and there is a
|
|
281
474
|
Postgres to dump (dedicated, or a `postgres://` URL in the `.env`);
|
|
282
475
|
`backup.beforeMigrate` forces it either way. `plan` says why when it is skipped.
|
|
476
|
+
Dumps go to `<state dir>/backups` (0700). Once `install` ran that is
|
|
477
|
+
`/var/lib/basalt/<app>/backups`, outside the checkout — never in an image, a
|
|
478
|
+
commit or a served directory. Before, it is `<checkout>/.basalt/backups`: a
|
|
479
|
+
new app's `.gitignore`/`.dockerignore` exclude `/.basalt` and `/backups`, and
|
|
480
|
+
the preflight warns (`dumps`) when git does not ignore the directory or a
|
|
481
|
+
Docker build would copy it. `backup.dir` (relative to the checkout) keeps
|
|
482
|
+
the old place; dumps left in `backups/predeploy`, the old default, are
|
|
483
|
+
pointed out until they are moved or deleted. When `/var/lib/basalt` exists
|
|
484
|
+
but `/var/lib/basalt/<app>` is missing or not reachable by the app user (a
|
|
485
|
+
parent only root can enter), the preflight says so (`state-dir`) instead of
|
|
486
|
+
falling back to the checkout in silence; `install` makes `/var/lib/basalt`
|
|
487
|
+
0755 (each app's own directory below stays 0700).
|
|
488
|
+
- The node it runs on, first on `PATH` for everything it starts (`pnpm`,
|
|
489
|
+
`node`, the app's scripts). With nvm, fnm or volta, a non-interactive shell
|
|
490
|
+
(`ssh host cmd`, cron, the local UI) does not have them on `PATH`; starting
|
|
491
|
+
the deploy with that node's absolute path is enough.
|
|
283
492
|
With external infra in a container, `backup: { container: 'myapp-postgres' }`
|
|
284
493
|
runs `pg_dump` inside it (`docker exec`), as the user and database of the
|
|
285
494
|
URL at `backup.urlKey` — the server's own pg_dump, none needed on the host.
|
|
@@ -315,9 +524,61 @@ environment to `~/.pm2/dump.pm2`).
|
|
|
315
524
|
|
|
316
525
|
- Before `release` (build, validation, backup, migration): the code on disk is
|
|
317
526
|
put back to the previous commit and rebuilt; nothing running was touched.
|
|
527
|
+
- A failed migration is recorded as `failed-migration`: the database may be
|
|
528
|
+
part-way, so the `pg_restore` command for the dump taken before it is printed.
|
|
318
529
|
- At `release`/`health`: the previous commit is rebuilt, restarted and checked.
|
|
319
530
|
- A release that applied a migration listed in `destructive` is never rolled
|
|
320
531
|
back automatically — its code would run on a schema it does not know. The
|
|
321
532
|
`pg_restore` command for the dump taken before it is printed instead.
|
|
322
533
|
- Healthy on `127.0.0.1` but not at `https://<domain>`: exit 1, no rollback —
|
|
323
534
|
the problem is the proxy, DNS or TLS, not the code.
|
|
535
|
+
|
|
536
|
+
## Who runs what: the trust boundary
|
|
537
|
+
|
|
538
|
+
| Who | Runs | Can change |
|
|
539
|
+
|---|---|---|
|
|
540
|
+
| the app user | `env`, `run`, `rollback`, `plan`, `status`, `install-plan`; the app itself | the checkout: `deploy.config.ts`, `node_modules`, every file in the tree; its `.env`; `<state dir>` |
|
|
541
|
+
| root | `bootstrap`, `install` — from a copy of the tool root owns | everything |
|
|
542
|
+
|
|
543
|
+
- **Root never runs the app user's code.** `install` reads a data-only plan
|
|
544
|
+
(`install-plan`), without following a link, and validates every field again:
|
|
545
|
+
the web root (inside the checkout, no dot directories, not the checkout
|
|
546
|
+
itself), the API prefix, the certificate name, the env files (only
|
|
547
|
+
`/etc/<app>/`), the checkout (must be the user's own directory). It never
|
|
548
|
+
loads `deploy.config.ts`, the checkout's `tsx` or `node_modules`, nor reads
|
|
549
|
+
the `.env`. Before writing it prints what it will do. Raw Caddy `extra` and a
|
|
550
|
+
non-default proxy root are shown and need a "yes" at the terminal; `extra`
|
|
551
|
+
may hold no control or direction character (what is shown is what is
|
|
552
|
+
written) and no `import`.
|
|
553
|
+
- **A plan cannot take another site.** The managed vhost is `<app>.conf` (or
|
|
554
|
+
`<app>-….conf`), and `install` refuses a domain — or a name under its
|
|
555
|
+
wildcard, or a wildcard over it — that another Apache vhost or Caddy site
|
|
556
|
+
already serves.
|
|
557
|
+
- **The served directory follows no planted link out of the user's files.**
|
|
558
|
+
The vhost sets `Options -FollowSymLinks +SymLinksIfOwnerMatch` and
|
|
559
|
+
`AllowOverride None` on the checkout and the web root. Caddy's
|
|
560
|
+
`file_server` has no such option: with `caddy()`, a link in the web root is
|
|
561
|
+
followed to anything the `caddy` user can read — keep secrets of other
|
|
562
|
+
sites out of its reach.
|
|
563
|
+
- **Root writes only where no other user can plant a link**: directories
|
|
564
|
+
only root can write (`/var/lib/basalt`, `/etc/basalt`, the Apache/Caddy
|
|
565
|
+
roots), or files changed through an `O_NOFOLLOW` descriptor.
|
|
566
|
+
- **The tool root runs is checked.** As root, `install` and `bootstrap` refuse
|
|
567
|
+
to run from files another user can change — `sudo node
|
|
568
|
+
node_modules/@basaltkit/deploy/dist/bin.js` from the checkout, a user's npm
|
|
569
|
+
cache, a per-user Node (nvm) — unless `--unsafe-tool`. Run the pinned copy:
|
|
570
|
+
`cd / && sudo -H npx --yes --package=@basaltkit/deploy@<version> -- basalt-deploy …`
|
|
571
|
+
(`cd /`: inside the checkout npx would pick its own copy; `-H`: root's npm
|
|
572
|
+
cache, not the user's), or a root-owned global install (`sudo npm install -g
|
|
573
|
+
@basaltkit/deploy@<version>`) with a root-owned Node (NodeSource's
|
|
574
|
+
`/usr/bin/node`). The check is a guardrail against a mistake, not a
|
|
575
|
+
boundary: it runs inside the copy being checked, so a copy the app user
|
|
576
|
+
changed can drop it. Running the pinned, root-owned copy is the control.
|
|
577
|
+
- **The app user's commands refuse root** (`--allow-root` to insist): as root
|
|
578
|
+
they would build and run the app's code, and `deploy.config.ts`, as root.
|
|
579
|
+
- **The `docker` group is root on the machine** (a container can mount `/`).
|
|
580
|
+
`bootstrap` adds the user to it so `dockerInfra` and `compose` work, and says
|
|
581
|
+
so; with it, the boundary above protects against mistakes and a compromised
|
|
582
|
+
checkout less than against the app user itself. Rootless Docker for the app
|
|
583
|
+
user is the real fix (`dockerd-rootless-setuptool.sh install`), and moves
|
|
584
|
+
every volume — a later step, not done for you.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { DeployError } from './context.js';
|
|
2
|
+
import { type ErrorCode } from './protocol.js';
|
|
3
|
+
/**
|
|
4
|
+
* `--answers=stdin` (RFC 0008 §7): answer lines arrive on stdin, are checked
|
|
5
|
+
* one by one as they arrive, and wait until the prompt that needs them. Every
|
|
6
|
+
* rule fails closed: a bad line, an id the config does not ask, a duplicate
|
|
7
|
+
* — the command stops; it never skips a line or guesses.
|
|
8
|
+
*
|
|
9
|
+
* The values are kept here and handed only to the prompt that asks for them:
|
|
10
|
+
* never echoed, never in an event, never in a child's argv or environment.
|
|
11
|
+
*/
|
|
12
|
+
export interface AskedQuestion {
|
|
13
|
+
key: string;
|
|
14
|
+
secret: boolean;
|
|
15
|
+
}
|
|
16
|
+
/** Default `--answer-timeout`, in seconds. */
|
|
17
|
+
export declare const ANSWER_TIMEOUT_SECONDS = 600;
|
|
18
|
+
export declare const answerError: (code: ErrorCode, message: string, hint?: string) => DeployError;
|
|
19
|
+
export declare class AnswerChannel {
|
|
20
|
+
private readonly questions;
|
|
21
|
+
private readonly onSecret;
|
|
22
|
+
private readonly pending;
|
|
23
|
+
private readonly consumed;
|
|
24
|
+
private readonly reprompted;
|
|
25
|
+
private readonly waiters;
|
|
26
|
+
private readonly eofWaiters;
|
|
27
|
+
private eof;
|
|
28
|
+
private stopped;
|
|
29
|
+
private fatal;
|
|
30
|
+
private count;
|
|
31
|
+
private iterator;
|
|
32
|
+
/**
|
|
33
|
+
* @param questions what `deploy.config.ts` can ask (`env.ask`), by answer id (`env.<KEY>`)
|
|
34
|
+
* @param onSecret called with a secret answer the moment it is parsed — before anything can print it
|
|
35
|
+
*/
|
|
36
|
+
constructor(questions: ReadonlyMap<string, AskedQuestion>, onSecret: (key: string, value: string) => void);
|
|
37
|
+
/** Reads `source` to its end in the background. */
|
|
38
|
+
start(source: AsyncIterable<string | Uint8Array>): void;
|
|
39
|
+
/** Answers can still arrive (stdin is open): a refused answer may be asked again. */
|
|
40
|
+
get live(): boolean;
|
|
41
|
+
/** stdin read to its end, every line checked (a detached run's answers; the child's before its lock). */
|
|
42
|
+
drain(): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* Before the lock: the lines already sent have been checked. Waits for the
|
|
45
|
+
* end of stdin, or for what is buffered to be read (a channel left open for
|
|
46
|
+
* live answers does not hold the command up).
|
|
47
|
+
*/
|
|
48
|
+
settle(graceMs?: number): Promise<void>;
|
|
49
|
+
throwIfFatal(): void;
|
|
50
|
+
/** The answer for `id`: buffered, or the next to arrive; `undefined` once stdin ended without it. */
|
|
51
|
+
take(id: string, timeoutMs: number): Promise<string | undefined>;
|
|
52
|
+
/** A buffered answer, without taking it (the detaching parent checks them all up front). */
|
|
53
|
+
peek(id: string): string | undefined;
|
|
54
|
+
/** The buffered answers as lines again — only the named fields — for a detached child's stdin. */
|
|
55
|
+
serialize(): string;
|
|
56
|
+
/** `id` was refused and is asked again: one more answer for it is not a duplicate. */
|
|
57
|
+
expectAgain(id: string): void;
|
|
58
|
+
/**
|
|
59
|
+
* No more questions: stops reading, and returns the keys answered but never
|
|
60
|
+
* asked (already in the .env, or given by the deploy's environment).
|
|
61
|
+
*/
|
|
62
|
+
finish(): string[];
|
|
63
|
+
private read;
|
|
64
|
+
private accept;
|
|
65
|
+
private fail;
|
|
66
|
+
}
|
|
67
|
+
/** The questions a config can ask, by answer id. */
|
|
68
|
+
export declare function askedQuestions(ask: Record<string, {
|
|
69
|
+
secret: boolean;
|
|
70
|
+
} | undefined> | undefined): Map<string, AskedQuestion>;
|
package/dist/answers.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
2
|
+
import { DeployError } from './context.js';
|
|
3
|
+
import { MAX_ANSWER_LINE_BYTES, MAX_ANSWER_LINES, parseAnswerLine } from './protocol.js';
|
|
4
|
+
/** Default `--answer-timeout`, in seconds. */
|
|
5
|
+
export const ANSWER_TIMEOUT_SECONDS = 600;
|
|
6
|
+
export const answerError = (code, message, hint) => new DeployError(message, [], code, hint);
|
|
7
|
+
export class AnswerChannel {
|
|
8
|
+
questions;
|
|
9
|
+
onSecret;
|
|
10
|
+
pending = new Map();
|
|
11
|
+
consumed = new Set();
|
|
12
|
+
reprompted = new Set();
|
|
13
|
+
waiters = new Map();
|
|
14
|
+
eofWaiters = [];
|
|
15
|
+
eof = false;
|
|
16
|
+
stopped = false;
|
|
17
|
+
fatal;
|
|
18
|
+
count = 0;
|
|
19
|
+
iterator;
|
|
20
|
+
/**
|
|
21
|
+
* @param questions what `deploy.config.ts` can ask (`env.ask`), by answer id (`env.<KEY>`)
|
|
22
|
+
* @param onSecret called with a secret answer the moment it is parsed — before anything can print it
|
|
23
|
+
*/
|
|
24
|
+
constructor(questions, onSecret) {
|
|
25
|
+
this.questions = questions;
|
|
26
|
+
this.onSecret = onSecret;
|
|
27
|
+
}
|
|
28
|
+
/** Reads `source` to its end in the background. */
|
|
29
|
+
start(source) {
|
|
30
|
+
this.iterator = source[Symbol.asyncIterator]();
|
|
31
|
+
void this.read();
|
|
32
|
+
}
|
|
33
|
+
/** Answers can still arrive (stdin is open): a refused answer may be asked again. */
|
|
34
|
+
get live() {
|
|
35
|
+
return !this.eof;
|
|
36
|
+
}
|
|
37
|
+
/** stdin read to its end, every line checked (a detached run's answers; the child's before its lock). */
|
|
38
|
+
async drain() {
|
|
39
|
+
if (!this.eof)
|
|
40
|
+
await new Promise((resolve) => this.eofWaiters.push(resolve));
|
|
41
|
+
this.throwIfFatal();
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Before the lock: the lines already sent have been checked. Waits for the
|
|
45
|
+
* end of stdin, or for what is buffered to be read (a channel left open for
|
|
46
|
+
* live answers does not hold the command up).
|
|
47
|
+
*/
|
|
48
|
+
async settle(graceMs = 50) {
|
|
49
|
+
if (!this.eof) {
|
|
50
|
+
let timer;
|
|
51
|
+
await Promise.race([
|
|
52
|
+
new Promise((resolve) => this.eofWaiters.push(resolve)),
|
|
53
|
+
new Promise((resolve) => { timer = setTimeout(resolve, graceMs); timer.unref?.(); }),
|
|
54
|
+
]);
|
|
55
|
+
if (timer)
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
}
|
|
58
|
+
this.throwIfFatal();
|
|
59
|
+
}
|
|
60
|
+
throwIfFatal() {
|
|
61
|
+
if (this.fatal)
|
|
62
|
+
throw this.fatal;
|
|
63
|
+
}
|
|
64
|
+
/** The answer for `id`: buffered, or the next to arrive; `undefined` once stdin ended without it. */
|
|
65
|
+
async take(id, timeoutMs) {
|
|
66
|
+
this.throwIfFatal();
|
|
67
|
+
const ready = this.pending.get(id);
|
|
68
|
+
if (ready !== undefined) {
|
|
69
|
+
this.pending.delete(id);
|
|
70
|
+
this.consumed.add(id);
|
|
71
|
+
return ready;
|
|
72
|
+
}
|
|
73
|
+
if (this.eof)
|
|
74
|
+
return undefined;
|
|
75
|
+
let timer;
|
|
76
|
+
try {
|
|
77
|
+
return await new Promise((resolve, reject) => {
|
|
78
|
+
this.waiters.set(id, { resolve, reject });
|
|
79
|
+
timer = setTimeout(() => {
|
|
80
|
+
this.waiters.delete(id);
|
|
81
|
+
reject(answerError('answer-timeout', `no answer for ${this.questions.get(id)?.key ?? id} within ${Math.round(timeoutMs / 1000)} s — nothing was written`, 'send the answers up front (plan --json lists the questions), or raise --answer-timeout'));
|
|
82
|
+
}, timeoutMs);
|
|
83
|
+
timer.unref?.();
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
if (timer)
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** A buffered answer, without taking it (the detaching parent checks them all up front). */
|
|
92
|
+
peek(id) {
|
|
93
|
+
return this.pending.get(id);
|
|
94
|
+
}
|
|
95
|
+
/** The buffered answers as lines again — only the named fields — for a detached child's stdin. */
|
|
96
|
+
serialize() {
|
|
97
|
+
return [...this.pending].map(([id, value]) => `${JSON.stringify({ v: 1, type: 'answer', id, value })}\n`).join('');
|
|
98
|
+
}
|
|
99
|
+
/** `id` was refused and is asked again: one more answer for it is not a duplicate. */
|
|
100
|
+
expectAgain(id) {
|
|
101
|
+
this.reprompted.add(id);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* No more questions: stops reading, and returns the keys answered but never
|
|
105
|
+
* asked (already in the .env, or given by the deploy's environment).
|
|
106
|
+
*/
|
|
107
|
+
finish() {
|
|
108
|
+
this.stopped = true;
|
|
109
|
+
void this.iterator?.return?.();
|
|
110
|
+
const left = [...this.pending.keys()].map((id) => this.questions.get(id)?.key ?? id);
|
|
111
|
+
this.pending.clear();
|
|
112
|
+
return left;
|
|
113
|
+
}
|
|
114
|
+
async read() {
|
|
115
|
+
const decoder = new StringDecoder('utf8');
|
|
116
|
+
let buffer = '';
|
|
117
|
+
try {
|
|
118
|
+
while (!this.stopped) {
|
|
119
|
+
const next = await this.iterator.next();
|
|
120
|
+
if (next.done || this.stopped)
|
|
121
|
+
break;
|
|
122
|
+
buffer += typeof next.value === 'string' ? next.value : decoder.write(Buffer.from(next.value));
|
|
123
|
+
let newline;
|
|
124
|
+
while ((newline = buffer.indexOf('\n')) !== -1) {
|
|
125
|
+
this.accept(buffer.slice(0, newline).replace(/\r$/, ''));
|
|
126
|
+
buffer = buffer.slice(newline + 1);
|
|
127
|
+
}
|
|
128
|
+
if (Buffer.byteLength(buffer) > MAX_ANSWER_LINE_BYTES) {
|
|
129
|
+
this.fail(answerError('protocol', `an answer line is larger than ${MAX_ANSWER_LINE_BYTES} bytes`));
|
|
130
|
+
buffer = '';
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (!this.stopped) {
|
|
134
|
+
buffer += decoder.end();
|
|
135
|
+
if (buffer.trim())
|
|
136
|
+
this.accept(buffer.replace(/\r$/, ''));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
this.fail(answerError('protocol', `stdin could not be read: ${error.message}`));
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
this.eof = true;
|
|
144
|
+
for (const waiter of this.waiters.values())
|
|
145
|
+
waiter.resolve(undefined);
|
|
146
|
+
this.waiters.clear();
|
|
147
|
+
for (const resolve of this.eofWaiters.splice(0))
|
|
148
|
+
resolve();
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
accept(line) {
|
|
152
|
+
if (this.fatal || line.trim() === '')
|
|
153
|
+
return;
|
|
154
|
+
if (++this.count > MAX_ANSWER_LINES)
|
|
155
|
+
return this.fail(answerError('protocol', `more than ${MAX_ANSWER_LINES} answer lines`));
|
|
156
|
+
const parsed = parseAnswerLine(line);
|
|
157
|
+
if (!parsed.ok)
|
|
158
|
+
return this.fail(answerError('protocol', parsed.error));
|
|
159
|
+
const { id, value } = parsed.value;
|
|
160
|
+
const question = this.questions.get(id);
|
|
161
|
+
if (!question) {
|
|
162
|
+
const key = id.slice('env.'.length);
|
|
163
|
+
return this.fail(answerError('answer-unknown', `an answer for ${key}, which deploy.config.ts does not ask (env.ask) — nothing was changed`));
|
|
164
|
+
}
|
|
165
|
+
// Known as a secret before anything else can print it.
|
|
166
|
+
if (question.secret)
|
|
167
|
+
this.onSecret(question.key, value);
|
|
168
|
+
if (this.pending.has(id) || (this.consumed.has(id) && !this.reprompted.has(id))) {
|
|
169
|
+
return this.fail(answerError('protocol', `two answers for ${question.key}`));
|
|
170
|
+
}
|
|
171
|
+
this.reprompted.delete(id);
|
|
172
|
+
const waiter = this.waiters.get(id);
|
|
173
|
+
if (waiter) {
|
|
174
|
+
this.waiters.delete(id);
|
|
175
|
+
this.consumed.add(id);
|
|
176
|
+
waiter.resolve(value);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
this.pending.set(id, value);
|
|
180
|
+
}
|
|
181
|
+
fail(error) {
|
|
182
|
+
this.fatal ??= error;
|
|
183
|
+
for (const waiter of this.waiters.values())
|
|
184
|
+
waiter.reject(error);
|
|
185
|
+
this.waiters.clear();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** The questions a config can ask, by answer id. */
|
|
189
|
+
export function askedQuestions(ask) {
|
|
190
|
+
const questions = new Map();
|
|
191
|
+
for (const [key, question] of Object.entries(ask ?? {})) {
|
|
192
|
+
if (question)
|
|
193
|
+
questions.set(`env.${key}`, { key, secret: question.secret });
|
|
194
|
+
}
|
|
195
|
+
return questions;
|
|
196
|
+
}
|