@basaltkit/deploy 0.4.0 → 0.5.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.
Files changed (53) hide show
  1. package/README.md +276 -23
  2. package/dist/answers.d.ts +70 -0
  3. package/dist/answers.js +196 -0
  4. package/dist/apache.js +11 -2
  5. package/dist/audit.d.ts +20 -0
  6. package/dist/audit.js +26 -0
  7. package/dist/backup.d.ts +17 -1
  8. package/dist/backup.js +49 -1
  9. package/dist/bin.js +9 -1
  10. package/dist/bootstrap.d.ts +68 -18
  11. package/dist/bootstrap.js +177 -45
  12. package/dist/caddy.js +2 -1
  13. package/dist/check.js +18 -5
  14. package/dist/checks.js +1 -1
  15. package/dist/cli.d.ts +22 -1
  16. package/dist/cli.js +498 -57
  17. package/dist/compose.d.ts +1 -1
  18. package/dist/compose.js +18 -1
  19. package/dist/config.d.ts +25 -2
  20. package/dist/config.js +65 -3
  21. package/dist/context.d.ts +43 -13
  22. package/dist/context.js +50 -7
  23. package/dist/detach.d.ts +23 -0
  24. package/dist/detach.js +105 -0
  25. package/dist/env-step.d.ts +16 -1
  26. package/dist/env-step.js +58 -5
  27. package/dist/events.d.ts +168 -0
  28. package/dist/events.js +477 -0
  29. package/dist/host.d.ts +171 -7
  30. package/dist/host.js +302 -41
  31. package/dist/index.d.ts +10 -5
  32. package/dist/index.js +7 -3
  33. package/dist/init.d.ts +2 -0
  34. package/dist/init.js +2 -1
  35. package/dist/install-plan.d.ts +40 -0
  36. package/dist/install-plan.js +433 -0
  37. package/dist/json-host.d.ts +32 -0
  38. package/dist/json-host.js +106 -0
  39. package/dist/lock.d.ts +45 -0
  40. package/dist/lock.js +128 -0
  41. package/dist/pipeline.d.ts +51 -3
  42. package/dist/pipeline.js +339 -173
  43. package/dist/protocol.d.ts +364 -0
  44. package/dist/protocol.js +134 -0
  45. package/dist/runs.d.ts +75 -0
  46. package/dist/runs.js +287 -0
  47. package/dist/state.d.ts +26 -13
  48. package/dist/state.js +68 -4
  49. package/dist/trust.d.ts +63 -0
  50. package/dist/trust.js +159 -0
  51. package/dist/version.d.ts +2 -0
  52. package/dist/version.js +10 -0
  53. package/package.json +5 -1
