@basaltkit/deploy 0.2.0 → 0.3.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/README.md +116 -2
- package/dist/backup.d.ts +5 -3
- package/dist/backup.js +33 -12
- package/dist/bootstrap.d.ts +35 -0
- package/dist/bootstrap.js +148 -0
- package/dist/caddy.d.ts +24 -0
- package/dist/caddy.js +154 -0
- package/dist/check.d.ts +12 -0
- package/dist/check.js +54 -0
- package/dist/checks.d.ts +2 -0
- package/dist/checks.js +2 -2
- package/dist/cli.js +34 -1
- package/dist/compose.d.ts +16 -0
- package/dist/compose.js +134 -0
- package/dist/config.d.ts +310 -48
- package/dist/config.js +60 -5
- package/dist/env-step.js +5 -4
- package/dist/host.d.ts +2 -0
- package/dist/host.js +3 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/infra.d.ts +12 -1
- package/dist/infra.js +50 -12
- package/dist/init.d.ts +76 -0
- package/dist/init.js +501 -0
- package/dist/pipeline.js +105 -22
- package/dist/services.d.ts +62 -0
- package/dist/services.js +195 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -12,6 +12,20 @@ pnpm add -D @basaltkit/deploy
|
|
|
12
12
|
## The config
|
|
13
13
|
|
|
14
14
|
`deploy.config.ts` at the app root, committed. It holds **no secrets**.
|
|
15
|
+
`basalt-deploy init --domain=<host>` writes it from the project:
|
|
16
|
+
|
|
17
|
+
| Read from | Fills |
|
|
18
|
+
|---|---|
|
|
19
|
+
| `src/env.ts` (as text — the app is not loaded) | the typed `defineDeploy<typeof env>`; `generate` for each `secret()` the app mints, `ask` for each required key and each provider-issued secret (S3, API, SMTP…) |
|
|
20
|
+
| `package.json`, `prisma.config.ts`, `prisma/tenants/` | `app`, `build.prisma`, `migrate` (`central`/`tenants`, or `command: ['pnpm', 'db:deploy']` when that script is the app's own) |
|
|
21
|
+
| `web/package.json` | `build.web` |
|
|
22
|
+
| a production compose file whose images are variables (`image: ${APP_IMAGE}`) | `runtime: compose(…)`: one image per variable (Dockerfile from `build:`, else `docker/<name>/Dockerfile`), the service on `127.0.0.1` as upstream |
|
|
23
|
+
| otherwise | `runtime: pm2()`, `infra: dockerInfra(app)` for the `DATABASE_URL`, `REDIS_URL`, `S3_*` keys the schema has |
|
|
24
|
+
| `--server`, on the server | the Apache vhosts that already serve the domain (`managed: false`), the ports taken (`avoid`) |
|
|
25
|
+
|
|
26
|
+
It asks the domain, the tenancy and the branch (or takes `--domain`,
|
|
27
|
+
`--tenants`, `--branch`, `--proxy`), never overwrites a config (`--force`),
|
|
28
|
+
and runs `check` on what it wrote.
|
|
15
29
|
|
|
16
30
|
```ts
|
|
17
31
|
import { apache, ask, defineDeploy, dockerInfra, pm2, secret } from '@basaltkit/deploy'
|
|
@@ -46,8 +60,51 @@ export default defineDeploy({
|
|
|
46
60
|
What is true of one server only (a port taken there, another branch) goes in
|
|
47
61
|
`/etc/basalt/<app>.json`: `{ "port": 3002, "infra": { "postgres": { "port": 5434 } } }`.
|
|
48
62
|
|
|
63
|
+
### Typed by your env
|
|
64
|
+
|
|
65
|
+
Give `defineDeploy` the type of your `defineEnv(...)` and every `.env` key the
|
|
66
|
+
config names is completed and checked — `env.fixed`, `generate`, `ask`,
|
|
67
|
+
`derive`, `backup.urlKey`, the infra `urlKey`s, `migrate.env`. Values follow the
|
|
68
|
+
schema: a `z.enum` completes its members, a number takes digits, a boolean
|
|
69
|
+
`'true' | 'false'`.
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
import type { env } from './src/env.js' // type only: the app is never loaded
|
|
73
|
+
import { defineDeploy } from '@basaltkit/deploy'
|
|
74
|
+
|
|
75
|
+
export default defineDeploy<typeof env>({
|
|
76
|
+
env: { fixed: { NODE_ENV: 'prod' } }, // ✗ '"prod"' is not assignable to '"development" | "production" | "test"'
|
|
77
|
+
backup: { urlKey: 'DATABSE_URL' }, // ✗ … Did you mean '"DATABASE_URL"'?
|
|
78
|
+
// …
|
|
79
|
+
})
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Without the type argument every key is a plain string, as before.
|
|
83
|
+
`basalt-deploy check` runs the same checks without a server — the config's
|
|
84
|
+
own validation, then your `tsc` on `deploy.config.ts` with your tsconfig — so
|
|
85
|
+
CI catches them too.
|
|
86
|
+
|
|
49
87
|
## On a new server
|
|
50
88
|
|
|
89
|
+
A fresh Ubuntu or Debian with Node, three commands:
|
|
90
|
+
|
|
91
|
+
```sh
|
|
92
|
+
git clone <repo> /srv/myapp && cd /srv/myapp
|
|
93
|
+
sudo npx -y -p @basaltkit/deploy basalt-deploy bootstrap --user=ubuntu # --dry-run first, to see it
|
|
94
|
+
node node_modules/@basaltkit/deploy/dist/bin.js run # as ubuntu, from then on
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
`bootstrap` installs only what is missing — base packages, Docker with compose,
|
|
98
|
+
Node at `engines.node` (NodeSource), the pnpm the lockfile records, swap when
|
|
99
|
+
RAM is under 6 GB (`bootstrap.swapGb`), ufw with SSH and 80/443 (turned on only
|
|
100
|
+
when nothing else listens; `--no-firewall`), Caddy when the proxy is `caddy()` —
|
|
101
|
+
gives the checkout and the `docker` group to the user (said plainly: that group
|
|
102
|
+
is root on the machine; rootless Docker is a later step), then runs, as the
|
|
103
|
+
user, `pnpm install` and `env` (it asks what it cannot generate) and, as root,
|
|
104
|
+
`install`. A step that fails stops it; running it again redoes nothing done.
|
|
105
|
+
|
|
106
|
+
By hand, the same thing:
|
|
107
|
+
|
|
51
108
|
```sh
|
|
52
109
|
# as the app user (never root), in the checkout:
|
|
53
110
|
pnpm install
|
|
@@ -71,13 +128,26 @@ refuses a modified tree.
|
|
|
71
128
|
preflight probes the remote with prompts disabled, warns at a terminal and
|
|
72
129
|
stops before anything changes when nobody can type them (cron, CI).
|
|
73
130
|
|
|
74
|
-
|
|
75
|
-
every deploy checks it.
|
|
131
|
+
With Apache the TLS certificate is yours to issue (`certbot --dns-cloudflare -d <domain> -d '*.<domain>'`);
|
|
132
|
+
every deploy checks it. With Caddy it is Caddy's:
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
proxy: caddy({ onDemandTls: { ask: '/tls/allowed' } }), // tenants: a certificate per host, for hosts the app vouches for
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`install` writes `/etc/caddy/sites/<app>.caddy` — the apex (and `*.<domain>`
|
|
139
|
+
with tenants), `/api/` stripped to the app, `web/dist` with the SPA fallback —
|
|
140
|
+
and, on a server still on the package's Caddyfile, a main file that imports it
|
|
141
|
+
and asks the app before each certificate. Someone's own Caddyfile only gets the
|
|
142
|
+
import line. `caddy validate` runs before the reload; a failure puts every file
|
|
143
|
+
back. Deploys diff the site and never rewrite it; C1, C2 (not imported) and C8
|
|
144
|
+
(no `ask`) are checked as for Apache.
|
|
76
145
|
|
|
77
146
|
## Commands
|
|
78
147
|
|
|
79
148
|
| | |
|
|
80
149
|
|---|---|
|
|
150
|
+
| `check` | the config is valid and types check (your `tsc`). No server needed — for CI. |
|
|
81
151
|
| `plan` | every check, then what `run` would do. Writes nothing, asks nothing. |
|
|
82
152
|
| `run` | preflight → fetch → env → infra → build → validate → backup → migrate → release → health → record |
|
|
83
153
|
| `env` | the `.env` and the containers only |
|
|
@@ -126,6 +196,46 @@ migrate: {
|
|
|
126
196
|
},
|
|
127
197
|
```
|
|
128
198
|
|
|
199
|
+
**Services you keep but do not create** (RFC 0007 §4) — containers that outlive
|
|
200
|
+
any release, adopted by name:
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
infra: external({
|
|
204
|
+
postgres: {
|
|
205
|
+
container: 'myapp-postgres',
|
|
206
|
+
urlKey: 'OWNER_DATABASE_URL', // the owner: role, grants and the dump run as it
|
|
207
|
+
appRole: { name: 'myapp_app', urlKey: 'DATABASE_URL' }, // what the app connects as: no DDL
|
|
208
|
+
},
|
|
209
|
+
redis: { container: 'myapp-redis' },
|
|
210
|
+
minio: { container: 'minio', buckets: [{ name: 'myapp-documents', versioned: true }, { name: 'myapp-quarantine', expireDays: 1 }] },
|
|
211
|
+
}),
|
|
212
|
+
runtime: compose({
|
|
213
|
+
// …
|
|
214
|
+
attach: { 'myapp-postgres': ['data'], 'myapp-redis': ['data', 'sandbox'] }, // onto <app>_<network> before up
|
|
215
|
+
jobs: [{ service: 'freshclam', command: ['freshclam', '--stdout'], once: { exists: '/var/lib/clamav/main.c?d' } }],
|
|
216
|
+
}),
|
|
217
|
+
verify: {
|
|
218
|
+
logs: { 'ingest-worker': ['EAI_AGAIN', 'ECONNREFUSED'] }, // since the release started; found → rolled back
|
|
219
|
+
http: [{ path: '/readyz' }],
|
|
220
|
+
},
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
- **Preflight:** each container running; every service and container name the
|
|
224
|
+
config uses exists (`did you mean "ingest-worker"?`).
|
|
225
|
+
- **The role:** created when missing, its password the `.env`'s (generated from
|
|
226
|
+
the owner's URL when the key is absent), proven over TCP before anything is
|
|
227
|
+
changed, granted DML through the owner's default privileges — never on
|
|
228
|
+
existing tables, which an app may keep append-only. With `migrate.tenants`,
|
|
229
|
+
every `tenant_*` schema too, after the migration.
|
|
230
|
+
- **Buckets:** created; versioning on; the expiry rule added once — the rules
|
|
231
|
+
are read first. The credentials are the running MinIO's.
|
|
232
|
+
- **Attach:** on a fresh server the project is created first (`up --no-start`)
|
|
233
|
+
so its networks exist and the first release is healthy, not the second.
|
|
234
|
+
- **Jobs:** `docker compose run --rm --no-deps` with this commit's images,
|
|
235
|
+
before `up`; `once` skips them when the path exists.
|
|
236
|
+
- **The dump** runs inside `infra.postgres.container` as the owner.
|
|
237
|
+
- `dockerInfra` services take `container` (adopt another name) and `appRole` too.
|
|
238
|
+
|
|
129
239
|
**Hooks** — what only your app does, as commands that also run by hand:
|
|
130
240
|
|
|
131
241
|
```ts
|
|
@@ -148,6 +258,10 @@ checks C2 and C1 on each vhost on every deploy and never writes them.
|
|
|
148
258
|
- The dump before migrating — when something is migrated and there is a
|
|
149
259
|
Postgres to dump (dedicated, or a `postgres://` URL in the `.env`);
|
|
150
260
|
`backup.beforeMigrate` forces it either way. `plan` says why when it is skipped.
|
|
261
|
+
With external infra in a container, `backup: { container: 'myapp-postgres' }`
|
|
262
|
+
runs `pg_dump` inside it (`docker exec`), as the user and database of the
|
|
263
|
+
URL at `backup.urlKey` — the server's own pg_dump, none needed on the host.
|
|
264
|
+
The preflight checks the container is running.
|
|
151
265
|
|
|
152
266
|
## What it refuses to do
|
|
153
267
|
|
package/dist/backup.d.ts
CHANGED
|
@@ -6,8 +6,10 @@ import type { InfraPlan } from './infra.js';
|
|
|
6
6
|
* schema-per-tenant every company's schema is in the same database, so one
|
|
7
7
|
* dump covers them all.
|
|
8
8
|
*
|
|
9
|
-
* With dedicated infra the dump runs INSIDE the
|
|
10
|
-
* as the server, by construction
|
|
9
|
+
* With dedicated infra, or `backup.container`, the dump runs INSIDE the
|
|
10
|
+
* container: same pg_dump major as the server, by construction. The password,
|
|
11
|
+
* when there is one, travels in the environment (`docker exec -e PGPASSWORD`,
|
|
12
|
+
* no value), never on a command line.
|
|
11
13
|
*/
|
|
12
14
|
export declare function backupDatabase(ctx: DeployContext, values: Map<string, string>, infra: InfraPlan, sha: string): Promise<string>;
|
|
13
|
-
export declare function restoreCommand(ctx: DeployContext, infra: InfraPlan, file: string): string;
|
|
15
|
+
export declare function restoreCommand(ctx: DeployContext, infra: InfraPlan, file: string, values?: Map<string, string>): string;
|
package/dist/backup.js
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import { join } from 'node:path';
|
|
2
2
|
import { DeployError } from './context.js';
|
|
3
|
+
import { dumpContainer, dumpUrlKey } from './services.js';
|
|
3
4
|
/**
|
|
4
5
|
* `pg_dump -Fc` of the central database before migrating — migrations do not
|
|
5
6
|
* undo themselves, and rollback restores code only (RFC 0006 §8). With
|
|
6
7
|
* schema-per-tenant every company's schema is in the same database, so one
|
|
7
8
|
* dump covers them all.
|
|
8
9
|
*
|
|
9
|
-
* With dedicated infra the dump runs INSIDE the
|
|
10
|
-
* as the server, by construction
|
|
10
|
+
* With dedicated infra, or `backup.container`, the dump runs INSIDE the
|
|
11
|
+
* container: same pg_dump major as the server, by construction. The password,
|
|
12
|
+
* when there is one, travels in the environment (`docker exec -e PGPASSWORD`,
|
|
13
|
+
* no value), never on a command line.
|
|
11
14
|
*/
|
|
12
15
|
export async function backupDatabase(ctx, values, infra, sha) {
|
|
13
16
|
const { host, config } = ctx;
|
|
@@ -21,16 +24,19 @@ export async function backupDatabase(ctx, values, infra, sha) {
|
|
|
21
24
|
result = await host.exec('docker', ['exec', pg.container, 'pg_dump', '-U', pg.user ?? config.app, '-d', pg.database ?? config.app, '--format=custom', '--no-owner', '--no-acl'], { stdoutFile: file });
|
|
22
25
|
}
|
|
23
26
|
else {
|
|
24
|
-
const
|
|
25
|
-
const raw = values.get(key);
|
|
26
|
-
if (!raw)
|
|
27
|
-
throw new DeployError(`backup: ${key} is not set in the .env`);
|
|
28
|
-
const url = new URL(raw);
|
|
27
|
+
const url = databaseUrl(ctx, values);
|
|
29
28
|
const password = decodeURIComponent(url.password);
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
29
|
+
const container = dumpContainer(config);
|
|
30
|
+
if (container) {
|
|
31
|
+
const args = ['exec', '-e', 'PGPASSWORD', container, 'pg_dump', '-U', decodeURIComponent(url.username), '-d', databaseName(url), '--format=custom', '--no-owner', '--no-acl'];
|
|
32
|
+
result = await host.exec('docker', args, { stdoutFile: file, env: { PGPASSWORD: password } });
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
url.password = '';
|
|
36
|
+
// Prisma's `?schema=` is not a libpq parameter; pg_dump refuses it.
|
|
37
|
+
url.search = '';
|
|
38
|
+
result = await host.exec('pg_dump', ['--dbname', url.toString(), '--format=custom', '--no-owner', '--no-acl'], { stdoutFile: file, env: { PGPASSWORD: password } });
|
|
39
|
+
}
|
|
34
40
|
}
|
|
35
41
|
const size = (await host.stat(file))?.size ?? 0;
|
|
36
42
|
if (result.code !== 0 || size === 0) {
|
|
@@ -43,9 +49,24 @@ export async function backupDatabase(ctx, values, infra, sha) {
|
|
|
43
49
|
await host.remove(join(dir, old));
|
|
44
50
|
return file;
|
|
45
51
|
}
|
|
46
|
-
export function restoreCommand(ctx, infra, file) {
|
|
52
|
+
export function restoreCommand(ctx, infra, file, values = new Map()) {
|
|
47
53
|
const pg = infra.services.find((s) => s.service === 'postgres');
|
|
48
54
|
if (pg)
|
|
49
55
|
return `docker exec -i ${pg.container} pg_restore --clean --if-exists --no-owner -U ${pg.user ?? ctx.config.app} -d ${pg.database ?? ctx.config.app} < ${file}`;
|
|
56
|
+
const container = dumpContainer(ctx.config);
|
|
57
|
+
if (container) {
|
|
58
|
+
const url = databaseUrl(ctx, values);
|
|
59
|
+
return `docker exec -i ${container} pg_restore --clean --if-exists --no-owner -U ${decodeURIComponent(url.username)} -d ${databaseName(url)} < ${file}`;
|
|
60
|
+
}
|
|
50
61
|
return `pg_restore --clean --if-exists --no-owner --dbname "<the database URL, without ?schema=>" ${file}`;
|
|
51
62
|
}
|
|
63
|
+
function databaseUrl(ctx, values) {
|
|
64
|
+
const key = dumpUrlKey(ctx.config);
|
|
65
|
+
const raw = values.get(key);
|
|
66
|
+
if (!raw)
|
|
67
|
+
throw new DeployError(`backup: ${key} is not set in the .env`);
|
|
68
|
+
return new URL(raw);
|
|
69
|
+
}
|
|
70
|
+
function databaseName(url) {
|
|
71
|
+
return decodeURIComponent(url.pathname.replace(/^\//, ''));
|
|
72
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Host } from './host.js';
|
|
2
|
+
/**
|
|
3
|
+
* `basalt-deploy bootstrap` — a fresh Ubuntu/Debian server, once (RFC 0007 §7).
|
|
4
|
+
* Root. Installs only what is missing, then hands over to the app user:
|
|
5
|
+
*
|
|
6
|
+
* base packages · Docker + compose · Node at engines.node · the pnpm the
|
|
7
|
+
* lockfile records · swap (< 6 GB RAM) · ufw (only when nothing but SSH
|
|
8
|
+
* listens) · Caddy (proxy: caddy) · the checkout and the docker group for
|
|
9
|
+
* the user · then, as the user, `pnpm install` and `env`, and as root,
|
|
10
|
+
* `install`.
|
|
11
|
+
*
|
|
12
|
+
* It needs no node_modules and no loaded config: it runs before either exists
|
|
13
|
+
* (`sudo npx -y -p @basaltkit/deploy basalt-deploy bootstrap --user=<u>`), so it
|
|
14
|
+
* reads package.json and takes the proxy and swap from flags.
|
|
15
|
+
*
|
|
16
|
+
* `--dry-run` prints every command and runs none.
|
|
17
|
+
*/
|
|
18
|
+
export interface BootstrapOptions {
|
|
19
|
+
user: string | undefined;
|
|
20
|
+
proxy: 'apache' | 'caddy' | 'none';
|
|
21
|
+
swapGb: number;
|
|
22
|
+
firewall: boolean;
|
|
23
|
+
dryRun: boolean;
|
|
24
|
+
}
|
|
25
|
+
interface Action {
|
|
26
|
+
what: string;
|
|
27
|
+
commands: string[][];
|
|
28
|
+
}
|
|
29
|
+
/** What a fresh server needs, given what is already there. Pure planning: it runs probes, never changes anything. */
|
|
30
|
+
export declare function planBootstrap(host: Host, dir: string, options: BootstrapOptions): Promise<{
|
|
31
|
+
actions: Action[];
|
|
32
|
+
notes: string[];
|
|
33
|
+
}>;
|
|
34
|
+
export declare function bootstrap(host: Host, dir: string, options: BootstrapOptions): Promise<number>;
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { tmpdir } from 'node:os';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { below, lockedPnpm, minimumVersion } from './checks.js';
|
|
4
|
+
import { DeployError } from './context.js';
|
|
5
|
+
const APT = ['env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get'];
|
|
6
|
+
const OUTSIDE = { cwd: tmpdir() };
|
|
7
|
+
/** What a fresh server needs, given what is already there. Pure planning: it runs probes, never changes anything. */
|
|
8
|
+
export async function planBootstrap(host, dir, options) {
|
|
9
|
+
const actions = [];
|
|
10
|
+
const notes = [];
|
|
11
|
+
const sh = (script) => ['sh', '-c', script];
|
|
12
|
+
const has = async (command) => (await host.exec('sh', ['-c', `command -v ${command}`], OUTSIDE)).code === 0;
|
|
13
|
+
if (!(await has('apt-get')))
|
|
14
|
+
throw new DeployError('bootstrap installs with apt: Ubuntu or Debian only');
|
|
15
|
+
const packages = [];
|
|
16
|
+
for (const name of ['ca-certificates', 'curl', 'git', 'openssl', 'gnupg']) {
|
|
17
|
+
if ((await host.exec('dpkg', ['-s', name], OUTSIDE)).code !== 0)
|
|
18
|
+
packages.push(name);
|
|
19
|
+
}
|
|
20
|
+
if (packages.length)
|
|
21
|
+
actions.push({ what: `packages: ${packages.join(', ')}`, commands: [[...APT, 'update', '-qq'], [...APT, 'install', '-y', '-qq', ...packages]] });
|
|
22
|
+
if ((await host.exec('docker', ['compose', 'version'], OUTSIDE)).code !== 0) {
|
|
23
|
+
actions.push({
|
|
24
|
+
what: 'Docker + compose (download.docker.com)',
|
|
25
|
+
commands: [
|
|
26
|
+
['install', '-m', '0755', '-d', '/etc/apt/keyrings'],
|
|
27
|
+
sh('curl -fsSL https://download.docker.com/linux/$(. /etc/os-release && echo "$ID")/gpg -o /etc/apt/keyrings/docker.asc && chmod a+r /etc/apt/keyrings/docker.asc'),
|
|
28
|
+
sh('echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/$(. /etc/os-release && echo "$ID") $(. /etc/os-release && echo "$VERSION_CODENAME") stable" > /etc/apt/sources.list.d/docker.list'),
|
|
29
|
+
[...APT, 'update', '-qq'],
|
|
30
|
+
[...APT, 'install', '-y', '-qq', 'docker-ce', 'docker-ce-cli', 'containerd.io', 'docker-buildx-plugin', 'docker-compose-plugin'],
|
|
31
|
+
['systemctl', 'enable', '--now', 'docker'],
|
|
32
|
+
],
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
let pkg = {};
|
|
36
|
+
try {
|
|
37
|
+
pkg = JSON.parse((await host.readFile(join(dir, 'package.json'))) ?? '{}');
|
|
38
|
+
}
|
|
39
|
+
catch { /* reported by run's C9 */ }
|
|
40
|
+
const wanted = minimumVersion(pkg.engines?.node);
|
|
41
|
+
const node = minimumVersion((await host.exec('node', ['--version'], OUTSIDE)).stdout);
|
|
42
|
+
if (!node || (wanted && below(node, wanted))) {
|
|
43
|
+
// §11.1: NodeSource — it updates with apt. The current LTS line, or the engines' major if newer.
|
|
44
|
+
const major = Math.max(24, wanted?.[0] ?? 0);
|
|
45
|
+
actions.push({ what: `Node ${major} (NodeSource; engines.node ${pkg.engines?.node ?? 'unset'})`, commands: [sh(`curl -fsSL https://deb.nodesource.com/setup_${major}.x | bash -`), [...APT, 'install', '-y', '-qq', 'nodejs']] });
|
|
46
|
+
}
|
|
47
|
+
if (pkg.packageManager?.startsWith('pnpm@')) {
|
|
48
|
+
// The lockfile's own pnpm when it records one (C11), else packageManager's.
|
|
49
|
+
const lockfile = await host.readFile(join(dir, 'pnpm-lock.yaml'));
|
|
50
|
+
const version = (lockfile && lockedPnpm(lockfile)) ?? pkg.packageManager.slice('pnpm@'.length).split('+')[0];
|
|
51
|
+
const current = (await host.exec('pnpm', ['--version'], OUTSIDE)).stdout.trim();
|
|
52
|
+
if (current !== version)
|
|
53
|
+
actions.push({ what: `pnpm ${version}${current ? ` (this server has ${current})` : ''}`, commands: [['npm', 'install', '-g', `pnpm@${version}`]] });
|
|
54
|
+
}
|
|
55
|
+
const meminfo = (await host.readFile('/proc/meminfo')) ?? '';
|
|
56
|
+
const memGb = Number(/MemTotal:\s+(\d+)/.exec(meminfo)?.[1] ?? 0) / 1024 / 1024;
|
|
57
|
+
const swapKb = Number(/SwapTotal:\s+(\d+)/.exec(meminfo)?.[1] ?? 0);
|
|
58
|
+
if (options.swapGb > 0 && meminfo && memGb < 6 && swapKb === 0 && !(await host.exists('/swapfile'))) {
|
|
59
|
+
actions.push({
|
|
60
|
+
what: `swap ${options.swapGb} GB (${memGb.toFixed(1)} GB RAM, none yet)`,
|
|
61
|
+
commands: [['fallocate', '-l', `${options.swapGb}G`, '/swapfile'], ['chmod', '600', '/swapfile'], ['mkswap', '/swapfile'], ['swapon', '/swapfile'], sh("grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab")],
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
if (options.firewall && (await has('ufw'))) {
|
|
65
|
+
// SSH_CONNECTION = "client-ip client-port server-ip server-port": split, not a regex over input.
|
|
66
|
+
const sshPort = (host.env['SSH_CONNECTION'] ?? '').trim().split(/\s+/)[3];
|
|
67
|
+
const ssh = sshPort && /^\d+$/.test(sshPort) ? sshPort : '22';
|
|
68
|
+
const web = options.proxy === 'none' ? [] : [['ufw', 'allow', '80/tcp'], ['ufw', 'allow', '443/tcp']];
|
|
69
|
+
const active = (await host.exec('ufw', ['status'], OUTSIDE)).stdout.includes('Status: active');
|
|
70
|
+
if (active) {
|
|
71
|
+
actions.push({ what: `ufw: SSH (${ssh})${web.length ? ', 80, 443' : ''} allowed`, commands: [['ufw', 'allow', `${ssh}/tcp`], ...web] });
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
// Turning ufw ON is safe on a fresh machine only: on a shared one it cuts every service not listed.
|
|
75
|
+
// ss -ltnH: "LISTEN 0 128 0.0.0.0:22 0.0.0.0:*" — the 4th column is the local address.
|
|
76
|
+
const listening = (await host.exec('ss', ['-ltnH'], OUTSIDE)).stdout.split('\n')
|
|
77
|
+
.map((l) => l.trim().split(/\s+/)[3] ?? '')
|
|
78
|
+
.filter((local) => local.includes(':') && !/^(127\.|\[::1\]|::1)/.test(local))
|
|
79
|
+
.map((local) => local.slice(local.lastIndexOf(':') + 1));
|
|
80
|
+
const others = [...new Set(listening.filter((p) => p !== ssh))];
|
|
81
|
+
if (others.length)
|
|
82
|
+
notes.push(`ufw is off and ports ${others.join(', ')} listen: not turned on, so nothing is cut off — configure it by hand`);
|
|
83
|
+
else
|
|
84
|
+
actions.push({ what: `ufw on: SSH (${ssh})${web.length ? ', 80, 443' : ''} only`, commands: [['ufw', 'allow', `${ssh}/tcp`], ...web, ['ufw', '--force', 'enable']] });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (options.proxy === 'caddy' && !(await has('caddy'))) {
|
|
88
|
+
actions.push({
|
|
89
|
+
what: 'Caddy (cloudsmith)',
|
|
90
|
+
commands: [
|
|
91
|
+
[...APT, 'install', '-y', '-qq', 'debian-keyring', 'debian-archive-keyring', 'apt-transport-https'],
|
|
92
|
+
sh("curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg"),
|
|
93
|
+
sh("curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' > /etc/apt/sources.list.d/caddy-stable.list"),
|
|
94
|
+
[...APT, 'update', '-qq'],
|
|
95
|
+
[...APT, 'install', '-y', '-qq', 'caddy'],
|
|
96
|
+
],
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
const user = options.user;
|
|
100
|
+
const owner = (await host.exec('stat', ['-c', '%U', dir], OUTSIDE)).stdout.trim();
|
|
101
|
+
if (owner !== user)
|
|
102
|
+
actions.push({ what: `${dir} owned by ${user}`, commands: [['chown', '-R', `${user}:`, dir]] });
|
|
103
|
+
const groups = (await host.exec('id', ['-nG', user], OUTSIDE)).stdout.split(/\s+/);
|
|
104
|
+
if (!groups.includes('docker')) {
|
|
105
|
+
// §11.2: the docker group, said plainly — rootless Docker is its own phase.
|
|
106
|
+
actions.push({ what: `${user} in the docker group`, commands: [['usermod', '-aG', 'docker', user]] });
|
|
107
|
+
notes.push(`${user} is now in the docker group — that is root on this machine (a container can mount /). Rootless Docker is a later step; it moves every volume.`);
|
|
108
|
+
}
|
|
109
|
+
// As the user, from the checkout: the project's own tools from here on.
|
|
110
|
+
const asUser = (...command) => ['sudo', '-u', user, '-H', '--', ...command];
|
|
111
|
+
actions.push({
|
|
112
|
+
what: `as ${user}: dependencies, then the .env (asks what it cannot generate)`,
|
|
113
|
+
commands: [
|
|
114
|
+
asUser('env', '-u', 'NODE_ENV', 'sh', '-c', `cd '${dir}' && pnpm install --frozen-lockfile`),
|
|
115
|
+
asUser('sh', '-c', `cd '${dir}' && node node_modules/@basaltkit/deploy/dist/bin.js env`),
|
|
116
|
+
],
|
|
117
|
+
});
|
|
118
|
+
actions.push({ what: 'install (root): state directory, the proxy site, env ownership', commands: [['sh', '-c', `cd '${dir}' && node node_modules/@basaltkit/deploy/dist/bin.js install --user=${user}`]] });
|
|
119
|
+
return { actions, notes };
|
|
120
|
+
}
|
|
121
|
+
export async function bootstrap(host, dir, options) {
|
|
122
|
+
if (!options.user || options.user === 'root')
|
|
123
|
+
throw new DeployError('bootstrap needs the unprivileged user the deploys will run as: --user=<name> (never root)');
|
|
124
|
+
if (!options.dryRun && host.uid() !== 0)
|
|
125
|
+
throw new DeployError('bootstrap installs packages: run it with sudo (or --dry-run to see what it would do)');
|
|
126
|
+
if ((await host.exec('id', ['-u', options.user], OUTSIDE)).code !== 0)
|
|
127
|
+
throw new DeployError(`no user ${options.user} on this server: adduser ${options.user} first`);
|
|
128
|
+
host.out.step(`bootstrap${options.dryRun ? ' — dry run, nothing below runs' : ''}`);
|
|
129
|
+
const { actions, notes } = await planBootstrap(host, dir, options);
|
|
130
|
+
for (const action of actions) {
|
|
131
|
+
host.out.info(action.what);
|
|
132
|
+
for (const command of action.commands) {
|
|
133
|
+
host.out.info(` + ${command.join(' ')}`);
|
|
134
|
+
if (options.dryRun)
|
|
135
|
+
continue;
|
|
136
|
+
const result = await host.exec(command[0], command.slice(1), { stream: true });
|
|
137
|
+
if (result.code !== 0)
|
|
138
|
+
throw new DeployError(`${action.what}: \`${command.join(' ')}\` failed (exit ${result.code}) — re-run bootstrap after fixing it; what is done is not redone`);
|
|
139
|
+
}
|
|
140
|
+
if (!options.dryRun)
|
|
141
|
+
host.out.ok(action.what);
|
|
142
|
+
}
|
|
143
|
+
for (const note of notes)
|
|
144
|
+
host.out.warn(note);
|
|
145
|
+
if (!options.dryRun)
|
|
146
|
+
host.out.ok(`server ready — from now on, as ${options.user} in ${dir}: node node_modules/@basaltkit/deploy/dist/bin.js run`);
|
|
147
|
+
return 0;
|
|
148
|
+
}
|
package/dist/caddy.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { CaddyProxy } from './config.js';
|
|
2
|
+
import { type DeployContext, type Finding } from './context.js';
|
|
3
|
+
/**
|
|
4
|
+
* The Caddy target (RFC 0007 §8): one site file per app, imported by the main
|
|
5
|
+
* Caddyfile. `install` writes it (and, on a server whose Caddyfile is still
|
|
6
|
+
* the package's, the main file), validates, reloads; deploys compare and never
|
|
7
|
+
* rewrite — the same contract as the Apache vhost (RFC 0006 §11.3).
|
|
8
|
+
*/
|
|
9
|
+
export declare const caddyOf: (ctx: DeployContext) => CaddyProxy;
|
|
10
|
+
export declare function caddyPaths(ctx: DeployContext): {
|
|
11
|
+
root: string;
|
|
12
|
+
main: string;
|
|
13
|
+
dir: string;
|
|
14
|
+
site: string;
|
|
15
|
+
importLine: string;
|
|
16
|
+
};
|
|
17
|
+
export declare function renderSite(ctx: DeployContext, port: number): string;
|
|
18
|
+
/** The main Caddyfile this package writes on a server that has none of its own yet. */
|
|
19
|
+
export declare function renderMain(ctx: DeployContext, port: number): string;
|
|
20
|
+
/** The ports a site file proxies to on this machine. */
|
|
21
|
+
export declare function caddyProxiedPorts(site: string): number[];
|
|
22
|
+
export declare function caddyPreflight(ctx: DeployContext, port: number): Promise<Finding[]>;
|
|
23
|
+
/** Root only. Writes the site (after the diff and a yes), the main Caddyfile if it is still the stock one, validates, reloads. */
|
|
24
|
+
export declare function caddyInstall(ctx: DeployContext, port: number, backupDir: string): Promise<void>;
|
package/dist/caddy.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { DeployError, INSTALL_COMMAND } from './context.js';
|
|
3
|
+
import { lineDiff } from './diff.js';
|
|
4
|
+
/**
|
|
5
|
+
* The Caddy target (RFC 0007 §8): one site file per app, imported by the main
|
|
6
|
+
* Caddyfile. `install` writes it (and, on a server whose Caddyfile is still
|
|
7
|
+
* the package's, the main file), validates, reloads; deploys compare and never
|
|
8
|
+
* rewrite — the same contract as the Apache vhost (RFC 0006 §11.3).
|
|
9
|
+
*/
|
|
10
|
+
export const caddyOf = (ctx) => {
|
|
11
|
+
if (ctx.config.proxy?.kind !== 'caddy')
|
|
12
|
+
throw new Error('not a caddy proxy');
|
|
13
|
+
return ctx.config.proxy;
|
|
14
|
+
};
|
|
15
|
+
export function caddyPaths(ctx) {
|
|
16
|
+
const root = caddyOf(ctx).root ?? '/etc/caddy';
|
|
17
|
+
return { root, main: join(root, 'Caddyfile'), dir: join(root, 'sites'), site: join(root, 'sites', `${ctx.config.app}.caddy`), importLine: `import ${join(root, 'sites')}/*.caddy` };
|
|
18
|
+
}
|
|
19
|
+
export function renderSite(ctx, port) {
|
|
20
|
+
const proxy = caddyOf(ctx);
|
|
21
|
+
const { app, domain } = ctx.config;
|
|
22
|
+
const hosts = ctx.config.tenants === 'subdomain' ? `${domain}, *.${domain}` : domain;
|
|
23
|
+
const prefix = proxy.apiPrefix.replace(/\/$/, '');
|
|
24
|
+
const tls = proxy.onDemandTls ? '\n\ttls {\n\t\ton_demand\n\t}\n' : '';
|
|
25
|
+
return `# Written by basalt-deploy install for "${app}". Deploys compare this file with
|
|
26
|
+
# what install would write and print the difference; they never rewrite it.
|
|
27
|
+
# To change it: edit deploy.config.ts, then sudo basalt-deploy install.
|
|
28
|
+
|
|
29
|
+
${hosts} {${tls}
|
|
30
|
+
\tencode gzip
|
|
31
|
+
|
|
32
|
+
\t# The API: ${prefix}/x reaches the app as /x; the Host is kept — the tenant is read from it.
|
|
33
|
+
\thandle ${prefix}/* {
|
|
34
|
+
\t\turi strip_prefix ${prefix}
|
|
35
|
+
\t\treverse_proxy 127.0.0.1:${port} {
|
|
36
|
+
\t\t\tflush_interval -1
|
|
37
|
+
\t\t}
|
|
38
|
+
\t}
|
|
39
|
+
|
|
40
|
+
\thandle {
|
|
41
|
+
\t\troot * ${join(ctx.dir, proxy.webRoot)}
|
|
42
|
+
\t\ttry_files {path} /index.html
|
|
43
|
+
\t\tfile_server
|
|
44
|
+
\t}
|
|
45
|
+
}
|
|
46
|
+
${proxy.extra ? `\n${proxy.extra.trim()}\n` : ''}`;
|
|
47
|
+
}
|
|
48
|
+
/** The main Caddyfile this package writes on a server that has none of its own yet. */
|
|
49
|
+
export function renderMain(ctx, port) {
|
|
50
|
+
const proxy = caddyOf(ctx);
|
|
51
|
+
const ask = proxy.onDemandTls ? `\n\ton_demand_tls {\n\t\task http://127.0.0.1:${port}${proxy.onDemandTls.ask}\n\t}\n` : '';
|
|
52
|
+
return `# Written by basalt-deploy install. Each app's site is in ${caddyPaths(ctx).dir}/.
|
|
53
|
+
{${ask}}
|
|
54
|
+
|
|
55
|
+
${caddyPaths(ctx).importLine}
|
|
56
|
+
`;
|
|
57
|
+
}
|
|
58
|
+
/** The ports a site file proxies to on this machine. */
|
|
59
|
+
export function caddyProxiedPorts(site) {
|
|
60
|
+
return [...site.matchAll(/^\s*reverse_proxy\s+(?:https?:\/\/)?(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/gm)].map((m) => Number(m[1]));
|
|
61
|
+
}
|
|
62
|
+
/** The main Caddyfile is the one the package installs (it serves /usr/share/caddy) — safe to replace. */
|
|
63
|
+
const isStock = (text) => text === undefined || /\/usr\/share\/caddy/.test(text) && !/^\s*import\s/m.test(text);
|
|
64
|
+
export async function caddyPreflight(ctx, port) {
|
|
65
|
+
const { host } = ctx;
|
|
66
|
+
const proxy = caddyOf(ctx);
|
|
67
|
+
const paths = caddyPaths(ctx);
|
|
68
|
+
const findings = [];
|
|
69
|
+
const main = await host.readFile(paths.main);
|
|
70
|
+
const site = await host.readFile(paths.site);
|
|
71
|
+
if (site === undefined) {
|
|
72
|
+
return [{ id: 'proxy', level: 'error', message: `no Caddy site ${paths.site} yet`, fix: `${INSTALL_COMMAND} (once per server)` }];
|
|
73
|
+
}
|
|
74
|
+
// C2 for Caddy: a site file the main Caddyfile does not import is not served.
|
|
75
|
+
if (!main?.includes(paths.importLine)) {
|
|
76
|
+
findings.push({ id: 'C2', level: 'error', message: `${paths.main} does not import ${paths.dir}/*.caddy: ${paths.site} is not served`, fix: `add "${paths.importLine}" to ${paths.main}, then sudo systemctl reload caddy` });
|
|
77
|
+
}
|
|
78
|
+
if (proxy.onDemandTls && !main?.includes(`ask http://127.0.0.1:${port}${proxy.onDemandTls.ask}`)) {
|
|
79
|
+
findings.push({
|
|
80
|
+
id: 'C8',
|
|
81
|
+
level: 'error',
|
|
82
|
+
message: `on-demand TLS: ${paths.main} does not ask http://127.0.0.1:${port}${proxy.onDemandTls.ask} — a tenant host gets no certificate`,
|
|
83
|
+
fix: `in the global block of ${paths.main}: on_demand_tls { ask http://127.0.0.1:${port}${proxy.onDemandTls.ask} }`,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
for (const proxied of caddyProxiedPorts(site)) {
|
|
87
|
+
if (proxied !== port) {
|
|
88
|
+
findings.push({ id: 'C1', level: 'error', message: `${paths.site} proxies to 127.0.0.1:${proxied}, but the app listens on ${port}`, fix: `${INSTALL_COMMAND} (shows the diff and rewrites it)` });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (proxy.managed !== false) {
|
|
92
|
+
const diff = lineDiff(site, renderSite(ctx, port));
|
|
93
|
+
if (diff.length > 0) {
|
|
94
|
+
findings.push({
|
|
95
|
+
id: 'vhost',
|
|
96
|
+
level: 'warning',
|
|
97
|
+
message: `the installed Caddy site differs from what install would write (not changed — audit only):\n${diff.map((l) => ` ${l}`).join('\n')}`,
|
|
98
|
+
fix: `to apply: ${INSTALL_COMMAND}`,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return findings;
|
|
103
|
+
}
|
|
104
|
+
/** Root only. Writes the site (after the diff and a yes), the main Caddyfile if it is still the stock one, validates, reloads. */
|
|
105
|
+
export async function caddyInstall(ctx, port, backupDir) {
|
|
106
|
+
const { host } = ctx;
|
|
107
|
+
const paths = caddyPaths(ctx);
|
|
108
|
+
const stamp = host.now().toISOString().replace(/[-:]/g, '').replace(/\..+$/, '');
|
|
109
|
+
const restore = [];
|
|
110
|
+
const put = async (path, wanted, label) => {
|
|
111
|
+
const current = await host.readFile(path);
|
|
112
|
+
if (current === wanted)
|
|
113
|
+
return;
|
|
114
|
+
if (current !== undefined) {
|
|
115
|
+
host.out.info(`${label} would change:`);
|
|
116
|
+
for (const line of lineDiff(current, wanted))
|
|
117
|
+
host.out.info(` ${line}`);
|
|
118
|
+
if (!(await host.confirm(`Write ${path}?`)))
|
|
119
|
+
throw new DeployError(`${label} not changed (declined)`);
|
|
120
|
+
const backup = join(backupDir, `${path.split('/').pop()}-${stamp}`);
|
|
121
|
+
await host.copyFile(path, backup, 0o600);
|
|
122
|
+
restore.push(() => host.copyFile(backup, path, 0o644));
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
restore.push(() => host.remove(path));
|
|
126
|
+
}
|
|
127
|
+
await host.writeFile(path, wanted, 0o644);
|
|
128
|
+
};
|
|
129
|
+
await host.mkdir(paths.dir, 0o755);
|
|
130
|
+
await put(paths.site, renderSite(ctx, port), paths.site);
|
|
131
|
+
const main = await host.readFile(paths.main);
|
|
132
|
+
if (isStock(main)) {
|
|
133
|
+
await put(paths.main, renderMain(ctx, port), paths.main);
|
|
134
|
+
}
|
|
135
|
+
else if (!main?.includes(paths.importLine)) {
|
|
136
|
+
// Somebody's own Caddyfile: one line added at the end, nothing else touched.
|
|
137
|
+
await put(paths.main, `${main?.trimEnd() ?? ''}\n\n${paths.importLine}\n`, paths.main);
|
|
138
|
+
}
|
|
139
|
+
const after = await host.readFile(paths.main);
|
|
140
|
+
const proxy = caddyOf(ctx);
|
|
141
|
+
if (proxy.onDemandTls && !after?.includes(`ask http://127.0.0.1:${port}${proxy.onDemandTls.ask}`)) {
|
|
142
|
+
host.out.warn(`${paths.main} is not the package's: add on_demand_tls { ask http://127.0.0.1:${port}${proxy.onDemandTls.ask} } to its global block, or tenant hosts get no certificate`);
|
|
143
|
+
}
|
|
144
|
+
const test = await host.exec('caddy', ['validate', '--adapter', 'caddyfile', '--config', paths.main]);
|
|
145
|
+
if (test.code !== 0) {
|
|
146
|
+
for (const undo of restore.reverse())
|
|
147
|
+
await undo();
|
|
148
|
+
throw new DeployError(`caddy validate failed — every file was put back as it was:\n${test.stderr.trim().split('\n').slice(-3).join('\n')}`);
|
|
149
|
+
}
|
|
150
|
+
const reload = await host.exec('systemctl', ['reload-or-restart', 'caddy']);
|
|
151
|
+
if (reload.code !== 0)
|
|
152
|
+
throw new DeployError(`systemctl reload caddy failed: ${reload.stderr.trim()}`);
|
|
153
|
+
host.out.ok(`${paths.site} installed and Caddy reloaded`);
|
|
154
|
+
}
|
package/dist/check.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { DeployConfig } from './config.js';
|
|
2
|
+
import type { Host } from './host.js';
|
|
3
|
+
/**
|
|
4
|
+
* `basalt-deploy check` — the config is valid and types against the app's own
|
|
5
|
+
* env, without touching the server (RFC 0007 §2.2). What CI runs.
|
|
6
|
+
*
|
|
7
|
+
* The runtime checks already ran (the config loaded and `validateConfig`
|
|
8
|
+
* passed). The types are the app's `tsc` on `deploy.config.ts`, with the app's
|
|
9
|
+
* tsconfig but this one file as the only root: an app whose tsconfig covers
|
|
10
|
+
* `src/` only still gets its deploy config checked.
|
|
11
|
+
*/
|
|
12
|
+
export declare function check(host: Host, dir: string, file: string, config: DeployConfig): Promise<number>;
|