@basaltkit/deploy 0.8.0 → 0.10.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 CHANGED
@@ -59,11 +59,18 @@ export default defineDeploy({
59
59
  }),
60
60
  build: { prisma: ['prisma.config.ts', 'prisma/tenants/prisma.config.ts'], web: 'web' },
61
61
  migrate: { central: true, tenants: true },
62
- runtime: pm2({ avoid: [3000, 3001] }), // runs the package.json "start" script
62
+ runtime: pm2({ avoid: [3000, 3001] }), // runs the package.json "start" script, with the .env loaded
63
63
  proxy: apache(), // web/dist at /, /api/ → the app
64
64
  })
65
65
  ```
66
66
 
67
+ `pm2()` gives the app its `env.file` without handing the values to pm2: the
68
+ process gets the file's path and a preload that loads it inside the app's own
69
+ processes only, so neither the pm2 daemon nor `pm2 save`'s dump ever holds a
70
+ secret. An exported `NODE_ENV`/`PORT`/`HOST` still wins over the file.
71
+ `pm2({ loadEnv: false })` turns it off for an app that loads its environment
72
+ itself.
73
+
67
74
  What is true of one server only (a port taken there, another branch) goes in
68
75
  `/etc/basalt/<app>.json`: `{ "port": 3002, "infra": { "postgres": { "port": 5434 } } }`.
69
76
 
@@ -208,7 +215,7 @@ As the app user, in the checkout (`node node_modules/@basaltkit/deploy/dist/bin.
208
215
  | `run` | preflight → fetch → env → infra → build → validate → backup → migrate → release → health → record |
209
216
  | `env` | the `.env` and the containers only |
210
217
  | `rollback [--to=<sha>]` | the last healthy release. Code only — the database keeps its migrations. Holds the commit it left. |
211
- | `status` | the last releases (who, from where), the process, the deploy lock, a hold |
218
+ | `status` | where the code comes from (remote, branch, address without credentials), the last releases (who, from where), the process, the deploy lock, a hold |
212
219
  | `commits --from=<sha> --to=<sha>` | the commits between two releases. Read-only: no lock, no fetch. |
213
220
  | `commits --rollback [--to=<sha>]` | what `rollback` would take out of production, to the commit it would choose |
214
221
  | `install-plan [--out=<file>\|-]` | what `install` needs, as JSON (default `<state dir>/install-plan.json`, 0600), and the root command to run |
@@ -368,7 +375,7 @@ node node_modules/@basaltkit/deploy/dist/bin.js cancel 20261013T100000Z-5f2c9a1b
368
375
  first signal: when the run was already cancelled once, from any client, it
369
376
  is refused (`already-cancelled`) and nothing is signalled. A client that
370
377
  asked for the mild cancel never sends the immediate one by surprise.
371
- - `status --json` reports the lock, the active run and the last run.
378
+ - `status --json` reports the lock, the active run and the last run, and (0.9.0) `source`: the config's remote and branch, and the remote's address as `host/path`, never with credentials, a query or a local path.
372
379
  - `--via=ui` records `via: "ui"` with the release; like `--actor`, it
373
380
  attributes, it does not authenticate.
374
381
 
package/dist/commits.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { DeployContext } from './context.js';
2
- import { type CommitInfo, type Commits } from './protocol.js';
2
+ import { type CommitInfo, type Commits, type Source } from './protocol.js';
3
3
  export declare const MAX_SUBJECT = 200;
4
4
  export declare const MAX_AUTHOR = 100;
5
5
  /** Per git call: a list of 50 capped commits is far below this; a huge one is cut, never read. */
@@ -37,3 +37,16 @@ export declare function incomingCommits(ctx: DeployContext, target: {
37
37
  remote: string;
38
38
  head: string;
39
39
  }, skipFetch: boolean): Promise<Commits>;
40
+ /**
41
+ * A remote's address as a person reads it: `host[:port]/path`, without the
42
+ * scheme, any `user:token@`, a query, a fragment or `.git`. scp-like
43
+ * addresses (`git@host:org/repo.git`) too. A local path, `file://`, or
44
+ * anything outside a plain host-and-path grammar gives undefined: the
45
+ * address never carries a secret or a path of the server to the page.
46
+ */
47
+ export declare function describeRemoteUrl(raw: string): string | undefined;
48
+ /** The config's remote and branch, and where that remote points; never throws. */
49
+ export declare function remoteSource(ctx: DeployContext, target: {
50
+ remote: string;
51
+ branch: string;
52
+ }): Promise<Source>;
package/dist/commits.js CHANGED
@@ -186,3 +186,44 @@ export async function incomingCommits(ctx, target, skipFetch) {
186
186
  await git(ctx, ['update-ref', '-d', PREVIEW_REF]);
187
187
  }
188
188
  }
189
+ const HOST_PATH = /^[A-Za-z0-9](?:[A-Za-z0-9.-]{0,252})(?::\d{1,5})?\/[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+){0,15}$/;
190
+ /**
191
+ * A remote's address as a person reads it: `host[:port]/path`, without the
192
+ * scheme, any `user:token@`, a query, a fragment or `.git`. scp-like
193
+ * addresses (`git@host:org/repo.git`) too. A local path, `file://`, or
194
+ * anything outside a plain host-and-path grammar gives undefined: the
195
+ * address never carries a secret or a path of the server to the page.
196
+ */
197
+ export function describeRemoteUrl(raw) {
198
+ const text = raw.trim();
199
+ let host;
200
+ let path;
201
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) {
202
+ let url;
203
+ try {
204
+ url = new URL(text);
205
+ }
206
+ catch {
207
+ return undefined;
208
+ }
209
+ if (!['https:', 'http:', 'ssh:', 'git:'].includes(url.protocol) || url.hostname === '')
210
+ return undefined;
211
+ host = url.port ? `${url.hostname}:${url.port}` : url.hostname;
212
+ path = url.pathname;
213
+ }
214
+ else {
215
+ const scp = /^(?:[^@/\s]+@)?([A-Za-z0-9][A-Za-z0-9.-]*):(?!\/)([^\s]+)$/.exec(text);
216
+ if (!scp)
217
+ return undefined;
218
+ host = scp[1];
219
+ path = scp[2];
220
+ }
221
+ const clean = `${host}/${path.replace(/^\/+/, '').replace(/\/+$/, '').replace(/\.git$/, '')}`;
222
+ return clean.length <= 200 && HOST_PATH.test(clean) ? clean : undefined;
223
+ }
224
+ /** The config's remote and branch, and where that remote points; never throws. */
225
+ export async function remoteSource(ctx, target) {
226
+ const answer = await git(ctx, ['remote', 'get-url', target.remote]);
227
+ const url = answer.ok && answer.code === 0 ? describeRemoteUrl(answer.stdout) : undefined;
228
+ return { remote: target.remote, branch: target.branch, ...(url ? { url } : {}) };
229
+ }
package/dist/config.d.ts CHANGED
@@ -446,6 +446,13 @@ export interface Pm2Runtime {
446
446
  port: number | 'auto';
447
447
  /** Ports never picked by `auto` (e.g. a port the proxy itself listens on). */
448
448
  avoid: number[];
449
+ /**
450
+ * Give the app its `env.file`: the process gets the file's path and a preload
451
+ * that loads it inside the app's own processes only, so the values never reach
452
+ * pm2's environment or `pm2 save`'s dump. Default true; `false` for an app that
453
+ * loads its environment itself (and then gets only NODE_ENV, PORT and HOST).
454
+ */
455
+ loadEnv?: boolean;
449
456
  }
450
457
  export type ProxyConfig = ApacheProxy | CaddyProxy | NoProxy;
451
458
  /**
@@ -549,6 +556,7 @@ export declare const pm2: (options?: {
549
556
  script?: string;
550
557
  port?: number | 'auto';
551
558
  avoid?: number[];
559
+ loadEnv?: boolean;
552
560
  }) => Pm2Runtime;
553
561
  export declare const caddy: (options?: {
554
562
  webRoot?: string;
package/dist/config.js CHANGED
@@ -40,6 +40,7 @@ export const pm2 = (options = {}) => ({
40
40
  script: options.script ?? 'start',
41
41
  port: options.port ?? 'auto',
42
42
  avoid: options.avoid ?? [],
43
+ ...(options.loadEnv === undefined ? {} : { loadEnv: options.loadEnv }),
43
44
  });
44
45
  export const caddy = (options = {}) => ({
45
46
  kind: 'caddy',
@@ -167,6 +168,9 @@ export function validateConfig(typed) {
167
168
  problems.push(`runtime.name "${name}" must start with "${config.app}-" — the deploy only touches what the app owns`);
168
169
  if (!/^[a-z0-9-]+$/.test(name))
169
170
  problems.push(`runtime.name "${name}" may only use a-z, 0-9 and -`);
171
+ const loadEnv = config.runtime.loadEnv;
172
+ if (loadEnv !== undefined && typeof loadEnv !== 'boolean')
173
+ problems.push('runtime.loadEnv must be true or false');
170
174
  }
171
175
  else {
172
176
  const rt = config.runtime;
package/dist/index.d.ts CHANGED
@@ -13,4 +13,4 @@ export { DeployLockedError, type LockHolder } from './lock.js';
13
13
  export { EXIT_ABORTED, EXIT_LOCKED } from './cli.js';
14
14
  export type { Hold, Release } from './state.js';
15
15
  export type { Audit } from './audit.js';
16
- export { parseEvent, parseAnswerLine, PROTOCOL_VERSION, STEP_IDS, ERROR_CODES, EVENT_TYPES, RUN_ID, type DeployEvent, type EventBody, type EventType, type Envelope, type HelloEvent, type StepStartEvent, type StepEndEvent, type LogEvent, type FindingEvent, type PromptEvent, type PromptDescriptor, type ResultEvent, type ErrorEvent, type DoneEvent, type AttachedEvent, type StepId, type StepStatus, type ErrorCode, type AnswerLine, type StatusResult, type CheckResult, type PlanResult, type RunResult, type RollbackResult, type EnvResult, type DetachResult, type CancelResult, type InstallPlanResult, } from './protocol.js';
16
+ export { parseEvent, parseAnswerLine, PROTOCOL_VERSION, STEP_IDS, ERROR_CODES, EVENT_TYPES, RUN_ID, type DeployEvent, type EventBody, type EventType, type Envelope, type HelloEvent, type StepStartEvent, type StepEndEvent, type LogEvent, type FindingEvent, type PromptEvent, type PromptDescriptor, type ResultEvent, type ErrorEvent, type DoneEvent, type AttachedEvent, type StepId, type StepStatus, type ErrorCode, type AnswerLine, type Source, type StatusResult, type CheckResult, type PlanResult, type RunResult, type RollbackResult, type EnvResult, type DetachResult, type CancelResult, type InstallPlanResult, } from './protocol.js';
package/dist/pipeline.js CHANGED
@@ -13,7 +13,7 @@ import { applyInfra, describeInfra, dockerPostgres, maintainServices, planInfra
13
13
  import { appRoleOf, describeServices, dumpContainer, dumpUrlKey, externalOf, externalPostgres, grantTenantSchemas } from './services.js';
14
14
  import { pm2List, pm2Preflight, pm2Release, resolvePort } from './pm2.js';
15
15
  import { clearHold, migrationNames, readHold, readReleases, recordRelease, rollbackTarget, writeHold } from './state.js';
16
- import { commitRange, commitSubjects, incomingCommits, resolveCommit } from './commits.js';
16
+ import { commitRange, commitSubjects, incomingCommits, remoteSource, resolveCommit } from './commits.js';
17
17
  import { acquireLock, describeHolder, readLock } from './lock.js';
18
18
  import { auditOf } from './audit.js';
19
19
  import { questionDescriptors } from './env-step.js';
@@ -887,6 +887,8 @@ export async function status(ctx) {
887
887
  const { host } = ctx;
888
888
  const releases = (await readReleases(ctx)).slice(-10).reverse();
889
889
  host.out.step(`${ctx.config.app} — last ${releases.length} release(s)`);
890
+ const source = await remoteSource(ctx, gitTarget(ctx));
891
+ host.out.info(`source: ${source.remote}/${source.branch}${source.url ? ` (${source.url})` : ''}`);
890
892
  const lock = await readLock(host, ctx.stateDir);
891
893
  if (!lock)
892
894
  host.out.info('no deploy running');
@@ -930,6 +932,7 @@ export async function status(ctx) {
930
932
  hold: hold ?? null,
931
933
  releases,
932
934
  process: running,
935
+ source,
933
936
  ...await subjectsOf(ctx, releases),
934
937
  });
935
938
  }
package/dist/pm2.d.ts CHANGED
@@ -12,13 +12,16 @@ export declare function pm2List(ctx: DeployContext): Promise<Pm2Process[] | unde
12
12
  /** The port the app listens on: the compose upstream's, or PM2's (`auto` picks a free one). */
13
13
  export declare function resolvePort(ctx: DeployContext, values: Map<string, string>): Promise<number>;
14
14
  export declare function pm2Preflight(ctx: DeployContext, port: number): Promise<Finding[]>;
15
+ /** `NODE_OPTIONS` splits on spaces: the program travels percent-encoded, as a data: URL. */
16
+ export declare const ENV_PRELOAD: string;
15
17
  /**
16
18
  * What the process is started with: a minimal environment, never the
17
19
  * operator's shell (a stray variable there would override the `.env` — dotenv
18
20
  * and `--env-file` never overwrite) and never the `.env`'s secrets (`pm2 save`
19
- * writes the process environment to `~/.pm2/dump.pm2`). The app reads its own
20
- * `.env`, as it does in development; only what PM2 itself must know is passed.
21
+ * writes the process environment to `~/.pm2/dump.pm2`). The values reach the
22
+ * app through {@link ENV_PRELOAD}: pm2 only ever holds the file's path. With
23
+ * `loadEnv: false` the app reads its environment itself.
21
24
  */
22
- export declare function processEnv(host: DeployContext['host'], env: Map<string, string>): Record<string, string>;
25
+ export declare function processEnv(ctx: DeployContext, env: Map<string, string>): Record<string, string>;
23
26
  /** Starts, restarts or re-creates the process; says which. */
24
27
  export declare function pm2Release(ctx: DeployContext, env: Map<string, string>): Promise<string>;
package/dist/pm2.js CHANGED
@@ -1,5 +1,7 @@
1
+ import { join } from 'node:path';
1
2
  import { processName } from './config.js';
2
3
  import { DeployError } from './context.js';
4
+ import { envFile } from './env-step.js';
3
5
  import { freePort, listeners } from './ports.js';
4
6
  export async function pm2List(ctx) {
5
7
  const result = await ctx.host.exec('pm2', ['jlist']);
@@ -35,6 +37,33 @@ export async function resolvePort(ctx, values) {
35
37
  return current;
36
38
  return freePort(ctx.host, PORT_FROM, runtime.avoid);
37
39
  }
40
+ /** `--env-file`, dotenv or `process.loadEnvFile` in the script: the app loads its environment itself. */
41
+ const LOADS_ENV = /--env-file|dotenv|loadEnvFile/;
42
+ /**
43
+ * With `loadEnv: false` the process gets NODE_ENV, PORT and HOST only, so the
44
+ * app must read its environment itself. A script that shows no loader is
45
+ * flagged — a warning, since the loader may live in the code.
46
+ */
47
+ async function ownEnvFindings(ctx) {
48
+ const runtime = pm2Of(ctx);
49
+ if (runtime.loadEnv !== false)
50
+ return [];
51
+ let scripts = {};
52
+ try {
53
+ scripts = JSON.parse((await ctx.host.readFile(join(ctx.dir, 'package.json'))) ?? '{}').scripts ?? {};
54
+ }
55
+ catch {
56
+ return []; // C9 reports an unreadable package.json
57
+ }
58
+ const command = scripts[runtime.script];
59
+ if (command === undefined || LOADS_ENV.test(command))
60
+ return [];
61
+ return [{
62
+ id: 'env', level: 'warning',
63
+ message: `pm2({ loadEnv: false }): the "${runtime.script}" script (${command}) shows no .env loader, and pm2 starts the app with NODE_ENV, PORT and HOST only`,
64
+ fix: `drop loadEnv: false (the runtime then gives the app ${ctx.config.env.file ?? '.env'}), or load it in the script: node --env-file-if-exists=.env …`,
65
+ }];
66
+ }
38
67
  export async function pm2Preflight(ctx, port) {
39
68
  const findings = [];
40
69
  const name = processName(ctx.config);
@@ -43,6 +72,7 @@ export async function pm2Preflight(ctx, port) {
43
72
  return [{ id: 'C9', level: 'error', message: 'pm2 is not available to this user', fix: 'npm i -g pm2 (as the app user), then pm2 startup' }];
44
73
  }
45
74
  const ours = processes.find((p) => p.name === name);
75
+ findings.push(...await ownEnvFindings(ctx));
46
76
  // C3 — `pm2 restart` reuses the directory the process was started in. One
47
77
  // started from an old clone kept running old code after every deploy.
48
78
  if (ours && ours.cwd !== ctx.dir) {
@@ -70,21 +100,51 @@ export async function pm2Preflight(ctx, port) {
70
100
  }
71
101
  return findings;
72
102
  }
103
+ /**
104
+ * The preload that gives the app its `env.file` (`pm2({ loadEnv })`, default on).
105
+ *
106
+ * pm2 records the environment it is given — in the daemon and, on `pm2 save`,
107
+ * in `~/.pm2/dump.pm2` — so the values must never be in it. Only the file's
108
+ * path is (`BASALT_ENV_FILE`), with this program in `NODE_OPTIONS`. Node runs
109
+ * it before the app's first module, in every node process of the tree: it
110
+ * acts only where pm2 set `pm_id`, which pm2 sets in the processes it manages
111
+ * and not in its own CLI or daemon. There `process.loadEnvFile` fills in what
112
+ * is not exported yet — NODE_ENV, PORT and HOST above still win, as with
113
+ * `--env-file`. A file that cannot be read stops the app with one line, never
114
+ * a boot without its secrets. (`--env-file` itself is not allowed in
115
+ * NODE_OPTIONS, so a preload it is.)
116
+ */
117
+ const PRELOAD_SOURCE = [
118
+ 'const file=process.env.BASALT_ENV_FILE;',
119
+ 'if(file&&process.env.pm_id!==undefined){',
120
+ 'try{process.loadEnvFile(file)}',
121
+ 'catch(error){process.stderr.write(`[basalt-deploy] env.file ${file} is not readable (${error?.code??error?.message})\\n`);process.exit(1)}',
122
+ '}',
123
+ ].join('');
124
+ /** `NODE_OPTIONS` splits on spaces: the program travels percent-encoded, as a data: URL. */
125
+ export const ENV_PRELOAD = `--import=data:text/javascript,${encodeURIComponent(PRELOAD_SOURCE)}`;
73
126
  /**
74
127
  * What the process is started with: a minimal environment, never the
75
128
  * operator's shell (a stray variable there would override the `.env` — dotenv
76
129
  * and `--env-file` never overwrite) and never the `.env`'s secrets (`pm2 save`
77
- * writes the process environment to `~/.pm2/dump.pm2`). The app reads its own
78
- * `.env`, as it does in development; only what PM2 itself must know is passed.
130
+ * writes the process environment to `~/.pm2/dump.pm2`). The values reach the
131
+ * app through {@link ENV_PRELOAD}: pm2 only ever holds the file's path. With
132
+ * `loadEnv: false` the app reads its environment itself.
79
133
  */
80
- export function processEnv(host, env) {
134
+ export function processEnv(ctx, env) {
81
135
  const out = {};
82
136
  for (const key of ['NODE_ENV', 'PORT', 'HOST']) {
83
137
  const value = env.get(key);
84
138
  if (value !== undefined)
85
139
  out[key] = value;
86
140
  }
87
- const pm2Home = host.env['PM2_HOME'];
141
+ if (pm2Of(ctx).loadEnv !== false) {
142
+ out['BASALT_ENV_FILE'] = envFile(ctx);
143
+ // NODE_OPTIONS from the file would come too late for node itself: pass it on.
144
+ const own = env.get('NODE_OPTIONS')?.trim();
145
+ out['NODE_OPTIONS'] = own ? `${own} ${ENV_PRELOAD}` : ENV_PRELOAD;
146
+ }
147
+ const pm2Home = ctx.host.env['PM2_HOME'];
88
148
  if (pm2Home)
89
149
  out['PM2_HOME'] = pm2Home;
90
150
  return out;
@@ -93,7 +153,7 @@ export function processEnv(host, env) {
93
153
  export async function pm2Release(ctx, env) {
94
154
  const { host } = ctx;
95
155
  const name = processName(ctx.config);
96
- const options = { cwd: ctx.dir, env: processEnv(host, env), inheritEnv: false };
156
+ const options = { cwd: ctx.dir, env: processEnv(ctx, env), inheritEnv: false };
97
157
  const ours = (await pm2List(ctx))?.find((p) => p.name === name);
98
158
  if (ours && ours.cwd !== ctx.dir) {
99
159
  host.out.info(`pm2 delete ${name} (it ran from ${ours.cwd})`);
@@ -240,6 +240,17 @@ export interface PromptEvent extends Envelope, PromptDescriptor {
240
240
  type: 'prompt';
241
241
  attempt: number;
242
242
  }
243
+ /**
244
+ * The config's remote and branch, and the remote's address for a person:
245
+ * host and path only (`github.com/acme/app`) — never credentials, a query or
246
+ * a local path. `url` is absent when git could not say or the address is
247
+ * not a plain host and path.
248
+ */
249
+ export interface Source {
250
+ remote: string;
251
+ branch: string;
252
+ url?: string;
253
+ }
243
254
  export interface StatusResult {
244
255
  app: string;
245
256
  stateDir: string;
@@ -268,6 +279,8 @@ export interface StatusResult {
268
279
  releases: Release[];
269
280
  /** The subject of each release's commit, by sha (`--json` only; absent when git could not say). */
270
281
  subjects?: Record<string, string>;
282
+ /** Where a run fetches from (0.9.0+): which app a target really is. */
283
+ source?: Source;
271
284
  process: {
272
285
  kind: 'pm2';
273
286
  name: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/deploy",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },
@@ -27,7 +27,7 @@
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.6.5",
29
29
  "typescript": "^7.0.2",
30
- "vitest": "^5.0.3",
30
+ "vitest": "^5.0.5",
31
31
  "@basaltkit/tsconfig": "^0.24.0"
32
32
  },
33
33
  "publishConfig": {