package/dist/runs.js ADDED
@@ -0,0 +1,287 @@
1
+ import { join } from 'node:path';
2
+ import { DeployError } from './context.js';
3
+ import { readLock } from './lock.js';
4
+ import { parseEvent, RUN_ID } from './protocol.js';
5
+ /**
6
+ * Run logs (RFC 0008 §8): `<stateDir>/runs/<runId>.ndjson`, one per
7
+ * JSON-mode locked command (`run`, `env`, `rollback`), holding its events —
8
+ * what `attach` replays, what `status` reports as the last run.
9
+ *
10
+ * The directory is 0700 and the deploy user's; a log is 0600, created
11
+ * O_EXCL|O_NOFOLLOW and read O_NOFOLLOW with its owner and mode checked.
12
+ * They protect it from other users, not from the app user itself (§10).
13
+ */
14
+ export const runsDir = (stateDir) => join(stateDir, 'runs');
15
+ export const runLogPath = (stateDir, runId) => join(runsDir(stateDir), `${runId}.ndjson`);
16
+ /** Created by the first `cancel` of a run: a second one is the second signal. */
17
+ const cancelMarker = (stateDir, runId) => join(runsDir(stateDir), `${runId}.cancel`);
18
+ /** Retention (RFC 0008 §8.7). */
19
+ export const KEEP_RUN_LOGS = 50;
20
+ export const KEEP_RUN_DAYS = 30;
21
+ const RUN_FILE = /^(\d{8}T\d{6}Z-[0-9a-f]{12})\.(ndjson|cancel)$/;
22
+ /** `<UTC yyyymmddThhmmssZ>-<12 hex>`. */
23
+ export function newRunId(host) {
24
+ const stamp = host.now().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z');
25
+ return `${stamp}-${host.randomHex(6)}`;
26
+ }
27
+ const notOurs = (path, why) => new DeployError(`${path} is not a run log this deploy wrote (${why}) — refused`, [], 'failed');
28
+ /** Creates the runs directory (0700) or checks it: a directory, the deploy user's, nobody else's. */
29
+ export async function ensureRunsDir(host, stateDir) {
30
+ const dir = runsDir(stateDir);
31
+ if (!(await host.stat(dir)))
32
+ await host.mkdir(dir, 0o700);
33
+ const stat = await host.stat(dir);
34
+ if (stat?.kind !== 'dir')
35
+ throw new DeployError(`${dir} is ${stat?.kind === 'symlink' ? 'a symbolic link' : 'not a directory'} — refused, never followed`, [], 'failed');
36
+ if (stat.uid !== undefined && stat.uid !== host.uid())
37
+ throw new DeployError(`${dir} is owned by uid ${stat.uid}, not by the deploy user (uid ${host.uid()}) — refused`, [], 'failed');
38
+ if (stat.mode !== undefined && (stat.mode & 0o077) !== 0)
39
+ throw new DeployError(`${dir} is ${(stat.mode & 0o777).toString(8)}: other users could read the run logs — chmod 700 ${dir}`, [], 'failed');
40
+ return dir;
41
+ }
42
+ /** A new run log, 0600, created exclusively (a link or file already there is an error). */
43
+ export async function createRunLog(host, stateDir, runId) {
44
+ if (!host.createLog)
45
+ throw new DeployError('this host cannot write run logs', [], 'unsupported');
46
+ await ensureRunsDir(host, stateDir);
47
+ const path = runLogPath(stateDir, runId);
48
+ try {
49
+ return { path, handle: await host.createLog(path, 0o600) };
50
+ }
51
+ catch (error) {
52
+ throw new DeployError(`cannot create the run log ${path} (${error.message}): something is already there — refused, never reused or followed`, [], 'failed');
53
+ }
54
+ }
55
+ /**
56
+ * Keeps the newest {@link KEEP_RUN_LOGS} logs and none older than
57
+ * {@link KEEP_RUN_DAYS} days; never `keep` (the run holding the lock). Only
58
+ * names this package writes, by unlink(2) — never recursive.
59
+ */
60
+ export async function pruneRunLogs(host, stateDir, keep) {
61
+ const dir = runsDir(stateDir);
62
+ const runs = new Map();
63
+ for (const name of await host.list(dir)) {
64
+ const match = RUN_FILE.exec(name);
65
+ if (!match)
66
+ continue;
67
+ const id = match[1];
68
+ runs.set(id, [...(runs.get(id) ?? []), name]);
69
+ }
70
+ const ids = [...runs.keys()].sort().reverse();
71
+ const cutoff = host.now().getTime() - KEEP_RUN_DAYS * 24 * 3600 * 1000;
72
+ const removed = [];
73
+ ids.forEach((id, index) => {
74
+ if (id === keep)
75
+ return;
76
+ if (index < KEEP_RUN_LOGS && runTime(id) >= cutoff)
77
+ return;
78
+ removed.push(...(runs.get(id) ?? []));
79
+ });
80
+ const done = [];
81
+ for (const name of removed) {
82
+ try {
83
+ await host.removeFile(join(dir, name));
84
+ done.push(name);
85
+ }
86
+ catch {
87
+ // Not a file (a directory with a log's name): left alone; retention never fails a deploy.
88
+ }
89
+ }
90
+ return done;
91
+ }
92
+ function runTime(runId) {
93
+ const m = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/.exec(runId);
94
+ return m ? Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6])) : 0;
95
+ }
96
+ /** One range of a run log, refused unless it is a plain file of the deploy user that nobody else can read. */
97
+ async function readRange(host, path, offset, length) {
98
+ if (!host.readFileRange)
99
+ throw new DeployError('this host cannot read run logs', [], 'unsupported');
100
+ let range;
101
+ try {
102
+ range = await host.readFileRange(path, offset, length);
103
+ }
104
+ catch (error) {
105
+ throw notOurs(path, error.message);
106
+ }
107
+ if (range.uid !== host.uid())
108
+ throw notOurs(path, `owned by uid ${range.uid}`);
109
+ if ((range.mode & 0o077) !== 0)
110
+ throw notOurs(path, `mode ${(range.mode & 0o777).toString(8)}`);
111
+ return range;
112
+ }
113
+ /** The run named by a live lock holder (`status --json`). */
114
+ export function activeRun(host, lock) {
115
+ const holder = lock?.holder;
116
+ if (!holder?.runId || lock?.stale)
117
+ return undefined;
118
+ return { runId: holder.runId, pid: holder.pid, command: holder.command, actor: holder.actor, startedAt: holder.startedAt, alive: holder.host === host.hostname() && host.processAlive(holder.pid) };
119
+ }
120
+ const TAIL = 64 * 1024;
121
+ /** The newest run log: its command, and how it ended — from its first and last 64 KiB. */
122
+ export async function lastRun(host, stateDir) {
123
+ if (!host.readFileRange)
124
+ return undefined;
125
+ const newest = (await host.list(runsDir(stateDir))).filter((n) => /\.ndjson$/.test(n) && RUN_ID.test(n.slice(0, -'.ndjson'.length))).sort().at(-1);
126
+ if (!newest)
127
+ return undefined;
128
+ const runId = newest.slice(0, -'.ndjson'.length);
129
+ const path = runLogPath(stateDir, runId);
130
+ try {
131
+ const head = await readRange(host, path, 0, 4096);
132
+ const first = parseEvent(Buffer.from(head.data).toString('utf8').split('\n')[0] ?? '');
133
+ const command = first.ok && first.value.type === 'hello' ? first.value.command : '';
134
+ const start = Math.max(0, head.size - TAIL);
135
+ const tail = await readRange(host, path, start, TAIL);
136
+ const lines = Buffer.from(tail.data).toString('utf8').split('\n');
137
+ if (start > 0)
138
+ lines.shift();
139
+ for (const line of lines.reverse()) {
140
+ const parsed = parseEvent(line);
141
+ if (parsed.ok && parsed.value.type === 'done')
142
+ return { runId, command, exitCode: parsed.value.exitCode, complete: true, endedAt: parsed.value.ts };
143
+ }
144
+ return { runId, command, complete: false };
145
+ }
146
+ catch {
147
+ return { runId, command: '', complete: false };
148
+ }
149
+ }
150
+ // ── attach ─────────────────────────────────────────────────────────────────
151
+ export const ATTACH_POLL_MS = 250;
152
+ export const VANISH_GRACE_MS = 2000;
153
+ /**
154
+ * Without `--follow`: how long a run that released its lock gets to write
155
+ * its last events (`error`, `done`) before it is called vanished.
156
+ */
157
+ export const LAST_EVENTS_GRACE_MS = 500;
158
+ const CHUNK = 64 * 1024;
159
+ /**
160
+ * Replays a run log (RFC 0008 §8.4): every line checked — the envelope, a
161
+ * known shape, `seq` exactly one more than the line before — then handed on.
162
+ * A bad line ends the replay; raw text is never passed through. Returns the
163
+ * run's exit code once its `done` is read, else (without `--follow`, a run
164
+ * still alive) `undefined`.
165
+ */
166
+ export async function attach(host, stateDir, runId, options) {
167
+ if (!RUN_ID.test(runId))
168
+ throw new DeployError(`"${runId}" is not a run id`, [], 'usage');
169
+ const path = runLogPath(stateDir, runId);
170
+ if (!(await host.exists(path)))
171
+ throw new DeployError(`no run ${runId} here (${path})`, [], 'not-found');
172
+ let offset = 0;
173
+ let pending = Buffer.alloc(0);
174
+ let expected;
175
+ let lineNo = 0;
176
+ let quietSince;
177
+ let graced = false;
178
+ for (;;) {
179
+ const range = await readRange(host, path, offset, CHUNK);
180
+ offset += range.data.length;
181
+ pending = Buffer.concat([pending, Buffer.from(range.data)]);
182
+ let newline;
183
+ while ((newline = pending.indexOf(0x0a)) !== -1) {
184
+ const line = pending.subarray(0, newline).toString('utf8');
185
+ pending = pending.subarray(newline + 1);
186
+ lineNo++;
187
+ const parsed = parseEvent(line);
188
+ if (!parsed.ok)
189
+ throw new DeployError(`run log corrupt at line ${lineNo}: ${parsed.error}`, [], 'failed');
190
+ const event = parsed.value;
191
+ if (expected !== undefined && event.seq !== expected)
192
+ throw new DeployError(`run log corrupt at line ${lineNo}: seq ${event.seq} after ${expected - 1}`, [], 'failed');
193
+ if (expected === undefined && event.seq !== 0)
194
+ throw new DeployError(`run log corrupt at line ${lineNo}: it starts at seq ${event.seq}`, [], 'failed');
195
+ expected = event.seq + 1;
196
+ if (event.seq >= options.fromSeq)
197
+ options.emit(event);
198
+ if (event.type === 'done')
199
+ return event.exitCode;
200
+ }
201
+ if (pending.length > 2 * CHUNK)
202
+ throw new DeployError(`run log corrupt at line ${lineNo + 1}: a line longer than ${2 * CHUNK} bytes`, [], 'failed');
203
+ if (range.data.length > 0) {
204
+ quietSince = undefined;
205
+ continue;
206
+ }
207
+ // At the end of what is written: the run may still be writing.
208
+ const alive = await runAlive(host, stateDir, runId);
209
+ if (!options.follow) {
210
+ if (alive)
211
+ return undefined;
212
+ // The lock is released before `done` is written: one more look before calling the run gone.
213
+ if (!graced) {
214
+ graced = true;
215
+ await host.sleep(LAST_EVENTS_GRACE_MS);
216
+ continue;
217
+ }
218
+ throw new DeployError(`run ${runId} ended without its last event (stopped at once by a second signal, killed, or out of memory)`, [], 'run-vanished');
219
+ }
220
+ if (alive)
221
+ quietSince = undefined;
222
+ else {
223
+ quietSince ??= host.now().getTime();
224
+ if (host.now().getTime() - quietSince >= VANISH_GRACE_MS) {
225
+ throw new DeployError(`run ${runId} is gone without its last event (stopped at once by a second signal, killed, or out of memory)`, [], 'run-vanished');
226
+ }
227
+ }
228
+ await host.sleep(ATTACH_POLL_MS);
229
+ }
230
+ }
231
+ /** The lock names this run, held by a live process on this host. */
232
+ async function runAlive(host, stateDir, runId) {
233
+ const lock = await readLock(host, stateDir);
234
+ const holder = lock?.holder;
235
+ return Boolean(holder && holder.runId === runId && holder.host === host.hostname() && host.processAlive(holder.pid));
236
+ }
237
+ // ── cancel ─────────────────────────────────────────────────────────────────
238
+ /**
239
+ * SIGTERM to the deploy holding the lock for `runId` (RFC 0008 §8.5) — only
240
+ * when its runId, host, a live pid and its own argv (`--run-id=<id>`, from
241
+ * /proc) all say it is that run: a recycled pid is never signalled. Where the
242
+ * argv cannot be read (not Linux), refused. A second cancel is the second
243
+ * signal: the run stops at once. With `firstOnly`, a run already cancelled
244
+ * once (from anywhere: the marker is on the server) is refused
245
+ * (`already-cancelled`) and not signalled — a client that asked only for the
246
+ * mild first cancel never sends the immediate second one by surprise.
247
+ */
248
+ export async function cancel(host, stateDir, runId, options = {}) {
249
+ if (!RUN_ID.test(runId))
250
+ throw new DeployError(`"${runId}" is not a run id`, [], 'usage');
251
+ if (!host.kill || !host.processCmdline)
252
+ throw new DeployError('cancel needs a host that can signal a process and read its argv', [], 'unsupported');
253
+ const holder = (await readLock(host, stateDir))?.holder;
254
+ if (!holder || holder.runId !== runId || holder.host !== host.hostname() || !host.processAlive(holder.pid)) {
255
+ throw new DeployError(`no running deploy holds the lock for run ${runId}`, [], 'not-found');
256
+ }
257
+ const argv = await host.processCmdline(holder.pid);
258
+ if (argv === undefined)
259
+ throw new DeployError(`cannot read the argv of pid ${holder.pid} (no /proc): its identity cannot be checked, so it is not signalled`, [], 'unsupported');
260
+ // A detached run carries its id in its argv; an attended one does not, and stops with its SSH session.
261
+ if (!argv.includes(`--run-id=${runId}`)) {
262
+ throw new DeployError(`pid ${holder.pid} does not carry --run-id=${runId} in its command line: not signalled`, [], 'not-found', 'only a detached run (run --detach) can be cancelled; an attended run stops when its SSH session ends');
263
+ }
264
+ await ensureRunsDir(host, stateDir);
265
+ const first = await host.createExclusive(cancelMarker(stateDir, runId), `${host.now().toISOString()}\n`, 0o600);
266
+ if (!first && options.firstOnly) {
267
+ throw new DeployError(`run ${runId} was already cancelled once: another cancel is the second signal, which stops it at once, mid-step — not sent (--first-only)`, [], 'already-cancelled', `cancel ${runId} again without --first-only to stop it at once (a migration may be left half-applied)`);
268
+ }
269
+ host.kill(holder.pid, 'SIGTERM');
270
+ return { pid: holder.pid, second: !first };
271
+ }
272
+ /** The complete, valid events a run log holds now (up to 1 MiB): what the detaching parent waits on. */
273
+ export async function scanRunLog(host, path) {
274
+ const range = await readRange(host, path, 0, 1024 * 1024);
275
+ const text = Buffer.from(range.data).toString('utf8');
276
+ const complete = text.slice(0, text.lastIndexOf('\n') + 1);
277
+ const events = [];
278
+ for (const line of complete.split('\n')) {
279
+ if (!line)
280
+ continue;
281
+ const parsed = parseEvent(line);
282
+ if (!parsed.ok)
283
+ throw new DeployError(`run log corrupt: ${parsed.error}`, [], 'failed');
284
+ events.push(parsed.value);
285
+ }
286
+ return events;
287
+ }
package/dist/state.d.ts CHANGED
@@ -1,20 +1,33 @@
1
1
  import type { DeployContext } from './context.js';
