@basaltkit/deploy 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +125 -2
- package/dist/apache.d.ts +13 -0
- package/dist/apache.js +179 -0
- package/dist/backup.d.ts +13 -0
- package/dist/backup.js +51 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +3 -0
- package/dist/checks.d.ts +13 -0
- package/dist/checks.js +99 -0
- package/dist/cli.d.ts +8 -0
- package/dist/cli.js +134 -0
- package/dist/config.d.ts +231 -0
- package/dist/config.js +163 -0
- package/dist/context.d.ts +34 -0
- package/dist/context.js +49 -0
- package/dist/diff.d.ts +2 -0
- package/dist/diff.js +33 -0
- package/dist/dotenv.d.ts +47 -0
- package/dist/dotenv.js +145 -0
- package/dist/env-check.d.ts +18 -0
- package/dist/env-check.js +95 -0
- package/dist/env-step.d.ts +29 -0
- package/dist/env-step.js +126 -0
- package/dist/host.d.ts +87 -0
- package/dist/host.js +199 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/infra.d.ts +42 -0
- package/dist/infra.js +242 -0
- package/dist/pipeline.d.ts +49 -0
- package/dist/pipeline.js +432 -0
- package/dist/pm2.d.ts +23 -0
- package/dist/pm2.js +110 -0
- package/dist/ports.d.ts +10 -0
- package/dist/ports.js +27 -0
- package/dist/state.d.ts +20 -0
- package/dist/state.js +34 -0
- package/package.json +48 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Basalt Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,126 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @basaltkit/deploy
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
One deploy pipeline for a Basalt app on a single Linux server: the `.env`,
|
|
4
|
+
dedicated Docker infra (Postgres, Redis, MinIO), PM2, Apache, a database dump
|
|
5
|
+
before migrating, a health check, and a rollback when the new release does not
|
|
6
|
+
answer. Design and decisions: [RFC 0006](../../docs/rfcs/0006-basalt-deploy.md).
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
pnpm add -D @basaltkit/deploy
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## The config
|
|
13
|
+
|
|
14
|
+
`deploy.config.ts` at the app root, committed. It holds **no secrets**.
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { apache, ask, defineDeploy, dockerInfra, pm2, secret } from '@basaltkit/deploy'
|
|
18
|
+
|
|
19
|
+
export default defineDeploy({
|
|
20
|
+
app: 'lexfirma', // names everything it owns: lexfirma-api, lexfirma-pg, …
|
|
21
|
+
domain: 'lexfirma.aipro.ao',
|
|
22
|
+
tenants: 'subdomain', // also checks the *.domain certificate and DNS
|
|
23
|
+
branch: 'master',
|
|
24
|
+
env: {
|
|
25
|
+
schema: 'src/env.ts', // your defineEnv(): the .env is validated against it
|
|
26
|
+
fixed: { NODE_ENV: 'production', HOST: '127.0.0.1' },
|
|
27
|
+
generate: { APP_SECRET: secret(32) },
|
|
28
|
+
ask: {
|
|
29
|
+
MAILER_URL: ask.secret('SMTP URL', { optional: true }),
|
|
30
|
+
PROXYPAY_SECRET_TOKEN: ask.secret('ProxyPay token'),
|
|
31
|
+
},
|
|
32
|
+
derive: ({ domain }) => ({ PROXYPAY_CALLBACK_URL: `https://${domain}/api/webhooks/proxypay` }),
|
|
33
|
+
forbid: ['PROXYPAY_FAKE'],
|
|
34
|
+
},
|
|
35
|
+
infra: dockerInfra('lexfirma', {
|
|
36
|
+
postgres: { urlParams: { schema: 'public' } },
|
|
37
|
+
minio: { buckets: ['lexfirma-documents', 'lexfirma-backups'] },
|
|
38
|
+
}),
|
|
39
|
+
build: { prisma: ['prisma.config.ts', 'prisma/tenants/prisma.config.ts'], web: 'web' },
|
|
40
|
+
migrate: { central: true, tenants: true },
|
|
41
|
+
runtime: pm2({ avoid: [3000, 3001] }), // runs the package.json "start" script
|
|
42
|
+
proxy: apache(), // web/dist at /, /api/ → the app
|
|
43
|
+
})
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
What is true of one server only (a port taken there, another branch) goes in
|
|
47
|
+
`/etc/basalt/<app>.json`: `{ "port": 3002, "infra": { "postgres": { "port": 5434 } } }`.
|
|
48
|
+
|
|
49
|
+
## On a new server
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
# as the app user (never root), in the checkout:
|
|
53
|
+
pnpm install
|
|
54
|
+
pnpm exec basalt-deploy env # writes the .env (asks once), starts the containers, validates
|
|
55
|
+
|
|
56
|
+
# once, as an administrator (node on the file: root often has no pnpm on its PATH):
|
|
57
|
+
sudo node node_modules/@basaltkit/deploy/dist/bin.js install --user=<app user> # Apache vhost, /var/lib/basalt/<app>
|
|
58
|
+
|
|
59
|
+
# then, every deploy, as the app user:
|
|
60
|
+
pnpm exec basalt-deploy run
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`run` pulls the code itself. Store the git credentials once
|
|
64
|
+
(`git config credential.helper store && git fetch`, or a read-only deploy key):
|
|
65
|
+
preflight probes the remote with prompts disabled, warns at a terminal and
|
|
66
|
+
stops before anything changes when nobody can type them (cron, CI).
|
|
67
|
+
|
|
68
|
+
The TLS certificate is yours to issue (`certbot --dns-cloudflare -d <domain> -d '*.<domain>'`);
|
|
69
|
+
every deploy checks it.
|
|
70
|
+
|
|
71
|
+
## Commands
|
|
72
|
+
|
|
73
|
+
| | |
|
|
74
|
+
|---|---|
|
|
75
|
+
| `plan` | every check, then what `run` would do. Writes nothing, asks nothing. |
|
|
76
|
+
| `run` | preflight → fetch → env → infra → build → validate → backup → migrate → release → health → record |
|
|
77
|
+
| `env` | the `.env` and the containers only |
|
|
78
|
+
| `rollback [--to=<sha>]` | the last healthy release. Code only — the database keeps its migrations. |
|
|
79
|
+
| `status` | the last releases and the process |
|
|
80
|
+
| `install --user=<name>` | root, once: vhost, state directory |
|
|
81
|
+
|
|
82
|
+
`--skip=fetch,backup,tls`, `--config=<file>`, `--overrides=<file>`.
|
|
83
|
+
|
|
84
|
+
## What runs by default
|
|
85
|
+
|
|
86
|
+
- `prisma migrate deploy` — when `build.prisma` lists a config, or `migrate.central: true`.
|
|
87
|
+
- `tenant:migrate` — only with `migrate.tenants`.
|
|
88
|
+
- The dump before migrating — when something is migrated and there is a
|
|
89
|
+
Postgres to dump (dedicated, or a `postgres://` URL in the `.env`);
|
|
90
|
+
`backup.beforeMigrate` forces it either way. `plan` says why when it is skipped.
|
|
91
|
+
|
|
92
|
+
## What it refuses to do
|
|
93
|
+
|
|
94
|
+
Each of these is a check that runs on every deploy, written after a production
|
|
95
|
+
incident (RFC 0006 §5):
|
|
96
|
+
|
|
97
|
+
- **C1** proxy or bind to a port another process owns — including Apache's own;
|
|
98
|
+
- **C2** trust a vhost copied into `sites-enabled/` instead of linked;
|
|
99
|
+
- **C3** restart a PM2 process that runs from another directory (it re-creates it);
|
|
100
|
+
- **C4** name any process, container or volume that does not start with `<app>-`;
|
|
101
|
+
- **C5** write or read a `.env` line that is not `KEY=value` (reported by line, never by value);
|
|
102
|
+
- **C6** accept a value meant as *off* that your schema reads as *on* (`z.coerce.boolean()` turns `"0"` into `true`);
|
|
103
|
+
- **C7** give an existing database volume a new password;
|
|
104
|
+
- **C8** stay silent about a certificate that does not cover the apex or a tenant host;
|
|
105
|
+
- **C9** run with a package manager major other than the one `packageManager` declares;
|
|
106
|
+
- **C10** keep a forbidden key, or a fixed key with another value.
|
|
107
|
+
|
|
108
|
+
Secrets never reach a command line, the compose file, or the terminal: the
|
|
109
|
+
summary names keys, passwords travel in child-process environments only.
|
|
110
|
+
|
|
111
|
+
**Your app loads its own `.env`** (`import 'dotenv/config'` first in
|
|
112
|
+
`src/server.ts`, or `node --env-file=.env`). PM2 starts it with `NODE_ENV`,
|
|
113
|
+
`PORT` and `HOST` only: not the operator's shell (a stray variable would
|
|
114
|
+
override the file), and not the secrets (`pm2 save` writes the process
|
|
115
|
+
environment to `~/.pm2/dump.pm2`).
|
|
116
|
+
|
|
117
|
+
## When a release fails
|
|
118
|
+
|
|
119
|
+
- Before `release` (build, validation, backup, migration): the code on disk is
|
|
120
|
+
put back to the previous commit and rebuilt; nothing running was touched.
|
|
121
|
+
- At `release`/`health`: the previous commit is rebuilt, restarted and checked.
|
|
122
|
+
- A release that applied a migration listed in `destructive` is never rolled
|
|
123
|
+
back automatically — its code would run on a schema it does not know. The
|
|
124
|
+
`pg_restore` command for the dump taken before it is printed instead.
|
|
125
|
+
- Healthy on `127.0.0.1` but not at `https://<domain>`: exit 1, no rollback —
|
|
126
|
+
the problem is the proxy, DNS or TLS, not the code.
|
package/dist/apache.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type DeployContext, type Finding } from './context.js';
|
|
2
|
+
export declare function vhostPaths(ctx: DeployContext): {
|
|
3
|
+
root: string;
|
|
4
|
+
file: string;
|
|
5
|
+
available: string;
|
|
6
|
+
enabled: string;
|
|
7
|
+
};
|
|
8
|
+
export declare function renderVhost(ctx: DeployContext, port: number): string;
|
|
9
|
+
/** The ports a vhost proxies to on this machine. */
|
|
10
|
+
export declare function proxiedPorts(vhost: string): number[];
|
|
11
|
+
export declare function apachePreflight(ctx: DeployContext, port: number): Promise<Finding[]>;
|
|
12
|
+
/** Root only. Writes the vhost (after showing the diff and asking), links it, configtest, reload. */
|
|
13
|
+
export declare function apacheInstall(ctx: DeployContext, port: number, backupDir: string): Promise<void>;
|
package/dist/apache.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { vhostName } from './config.js';
|
|
3
|
+
import { DeployError, INSTALL_COMMAND } from './context.js';
|
|
4
|
+
import { lineDiff } from './diff.js';
|
|
5
|
+
/**
|
|
6
|
+
* The Apache target (RFC 0006 §11.3): the vhost is written ONLY by `install`,
|
|
7
|
+
* as root, once. Every deploy compares what is installed with what `install`
|
|
8
|
+
* would write now and prints the difference — it never rewrites a vhost in
|
|
9
|
+
* production. Writing Apache configuration is root-equivalent (`CustomLog
|
|
10
|
+
* "|cmd"` runs a command as root), so it is never delegated to the app user.
|
|
11
|
+
*/
|
|
12
|
+
const apacheOf = (ctx) => {
|
|
13
|
+
if (ctx.config.proxy?.kind !== 'apache')
|
|
14
|
+
throw new Error('not an apache proxy');
|
|
15
|
+
return ctx.config.proxy;
|
|
16
|
+
};
|
|
17
|
+
export function vhostPaths(ctx) {
|
|
18
|
+
const proxy = apacheOf(ctx);
|
|
19
|
+
const root = proxy.root ?? '/etc/apache2';
|
|
20
|
+
const file = vhostName(ctx.config);
|
|
21
|
+
return { root, file, available: join(root, 'sites-available', file), enabled: join(root, 'sites-enabled', file) };
|
|
22
|
+
}
|
|
23
|
+
export function renderVhost(ctx, port) {
|
|
24
|
+
const proxy = apacheOf(ctx);
|
|
25
|
+
const { app, domain } = ctx.config;
|
|
26
|
+
const alias = ctx.config.tenants === 'subdomain' ? ` ServerAlias *.${domain}\n` : '';
|
|
27
|
+
const webRoot = join(ctx.dir, proxy.webRoot);
|
|
28
|
+
const prefix = proxy.apiPrefix.replace(/\/$/, '');
|
|
29
|
+
const cert = `/etc/letsencrypt/live/${proxy.certName ?? domain}`;
|
|
30
|
+
return `# Written by basalt-deploy install for "${app}". Deploys compare this file with
|
|
31
|
+
# what install would write and print the difference; they never rewrite it.
|
|
32
|
+
# To change it: edit deploy.config.ts, then sudo basalt-deploy install.
|
|
33
|
+
|
|
34
|
+
<VirtualHost *:80>
|
|
35
|
+
ServerName ${domain}
|
|
36
|
+
${alias} RewriteEngine On
|
|
37
|
+
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
|
|
38
|
+
</VirtualHost>
|
|
39
|
+
|
|
40
|
+
<IfModule mod_ssl.c>
|
|
41
|
+
<VirtualHost *:443>
|
|
42
|
+
ServerName ${domain}
|
|
43
|
+
${alias}
|
|
44
|
+
DocumentRoot ${webRoot}
|
|
45
|
+
<Directory ${webRoot}>
|
|
46
|
+
Require all granted
|
|
47
|
+
Options -Indexes
|
|
48
|
+
FallbackResource /index.html
|
|
49
|
+
</Directory>
|
|
50
|
+
|
|
51
|
+
# The API: ${prefix}/x reaches the app as /x. The Host header is kept — the
|
|
52
|
+
# tenant is read from it.
|
|
53
|
+
ProxyPreserveHost On
|
|
54
|
+
RequestHeader set X-Forwarded-Proto "https"
|
|
55
|
+
ProxyPass ${prefix}/ http://127.0.0.1:${port}/ upgrade=websocket
|
|
56
|
+
ProxyPassReverse ${prefix}/ http://127.0.0.1:${port}/
|
|
57
|
+
|
|
58
|
+
SSLEngine on
|
|
59
|
+
SSLCertificateFile ${cert}/fullchain.pem
|
|
60
|
+
SSLCertificateKeyFile ${cert}/privkey.pem
|
|
61
|
+
|
|
62
|
+
ErrorLog \${APACHE_LOG_DIR}/${app}-error.log
|
|
63
|
+
CustomLog \${APACHE_LOG_DIR}/${app}-access.log combined
|
|
64
|
+
</VirtualHost>
|
|
65
|
+
</IfModule>
|
|
66
|
+
`;
|
|
67
|
+
}
|
|
68
|
+
/** The ports a vhost proxies to on this machine. */
|
|
69
|
+
export function proxiedPorts(vhost) {
|
|
70
|
+
return [...vhost.matchAll(/^\s*ProxyPass\s+\S+\s+(?:https?|wss?):\/\/(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/gim)].map((m) => Number(m[1]));
|
|
71
|
+
}
|
|
72
|
+
export async function apachePreflight(ctx, port) {
|
|
73
|
+
const { host } = ctx;
|
|
74
|
+
const paths = vhostPaths(ctx);
|
|
75
|
+
const findings = [];
|
|
76
|
+
const enabled = await host.stat(paths.enabled);
|
|
77
|
+
const available = await host.readFile(paths.available);
|
|
78
|
+
if (!enabled && available === undefined) {
|
|
79
|
+
return [{ id: 'proxy', level: 'error', message: `no Apache vhost ${paths.file} yet`, fix: `${INSTALL_COMMAND} (once per server)` }];
|
|
80
|
+
}
|
|
81
|
+
if (!enabled) {
|
|
82
|
+
findings.push({ id: 'proxy', level: 'error', message: `${paths.file} is in sites-available but not enabled`, fix: `sudo a2ensite ${paths.file} && sudo systemctl reload apache2` });
|
|
83
|
+
}
|
|
84
|
+
else if (enabled.kind === 'file') {
|
|
85
|
+
// C2 — a copy in sites-enabled is what Apache loads; the file everyone
|
|
86
|
+
// edits is in sites-available. The wildcard certificate went into the
|
|
87
|
+
// second and was never served.
|
|
88
|
+
const copy = await host.readFile(paths.enabled) ?? '';
|
|
89
|
+
const same = available !== undefined && copy === available;
|
|
90
|
+
findings.push({
|
|
91
|
+
id: 'C2',
|
|
92
|
+
level: 'error',
|
|
93
|
+
message: `sites-enabled/${paths.file} is a regular file, not a link to sites-available — ${same ? 'identical today, but edits to sites-available will not be served' : 'and it DIFFERS from sites-available: Apache serves the copy'}`,
|
|
94
|
+
fix: `${INSTALL_COMMAND} (replaces it with a link, after showing the diff)`,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
else if (enabled.kind === 'symlink') {
|
|
98
|
+
const target = await host.readlink(paths.enabled);
|
|
99
|
+
if (target !== `../sites-available/${paths.file}` && target !== paths.available) {
|
|
100
|
+
findings.push({ id: 'C2', level: 'error', message: `sites-enabled/${paths.file} links to ${target}, not to sites-available/${paths.file}` });
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const served = enabled?.kind === 'file' ? await host.readFile(paths.enabled) : available;
|
|
104
|
+
if (served !== undefined) {
|
|
105
|
+
// C1 — the incident itself: the vhost proxied to :3000 (Apache's own
|
|
106
|
+
// port on that server) while the app listened on :3002.
|
|
107
|
+
for (const proxied of proxiedPorts(served)) {
|
|
108
|
+
if (proxied !== port) {
|
|
109
|
+
findings.push({
|
|
110
|
+
id: 'C1',
|
|
111
|
+
level: 'error',
|
|
112
|
+
message: `the vhost proxies to 127.0.0.1:${proxied}, but the app listens on ${port}`,
|
|
113
|
+
fix: `${INSTALL_COMMAND} (shows the diff and rewrites it)`,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const diff = lineDiff(served, renderVhost(ctx, port));
|
|
118
|
+
if (diff.length > 0) {
|
|
119
|
+
findings.push({
|
|
120
|
+
id: 'vhost',
|
|
121
|
+
level: 'warning',
|
|
122
|
+
message: `the installed vhost differs from what install would write (not changed — audit only):\n${diff.map((l) => ` ${l}`).join('\n')}`,
|
|
123
|
+
fix: `to apply: ${INSTALL_COMMAND}`,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return findings;
|
|
128
|
+
}
|
|
129
|
+
/** Root only. Writes the vhost (after showing the diff and asking), links it, configtest, reload. */
|
|
130
|
+
export async function apacheInstall(ctx, port, backupDir) {
|
|
131
|
+
const { host } = ctx;
|
|
132
|
+
const paths = vhostPaths(ctx);
|
|
133
|
+
const wanted = renderVhost(ctx, port);
|
|
134
|
+
const stamp = host.now().toISOString().replace(/[-:]/g, '').replace(/\..+$/, '');
|
|
135
|
+
const restore = [];
|
|
136
|
+
const current = await host.readFile(paths.available);
|
|
137
|
+
if (current !== wanted) {
|
|
138
|
+
if (current !== undefined) {
|
|
139
|
+
host.out.info(`sites-available/${paths.file} would change:`);
|
|
140
|
+
for (const line of lineDiff(current, wanted))
|
|
141
|
+
host.out.info(` ${line}`);
|
|
142
|
+
if (!(await host.confirm(`Write sites-available/${paths.file}?`)))
|
|
143
|
+
throw new DeployError('vhost not changed (declined)');
|
|
144
|
+
const backup = join(backupDir, `${paths.file}.available-${stamp}`);
|
|
145
|
+
await host.copyFile(paths.available, backup, 0o600);
|
|
146
|
+
restore.push(() => host.copyFile(backup, paths.available, 0o644));
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
restore.push(() => host.remove(paths.available));
|
|
150
|
+
}
|
|
151
|
+
await host.writeFile(paths.available, wanted, 0o644);
|
|
152
|
+
}
|
|
153
|
+
const enabled = await host.stat(paths.enabled);
|
|
154
|
+
if (enabled?.kind === 'file') {
|
|
155
|
+
host.out.info(`sites-enabled/${paths.file} is a copy; replacing it with a link (the copy is kept in ${backupDir})`);
|
|
156
|
+
const backup = join(backupDir, `${paths.file}.enabled-copy-${stamp}`);
|
|
157
|
+
await host.copyFile(paths.enabled, backup, 0o600);
|
|
158
|
+
await host.remove(paths.enabled);
|
|
159
|
+
restore.push(async () => { await host.remove(paths.enabled); await host.copyFile(backup, paths.enabled, 0o644); });
|
|
160
|
+
}
|
|
161
|
+
if ((await host.stat(paths.enabled))?.kind !== 'symlink') {
|
|
162
|
+
await host.symlink(`../sites-available/${paths.file}`, paths.enabled);
|
|
163
|
+
if (enabled?.kind !== 'file')
|
|
164
|
+
restore.push(() => host.remove(paths.enabled));
|
|
165
|
+
}
|
|
166
|
+
const mods = await host.exec('a2enmod', ['-q', 'ssl', 'proxy', 'proxy_http', 'rewrite', 'headers']);
|
|
167
|
+
if (mods.code !== 0)
|
|
168
|
+
host.out.warn(`a2enmod: ${mods.stderr.trim()}`);
|
|
169
|
+
const test = await host.exec('apachectl', ['configtest']);
|
|
170
|
+
if (test.code !== 0) {
|
|
171
|
+
for (const undo of restore.reverse())
|
|
172
|
+
await undo();
|
|
173
|
+
throw new DeployError(`apachectl configtest failed — every file was put back as it was:\n${test.stderr.trim()}`);
|
|
174
|
+
}
|
|
175
|
+
const reload = await host.exec('systemctl', ['reload', 'apache2']);
|
|
176
|
+
if (reload.code !== 0)
|
|
177
|
+
throw new DeployError(`systemctl reload apache2 failed: ${reload.stderr.trim()}`);
|
|
178
|
+
host.out.ok(`${paths.file} installed and Apache reloaded`);
|
|
179
|
+
}
|
package/dist/backup.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type DeployContext } from './context.js';
|
|
2
|
+
import type { InfraPlan } from './infra.js';
|
|
3
|
+
/**
|
|
4
|
+
* `pg_dump -Fc` of the central database before migrating — migrations do not
|
|
5
|
+
* undo themselves, and rollback restores code only (RFC 0006 §8). With
|
|
6
|
+
* schema-per-tenant every company's schema is in the same database, so one
|
|
7
|
+
* dump covers them all.
|
|
8
|
+
*
|
|
9
|
+
* With dedicated infra the dump runs INSIDE the container: same pg_dump major
|
|
10
|
+
* as the server, by construction, and no password needed on the local socket.
|
|
11
|
+
*/
|
|
12
|
+
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;
|
package/dist/backup.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { DeployError } from './context.js';
|
|
3
|
+
/**
|
|
4
|
+
* `pg_dump -Fc` of the central database before migrating — migrations do not
|
|
5
|
+
* undo themselves, and rollback restores code only (RFC 0006 §8). With
|
|
6
|
+
* schema-per-tenant every company's schema is in the same database, so one
|
|
7
|
+
* dump covers them all.
|
|
8
|
+
*
|
|
9
|
+
* With dedicated infra the dump runs INSIDE the container: same pg_dump major
|
|
10
|
+
* as the server, by construction, and no password needed on the local socket.
|
|
11
|
+
*/
|
|
12
|
+
export async function backupDatabase(ctx, values, infra, sha) {
|
|
13
|
+
const { host, config } = ctx;
|
|
14
|
+
const dir = join(ctx.dir, config.backup?.dir ?? 'backups/predeploy');
|
|
15
|
+
await host.mkdir(dir, 0o700);
|
|
16
|
+
const stamp = host.now().toISOString().replace(/[-:]/g, '').replace(/\..+$/, '');
|
|
17
|
+
const file = join(dir, `${stamp}-${sha.slice(0, 7)}.dump`);
|
|
18
|
+
const pg = infra.services.find((s) => s.service === 'postgres');
|
|
19
|
+
let result;
|
|
20
|
+
if (pg) {
|
|
21
|
+
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
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
const key = config.backup?.urlKey ?? 'DATABASE_URL';
|
|
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);
|
|
29
|
+
const password = decodeURIComponent(url.password);
|
|
30
|
+
url.password = '';
|
|
31
|
+
// Prisma's `?schema=` is not a libpq parameter; pg_dump refuses it.
|
|
32
|
+
url.search = '';
|
|
33
|
+
result = await host.exec('pg_dump', ['--dbname', url.toString(), '--format=custom', '--no-owner', '--no-acl'], { stdoutFile: file, env: { PGPASSWORD: password } });
|
|
34
|
+
}
|
|
35
|
+
const size = (await host.stat(file))?.size ?? 0;
|
|
36
|
+
if (result.code !== 0 || size === 0) {
|
|
37
|
+
await host.remove(file);
|
|
38
|
+
throw new DeployError(`pg_dump failed — nothing was changed: ${result.stderr.trim().split('\n')[0] ?? ''}`);
|
|
39
|
+
}
|
|
40
|
+
const keep = config.backup?.keep ?? 10;
|
|
41
|
+
const dumps = (await host.list(dir)).filter((name) => name.endsWith('.dump')).sort();
|
|
42
|
+
for (const old of dumps.slice(0, -keep))
|
|
43
|
+
await host.remove(join(dir, old));
|
|
44
|
+
return file;
|
|
45
|
+
}
|
|
46
|
+
export function restoreCommand(ctx, infra, file) {
|
|
47
|
+
const pg = infra.services.find((s) => s.service === 'postgres');
|
|
48
|
+
if (pg)
|
|
49
|
+
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}`;
|
|
50
|
+
return `pg_restore --clean --if-exists --no-owner --dbname "<the database URL, without ?schema=>" ${file}`;
|
|
51
|
+
}
|
package/dist/bin.d.ts
ADDED
package/dist/bin.js
ADDED
package/dist/checks.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { DeployContext, Finding } from './context.js';
|
|
2
|
+
/** Whether a certificate name (`*.example.com` or exact) covers `host`. Wildcards cover one label only. */
|
|
3
|
+
export declare function covers(name: string, host: string): boolean;
|
|
4
|
+
/**
|
|
5
|
+
* C8 — what a browser will see, through public DNS: the apex and, for
|
|
6
|
+
* subdomain tenants, a random `x<hex>.<domain>`. A wildcard record proxied by
|
|
7
|
+
* Cloudflare served the apex certificate on every tenant host; a Cloudflare
|
|
8
|
+
* Origin certificate is not trusted by browsers. Warnings, not errors: the
|
|
9
|
+
* deploy cannot fix a certificate, and a hotfix must not wait for one.
|
|
10
|
+
*/
|
|
11
|
+
export declare function tlsFindings(ctx: DeployContext): Promise<Finding[]>;
|
|
12
|
+
/** C9 — the toolchain the pipeline will call, before it calls it. */
|
|
13
|
+
export declare function toolingFindings(ctx: DeployContext): Promise<Finding[]>;
|
package/dist/checks.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
/** Whether a certificate name (`*.example.com` or exact) covers `host`. Wildcards cover one label only. */
|
|
3
|
+
export function covers(name, host) {
|
|
4
|
+
const n = name.toLowerCase();
|
|
5
|
+
const h = host.toLowerCase();
|
|
6
|
+
if (!n.startsWith('*.'))
|
|
7
|
+
return n === h;
|
|
8
|
+
const dot = h.indexOf('.');
|
|
9
|
+
return dot > 0 && h.slice(dot + 1) === n.slice(2);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* C8 — what a browser will see, through public DNS: the apex and, for
|
|
13
|
+
* subdomain tenants, a random `x<hex>.<domain>`. A wildcard record proxied by
|
|
14
|
+
* Cloudflare served the apex certificate on every tenant host; a Cloudflare
|
|
15
|
+
* Origin certificate is not trusted by browsers. Warnings, not errors: the
|
|
16
|
+
* deploy cannot fix a certificate, and a hotfix must not wait for one.
|
|
17
|
+
*/
|
|
18
|
+
export async function tlsFindings(ctx) {
|
|
19
|
+
const { host, config } = ctx;
|
|
20
|
+
const hosts = [config.domain];
|
|
21
|
+
if (config.tenants === 'subdomain')
|
|
22
|
+
hosts.push(`x${host.randomHex(4)}.${config.domain}`);
|
|
23
|
+
const findings = [];
|
|
24
|
+
for (const name of hosts) {
|
|
25
|
+
const label = name === config.domain ? name : `a tenant host (${name})`;
|
|
26
|
+
const cert = await host.tlsCertificate(name);
|
|
27
|
+
if ('error' in cert) {
|
|
28
|
+
const dns = /ENOTFOUND|EAI_AGAIN/.test(cert.error);
|
|
29
|
+
findings.push({
|
|
30
|
+
id: 'C8', level: 'warning', message: `TLS to ${label}: ${cert.error}`,
|
|
31
|
+
...(name !== config.domain && dns ? { fix: `add a DNS-only (not proxied) record *.${config.domain} pointing at this server` } : {}),
|
|
32
|
+
...(/not trusted/.test(cert.error) ? { fix: 'a Cloudflare Origin certificate behind a DNS-only record? Issue a Let\'s Encrypt one (certbot --dns-cloudflare)' } : {}),
|
|
33
|
+
});
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (!cert.names.some((n) => covers(n, name))) {
|
|
37
|
+
findings.push({
|
|
38
|
+
id: 'C8', level: 'warning', message: `the certificate served for ${label} covers only ${cert.names.join(', ') || '(no names)'}`,
|
|
39
|
+
...(name === config.domain ? {} : { fix: `issue a wildcard: certbot certonly --dns-cloudflare -d ${config.domain} -d '*.${config.domain}', and make *.${config.domain} DNS-only` }),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
else if (!cert.trusted) {
|
|
43
|
+
findings.push({ id: 'C8', level: 'warning', message: `the certificate served for ${label} is not trusted by browsers (${cert.trustError ?? 'unknown reason'}) — a Cloudflare Origin certificate behind a DNS-only record?` });
|
|
44
|
+
}
|
|
45
|
+
const days = Math.floor((cert.validTo.getTime() - host.now().getTime()) / 86_400_000);
|
|
46
|
+
if (days < 14)
|
|
47
|
+
findings.push({ id: 'C8', level: 'warning', message: `the certificate for ${label} expires in ${days} day(s)`, fix: 'certbot renew' });
|
|
48
|
+
}
|
|
49
|
+
return findings;
|
|
50
|
+
}
|
|
51
|
+
function minimumVersion(range) {
|
|
52
|
+
const match = range ? /(\d+)\.(\d+)(?:\.(\d+))?/.exec(range) : null;
|
|
53
|
+
return match ? [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)] : undefined;
|
|
54
|
+
}
|
|
55
|
+
const below = (version, minimum) => {
|
|
56
|
+
for (let i = 0; i < 3; i++) {
|
|
57
|
+
if ((version[i] ?? 0) !== (minimum[i] ?? 0))
|
|
58
|
+
return (version[i] ?? 0) < (minimum[i] ?? 0);
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
};
|
|
62
|
+
/** C9 — the toolchain the pipeline will call, before it calls it. */
|
|
63
|
+
export async function toolingFindings(ctx) {
|
|
64
|
+
const { host } = ctx;
|
|
65
|
+
const findings = [];
|
|
66
|
+
let pkg = {};
|
|
67
|
+
try {
|
|
68
|
+
pkg = JSON.parse((await host.readFile(join(ctx.dir, 'package.json'))) ?? '{}');
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
findings.push({ id: 'C9', level: 'error', message: 'package.json is not valid JSON' });
|
|
72
|
+
}
|
|
73
|
+
const node = await host.exec('node', ['--version']);
|
|
74
|
+
const nodeVersion = minimumVersion(node.stdout);
|
|
75
|
+
const nodeMinimum = minimumVersion(pkg.engines?.node);
|
|
76
|
+
if (!nodeVersion)
|
|
77
|
+
findings.push({ id: 'C9', level: 'error', message: 'node is not on PATH' });
|
|
78
|
+
else if (nodeMinimum && below(nodeVersion, nodeMinimum)) {
|
|
79
|
+
findings.push({ id: 'C9', level: 'error', message: `node ${node.stdout.trim()} is older than engines.node (${pkg.engines?.node})` });
|
|
80
|
+
}
|
|
81
|
+
const pm = await host.exec(ctx.pm, ['--version']);
|
|
82
|
+
if (pm.code !== 0) {
|
|
83
|
+
findings.push({ id: 'C9', level: 'error', message: `${ctx.pm} is not on PATH`, fix: 'corepack enable' });
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
const declared = pkg.packageManager?.split('@')[1]?.split('.')[0];
|
|
87
|
+
const actual = pm.stdout.trim().split('.')[0];
|
|
88
|
+
// Flags change between majors (pnpm 11 refuses --prod=false).
|
|
89
|
+
if (declared && actual && declared !== actual) {
|
|
90
|
+
findings.push({ id: 'C9', level: 'error', message: `${ctx.pm} ${pm.stdout.trim()} on this server, but package.json declares ${pkg.packageManager}`, fix: 'corepack enable (it then runs the declared version)' });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (ctx.config.infra?.kind === 'docker') {
|
|
94
|
+
const docker = await host.exec('docker', ['compose', 'version']);
|
|
95
|
+
if (docker.code !== 0)
|
|
96
|
+
findings.push({ id: 'C9', level: 'error', message: 'docker compose is not available to this user' });
|
|
97
|
+
}
|
|
98
|
+
return findings;
|
|
99
|
+
}
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type DeployConfig } from './config.js';
|
|
2
|
+
import { type DeployContext } from './context.js';
|
|
3
|
+
import { type Host } from './host.js';
|
|
4
|
+
export declare const USAGE: string;
|
|
5
|
+
/** Loads deploy.config.ts with the app's own tsx when it has one, else Node's type stripping. */
|
|
6
|
+
export declare function loadConfig(dir: string, file: string): Promise<DeployConfig>;
|
|
7
|
+
export declare function createContext(host: Host, dir: string, config: DeployConfig): Promise<DeployContext>;
|
|
8
|
+
export declare function main(argv: string[], host?: Host, cwd?: string): Promise<number>;
|