@basaltkit/deploy 0.1.4 → 0.2.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 CHANGED
@@ -87,13 +87,71 @@ every deploy checks it.
87
87
 
88
88
  `--skip=fetch,backup,tls`, `--config=<file>`, `--overrides=<file>`.
89
89
 
90
+ ## Docker Compose apps
91
+
92
+ ```ts
93
+ runtime: compose({
94
+ file: 'docker/compose.prod.yml',
95
+ images: [
96
+ { tag: 'myapp', dockerfile: 'docker/app/Dockerfile', env: 'MYAPP_IMAGE' },
97
+ { tag: 'myapp-worker', dockerfile: 'docker/worker/Dockerfile', env: 'MYAPP_WORKER_IMAGE' },
98
+ ],
99
+ upstream: { service: 'api', port: 3001 }, // published on 127.0.0.1 by the compose file
100
+ env: { MYAPP_API_HOST_PORT: '3001' }, // compose interpolation — never secrets
101
+ keepImages: 3,
102
+ }),
103
+ ```
104
+
105
+ - Each image is built once per commit as `<tag>:<7-char sha>` and skipped when it
106
+ exists; `compose up -d` gets the tags through the `env` variable of each image.
107
+ - Health: the upstream service healthy by its own healthcheck, **no service of
108
+ the project restarting**, then the loopback and public URLs.
109
+ - Rollback starts the previous commit's images again — no rebuild. After a
110
+ healthy release, `<sha>` tags of these images outside the last `keepImages`
111
+ releases are removed; nothing else is ever pruned.
112
+ - Image tags must be `<app>` or `<app>-…` (C4).
113
+
114
+ **The env file outside the checkout:** `env: { file: '/etc/myapp/api.env', mirror: ['/etc/myapp/worker.env'] }`.
115
+ Mirrors are rewritten as exact copies; one that differs is a C10 error. `install`
116
+ gives the files — and `/etc/myapp` itself, when its name contains the app's —
117
+ to the deploy user.
118
+
119
+ **Migrations by command**, with values that override the `.env` for them and for
120
+ the pre-migration dump (a container name the host cannot resolve):
121
+
122
+ ```ts
123
+ migrate: {
124
+ command: ['./node_modules/.bin/tsx', 'scripts/db.ts', 'deploy'],
125
+ env: (v) => ({ DATABASE_URL: v.get('DATABASE_URL')!.replace('@myapp-postgres:', '@127.0.0.1:') }),
126
+ },
127
+ ```
128
+
129
+ **Hooks** — what only your app does, as commands that also run by hand:
130
+
131
+ ```ts
132
+ hooks: {
133
+ infra: [['bash', 'scripts/deploy/infra.sh']], // after the .env and infra, before the build
134
+ verify: [['bash', 'scripts/deploy/verify.sh']], // after the health check; failing rolls back
135
+ },
136
+ ```
137
+
138
+ They run in the checkout as the deploy user with the `.env` values, the image
139
+ variables, `DEPLOY_SHA` and `DEPLOY_APP`. They run on every deploy: idempotent.
140
+
141
+ **Apache you write yourself:** `apache({ managed: false, vhosts: ['myapp.conf'] })`
142
+ checks C2 and C1 on each vhost on every deploy and never writes them.
143
+
90
144
  ## What runs by default
91
145
 
92
- - `prisma migrate deploy` — when `build.prisma` lists a config, or `migrate.central: true`.
146
+ - `prisma migrate deploy` — when `build.prisma` lists a config, or `migrate.central: true`; not with a `migrate.command` unless `central: true`.
93
147
  - `tenant:migrate` — only with `migrate.tenants`.
94
148
  - The dump before migrating — when something is migrated and there is a
95
149
  Postgres to dump (dedicated, or a `postgres://` URL in the `.env`);
96
150
  `backup.beforeMigrate` forces it either way. `plan` says why when it is skipped.
151
+ With external infra in a container, `backup: { container: 'myapp-postgres' }`
152
+ runs `pg_dump` inside it (`docker exec`), as the user and database of the
153
+ URL at `backup.urlKey` — the server's own pg_dump, none needed on the host.
154
+ The preflight checks the container is running.
97
155
 
98
156
  ## What it refuses to do
99
157
 
package/dist/apache.js CHANGED
@@ -67,9 +67,55 @@ ${alias}
67
67
  }
68
68
  /** The ports a vhost proxies to on this machine. */
69
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]));
70
+ // Path and URL may be quoted (`ProxyPass "/api/" "http://127.0.0.1:3001/"`):
71
+ // unquoted-only matching found no port in that form and C1 passed in silence.
72
+ return [...vhost.matchAll(/^\s*ProxyPass\s+(?:"[^"]*"|\S+)\s+"?(?:https?|wss?):\/\/(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/gim)].map((m) => Number(m[1]));
73
+ }
74
+ /**
75
+ * `managed: false` (RFC 0006 §13.4): the app's own vhosts, checked — each one
76
+ * linked into sites-enabled (C2) and every local ProxyPass on the upstream
77
+ * port (C1) — and never rendered, diffed or written.
78
+ */
79
+ async function unmanagedPreflight(ctx, port) {
80
+ const proxy = apacheOf(ctx);
81
+ const root = proxy.root ?? '/etc/apache2';
82
+ const findings = [];
83
+ for (const file of proxy.vhosts ?? []) {
84
+ const available = join(root, 'sites-available', file);
85
+ const enabled = join(root, 'sites-enabled', file);
86
+ const stat = await ctx.host.stat(enabled);
87
+ if (!stat) {
88
+ findings.push({ id: 'proxy', level: 'error', message: `sites-enabled/${file} does not exist`, fix: `sudo a2ensite ${file} && sudo apachectl configtest && sudo systemctl reload apache2` });
89
+ continue;
90
+ }
91
+ if (stat.kind === 'file') {
92
+ const copy = await ctx.host.readFile(enabled);
93
+ const original = await ctx.host.readFile(available);
94
+ findings.push({
95
+ id: 'C2',
96
+ level: 'error',
97
+ message: `sites-enabled/${file} is a regular file, not a link to sites-available — ${copy === original ? 'identical today, but edits to sites-available will not be served' : 'and it DIFFERS from sites-available: Apache serves the copy'}`,
98
+ fix: `after merging any difference into sites-available/${file}: sudo rm ${enabled} && sudo a2ensite ${file} && sudo apachectl configtest && sudo systemctl reload apache2`,
99
+ });
100
+ }
101
+ else if (stat.kind === 'symlink') {
102
+ const target = await ctx.host.readlink(enabled);
103
+ if (target !== `../sites-available/${file}` && target !== available) {
104
+ findings.push({ id: 'C2', level: 'error', message: `sites-enabled/${file} links to ${target}, not to sites-available/${file}` });
105
+ }
106
+ }
107
+ const served = await ctx.host.readFile(enabled);
108
+ for (const proxied of proxiedPorts(served ?? '')) {
109
+ if (proxied !== port) {
110
+ findings.push({ id: 'C1', level: 'error', message: `${file} proxies to 127.0.0.1:${proxied}, but the app is reached on ${port}`, fix: `edit the ProxyPass lines of sites-available/${file}, then sudo apachectl configtest && sudo systemctl reload apache2` });
111
+ }
112
+ }
113
+ }
114
+ return findings;
71
115
  }
72
116
  export async function apachePreflight(ctx, port) {
117
+ if (apacheOf(ctx).managed === false)
118
+ return unmanagedPreflight(ctx, port);
73
119
  const { host } = ctx;
74
120
  const paths = vhostPaths(ctx);
75
121
  const findings = [];
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 container: same pg_dump major
10
- * as the server, by construction, and no password needed on the local socket.
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
@@ -6,8 +6,10 @@ import { DeployError } from './context.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 container: same pg_dump major
10
- * as the server, by construction, and no password needed on the local socket.
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 async function backupDatabase(ctx, values, infra, sha) {
13
15
  const { host, config } = ctx;
@@ -21,16 +23,19 @@ export async function backupDatabase(ctx, values, infra, sha) {
21
23
  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
24
  }
23
25
  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);
26
+ const url = databaseUrl(ctx, values);
29
27
  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 } });
28
+ const container = config.backup?.container;
29
+ if (container) {
30
+ const args = ['exec', '-e', 'PGPASSWORD', container, 'pg_dump', '-U', decodeURIComponent(url.username), '-d', databaseName(url), '--format=custom', '--no-owner', '--no-acl'];
31
+ result = await host.exec('docker', args, { stdoutFile: file, env: { PGPASSWORD: password } });
32
+ }
33
+ else {
34
+ url.password = '';
35
+ // Prisma's `?schema=` is not a libpq parameter; pg_dump refuses it.
36
+ url.search = '';
37
+ result = await host.exec('pg_dump', ['--dbname', url.toString(), '--format=custom', '--no-owner', '--no-acl'], { stdoutFile: file, env: { PGPASSWORD: password } });
38
+ }
34
39
  }
35
40
  const size = (await host.stat(file))?.size ?? 0;