2
- /** One line per release in `<stateDir>/releases.json` (RFC 0006 §8). */
3
- export interface Release {
4
- sha: string;
5
- previous?: string;
6
- at: string;
7
- user: string;
8
- status: 'ok' | 'rolled-back' | 'failed' | 'public-unreachable';
9
- /** Migration directories this release applied for the first time. */
10
- migrations: string[];
11
- backup?: string;
12
- note?: string;
13
- }
2
+ import type { Hold, Release } from './protocol.js';
3
+ export type { Hold, Release } from './protocol.js';
14
4
  export declare const releasesFile: (ctx: DeployContext) => string;
5
+ /**
6
+ * The history, from `<stateDir>/releases.json` — or, the first time after
7
+ * `install` created `/var/lib/basalt/<app>`, from the checkout's
8
+ * `.basalt/releases.json` it was kept in before (moved by the next record,
9
+ * as the app user: root never copies a file the app user can point anywhere).
10
+ */
15
11
  export declare function readReleases(ctx: DeployContext): Promise<Release[]>;
12
+ /** Appends a release (stamped with the command's audit fields) — under the deploy lock, so no write is lost. */
16
13
  export declare function recordRelease(ctx: DeployContext, release: Release): Promise<void>;
17
- /** The last release that ended healthy, other than `sha`. */
14
+ /**
15
+ * The last release that ended healthy, other than `sha` — and not a commit
16
+ * that failed its health check AFTER that (a rollback onto it that did not
17
+ * answer, or a redeploy of it that was rolled back).
18
+ */
18
19
  export declare function lastGood(releases: Release[], except: string): Release | undefined;
20
+ /**
21
+ * With no healthy release on record: the commit `current` was deployed over
22
+ * — from a release of `current` itself, never from a rollback's record (its
23
+ * `previous` is the commit rolled away from), and never a commit recorded
24
+ * unhealthy. `undefined` when there is none: the caller asks for `--to`.
25
+ */
26
+ export declare function deployedOver(releases: Release[], current: string): string | undefined;
27
+ export declare const holdFile: (ctx: DeployContext) => string;
28
+ /** The hold — from `<stateDir>/hold.json`, else (after `install`) the checkout's `.basalt/hold.json`, like the release history. */
29
+ export declare function readHold(ctx: DeployContext): Promise<Hold | undefined>;
30
+ export declare function writeHold(ctx: DeployContext, hold: Hold): Promise<void>;
31
+ export declare function clearHold(ctx: DeployContext): Promise<void>;
19
32
  /** Migration directory names among changed paths (`…/migrations/<name>/migration.sql`). */
20
33
  export declare function migrationNames(paths: string[]): string[];
package/dist/state.js CHANGED
@@ -1,8 +1,16 @@
1
1
  import { join } from 'node:path';
2
+ import { syslogRelease } from './audit.js';
2
3
  const KEEP = 100;
3
4
  export const releasesFile = (ctx) => join(ctx.stateDir, 'releases.json');
5
+ /**
6
+ * The history, from `<stateDir>/releases.json` — or, the first time after
7
+ * `install` created `/var/lib/basalt/<app>`, from the checkout's
8
+ * `.basalt/releases.json` it was kept in before (moved by the next record,
9
+ * as the app user: root never copies a file the app user can point anywhere).
10
+ */
4
11
  export async function readReleases(ctx) {
5
- const text = await ctx.host.readFile(releasesFile(ctx));
12
+ const legacy = join(ctx.dir, '.basalt', 'releases.json');
13
+ const text = (await ctx.host.readFile(releasesFile(ctx))) ?? (releasesFile(ctx) === legacy ? undefined : await ctx.host.readFile(legacy));
6
14
  if (!text)
7
15
  return [];
8
16
  try {
@@ -13,14 +21,70 @@ export async function readReleases(ctx) {
13
21
  return [];
14
22
  }
15
23
  }
24
+ /** Appends a release (stamped with the command's audit fields) — under the deploy lock, so no write is lost. */
16
25
  export async function recordRelease(ctx, release) {
17
- const releases = [...(await readReleases(ctx)), release].slice(-KEEP);
26
+ const stamped = { ...ctx.audit, ...release };
27
+ const releases = [...(await readReleases(ctx)), stamped].slice(-KEEP);
18
28
  await ctx.host.mkdir(ctx.stateDir, 0o700);
19
29
  await ctx.host.writeFile(releasesFile(ctx), `${JSON.stringify(releases, null, 2)}\n`, 0o600);
30
+ await syslogRelease(ctx, stamped);
20
31
  }
21
- /** The last release that ended healthy, other than `sha`. */
32
+ /** Statuses that say the commit's code did not answer when released. */
33
+ const UNHEALTHY = new Set(['rolled-back', 'rollback-unhealthy']);
34
+ /**
35
+ * The last release that ended healthy, other than `sha` — and not a commit
36
+ * that failed its health check AFTER that (a rollback onto it that did not
37
+ * answer, or a redeploy of it that was rolled back).
38
+ */
22
39
  export function lastGood(releases, except) {
23
- return [...releases].reverse().find((r) => r.status === 'ok' && r.sha !== except);
40
+ const unhealthy = new Set();
41
+ for (const release of [...releases].reverse()) {
42
+ if (UNHEALTHY.has(release.status)) {
43
+ unhealthy.add(release.sha);
44
+ continue;
45
+ }
46
+ if (release.status === 'ok' && release.sha !== except && !unhealthy.has(release.sha))
47
+ return release;
48
+ }
49
+ return undefined;
50
+ }
51
+ /**
52
+ * With no healthy release on record: the commit `current` was deployed over
53
+ * — from a release of `current` itself, never from a rollback's record (its
54
+ * `previous` is the commit rolled away from), and never a commit recorded
55
+ * unhealthy. `undefined` when there is none: the caller asks for `--to`.
56
+ */
57
+ export function deployedOver(releases, current) {
58
+ const own = [...releases].reverse().find((r) => r.sha === current && !UNHEALTHY.has(r.status));
59
+ const target = own?.previous;
60
+ if (!target || releases.some((r) => r.sha === target && UNHEALTHY.has(r.status)))
61
+ return undefined;
62
+ return target;
63
+ }
64
+ export const holdFile = (ctx) => join(ctx.stateDir, 'hold.json');
65
+ /** Where the hold was kept before `install` moved the state out of the checkout. */
66
+ const legacyHold = (ctx) => join(ctx.dir, '.basalt', 'hold.json');
67
+ /** The hold — from `<stateDir>/hold.json`, else (after `install`) the checkout's `.basalt/hold.json`, like the release history. */
68
+ export async function readHold(ctx) {
69
+ const text = (await ctx.host.readFile(holdFile(ctx))) ?? (holdFile(ctx) === legacyHold(ctx) ? undefined : await ctx.host.readFile(legacyHold(ctx)));
70
+ if (!text)
71
+ return undefined;
72
+ try {
73
+ const value = JSON.parse(text);
74
+ return typeof value.sha === 'string' ? { sha: value.sha, at: String(value.at ?? ''), actor: String(value.actor ?? ''), note: String(value.note ?? '') } : undefined;
75
+ }
76
+ catch {
77
+ return undefined;
78
+ }
79
+ }
80
+ export async function writeHold(ctx, hold) {
81
+ await ctx.host.mkdir(ctx.stateDir, 0o700);
82
+ await ctx.host.writeFile(holdFile(ctx), `${JSON.stringify(hold, null, 2)}\n`, 0o600);
83
+ }
84
+ export async function clearHold(ctx) {
85
+ for (const file of new Set([holdFile(ctx), legacyHold(ctx)]))
86
+ if (await ctx.host.exists(file))
87
+ await ctx.host.removeFile(file);
24
88
  }
25
89
  /** Migration directory names among changed paths (`…/migrations/<name>/migration.sql`). */
26
90
  export function migrationNames(paths) {
@@ -0,0 +1,63 @@
1
+ import type { Host } from './host.js';
2
+ /**
3
+ * The trust boundary between the app user and root (RFC 0006 §11.4).
4
+ *
5
+ * The app user can change its checkout: `deploy.config.ts`, `node_modules`,
6
+ * every file in the tree. Root therefore never runs any of it. `install`
7
+ * reads a data-only plan the app user wrote (`install-plan`), validates every
8
+ * field again with the patterns below, and writes only where the app user
9
+ * cannot plant a link: root-owned directories, or files opened with
10
+ * O_NOFOLLOW and changed through their descriptor.
11
+ */
12
+ /** A login name: what `useradd` accepts, never an option or a path. */
13
+ export declare const USER_NAME: RegExp;
14
+ /** Directory served by the proxy, relative to the checkout: inside it, never the checkout itself, never a dot directory. */
15
+ export declare function isWebRoot(value: unknown): value is string;
16
+ /** `/api`, `/api/v1/`: URL path segments, no dot segments, nothing a config file would parse. */
17
+ export declare const API_PREFIX: RegExp;
18
+ /** An on-demand TLS `ask` path on the app. */
19
+ export declare const ASK_PATH: RegExp;
20
+ /** A Let's Encrypt certificate name (`/etc/letsencrypt/live/<name>/`). */
21
+ export declare const CERT_NAME: RegExp;
22
+ /**
23
+ * Raw Caddy `extra`: no character that hides text on a terminal, and no
24
+ * `import` — a file the app user can change later would be configuration
25
+ * root loads without anyone seeing it again.
26
+ */
27
+ export declare function caddyExtraProblem(extra: unknown): string | undefined;
28
+ /**
29
+ * The managed vhost file name: the app's own (`<app>.conf`, `<app>-<x>.conf`),
30
+ * never one that sorts ahead of another site's or takes its name.
31
+ */
32
+ export declare function vhostFileProblem(app: string, vhost: unknown): string | undefined;
33
+ /** An absolute directory with no dot segments (`/etc/apache2`). */
34
+ export declare function isConfigRoot(value: unknown): value is string;
35
+ /**
36
+ * App names whose `/etc/<app>` is a system directory (or this tool's own
37
+ * `/etc/basalt`). `install` hands `/etc/<app>` to the app user when the env
38
+ * lives there: owning `/etc/systemd`, `/etc/ssh` or `/etc/apt` is root. The
39
+ * list is a first line; `install` also refuses a directory a Debian package
40
+ * ships, one another user owns, and asks before taking over one root made.
41
+ */
42
+ export declare const RESERVED_APP_NAMES: ReadonlySet<string>;
43
+ /**
44
+ * Where an env file may live: inside the checkout (relative, no `..`), or
45
+ * directly in `/etc/<app>/`. Never `/etc/environment`, never another app's
46
+ * directory — `install` hands these files to the app user.
47
+ */
48
+ export declare function envLocationProblem(app: string, file: string): string | undefined;
49
+ /**
50
+ * Every directory from `path` up to `/` is root's and writable by root only —
51
+ * so no other user can swap an entry under root while it writes there.
52
+ * Returns the first one that is not, or `undefined`.
53
+ */
54
+ export declare function untrustedAncestor(host: Host, path: string): Promise<string | undefined>;
55
+ /** Throws unless root alone controls `dir` and every directory above it. */
56
+ export declare function assertRootOwnedDir(host: Host, dir: string, what: string): Promise<void>;
57
+ /**
58
+ * The tool root is about to run: the node binary and this package's own
59
+ * files, each root's (after symlinks) in directories only root can write.
60
+ * `sudo node node_modules/@basaltkit/deploy/dist/bin.js` from the checkout
61
+ * fails this — that file is the app user's to change.
62
+ */
63
+ export declare function untrustedToolPaths(host: Host, paths: string[]): Promise<string[]>;
package/dist/trust.js ADDED
@@ -0,0 +1,159 @@
1
+ import { dirname, normalize } from 'node:path';
2
+ import { DeployError } from './context.js';
3
+ /**
4
+ * The trust boundary between the app user and root (RFC 0006 §11.4).
5
+ *
6
+ * The app user can change its checkout: `deploy.config.ts`, `node_modules`,
7
+ * every file in the tree. Root therefore never runs any of it. `install`
8
+ * reads a data-only plan the app user wrote (`install-plan`), validates every
9
+ * field again with the patterns below, and writes only where the app user
10
+ * cannot plant a link: root-owned directories, or files opened with
11
+ * O_NOFOLLOW and changed through their descriptor.
12
+ */
13
+ /** A login name: what `useradd` accepts, never an option or a path. */
14
+ export const USER_NAME = /^[a-z_][a-z0-9_-]{0,31}$/;
15
+ /** A path segment with no leading dot: never `.`, `..`, `.git`, `.env`, `.basalt`. */
16
+ const SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
17
+ /** Directory served by the proxy, relative to the checkout: inside it, never the checkout itself, never a dot directory. */
18
+ export function isWebRoot(value) {
19
+ if (typeof value !== 'string' || value.length > 200)
20
+ return false;
21
+ // `./web/dist` is `web/dist`; `.` and `./` stay refused (the checkout itself).
22
+ const relative = value.replace(/^(\.\/)+/, '').replace(/\/$/, '');
23
+ return relative.length > 0 && relative.split('/').every((segment) => SEGMENT.test(segment));
24
+ }
25
+ /** `/api`, `/api/v1/`: URL path segments, no dot segments, nothing a config file would parse. */
26
+ export const API_PREFIX = /^(\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)+\/?$/;
27
+ /** An on-demand TLS `ask` path on the app. */
28
+ export const ASK_PATH = /^(\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)+$/;
29
+ /** A Let's Encrypt certificate name (`/etc/letsencrypt/live/<name>/`). */
30
+ export const CERT_NAME = /^[A-Za-z0-9][A-Za-z0-9-]*(\.[A-Za-z0-9-]+)*$/;
31
+ /**
32
+ * Characters a terminal acts on instead of showing (CR, ESC and the C1 CSI,
33
+ * line separators, bidirectional overrides): `install` shows raw Caddy
34
+ * `extra` before root writes it, and what is shown must be what is written.
35
+ */
36
+ const HIDDEN = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/;
37
+ /**
38
+ * Raw Caddy `extra`: no character that hides text on a terminal, and no
39
+ * `import` — a file the app user can change later would be configuration
40
+ * root loads without anyone seeing it again.
41
+ */
42
+ export function caddyExtraProblem(extra) {
43
+ if (typeof extra !== 'string' || extra.length > 16_384)
44
+ return 'must be a string (at most 16 KiB)';
45
+ const hidden = HIDDEN.exec(extra);
46
+ if (hidden)
47
+ return `holds a control or direction character (U+${(hidden[0].codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, '0')}) — tabs and newlines only`;
48
+ if (/^\s*import(\s|$)/m.test(extra))
49
+ return 'may not `import` a file: root would load whatever that file says later, unseen';
50
+ return undefined;
51
+ }
52
+ /**
53
+ * The managed vhost file name: the app's own (`<app>.conf`, `<app>-<x>.conf`),
54
+ * never one that sorts ahead of another site's or takes its name.
55
+ */
56
+ export function vhostFileProblem(app, vhost) {
57
+ if (typeof vhost !== 'string' || !/^[a-z0-9][a-z0-9.-]*\.conf$/.test(vhost))
58
+ return 'must be a plain *.conf file name';
59
+ if (vhost !== `${app}.conf` && !vhost.startsWith(`${app}-`) && !vhost.startsWith(`${app}.`))
60
+ return `must be ${app}.conf or start with "${app}-" — the app's own file`;
61
+ return undefined;
62
+ }
63
+ /** An absolute directory with no dot segments (`/etc/apache2`). */
64
+ export function isConfigRoot(value) {
65
+ if (typeof value !== 'string' || !value.startsWith('/') || value.length > 200)
66
+ return false;
67
+ return value.slice(1).split('/').every((segment) => SEGMENT.test(segment));
68
+ }
69
+ /**
70
+ * App names whose `/etc/<app>` is a system directory (or this tool's own
71
+ * `/etc/basalt`). `install` hands `/etc/<app>` to the app user when the env
72
+ * lives there: owning `/etc/systemd`, `/etc/ssh` or `/etc/apt` is root. The
73
+ * list is a first line; `install` also refuses a directory a Debian package
74
+ * ships, one another user owns, and asks before taking over one root made.
75
+ */
76
+ export const RESERVED_APP_NAMES = new Set([
77
+ 'basalt', 'basaltkit', 'alternatives', 'apache2', 'apparmor', 'apt', 'bash-completion', 'bind', 'ca-certificates', 'caddy', 'cloud', 'containerd',
78
+ 'cron', 'cryptsetup-initramfs', 'dbus-1', 'default', 'dhcp', 'docker', 'dpkg', 'fail2ban', 'fonts', 'gnupg', 'groff', 'grub', 'gss', 'init', 'initramfs-tools',
79
+ 'iproute2', 'iptables', 'kernel', 'ldap', 'letsencrypt', 'libvirt', 'logcheck', 'logrotate', 'lvm', 'mysql', 'netplan', 'network', 'networkd-dispatcher', 'nftables', 'nginx',
80
+ 'node', 'nodejs', 'npm', 'openvpn', 'opt', 'pam', 'php', 'pki', 'pm2', 'polkit-1', 'postfix', 'postgresql', 'postgresql-common', 'ppp', 'profile', 'python3', 'redis',
81
+ 'resolvconf', 'rsyslog', 'security', 'selinux', 'skel', 'snap', 'ssh', 'ssl', 'sudo', 'sysctl', 'systemd', 'terminfo', 'tmpfiles', 'udev', 'ufw', 'update-motd',
82
+ 'vim', 'wireguard', 'xdg',
83
+ ]);
84
+ /** An env file name in `/etc/<app>/`. */
85
+ const ENV_NAME = /^[A-Za-z0-9_.][A-Za-z0-9._-]*$/;
86
+ /**
87
+ * Where an env file may live: inside the checkout (relative, no `..`), or
88
+ * directly in `/etc/<app>/`. Never `/etc/environment`, never another app's
89
+ * directory — `install` hands these files to the app user.
90
+ */
91
+ export function envLocationProblem(app, file) {
92
+ if (file.startsWith('/')) {
93
+ if (RESERVED_APP_NAMES.has(app))
94
+ return `"${file}": /etc/${app} is a system directory — keep the env inside the checkout, or name the app something else`;
95
+ const name = file.slice(`/etc/${app}/`.length);
96
+ if (file.startsWith(`/etc/${app}/`) && ENV_NAME.test(name) && name !== '.' && name !== '..' && normalize(file) === file)
97
+ return undefined;
98
+ return `"${file}" must be inside the checkout or directly in /etc/${app}/ (install gives it to the deploy user)`;
99
+ }
100
+ if (file.length === 0 || file.includes('\0') || file.split('/').some((segment) => segment === '..' || segment === '')) {
101
+ return `"${file}" must stay inside the checkout (no "..")`;
102
+ }
103
+ return undefined;
104
+ }
105
+ /** Owned by root, and nobody else can write it (a world-writable sticky directory is fine: nobody can replace root's entries). */
106
+ function rootOnly(stat) {
107
+ if (stat.uid !== 0 || stat.mode === undefined)
108
+ return false;
109
+ if ((stat.mode & 0o020) !== 0 && stat.gid !== 0)
110
+ return false;
111
+ if ((stat.mode & 0o002) !== 0 && !(stat.kind === 'dir' && (stat.mode & 0o1000) !== 0))
112
+ return false;
113
+ return true;
114
+ }
115
+ /**
116
+ * Every directory from `path` up to `/` is root's and writable by root only —
117
+ * so no other user can swap an entry under root while it writes there.
118
+ * Returns the first one that is not, or `undefined`.
119
+ */
120
+ export async function untrustedAncestor(host, path) {
121
+ for (let dir = path;; dir = dirname(dir)) {
122
+ const stat = await host.stat(dir);
123
+ if (!stat || stat.kind !== 'dir' || !rootOnly(stat))
124
+ return dir;
125
+ if (dir === '/')
126
+ return undefined;
127
+ }
128
+ }
129
+ /** Throws unless root alone controls `dir` and every directory above it. */
130
+ export async function assertRootOwnedDir(host, dir, what) {
131
+ const bad = await untrustedAncestor(host, dir);
132
+ if (bad)
133
+ throw new DeployError(`${what}: ${bad} is not a directory only root can write — root does not write under a path another user can change`);
134
+ }
135
+ /**
136
+ * The tool root is about to run: the node binary and this package's own
137
+ * files, each root's (after symlinks) in directories only root can write.
138
+ * `sudo node node_modules/@basaltkit/deploy/dist/bin.js` from the checkout
139
+ * fails this — that file is the app user's to change.
140
+ */
141
+ export async function untrustedToolPaths(host, paths) {
142
+ const problems = [];
143
+ for (const path of paths) {
144
+ const real = await host.realpath(path);
145
+ if (!real) {
146
+ problems.push(`${path} (not found)`);
147
+ continue;
148
+ }
149
+ const stat = await host.stat(real);
150
+ if (!stat || !rootOnly(stat)) {
151
+ problems.push(`${real} (owned by uid ${stat?.uid ?? '?'}, or writable by others)`);
152
+ continue;
153
+ }
154
+ const bad = await untrustedAncestor(host, dirname(real));
155
+ if (bad)
156
+ problems.push(`${real} (its directory ${bad} is not root's alone)`);
157
+ }
158
+ return problems;
159
+ }
@@ -0,0 +1,2 @@
1
+ /** This package's own version (its package.json, next to dist/): what the printed root commands pin. */
2
+ export declare const VERSION: string;
@@ -0,0 +1,10 @@
1
+ import { readFileSync } from 'node:fs';
2
+ /** This package's own version (its package.json, next to dist/): what the printed root commands pin. */
3
+ export const VERSION = (() => {
4
+ try {
5
+ return String(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version ?? '0.0.0');
6
+ }
7
+ catch {
8
+ return '0.0.0';
9
+ }
10
+ })();