@basaltkit/deploy 0.9.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
 
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/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})`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/deploy",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },