@basaltkit/deploy 0.5.2 → 0.5.4

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
@@ -269,8 +269,12 @@ only NDJSON events, one per line:
269
269
  - **No event carries a secret.** Every string is redacted before it is
270
270
  written: the values of generated, asked-secret and secret-named `.env` keys,
271
271
  passwords inside URLs, the infra passwords, secret-named variables of the
272
- deploy's own environment, every secret answer — raw and URL-encoded —
273
- become `[redacted:KEY]`. What the config prints while it loads waits until
272
+ deploy's own environment, every secret answer — raw and URL-encoded, and a
273
+ multi-line value (a PEM key) also with its newlines escaped and line by
274
+ line — become `[redacted:KEY]`. A name is secret when it holds `SECRET`,
275
+ `TOKEN`, `PASSW`, `PRIVATE`, `APIKEY`, `CREDENTIAL`, a `KEY`, `SALT` or
276
+ `PWD` word, or ends in `_URL`/`_DSN`; declare any other with `generate` or
277
+ `ask.secret`. What the config prints while it loads waits until
274
278
  its `.env` has been read. A bare origin in a `*_URL` key
275
279
  (`APP_URL=https://app.example.com`) is the app's address and is not
276
280
  redacted. A value shorter than 6 characters cannot be matched; a
@@ -553,25 +557,38 @@ environment to `~/.pm2/dump.pm2`).
553
557
  loads `deploy.config.ts`, the checkout's `tsx` or `node_modules`, nor reads
554
558
  the `.env`. Before writing it prints what it will do. Raw Caddy `extra` and a
555
559
  non-default proxy root are shown and need a "yes" at the terminal; `extra`
556
- may hold no control or direction character (what is shown is what is
557
- written) and no `import`.
560
+ may hold no control, direction or zero-width character (what is shown is
561
+ what is written) and no `import`.
558
562
  - **A plan cannot take another site.** The managed vhost is `<app>.conf` (or
559
563
  `<app>-….conf`), and `install` refuses a domain — or a name under its
560
564
  wildcard, or a wildcard over it — that another Apache vhost or Caddy site
561
- already serves.
565
+ already serves (Caddy `extra` site blocks included). The file it replaces
566
+ must be the app's own: written by `install` for it, or serving only its
567
+ names.
562
568
  - **The served directory follows no planted link out of the user's files.**
563
569
  The vhost sets `Options -FollowSymLinks +SymLinksIfOwnerMatch` and
564
- `AllowOverride None` on the checkout and the web root. Caddy's
565
- `file_server` has no such option: with `caddy()`, a link in the web root is
566
- followed to anything the `caddy` user can read — keep secrets of other
567
- sites out of its reach.
570
+ `AllowOverride None` on the checkout and the web root, and the link rule on
571
+ every directory above the checkout too — a parent the user can write
572
+ (`/home/<user>`) could otherwise hold a link swapped in for the checkout
573
+ itself. `install` refuses a checkout reached through a link, and the plan's
574
+ `dir` is letters, digits and `. _ @ + -` only. Caddy's `file_server` has no
575
+ such option: with `caddy()`, a link in the web root is followed to anything
576
+ the `caddy` user can read — keep secrets of other sites out of its reach,
577
+ and the checkout under a root-owned directory (`/srv/<app>`; `install` warns
578
+ otherwise).
579
+ - **A user step never gets root's terminal.** In `bootstrap`, the app user's
580
+ `pnpm install` (and `env` without a terminal) writes to a pipe, not to
581
+ root's terminal: a process a postinstall leaves behind cannot read root's
582
+ keystrokes. Its output is shown line by line, without escape sequences.
568
583
  - **Root writes only where no other user can plant a link**: directories
569
584
  only root can write (`/var/lib/basalt`, `/etc/basalt`, the Apache/Caddy
570
585
  roots), or files changed through an `O_NOFOLLOW` descriptor.
571
586
  - **The tool root runs is checked.** As root, `install` and `bootstrap` refuse
572
587
  to run from files another user can change — `sudo node
573
588
  node_modules/@basaltkit/deploy/dist/bin.js` from the checkout, a user's npm
574
- cache, a per-user Node (nvm) — unless `--unsafe-tool`. Run the pinned copy:
589
+ cache, a per-user Node (nvm) — unless `--unsafe-tool`. The check catches
590
+ that mistake; it cannot stop a copy someone already tampered with (its code
591
+ has run by then), so the defence is the copy itself. Run the pinned copy:
575
592
  `cd / && sudo -H npx --yes --package=@basaltkit/deploy@<version> -- basalt-deploy …`
576
593
  (`cd /`: inside the checkout npx would pick its own copy; `-H`: root's npm
577
594
  cache, not the user's), or a root-owned global install (`sudo npm install -g
package/dist/apache.js CHANGED
@@ -1,4 +1,4 @@
1
- import { join } from 'node:path';
1
+ import { dirname, join } from 'node:path';
2
2
  import { vhostName } from './config.js';
3
3
  import { DeployError, INSTALL_COMMAND } from './context.js';
4
4
  import { lineDiff } from './diff.js';
@@ -27,6 +27,18 @@ export function renderVhost(ctx, port) {
27
27
  const webRoot = join(ctx.dir, proxy.webRoot);
28
28
  const prefix = proxy.apiPrefix.replace(/\/$/, '');
29
29
  const cert = `/etc/letsencrypt/live/${proxy.certName ?? domain}`;
30
+ // Apache checks a link against the options of the directory that holds it:
31
+ // a parent the app user can write (/home/<user>) could hold a link swapped
32
+ // in for the checkout itself, judged by the server's <Directory /> (which
33
+ // follows links), not by the blocks below. Every directory above the
34
+ // checkout gets the same rule.
35
+ const above = [];
36
+ for (let parent = dirname(ctx.dir); parent !== '/' && parent !== '.'; parent = dirname(parent))
37
+ above.unshift(parent);
38
+ const parents = above.map((parent) => ` <Directory ${parent}>
39
+ Options -FollowSymLinks +SymLinksIfOwnerMatch
40
+ </Directory>
41
+ `).join('');
30
42
  return `# Written by basalt-deploy install for "${app}". Deploys compare this file with
31
43
  # what install would write and print the difference; they never rewrite it.
32
44
  # To change it: edit deploy.config.ts, run ${INSTALL_COMMAND}
@@ -46,7 +58,7 @@ ${alias}
46
58
  # The checkout is the app user's: a link it plants is followed only to a
47
59
  # file it owns too (never to /, nor to another site's files), and no
48
60
  # .htaccess turns that back on.
49
- <Directory ${ctx.dir}>
61
+ ${parents} <Directory ${ctx.dir}>
50
62
  Options -Indexes -FollowSymLinks +SymLinksIfOwnerMatch
51
63
  AllowOverride None
52
64
  </Directory>
@@ -36,7 +36,11 @@ export interface Action {
36
36
  interactive?: boolean;
37
37
  /** Asked at the terminal before a real run runs it; a "no" (or no terminal) stops bootstrap. */
38
38
  confirm?: string;
39
+ /** Runs as the app user: its output reaches root's terminal only through a pipe, line by line, sanitized. */
40
+ user?: boolean;
39
41
  }
42
+ /** The oldest pnpm root installs globally (lockfile v9; the app user chooses the version, root sets the floor). */
43
+ export declare const MIN_PNPM: number[];
40
44
  /**
41
45
  * The checkout bootstrap works on — and may `chown -R` to the user — named
42
46
  * with `--dir`, never taken from the working directory (root's commands run
@@ -60,6 +64,13 @@ export declare function planSystem(host: Host, dir: string, user: string): Promi
60
64
  * of its own (`script`, run by root, relays the keys) — or, with no terminal
61
65
  * to relay, runs like the others and fails closed on a missing answer.
62
66
  *
67
+ * And never root's terminal as the step's stdout/stderr either: an inherited
68
+ * descriptor is the session's read-write pty, and a process the step leaves
69
+ * behind could keep it and read root's keystrokes for the rest of the SSH
70
+ * session. Its output comes through a pipe instead — split into lines, every
71
+ * escape sequence and control character stripped — and the pipe is closed
72
+ * once the step exits, whatever it left running.
73
+ *
63
74
  * A Ctrl-C does not reach a step in its own session: bootstrap stops, the
64
75
  * step finishes on its own.
65
76
  */
@@ -82,4 +93,9 @@ export declare function planBootstrap(host: Host, dir: string, options: Bootstra
82
93
  }>;
83
94
  /** The @basaltkit/deploy version the lockfile records — what root should be running. */
84
95
  export declare function lockedDeployVersion(lockfile: string): string | undefined;
96
+ /** A user step's output, for root's terminal: whole lines, sanitized, nothing that can drive the terminal. */
97
+ export declare function relay(host: Host): {
98
+ write: (text: string, stream: 'stdout' | 'stderr') => void;
99
+ flush: () => void;
100
+ };
85
101
  export declare function bootstrap(host: Host, dir: string, options: BootstrapOptions, tool?: string): Promise<number>;
package/dist/bootstrap.js CHANGED
@@ -1,11 +1,14 @@
1
- import { tmpdir } from 'node:os';
2
1
  import { join, normalize } from 'node:path';
3
2
  import { below, lockedPnpm, minimumVersion } from './checks.js';
4
3
  import { DeployError } from './context.js';
4
+ import { LineSplitter, sanitize } from './events.js';
5
5
  import { install, parseInstallPlan } from './install-plan.js';
6
- import { USER_NAME } from './trust.js';
6
+ import { CHECKOUT_PATH, USER_NAME } from './trust.js';
7
7
  const APT = ['env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get'];
8
- const OUTSIDE = { cwd: tmpdir() };
8
+ /** The oldest pnpm root installs globally (lockfile v9; the app user chooses the version, root sets the floor). */
9
+ export const MIN_PNPM = [9, 0, 0];
10
+ // `/`, never a world-writable directory: a tool that reads project config from its working directory finds none there.
11
+ const OUTSIDE = { cwd: '/' };
9
12
  const BIN = 'node_modules/@basaltkit/deploy/dist/bin.js';
10
13
  const sh = (script) => ['sh', '-c', script];
11
14
  /** Read as data, as root, from the app user's checkout: no link followed, a size cap (a FIFO or /dev/zero must not hang root). */
@@ -29,8 +32,8 @@ const SYSTEM_TREES = ['/bin/', '/boot/', '/dev/', '/etc/', '/lib/', '/lib32/', '
29
32
  * no link in it, not a system directory, holding package.json and .git.
30
33
  */
31
34
  export async function checkoutProblem(host, dir) {
32
- if (!dir.startsWith('/') || normalize(dir) !== dir || (dir !== '/' && dir.endsWith('/')) || /[\0\n\r"'\\$`\s]/.test(dir))
33
- return `${dir} must be an absolute, normalized path without quotes, spaces or shell characters`;
35
+ if (!CHECKOUT_PATH.test(dir) || normalize(dir) !== dir || (dir !== '/' && dir.endsWith('/')))
36
+ return `${dir} must be an absolute, normalized path of letters, digits and . _ @ + - only`;
34
37
  if (SYSTEM_DIRS.has(dir) || SYSTEM_TREES.some((tree) => dir.startsWith(tree)))
35
38
  return `${dir} is a system directory, not an app checkout`;
36
39
  const stat = await host.stat(dir);
@@ -91,6 +94,9 @@ export async function planSystem(host, dir, user) {
91
94
  const version = (lockfile && lockedPnpm(lockfile)) ?? pkg.packageManager.slice('pnpm@'.length).split('+')[0];
92
95
  if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(version))
93
96
  throw new DeployError(`the pnpm version the project records ("${version}") is not a version`);
97
+ // The app user picks the version root installs globally: never one older than the floor.
98
+ if (below(minimumVersion(version), MIN_PNPM))
99
+ throw new DeployError(`the project records pnpm ${version}; bootstrap installs pnpm ${MIN_PNPM.join('.')} or newer globally, as root — update packageManager and the lockfile`);
94
100
  const current = (await host.exec('pnpm', ['--version'], OUTSIDE)).stdout.trim();
95
101
  if (current !== version)
96
102
  actions.push({ what: `pnpm ${version}${current ? ` (this server has ${current})` : ''}`, commands: [['npm', 'install', '-g', `pnpm@${version}`]] });
@@ -122,6 +128,13 @@ export async function planSystem(host, dir, user) {
122
128
  * of its own (`script`, run by root, relays the keys) — or, with no terminal
123
129
  * to relay, runs like the others and fails closed on a missing answer.
124
130
  *
131
+ * And never root's terminal as the step's stdout/stderr either: an inherited
132
+ * descriptor is the session's read-write pty, and a process the step leaves
133
+ * behind could keep it and read root's keystrokes for the rest of the SSH
134
+ * session. Its output comes through a pipe instead — split into lines, every
135
+ * escape sequence and control character stripped — and the pipe is closed
136
+ * once the step exits, whatever it left running.
137
+ *
125
138
  * A Ctrl-C does not reach a step in its own session: bootstrap stops, the
126
139
  * step finishes on its own.
127
140
  */
@@ -132,8 +145,8 @@ export function userSteps(user, dir, tty) {
132
145
  ? ['script', '--quiet', '--return', '--command', asUser('node', BIN, 'env').join(' '), '/dev/null']
133
146
  : ['setsid', '-w', ...asUser('node', BIN, 'env')];
134
147
  return [
135
- { what: `as ${user}: dependencies`, cwd: dir, commands: [['setsid', '-w', ...asUser('env', '-u', 'NODE_ENV', 'pnpm', 'install', '--frozen-lockfile')]] },
136
- { what: `as ${user}: the .env (asks what it cannot generate)`, cwd: dir, ...(tty ? { interactive: true } : {}), commands: [env] },
148
+ { what: `as ${user}: dependencies`, cwd: dir, user: true, commands: [['setsid', '-w', ...asUser('env', '-u', 'NODE_ENV', 'pnpm', 'install', '--frozen-lockfile')]] },
149
+ { what: `as ${user}: the .env (asks what it cannot generate)`, cwd: dir, ...(tty ? { interactive: true } : { user: true }), commands: [env] },
137
150
  ];
138
151
  }
139
152
  /** The phase-2 command whose stdout is the install plan (JSON) — in its own session, like the other steps. */
@@ -208,6 +221,18 @@ export async function planBootstrap(host, dir, options) {
208
221
  export function lockedDeployVersion(lockfile) {
209
222
  return /['"]?@basaltkit\/deploy@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)['"]?:/.exec(lockfile)?.[1];
210
223
  }
224
+ /** A user step's output, for root's terminal: whole lines, sanitized, nothing that can drive the terminal. */
225
+ export function relay(host) {
226
+ const splitters = { stdout: new LineSplitter(), stderr: new LineSplitter() };
227
+ const show = (lines) => {
228
+ for (const line of lines)
229
+ host.out.info(` ${sanitize(line.text)}${line.cut ? ' …' : ''}`);
230
+ };
231
+ return {
232
+ write: (text, stream) => show(splitters[stream].push(text)),
233
+ flush: () => { show(splitters.stdout.end()); show(splitters.stderr.end()); },
234
+ };
235
+ }
211
236
  async function runActions(host, actions, dryRun) {
212
237
  for (const action of actions) {
213
238
  host.out.info(action.what);
@@ -218,10 +243,12 @@ async function runActions(host, actions, dryRun) {
218
243
  host.out.info(` + ${command.join(' ')}${action.cwd ? ` (in ${action.cwd})` : ''}`);
219
244
  if (dryRun)
220
245
  continue;
246
+ const output = action.user && !action.interactive ? relay(host) : undefined;
221
247
  const result = await host.exec(command[0], command.slice(1), {
222
248
  cwd: action.cwd ?? OUTSIDE.cwd,
223
- ...(action.interactive ? { interactive: true } : { stream: true }),
249
+ ...(action.interactive ? { interactive: true } : output ? { stream: true, onOutput: output.write } : { stream: true }),
224
250
  });
251
+ output?.flush();
225
252
  if (result.code !== 0)
226
253
  throw new DeployError(`${action.what}: \`${command.join(' ')}\` failed (exit ${result.code}) — re-run bootstrap after fixing it; what is done is not redone`);
227
254
  }
@@ -262,7 +289,7 @@ export async function bootstrap(host, dir, options, tool) {
262
289
  host.out.info(`as ${user}: the install plan\n + ${command.join(' ')}`);
263
290
  const written = await host.exec(command[0], command.slice(1), { cwd: dir });
264
291
  if (written.code !== 0)
265
- throw new DeployError(`install-plan as ${user} failed (exit ${written.code}): ${written.stderr.trim().split('\n').slice(-3).join(' ')}`);
292
+ throw new DeployError(`install-plan as ${user} failed (exit ${written.code}): ${sanitize(written.stderr.trim().split('\n').slice(-3).join(' '))}`);
266
293
  const plan = parseInstallPlan(written.stdout, `the install plan from ${user}`);
267
294
  if (plan.dir !== dir)
268
295
  throw new DeployError(`the install plan names ${plan.dir}, not ${dir} — refused`);
package/dist/cli.js CHANGED
@@ -121,7 +121,14 @@ const COMMANDS = ['init', 'check', 'plan', 'run', 'env', 'rollback', 'status', '
121
121
  /** The commands that take the deploy lock, and so write a run log under --json. */
122
122
  const LOCKED = new Set(['run', 'env', 'rollback']);
123
123
  const usage = (message, hint) => new DeployError(message, [], 'usage', hint);
124
- /** The files root is about to run: node, and this package's own (its directory and modules). */
124
+ /**
125
+ * The files root is about to run: node, and this package's own (its directory
126
+ * and modules). A guard against the mistake — `sudo node node_modules/…` from
127
+ * the checkout, a user's npm cache, an nvm node — not against a tampered
128
+ * copy: every module is already loaded when this runs. The defence is to run
129
+ * a copy only root can change (the pinned `npx` line, or a root-owned global
130
+ * install).
131
+ */
125
132
  async function assertTrustedTool(host, unsafe) {
126
133
  const dir = dirname(fileURLToPath(import.meta.url));
127
134
  const modules = (await host.list(dir)).filter((name) => name.endsWith('.js')).map((name) => join(dir, name));
package/dist/events.js CHANGED
@@ -149,7 +149,11 @@ export class Redactor {
149
149
  return 'short';
150
150
  }
151
151
  let added = false;
152
- for (const form of new Set([value, encodeURIComponent(value)])) {
152
+ // A multi-line value (a PEM key) reaches the log line by line, or with its
153
+ // newlines escaped: each form, and each line long enough not to be common text.
154
+ const lines = value.includes('\n') ? value.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length >= 16) : [];
155
+ const escaped = lines.length ? [value.replace(/\r?\n/g, '\\n')] : [];
156
+ for (const form of new Set([value, encodeURIComponent(value), ...escaped, ...lines])) {
153
157
  if (form.length < MIN_REDACTED_LENGTH || this.needles.has(form))
154
158
  continue;
155
159
  this.needles.set(form, key);
package/dist/init.js CHANGED
@@ -4,7 +4,7 @@ const COMPOSE_FILES = ['docker/compose.prod.yml', 'docker/compose.prod.yaml', 'c
4
4
  const PRISMA_CENTRAL = 'prisma.config.ts';
5
5
  const PRISMA_TENANTS = 'prisma/tenants/prisma.config.ts';
6
6
  /** Key names whose values are secrets (what `init` asks as `ask.secret`, what JSON mode redacts). */
7
- export const SENSITIVE = /SECRET|TOKEN|PASSWORD|PASS\b|_KEY\b|^KEY_|CREDENTIAL|_URL$|_DSN$/;
7
+ export const SENSITIVE = /SECRET|TOKEN|PASSW|PASS\b|_PWD(?:_|$)|(?:^|_)KEY(?:_|$)|APIKEY|PRIVATE|(?:^|_)SALT(?:_|$)|CREDENTIAL|_URL$|_DSN$/;
8
8
  /**
9
9
  * A `secret()` the app can mint for itself (signing, encryption): generated on
10
10
  * the server. One a provider issues (S3, an API, SMTP) is asked instead — a
@@ -7,7 +7,7 @@ import { envValues } from './dotenv.js';
7
7
  import { envFile, envMirrors, readEnv } from './env-step.js';
8
8
  import { acquireLock } from './lock.js';
9
9
  import { covers } from './checks.js';
10
- import { API_PREFIX, ASK_PATH, assertRootOwnedDir, caddyExtraProblem, CERT_NAME, envLocationProblem, isConfigRoot, isWebRoot, USER_NAME, vhostFileProblem } from './trust.js';
10
+ import { API_PREFIX, ASK_PATH, assertRootOwnedDir, caddyExtraProblem, CERT_NAME, CHECKOUT_PATH, envLocationProblem, isConfigRoot, isWebRoot, untrustedAncestor, USER_NAME, vhostFileProblem } from './trust.js';
11
11
  /**
12
12
  * `install` in two halves (RFC 0006 §11.4), so that root never runs code the
13
13
  * app user can change:
@@ -100,8 +100,8 @@ export function parseInstallPlan(text, source) {
100
100
  if (plan['tenants'] !== 'subdomain' && plan['tenants'] !== 'none')
101
101
  problems.push('tenants is subdomain or none');
102
102
  const dir = plan['dir'];
103
- if (typeof dir !== 'string' || !dir.startsWith('/') || dir === '/' || normalize(dir) !== dir || dir.endsWith('/') || /[\0\n\r"'\\$`\s]/.test(dir)) {
104
- problems.push('dir must be an absolute, normalized path without quotes, spaces or shell characters (not /)');
103
+ if (typeof dir !== 'string' || !CHECKOUT_PATH.test(dir) || dir === '/' || normalize(dir) !== dir || dir.endsWith('/')) {
104
+ problems.push('dir must be an absolute, normalized path of letters, digits and . _ @ + - only (not /)');
105
105
  }
106
106
  const port = plan['port'];
107
107
  if (typeof port !== 'number' || !Number.isInteger(port) || port < 1 || port > 65535)
@@ -231,6 +231,9 @@ export async function install(host, plan, user, options = {}) {
231
231
  throw new DeployError(`${plan.dir} is not a directory (a symbolic link is refused)`);
232
232
  if (checkout.uid !== owner.uid)
233
233
  throw new DeployError(`${plan.dir} is not ${user}'s (uid ${checkout.uid}): install serves ${user}'s checkout only`);
234
+ const real = await host.realpath(plan.dir);
235
+ if (real !== plan.dir)
236
+ throw new DeployError(`${plan.dir} goes through a symbolic link (it is ${real ?? 'unreadable'}): the plan must name the real directory`);
234
237
  const stateRoot = options.stateRoot ?? '/var/lib/basalt';
235
238
  await host.mkdir(stateRoot, 0o755);
236
239
  await assertRootOwnedDir(host, stateRoot, 'state directory');
@@ -281,6 +284,10 @@ export async function install(host, plan, user, options = {}) {
281
284
  await host.mkdir(caddyPaths(ctx).dir, 0o755);
282
285
  await assertRootOwnedDir(host, caddyPaths(ctx).dir, 'Caddy');
283
286
  await caddyInstall(ctx, plan.port, backups);
287
+ // Caddy follows links wherever they go (RFC 0006 §14.1): said, not hidden.
288
+ const open = await untrustedAncestor(host, dirname(plan.dir));
289
+ if (open)
290
+ host.out.warn(`${open} is writable by a user other than root: ${user} could swap ${plan.dir} for a link, and Caddy would serve wherever it points — keep checkouts under a root-owned directory (/srv/<app>)`);
284
291
  }
285
292
  if (plan.docker) {
286
293
  const groups = (await host.exec('id', ['-nG', user])).stdout.split(/\s+/);
@@ -339,7 +346,22 @@ const overlap = (a, b) => a === b || (a.startsWith('*.') && covers(a, b)) || (b.
339
346
  * its wildcard — would take that app's traffic and certificate.
340
347
  */
341
348
  async function refuseTakenNames(host, plan, dirs, own, kind, main) {
342
- const ours = [plan.domain, ...(plan.tenants === 'subdomain' ? [`*.${plan.domain}`] : [])];
349
+ // Caddy `extra` can open site blocks of its own: their addresses are names this site takes too.
350
+ const extra = plan.proxy.kind === 'caddy' && plan.proxy.managed && plan.proxy.extra !== undefined ? servedNames(plan.proxy.extra, 'caddy') : [];
351
+ const ours = [plan.domain, ...(plan.tenants === 'subdomain' ? [`*.${plan.domain}`] : []), ...extra];
352
+ // The file about to be replaced is this app's: written by install for it, or (hand-written,
353
+ // being adopted) serving nothing but its names — never another app's that `vhost` happens to name.
354
+ for (const dir of dirs) {
355
+ const file = join(dir, own);
356
+ const text = await host.readFile(file);
357
+ if (text === undefined)
358
+ continue;
359
+ const writer = /^# Written by basalt-deploy install for "([^"]*)"/m.exec(text)?.[1];
360
+ const foreign = servedNames(text, kind).filter((name) => !ours.some((mine) => overlap(mine, name)));
361
+ if ((writer !== undefined && writer !== plan.app) || (writer === undefined && foreign.length > 0)) {
362
+ throw new DeployError(`refused: ${file} is ${writer !== undefined ? `"${writer}"'s` : `a site for ${[...new Set(foreign)].join(', ')}`}, not "${plan.app}"'s — name another file (proxy.vhost)`);
363
+ }
364
+ }
343
365
  const files = [...(main ? [main] : []), ...(await Promise.all(dirs.map(async (dir) => (await host.list(dir)).filter((name) => name !== own).map((name) => join(dir, name))))).flat()];
344
366
  for (const file of files) {
345
367
  const text = await host.readFile(file);
package/dist/trust.d.ts CHANGED
@@ -11,6 +11,12 @@ import type { Host } from './host.js';
11
11
  */
12
12
  /** A login name: what `useradd` accepts, never an option or a path. */
13
13
  export declare const USER_NAME: RegExp;
14
+ /**
15
+ * A checkout path: a closed set of characters. It is written into the Apache
16
+ * vhost and the Caddy site, where `{ }` are placeholders, `* ? [ ]`
17
+ * wildcards and `#` a comment.
18
+ */
19
+ export declare const CHECKOUT_PATH: RegExp;
14
20
  /** Directory served by the proxy, relative to the checkout: inside it, never the checkout itself, never a dot directory. */
15
21
  export declare function isWebRoot(value: unknown): value is string;
16
22
  /** `/api`, `/api/v1/`: URL path segments, no dot segments, nothing a config file would parse. */
package/dist/trust.js CHANGED
@@ -12,6 +12,12 @@ import { DeployError } from './context.js';
12
12
  */
13
13
  /** A login name: what `useradd` accepts, never an option or a path. */
14
14
  export const USER_NAME = /^[a-z_][a-z0-9_-]{0,31}$/;
15
+ /**
16
+ * A checkout path: a closed set of characters. It is written into the Apache
17
+ * vhost and the Caddy site, where `{ }` are placeholders, `* ? [ ]`
18
+ * wildcards and `#` a comment.
19
+ */
20
+ export const CHECKOUT_PATH = /^\/[A-Za-z0-9._@+/-]*$/;
15
21
  /** A path segment with no leading dot: never `.`, `..`, `.git`, `.env`, `.basalt`. */
16
22
  const SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
17
23
  /** Directory served by the proxy, relative to the checkout: inside it, never the checkout itself, never a dot directory. */
@@ -30,10 +36,11 @@ export const ASK_PATH = /^(\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)+$/;
30
36
  export const CERT_NAME = /^[A-Za-z0-9][A-Za-z0-9-]*(\.[A-Za-z0-9-]+)*$/;
31
37
  /**
32
38
  * Characters a terminal acts on instead of showing (CR, ESC and the C1 CSI,
33
- * line separators, bidirectional overrides): `install` shows raw Caddy
39
+ * line separators, bidirectional overrides), or shows as nothing (zero-width
40
+ * spaces and joiners, soft hyphen, BOM): `install` shows raw Caddy
34
41
  * `extra` before root writes it, and what is shown must be what is written.
35
42
  */
36
- const HIDDEN = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/;
43
+ const HIDDEN = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u00ad\u061c\u180e\u200b-\u200f\u2028\u2029\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/;
37
44
  /**
38
45
  * Raw Caddy `extra`: no character that hides text on a terminal, and no
39
46
  * `import` — a file the app user can change later would be configuration
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/deploy",
3
- "version": "0.5.2",
3
+ "version": "0.5.4",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },