@basaltkit/deploy 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/pipeline.js CHANGED
@@ -1,14 +1,16 @@
1
1
  import { basename, dirname, join } from 'node:path';
2
2
  import { apacheInstall, apachePreflight, vhostPaths } from './apache.js';
3
+ import { caddyInstall, caddyPaths, caddyPreflight } from './caddy.js';
3
4
  import { backupDatabase, restoreCommand } from './backup.js';
4
5
  import { lockfileFindings, tlsFindings, toolingFindings } from './checks.js';
5
- import { composeBuild, composeEnv, composeHealthy, composeOf, composePreflight, composeRelease, composeStatus, pruneImages } from './compose.js';
6
- import { processName } from './config.js';
6
+ import { composeBuild, composeEnv, composeHealthy, composeOf, composePreflight, composeRelease, composeStatus, logFindings, pruneImages } from './compose.js';
7
+ import { definedEntries, processName } from './config.js';
7
8
  import { DeployError, errors, INSTALL_COMMAND, report, RUN_COMMAND } from './context.js';
8
9
  import { checkSchema, coercionFindings, policyFindings } from './env-check.js';
9
10
  import { answerQuestions, describeEnv, envFile, envMirrors, mirrorFindings, planEnv, readEnv, syntaxFindings, writeEnv } from './env-step.js';
10
11
  import { envValues } from './dotenv.js';
11
- import { applyInfra, describeInfra, planInfra } from './infra.js';
12
+ import { applyInfra, describeInfra, dockerPostgres, maintainServices, planInfra } from './infra.js';
13
+ import { appRoleOf, describeServices, dumpContainer, dumpUrlKey, externalOf, externalPostgres, grantTenantSchemas } from './services.js';
12
14
  import { pm2List, pm2Preflight, pm2Release, resolvePort } from './pm2.js';
13
15
  import { lastGood, migrationNames, readReleases, recordRelease } from './state.js';
14
16
  export const SKIPPABLE = ['fetch', 'backup', 'tls'];
@@ -78,10 +80,29 @@ export async function preflight(ctx, options = {}) {
78
80
  findings.push(...await mirrorFindings(ctx));
79
81
  if (ctx.config.proxy?.kind === 'apache')
80
82
  findings.push(...await apachePreflight(ctx, port));
83
+ if (ctx.config.proxy?.kind === 'caddy')
84
+ findings.push(...await caddyPreflight(ctx, port));
81
85
  if (!options.skip?.includes('tls'))
82
86
  findings.push(...await tlsFindings(ctx));
87
+ findings.push(...await backupFindings(ctx, values, options));
83
88
  return { findings, port, values };
84
89
  }
90
+ /** The dump's container running — found now, not after the build, minutes later. */
91
+ async function backupFindings(ctx, values, options) {
92
+ const container = ctx.config.backup?.container;
93
+ // An external infra.postgres is checked with the rest of the infra.
94
+ if (!container || !backupDecision(ctx.config, values, options.skip ?? []).run)
95
+ return [];
96
+ const running = await ctx.host.exec('docker', ['inspect', '--format', '{{.State.Running}}', container]);
97
+ if (running.stdout.trim() === 'true')
98
+ return [];
99
+ return [{
100
+ id: 'backup',
101
+ level: 'error',
102
+ message: running.code === 0 ? `backup.container ${container} is not running` : `backup.container ${container} does not exist (or docker is not available to this user)`,
103
+ fix: `docker start ${container}, or deploy with --skip=backup`,
104
+ }];
105
+ }
85
106
  const LOCKFILES = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock'];
86
107
  async function gitFindings(ctx, options) {
87
108
  const findings = [];
@@ -145,7 +166,7 @@ const migratesAnything = (config) => Boolean(config.migrate?.command) || migrate
145
166
  /** The `.env` as the migration and the dump see it: `migrate.env` on top (host URLs for container names). */
146
167
  export function migrationValues(config, values) {
147
168
  const extra = config.migrate?.env?.(values) ?? {};
148
- return new Map([...values, ...Object.entries(extra)]);
169
+ return new Map([...values, ...definedEntries(extra)]);
149
170
  }
150
171
  /**
151
172
  * Whether the pre-migration dump runs, and why not when it does not. Unsaid,
@@ -165,7 +186,9 @@ export function backupDecision(config, values, skip = []) {
165
186
  return { run: false, why: 'nothing to migrate' };
166
187
  if (config.infra?.kind === 'docker' && config.infra.postgres)
167
188
  return { run: true };
168
- const url = migrationValues(config, values).get(config.backup?.urlKey ?? 'DATABASE_URL') ?? '';
189
+ if (dumpContainer(config))
190
+ return { run: true };
191
+ const url = migrationValues(config, values).get(dumpUrlKey(config)) ?? '';
169
192
  return /^postgres(ql)?:\/\//.test(url) ? { run: true } : { run: false, why: 'no Postgres database in the .env' };
170
193
  }
171
194
  // ── the building blocks ────────────────────────────────────────────────────
@@ -193,6 +216,8 @@ async function build(ctx, values, sha) {
193
216
  await run(frozen, { unset: ['NODE_ENV'] });
194
217
  for (const config of ctx.config.build?.prisma ?? [])
195
218
  await run(['exec', 'prisma', 'generate', '--config', config], { env: values });
219
+ if (ctx.config.build?.script)
220
+ await run(['run', ctx.config.build.script], { env: values });
196
221
  if (ctx.config.build?.web)
197
222
  await run(['--dir', ctx.config.build.web, 'run', 'build'], { env: values });
198
223
  if (isCompose(ctx))
@@ -278,19 +303,46 @@ async function healthy(ctx, port) {
278
303
  } while (host.now().getTime() < deadline);
279
304
  return false;
280
305
  }
306
+ /** `verify.logs` and `verify.http` (RFC 0007 §6); throws what failed, which rolls the release back. */
307
+ async function verifyDeclared(ctx, sha, port, since) {
308
+ const verify = ctx.config.verify;
309
+ if (!verify)
310
+ return;
311
+ const problems = [];
312
+ if (verify.logs && Object.keys(verify.logs).length) {
313
+ if (!isCompose(ctx))
314
+ throw new DeployError('verify.logs reads compose service logs: it needs runtime: compose(…)');
315
+ const found = await logFindings(ctx, sha, since);
316
+ problems.push(...found);
317
+ if (found.length === 0)
318
+ ctx.host.out.ok(`logs of ${Object.keys(verify.logs).join(', ')}: clean since the release`);
319
+ }
320
+ for (const check of verify.http ?? []) {
321
+ const expect = check.expect ?? 200;
322
+ const answer = await ctx.host.httpGet(`http://127.0.0.1:${port}${check.path}`, { host: ctx.config.domain });
323
+ if ('status' in answer && answer.status === expect)
324
+ ctx.host.out.ok(`${check.path}: ${expect}`);
325
+ else
326
+ problems.push(`${check.path}: ${'status' in answer ? `HTTP ${answer.status}` : answer.error}, expected ${expect}`);
327
+ }
328
+ if (problems.length > 0)
329
+ throw new DeployError(`verify: ${problems.join('; ')}`);
330
+ }
281
331
  async function publicHealthy(ctx) {
282
332
  const { config } = ctx;
283
- if (config.health?.public === false || config.proxy?.kind !== 'apache')
333
+ if (config.health?.public === false || (config.proxy?.kind !== 'apache' && config.proxy?.kind !== 'caddy'))
284
334
  return undefined;
285
335
  const url = `https://${config.domain}${config.proxy.apiPrefix.replace(/\/$/, '')}${config.health?.path ?? '/health'}`;
286
336
  const answer = await ctx.host.httpGet(url, { timeoutMs: 10_000 });
287
- if ('status' in answer && answer.status >= 200 && answer.status < 400)
337
+ if ('status' in answer && answer.status >= 200 && answer.status < 400) {
338
+ ctx.host.out.ok(url);
288
339
  return undefined;
340
+ }
289
341
  return {
290
342
  id: 'health',
291
343
  level: 'error',
292
344
  message: `the app answers on 127.0.0.1 but not at ${url} (${'status' in answer ? `HTTP ${answer.status}` : answer.error}) — the proxy, DNS or TLS, not the code`,
293
- fix: 'the [C1]/[C2]/[vhost] findings above, then: apachectl -S',
345
+ fix: config.proxy.kind === 'caddy' ? 'the [C1]/[C2]/[C8] findings above, then: journalctl -u caddy -n 50' : 'the [C1]/[C2]/[vhost] findings above, then: apachectl -S',
294
346
  };
295
347
  }
296
348
  /** Puts the code on disk back to `sha` and rebuilds it. Does not restart anything. */
@@ -308,12 +360,27 @@ function reportEnv(ctx, plan) {
308
360
  for (const line of lines)
309
361
  ctx.host.out.info(line);
310
362
  }
311
- async function infraStep(ctx, infra) {
363
+ async function infraStep(ctx, infra, values) {
312
364
  stopOnErrors(ctx, await applyInfra(ctx, infra), 'infra');
313
- if (infra.services.length === 0)
314
- ctx.host.out.ok('nothing to start (external infra)');
365
+ const external = externalOf(ctx.config);
366
+ const adopted = [external?.postgres?.container, external?.redis?.container, external?.minio?.container].filter(Boolean);
367
+ if (infra.services.length > 0)
368
+ ctx.host.out.ok(`${infra.services.map((s) => s.container).join(', ')} healthy; credentials accepted`);
369
+ else if (adopted.length > 0)
370
+ ctx.host.out.ok(`${adopted.join(', ')} running (external)`);
315
371
  else
316
- ctx.host.out.ok(`${infra.services.map((s) => s.container).join(', ')} healthy; credentials accepted${ctx.config.infra?.kind === 'docker' && ctx.config.infra.minio?.buckets.length ? '; buckets in place' : ''}`);
372
+ ctx.host.out.ok('nothing to start (external infra)');
373
+ for (const line of await maintainServices(ctx, infra, values))
374
+ ctx.host.out.ok(line);
375
+ }
376
+ /** The app role on every company schema, after the companies' migrations (RFC 0007 §11.3). */
377
+ async function tenantGrants(ctx, infra, values) {
378
+ const role = appRoleOf(ctx.config);
379
+ if (!role || !ctx.config.migrate?.tenants)
380
+ return;
381
+ const pg = ctx.config.infra?.kind === 'docker' ? dockerPostgres(infra) : externalPostgres(ctx, values);
382
+ if (pg)
383
+ ctx.host.out.ok(await grantTenantSchemas(ctx, pg, role));
317
384
  }
318
385
  async function validateStep(ctx, values) {
319
386
  stopOnErrors(ctx, await validate(ctx, values), 'validate');
@@ -332,18 +399,25 @@ export async function plan(ctx, options = {}) {
332
399
  options.skip?.includes('fetch') ? 'fetch: skipped' : `fetch: git fetch ${config.remote ?? 'origin'} ${config.branch ?? 'main'} && git merge --ff-only`,
333
400
  ...describeEnv(env).map((l) => `env: ${l}`),
334
401
  ...describeInfra(infra).map((l) => `infra: ${l}`),
335
- `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)` : ''}`,
402
+ ...describeServices(config).map((l) => `infra: ${l}`),
403
+ `build: ${pm} install (frozen), ${(config.build?.prisma ?? []).map((c) => `prisma generate --config ${c}`).join(', ') || 'no prisma'}${config.build?.script ? `, ${pm} run ${config.build.script}` : ''}${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)` : ''}`,
336
404
  ...(config.hooks?.infra ?? []).map((h) => `infra hook: ${h.join(' ')}`),
337
405
  `validate: ${config.env.schema ?? '(no schema configured)'} against the new .env`,
338
406
  ((decision) => decision.run
339
- ? `backup: pg_dump → ${config.backup?.dir ?? 'backups/predeploy'} (keep ${config.backup?.keep ?? 10})`
407
+ ? `backup: pg_dump${dumpContainer(config) ? ` inside ${dumpContainer(config)}` : ''} → ${config.backup?.dir ?? 'backups/predeploy'} (keep ${config.backup?.keep ?? 10})`
340
408
  : `backup: skipped (${decision.why})`)(backupDecision(config, checked.values, options.skip ?? [])),
341
409
  `migrate: ${[config.migrate?.command?.join(' ') ?? '', migratesCentral(config) ? 'prisma migrate deploy' : '', config.migrate?.tenants ? 'tenant:migrate' : ''].filter(Boolean).join(' + ') || 'nothing configured'}`,
410
+ ...(isCompose(ctx) && composeOf(ctx).attach ? [`attach: ${Object.entries(composeOf(ctx).attach ?? {}).map(([c, n]) => `${c} → ${n.join(', ')}`).join('; ')}`] : []),
411
+ ...(isCompose(ctx) ? (composeOf(ctx).jobs ?? []).map((j) => `job: ${j.service}${j.command ? ` ${j.command.join(' ')}` : ''}${j.once ? ` (unless ${j.once.exists} exists)` : ''}`) : []),
342
412
  `release: ${describeRelease(ctx, checked.port)}`,
343
- `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'}` : ''}`,
413
+ `health: http://127.0.0.1:${checked.port}${config.health?.path ?? '/health'} (Host: ${config.domain})${(config.proxy?.kind === 'apache' || config.proxy?.kind === 'caddy') && config.health?.public !== false ? `, then https://${config.domain}${config.proxy.apiPrefix}${config.health?.path ?? '/health'}` : ''}`,
344
414
  ];
345
415
  for (const hook of config.hooks?.verify ?? [])
346
416
  lines.push(`verify hook: ${hook.join(' ')}`);
417
+ if (config.verify?.logs)
418
+ lines.push(`verify: no ${[...new Set(Object.values(config.verify.logs).flat())].join(' / ')} in the logs of ${Object.keys(config.verify.logs).join(', ')}`);
419
+ for (const check of config.verify?.http ?? [])
420
+ lines.push(`verify: ${check.path} answers ${check.expect ?? 200}`);
347
421
  for (const line of lines)
348
422
  host.out.info(line);
349
423
  return errors([...checked.findings, ...infra.findings]).length > 0 ? 1 : 0;
@@ -360,7 +434,7 @@ export async function envCommand(ctx) {
360
434
  throw new DeployError(`no answer for ${missing.join(', ')} (no terminal to ask): set them in the environment of this command`);
361
435
  reportEnv(ctx, env);
362
436
  await writeEnv(ctx, env);
363
- await step(ctx, 'infra', () => infraStep(ctx, infra));
437
+ await step(ctx, 'infra', () => infraStep(ctx, infra, env.values));
364
438
  await step(ctx, 'validate', () => validateStep(ctx, env.values));
365
439
  ctx.host.out.ok(isCompose(ctx) ? `${envFile(ctx)} ready` : `.env ready (PORT=${port})`);
366
440
  return 0;
@@ -399,7 +473,7 @@ export async function run(ctx, options = {}) {
399
473
  reportEnv(ctx, prepared.env);
400
474
  await writeEnv(ctx, prepared.env);
401
475
  values = prepared.env.values;
402
- await step(ctx, 'infra', async () => { await infraStep(ctx, infra); await runHooks(ctx, 'infra', values, sha); });
476
+ await step(ctx, 'infra', async () => { await infraStep(ctx, infra, values); await runHooks(ctx, 'infra', values, sha); });
403
477
  await step(ctx, 'build', async () => { await build(ctx, values, sha); await settleLockfile(ctx, lockfileSaid); });
404
478
  await step(ctx, 'validate', () => validateStep(ctx, values));
405
479
  const backup = backupDecision(config, values, skip);
@@ -411,7 +485,7 @@ export async function run(ctx, options = {}) {
411
485
  host.out.step('backup');
412
486
  host.out.info(`skipped: ${backup.why}`);
413
487
  }
414
- await step(ctx, 'migrate', async () => { await migrate(ctx, values); await settleLockfile(ctx, lockfileSaid); });
488
+ await step(ctx, 'migrate', async () => { await migrate(ctx, values); await tenantGrants(ctx, infra, values); await settleLockfile(ctx, lockfileSaid); });
415
489
  }
416
490
  catch (error) {
417
491
  if (sha !== previous)
@@ -427,7 +501,7 @@ export async function run(ctx, options = {}) {
427
501
  if (destructive.length > 0)
428
502
  host.out.error(`not rolled back automatically: ${destructive.join(', ')} ${destructive.length === 1 ? 'is' : 'are'} marked destructive`);
429
503
  if (record.backup)
430
- host.out.info(`database before this release: ${restoreCommand(ctx, infra, record.backup)}`);
504
+ host.out.info(`database before this release: ${restoreCommand(ctx, infra, record.backup, values)}`);
431
505
  record.note = why;
432
506
  await recordRelease(ctx, record);
433
507
  return 1;
@@ -438,6 +512,7 @@ export async function run(ctx, options = {}) {
438
512
  await recordRelease(ctx, record);
439
513
  return 1;
440
514
  };
515
+ const releasedAt = host.now();
441
516
  try {
442
517
  host.out.ok(await step(ctx, 'release', () => release(ctx, values, sha)));
443
518
  }
@@ -448,15 +523,20 @@ export async function run(ctx, options = {}) {
448
523
  if (!health.ok)
449
524
  return recover(health.why);
450
525
  host.out.ok(`http://127.0.0.1:${port}${config.health?.path ?? '/health'}`);
451
- if (config.hooks?.verify?.length) {
526
+ // Through the proxy, under the health step: a failure here is the proxy,
527
+ // DNS or TLS — reported at the end, never rolled back.
528
+ const publicProblem = await publicHealthy(ctx);
529
+ if (config.hooks?.verify?.length || config.verify) {
452
530
  try {
453
- await step(ctx, 'verify', () => runHooks(ctx, 'verify', values, sha));
531
+ await step(ctx, 'verify', async () => {
532
+ await runHooks(ctx, 'verify', values, sha);
533
+ await verifyDeclared(ctx, sha, port, releasedAt);
534
+ });
454
535
  }
455
536
  catch (error) {
456
537
  return recover(error.message);
457
538
  }
458
539
  }
459
- const publicProblem = await publicHealthy(ctx);
460
540
  record.status = publicProblem ? 'public-unreachable' : 'ok';
461
541
  // `pnpm run start`, launched by PM2 in the checkout, may rewrite it too.
462
542
  await settleLockfile(ctx, lockfileSaid);
@@ -619,6 +699,9 @@ export async function install(ctx, user) {
619
699
  if (config.proxy?.kind === 'apache' && config.proxy.managed !== false) {
620
700
  await step(ctx, `Apache vhost ${vhostPaths(ctx).file}`, () => apacheInstall(ctx, port, join(stateDir, 'install-backups')));
621
701
  }
702
+ if (config.proxy?.kind === 'caddy' && config.proxy.managed !== false) {
703
+ await step(ctx, `Caddy site ${caddyPaths(ctx).site}`, () => caddyInstall(ctx, port, join(stateDir, 'install-backups')));
704
+ }
622
705
  if (config.infra?.kind === 'docker') {
623
706
  const groups = (await host.exec('id', ['-nG', user])).stdout.split(/\s+/);
624
707
  if (groups.includes('docker')) {
@@ -0,0 +1,62 @@
1
+ import { type AppRole, type Bucket, type DeployConfig } from './config.js';
2
+ import { type DeployContext, type Finding } from './context.js';
3
+ import type { EnvChange } from './dotenv.js';
4
+ /**
5
+ * What every deploy keeps true of the app's services, dedicated or not
6
+ * (RFC 0007 §4): the external containers are running, the app's database role
7
+ * exists with the `.env`'s password and its grants, the buckets exist with
8
+ * their policies. Each is idempotent and says what it did.
9
+ *
10
+ * Credentials never reach a command line: `docker exec -e NAME` (no value)
11
+ * copies them from this process's environment, SQL with a password goes on
12
+ * stdin.
13
+ */
14
+ /** Where to reach Postgres as its owner, inside the container. */
15
+ export interface PostgresHandle {
16
+ container: string;
17
+ user: string;
18
+ database: string;
19
+ password: string;
20
+ /** Over TCP (proves the password) or the local socket (as the image allows). */
21
+ tcp: boolean;
22
+ /** The owner's URL, from which the app role's URL is derived. */
23
+ url: string | undefined;
24
+ }
25
+ export interface MinioHandle {
26
+ container: string;
27
+ user: string;
28
+ password: string;
29
+ }
30
+ export declare const externalOf: (config: DeployConfig) => import("./config.js").ExternalInfra<import("./config.js").EnvShape> | undefined;
31
+ /** The container the pre-migration dump runs in, with external infra: `backup.container`, else `infra.postgres.container`. */
32
+ export declare const dumpContainer: (config: DeployConfig) => string | undefined;
33
+ /** The `.env` key of the URL the dump connects with: `backup.urlKey`, else the external Postgres's owner URL. */
34
+ export declare const dumpUrlKey: (config: DeployConfig) => string;
35
+ /** The app role, wherever it is declared. */
36
+ export declare function appRoleOf(config: DeployConfig): AppRole | undefined;
37
+ /** The external containers, each running — before anything is built. */
38
+ export declare function externalFindings(ctx: DeployContext): Promise<Finding[]>;
39
+ export declare function externalPostgres(ctx: DeployContext, values: Map<string, string>): PostgresHandle | undefined;
40
+ /**
41
+ * The app role's URL, when the `.env` has none yet: the owner's, with the
42
+ * role's name and a new password. Kept from then on — the role follows it.
43
+ */
44
+ export declare function appRoleEnv(ctx: DeployContext, values: Map<string, string>, ownerUrl: string | undefined): EnvChange[];
45
+ /**
46
+ * The role exists, logs in with the `.env`'s password, and gets DML on what the
47
+ * owner creates in `public` (default privileges — never on existing tables: an
48
+ * app may keep some append-only, as Mukanda's audit log is).
49
+ */
50
+ export declare function ensureAppRole(ctx: DeployContext, pg: PostgresHandle, role: AppRole, values: Map<string, string>): Promise<string>;
51
+ /**
52
+ * After the companies' migrations (RFC 0007 §11.3): every `tenant_*` schema
53
+ * gets the role's DML on what it has and what its owner creates later. A new
54
+ * company without them is an outage the role only finds at runtime.
55
+ */
56
+ export declare function grantTenantSchemas(ctx: DeployContext, pg: PostgresHandle, role: AppRole): Promise<string>;
57
+ /** Credentials of a running MinIO: its own, never the config's. */
58
+ export declare function minioHandle(ctx: DeployContext, container: string): Promise<MinioHandle>;
59
+ /** Each bucket exists; versioning on where asked; the expiry rule added once. */
60
+ export declare function ensureBuckets(ctx: DeployContext, minio: MinioHandle, buckets: Bucket[]): Promise<string>;
61
+ /** What `plan` says about the services: the external containers, the role, the buckets. */
62
+ export declare function describeServices(config: DeployConfig): string[];
@@ -0,0 +1,195 @@
1
+ import { bucketName } from './config.js';
2
+ import { DeployError } from './context.js';
3
+ export const externalOf = (config) => (config.infra?.kind === 'external' ? config.infra : undefined);
4
+ /** The container the pre-migration dump runs in, with external infra: `backup.container`, else `infra.postgres.container`. */
5
+ export const dumpContainer = (config) => config.backup?.container ?? externalOf(config)?.postgres?.container;
6
+ /** The `.env` key of the URL the dump connects with: `backup.urlKey`, else the external Postgres's owner URL. */
7
+ export const dumpUrlKey = (config) => config.backup?.urlKey ?? externalOf(config)?.postgres?.urlKey ?? 'DATABASE_URL';
8
+ /** The app role, wherever it is declared. */
9
+ export function appRoleOf(config) {
10
+ if (config.infra?.kind === 'docker')
11
+ return config.infra.postgres?.appRole;
12
+ return externalOf(config)?.postgres?.appRole;
13
+ }
14
+ /** The external containers, each running — before anything is built. */
15
+ export async function externalFindings(ctx) {
16
+ const services = externalOf(ctx.config);
17
+ if (!services)
18
+ return [];
19
+ const findings = [];
20
+ for (const [service, container] of [['postgres', services.postgres?.container], ['redis', services.redis?.container], ['minio', services.minio?.container]]) {
21
+ if (!container)
22
+ continue;
23
+ const state = await ctx.host.exec('docker', ['inspect', '--format', '{{.State.Running}}', container]);
24
+ if (state.stdout.trim() === 'true')
25
+ continue;
26
+ findings.push({
27
+ id: 'infra',
28
+ level: 'error',
29
+ message: state.code === 0 ? `${service}: ${container} is not running` : `${service}: ${container} does not exist (or docker is not available to this user)`,
30
+ fix: state.code === 0 ? `docker start ${container}` : 'a new server is prepared with basalt-deploy bootstrap; adopt a container under another name with infra.<service>.container',
31
+ });
32
+ }
33
+ return findings;
34
+ }
35
+ export function externalPostgres(ctx, values) {
36
+ const pg = externalOf(ctx.config)?.postgres;
37
+ if (!pg)
38
+ return undefined;
39
+ const key = pg.urlKey ?? 'DATABASE_URL';
40
+ const raw = values.get(key);
41
+ if (!raw)
42
+ throw new DeployError(`infra.postgres: ${key} is not set in the .env — it holds the owner's URL`);
43
+ const url = new URL(raw);
44
+ return {
45
+ container: pg.container,
46
+ user: decodeURIComponent(url.username),
47
+ database: decodeURIComponent(url.pathname.replace(/^\//, '')),
48
+ password: decodeURIComponent(url.password),
49
+ tcp: false,
50
+ url: raw,
51
+ };
52
+ }
53
+ /**
54
+ * The app role's URL, when the `.env` has none yet: the owner's, with the
55
+ * role's name and a new password. Kept from then on — the role follows it.
56
+ */
57
+ export function appRoleEnv(ctx, values, ownerUrl) {
58
+ const role = appRoleOf(ctx.config);
59
+ if (!role || values.get(role.urlKey) || !ownerUrl)
60
+ return [];
61
+ const url = new URL(ownerUrl);
62
+ url.username = role.name;
63
+ url.password = ctx.host.randomHex(24);
64
+ return [{ kind: 'set', key: role.urlKey, value: url.toString(), reason: `password of the ${role.name} role (new)` }];
65
+ }
66
+ const ident = (name) => `"${name.replace(/"/g, '""')}"`;
67
+ const literal = (value) => `'${value.replace(/'/g, "''")}'`;
68
+ async function psql(ctx, pg, sql, as) {
69
+ const user = as?.user ?? pg.user;
70
+ const password = as?.password ?? pg.password;
71
+ const args = ['exec', '-i', '-e', 'PGPASSWORD', pg.container, 'psql', '-v', 'ON_ERROR_STOP=1', '-qtA', ...(pg.tcp || as ? ['-h', '127.0.0.1'] : []), '-U', user, '-d', pg.database];
72
+ return ctx.host.exec('docker', args, { env: { PGPASSWORD: password }, stdin: sql });
73
+ }
74
+ /**
75
+ * The role exists, logs in with the `.env`'s password, and gets DML on what the
76
+ * owner creates in `public` (default privileges — never on existing tables: an
77
+ * app may keep some append-only, as Mukanda's audit log is).
78
+ */
79
+ export async function ensureAppRole(ctx, pg, role, values) {
80
+ const raw = values.get(role.urlKey);
81
+ if (!raw)
82
+ throw new DeployError(`appRole ${role.name}: ${role.urlKey} is not set in the .env`);
83
+ const password = decodeURIComponent(new URL(raw).password);
84
+ const exists = (await psql(ctx, pg, `SELECT 1 FROM pg_roles WHERE rolname = ${literal(role.name)};\n`)).stdout.trim() === '1';
85
+ // Proven over TCP before anything is changed: an ALTER ROLE … PASSWORD on
86
+ // every deploy would write the password to any statement log.
87
+ const works = exists && (await psql(ctx, pg, 'SELECT 1;\n', { user: role.name, password })).code === 0;
88
+ const sql = [
89
+ ...(exists ? [] : [`CREATE ROLE ${ident(role.name)} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;`]),
90
+ ...(works ? [] : [`ALTER ROLE ${ident(role.name)} WITH LOGIN PASSWORD ${literal(password)};`]),
91
+ `GRANT CONNECT ON DATABASE ${ident(pg.database)} TO ${ident(role.name)};`,
92
+ `GRANT USAGE ON SCHEMA public TO ${ident(role.name)};`,
93
+ `ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(pg.user)} IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO ${ident(role.name)};`,
94
+ `ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(pg.user)} IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO ${ident(role.name)};`,
95
+ ].join('\n');
96
+ const result = await psql(ctx, pg, `${sql}\n`);
97
+ if (result.code !== 0)
98
+ throw new DeployError(`appRole ${role.name}: ${result.stderr.trim().split('\n')[0] ?? 'psql failed'}`);
99
+ return `role ${role.name}: ${exists ? (works ? 'in place' : 'password set from the .env') : 'created'}; grants in place`;
100
+ }
101
+ /**
102
+ * After the companies' migrations (RFC 0007 §11.3): every `tenant_*` schema
103
+ * gets the role's DML on what it has and what its owner creates later. A new
104
+ * company without them is an outage the role only finds at runtime.
105
+ */
106
+ export async function grantTenantSchemas(ctx, pg, role) {
107
+ const r = ident(role.name);
108
+ const owner = ident(pg.user);
109
+ const sql = `DO $basalt$
110
+ DECLARE s text; n int := 0;
111
+ BEGIN
112
+ FOR s IN SELECT nspname FROM pg_namespace WHERE nspname LIKE 'tenant\\_%' LOOP
113
+ EXECUTE format('GRANT USAGE ON SCHEMA %I TO ${r.replace(/%/g, '%%')}', s);
114
+ EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA %I TO ${r.replace(/%/g, '%%')}', s);
115
+ EXECUTE format('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA %I TO ${r.replace(/%/g, '%%')}', s);
116
+ EXECUTE format('ALTER DEFAULT PRIVILEGES FOR ROLE ${owner.replace(/%/g, '%%')} IN SCHEMA %I GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO ${r.replace(/%/g, '%%')}', s);
117
+ n := n + 1;
118
+ END LOOP;
119
+ RAISE NOTICE 'basalt: % schema(s)', n;
120
+ END
121
+ $basalt$;
122
+ SELECT count(*) FROM pg_namespace WHERE nspname LIKE 'tenant\\_%';
123
+ `;
124
+ const result = await psql(ctx, pg, sql);
125
+ if (result.code !== 0)
126
+ throw new DeployError(`appRole ${role.name} on the company schemas: ${result.stderr.trim().split('\n').pop() ?? 'psql failed'}`);
127
+ return `role ${role.name}: granted on ${result.stdout.trim().split('\n').pop() ?? '0'} company schema(s)`;
128
+ }
129
+ /** Credentials of a running MinIO: its own, never the config's. */
130
+ export async function minioHandle(ctx, container) {
131
+ const result = await ctx.host.exec('docker', ['inspect', container, '--format', '{{json .Config.Env}}']);
132
+ if (result.code !== 0)
133
+ throw new DeployError(`minio: cannot inspect ${container}`);
134
+ const env = new Map(JSON.parse(result.stdout.trim() || '[]').map((e) => [e.slice(0, e.indexOf('=')), e.slice(e.indexOf('=') + 1)]));
135
+ const user = env.get('MINIO_ROOT_USER');
136
+ const password = env.get('MINIO_ROOT_PASSWORD');
137
+ if (!user || !password)
138
+ throw new DeployError(`minio: ${container} has no MINIO_ROOT_USER/MINIO_ROOT_PASSWORD`);
139
+ return { container, user, password };
140
+ }
141
+ /** Each bucket exists; versioning on where asked; the expiry rule added once. */
142
+ export async function ensureBuckets(ctx, minio, buckets) {
143
+ if (buckets.length === 0)
144
+ return '';
145
+ const alias = `http://${encodeURIComponent(minio.user)}:${encodeURIComponent(minio.password)}@127.0.0.1:9000`;
146
+ const mc = (args) => ctx.host.exec('docker', ['exec', '-e', 'MC_HOST_local', minio.container, 'mc', ...args], { env: { MC_HOST_local: alias } });
147
+ const fail = (what, result) => new DeployError(`minio: ${what}: ${result.stderr.trim().split('\n')[0] ?? 'mc failed'}`);
148
+ const made = await mc(['mb', '-p', ...buckets.map((b) => `local/${bucketName(b)}`)]);
149
+ if (made.code !== 0)
150
+ throw fail('creating the buckets', made);
151
+ const said = [];
152
+ for (const bucket of buckets) {
153
+ if (typeof bucket === 'string') {
154
+ said.push(bucket);
155
+ continue;
156
+ }
157
+ const notes = [];
158
+ if (bucket.versioned) {
159
+ const versioned = await mc(['version', 'enable', `local/${bucket.name}`]);
160
+ if (versioned.code !== 0)
161
+ throw fail(`versioning ${bucket.name}`, versioned);
162
+ notes.push('versioned');
163
+ }
164
+ if (bucket.expireDays !== undefined) {
165
+ // `mc ilm rule add` adds ANOTHER rule every time: read the rules first.
166
+ const rules = await mc(['ilm', 'rule', 'ls', '--json', `local/${bucket.name}`]);
167
+ const present = new RegExp(`"Expiration":\\s*\\{[^}]*"Days":\\s*${bucket.expireDays}\\b`).test(rules.stdout);
168
+ if (!present) {
169
+ const added = await mc(['ilm', 'rule', 'add', '--expire-days', String(bucket.expireDays), `local/${bucket.name}`]);
170
+ if (added.code !== 0)
171
+ throw fail(`expiry on ${bucket.name}`, added);
172
+ }
173
+ notes.push(`${bucket.expireDays}-day expiry${present ? '' : ' (added)'}`);
174
+ }
175
+ said.push(notes.length ? `${bucket.name} (${notes.join(', ')})` : bucket.name);
176
+ }
177
+ return `buckets: ${said.join(', ')}`;
178
+ }
179
+ /** What `plan` says about the services: the external containers, the role, the buckets. */
180
+ export function describeServices(config) {
181
+ const lines = [];
182
+ const external = externalOf(config);
183
+ for (const [service, container] of [['postgres', external?.postgres?.container], ['redis', external?.redis?.container], ['minio', external?.minio?.container]]) {
184
+ if (container)
185
+ lines.push(`${service}: ${container} (external, kept running by its owner)`);
186
+ }
187
+ const role = appRoleOf(config);
188
+ if (role)
189
+ lines.push(`role ${role.name}: created if missing, password from ${role.urlKey}, DML grants${config.migrate?.tenants ? ' (company schemas too, after the migration)' : ''}`);
190
+ const buckets = [...(external?.minio?.buckets ?? []), ...(config.infra?.kind === 'docker' ? config.infra.minio?.buckets ?? [] : [])];
191
+ const policies = buckets.filter((b) => typeof b === 'object' && (b.versioned || b.expireDays));
192
+ if (policies.length)
193
+ lines.push(`buckets: ${policies.map((b) => typeof b === 'object' ? `${b.name} (${[b.versioned ? 'versioned' : '', b.expireDays ? `${b.expireDays}-day expiry` : ''].filter(Boolean).join(', ')})` : b).join(', ')}`);
194
+ return lines;
195
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/deploy",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },