@buffcore/cli 0.8.47 → 0.8.48

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 (93) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/commands/build/server-text.en.d.ts +5 -0
  3. package/dist/commands/build/server-text.en.js +5 -0
  4. package/dist/commands/build/server-text.js +5 -0
  5. package/dist/commands/build/server.d.ts +4 -0
  6. package/dist/commands/build/server.js +10 -1
  7. package/dist/commands/change-merge.d.ts +2 -2
  8. package/dist/commands/dev.d.ts +9 -2
  9. package/dist/commands/dev.js +24 -5
  10. package/dist/commands/hardening.d.ts +3 -0
  11. package/dist/commands/hardening.en.d.ts +3 -0
  12. package/dist/commands/hardening.en.js +3 -0
  13. package/dist/commands/hardening.es.d.ts +2 -0
  14. package/dist/commands/hardening.es.js +3 -0
  15. package/dist/commands/hardening.js +19 -0
  16. package/dist/commands/prototype/comp-record.d.ts +5 -0
  17. package/dist/commands/prototype/comp-record.js +22 -0
  18. package/dist/commands/server/build.d.ts +2 -1
  19. package/dist/commands/server/build.js +10 -2
  20. package/dist/commands/server/deploy-local.d.ts +3 -0
  21. package/dist/commands/server/deploy-local.js +9 -0
  22. package/dist/commands/server/deploy-plan.d.ts +5 -0
  23. package/dist/commands/server/deploy-plan.js +56 -0
  24. package/dist/commands/server/deploy-result.d.ts +7 -0
  25. package/dist/commands/server/deploy-result.js +1 -0
  26. package/dist/commands/server/deploy-script.d.ts +2 -0
  27. package/dist/commands/server/deploy-script.js +3 -2
  28. package/dist/commands/server/deploy.d.ts +9 -6
  29. package/dist/commands/server/deploy.js +39 -61
  30. package/dist/commands/server/files.d.ts +9 -1
  31. package/dist/commands/server/files.js +25 -5
  32. package/dist/commands/server/image.d.ts +4 -2
  33. package/dist/commands/server/image.js +6 -5
  34. package/dist/commands/server/setup.js +4 -0
  35. package/dist/commands/server/system-packages.d.ts +29 -0
  36. package/dist/commands/server/system-packages.js +103 -0
  37. package/dist/commands/services/compose.d.ts +1 -1
  38. package/dist/commands/services/compose.js +5 -3
  39. package/dist/commands/ui/agents-route.js +2 -0
  40. package/dist/commands/ui/approval-authority.en.d.ts +1 -0
  41. package/dist/commands/ui/approval-authority.en.js +1 -0
  42. package/dist/commands/ui/approval-authority.es.d.ts +1 -0
  43. package/dist/commands/ui/approval-authority.es.js +1 -0
  44. package/dist/commands/ui/approval-authority.js +7 -2
  45. package/dist/commands/ui/approve.js +2 -4
  46. package/dist/commands/ui/autopilot-records.d.ts +2 -0
  47. package/dist/commands/ui/autopilot-records.js +5 -0
  48. package/dist/commands/ui/brand-approval.js +5 -1
  49. package/dist/commands/ui/chat/permissions.js +1 -1
  50. package/dist/commands/ui/chat/routes.js +4 -0
  51. package/dist/commands/ui/comp-approval.d.ts +14 -2
  52. package/dist/commands/ui/comp-approval.js +45 -8
  53. package/dist/commands/ui/level-route.js +3 -0
  54. package/dist/commands/ui/merge-authority.d.ts +4 -1
  55. package/dist/commands/ui/merge-authority.en.d.ts +4 -0
  56. package/dist/commands/ui/merge-authority.en.js +5 -1
  57. package/dist/commands/ui/merge-authority.es.d.ts +4 -0
  58. package/dist/commands/ui/merge-authority.es.js +5 -1
  59. package/dist/commands/ui/merge-authority.js +6 -3
  60. package/dist/commands/ui/merge-claims.d.ts +7 -0
  61. package/dist/commands/ui/merge-claims.js +21 -0
  62. package/dist/commands/ui/merge-delegation.js +8 -3
  63. package/dist/commands/ui/merge-hold-name.d.ts +5 -0
  64. package/dist/commands/ui/merge-hold-name.js +5 -0
  65. package/dist/commands/ui/merge-hold.d.ts +6 -1
  66. package/dist/commands/ui/merge-hold.js +23 -5
  67. package/dist/commands/ui/merge-publish-host.d.ts +1 -0
  68. package/dist/commands/ui/merge-publish-host.js +2 -2
  69. package/dist/commands/ui/merge-record.d.ts +2 -0
  70. package/dist/commands/ui/merge-record.js +1 -1
  71. package/dist/commands/ui/merge-route.js +17 -1
  72. package/dist/commands/ui/merge-settle.d.ts +32 -0
  73. package/dist/commands/ui/merge-settle.js +133 -0
  74. package/dist/commands/ui/merge-state.d.ts +5 -0
  75. package/dist/commands/ui/merge-state.js +7 -1
  76. package/dist/commands/ui/merge-withdraw.d.ts +9 -0
  77. package/dist/commands/ui/merge-withdraw.js +29 -0
  78. package/dist/commands/ui/plan-files.js +5 -2
  79. package/dist/commands/ui/plan-structure.js +5 -7
  80. package/dist/commands/ui/prototype-comp-route.d.ts +12 -3
  81. package/dist/commands/ui/prototype-comp-route.js +35 -17
  82. package/dist/commands/ui/real-file.d.ts +11 -0
  83. package/dist/commands/ui/real-file.js +84 -0
  84. package/dist/commands/ui/save-route.js +4 -1
  85. package/dist/commands/ui/server.d.ts +1 -0
  86. package/dist/commands/ui/server.js +1 -0
  87. package/dist/commands/ui/studio-state.d.ts +1 -0
  88. package/dist/commands/ui/studio-versions.js +19 -3
  89. package/dist/ui/page.js +79 -79
  90. package/docs/PROTOTYPE.md +13 -0
  91. package/docs/WORKBENCH.md +30 -0
  92. package/package.json +11 -11
  93. package/skills/ape-deploy/SKILL.md +4 -2