36
41
  if (result.code !== 0 || size === 0) {
@@ -43,9 +48,24 @@ export async function backupDatabase(ctx, values, infra, sha) {
43
48
  await host.remove(join(dir, old));
44
49
  return file;
45
50
  }
46
- export function restoreCommand(ctx, infra, file) {
51
+ export function restoreCommand(ctx, infra, file, values = new Map()) {
47
52
  const pg = infra.services.find((s) => s.service === 'postgres');
48
53
  if (pg)
49
54
  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}`;
55
+ const container = ctx.config.backup?.container;
56
+ if (container) {
57
+ const url = databaseUrl(ctx, values);
58
+ return `docker exec -i ${container} pg_restore --clean --if-exists --no-owner -U ${decodeURIComponent(url.username)} -d ${databaseName(url)} < ${file}`;
59
+ }
50
60
  return `pg_restore --clean --if-exists --no-owner --dbname "<the database URL, without ?schema=>" ${file}`;
51
61
  }
62
+ function databaseUrl(ctx, values) {
63
+ const key = ctx.config.backup?.urlKey ?? 'DATABASE_URL';
64
+ const raw = values.get(key);
65
+ if (!raw)
66
+ throw new DeployError(`backup: ${key} is not set in the .env`);
67
+ return new URL(raw);
68
+ }
69
+ function databaseName(url) {
70
+ return decodeURIComponent(url.pathname.replace(/^\//, ''));
71
+ }
package/dist/cli.js CHANGED
@@ -77,7 +77,7 @@ export async function createContext(host, dir, config) {
77
77
  dir,
78
78
  host,
79
79
  pm: await detectPackageManager(host, dir),
80
- envPath: join(dir, config.env.file ?? '.env'),
80
+ envPath: resolve(dir, config.env.file ?? '.env'),
81
81
  stateDir: await resolveStateDir(host, config, dir),
82
82
  };
83
83
  }
@@ -0,0 +1,40 @@
1
+ import type { ComposeRuntime } from './config.js';
2
+ import { type DeployContext, type Finding } from './context.js';
3
+ /**
4
+ * The Docker Compose runtime (RFC 0006 §13.2): images built once per commit
5
+ * and tagged `<tag>:<sha>`, `compose up -d` with those tags, a rollback that
6
+ * reuses the images of an earlier release instead of rebuilding them.
7
+ *
8
+ * Only the configured image tags (C4: `<app>` or `<app>-…`) and the project
9
+ * named after the app are ever touched.
10
+ */
11
+ export declare const composeOf: (ctx: DeployContext) => ComposeRuntime;
12
+ /** Compose's own environment: each image variable → `<tag>:<sha>`, plus `runtime.env`. */
13
+ export declare function composeEnv(ctx: DeployContext, sha: string): Record<string, string>;
14
+ interface ServiceState {
15
+ service: string;
16
+ state: string;
17
+ health: string;
18
+ publishers: number[];
19
+ }
20
+ /** `docker compose ps` of the project, one entry per container. */
21
+ export declare function composeServices(ctx: DeployContext, sha: string): Promise<ServiceState[] | undefined>;
22
+ export declare function composePreflight(ctx: DeployContext, sha: string): Promise<Finding[]>;
23
+ /** `docker build` of every image not built yet for this commit. */
24
+ export declare function composeBuild(ctx: DeployContext, sha: string): Promise<void>;
25
+ export declare function composeRelease(ctx: DeployContext, sha: string): Promise<string>;
26
+ /**
27
+ * The upstream service healthy by its own healthcheck (or running, when it
28
+ * declares none), and no service of the project restarting — the ingest
29
+ * worker once crash-looped through a whole deploy unnoticed.
30
+ */
31
+ export declare function composeHealthy(ctx: DeployContext, sha: string): Promise<{
32
+ ok: true;
33
+ } | {
34
+ ok: false;
35
+ why: string;
36
+ }>;
37
+ /** Removes `<tag>:<sha>` of the configured images for commits outside `keep`. Nothing else. */
38
+ export declare function pruneImages(ctx: DeployContext, keep: string[]): Promise<string[]>;
39
+ export declare function composeStatus(ctx: DeployContext, sha: string): Promise<string[]>;
40
+ export {};
@@ -0,0 +1,152 @@
1
+ import { join } from 'node:path';
2
+ import { DeployError } from './context.js';
3
+ import { listeners } from './ports.js';
4
+ /**
5
+ * The Docker Compose runtime (RFC 0006 §13.2): images built once per commit
6
+ * and tagged `<tag>:<sha>`, `compose up -d` with those tags, a rollback that
7
+ * reuses the images of an earlier release instead of rebuilding them.
8
+ *
9
+ * Only the configured image tags (C4: `<app>` or `<app>-…`) and the project
10
+ * named after the app are ever touched.
11
+ */
12
+ export const composeOf = (ctx) => {
13
+ if (ctx.config.runtime.kind !== 'compose')
14
+ throw new Error('not a compose runtime');
15
+ return ctx.config.runtime;
16
+ };
17
+ /** 7 characters, as `git rev-parse --short` and the scripts before this one: their images stay usable for a rollback. */
18
+ const short = (sha) => sha.slice(0, 7);
19
+ /** Compose's own environment: each image variable → `<tag>:<sha>`, plus `runtime.env`. */
20
+ export function composeEnv(ctx, sha) {
21
+ const rt = composeOf(ctx);
22
+ const env = { ...rt.env };
23
+ for (const image of rt.images)
24
+ env[image.env] = `${image.tag}:${short(sha)}`;
25
+ return env;
26
+ }
27
+ const composeArgs = (ctx, ...args) => ['compose', '-p', ctx.config.app, '-f', join(ctx.dir, composeOf(ctx).file), ...args];
28
+ /** `docker compose ps` of the project, one entry per container. */
29
+ export async function composeServices(ctx, sha) {
30
+ const result = await ctx.host.exec('docker', composeArgs(ctx, 'ps', '--all', '--format', 'json'), { cwd: ctx.dir, env: composeEnv(ctx, sha) });
31
+ if (result.code !== 0)
32
+ return undefined;
33
+ // Compose prints one JSON object per line (v2.21+) or a single array (older).
34
+ const text = result.stdout.trim();
35
+ if (!text)
36
+ return [];
37
+ const rows = text.startsWith('[')
38
+ ? JSON.parse(text)
39
+ : text.split('\n').filter(Boolean).map((line) => JSON.parse(line));
40
+ return rows.map((row) => ({
41
+ service: String(row['Service'] ?? ''),
42
+ state: String(row['State'] ?? ''),
43
+ health: String(row['Health'] ?? ''),
44
+ publishers: (Array.isArray(row['Publishers']) ? row['Publishers'] : [])
45
+ .map((p) => Number(p.PublishedPort ?? 0)).filter((port) => port > 0),
46
+ }));
47
+ }
48
+ export async function composePreflight(ctx, sha) {
49
+ const rt = composeOf(ctx);
50
+ const findings = [];
51
+ if (!(await ctx.host.exists(join(ctx.dir, rt.file)))) {
52
+ return [{ id: 'compose', level: 'error', message: `the compose file ${rt.file} does not exist` }];
53
+ }
54
+ const config = await ctx.host.exec('docker', composeArgs(ctx, 'config', '--quiet'), { cwd: ctx.dir, env: composeEnv(ctx, sha) });
55
+ if (config.code !== 0) {
56
+ findings.push({ id: 'compose', level: 'error', message: `docker compose rejects ${rt.file}: ${config.stderr.trim().split('\n')[0] ?? ''}` });
57
+ }
58
+ // C1 under compose: the published port belongs to docker-proxy (root), so a
59
+ // listener with no visible pid is not foreign by itself — it is ours when
60
+ // the upstream service of THIS project publishes it.
61
+ const port = rt.upstream.port;
62
+ if ((await listeners(ctx.host)).some((l) => l.port === port)) {
63
+ const services = await composeServices(ctx, sha);
64
+ const ours = services?.some((s) => s.service === rt.upstream.service && s.publishers.includes(port));
65
+ if (!ours) {
66
+ findings.push({
67
+ id: 'C1',
68
+ level: 'error',
69
+ message: `port ${port} (runtime.upstream.port) is taken by something that is not the "${rt.upstream.service}" service of the ${ctx.config.app} project`,
70
+ fix: 'pick another: "port": <n> in /etc/basalt/<app>.json, and publish the same in the compose file',
71
+ });
72
+ }
73
+ }
74
+ return findings;
75
+ }
76
+ /** `docker build` of every image not built yet for this commit. */
77
+ export async function composeBuild(ctx, sha) {
78
+ const rt = composeOf(ctx);
79
+ for (const image of rt.images) {
80
+ const ref = `${image.tag}:${short(sha)}`;
81
+ if ((await ctx.host.exec('docker', ['image', 'inspect', ref])).code === 0) {
82
+ ctx.host.out.info(`${ref} already built`);
83
+ continue;
84
+ }
85
+ ctx.host.out.info(`docker build -f ${image.dockerfile} -t ${ref} ${image.context ?? '.'}`);
86
+ const built = await ctx.host.exec('docker', ['build', '-f', join(ctx.dir, image.dockerfile), '-t', ref, join(ctx.dir, image.context ?? '.')], { cwd: ctx.dir, stream: true });
87
+ if (built.code !== 0)
88
+ throw new DeployError(`docker build of ${ref} failed (exit ${built.code})`);
89
+ }
90
+ }
91
+ export async function composeRelease(ctx, sha) {
92
+ const rt = composeOf(ctx);
93
+ for (const image of rt.images) {
94
+ const ref = `${image.tag}:${short(sha)}`;
95
+ if ((await ctx.host.exec('docker', ['image', 'inspect', ref])).code !== 0)
96
+ throw new DeployError(`the image ${ref} does not exist — nothing to start`);
97
+ }
98
+ const up = await ctx.host.exec('docker', composeArgs(ctx, 'up', '-d'), { cwd: ctx.dir, env: composeEnv(ctx, sha), stream: true });
99
+ if (up.code !== 0)
100
+ throw new DeployError(`docker compose up failed (exit ${up.code})`);
101
+ return `${ctx.config.app} project up on ${short(sha)} (${rt.images.map((i) => i.tag).join(', ')})`;
102
+ }
103
+ /**
104
+ * The upstream service healthy by its own healthcheck (or running, when it
105
+ * declares none), and no service of the project restarting — the ingest
106
+ * worker once crash-looped through a whole deploy unnoticed.
107
+ */
108
+ export async function composeHealthy(ctx, sha) {
109
+ const rt = composeOf(ctx);
110
+ const deadline = ctx.host.now().getTime() + (ctx.config.health?.timeoutSeconds ?? 240) * 1000;
111
+ let last = 'no container';
112
+ do {
113
+ const services = await composeServices(ctx, sha) ?? [];
114
+ const upstream = services.filter((s) => s.service === rt.upstream.service);
115
+ const restarting = [...new Set(services.filter((s) => s.state === 'restarting').map((s) => s.service))];
116
+ if (restarting.length > 0)
117
+ return { ok: false, why: `restarting: ${restarting.join(', ')}` };
118
+ const ready = upstream.length > 0 && upstream.every((s) => s.state === 'running' && (s.health === '' || s.health === 'healthy'));
119
+ if (ready)
120
+ return { ok: true };
121
+ last = upstream.length === 0 ? 'no container' : upstream.map((s) => s.health || s.state).join(', ');
122
+ await ctx.host.sleep(5000);
123
+ } while (ctx.host.now().getTime() < deadline);
124
+ return { ok: false, why: `${rt.upstream.service}: ${last} after ${ctx.config.health?.timeoutSeconds ?? 240}s` };
125
+ }
126
+ /** Removes `<tag>:<sha>` of the configured images for commits outside `keep`. Nothing else. */
127
+ export async function pruneImages(ctx, keep) {
128
+ const rt = composeOf(ctx);
129
+ const keepTags = new Set(keep.map(short));
130
+ const removed = [];
131
+ for (const image of rt.images) {
132
+ const listed = await ctx.host.exec('docker', ['image', 'ls', image.tag, '--format', '{{.Tag}}']);
133
+ if (listed.code !== 0)
134
+ continue;
135
+ for (const tag of listed.stdout.split('\n').map((t) => t.trim()).filter(Boolean)) {
136
+ if (!/^[0-9a-f]{7,40}$/.test(tag) || keepTags.has(tag))
137
+ continue;
138
+ const rm = await ctx.host.exec('docker', ['image', 'rm', `${image.tag}:${tag}`]);
139
+ if (rm.code === 0)
140
+ removed.push(`${image.tag}:${tag}`);
141
+ }
142
+ }
143
+ return removed;
144
+ }
145
+ export async function composeStatus(ctx, sha) {
146
+ const services = await composeServices(ctx, sha);
147
+ if (services === undefined)
148
+ return [`compose project ${ctx.config.app}: docker compose is not available`];
149
+ if (services.length === 0)
150
+ return [`compose project ${ctx.config.app}: no containers`];
151
+ return services.map((s) => `${s.service}: ${s.state}${s.health ? ` (${s.health})` : ''}`);
152
+ }
package/dist/config.d.ts CHANGED
@@ -29,10 +29,27 @@ export interface DeployConfig {
29
29
  * for the pre-migration dump instead (RFC 0006 §8).
30
30
  */
31
31
  destructive?: string[];
32
+ /**
33
+ * Commands only this app needs, run at fixed points (RFC 0006 §13.3): in the
34
+ * checkout, as the deploy user, with the `.env` values plus `DEPLOY_SHA` and
35
+ * `DEPLOY_APP` in their environment. Idempotent — they run on every deploy.
36
+ */
37
+ hooks?: HooksConfig;
38
+ }
39
+ export interface HooksConfig {
40
+ /** After the `.env` and the infra, before the build. Failing stops the deploy (code put back). */
41
+ infra?: string[][];
42
+ /** After the health check. Failing is a failed release (rolled back). */
43
+ verify?: string[][];
32
44
  }
33
45
  export interface EnvConfig {
34
- /** Relative to the app directory. Written 0600, backed up before every change. */
46
+ /**
47
+ * Relative to the app directory, or absolute (e.g. `/etc/mukanda/api.env`).
48
+ * Written 0600, backed up before every change, in its own directory.
49
+ */
35
50
  file?: string;
51
+ /** Exact copies of the file (0600), rewritten with it; one that differs is a C10 error. */
52
+ mirror?: string[];
36
53
  /** The module whose import runs the app's `defineEnv(...)`, e.g. `src/env.ts`. */
37
54
  schema?: string;
38
55
  /** Always these values — a different one in the file is corrected. */
@@ -114,6 +131,17 @@ export interface MigrateConfig {
114
131
  central?: boolean;
115
132
  /** `<pm> basalt tenant:migrate` (or the given package.json script arguments). */
116
133
  tenants?: boolean | string[];
134
+ /**
135
+ * The app's own migration command, run in the checkout instead of
136
+ * `central`/`tenants` (e.g. `['./node_modules/.bin/tsx', 'scripts/db.ts', 'deploy']`).
137
+ */
138
+ command?: string[];
139
+ /**
140
+ * Values that override the `.env` for the migration and the pre-migration
141
+ * dump — e.g. URLs that name a container (`@mukanda-postgres:`) rewritten to
142
+ * reach it from the host (`@127.0.0.1:`).
143
+ */
144
+ env?: (values: ReadonlyMap<string, string>) => Record<string, string>;
117
145
  }
118
146
  export interface BackupConfig {
119
147
  beforeMigrate?: boolean;
@@ -122,8 +150,39 @@ export interface BackupConfig {
122
150
  dir?: string;
123
151
  /** With external infra: the `.env` key holding the database URL. Default `DATABASE_URL`. */
124
152
  urlKey?: string;
153
+ /**
154
+ * With external infra: the Postgres container to dump INSIDE (`docker exec`)
155
+ * — the server's own pg_dump major, and no pg_dump needed on the host. The
156
+ * user and database come from the URL at `urlKey`.
157
+ */
158
+ container?: string;
159
+ }
160
+ export type RuntimeConfig = Pm2Runtime | ComposeRuntime;
161
+ /** A Docker Compose project, its images built per commit (RFC 0006 §13.2). */
162
+ export interface ComposeRuntime {
163
+ kind: 'compose';
164
+ /** The compose file, relative to the checkout. */
165
+ file: string;
166
+ /** Built as `<tag>:<sha>`; each tag must start with the app name (C4). */
167
+ images: ComposeImage[];
168
+ /** What the proxy reaches on 127.0.0.1: the service and its published port. */
169
+ upstream: {
170
+ service: string;
171
+ port: number;
172
+ };
173
+ /** Compose interpolation values (never secrets: they are not in a 0600 file). */
174
+ env: Record<string, string>;
175
+ /** Releases whose images are kept for a rollback without a rebuild. */
176
+ keepImages: number;
177
+ }
178
+ export interface ComposeImage {
179
+ tag: string;
180
+ dockerfile: string;
181
+ /** Build context, relative to the checkout. Default `.`. */
182
+ context?: string;
183
+ /** The compose variable that receives `<tag>:<sha>`. */
184
+ env: string;
125
185
  }
126
- export type RuntimeConfig = Pm2Runtime;
127
186
  export interface Pm2Runtime {
128
187
  kind: 'pm2';
129
188
  /** Default `<app>-api`. Must start with `<app>-` (RFC 0006 §5, C4). */
@@ -137,6 +196,15 @@ export interface Pm2Runtime {
137
196
  export type ProxyConfig = ApacheProxy | NoProxy;
138
197
  export interface ApacheProxy {
139
198
  kind: 'apache';
199
+ /**
200
+ * `false`: the app writes its own vhosts (more than one site, special
201
+ * rules). They are checked on every deploy — C2 (linked, not copied) and C1
202
+ * (every ProxyPass to 127.0.0.1 targets the upstream port) — and never
203
+ * rendered, diffed or written; `install` leaves Apache alone (§13.4).
204
+ */
205
+ managed?: boolean;
206
+ /** With `managed: false`: the vhost file names to check. */
207
+ vhosts?: string[];
140
208
  /** File name under `sites-available/`. Default `<app>.conf`. */
141
209
  vhost?: string;
142
210
  /** Directory served as the site's root, relative to the app directory. */
@@ -181,7 +249,19 @@ export declare const apache: (options?: {
181
249
  apiPrefix?: string;
182
250
  certName?: string;
183
251
  root?: string;
252
+ managed?: boolean;
253
+ vhosts?: string[];
184
254
  }) => ApacheProxy;
255
+ export declare const compose: (options: {
256
+ file: string;
257
+ images: ComposeImage[];
258
+ upstream: {
259
+ service: string;
260
+ port: number;
261
+ };
262
+ env?: Record<string, string>;
263
+ keepImages?: number;
264
+ }) => ComposeRuntime;
185
265
  export declare const none: () => NoProxy;
186
266
  export declare const external: () => ExternalInfra;
187
267
  export declare const MINIO_IMAGE = "minio/minio:RELEASE.2025-03-12T18-04-18Z";
@@ -202,6 +282,7 @@ export declare class DeployConfigError extends Error {
202
282
  readonly problems: string[];
203
283
  constructor(problems: string[]);
204
284
  }
285
+ /** The PM2 process name (`<app>-api` by default). Compose names its own containers. */
205
286
  export declare const processName: (config: DeployConfig) => string;
206
287
  export declare const vhostName: (config: DeployConfig) => string | undefined;
207
288
  export declare function validateConfig(config: DeployConfig): DeployConfig;
package/dist/config.js CHANGED
@@ -28,12 +28,22 @@ export const pm2 = (options = {}) => ({
28
28
  });
29
29
  export const apache = (options = {}) => ({
30
30
  kind: 'apache',
31
+ ...(options.managed === undefined ? {} : { managed: options.managed }),
32
+ ...(options.vhosts === undefined ? {} : { vhosts: options.vhosts }),
31
33
  ...(options.vhost === undefined ? {} : { vhost: options.vhost }),
32
34
  webRoot: options.webRoot ?? 'web/dist',
33
35
  apiPrefix: options.apiPrefix ?? '/api',
34
36
  ...(options.certName === undefined ? {} : { certName: options.certName }),
35
37
  ...(options.root === undefined ? {} : { root: options.root }),
36
38
  });
39
+ export const compose = (options) => ({
40
+ kind: 'compose',
41
+ file: options.file,
42
+ images: options.images,
43
+ upstream: options.upstream,
44
+ env: options.env ?? {},
45
+ keepImages: options.keepImages ?? 3,
46
+ });
37
47
  export const none = () => ({ kind: 'none' });
38
48
  export const external = () => ({ kind: 'external' });
39
49
  export const MINIO_IMAGE = 'minio/minio:RELEASE.2025-03-12T18-04-18Z';
@@ -74,7 +84,8 @@ export class DeployConfigError extends Error {
74
84
  this.name = 'DeployConfigError';
75
85
  }
76
86
  }
77
- export const processName = (config) => config.runtime.name ?? `${config.app}-api`;
87
+ /** The PM2 process name (`<app>-api` by default). Compose names its own containers. */
88
+ export const processName = (config) => config.runtime.kind === 'pm2' ? (config.runtime.name ?? `${config.app}-api`) : config.app;
78
89
  export const vhostName = (config) => config.proxy?.kind === 'apache' ? (config.proxy.vhost ?? `${config.app}.conf`) : undefined;
79
90
  export function validateConfig(config) {
80
91
  const problems = [];
@@ -84,11 +95,52 @@ export function validateConfig(config) {
84
95
  problems.push(`domain "${config.domain}" is not a lowercase host name`);
85
96
  // C4: the deploy only ever names what carries the app's label. `pm2 restart
86
97
  // all` once was one keystroke away from a production app that is not ours.
87
- const name = processName(config);
88
- if (!name.startsWith(`${config.app}-`))
89
- problems.push(`runtime.name "${name}" must start with "${config.app}-" — the deploy only touches what the app owns`);
90
- if (!/^[a-z0-9-]+$/.test(name))
91
- problems.push(`runtime.name "${name}" may only use a-z, 0-9 and -`);
98
+ if (config.runtime.kind === 'pm2') {
99
+ const name = processName(config);
100
+ if (!name.startsWith(`${config.app}-`))
101
+ problems.push(`runtime.name "${name}" must start with "${config.app}-" — the deploy only touches what the app owns`);
102
+ if (!/^[a-z0-9-]+$/.test(name))
103
+ problems.push(`runtime.name "${name}" may only use a-z, 0-9 and -`);
104
+ }
105
+ else {
106
+ const rt = config.runtime;
107
+ if (rt.images.length === 0)
108
+ problems.push('runtime.images: at least one image');
109
+ for (const image of rt.images) {
110
+ // C4: an image tag outside the app's name could prune another app's images.
111
+ if (image.tag !== config.app && !image.tag.startsWith(`${config.app}-`))
112
+ problems.push(`runtime image "${image.tag}" must be "${config.app}" or start with "${config.app}-" — the deploy only touches what the app owns`);
113
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(image.tag))
114
+ problems.push(`runtime image "${image.tag}" is not a plain image name (no registry, no tag)`);
115
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(image.env))
116
+ problems.push(`runtime image env "${image.env}" is not a variable name`);
117
+ }
118
+ if (new Set(rt.images.map((i) => i.tag)).size !== rt.images.length)
119
+ problems.push('runtime.images: each tag once');
120
+ if (!/^[a-z0-9][a-z0-9_-]*$/.test(rt.upstream.service))
121
+ problems.push(`runtime.upstream.service "${rt.upstream.service}" is not a compose service name`);
122
+ if (!Number.isInteger(rt.upstream.port) || rt.upstream.port < 1 || rt.upstream.port > 65535)
123
+ problems.push('runtime.upstream.port must be a port number');
124
+ if (!Number.isInteger(rt.keepImages) || rt.keepImages < 1)
125
+ problems.push('runtime.keepImages must be a whole number ≥ 1');
126
+ for (const key of Object.keys(rt.env))
127
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(key))
128
+ problems.push(`runtime.env key "${key}" is not a variable name`);
129
+ }
130
+ if (config.proxy?.kind === 'apache' && config.proxy.managed === false) {
131
+ const vhosts = config.proxy.vhosts ?? [];
132
+ if (vhosts.length === 0)
133
+ problems.push('proxy.vhosts: name the vhost files to check when managed is false');
134
+ for (const v of vhosts)
135
+ if (!/^[a-z0-9.-]+\.conf$/.test(v))
136
+ problems.push(`proxy.vhosts "${v}" must be a plain *.conf file name`);
137
+ }
138
+ for (const hook of [...(config.hooks?.infra ?? []), ...(config.hooks?.verify ?? [])]) {
139
+ if (!Array.isArray(hook) || hook.length === 0 || hook.some((part) => typeof part !== 'string'))
140
+ problems.push('hooks: each hook is a non-empty array of strings (a command and its arguments)');
141
+ }
142
+ if (config.migrate?.command && config.migrate.command.length === 0)
143
+ problems.push('migrate.command must not be empty');
92
144
  const vhost = vhostName(config);
93
145
  if (vhost !== undefined && !/^[a-z0-9.-]+\.conf$/.test(vhost))
94
146
  problems.push(`proxy.vhost "${vhost}" must be a plain *.conf file name`);
@@ -114,6 +166,9 @@ export function validateConfig(config) {
114
166
  if (config.backup?.keep !== undefined && (!Number.isInteger(config.backup.keep) || config.backup.keep < 1)) {
115
167
  problems.push('backup.keep must be a whole number ≥ 1');
116
168
  }
169
+ if (config.backup?.container !== undefined && !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(config.backup.container)) {
170
+ problems.push(`backup.container "${config.backup.container}" is not a container name`);
171
+ }
117
172
  if (problems.length > 0)
118
173
  throw new DeployConfigError(problems);
119
174
  return config;
@@ -124,8 +179,11 @@ export function applyOverrides(config, overrides) {
124
179
  next.domain = overrides.domain;
125
180
  if (overrides.branch !== undefined)
126
181
  next.branch = overrides.branch;
127
- if (overrides.port !== undefined)
128
- next.runtime = { ...config.runtime, port: overrides.port };
182
+ if (overrides.port !== undefined) {
183
+ next.runtime = config.runtime.kind === 'pm2'
184
+ ? { ...config.runtime, port: overrides.port }
185
+ : { ...config.runtime, upstream: { ...config.runtime.upstream, port: overrides.port } };
186
+ }
129
187
  if (overrides.infra && config.infra?.kind === 'docker') {
130
188
  const infra = { ...config.infra };
131
189
  const o = overrides.infra;
@@ -14,7 +14,10 @@ export interface EnvPlan {
14
14
  questions: string[];
15
15
  findings: Finding[];
16
16
  }
17
+ /** The `.env`: relative to the checkout, or absolute (`/etc/<app>/api.env`). */
17
18
  export declare const envFile: (ctx: DeployContext) => string;
19
+ /** Its exact copies (`env.mirror`), resolved the same way. */
20
+ export declare const envMirrors: (ctx: DeployContext) => string[];
18
21
  export declare function readEnv(ctx: DeployContext): Promise<EnvDocument>;
19
22
  export declare function syntaxFindings(document: EnvDocument, file: string): Finding[];
20
23
  export declare function planEnv(ctx: DeployContext, document: EnvDocument, port: number, infra: EnvChange[]): EnvPlan;
@@ -27,3 +30,7 @@ export declare function answerQuestions(ctx: DeployContext, plan: EnvPlan): Prom
27
30
  export declare function describeEnv(plan: EnvPlan): string[];
28
31
  /** Backs the file up (0600, last 5 kept) and writes it atomically, 0600. */
29
32
  export declare function writeEnv(ctx: DeployContext, plan: EnvPlan): Promise<void>;
33
+ /** Rewrites every mirror as an exact copy of the file (0600). */
34
+ export declare function writeMirrors(ctx: DeployContext, text: string): Promise<void>;
35
+ /** C10 — a mirror that is not an exact copy: two env files that disagree are two configurations. */
36
+ export declare function mirrorFindings(ctx: DeployContext): Promise<Finding[]>;
package/dist/env-step.js CHANGED
@@ -1,6 +1,9 @@
1
- import { join } from 'node:path';
1
+ import { basename, dirname, join, resolve } from 'node:path';
2
2
  import { applyEnvChanges, envValues, formatValue, parseEnv, UnwritableValueError } from './dotenv.js';
3
- export const envFile = (ctx) => join(ctx.dir, ctx.config.env.file ?? '.env');
3
+ /** The `.env`: relative to the checkout, or absolute (`/etc/<app>/api.env`). */
4
+ export const envFile = (ctx) => resolve(ctx.dir, ctx.config.env.file ?? '.env');
5
+ /** Its exact copies (`env.mirror`), resolved the same way. */
6
+ export const envMirrors = (ctx) => (ctx.config.env.mirror ?? []).map((m) => resolve(ctx.dir, m));
4
7
  export async function readEnv(ctx) {
5
8
  return parseEnv((await ctx.host.readFile(envFile(ctx))) ?? '');
6
9
  }
@@ -26,7 +29,10 @@ export function planEnv(ctx, document, port, infra) {
26
29
  changes.push({ kind: 'set', key, value, reason });
27
30
  pending.set(key, value);
28
31
  };
29
- set('PORT', String(port), 'the port the process listens on');
32
+ // PM2 runs the app on the host: PORT is where it listens. Under compose the
33
+ // port inside the container is the compose file's business, not the .env's.
34
+ if (config.runtime.kind === 'pm2')
35
+ set('PORT', String(port), 'the port the process listens on');
30
36
  for (const [key, value] of Object.entries(config.env.fixed ?? {}))
31
37
  set(key, value, 'fixed in deploy.config.ts');
32
38
  for (const [key, spec] of Object.entries(config.env.generate ?? {})) {
@@ -113,14 +119,43 @@ export async function writeEnv(ctx, plan) {
113
119
  if (await host.exists(file)) {
114
120
  const stamp = host.now().toISOString().replace(/[-:]/g, '').replace(/\..+$/, '');
115
121
  await host.copyFile(file, `${file}.bak-${stamp}`, 0o600);
116
- const base = file.slice(file.lastIndexOf('/') + 1);
117
- const dir = file.slice(0, file.lastIndexOf('/'));
122
+ const base = basename(file);
123
+ const dir = dirname(file);
118
124
  const backups = (await host.list(dir)).filter((name) => name.startsWith(`${base}.bak-`)).sort();
119
125
  for (const old of backups.slice(0, -5))
120
126
  await host.remove(join(dir, old));
121
127
  }
122
128
  await host.writeFile(file, text, 0o600);
129
+ await writeMirrors(ctx, text);
123
130
  plan.document = parseEnv(text);
124
131
  plan.values = envValues(plan.document);
125
132
  plan.changes = [];
126
133
  }
134
+ /** Rewrites every mirror as an exact copy of the file (0600). */
135
+ export async function writeMirrors(ctx, text) {
136
+ for (const mirror of envMirrors(ctx)) {
137
+ if ((await ctx.host.readFile(mirror)) === text)
138
+ continue;
139
+ await ctx.host.writeFile(mirror, text, 0o600);
140
+ }
141
+ }
142
+ /** C10 — a mirror that is not an exact copy: two env files that disagree are two configurations. */
143
+ export async function mirrorFindings(ctx) {
144
+ const mirrors = envMirrors(ctx);
145
+ if (mirrors.length === 0)
146
+ return [];
147
+ const text = await ctx.host.readFile(envFile(ctx));
148
+ const findings = [];
149
+ for (const mirror of mirrors) {
150
+ const copy = await ctx.host.readFile(mirror);
151
+ if (text === undefined || copy === text)
152
+ continue;
153
+ findings.push({
154
+ id: 'C10',
155
+ level: 'error',
156
+ message: copy === undefined ? `${mirror} (env.mirror) does not exist` : `${mirror} (env.mirror) differs from ${envFile(ctx)}`,
157
+ fix: `cp -p ${envFile(ctx)} ${mirror} — after checking which one is right; the deploy rewrites the mirror from the file`,
158
+ });
159
+ }
160
+ return findings;
161
+ }
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- export { defineDeploy, secret, ask, pm2, apache, none, external, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, type DeployConfig, type EnvConfig, type DeriveContext, type SecretSpec, type Question, type InfraConfig, type DockerInfra, type DockerInfraOptions, type ExternalInfra, type PostgresService, type RedisService, type MinioService, type BuildConfig, type MigrateConfig, type BackupConfig, type RuntimeConfig, type Pm2Runtime, type ProxyConfig, type ApacheProxy, type NoProxy, type HealthConfig, type ServerOverrides, } from './config.js';
1
+ export { defineDeploy, secret, ask, pm2, compose, apache, none, external, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, type DeployConfig, type EnvConfig, type DeriveContext, type SecretSpec, type Question, type InfraConfig, type DockerInfra, type DockerInfraOptions, type ExternalInfra, type PostgresService, type RedisService, type MinioService, type BuildConfig, type MigrateConfig, type BackupConfig, type RuntimeConfig, type Pm2Runtime, type ComposeRuntime, type ComposeImage, type HooksConfig, type ProxyConfig, type ApacheProxy, type NoProxy, type HealthConfig, type ServerOverrides, } from './config.js';
2
2
  export { main, loadConfig, createContext, USAGE } from './cli.js';
3
3
  export { nodeHost, consoleOutput, type Host, type ExecOptions, type ExecResult, type Output, type TlsCertificate } from './host.js';
4
- export { DeployError, type DeployContext, type Finding } from './context.js';
4
+ export { DeployError, INSTALL_COMMAND, RUN_COMMAND, type DeployContext, type Finding } from './context.js';
5
5
  export { parseEnv, applyEnvChanges, formatValue, envValues, UnwritableValueError, type EnvDocument, type EnvChange } from './dotenv.js';
6
6
  export { renderVhost, proxiedPorts } from './apache.js';
7
7
  export { renderCompose } from './infra.js';
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- export { defineDeploy, secret, ask, pm2, apache, none, external, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, } from './config.js';
1
+ export { defineDeploy, secret, ask, pm2, compose, apache, none, external, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, } from './config.js';
2
2
  export { main, loadConfig, createContext, USAGE } from './cli.js';
3
3
  export { nodeHost, consoleOutput } from './host.js';
4
- export { DeployError } from './context.js';
4
+ export { DeployError, INSTALL_COMMAND, RUN_COMMAND } from './context.js';
5
5
  export { parseEnv, applyEnvChanges, formatValue, envValues, UnwritableValueError } from './dotenv.js';
6
6
  export { renderVhost, proxiedPorts } from './apache.js';
7
7
  export { renderCompose } from './infra.js';
@@ -20,6 +20,8 @@ export interface Preflight {
20
20
  export declare function preflight(ctx: DeployContext, options?: RunOptions): Promise<Preflight>;
21
21
  /** `prisma migrate deploy` runs when asked to, or — unsaid — when the app generates a Prisma client. */
22
22
  export declare function migratesCentral(config: DeployContext['config']): boolean;
23
+ /** The `.env` as the migration and the dump see it: `migrate.env` on top (host URLs for container names). */
24
+ export declare function migrationValues(config: DeployContext['config'], values: Map<string, string>): Map<string, string>;
23
25
  /**
24
26
  * Whether the pre-migration dump runs, and why not when it does not. Unsaid,
25
27
  * it runs when there is something to migrate AND a Postgres to dump: the
@@ -39,11 +41,4 @@ export declare function run(ctx: DeployContext, options?: RunOptions): Promise<n
39
41
  /** `basalt-deploy rollback [--to=<sha>]` — code only; the database stays as it is. */
40
42
  export declare function rollback(ctx: DeployContext, to?: string): Promise<number>;
41
43
  export declare function status(ctx: DeployContext): Promise<number>;
42
- /**
43
- * `sudo basalt-deploy install` — once per server, by an administrator (RFC
44
- * 0006 §11.4). Everything that needs root and nothing else: the vhost, the
45
- * state directory owned by the app user. The app user is never added to the
46
- * `docker` group (root-equivalent); with dedicated infra it needs rootless
47
- * Docker, and this says so.
48
- */
49
44
  export declare function install(ctx: DeployContext, user: string | undefined): Promise<number>;
package/dist/pipeline.js CHANGED
@@ -1,11 +1,12 @@
1
- import { join } from 'node:path';
1
+ import { basename, dirname, join } from 'node:path';
2
2
  import { apacheInstall, apachePreflight, vhostPaths } from './apache.js';
3
3
  import { backupDatabase, restoreCommand } from './backup.js';
4
4
  import { lockfileFindings, tlsFindings, toolingFindings } from './checks.js';
5
+ import { composeBuild, composeEnv, composeHealthy, composeOf, composePreflight, composeRelease, composeStatus, pruneImages } from './compose.js';
5
6
  import { processName } from './config.js';
6
7
  import { DeployError, errors, INSTALL_COMMAND, report, RUN_COMMAND } from './context.js';
7
8
  import { checkSchema, coercionFindings, policyFindings } from './env-check.js';
8
- import { answerQuestions, describeEnv, planEnv, readEnv, syntaxFindings, writeEnv } from './env-step.js';
9
+ import { answerQuestions, describeEnv, envFile, envMirrors, mirrorFindings, planEnv, readEnv, syntaxFindings, writeEnv } from './env-step.js';
9
10
  import { envValues } from './dotenv.js';
10
11
  import { applyInfra, describeInfra, planInfra } from './infra.js';
11
12
  import { pm2List, pm2Preflight, pm2Release, resolvePort } from './pm2.js';
@@ -26,6 +27,42 @@ async function step(ctx, title, run) {
26
27
  ctx.host.out.step(title);
27
28
  return run();
28
29
  }
30
+ // ── the runtime: PM2 on the host, or a compose project ────────────────────
31
+ const isCompose = (ctx) => ctx.config.runtime.kind === 'compose';
32
+ async function runtimePreflight(ctx, port, sha) {
33
+ return isCompose(ctx) ? composePreflight(ctx, sha) : pm2Preflight(ctx, port);
34
+ }
35
+ async function release(ctx, values, sha) {
36
+ return isCompose(ctx) ? composeRelease(ctx, sha) : pm2Release(ctx, values);
37
+ }
38
+ function describeRelease(ctx, port) {
39
+ if (!isCompose(ctx))
40
+ return `pm2 ${processName(ctx.config)} on 127.0.0.1:${port}`;
41
+ const rt = composeOf(ctx);
42
+ return `docker compose -p ${ctx.config.app} up -d (${rt.images.map((i) => `${i.tag}:<sha>`).join(', ')}); ${rt.upstream.service} on 127.0.0.1:${port}`;
43
+ }
44
+ const logsHint = (ctx) => isCompose(ctx)
45
+ ? `docker compose -p ${ctx.config.app} logs ${composeOf(ctx).upstream.service} --tail=50`
46
+ : `pm2 logs ${processName(ctx.config)}`;
47
+ // ── hooks (RFC 0006 §13.3) ─────────────────────────────────────────────────
48
+ async function runHooks(ctx, which, values, sha) {
49
+ const hooks = ctx.config.hooks?.[which] ?? [];
50
+ if (hooks.length === 0)
51
+ return;
52
+ const env = {
53
+ ...Object.fromEntries(values),
54
+ ...(isCompose(ctx) ? composeEnv(ctx, sha) : {}),
55
+ DEPLOY_SHA: sha,
56
+ DEPLOY_APP: ctx.config.app,
57
+ };
58
+ for (const [command, ...args] of hooks) {
59
+ ctx.host.out.info(`${which} hook: ${[command, ...args].join(' ')}`);
60
+ const result = await ctx.host.exec(command, args, { cwd: ctx.dir, env, stream: true });
61
+ if (result.code !== 0)
62
+ throw new DeployError(`${which} hook \`${[command, ...args].join(' ')}\` failed (exit ${result.code})`);
63
+ }
64
+ ctx.host.out.ok(`${hooks.length} ${which} hook(s) passed`);
65
+ }
29
66
  export async function preflight(ctx, options = {}) {
30
67
  // First, before any command runs: the tree as the operator left it. A
31
68
  // later probe that writes to the checkout would otherwise be blamed on them.
@@ -36,13 +73,31 @@ export async function preflight(ctx, options = {}) {
36
73
  const port = await resolvePort(ctx, values);
37
74
  findings.push(...await toolingFindings(ctx));
38
75
  findings.push(...await lockfileFindings(ctx));
39
- findings.push(...await pm2Preflight(ctx, port));
76
+ const head = (await ctx.host.exec('git', ['rev-parse', 'HEAD'], { cwd: ctx.dir })).stdout.trim();
77
+ findings.push(...await runtimePreflight(ctx, port, head));
78
+ findings.push(...await mirrorFindings(ctx));
40
79
  if (ctx.config.proxy?.kind === 'apache')
41
80
  findings.push(...await apachePreflight(ctx, port));
42
81
  if (!options.skip?.includes('tls'))
43
82
  findings.push(...await tlsFindings(ctx));
83
+ findings.push(...await backupFindings(ctx, values, options));
44
84
  return { findings, port, values };
45
85
  }
86
+ /** `backup.container` running — found now, not after the build, minutes later. */
87
+ async function backupFindings(ctx, values, options) {
88
+ const container = ctx.config.backup?.container;
89
+ if (!container || !backupDecision(ctx.config, values, options.skip ?? []).run)
90
+ return [];
91
+ const running = await ctx.host.exec('docker', ['inspect', '--format', '{{.State.Running}}', container]);
92
+ if (running.stdout.trim() === 'true')
93
+ return [];
94
+ return [{
95
+ id: 'backup',
96
+ level: 'error',
97
+ message: running.code === 0 ? `backup.container ${container} is not running` : `backup.container ${container} does not exist (or docker is not available to this user)`,
98
+ fix: `docker start ${container}, or deploy with --skip=backup`,
99
+ }];
100
+ }
46
101
  const LOCKFILES = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock'];
47
102
  async function gitFindings(ctx, options) {
48
103
  const findings = [];
@@ -97,9 +152,17 @@ function stopOnErrors(ctx, findings, what) {
97
152
  // ── what runs by default ───────────────────────────────────────────────────
98
153
  /** `prisma migrate deploy` runs when asked to, or — unsaid — when the app generates a Prisma client. */
99
154
  export function migratesCentral(config) {
155
+ // An app migrating by its own command does not also get `prisma migrate deploy` unasked.
156
+ if (config.migrate?.command)
157
+ return config.migrate.central === true;
100
158
  return config.migrate?.central ?? (config.build?.prisma?.length ?? 0) > 0;
101
159
  }
102
- const migratesAnything = (config) => migratesCentral(config) || Boolean(config.migrate?.tenants);
160
+ const migratesAnything = (config) => Boolean(config.migrate?.command) || migratesCentral(config) || Boolean(config.migrate?.tenants);
161
+ /** The `.env` as the migration and the dump see it: `migrate.env` on top (host URLs for container names). */
162
+ export function migrationValues(config, values) {
163
+ const extra = config.migrate?.env?.(values) ?? {};
164
+ return new Map([...values, ...Object.entries(extra)]);
165
+ }
103
166
  /**
104
167
  * Whether the pre-migration dump runs, and why not when it does not. Unsaid,
105
168
  * it runs when there is something to migrate AND a Postgres to dump: the
@@ -118,7 +181,7 @@ export function backupDecision(config, values, skip = []) {
118
181
  return { run: false, why: 'nothing to migrate' };
119
182
  if (config.infra?.kind === 'docker' && config.infra.postgres)
120
183
  return { run: true };
121
- const url = values.get(config.backup?.urlKey ?? 'DATABASE_URL') ?? '';
184
+ const url = migrationValues(config, values).get(config.backup?.urlKey ?? 'DATABASE_URL') ?? '';
122
185
  return /^postgres(ql)?:\/\//.test(url) ? { run: true } : { run: false, why: 'no Postgres database in the .env' };
123
186
  }
124
187
  // ── the building blocks ────────────────────────────────────────────────────
@@ -128,7 +191,7 @@ async function prepareEnv(ctx, port) {
128
191
  const env = planEnv(ctx, document, port, infra.env);
129
192
  return { env, infra };
130
193
  }
131
- async function build(ctx, values) {
194
+ async function build(ctx, values, sha) {
132
195
  const { host, pm } = ctx;
133
196
  const run = async (args, options = {}) => {
134
197
  host.out.info(`${pm} ${args.join(' ')}`);
@@ -148,6 +211,8 @@ async function build(ctx, values) {
148
211
  await run(['exec', 'prisma', 'generate', '--config', config], { env: values });
149
212
  if (ctx.config.build?.web)
150
213
  await run(['--dir', ctx.config.build.web, 'run', 'build'], { env: values });
214
+ if (isCompose(ctx))
215
+ await composeBuild(ctx, sha);
151
216
  }
152
217
  /**
153
218
  * The deploy leaves the checkout as committed. pnpm ≥ 12 may rewrite the
@@ -177,9 +242,17 @@ async function validate(ctx, values) {
177
242
  const schema = await checkSchema(ctx, values);
178
243
  return [...schema.findings, ...coercionFindings(values, schema.trueKeys), ...policyFindings(ctx, values)];
179
244
  }
180
- async function migrate(ctx, values) {
245
+ async function migrate(ctx, raw) {
181
246
  const { host, pm } = ctx;
247
+ const values = migrationValues(ctx.config, raw);
182
248
  const env = { cwd: ctx.dir, stream: true, env: Object.fromEntries(values) };
249
+ const command = ctx.config.migrate?.command;
250
+ if (command) {
251
+ host.out.info(command.join(' '));
252
+ const result = await host.exec(command[0], command.slice(1), env);
253
+ if (result.code !== 0)
254
+ throw new DeployError(`${command.join(' ')} failed (exit ${result.code})`);
255
+ }
183
256
  if (migratesCentral(ctx.config)) {
184
257
  host.out.info(`${pm} exec prisma migrate deploy`);
185
258
  const central = await host.exec(pm, ['exec', 'prisma', 'migrate', 'deploy'], env);
@@ -195,7 +268,19 @@ async function migrate(ctx, values) {
195
268
  throw new DeployError('the tenant migrations failed');
196
269
  }
197
270
  if (!migratesAnything(ctx.config))
198
- host.out.info('nothing to migrate (no build.prisma, no migrate.tenants)');
271
+ host.out.info('nothing to migrate (no build.prisma, no migrate.tenants, no migrate.command)');
272
+ }
273
+ /** Compose: the upstream service healthy and nothing restarting; then, any runtime, the loopback URL. */
274
+ async function healthCheck(ctx, port, sha) {
275
+ if (isCompose(ctx)) {
276
+ const services = await composeHealthy(ctx, sha);
277
+ if (!services.ok)
278
+ return services;
279
+ ctx.host.out.ok(`${composeOf(ctx).upstream.service} healthy; no service restarting`);
280
+ }
281
+ if (await healthy(ctx, port))
282
+ return { ok: true };
283
+ return { ok: false, why: `the app does not answer on http://127.0.0.1:${port}${ctx.config.health?.path ?? '/health'}` };
199
284
  }
200
285
  async function healthy(ctx, port) {
201
286
  const { host, config } = ctx;
@@ -215,8 +300,10 @@ async function publicHealthy(ctx) {
215
300
  return undefined;
216
301
  const url = `https://${config.domain}${config.proxy.apiPrefix.replace(/\/$/, '')}${config.health?.path ?? '/health'}`;
217
302
  const answer = await ctx.host.httpGet(url, { timeoutMs: 10_000 });
218
- if ('status' in answer && answer.status >= 200 && answer.status < 400)
303
+ if ('status' in answer && answer.status >= 200 && answer.status < 400) {
304
+ ctx.host.out.ok(url);
219
305
  return undefined;
306
+ }
220
307
  return {
221
308
  id: 'health',
222
309
  level: 'error',
@@ -228,7 +315,7 @@ async function publicHealthy(ctx) {
228
315
  async function restoreCode(ctx, sha, values) {
229
316
  ctx.host.out.step(`restoring the code to ${sha.slice(0, 7)}`);
230
317
  await git(ctx, ['reset', '--hard', sha]);
231
- await build(ctx, values);
318
+ await build(ctx, values, sha);
232
319
  await settleLockfile(ctx);
233
320
  }
234
321
  /** The env step's summary: what changed, or that nothing did. */
@@ -263,15 +350,18 @@ export async function plan(ctx, options = {}) {
263
350
  options.skip?.includes('fetch') ? 'fetch: skipped' : `fetch: git fetch ${config.remote ?? 'origin'} ${config.branch ?? 'main'} && git merge --ff-only`,
264
351
  ...describeEnv(env).map((l) => `env: ${l}`),
265
352
  ...describeInfra(infra).map((l) => `infra: ${l}`),
266
- `build: ${pm} install (frozen), ${(config.build?.prisma ?? []).map((c) => `prisma generate --config ${c}`).join(', ') || 'no prisma'}${config.build?.web ? `, ${config.build.web} build` : ''}`,
353
+ `build: ${pm} install (frozen), ${(config.build?.prisma ?? []).map((c) => `prisma generate --config ${c}`).join(', ') || 'no prisma'}${config.build?.web ? `, ${config.build.web} build` : ''}${isCompose(ctx) ? `, docker build ${composeOf(ctx).images.map((i) => i.tag).join(', ')} (skipped when the commit's tag exists)` : ''}`,
354
+ ...(config.hooks?.infra ?? []).map((h) => `infra hook: ${h.join(' ')}`),
267
355
  `validate: ${config.env.schema ?? '(no schema configured)'} against the new .env`,
268
356
  ((decision) => decision.run
269
- ? `backup: pg_dump → ${config.backup?.dir ?? 'backups/predeploy'} (keep ${config.backup?.keep ?? 10})`
357
+ ? `backup: pg_dump${config.backup?.container ? ` inside ${config.backup.container}` : ''} → ${config.backup?.dir ?? 'backups/predeploy'} (keep ${config.backup?.keep ?? 10})`
270
358
  : `backup: skipped (${decision.why})`)(backupDecision(config, checked.values, options.skip ?? [])),
271
- `migrate: ${[migratesCentral(config) ? 'prisma migrate deploy' : '', config.migrate?.tenants ? 'tenant:migrate' : ''].filter(Boolean).join(' + ') || 'nothing configured'}`,
272
- `release: pm2 ${processName(config)} on 127.0.0.1:${checked.port}`,
359
+ `migrate: ${[config.migrate?.command?.join(' ') ?? '', migratesCentral(config) ? 'prisma migrate deploy' : '', config.migrate?.tenants ? 'tenant:migrate' : ''].filter(Boolean).join(' + ') || 'nothing configured'}`,
360
+ `release: ${describeRelease(ctx, checked.port)}`,
273
361
  `health: http://127.0.0.1:${checked.port}${config.health?.path ?? '/health'} (Host: ${config.domain})${config.proxy?.kind === 'apache' && config.health?.public !== false ? `, then https://${config.domain}${config.proxy.apiPrefix}${config.health?.path ?? '/health'}` : ''}`,
274
362
  ];
363
+ for (const hook of config.hooks?.verify ?? [])
364
+ lines.push(`verify hook: ${hook.join(' ')}`);
275
365
  for (const line of lines)
276
366
  host.out.info(line);
277
367
  return errors([...checked.findings, ...infra.findings]).length > 0 ? 1 : 0;
@@ -290,7 +380,7 @@ export async function envCommand(ctx) {
290
380
  await writeEnv(ctx, env);
291
381
  await step(ctx, 'infra', () => infraStep(ctx, infra));
292
382
  await step(ctx, 'validate', () => validateStep(ctx, env.values));
293
- ctx.host.out.ok(`.env ready (PORT=${port})`);
383
+ ctx.host.out.ok(isCompose(ctx) ? `${envFile(ctx)} ready` : `.env ready (PORT=${port})`);
294
384
  return 0;
295
385
  }
296
386
  export async function run(ctx, options = {}) {
@@ -309,7 +399,7 @@ export async function run(ctx, options = {}) {
309
399
  const sha = await git(ctx, ['rev-parse', 'HEAD']);
310
400
  host.out.info(sha === previous ? `already at ${sha.slice(0, 7)}` : `${previous.slice(0, 7)} → ${sha.slice(0, 7)}`);
311
401
  const applied = sha === previous ? [] : migrationNames((await git(ctx, ['diff', '--name-only', previous, sha])).split('\n'));
312
- const release = { sha, previous, at: host.now().toISOString(), user: host.env['USER'] ?? String(host.uid()), status: 'failed', migrations: applied };
402
+ const record = { sha, previous, at: host.now().toISOString(), user: host.env['USER'] ?? String(host.uid()), status: 'failed', migrations: applied };
313
403
  // From here a failure puts the code on disk back before it is reported.
314
404
  const lockfileSaid = { warned: false };
315
405
  let values = checked.values;
@@ -327,13 +417,13 @@ export async function run(ctx, options = {}) {
327
417
  reportEnv(ctx, prepared.env);
328
418
  await writeEnv(ctx, prepared.env);
329
419
  values = prepared.env.values;
330
- await step(ctx, 'infra', () => infraStep(ctx, infra));
331
- await step(ctx, 'build', async () => { await build(ctx, values); await settleLockfile(ctx, lockfileSaid); });
420
+ await step(ctx, 'infra', async () => { await infraStep(ctx, infra); await runHooks(ctx, 'infra', values, sha); });
421
+ await step(ctx, 'build', async () => { await build(ctx, values, sha); await settleLockfile(ctx, lockfileSaid); });
332
422
  await step(ctx, 'validate', () => validateStep(ctx, values));
333
423
  const backup = backupDecision(config, values, skip);
334
424
  if (backup.run) {
335
- release.backup = await step(ctx, 'backup', () => backupDatabase(ctx, values, infra, sha));
336
- host.out.ok(release.backup);
425
+ record.backup = await step(ctx, 'backup', () => backupDatabase(ctx, migrationValues(config, values), infra, sha));
426
+ host.out.ok(record.backup);
337
427
  }
338
428
  else {
339
429
  host.out.step('backup');
@@ -344,8 +434,8 @@ export async function run(ctx, options = {}) {
344
434
  catch (error) {
345
435
  if (sha !== previous)
346
436
  await restoreCode(ctx, previous, values).catch((e) => host.out.error(`could not restore the code: ${e.message}`));
347
- release.note = error.message;
348
- await recordRelease(ctx, release).catch(() => undefined);
437
+ record.note = error.message;
438
+ await recordRelease(ctx, record).catch(() => undefined);
349
439
  throw error;
350
440
  }
351
441
  const destructive = applied.filter((name) => config.destructive?.includes(name));
@@ -354,33 +444,43 @@ export async function run(ctx, options = {}) {
354
444
  if (destructive.length > 0 || sha === previous) {
355
445
  if (destructive.length > 0)
356
446
  host.out.error(`not rolled back automatically: ${destructive.join(', ')} ${destructive.length === 1 ? 'is' : 'are'} marked destructive`);
357
- if (release.backup)
358
- host.out.info(`database before this release: ${restoreCommand(ctx, infra, release.backup)}`);
359
- release.note = why;
360
- await recordRelease(ctx, release);
447
+ if (record.backup)
448
+ host.out.info(`database before this release: ${restoreCommand(ctx, infra, record.backup, values)}`);
449
+ record.note = why;
450
+ await recordRelease(ctx, record);
361
451
  return 1;
362
452
  }
363
453
  await rollbackTo(ctx, previous, values, port);
364
- release.status = 'rolled-back';
365
- release.note = why;
366
- await recordRelease(ctx, release);
454
+ record.status = 'rolled-back';
455
+ record.note = why;
456
+ await recordRelease(ctx, record);
367
457
  return 1;
368
458
  };
369
459
  try {
370
- host.out.ok(await step(ctx, 'release', () => pm2Release(ctx, values)));
460
+ host.out.ok(await step(ctx, 'release', () => release(ctx, values, sha)));
371
461
  }
372
462
  catch (error) {
373
463
  return recover(error.message);
374
464
  }
375
- const ok = await step(ctx, 'health', () => healthy(ctx, port));
376
- if (!ok)
377
- return recover(`the app does not answer on http://127.0.0.1:${port}${config.health?.path ?? '/health'}`);
465
+ const health = await step(ctx, 'health', () => healthCheck(ctx, port, sha));
466
+ if (!health.ok)
467
+ return recover(health.why);
378
468
  host.out.ok(`http://127.0.0.1:${port}${config.health?.path ?? '/health'}`);
469
+ if (config.hooks?.verify?.length) {
470
+ try {
471
+ await step(ctx, 'verify', () => runHooks(ctx, 'verify', values, sha));
472
+ }
473
+ catch (error) {
474
+ return recover(error.message);
475
+ }
476
+ }
379
477
  const publicProblem = await publicHealthy(ctx);
380
- release.status = publicProblem ? 'public-unreachable' : 'ok';
478
+ record.status = publicProblem ? 'public-unreachable' : 'ok';
381
479
  // `pnpm run start`, launched by PM2 in the checkout, may rewrite it too.
382
480
  await settleLockfile(ctx, lockfileSaid);
383
- await step(ctx, 'record', () => recordRelease(ctx, release));
481
+ await step(ctx, 'record', () => recordRelease(ctx, record));
482
+ if (isCompose(ctx) && !publicProblem)
483
+ await retainImages(ctx);
384
484
  if (publicProblem) {
385
485
  report(host, [publicProblem]);
386
486
  return 1;
@@ -388,14 +488,26 @@ export async function run(ctx, options = {}) {
388
488
  host.out.ok(`${config.app} ${sha.slice(0, 7)} is live at https://${config.domain}`);
389
489
  return 0;
390
490
  }
491
+ /** Compose: keep the images of the last `keepImages` healthy releases; remove older ones of these tags only. */
492
+ async function retainImages(ctx) {
493
+ const keep = composeOf(ctx).keepImages;
494
+ const releases = await readReleases(ctx);
495
+ const shas = [...new Set([...releases].reverse().filter((r) => r.status === 'ok').map((r) => r.sha))].slice(0, keep);
496
+ const removed = await pruneImages(ctx, shas);
497
+ if (removed.length > 0)
498
+ ctx.host.out.info(`removed ${removed.length} image(s) of releases older than the last ${keep}: ${removed.join(', ')}`);
499
+ }
391
500
  async function rollbackTo(ctx, sha, values, port) {
501
+ // Compose: the images of `sha` exist (kept by retention), so the rebuild
502
+ // inside restoreCode skips them — a rollback is not a new build.
392
503
  await restoreCode(ctx, sha, values);
393
504
  ctx.host.out.step(`release ${sha.slice(0, 7)}`);
394
- ctx.host.out.ok(await pm2Release(ctx, values));
395
- if (await healthy(ctx, port))
505
+ ctx.host.out.ok(await release(ctx, values, sha));
506
+ const health = await healthCheck(ctx, port, sha);
507
+ if (health.ok)
396
508
  ctx.host.out.ok(`back on ${sha.slice(0, 7)}`);
397
509
  else
398
- ctx.host.out.error(`${sha.slice(0, 7)} does not answer either — pm2 logs ${processName(ctx.config)}`);
510
+ ctx.host.out.error(`${sha.slice(0, 7)} does not answer either (${health.why}) — ${logsHint(ctx)}`);
399
511
  }
400
512
  /** `basalt-deploy rollback [--to=<sha>]` — code only; the database stays as it is. */
401
513
  export async function rollback(ctx, to) {
@@ -426,6 +538,12 @@ export async function status(ctx) {
426
538
  host.out.step(`${ctx.config.app} — last ${releases.length} release(s)`);
427
539
  for (const r of releases)
428
540
  host.out.info(`${r.at} ${r.sha.slice(0, 7)} ${r.status.padEnd(18)} ${r.user}${r.migrations.length ? ` +${r.migrations.length} migration(s)` : ''}${r.note ? ` — ${r.note}` : ''}`);
541
+ if (isCompose(ctx)) {
542
+ const head = (await ctx.host.exec('git', ['rev-parse', 'HEAD'], { cwd: ctx.dir })).stdout.trim();
543
+ for (const line of await composeStatus(ctx, head))
544
+ host.out.info(line);
545
+ return 0;
546
+ }
429
547
  const process = (await pm2List(ctx))?.find((p) => p.name === processName(ctx.config));
430
548
  host.out.info(process ? `pm2 ${process.name}: ${process.status} (pid ${process.pid}, ${process.cwd})` : `pm2 ${processName(ctx.config)}: not running`);
431
549
  return 0;
@@ -437,13 +555,50 @@ export async function status(ctx) {
437
555
  * `docker` group (root-equivalent); with dedicated infra it needs rootless
438
556
  * Docker, and this says so.
439
557
  */
558
+ /**
559
+ * An env file outside the checkout (`/etc/<app>/api.env`) was root's while
560
+ * deploys ran under sudo. Deploys run as the app user (§11.4, §13.5), so it
561
+ * takes over the files — and their directory, where the atomic write and the
562
+ * backups are created, but only a directory that is plainly the app's own
563
+ * (its name contains the app's). Never /etc, never a shared directory.
564
+ */
565
+ async function envOwnership(ctx, user) {
566
+ const files = [envFile(ctx), ...envMirrors(ctx)].filter((f) => !f.startsWith(`${ctx.dir}/`));
567
+ if (files.length === 0)
568
+ return;
569
+ await step(ctx, 'env files outside the checkout', async () => {
570
+ const { host } = ctx;
571
+ for (const file of files) {
572
+ if (!(await host.exists(file))) {
573
+ host.out.warn(`${file} does not exist yet — the first deploy creates it`);
574
+ continue;
575
+ }
576
+ const chown = await host.exec('chown', [`${user}:`, file]);
577
+ if (chown.code !== 0)
578
+ throw new DeployError(`chown ${user} ${file}: ${chown.stderr.trim()}`);
579
+ await host.exec('chmod', ['600', file]);
580
+ }
581
+ for (const dir of [...new Set(files.map((f) => dirname(f)))]) {
582
+ if (basename(dir).includes(ctx.config.app) && dir !== '/' && dir !== '/etc') {
583
+ const chown = await host.exec('chown', [`${user}:`, dir]);
584
+ if (chown.code !== 0)
585
+ throw new DeployError(`chown ${user} ${dir}: ${chown.stderr.trim()}`);
586
+ await host.exec('chmod', ['700', dir]);
587
+ host.out.ok(`${dir} and its env files (${files.filter((f) => dirname(f) === dir).map((f) => basename(f)).join(', ')}) now owned by ${user}, 0700/0600`);
588
+ }
589
+ else {
590
+ host.out.warn(`${dir} is not ${ctx.config.app}'s own directory: the files are ${user}'s, but backups and atomic writes need ${user} to write in ${dir}`);
591
+ }
592
+ }
593
+ });
594
+ }
440
595
  export async function install(ctx, user) {
441
596
  const { host, config } = ctx;
442
597
  if (host.uid() !== 0)
443
598
  throw new DeployError(`install needs root: ${INSTALL_COMMAND}`);
444
599
  if (!user || user === 'root')
445
600
  throw new DeployError('install needs the unprivileged user the deploys run as: --user=<name> (never root)');
446
- const port = Number(envValues(await readEnv(ctx)).get('PORT'));
601
+ const port = isCompose(ctx) ? composeOf(ctx).upstream.port : Number(envValues(await readEnv(ctx)).get('PORT'));
447
602
  if (!Number.isInteger(port) || port <= 0)
448
603
  throw new DeployError(`no PORT in the .env yet: run \`${RUN_COMMAND.replace(/ run$/, ' env')}\` as the app user first`);
449
604
  const stateDir = `/var/lib/basalt/${config.app}`;
@@ -478,7 +633,8 @@ export async function install(ctx, user) {
478
633
  host.out.ok(`${overrides} created (server-local overrides, no secrets)`);
479
634
  }
480
635
  });
481
- if (config.proxy?.kind === 'apache') {
636
+ await envOwnership(ctx, user);
637
+ if (config.proxy?.kind === 'apache' && config.proxy.managed !== false) {
482
638
  await step(ctx, `Apache vhost ${vhostPaths(ctx).file}`, () => apacheInstall(ctx, port, join(stateDir, 'install-backups')));
483
639
  }
484
640
  if (config.infra?.kind === 'docker') {
package/dist/pm2.d.ts CHANGED
@@ -9,6 +9,7 @@ export interface Pm2Process {
9
9
  status: string;
10
10
  }
11
11
  export declare function pm2List(ctx: DeployContext): Promise<Pm2Process[] | undefined>;
12
+ /** The port the app listens on: the compose upstream's, or PM2's (`auto` picks a free one). */
12
13
  export declare function resolvePort(ctx: DeployContext, values: Map<string, string>): Promise<number>;
13
14
  export declare function pm2Preflight(ctx: DeployContext, port: number): Promise<Finding[]>;
14
15
  /**
package/dist/pm2.js CHANGED
@@ -18,8 +18,16 @@ export async function pm2List(ctx) {
18
18
  }
19
19
  }
20
20
  const PORT_FROM = 3000;
21
+ const pm2Of = (ctx) => {
22
+ if (ctx.config.runtime.kind !== 'pm2')
23
+ throw new Error('not a pm2 runtime');
24
+ return ctx.config.runtime;
25
+ };
26
+ /** The port the app listens on: the compose upstream's, or PM2's (`auto` picks a free one). */
21
27
  export async function resolvePort(ctx, values) {
22
- const runtime = ctx.config.runtime;
28
+ if (ctx.config.runtime.kind === 'compose')
29
+ return ctx.config.runtime.upstream.port;
30
+ const runtime = pm2Of(ctx);
23
31
  if (typeof runtime.port === 'number')
24
32
  return runtime.port;
25
33
  const current = Number(values.get('PORT'));
@@ -97,11 +105,11 @@ export async function pm2Release(ctx, env) {
97
105
  done = `${name} restarted`;
98
106
  }
99
107
  else {
100
- await must(ctx, ['start', ctx.pm, '--name', name, '--cwd', ctx.dir, '--', 'run', ctx.config.runtime.script], options);
108
+ await must(ctx, ['start', ctx.pm, '--name', name, '--cwd', ctx.dir, '--', 'run', pm2Of(ctx).script], options);
101
109
  done = ours ? `${name} re-created in ${ctx.dir}` : `${name} started`;
102
110
  }
103
111
  await must(ctx, ['save'], options);
104
- return `${done} (${ctx.pm} run ${ctx.config.runtime.script}, port ${env.get('PORT') ?? '?'})`;
112
+ return `${done} (${ctx.pm} run ${pm2Of(ctx).script}, port ${env.get('PORT') ?? '?'})`;
105
113
  }
106
114
  async function must(ctx, args, options) {
107
115
  const result = await ctx.host.exec('pm2', args, options);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/deploy",
3
- "version": "0.1.4",
3
+ "version": "0.2.1",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },