@basaltkit/deploy 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -7
- package/dist/cli.js +6 -1
- package/dist/compose.js +7 -0
- package/dist/config.d.ts +31 -5
- package/dist/config.js +8 -1
- package/dist/context.d.ts +7 -0
- package/dist/env-check.d.ts +1 -1
- package/dist/env-check.js +1 -1
- package/dist/infra.d.ts +8 -0
- package/dist/infra.js +35 -21
- package/dist/init.js +2 -2
- package/dist/pipeline.d.ts +6 -2
- package/dist/pipeline.js +18 -6
- package/dist/services.d.ts +5 -3
- package/dist/services.js +21 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,8 +31,8 @@ and runs `check` on what it wrote.
|
|
|
31
31
|
import { apache, ask, defineDeploy, dockerInfra, pm2, secret } from '@basaltkit/deploy'
|
|
32
32
|
|
|
33
33
|
export default defineDeploy({
|
|
34
|
-
app: '
|
|
35
|
-
domain: '
|
|
34
|
+
app: 'acme', // names everything it owns: acme-api, acme-pg, …
|
|
35
|
+
domain: 'acme.example.com',
|
|
36
36
|
tenants: 'subdomain', // also checks the *.domain certificate and DNS
|
|
37
37
|
branch: 'master',
|
|
38
38
|
env: {
|
|
@@ -41,14 +41,14 @@ export default defineDeploy({
|
|
|
41
41
|
generate: { APP_SECRET: secret(32) },
|
|
42
42
|
ask: {
|
|
43
43
|
MAILER_URL: ask.secret('SMTP URL', { optional: true }),
|
|
44
|
-
|
|
44
|
+
PAYCO_SECRET_TOKEN: ask.secret('PayCo token'),
|
|
45
45
|
},
|
|
46
|
-
derive: ({ domain }) => ({
|
|
47
|
-
forbid: ['
|
|
46
|
+
derive: ({ domain }) => ({ PAYCO_CALLBACK_URL: `https://${domain}/api/webhooks/payco` }),
|
|
47
|
+
forbid: ['PAYCO_FAKE'],
|
|
48
48
|
},
|
|
49
|
-
infra: dockerInfra('
|
|
49
|
+
infra: dockerInfra('acme', {
|
|
50
50
|
postgres: { urlParams: { schema: 'public' } },
|
|
51
|
-
minio: { buckets: ['
|
|
51
|
+
minio: { buckets: ['acme-documents', 'acme-backups'] },
|
|
52
52
|
}),
|
|
53
53
|
build: { prisma: ['prisma.config.ts', 'prisma/tenants/prisma.config.ts'], web: 'web' },
|
|
54
54
|
migrate: { central: true, tenants: true },
|
|
@@ -196,6 +196,28 @@ migrate: {
|
|
|
196
196
|
},
|
|
197
197
|
```
|
|
198
198
|
|
|
199
|
+
**Dedicated infra for a compose app** — the containers created by the deploy
|
|
200
|
+
too, in their own compose project, reached by name from the app's containers:
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
infra: dockerInfra('myapp', {
|
|
204
|
+
project: 'myapp-infra', // never the runtime's project: each would remove the other's containers
|
|
205
|
+
access: 'containers', // URLs name the containers (myapp-pg:5432); migrations get 127.0.0.1:<port>
|
|
206
|
+
postgres: { user: 'myapp_owner', urlKey: 'OWNER_DATABASE_URL', appRole: { name: 'myapp_app', urlKey: 'DATABASE_URL' } },
|
|
207
|
+
redis: { urlKey: 'REDIS_URL' },
|
|
208
|
+
minio: { buckets: [{ name: 'myapp-documents', versioned: true }] },
|
|
209
|
+
}),
|
|
210
|
+
runtime: compose({
|
|
211
|
+
// …
|
|
212
|
+
attach: { 'myapp-pg': ['data'], 'myapp-redis': ['data'], 'myapp-minio': ['data'] },
|
|
213
|
+
passEnv: ['REDIS_URL'], // a service without env_file gets it through ${REDIS_URL}: from memory only
|
|
214
|
+
}),
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
Ports are still published on 127.0.0.1 for the host; the app role's URL
|
|
218
|
+
follows the database when it moves (a recreated container) and keeps its
|
|
219
|
+
password.
|
|
220
|
+
|
|
199
221
|
**Services you keep but do not create** (RFC 0007 §4) — containers that outlive
|
|
200
222
|
any release, adopted by name:
|
|
201
223
|
|
package/dist/cli.js
CHANGED
|
@@ -6,6 +6,7 @@ import { check } from './check.js';
|
|
|
6
6
|
import { init } from './init.js';
|
|
7
7
|
import { applyOverrides, DeployConfigError, parseOverrides, validateConfig } from './config.js';
|
|
8
8
|
import { DeployError, detectPackageManager, resolveStateDir } from './context.js';
|
|
9
|
+
import { envValues, parseEnv } from './dotenv.js';
|
|
9
10
|
import { nodeHost } from './host.js';
|
|
10
11
|
import { envCommand, install, plan, rollback, run, SKIPPABLE, status } from './pipeline.js';
|
|
11
12
|
export const USAGE = `basalt-deploy — deploy this Basalt app on this server (RFC 0006)
|
|
@@ -81,13 +82,17 @@ export async function loadConfig(dir, file) {
|
|
|
81
82
|
return config;
|
|
82
83
|
}
|
|
83
84
|
export async function createContext(host, dir, config) {
|
|
85
|
+
const envPath = resolve(dir, config.env.file ?? '.env');
|
|
86
|
+
const text = await host.readFile(envPath);
|
|
84
87
|
return {
|
|
85
88
|
config,
|
|
86
89
|
dir,
|
|
87
90
|
host,
|
|
88
91
|
pm: await detectPackageManager(host, dir),
|
|
89
|
-
envPath
|
|
92
|
+
envPath,
|
|
90
93
|
stateDir: await resolveStateDir(host, config, dir),
|
|
94
|
+
// What compose interpolation reads for passEnv in plan, status, rollback.
|
|
95
|
+
...(text === undefined ? {} : { values: envValues(parseEnv(text)) }),
|
|
91
96
|
};
|
|
92
97
|
}
|
|
93
98
|
export async function main(argv, host = nodeHost(), cwd = process.cwd()) {
|
package/dist/compose.js
CHANGED
|
@@ -22,6 +22,13 @@ export function composeEnv(ctx, sha) {
|
|
|
22
22
|
const env = { ...rt.env };
|
|
23
23
|
for (const image of rt.images)
|
|
24
24
|
env[image.env] = `${image.tag}:${short(sha)}`;
|
|
25
|
+
// From the .env, in compose's environment only (RFC 0007 §4): a password
|
|
26
|
+
// never goes into deploy.config.ts, a command line or a file.
|
|
27
|
+
for (const key of rt.passEnv ?? []) {
|
|
28
|
+
const value = ctx.values?.get(key);
|
|
29
|
+
if (value !== undefined)
|
|
30
|
+
env[key] = value;
|
|
31
|
+
}
|
|
25
32
|
return env;
|
|
26
33
|
}
|
|
27
34
|
const composeArgs = (ctx, ...args) => ['compose', '-p', ctx.config.app, '-f', join(ctx.dir, composeOf(ctx).file), ...args];
|
package/dist/config.d.ts
CHANGED
|
@@ -25,12 +25,12 @@ export interface DeployConfig<E extends object = EnvShape> {
|
|
|
25
25
|
/**
|
|
26
26
|
* Owner label: names every process, container, volume, vhost and backup.
|
|
27
27
|
* `[a-z][a-z0-9-]{1,30}`.
|
|
28
|
-
* @example '
|
|
28
|
+
* @example 'acme'
|
|
29
29
|
*/
|
|
30
30
|
app: string;
|
|
31
31
|
/**
|
|
32
32
|
* The apex the app answers on.
|
|
33
|
-
* @example '
|
|
33
|
+
* @example 'acme.example.com'
|
|
34
34
|
*/
|
|
35
35
|
domain: string;
|
|
36
36
|
/**
|
|
@@ -108,7 +108,7 @@ export interface EnvConfig<E extends object = EnvShape> {
|
|
|
108
108
|
* Relative to the app directory, or absolute. Written 0600, backed up
|
|
109
109
|
* before every change, in its own directory.
|
|
110
110
|
* @default '.env'
|
|
111
|
-
* @example '/etc/
|
|
111
|
+
* @example '/etc/globex/api.env'
|
|
112
112
|
*/
|
|
113
113
|
file?: string;
|
|
114
114
|
/** Exact copies of the file (0600), rewritten with it; one that differs is a C10 error. */
|
|
@@ -202,7 +202,7 @@ export interface ExternalPostgres<E extends object = EnvShape> {
|
|
|
202
202
|
* there when absent), and granted DML through the owner's default privileges.
|
|
203
203
|
*/
|
|
204
204
|
export interface AppRole<E extends object = EnvShape> {
|
|
205
|
-
/** @example '
|
|
205
|
+
/** @example 'globex_app' */
|
|
206
206
|
name: string;
|
|
207
207
|
/** The `.env` key with the app's URL. */
|
|
208
208
|
urlKey: EnvKey<E>;
|
|
@@ -221,6 +221,22 @@ export interface DockerInfra<E extends object = EnvShape> {
|
|
|
221
221
|
postgres?: PostgresService<E>;
|
|
222
222
|
redis?: RedisService<E>;
|
|
223
223
|
minio?: MinioService;
|
|
224
|
+
/**
|
|
225
|
+
* The compose project the containers belong to. Default: the app — what an
|
|
226
|
+
* older compose file of the app's infra already used. An app whose own
|
|
227
|
+
* runtime is a compose project named after it needs another one.
|
|
228
|
+
* @example 'myapp-infra'
|
|
229
|
+
*/
|
|
230
|
+
project?: string;
|
|
231
|
+
/**
|
|
232
|
+
* Who reaches the services through the URLs written to the `.env`:
|
|
233
|
+
* `host` — a process on the host (PM2): `127.0.0.1:<published port>`;
|
|
234
|
+
* `containers` — the app's containers: `<container>:<internal port>`, on
|
|
235
|
+
* the networks `runtime.attach` connects them to. Migrations and the dump,
|
|
236
|
+
* which run on the host, get the `127.0.0.1` form either way.
|
|
237
|
+
* @default 'host'
|
|
238
|
+
*/
|
|
239
|
+
access?: 'host' | 'containers';
|
|
224
240
|
}
|
|
225
241
|
export interface PostgresService<E extends object = EnvShape> {
|
|
226
242
|
image: string;
|
|
@@ -287,7 +303,7 @@ export interface MigrateConfig<E extends object = EnvShape> {
|
|
|
287
303
|
command?: string[];
|
|
288
304
|
/**
|
|
289
305
|
* Values that override the `.env` for the migration and the pre-migration
|
|
290
|
-
* dump — e.g. URLs that name a container (`@
|
|
306
|
+
* dump — e.g. URLs that name a container (`@globex-postgres:`) rewritten to
|
|
291
307
|
* reach it from the host (`@127.0.0.1:`).
|
|
292
308
|
*/
|
|
293
309
|
env?: (values: ReadonlyMap<EnvKey<E>, string>) => {
|
|
@@ -339,6 +355,13 @@ export interface ComposeRuntime {
|
|
|
339
355
|
env: Record<string, string>;
|
|
340
356
|
/** Releases whose images are kept for a rollback without a rebuild. */
|
|
341
357
|
keepImages: number;
|
|
358
|
+
/**
|
|
359
|
+
* `.env` keys handed to compose for interpolation (`${KEY}` in the file) —
|
|
360
|
+
* a service without `env_file` that still needs one value, a password among
|
|
361
|
+
* them. In compose's environment only: never on a command line, never in a file.
|
|
362
|
+
* @example ['MYAPP_REDIS_URL']
|
|
363
|
+
*/
|
|
364
|
+
passEnv?: string[];
|
|
342
365
|
/**
|
|
343
366
|
* Containers this project does not own, connected to its networks before
|
|
344
367
|
* `up` — creating the project first on a fresh server, so the first release
|
|
@@ -514,6 +537,7 @@ export declare const compose: (options: {
|
|
|
514
537
|
keepImages?: number;
|
|
515
538
|
attach?: Record<string, string[]>;
|
|
516
539
|
jobs?: ComposeJob[];
|
|
540
|
+
passEnv?: string[];
|
|
517
541
|
}) => ComposeRuntime;
|
|
518
542
|
export declare const none: () => NoProxy;
|
|
519
543
|
export declare const external: <E extends object = EnvShape>(services?: NoInfer<Omit<ExternalInfra<E>, 'kind'>>) => ExternalInfra<E>;
|
|
@@ -521,6 +545,8 @@ export declare const external: <E extends object = EnvShape>(services?: NoInfer<
|
|
|
521
545
|
export declare const bucketName: (bucket: Bucket) => string;
|
|
522
546
|
export declare const MINIO_IMAGE = "minio/minio:RELEASE.2025-03-12T18-04-18Z";
|
|
523
547
|
export interface DockerInfraOptions<E extends object = EnvShape> {
|
|
548
|
+
project?: string;
|
|
549
|
+
access?: 'host' | 'containers';
|
|
524
550
|
postgres?: Partial<PostgresService<E>> | false;
|
|
525
551
|
redis?: Partial<RedisService<E>> | false;
|
|
526
552
|
minio?: Partial<MinioService> | false;
|
package/dist/config.js
CHANGED
|
@@ -67,6 +67,7 @@ export const compose = (options) => ({
|
|
|
67
67
|
keepImages: options.keepImages ?? 3,
|
|
68
68
|
...(options.attach ? { attach: options.attach } : {}),
|
|
69
69
|
...(options.jobs ? { jobs: options.jobs } : {}),
|
|
70
|
+
...(options.passEnv ? { passEnv: options.passEnv } : {}),
|
|
70
71
|
});
|
|
71
72
|
export const none = () => ({ kind: 'none' });
|
|
72
73
|
export const external = (services = {}) => ({ kind: 'external', ...services });
|
|
@@ -80,7 +81,7 @@ export const MINIO_IMAGE = 'minio/minio:RELEASE.2025-03-12T18-04-18Z';
|
|
|
80
81
|
* duplicated.
|
|
81
82
|
*/
|
|
82
83
|
export function dockerInfra(app, options = {}) {
|
|
83
|
-
const infra = { kind: 'docker' };
|
|
84
|
+
const infra = { kind: 'docker', ...(options.project ? { project: options.project } : {}), ...(options.access ? { access: options.access } : {}) };
|
|
84
85
|
if (options.postgres !== false) {
|
|
85
86
|
infra.postgres = {
|
|
86
87
|
image: 'postgres:16', port: 'auto', user: app, database: app, urlKey: 'DATABASE_URL', urlParams: {},
|
|
@@ -209,6 +210,12 @@ export function validateConfig(typed) {
|
|
|
209
210
|
if (container !== undefined && !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(container))
|
|
210
211
|
problems.push(`container "${container}" is not a container name`);
|
|
211
212
|
}
|
|
213
|
+
if (config.infra?.kind === 'docker' && config.infra.project !== undefined && !/^[a-z0-9][a-z0-9_-]*$/.test(config.infra.project)) {
|
|
214
|
+
problems.push(`infra.project "${config.infra.project}" is not a compose project name`);
|
|
215
|
+
}
|
|
216
|
+
if (config.infra?.kind === 'docker' && (config.infra.project ?? config.app) === config.app && config.runtime.kind === 'compose') {
|
|
217
|
+
problems.push(`infra.project "${config.app}" is the runtime's compose project too: the two would remove each other's containers as orphans — use "${config.app}-infra"`);
|
|
218
|
+
}
|
|
212
219
|
const role = services?.postgres?.appRole ?? (config.infra?.kind === 'docker' ? config.infra.postgres?.appRole : undefined);
|
|
213
220
|
if (role && !/^[a-z_][a-z0-9_]{0,62}$/.test(role.name))
|
|
214
221
|
problems.push(`appRole "${role.name}" must be a lowercase Postgres identifier`);
|
package/dist/context.d.ts
CHANGED
|
@@ -10,6 +10,13 @@ export interface DeployContext {
|
|
|
10
10
|
envPath: string;
|
|
11
11
|
/** Releases, generated infra files. `/var/lib/basalt/<app>` once `install` ran, else `<dir>/.basalt`. */
|
|
12
12
|
stateDir: string;
|
|
13
|
+
/**
|
|
14
|
+
* The `.env` as last read or written — what `compose({ passEnv })` hands to
|
|
15
|
+
* compose in its environment (never on a command line, never in a file).
|
|
16
|
+
*/
|
|
17
|
+
values?: Map<string, string>;
|
|
18
|
+
/** Container addresses → their 127.0.0.1 form, for what runs on the host (`dockerInfra({ access: 'containers' })`). */
|
|
19
|
+
hostUrls?: Array<[string, string]>;
|
|
13
20
|
}
|
|
14
21
|
export interface Finding {
|
|
15
22
|
/** The RFC 0006 §5 check id (`C1`…`C10`) or a step name. */
|
package/dist/env-check.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export declare function checkSchema(ctx: DeployContext, values: Map<string, stri
|
|
|
8
8
|
/**
|
|
9
9
|
* C6 — a value written to turn something OFF that the schema reads as ON.
|
|
10
10
|
* `z.coerce.boolean()` is `Boolean(string)`: every non-empty string is true,
|
|
11
|
-
* "0" and "false" included. `
|
|
11
|
+
* "0" and "false" included. `PAYCO_FAKE="0"` switched the fake payment
|
|
12
12
|
* gateway on in production. Generic on purpose: it needs no list of boolean
|
|
13
13
|
* keys, only the parsed result (prefixed names — `MY_APP_FLAG` for `FLAG` —
|
|
14
14
|
* are matched too).
|
package/dist/env-check.js
CHANGED
|
@@ -59,7 +59,7 @@ const FALSY = new Set(['0', 'false', 'no', 'off']);
|
|
|
59
59
|
/**
|
|
60
60
|
* C6 — a value written to turn something OFF that the schema reads as ON.
|
|
61
61
|
* `z.coerce.boolean()` is `Boolean(string)`: every non-empty string is true,
|
|
62
|
-
* "0" and "false" included. `
|
|
62
|
+
* "0" and "false" included. `PAYCO_FAKE="0"` switched the fake payment
|
|
63
63
|
* gateway on in production. Generic on purpose: it needs no list of boolean
|
|
64
64
|
* keys, only the parsed result (prefixed names — `MY_APP_FLAG` for `FLAG` —
|
|
65
65
|
* are matched too).
|
package/dist/infra.d.ts
CHANGED
|
@@ -35,7 +35,15 @@ export interface InfraPlan {
|
|
|
35
35
|
secrets: Record<string, string>;
|
|
36
36
|
/** The dedicated Postgres's owner URL, as the `.env` will hold it (the app role's is derived from it). */
|
|
37
37
|
ownerUrl?: string;
|
|
38
|
+
/**
|
|
39
|
+
* With `access: 'containers'`: each container address in the `.env` and the
|
|
40
|
+
* 127.0.0.1 one that reaches it from the host — for the migrations, which
|
|
41
|
+
* run on the host. `['@myapp-pg:5432', '@127.0.0.1:5433']`.
|
|
42
|
+
*/
|
|
43
|
+
hostUrls?: Array<[string, string]>;
|
|
38
44
|
}
|
|
45
|
+
/** The compose project of the dedicated infra. */
|
|
46
|
+
export declare const infraProject: (app: string, infra: DockerInfra) => string;
|
|
39
47
|
export declare function planInfra(ctx: DeployContext, values: Map<string, string>): Promise<InfraPlan>;
|
|
40
48
|
/** The compose file, with no secret in it: compose interpolates them from its environment. */
|
|
41
49
|
export declare function renderCompose(app: string, infra: DockerInfra, plan: InfraPlan): string;
|
package/dist/infra.js
CHANGED
|
@@ -25,17 +25,19 @@ async function inspect(ctx, container) {
|
|
|
25
25
|
async function volumeExists(ctx, volume) {
|
|
26
26
|
return (await ctx.host.exec('docker', ['volume', 'inspect', volume])).code === 0;
|
|
27
27
|
}
|
|
28
|
-
function urlParts(value) {
|
|
28
|
+
function urlParts(value, container) {
|
|
29
29
|
if (!value)
|
|
30
30
|
return undefined;
|
|
31
31
|
try {
|
|
32
32
|
const url = new URL(value);
|
|
33
|
-
|
|
33
|
+
const onHost = url.hostname === 'localhost' || url.hostname === '127.0.0.1';
|
|
34
|
+
if (!onHost && url.hostname !== container)
|
|
34
35
|
return undefined;
|
|
35
36
|
return {
|
|
36
37
|
user: decodeURIComponent(url.username),
|
|
37
38
|
password: decodeURIComponent(url.password),
|
|
38
|
-
port:
|
|
39
|
+
// A container's port is its internal one: no use for picking the published port.
|
|
40
|
+
port: onHost ? Number(url.port) : undefined,
|
|
39
41
|
database: url.pathname.replace(/^\//, ''),
|
|
40
42
|
};
|
|
41
43
|
}
|
|
@@ -43,15 +45,17 @@ function urlParts(value) {
|
|
|
43
45
|
return undefined;
|
|
44
46
|
}
|
|
45
47
|
}
|
|
46
|
-
const names = (app, service, container) => {
|
|
48
|
+
const names = (app, project, service, container) => {
|
|
47
49
|
const suffix = service === 'postgres' ? 'pg' : service;
|
|
48
|
-
// Compose prefixes volumes with the project name — the app — so
|
|
49
|
-
// what an older compose file with the same project name
|
|
50
|
-
return { container: container ?? `${app}-${suffix}`, volumeKey: `${app}-${suffix}-data`, volume: `${
|
|
50
|
+
// Compose prefixes volumes with the project name — by default the app — so
|
|
51
|
+
// this is what an older compose file with the same project name created.
|
|
52
|
+
return { container: container ?? `${app}-${suffix}`, volumeKey: `${app}-${suffix}-data`, volume: `${project}_${app}-${suffix}-data` };
|
|
51
53
|
};
|
|
54
|
+
/** The compose project of the dedicated infra. */
|
|
55
|
+
export const infraProject = (app, infra) => infra.project ?? app;
|
|
52
56
|
export async function planInfra(ctx, values) {
|
|
53
57
|
const infra = ctx.config.infra;
|
|
54
|
-
const plan = { services: [], env: [], findings: [], secrets: {} };
|
|
58
|
+
const plan = { services: [], env: [], findings: [], secrets: {}, hostUrls: [] };
|
|
55
59
|
if (infra?.kind === 'external') {
|
|
56
60
|
plan.findings.push(...await externalFindings(ctx));
|
|
57
61
|
const pg = infra.postgres;
|
|
@@ -62,6 +66,15 @@ export async function planInfra(ctx, values) {
|
|
|
62
66
|
if (infra?.kind !== 'docker')
|
|
63
67
|
return plan;
|
|
64
68
|
const { app } = ctx.config;
|
|
69
|
+
const project = infraProject(app, infra);
|
|
70
|
+
const inContainers = infra.access === 'containers';
|
|
71
|
+
/** The address the `.env` holds: the container's, or the host's. */
|
|
72
|
+
const address = (container, internal, published) => {
|
|
73
|
+
if (!inContainers)
|
|
74
|
+
return `127.0.0.1:${published}`;
|
|
75
|
+
plan.hostUrls?.push([`${container}:${internal}`, `127.0.0.1:${published}`]);
|
|
76
|
+
return `${container}:${internal}`;
|
|
77
|
+
};
|
|
65
78
|
const picked = [];
|
|
66
79
|
const pick = async (wanted, existing, from) => {
|
|
67
80
|
const port = typeof wanted === 'number' ? wanted : existing ?? await freePort(ctx.host, from, [], picked);
|
|
@@ -80,9 +93,9 @@ export async function planInfra(ctx, values) {
|
|
|
80
93
|
});
|
|
81
94
|
if (infra.postgres) {
|
|
82
95
|
const pg = infra.postgres;
|
|
83
|
-
const { container, volume } = names(app, 'postgres', pg.container);
|
|
96
|
+
const { container, volume } = names(app, project, 'postgres', pg.container);
|
|
84
97
|
const running = await inspect(ctx, container);
|
|
85
|
-
const fromEnv = urlParts(values.get(pg.urlKey));
|
|
98
|
+
const fromEnv = urlParts(values.get(pg.urlKey), inContainers ? container : undefined);
|
|
86
99
|
let password = running?.env.get('POSTGRES_PASSWORD');
|
|
87
100
|
let source = 'container';
|
|
88
101
|
if (password === undefined && fromEnv?.password) {
|
|
@@ -99,7 +112,7 @@ export async function planInfra(ctx, values) {
|
|
|
99
112
|
const database = running?.env.get('POSTGRES_DB') ?? fromEnv?.database ?? pg.database;
|
|
100
113
|
const port = await pick(pg.port, running?.ports.get('5432/tcp') ?? fromEnv?.port, 5433);
|
|
101
114
|
const params = new URLSearchParams(pg.urlParams).toString();
|
|
102
|
-
plan.ownerUrl = `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}
|
|
115
|
+
plan.ownerUrl = `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${address(container, 5432, port)}/${database}${params ? `?${params}` : ''}`;
|
|
103
116
|
setEnv(pg.urlKey, plan.ownerUrl, source === 'container' ? `from the running ${container}` : source === 'generated' ? 'new database' : 'port or parameters');
|
|
104
117
|
plan.env.push(...appRoleEnv(ctx, values, plan.ownerUrl));
|
|
105
118
|
plan.secrets['BASALT_PG_PASSWORD'] = password;
|
|
@@ -107,9 +120,9 @@ export async function planInfra(ctx, values) {
|
|
|
107
120
|
}
|
|
108
121
|
if (infra.redis) {
|
|
109
122
|
const redis = infra.redis;
|
|
110
|
-
const { container, volume } = names(app, 'redis', redis.container);
|
|
123
|
+
const { container, volume } = names(app, project, 'redis', redis.container);
|
|
111
124
|
const running = await inspect(ctx, container);
|
|
112
|
-
const fromEnv = urlParts(values.get(redis.urlKey));
|
|
125
|
+
const fromEnv = urlParts(values.get(redis.urlKey), inContainers ? container : undefined);
|
|
113
126
|
let password = running?.env.get('REDIS_PASSWORD');
|
|
114
127
|
let source = 'container';
|
|
115
128
|
if (password === undefined && fromEnv?.password) {
|
|
@@ -122,13 +135,13 @@ export async function planInfra(ctx, values) {
|
|
|
122
135
|
source = 'generated';
|
|
123
136
|
}
|
|
124
137
|
const port = await pick(redis.port, running?.ports.get('6379/tcp') ?? fromEnv?.port, 6380);
|
|
125
|
-
setEnv(redis.urlKey, `redis://:${encodeURIComponent(password)}
|
|
138
|
+
setEnv(redis.urlKey, `redis://:${encodeURIComponent(password)}@${address(container, 6379, port)}`, source === 'container' ? `from the running ${container}` : source === 'generated' ? 'new redis' : 'port');
|
|
126
139
|
plan.secrets['BASALT_REDIS_PASSWORD'] = password;
|
|
127
140
|
plan.services.push({ service: 'redis', container, volume, action: running ? 'adopt' : 'create', port, source });
|
|
128
141
|
}
|
|
129
142
|
if (infra.minio) {
|
|
130
143
|
const minio = infra.minio;
|
|
131
|
-
const { container, volume } = names(app, 'minio', minio.container);
|
|
144
|
+
const { container, volume } = names(app, project, 'minio', minio.container);
|
|
132
145
|
const running = await inspect(ctx, container);
|
|
133
146
|
let user = running?.env.get('MINIO_ROOT_USER');
|
|
134
147
|
let password = running?.env.get('MINIO_ROOT_PASSWORD');
|
|
@@ -148,7 +161,7 @@ export async function planInfra(ctx, values) {
|
|
|
148
161
|
let endpointPort;
|
|
149
162
|
try {
|
|
150
163
|
const endpoint = values.get(minio.keys.endpoint);
|
|
151
|
-
endpointPort = endpoint ? Number(new URL(endpoint).port) || undefined : undefined;
|
|
164
|
+
endpointPort = endpoint && !inContainers ? Number(new URL(endpoint).port) || undefined : undefined;
|
|
152
165
|
}
|
|
153
166
|
catch {
|
|
154
167
|
endpointPort = undefined;
|
|
@@ -156,7 +169,7 @@ export async function planInfra(ctx, values) {
|
|
|
156
169
|
const port = await pick(minio.port, running?.ports.get('9000/tcp') ?? endpointPort, 9100);
|
|
157
170
|
const consolePort = await pick(minio.consolePort, running?.ports.get('9001/tcp'), port + 1);
|
|
158
171
|
const reason = source === 'container' ? `from the running ${container}` : source === 'generated' ? 'new minio' : 'port';
|
|
159
|
-
setEnv(minio.keys.endpoint, `http
|
|
172
|
+
setEnv(minio.keys.endpoint, `http://${address(container, 9000, port)}`, reason);
|
|
160
173
|
setEnv(minio.keys.accessKey, user, reason);
|
|
161
174
|
setEnv(minio.keys.secretKey, password, reason);
|
|
162
175
|
plan.secrets['BASALT_MINIO_USER'] = user;
|
|
@@ -180,13 +193,13 @@ export function renderCompose(app, infra, plan) {
|
|
|
180
193
|
`# Generated by basalt-deploy for "${app}". Do not edit — change deploy.config.ts.`,
|
|
181
194
|
'# Every port is bound to 127.0.0.1: Docker writes its own iptables rules and',
|
|
182
195
|
'# ignores ufw, so a port published without an address is open to the internet.',
|
|
183
|
-
`name: ${app}`,
|
|
196
|
+
`name: ${infraProject(app, infra)}`,
|
|
184
197
|
'',
|
|
185
198
|
'services:',
|
|
186
199
|
];
|
|
187
200
|
const volumes = [];
|
|
188
201
|
for (const service of plan.services) {
|
|
189
|
-
const key = service.volume.slice(app.length + 1);
|
|
202
|
+
const key = service.volume.slice(infraProject(app, infra).length + 1);
|
|
190
203
|
volumes.push(key);
|
|
191
204
|
if (service.service === 'postgres' && infra.postgres) {
|
|
192
205
|
lines.push(' postgres:', ` image: ${infra.postgres.image}`, ` container_name: ${service.container}`, ' restart: unless-stopped', ` labels: { basalt.app: ${app} }`, ` ports: ['127.0.0.1:${service.port}:5432']`, ' environment:', ` POSTGRES_USER: ${service.user}`, ' POSTGRES_PASSWORD: ${BASALT_PG_PASSWORD:?missing}', ` POSTGRES_DB: ${service.database}`, ` volumes: ['${key}:/var/lib/postgresql/data']`, ' healthcheck:', ` test: ['CMD-SHELL', 'pg_isready -U ${service.user} -d ${service.database}']`, ' interval: 10s', ' timeout: 5s', ' retries: 10');
|
|
@@ -211,9 +224,10 @@ export async function applyInfra(ctx, plan) {
|
|
|
211
224
|
const { app } = ctx.config;
|
|
212
225
|
await host.mkdir(ctx.stateDir, 0o700);
|
|
213
226
|
await host.writeFile(composeFile(ctx), renderCompose(app, infra, plan), 0o600);
|
|
214
|
-
const
|
|
227
|
+
const project = infraProject(app, infra);
|
|
228
|
+
const up = await host.exec('docker', ['compose', '-p', project, '-f', composeFile(ctx), 'up', '-d', '--wait', '--wait-timeout', '180'], { env: plan.secrets });
|
|
215
229
|
if (up.code !== 0) {
|
|
216
|
-
return [{ id: 'infra', level: 'error', message: `docker compose up failed:\n${up.stderr.trim()}`, fix: `docker compose -p ${
|
|
230
|
+
return [{ id: 'infra', level: 'error', message: `docker compose up failed:\n${up.stderr.trim()}`, fix: `docker compose -p ${project} ps; docker logs ${plan.services[0]?.container ?? app}` }];
|
|
217
231
|
}
|
|
218
232
|
const findings = [];
|
|
219
233
|
for (const service of plan.services) {
|
package/dist/init.js
CHANGED
|
@@ -9,7 +9,7 @@ const SENSITIVE = /SECRET|TOKEN|PASSWORD|PASS\b|_KEY\b|^KEY_|CREDENTIAL|_URL$|_D
|
|
|
9
9
|
* the server. One a provider issues (S3, an API, SMTP) is asked instead — a
|
|
10
10
|
* random value would only fail at the first call.
|
|
11
11
|
*/
|
|
12
|
-
const ISSUED = /S3|AWS|ACCESS_KEY|API_?KEY|TOKEN|SMTP|MAIL|OAUTH|CLIENT|STRIPE|
|
|
12
|
+
const ISSUED = /S3|AWS|ACCESS_KEY|API_?KEY|TOKEN|SMTP|MAIL|OAUTH|CLIENT|STRIPE|PAYCO|TWILIO|SENDGRID|PASSWORD/;
|
|
13
13
|
// ── detection ──────────────────────────────────────────────────────────────
|
|
14
14
|
export async function detectProject(host, dir, options = {}) {
|
|
15
15
|
const pkg = parseJson(await host.readFile(`${dir}/package.json`));
|
|
@@ -427,7 +427,7 @@ function block(name, entries) {
|
|
|
427
427
|
return [` ${name}: { ${entries.join(', ')} },`];
|
|
428
428
|
return [` ${name}: {`, ...entries.map((e) => ` ${e},`), ' },'];
|
|
429
429
|
}
|
|
430
|
-
/** `
|
|
430
|
+
/** `GLOBEX_SMTP_URL` → `SMTP URL`: the prompt the operator sees once. */
|
|
431
431
|
function label(key, app) {
|
|
432
432
|
const prefix = `${app.toUpperCase().replace(/-/g, '_')}_`;
|
|
433
433
|
return (key.startsWith(prefix) ? key.slice(prefix.length) : key).replace(/_/g, ' ');
|
package/dist/pipeline.d.ts
CHANGED
|
@@ -20,8 +20,12 @@ 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
|
-
/**
|
|
24
|
-
|
|
23
|
+
/**
|
|
24
|
+
* The `.env` as the migration and the dump see it — they run on the host:
|
|
25
|
+
* container addresses (`@myapp-pg:5432`) become the published 127.0.0.1 ones,
|
|
26
|
+
* then `migrate.env` on top.
|
|
27
|
+
*/
|
|
28
|
+
export declare function migrationValues(config: DeployContext['config'], values: Map<string, string>, hostUrls?: Array<[string, string]>): Map<string, string>;
|
|
25
29
|
/**
|
|
26
30
|
* Whether the pre-migration dump runs, and why not when it does not. Unsaid,
|
|
27
31
|
* it runs when there is something to migrate AND a Postgres to dump: the
|
package/dist/pipeline.js
CHANGED
|
@@ -163,10 +163,20 @@ export function migratesCentral(config) {
|
|
|
163
163
|
return config.migrate?.central ?? (config.build?.prisma?.length ?? 0) > 0;
|
|
164
164
|
}
|
|
165
165
|
const migratesAnything = (config) => Boolean(config.migrate?.command) || migratesCentral(config) || Boolean(config.migrate?.tenants);
|
|
166
|
-
/**
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
166
|
+
/**
|
|
167
|
+
* The `.env` as the migration and the dump see it — they run on the host:
|
|
168
|
+
* container addresses (`@myapp-pg:5432`) become the published 127.0.0.1 ones,
|
|
169
|
+
* then `migrate.env` on top.
|
|
170
|
+
*/
|
|
171
|
+
export function migrationValues(config, values, hostUrls = []) {
|
|
172
|
+
const onHost = new Map([...values].map(([key, value]) => {
|
|
173
|
+
let rewritten = value;
|
|
174
|
+
for (const [from, to] of hostUrls)
|
|
175
|
+
rewritten = rewritten.replace(`@${from}`, `@${to}`).replace(`//${from}`, `//${to}`);
|
|
176
|
+
return [key, rewritten];
|
|
177
|
+
}));
|
|
178
|
+
const extra = config.migrate?.env?.(onHost) ?? {};
|
|
179
|
+
return new Map([...onHost, ...definedEntries(extra)]);
|
|
170
180
|
}
|
|
171
181
|
/**
|
|
172
182
|
* Whether the pre-migration dump runs, and why not when it does not. Unsaid,
|
|
@@ -196,6 +206,8 @@ async function prepareEnv(ctx, port) {
|
|
|
196
206
|
const document = await readEnv(ctx);
|
|
197
207
|
const infra = await planInfra(ctx, envValues(document));
|
|
198
208
|
const env = planEnv(ctx, document, port, infra.env);
|
|
209
|
+
ctx.hostUrls = infra.hostUrls ?? [];
|
|
210
|
+
ctx.values = env.values;
|
|
199
211
|
return { env, infra };
|
|
200
212
|
}
|
|
201
213
|
async function build(ctx, values, sha) {
|
|
@@ -253,7 +265,7 @@ async function validate(ctx, values) {
|
|
|
253
265
|
}
|
|
254
266
|
async function migrate(ctx, raw) {
|
|
255
267
|
const { host, pm } = ctx;
|
|
256
|
-
const values = migrationValues(ctx.config, raw);
|
|
268
|
+
const values = migrationValues(ctx.config, raw, ctx.hostUrls);
|
|
257
269
|
const env = { cwd: ctx.dir, stream: true, env: Object.fromEntries(values) };
|
|
258
270
|
const command = ctx.config.migrate?.command;
|
|
259
271
|
if (command) {
|
|
@@ -478,7 +490,7 @@ export async function run(ctx, options = {}) {
|
|
|
478
490
|
await step(ctx, 'validate', () => validateStep(ctx, values));
|
|
479
491
|
const backup = backupDecision(config, values, skip);
|
|
480
492
|
if (backup.run) {
|
|
481
|
-
record.backup = await step(ctx, 'backup', () => backupDatabase(ctx, migrationValues(config, values), infra, sha));
|
|
493
|
+
record.backup = await step(ctx, 'backup', () => backupDatabase(ctx, migrationValues(config, values, infra.hostUrls), infra, sha));
|
|
482
494
|
host.out.ok(record.backup);
|
|
483
495
|
}
|
|
484
496
|
else {
|
package/dist/services.d.ts
CHANGED
|
@@ -38,14 +38,16 @@ export declare function appRoleOf(config: DeployConfig): AppRole | undefined;
|
|
|
38
38
|
export declare function externalFindings(ctx: DeployContext): Promise<Finding[]>;
|
|
39
39
|
export declare function externalPostgres(ctx: DeployContext, values: Map<string, string>): PostgresHandle | undefined;
|
|
40
40
|
/**
|
|
41
|
-
* The app role's URL
|
|
42
|
-
*
|
|
41
|
+
* The app role's URL: the owner's, with the role's name and a new password,
|
|
42
|
+
* when the `.env` has none yet; then kept — the role follows its password.
|
|
43
|
+
* When the database moves (another host, port or name: a recreated
|
|
44
|
+
* container), the URL follows it and keeps the password.
|
|
43
45
|
*/
|
|
44
46
|
export declare function appRoleEnv(ctx: DeployContext, values: Map<string, string>, ownerUrl: string | undefined): EnvChange[];
|
|
45
47
|
/**
|
|
46
48
|
* The role exists, logs in with the `.env`'s password, and gets DML on what the
|
|
47
49
|
* owner creates in `public` (default privileges — never on existing tables: an
|
|
48
|
-
* app may keep some append-only, as
|
|
50
|
+
* app may keep some append-only, as Globex's audit log is).
|
|
49
51
|
*/
|
|
50
52
|
export declare function ensureAppRole(ctx: DeployContext, pg: PostgresHandle, role: AppRole, values: Map<string, string>): Promise<string>;
|
|
51
53
|
/**
|
package/dist/services.js
CHANGED
|
@@ -51,17 +51,31 @@ export function externalPostgres(ctx, values) {
|
|
|
51
51
|
};
|
|
52
52
|
}
|
|
53
53
|
/**
|
|
54
|
-
* The app role's URL
|
|
55
|
-
*
|
|
54
|
+
* The app role's URL: the owner's, with the role's name and a new password,
|
|
55
|
+
* when the `.env` has none yet; then kept — the role follows its password.
|
|
56
|
+
* When the database moves (another host, port or name: a recreated
|
|
57
|
+
* container), the URL follows it and keeps the password.
|
|
56
58
|
*/
|
|
57
59
|
export function appRoleEnv(ctx, values, ownerUrl) {
|
|
58
60
|
const role = appRoleOf(ctx.config);
|
|
59
|
-
if (!role ||
|
|
61
|
+
if (!role || !ownerUrl)
|
|
60
62
|
return [];
|
|
61
|
-
const
|
|
63
|
+
const owner = new URL(ownerUrl);
|
|
64
|
+
const current = values.get(role.urlKey);
|
|
65
|
+
if (!current) {
|
|
66
|
+
const url = new URL(ownerUrl);
|
|
67
|
+
url.username = role.name;
|
|
68
|
+
url.password = ctx.host.randomHex(24);
|
|
69
|
+
return [{ kind: 'set', key: role.urlKey, value: url.toString(), reason: `password of the ${role.name} role (new)` }];
|
|
70
|
+
}
|
|
71
|
+
const url = new URL(current);
|
|
72
|
+
if (url.host === owner.host && url.pathname === owner.pathname && url.search === owner.search && url.username === role.name)
|
|
73
|
+
return [];
|
|
74
|
+
url.host = owner.host;
|
|
75
|
+
url.pathname = owner.pathname;
|
|
76
|
+
url.search = owner.search;
|
|
62
77
|
url.username = role.name;
|
|
63
|
-
url.
|
|
64
|
-
return [{ kind: 'set', key: role.urlKey, value: url.toString(), reason: `password of the ${role.name} role (new)` }];
|
|
78
|
+
return [{ kind: 'set', key: role.urlKey, value: url.toString(), reason: `the ${role.name} role follows the database (${owner.host}${owner.pathname})` }];
|
|
65
79
|
}
|
|
66
80
|
const ident = (name) => `"${name.replace(/"/g, '""')}"`;
|
|
67
81
|
const literal = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
@@ -74,7 +88,7 @@ async function psql(ctx, pg, sql, as) {
|
|
|
74
88
|
/**
|
|
75
89
|
* The role exists, logs in with the `.env`'s password, and gets DML on what the
|
|
76
90
|
* owner creates in `public` (default privileges — never on existing tables: an
|
|
77
|
-
* app may keep some append-only, as
|
|
91
|
+
* app may keep some append-only, as Globex's audit log is).
|
|
78
92
|
*/
|
|
79
93
|
export async function ensureAppRole(ctx, pg, role, values) {
|
|
80
94
|
const raw = values.get(role.urlKey);
|