@@ -1,76 +1,21 @@
1
- // `ape deploy <ssh destination>`: the product's image (and each container's with a Dockerfile)
2
- // built from the commit, loaded on a server `ape server setup` prepared, then the server's steps: a backup, migrations (BuffCore's first),
3
- // restart and health, and the previous image again when the new one fails its health check
4
- // (ARCHITECTURE's environments and deployment). A server already running this exact image is left
5
- // as it is. The image is `image.ts`; the steps on the server, `deploy-script.ts`; `--local`,
6
- // `deploy-local.ts`; how it ends, `deploy-result.ts`.
7
- import { existsSync, readFileSync } from 'node:fs';
8
1
  import { homedir } from 'node:os';
9
- import { dirname, join, relative } from 'node:path';
10
2
  import { findRoot, loadProduct } from '../../project.js';
11
3
  import { t as buildText } from '../build/server-text.js';
12
- import { apiFolder } from '../dev.js';
13
4
  import { refuseUnreviewed } from '../extension/catalog-commands.js';
14
5
  import { printIntakeWarnings } from '../intake-text.js';
15
- import { surfaceDir } from '../prototype/export.js';
16
6
  import { buildImages, local } from './build.js';
17
7
  import { checkDeploy } from './deploy-chain.js';
18
8
  import { DeployRefused, outcomeOf, tracking } from './deploy-result.js';
19
9
  import { deployScript, healthScript, imageIdScript, LOAD_COMMAND, parseState, stateScript, } from './deploy-script.js';
20
10
  import { intakeWarnings } from './deploy-warnings.js';
21
- import { stackDir } from './files.js';
11
+ import { hardeningMark, stackDir } from './files.js';
22
12
  import { dockerfile } from './image.js';
13
+ import { imageIdOf } from './image-id.js';
23
14
  import { SCRIPT_COMMAND } from './script.js';
24
15
  import { ssh, sshRead } from './ssh.js';
25
- const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'));
26
- /** The folder with the lockfile: the product's, or the repository the product sits in. */
27
- export function workspaceOf(root) {
28
- for (let dir = root;; dir = dirname(dir)) {
29
- if (existsSync(join(dir, 'pnpm-lock.yaml')))
30
- return dir;
31
- if (dirname(dir) === dir)
32
- throw new Error(`No pnpm-lock.yaml in ${root} or above.`);
33
- }
34
- }
35
- /** The image's plan: where the product, its API, its console and its web app are, and what they're called. */
36
- export function imagePlan(root, workspace, site) {
37
- const from = (dir) => relative(workspace, dir).replaceAll('\\', '/') || '.';
38
- const product = from(root);
39
- const api = from(join(root, apiFolder(root)));
40
- const admin = surfaceDir(root, 'admin');
41
- if (!admin)
42
- throw new Error(`No admin console in ${root} (admin/ or apps/admin/).`);
43
- const app = surfaceDir(root, 'app');
44
- const apiPackage = readJson(join(workspace, api, 'package.json'));
45
- if (!apiPackage.dependencies?.['@buffcore/cli']) {
46
- throw new Error(`${api}/package.json must list @buffcore/cli in its dependencies: the server runs one-off commands with its ape (Node runs the API and processes), and the image installs only what the API's package depends on.`);
47
- }
48
- const pnpm = /^pnpm@(\d+\.\d+\.\d+)/.exec(readJson(join(workspace, 'package.json')).packageManager ?? '');
49
- if (!pnpm)
50
- throw new Error(`${workspace}/package.json must name pnpm in packageManager.`);
51
- const names = {
52
- product: readJson(join(root, 'package.json')).name,
53
- api: apiPackage.name,
54
- admin: readJson(join(admin, 'package.json')).name,
55
- app: app && readJson(join(app, 'package.json')).name,
56
- };
57
- if (!names.product || !names.api || !names.admin || (app && !names.app))
58
- throw new Error("The product's, API's, console's and web app's package.json need names.");
59
- return {
60
- ...site,
61
- pnpm: pnpm[1],
62
- dirs: { product, api, admin: from(admin), ...(app ? { app: from(app) } : {}) },
63
- packages: {
64
- product: names.product,
65
- api: names.api,
66
- admin: names.admin,
67
- ...(names.app ? { app: names.app } : {}),
68
- },
69
- ...(apiPackage.dependencies?.['@buffcore/cli']?.startsWith('workspace:')
70
- ? { sources: true }
71
- : {}),
72
- };
73
- }
16
+ import { packageVersions, systemPackagesOf } from './system-packages.js';
17
+ import { imagePlan, workspaceOf } from './deploy-plan.js';
18
+ export { imagePlan, workspaceOf };
74
19
  /** The stack's own services, which setup adds beside the product's. */
75
20
  const STACK = ['postgres', 'redis', 'caddy', 'ape'];
76
21
  /**
@@ -91,6 +36,10 @@ export function checkStack(product, state, destination) {
91
36
  ];
92
37
  throw new DeployRefused(`${destination} runs other processes than buffcore.config.ts declares (${differ.join('; ')}): run ape server setup there again, then deploy. Nothing was changed.`);
93
38
  }
39
+ // A file from before hardening has no mark: it lacks the core-file limit every product now gets.
40
+ const wanted = hardeningMark(product.hardening);
41
+ if ((state.hardening ?? '') !== wanted)
42
+ throw new DeployRefused(`${destination}'s compose file was written for ${state.hardening ? `other hardening (${state.hardening})` : 'a BuffCore without hardening'}, and buffcore.config.ts now asks for ${wanted}: run ape server setup there again, then deploy. Nothing was changed.`);
94
43
  }
95
44
  /**
96
45
  * `ape deploy`. Read the server, build if it runs something else, ship, then the server's steps.
@@ -110,6 +59,7 @@ export async function deploy(destination, options, deps = {}) {
110
59
  log(`Deploying ${name} at ${commit.sha.slice(0, 12)} to ${destination} (${state.api}).`);
111
60
  if (state.running === docker.source) {
112
61
  log(`${destination} already runs this image: nothing to change.`);
62
+ result.systemPackages = await runningPackages(`${name}:${docker.source}`, name, plan, deps, ask);
113
63
  await run(SCRIPT_COMMAND, healthScript(name, state));
114
64
  printIntakeWarnings(result.warnings, log);
115
65
  return end({ result: 'unchanged' });
@@ -120,7 +70,9 @@ export async function deploy(destination, options, deps = {}) {
120
70
  const { tags, built } = await buildImages(here, where, product, docker, {
121
71
  json: Boolean(options.json),
122
72
  log,
73
+ packages: plan.systemPackages,
123
74
  });
75
+ result.systemPackages = await packageVersions(tags[0], plan.systemPackages ?? [], where.platform, deps.readPackages);
124
76
  log(`Sending the image${tags.length > 1 ? 's' : ''} to ${destination}...`);
125
77
  await run(LOAD_COMMAND, here.save(tags));
126
78
  const tag = tags[0];
@@ -158,7 +110,14 @@ async function prepareDeploy(destination, options, deps, result) {
158
110
  const ask = (deps.read ?? sshRead)(destination, identity);
159
111
  const state = parseState(await ask(SCRIPT_COMMAND, stateScript(name)), destination, name);
160
112
  checkStack(product, state, destination);
161
- const plan = imagePlan(root, workspace, { name, commit: commit.sha });
113
+ let systemPackages;
114
+ try {
115
+ systemPackages = systemPackagesOf(product);
116
+ }
117
+ catch (error) {
118
+ throw new DeployRefused(error.message);
119
+ }
120
+ const plan = imagePlan(root, workspace, { name, commit: commit.sha, systemPackages });
162
121
  if (plan.dirs.app && !state.web)
163
122
  throw new DeployRefused(`${destination}'s web server doesn't serve the web app yet (setup before ape deploy shipped it): run ape server setup there again, then deploy. Nothing was changed.`);
164
123
  return { product, workspace, commit, identity, ask, state, plan };
@@ -177,3 +136,22 @@ export function doneLines(destination, name, state, identity, web = false) {
177
136
  ]),
178
137
  ];
179
138
  }
139
+ /**
140
+ * An unchanged deploy's versions: the image this computer built for the server last time, only
141
+ * when it is still here and its ID is the one the server runs (a rebuild of the same source may
142
+ * hold newer packages); null otherwise, never a guess.
143
+ */
144
+ async function runningPackages(image, name, plan, deps, ask) {
145
+ const names = plan.systemPackages ?? [];
146
+ if (!names.length)
147
+ return {};
148
+ try {
149
+ const running = (await ask(SCRIPT_COMMAND, imageIdScript(name))).trim();
150
+ if (!running || running !== (await imageIdOf(image, deps.readImage)))
151
+ return null;
152
+ return await packageVersions(image, names, undefined, deps.readPackages);
153
+ }
154
+ catch {
155
+ return null;
156
+ }
157
+ }
@@ -1,4 +1,4 @@
1
- import type { ContainerProcess, ProcessSize } from '@buffcore/config';
1
+ import { type ContainerProcess, type Hardening, type ProcessSize } from '@buffcore/config';
2
2
  /** Where the API listens on the server, on 127.0.0.1 only: Caddy is the way in. */
3
3
  export declare const API_PORT = 4300;
4
4
  /** The web app's port at the server's address when the settings file names no `APE_APP_URL`. */
@@ -37,6 +37,8 @@ export interface ServerPlan {
37
37
  web?: boolean;
38
38
  /** The web app's origin when it isn't the console's: the console shows it in a preview frame. */
39
39
  appOrigin?: string;
40
+ /** `hardening` from buffcore.config.ts: the debug guard, and core dumps (off unless `coreDumps`). */
41
+ hardening?: Hardening;
40
42
  /** What the console reads when it starts (`/console.json`): its addresses and environment. */
41
43
  console?: {
42
44
  apiUrl: string;
@@ -44,6 +46,12 @@ export interface ServerPlan {
44
46
  environment: string;
45
47
  };
46
48
  }
49
+ /**
50
+ * The `hardening` a compose file was written for, on its own comment line (`# ape.hardening: `):
51
+ * deploy refuses a server whose file says otherwise, or nothing (one from before hardening).
52
+ */
53
+ export declare const hardeningMark: (h: Hardening | undefined) => string;
54
+ export declare const HARDENING_LINE = "# ape.hardening: ";
47
55
  /** The stack's folder on the server. */
48
56
  export declare const stackDir: (name: string) => string;
49
57
  /** Shell lines printing `other=<name>` for each other product's stack on the server. */
@@ -1,3 +1,8 @@
1
+ // What `ape server setup` writes on a server, decided here and nowhere else: the stack's compose
2
+ // file, the backup cron and the settings file only root reads (Caddy's configuration is
3
+ // `caddyfile.ts`). Pure functions of the plan, so a test reads exactly what a server gets. The
4
+ // product's containers' services are `../services/compose.ts`'s, the same as in development.
5
+ import { refuseDebugImport, } from '@buffcore/config';
1
6
  import { containerServices } from '../services/compose.js';
2
7
  /** Where the API listens on the server, on 127.0.0.1 only: Caddy is the way in. */
3
8
  export const API_PORT = 4300;
@@ -10,6 +15,12 @@ export const STOP_GRACE = '30s';
10
15
  * digest, so the server runs exactly this one.
11
16
  */
12
17
  export const CADDY_IMAGE = 'caddy:2.11.4-alpine@sha256:6aeddd44c3078b0f9a35206472a11420648a79c184603ef95957d0a20044cb2b';
18
+ /**
19
+ * The `hardening` a compose file was written for, on its own comment line (`# ape.hardening: `):
20
+ * deploy refuses a server whose file says otherwise, or nothing (one from before hardening).
21
+ */
22
+ export const hardeningMark = (h) => `refuseDebugOptions=${h?.refuseDebugOptions === true} coreDumps=${h?.coreDumps === true}`;
23
+ export const HARDENING_LINE = '# ape.hardening: ';
13
24
  /** The stack's folder on the server. */
14
25
  export const stackDir = (name) => `/srv/${name}`;
15
26
  /** Shell lines printing `other=<name>` for each other product's stack on the server. */
@@ -32,12 +43,15 @@ const list = (items) => `[${items.map((item) => JSON.stringify(item)).join(', ')
32
43
  * the product's TypeScript as it is (its built-in type stripping); BuffCore's packages are JavaScript
33
44
  * (in BuffCore's own repository, TypeScript the image runs through tsx: `image.ts`).
34
45
  */
35
- function appService({ name, entry, size, count = 1 }) {
46
+ function appService({ name, entry, size, count = 1 }, refuseDebug) {
36
47
  const health = `fetch('http://127.0.0.1:${API_PORT}/health').then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1))`;
37
48
  return [
38
49
  ` ${name}:`,
39
50
  ' <<: *app',
40
- ` command: ${list(['node', entry])}`,
51
+ // With hardening.refuseDebugOptions, a module that needs no file refuses Node's debugging
52
+ // and dump options before the entry loads (`debug-options.ts` in @buffcore/config).
53
+ // --disable-sigusr1: no signal turns the inspector on in a running process either.
54
+ ` command: ${list(['node', ...(refuseDebug ? ['--disable-sigusr1', `--import=${refuseDebugImport()}`] : []), entry])}`,
41
55
  // A declared size is its limit; without one it runs unlimited, as before sizes.
42
56
  ...(size ? [` cpus: ${size.cpus}`, ` mem_limit: ${size.memoryMb}m`] : []),
43
57
  ...(count > 1 ? [` scale: ${count}`] : []),
@@ -56,12 +70,15 @@ function appService({ name, entry, size, count = 1 }) {
56
70
  export function composeFile(plan) {
57
71
  const { name, images } = plan;
58
72
  const db = dbName(name);
59
- const containers = containerServices(name, plan.containers, 'server');
73
+ const coreDumps = plan.hardening?.coreDumps === true;
74
+ const containers = containerServices(name, plan.containers, 'server', coreDumps);
75
+ const refuseDebug = plan.hardening?.refuseDebugOptions === true;
60
76
  return `# ${name}'s production stack, from ape server setup (run it again to change this file).
61
77
  # Every service shares the host's network and listens on 127.0.0.1 only, except Caddy on 80 and
62
78
  # 443, so the firewall alone decides what reaches the server; the product's containers have a
63
79
  # network of their own and publish their port on 127.0.0.1 only. The settings and secrets are in
64
80
  # .env beside this file, which only root reads; the containers get none of them.
81
+ ${HARDENING_LINE}${hardeningMark(plan.hardening)}
65
82
  name: ${name}
66
83
 
67
84
  x-logs: &logs
@@ -81,7 +98,10 @@ x-app: &app
81
98
  network_mode: host
82
99
  env_file: .env
83
100
  restart: unless-stopped
84
- depends_on:
101
+ ${coreDumps
102
+ ? ''
103
+ : ` ulimits: { core: 0 } # a crash writes no core dump of the process's memory (hardening.coreDumps)
104
+ `} depends_on:
85
105
  postgres: { condition: service_healthy }
86
106
  redis: { condition: service_healthy }
87
107
 
@@ -121,7 +141,7 @@ services:
121
141
  volumes: [./Caddyfile:/etc/caddy/Caddyfile:ro, ./admin:/srv/admin:ro, ./app:/srv/app:ro, caddy:/data]
122
142
  restart: unless-stopped
123
143
 
124
- ${[...plan.services.map(appService), ...containers.services].join('\n\n')}
144
+ ${[...plan.services.map((s) => appService(s, refuseDebug)), ...containers.services].join('\n\n')}
125
145
 
126
146
  # One-off commands, run by root only: docker compose run --rm ape <command> (the backup cron,
127
147
  # ape deploy's migrations). Backups run pg_dump in the Postgres image above, so that versions
@@ -42,10 +42,12 @@ export interface ImagePlan {
42
42
  * dependencies. A product installed from the registry runs BuffCore's built JavaScript.
43
43
  */
44
44
  sources?: boolean;
45
+ /** Debian packages the API's own programs need (`server.systemPackages`); none, no lines. */
46
+ systemPackages?: readonly string[];
45
47
  }
46
48
  /**
47
- * The Dockerfile and its source: a hash of everything the image is made from (the commit and the
48
- * versions above). The image carries it as a label, so deploy sees when the server
49
+ * The Dockerfile and its source: a hash of everything the image is made from (the commit, the
50
+ * versions above and the system packages). The image carries it as a label, so deploy sees when the server
49
51
  * already runs exactly this.
50
52
  */
51
53
  export declare function dockerfile(plan: ImagePlan): {
@@ -4,6 +4,7 @@
4
4
  // what the API's package depends on, and carries the admin console's files, and the web app's, for
5
5
  // the server to copy.
6
6
  import { createHash } from 'node:crypto';
7
+ import { packagesLabel, systemPackageLines } from './system-packages.js';
7
8
  /** Node 24.20.0, the newest 24 at least two weeks old when S32 was built, by its digest. */
8
9
  export const NODE_IMAGE = 'node:24.20.0-slim@sha256:ba849c60be29959425b8734d57b8b4b7d56f98edd9504c9af091d5281095a71e';
9
10
  /** The Docker CLI alone (backups run pg_dump in the Postgres image through the server's Docker). */
@@ -37,7 +38,7 @@ ${store}
37
38
  }
38
39
  /** The Dockerfile, without its label. */
39
40
  function body(plan) {
40
- const { name, commit, pnpm, dirs, packages, sources } = plan;
41
+ const { name, commit, pnpm, dirs, packages, sources, systemPackages } = plan;
41
42
  return `# ${name}'s image, from ape deploy: the commit ${commit}, built on the developer's computer and
42
43
  # loaded on the server, never pushed to a registry. Only what the API's package depends on is
43
44
  # installed; the admin console and the web app are built in stages of their own and only their
@@ -68,7 +69,7 @@ FROM ${NODE_IMAGE}
68
69
  # No package manager in a release: it installs nothing, and deploy refuses development tooling.
69
70
  RUN rm -rf /usr/local/lib/node_modules/npm /usr/local/lib/node_modules/corepack /opt/yarn-* \\
70
71
  && cd /usr/local/bin && rm -f npm npx corepack yarn yarnpkg
71
- COPY --from=${DOCKER_CLI_IMAGE} /usr/local/bin/docker /usr/local/bin/docker
72
+ ${systemPackageLines(systemPackages)}COPY --from=${DOCKER_CLI_IMAGE} /usr/local/bin/docker /usr/local/bin/docker
72
73
  COPY --from=api /src /app
73
74
  COPY --from=console /src/${dirs.admin}/dist ${CONSOLE_DIR}
74
75
  ${dirs.app ? `COPY --from=web ${WEB_DIR} ${WEB_DIR}\n` : ''}WORKDIR ${at('/app', dirs.product)}
@@ -78,15 +79,15 @@ USER node
78
79
  `;
79
80
  }
80
81
  /**
81
- * The Dockerfile and its source: a hash of everything the image is made from (the commit and the
82
- * versions above). The image carries it as a label, so deploy sees when the server
82
+ * The Dockerfile and its source: a hash of everything the image is made from (the commit, the
83
+ * versions above and the system packages). The image carries it as a label, so deploy sees when the server
83
84
  * already runs exactly this.
84
85
  */
85
86
  export function dockerfile(plan) {
86
87
  const text = body(plan);
87
88
  const source = createHash('sha256').update(text).digest('hex').slice(0, 16);
88
89
  return {
89
- text: `${text}LABEL ape.product="${plan.name}" ape.source="${source}"\n`,
90
+ text: `${text}LABEL ape.product="${plan.name}" ape.source="${source}"${packagesLabel(plan.systemPackages)}\n`,
90
91
  source,
91
92
  };
92
93
  }
@@ -14,6 +14,7 @@ import { coreEnvSchema, defineEnv, isContainer, isEnabled, } from '@buffcore/con
14
14
  import { backupKey } from '@buffcore/modules/ops';
15
15
  import { findRoot, loadProduct } from '../../project.js';
16
16
  import { apiFolder, composeFile } from '../dev.js';
17
+ import { refuseDebugStart } from '../hardening.js';
17
18
  import { surfaceDir } from '../prototype/export.js';
18
19
  import { containersOf } from '../services/compose.js';
19
20
  import { deployKey } from './approval.js';
@@ -117,6 +118,7 @@ export async function planFor(root, site, images = serviceImages) {
117
118
  services,
118
119
  ...(containers.length ? { containers } : {}),
119
120
  push: isEnabled(product, 'push'),
121
+ ...(product.hardening ? { hardening: product.hardening } : {}),
120
122
  ...(surfaceDir(root, 'app') ? { web: true } : {}),
121
123
  };
122
124
  }
@@ -129,6 +131,8 @@ export function settingsFor(path, plan) {
129
131
  throw new Error(`No ${path}: make it with the product's own settings and the bucket for uploads and backups, ${GET_A_BUCKET} Setup adds the secrets it can make.`);
130
132
  }
131
133
  const file = parseEnv(readFileSync(path, 'utf8'));
134
+ // The services read NODE_OPTIONS from this file before any code runs: refused before it is written.
135
+ refuseDebugStart(plan.hardening, { [path]: file.NODE_OPTIONS });
132
136
  const missing = BUCKET.filter((key) => !file[key]);
133
137
  if (missing.length)
134
138
  throw new Error(`${path} must name the bucket for uploads and backups (${missing.join(', ')} missing): ${GET_A_BUCKET}`);
@@ -0,0 +1,29 @@
1
+ import { type ProductConfig } from '@buffcore/config';
2
+ /** Runs `docker` with these arguments, no shell, and answers its output; tests stand in for it. */
3
+ export type PackageReader = (args: string[]) => string | Promise<string>;
4
+ /** The list, refused with a plain sentence when a name isn't a Debian package name. */
5
+ export declare function systemPackagesOf(product: Pick<ProductConfig, 'server'>): string[];
6
+ /** The image label that names the list, so a deploy that only has the image can read it. */
7
+ export declare const PACKAGES_LABEL = "ape.system-packages";
8
+ /**
9
+ * The Dockerfile's lines that install them, or nothing for none (the image stays byte-identical).
10
+ * Each name is checked again here: nothing reaches the shell line unchecked. apt-get takes a name
11
+ * that matches no package as a pattern, so each is then checked as installed by its exact name.
12
+ */
13
+ export declare function systemPackageLines(names?: readonly string[]): string;
14
+ /** The label's part for the list (` ape.system-packages="a b"`), nothing for none. */
15
+ export declare const packagesLabel: (names?: readonly string[]) => string;
16
+ /** The sentence added to a failed build when the image installs system packages. */
17
+ export declare const packagesFailed: (names: readonly string[]) => string;
18
+ /** dpkg-query's format (its own fields; a real tab and newline): `name<TAB>version` per line. */
19
+ export declare const FORMAT = "-f=${Package}\t${Version}\n";
20
+ /**
21
+ * Each listed package's installed version in the built image, as `dpkg-query -W` reads it
22
+ * (never pulled, without network, as the image's own user). None listed, no Docker call and `{}`.
23
+ */
24
+ export declare function packageVersions(image: string, names: readonly string[], platform?: string, read?: PackageReader): Promise<Record<string, string>>;
25
+ /**
26
+ * The versions in an image that only the image says what it holds (`ape deploy --local`): the
27
+ * list from its label, checked again, then `packageVersions`. No label, `{}`.
28
+ */
29
+ export declare function imagePackages(image: string, read?: PackageReader): Promise<Record<string, string>>;
@@ -0,0 +1,103 @@
1
+ // The product's system packages (`server.systemPackages` in buffcore.config.ts): checked here,
2
+ // installed in the image's last stage as root before it drops to the API's user, and their
3
+ // installed versions read back from the built image so the build and the deploy record them.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { SYSTEM_PACKAGE, serverProblems } from '@buffcore/config';
6
+ import { t } from '../build/server-text.js';
7
+ /** The list, refused with a plain sentence when a name isn't a Debian package name. */
8
+ export function systemPackagesOf(product) {
9
+ const problems = serverProblems(product.server);
10
+ if (problems.length)
11
+ throw new Error(t('build.server.packages', { problems: problems.join('; ') }));
12
+ return [...(product.server?.systemPackages ?? [])];
13
+ }
14
+ /** The image label that names the list, so a deploy that only has the image can read it. */
15
+ export const PACKAGES_LABEL = 'ape.system-packages';
16
+ /**
17
+ * The Dockerfile's lines that install them, or nothing for none (the image stays byte-identical).
18
+ * Each name is checked again here: nothing reaches the shell line unchecked. apt-get takes a name
19
+ * that matches no package as a pattern, so each is then checked as installed by its exact name.
20
+ */
21
+ export function systemPackageLines(names = []) {
22
+ if (!names.length)
23
+ return '';
24
+ systemPackagesOf({ server: { systemPackages: names } });
25
+ return `# The product's system packages (server.systemPackages in buffcore.config.ts), installed as
26
+ # root before the image drops to the API's user. One that can't be installed fails the build, as
27
+ # does one not installed by its exact name.
28
+ RUN apt-get update \\
29
+ && apt-get install -y --no-install-recommends ${names.join(' ')} \\
30
+ && for p in ${names.join(' ')}; do \\
31
+ [ "$(dpkg-query -W -f='\${db:Status-Status}' "$p" 2>/dev/null)" = installed ] \\
32
+ || { echo "ape: the system package $p is not installed by that exact name" >&2; exit 1; }; \\
33
+ done \\
34
+ && rm -rf /var/lib/apt/lists/*
35
+ `;
36
+ }
37
+ /** The label's part for the list (` ape.system-packages="a b"`), nothing for none. */
38
+ export const packagesLabel = (names = []) => names.length ? ` ${PACKAGES_LABEL}="${names.join(' ')}"` : '';
39
+ /** The sentence added to a failed build when the image installs system packages. */
40
+ export const packagesFailed = (names) => t('build.server.packagesFailed', { names: names.join(', ') });
41
+ /** dpkg-query's format (its own fields; a real tab and newline): `name<TAB>version` per line. */
42
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: dpkg-query's placeholders, passed as is.
43
+ export const FORMAT = '-f=${Package}\t${Version}\n';
44
+ /** Docker's answer, or an error carrying its own last line (Docker down, no such image). */
45
+ const readDocker = (args) => {
46
+ const run = spawnSync('docker', args, { encoding: 'utf8', timeout: 120_000 });
47
+ if (run.status === 0)
48
+ return run.stdout;
49
+ const said = `${run.stderr ?? ''}`.trim().split('\n').pop();
50
+ throw new Error(said || run.error?.message || `docker exited with ${run.status}`);
51
+ };
52
+ /**
53
+ * Each listed package's installed version in the built image, as `dpkg-query -W` reads it
54
+ * (never pulled, without network, as the image's own user). None listed, no Docker call and `{}`.
55
+ */
56
+ export async function packageVersions(image, names, platform, read = readDocker) {
57
+ if (!names.length)
58
+ return {};
59
+ const args = ['run', '--rm', '--pull=never', '--network', 'none'];
60
+ if (platform)
61
+ args.push('--platform', platform);
62
+ args.push('--entrypoint', 'dpkg-query', image, '-W', FORMAT, ...names);
63
+ let out;
64
+ try {
65
+ out = await read(args);
66
+ }
67
+ catch (error) {
68
+ const cause = error instanceof Error ? error.message : String(error);
69
+ throw new Error(t('build.server.versionsRun', { image, cause }));
70
+ }
71
+ const found = new Map(out
72
+ .split('\n')
73
+ .map((line) => line.trim().split('\t'))
74
+ .filter((pair) => pair.length === 2 && Boolean(pair[1])));
75
+ const versions = {};
76
+ for (const name of names) {
77
+ const version = found.get(name);
78
+ if (!version)
79
+ throw new Error(t('build.server.versionsMissing', { image, name }));
80
+ versions[name] = version;
81
+ }
82
+ return versions;
83
+ }
84
+ /**
85
+ * The versions in an image that only the image says what it holds (`ape deploy --local`): the
86
+ * list from its label, checked again, then `packageVersions`. No label, `{}`.
87
+ */
88
+ export async function imagePackages(image, read = readDocker) {
89
+ const format = `{{index .Config.Labels "${PACKAGES_LABEL}"}}`;
90
+ let label;
91
+ try {
92
+ label = `${await read(['image', 'inspect', '--format', format, image])}`.trim();
93
+ }
94
+ catch (error) {
95
+ const cause = error instanceof Error ? error.message : String(error);
96
+ throw new Error(t('build.server.versionsRun', { image, cause }));
97
+ }
98
+ const names = label && label !== '<no value>' ? label.split(/\s+/) : [];
99
+ const bad = names.find((name) => !SYSTEM_PACKAGE.test(name));
100
+ if (bad !== undefined)
101
+ throw new Error(t('build.server.label', { image, name: bad }));
102
+ return packageVersions(image, names, undefined, read);
103
+ }
@@ -10,7 +10,7 @@ export type Where = {
10
10
  dev: string;
11
11
  } | 'server';
12
12
  /** The containers' services, and their volumes' entries, for a compose file's two sections. */
13
- export declare function containerServices(product: string, processes: readonly ProductProcess[] | undefined, where: Where): {
13
+ export declare function containerServices(product: string, processes: readonly ProductProcess[] | undefined, where: Where, coreDumps?: boolean): {
14
14
  services: string[];
15
15
  volumes: string[];
16
16
  };
@@ -26,7 +26,7 @@ function imageLines(product, c, where) {
26
26
  return [` build: ${quoted(slashes(folder))}`];
27
27
  }
28
28
  /** One container's service. */
29
- function service(product, c, where) {
29
+ function service(product, c, where, coreDumps) {
30
30
  const server = where === 'server';
31
31
  const count = c.count ?? 1;
32
32
  return [
@@ -45,13 +45,15 @@ function service(product, c, where) {
45
45
  ` mem_limit: ${c.size.memoryMb}m`,
46
46
  ...(server && count > 1 ? [` scale: ${count}`] : []),
47
47
  ...(server ? [' restart: unless-stopped'] : []),
48
+ // On a server a crash writes no core dump unless the product keeps them (hardening.coreDumps).
49
+ ...(server && !coreDumps ? [' ulimits: { core: 0 }'] : []),
48
50
  ].join('\n');
49
51
  }
50
52
  /** The containers' services, and their volumes' entries, for a compose file's two sections. */
51
- export function containerServices(product, processes, where) {
53
+ export function containerServices(product, processes, where, coreDumps = false) {
52
54
  const containers = containersOf(processes);
53
55
  return {
54
- services: containers.map((c) => service(product, c, where)),
56
+ services: containers.map((c) => service(product, c, where, coreDumps)),
55
57
  volumes: containers
56
58
  .filter((c) => c.volume)
57
59
  .map((c) => ` ${c.name}:\n name: ${volumeName(product, c.name)}`),
@@ -3,6 +3,7 @@ import { readAgentsFile, writeAgentsFile } from '../agents-file.js';
3
3
  import { supportedChoices } from './chat/supported-choices.js';
4
4
  import { modelForAgent } from './chat/turn-overrides.js';
5
5
  import { factsChanged, mergeEvent } from './merge-events.js';
6
+ import { afterLevel } from './merge-withdraw.js';
6
7
  async function saveAssignment(root, { role, agent }, local) {
7
8
  const previous = await readAgentsFile(root).catch((error) => {
8
9
  // The local route can still repair a damaged file.
@@ -37,6 +38,7 @@ async function saveAssignment(root, { role, agent }, local) {
37
38
  factsChanged('levels', 'unsaved');
38
39
  if (file.level !== 'auto')
39
40
  mergeEvent('level', root);
41
+ await afterLevel(root);
40
42
  }
41
43
  const queues = new Map();
42
44
  /** One queue per product for every write of plan/agents.md: each applies to the file the last left. */
@@ -1,5 +1,6 @@
1
1
  export declare const en: {
2
2
  'ui.authority.elsewhere': string;
3
3
  'ui.authority.refused': string;
4
+ 'ui.authority.unread': string;
4
5
  'ui.authority.signIn': string;
5
6
  };
@@ -1,5 +1,6 @@
1
1
  export const en = {
2
2
  'ui.authority.elsewhere': "Approve this in the product's own console, then come back.",
3
3
  'ui.authority.refused': 'The host did not approve this artifact. Ask again before continuing.',
4
+ 'ui.authority.unread': "This change's version record can't be read here (a link out of the product, or not a valid record), so it shows no approval.",
4
5
  'ui.authority.signIn': 'An approval authority requires hosted sign-in.',
5
6
  };
@@ -1,5 +1,6 @@
1
1
  export declare const es: {
2
2
  'ui.authority.elsewhere': string;
3
3
  'ui.authority.refused': string;
4
+ 'ui.authority.unread': string;
4
5
  'ui.authority.signIn': string;
5
6
  };
@@ -1,5 +1,6 @@
1
1
  export const es = {
2
2
  'ui.authority.elsewhere': 'Aprueba esto en la consola del propio producto y luego vuelve.',
3
3
  'ui.authority.refused': 'El anfitrión no aprobó este artefacto. Vuelve a consultar antes de continuar.',
4
+ 'ui.authority.unread': 'El registro de versiones de este cambio no se puede leer aquí (un enlace fuera del producto o un registro no válido), así que no muestra aprobación.',
4
5
  'ui.authority.signIn': 'Una autoridad de aprobación requiere iniciar sesión con el anfitrión.',
5
6
  };
@@ -41,7 +41,9 @@ export function approvalBound(approval, artifact, root) {
41
41
  approval.signatures.length === 0 ||
42
42
  approval.signatures.some((s) => s.fingerprint !== artifact.fingerprint ||
43
43
  (s.agent !== undefined &&
44
- (approval.rule !== undefined || !['brand', 'prototype'].includes(approval.kind)))))
44
+ (approval.rule !== undefined || !['brand', 'prototype'].includes(approval.kind))) ||
45
+ // The look is a person's at every level: no agent's or AI's signature on a comp grant.
46
+ (approval.kind === 'comp' && s.ai !== undefined)))
45
47
  return false;
46
48
  if (approval.signatures.every((s) => s.commit === artifact.commit))
47
49
  return true;
@@ -128,8 +130,11 @@ export async function judge(context, resolve, action, root) {
128
130
  let artifact;
129
131
  try {
130
132
  const found = resolve();
131
- if (!['brand', 'prototype', 'release', 'places'].includes(found.kind))
133
+ if (!['brand', 'prototype', 'release', 'places', 'comp'].includes(found.kind))
132
134
  return refused('approval_authority_invalid');
135
+ // Approve the look is a person's: an agent, an Autopilot turn or an AI approver never asks.
136
+ if (found.kind === 'comp' && (context.agent !== undefined || context.ai !== undefined))
137
+ return refused('approval_person_only');
133
138
  artifact = Object.freeze({
134
139
  ...found,
135
140
  version: found.version ? Object.freeze({ ...found.version }) : null,
@@ -4,7 +4,7 @@ import { ApprovalRefusal } from '../approval-rules.js';
4
4
  import { requireLegacyChange } from '../prototype/milestone-key.js';
5
5
  import { brandResolver, prototypeArtifact, releaseArtifact } from './approval-artifact.js';
6
6
  import { authorityFor, hostedApproval } from './approval-authority.js';
7
- import { compApproval, compResolver } from './comp-approval.js';
7
+ import { compApproval } from './comp-approval.js';
8
8
  import { brandApproval, prototypeApproval } from './loop-approve.js';
9
9
  import { placesApproval } from './places-approval.js';
10
10
  import { approveChangePlaces } from './places-change-approval.js';
@@ -60,9 +60,7 @@ export function brandApprovalRoute(root) {
60
60
  if (request.kind === 'places')
61
61
  return placesApproval(root, request, signer, role, context, source);
62
62
  if (request.kind === 'comp')
63
- return context
64
- ? hostedApproval(context, await compResolver(root, request.fingerprint))
65
- : compApproval(root, request.fingerprint, signer, role, undefined, source);
63
+ return compApproval(root, request.fingerprint, signer, role, undefined, source, context);
66
64
  if (context) {
67
65
  if (request.kind === 'brand') {
68
66
  const resolve = await brandResolver(root, request.direction);
@@ -9,6 +9,7 @@ declare const pendingSchema: z.ZodObject<{
9
9
  main: z.ZodString;
10
10
  automatic: z.ZodOptional<z.ZodLiteral<true>>;
11
11
  published: z.ZodOptional<z.ZodLiteral<true>>;
12
+ claimHash: z.ZodOptional<z.ZodString>;
12
13
  }, z.core.$strip>;
13
14
  /** What became of a head: the host's merge (seen in main) or its refusal of the ask. */
14
15
  declare const outcomeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
@@ -77,6 +78,7 @@ declare const recordSchema: z.ZodObject<{
77
78
  main: z.ZodString;
78
79
  automatic: z.ZodOptional<z.ZodLiteral<true>>;
79
80
  published: z.ZodOptional<z.ZodLiteral<true>>;
81
+ claimHash: z.ZodOptional<z.ZodString>;
80
82
  }, z.core.$strip>>;
81
83
  outcomes: z.ZodDefault<z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
82
84
  change: z.ZodString;
@@ -19,6 +19,11 @@ const pendingSchema = z.object({
19
19
  main: fullSha,
20
20
  automatic: z.literal(true).optional(),
21
21
  published: z.literal(true).optional(),
22
+ /** SHA-256 of the claim only the host was given; the claim itself is never kept. */
23
+ claimHash: z
24
+ .string()
25
+ .regex(/^[0-9a-f]{64}$/)
26
+ .optional(),
22
27
  });
23
28
  const outcomeFacts = { change, head: fullSha, at: z.iso.datetime() };
24
29
  /** What became of a head: the host's merge (seen in main) or its refusal of the ask. */