@buffcore/cli 0.8.47 → 0.8.49

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 (175) hide show
  1. package/CHANGELOG.md +52 -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-serial.d.ts +6 -2
  8. package/dist/commands/change-merge-serial.js +5 -1
  9. package/dist/commands/change-merge.d.ts +2 -2
  10. package/dist/commands/change.js +3 -0
  11. package/dist/commands/check-skills.d.ts +16 -0
  12. package/dist/commands/check-skills.en.d.ts +14 -0
  13. package/dist/commands/check-skills.en.js +14 -0
  14. package/dist/commands/check-skills.es.d.ts +2 -0
  15. package/dist/commands/check-skills.es.js +14 -0
  16. package/dist/commands/check-skills.js +146 -0
  17. package/dist/commands/check.js +5 -0
  18. package/dist/commands/dev.d.ts +9 -2
  19. package/dist/commands/dev.js +24 -5
  20. package/dist/commands/extension/config-text.d.ts +2 -0
  21. package/dist/commands/extension/config-text.js +2 -0
  22. package/dist/commands/extension/index.js +14 -2
  23. package/dist/commands/extension/new.d.ts +16 -0
  24. package/dist/commands/extension/new.js +52 -0
  25. package/dist/commands/extension/pack-files.d.ts +23 -0
  26. package/dist/commands/extension/pack-files.js +78 -0
  27. package/dist/commands/extension/pack-scan.d.ts +24 -0
  28. package/dist/commands/extension/pack-scan.js +131 -0
  29. package/dist/commands/extension/pack.d.ts +48 -0
  30. package/dist/commands/extension/pack.js +142 -0
  31. package/dist/commands/extension/share-text.d.ts +3 -0
  32. package/dist/commands/extension/share-text.js +6 -0
  33. package/dist/commands/extension/share.en.d.ts +32 -0
  34. package/dist/commands/extension/share.en.js +32 -0
  35. package/dist/commands/extension/share.es.d.ts +2 -0
  36. package/dist/commands/extension/share.es.js +32 -0
  37. package/dist/commands/hardening.d.ts +3 -0
  38. package/dist/commands/hardening.en.d.ts +3 -0
  39. package/dist/commands/hardening.en.js +3 -0
  40. package/dist/commands/hardening.es.d.ts +2 -0
  41. package/dist/commands/hardening.es.js +3 -0
  42. package/dist/commands/hardening.js +19 -0
  43. package/dist/commands/prototype/comp-record.d.ts +5 -0
  44. package/dist/commands/prototype/comp-record.js +22 -0
  45. package/dist/commands/server/build.d.ts +2 -1
  46. package/dist/commands/server/build.js +10 -2
  47. package/dist/commands/server/deploy-local.d.ts +3 -0
  48. package/dist/commands/server/deploy-local.js +9 -0
  49. package/dist/commands/server/deploy-plan.d.ts +5 -0
  50. package/dist/commands/server/deploy-plan.js +56 -0
  51. package/dist/commands/server/deploy-result.d.ts +7 -0
  52. package/dist/commands/server/deploy-result.js +1 -0
  53. package/dist/commands/server/deploy-script.d.ts +2 -0
  54. package/dist/commands/server/deploy-script.js +3 -2
  55. package/dist/commands/server/deploy.d.ts +9 -6
  56. package/dist/commands/server/deploy.js +39 -61
  57. package/dist/commands/server/files.d.ts +9 -1
  58. package/dist/commands/server/files.js +25 -5
  59. package/dist/commands/server/image.d.ts +4 -2
  60. package/dist/commands/server/image.js +6 -5
  61. package/dist/commands/server/setup.d.ts +1 -0
  62. package/dist/commands/server/setup.js +4 -0
  63. package/dist/commands/server/system-packages.d.ts +29 -0
  64. package/dist/commands/server/system-packages.js +103 -0
  65. package/dist/commands/services/compose.d.ts +1 -1
  66. package/dist/commands/services/compose.js +5 -3
  67. package/dist/commands/ui/agents-route.js +2 -0
  68. package/dist/commands/ui/approval-authority.en.d.ts +1 -0
  69. package/dist/commands/ui/approval-authority.en.js +1 -0
  70. package/dist/commands/ui/approval-authority.es.d.ts +1 -0
  71. package/dist/commands/ui/approval-authority.es.js +1 -0
  72. package/dist/commands/ui/approval-authority.js +7 -2
  73. package/dist/commands/ui/approve.js +2 -4
  74. package/dist/commands/ui/autopilot-records.d.ts +2 -0
  75. package/dist/commands/ui/autopilot-records.js +5 -0
  76. package/dist/commands/ui/brand-approval.js +5 -1
  77. package/dist/commands/ui/chat/permissions.js +1 -1
  78. package/dist/commands/ui/chat/routes.js +4 -0
  79. package/dist/commands/ui/comp-approval.d.ts +14 -2
  80. package/dist/commands/ui/comp-approval.js +45 -8
  81. package/dist/commands/ui/index.d.ts +1 -0
  82. package/dist/commands/ui/level-route.js +3 -0
  83. package/dist/commands/ui/merge-authority.d.ts +4 -1
  84. package/dist/commands/ui/merge-authority.en.d.ts +4 -0
  85. package/dist/commands/ui/merge-authority.en.js +5 -1
  86. package/dist/commands/ui/merge-authority.es.d.ts +4 -0
  87. package/dist/commands/ui/merge-authority.es.js +5 -1
  88. package/dist/commands/ui/merge-authority.js +6 -3
  89. package/dist/commands/ui/merge-claims.d.ts +7 -0
  90. package/dist/commands/ui/merge-claims.js +21 -0
  91. package/dist/commands/ui/merge-delegation.js +8 -3
  92. package/dist/commands/ui/merge-hold-name.d.ts +5 -0
  93. package/dist/commands/ui/merge-hold-name.js +5 -0
  94. package/dist/commands/ui/merge-hold.d.ts +6 -1
  95. package/dist/commands/ui/merge-hold.js +23 -5
  96. package/dist/commands/ui/merge-publish-host.d.ts +1 -0
  97. package/dist/commands/ui/merge-publish-host.js +2 -2
  98. package/dist/commands/ui/merge-record.d.ts +2 -0
  99. package/dist/commands/ui/merge-record.js +1 -1
  100. package/dist/commands/ui/merge-route.js +17 -1
  101. package/dist/commands/ui/merge-settle.d.ts +32 -0
  102. package/dist/commands/ui/merge-settle.js +133 -0
  103. package/dist/commands/ui/merge-state.d.ts +5 -0
  104. package/dist/commands/ui/merge-state.js +7 -1
  105. package/dist/commands/ui/merge-withdraw.d.ts +9 -0
  106. package/dist/commands/ui/merge-withdraw.js +29 -0
  107. package/dist/commands/ui/outside-merge.d.ts +13 -0
  108. package/dist/commands/ui/outside-merge.js +84 -0
  109. package/dist/commands/ui/outside.d.ts +7 -4
  110. package/dist/commands/ui/outside.js +3 -0
  111. package/dist/commands/ui/plan-extensions.d.ts +34 -0
  112. package/dist/commands/ui/plan-extensions.en.d.ts +4 -0
  113. package/dist/commands/ui/plan-extensions.en.js +4 -0
  114. package/dist/commands/ui/plan-extensions.es.d.ts +2 -0
  115. package/dist/commands/ui/plan-extensions.es.js +4 -0
  116. package/dist/commands/ui/plan-extensions.js +86 -0
  117. package/dist/commands/ui/plan-files.js +9 -3
  118. package/dist/commands/ui/plan-structure.js +5 -7
  119. package/dist/commands/ui/prototype-comp-route.d.ts +12 -3
  120. package/dist/commands/ui/prototype-comp-route.js +35 -17
  121. package/dist/commands/ui/prototype-main.d.ts +6 -0
  122. package/dist/commands/ui/real-file.d.ts +11 -0
  123. package/dist/commands/ui/real-file.js +84 -0
  124. package/dist/commands/ui/save-route.js +4 -1
  125. package/dist/commands/ui/server.d.ts +1 -0
  126. package/dist/commands/ui/server.js +1 -0
  127. package/dist/commands/ui/studio-routes.js +2 -0
  128. package/dist/commands/ui/studio-state.d.ts +8 -0
  129. package/dist/commands/ui/studio-versions.js +19 -3
  130. package/dist/commands/ui/studio.en.d.ts +2 -0
  131. package/dist/commands/ui/studio.en.js +2 -0
  132. package/dist/commands/ui/studio.es.d.ts +2 -0
  133. package/dist/commands/ui/studio.es.js +2 -0
  134. package/dist/commands/upgrade.js +1 -1
  135. package/dist/ui/page.js +91 -91
  136. package/docs/EXTENSIONS.md +6 -0
  137. package/docs/PROTOTYPE.md +13 -0
  138. package/docs/WORKBENCH.md +55 -2
  139. package/package.json +11 -11
  140. package/skills/ape-add-ai-purpose/SKILL.md +1 -1
  141. package/skills/ape-add-event/SKILL.md +1 -1
  142. package/skills/ape-add-extension/SKILL.md +5 -1
  143. package/skills/ape-add-feature/SKILL.md +1 -1
  144. package/skills/ape-add-generator/SKILL.md +1 -1
  145. package/skills/ape-add-module/SKILL.md +1 -1
  146. package/skills/ape-add-route/SKILL.md +3 -1
  147. package/skills/ape-add-service/SKILL.md +1 -1
  148. package/skills/ape-add-translations/SKILL.md +2 -2
  149. package/skills/ape-admin-screen/SKILL.md +1 -1
  150. package/skills/ape-app-screen/SKILL.md +1 -1
  151. package/skills/ape-critique/SKILL.md +11 -32
  152. package/skills/ape-critique/references/after.md +15 -0
  153. package/skills/ape-critique/references/spacing-pass.md +20 -0
  154. package/skills/ape-deploy/SKILL.md +8 -3
  155. package/skills/ape-design-system/SKILL.md +15 -15
  156. package/skills/ape-design-system/references/by-hand.md +7 -0
  157. package/skills/ape-design-system/references/reference-study.md +11 -0
  158. package/skills/ape-diagnose/SKILL.md +24 -0
  159. package/skills/ape-migration/SKILL.md +1 -1
  160. package/skills/ape-plan-change/SKILL.md +37 -31
  161. package/skills/ape-plan-change/references/change-file-fields.md +5 -0
  162. package/skills/ape-plan-change/references/extensions.md +25 -0
  163. package/skills/ape-plan-change/references/finishing.md +3 -0
  164. package/skills/ape-plan-change/references/fix-from-error.md +3 -0
  165. package/skills/ape-plan-change/references/refactor.md +9 -0
  166. package/skills/ape-plan-change/references/structure.md +19 -0
  167. package/skills/ape-prototype/SKILL.md +13 -23
  168. package/skills/ape-prototype/references/comp.md +3 -0
  169. package/skills/ape-prototype/references/scope-and-export.md +5 -0
  170. package/skills/ape-prototype/references/snapshot.md +3 -0
  171. package/skills/ape-prototype/references/structure.md +11 -0
  172. package/skills/ape-prototype/references/working-app.md +7 -0
  173. package/skills/ape-request/SKILL.md +1 -1
  174. package/skills/ape-upgrade/SKILL.md +4 -1
  175. package/templates/product/package.json +1 -1
@@ -0,0 +1,32 @@
1
+ export const es = {
2
+ 'share.new.command': 'Empieza una extensión construida para compartir en este producto: packages/<clave> con sus propias tablas, palabras neutras, pruebas en su propio producto pequeño y su guía',
3
+ 'share.new.key': 'La clave son letras minúsculas y dígitos, empezando por una letra (sms, invoices2)',
4
+ 'share.new.product': 'Ejecútelo en un producto: aquí no hay buffcore.config.ts',
5
+ 'share.new.exists': '{path} ya existe: elija otra clave, o siga construyendo esa',
6
+ 'share.new.made': 'Empezada {path} ({name}). Instálela con pnpm ape add ./{path}; sus pruebas corren con las del producto, y pnpm ape check compatible ./{path} la comprueba como lo hará el catálogo.',
7
+ 'share.pack.command': 'Escribe un paquete de envío para el catálogo que nombra el producto: el paquete, su informe de comprobaciones y el escaneo. Nunca publica ni llama a la red',
8
+ 'share.pack.out': 'la carpeta donde va el paquete (por defecto .ape/pack)',
9
+ 'share.pack.missing': 'No hay extensión en {path} (pnpm ape extension new <clave> empieza una)',
10
+ 'share.pack.refused': 'No empaquetada: {count, plural, one {# hallazgo} other {# hallazgos}} que quitar antes (cada uno nombrado, nunca su valor):',
11
+ 'share.pack.secret': '{file}:{line}: un secreto ({rule})',
12
+ 'share.pack.secretFile': '{file}: un archivo de secretos o datos, por su nombre',
13
+ 'share.pack.email': '{file}:{line}: una dirección de correo que parece real (use example.com)',
14
+ 'share.pack.phone': '{file}:{line}: un número de teléfono que parece real (use 555-0100 a 555-0199)',
15
+ 'share.pack.name': '{file}:{line}: el nombre del propio producto, "{name}" (las palabras de una extensión no nombran ningún producto)',
16
+ 'share.pack.nameFile': '{file}: el nombre del propio producto, "{name}", en su ruta',
17
+ 'share.pack.hidden': '{file}: un archivo o carpeta oculto, nunca se envía (solo .gitignore, .npmignore y .editorconfig)',
18
+ 'share.pack.notText': '{file}: no es texto que pack pueda escanear (un archivo comprimido u otro binario); solo se envían texto, imágenes y fuentes',
19
+ 'share.pack.outside': 'El paquete va dentro de .ape/pack/ en el producto: {out} no está ahí',
20
+ 'share.pack.notBundle': '{path} existe y no es un paquete que escribió pack; muévalo antes',
21
+ 'share.new.installed': '{key} ya está instalada: elija otra clave, o sus tablas chocarían',
22
+ 'share.new.reserved': '{key} es un nombre que Windows reserva: elija otra clave',
23
+ 'share.pack.done': 'Paquete escrito en {path}, para {catalog}. No se envió nada: una persona lo presenta.',
24
+ 'share.pack.noCatalog': 'aún no hay catálogo nombrado en buffcore.config.ts',
25
+ 'share.pack.checks': 'Comprobaciones: {state}. El informe es check-report.json.',
26
+ 'share.pack.passed': 'pasadas',
27
+ 'share.pack.failed': 'aún no pasadas, vea el informe',
28
+ 'share.pack.touches': 'Puede tocar: lee {reads}; hosts {hosts}; lugares {places}',
29
+ 'share.pack.license': 'Licencia: {license}',
30
+ 'share.pack.screens': 'Pantallas: {screens}',
31
+ 'share.pack.none': 'ninguno',
32
+ };
@@ -0,0 +1,3 @@
1
+ import { type Hardening } from '@buffcore/config';
2
+ /** Throws, naming the options, when the setting is on and a NODE_OPTIONS carries any. */
3
+ export declare function refuseDebugStart(hardening: Hardening | undefined, nodeOptions: Readonly<Record<string, string | undefined>>): void;
@@ -0,0 +1,3 @@
1
+ export declare const en: {
2
+ 'hardening.refused': string;
3
+ };
@@ -0,0 +1,3 @@
1
+ export const en = {
2
+ 'hardening.refused': "buffcore.config.ts turns hardening.refuseDebugOptions on, and {where}'s NODE_OPTIONS carries Node's debugging or dump options, or a word with a quote or a backslash ({found}): Node reads it before any code runs, so nothing was started. Remove them and run this again.",
3
+ };
@@ -0,0 +1,2 @@
1
+ import type { en } from './hardening.en.ts';
2
+ export declare const es: typeof en;
@@ -0,0 +1,3 @@
1
+ export const es = {
2
+ 'hardening.refused': 'buffcore.config.ts activa hardening.refuseDebugOptions, y el NODE_OPTIONS de {where} lleva opciones de depuración o de volcado de Node, o una palabra con comillas o barra invertida ({found}): Node lo lee antes de ejecutar código, así que no se inició nada. Quítalas y vuelve a ejecutar esto.',
3
+ };
@@ -0,0 +1,19 @@
1
+ // `hardening.refuseDebugOptions` where BuffCore starts the processes (`ape dev`) or writes what
2
+ // starts them (`ape server setup`): a NODE_OPTIONS Node would read before any code runs is
3
+ // refused before anything starts (`debug-options.ts` in @buffcore/config).
4
+ import { debugStartOptions } from '@buffcore/config';
5
+ import { createI18n } from '@buffcore/i18n';
6
+ import { en } from './hardening.en.js';
7
+ import { es } from './hardening.es.js';
8
+ const translator = createI18n({ catalogs: [{ en, es }] });
9
+ /** Throws, naming the options, when the setting is on and a NODE_OPTIONS carries any. */
10
+ export function refuseDebugStart(hardening, nodeOptions) {
11
+ for (const [where, value] of Object.entries(nodeOptions)) {
12
+ const found = debugStartOptions(hardening, [value]);
13
+ if (found.length)
14
+ throw new Error(translator.t(new Intl.NumberFormat().resolvedOptions().locale, 'hardening.refused', {
15
+ where,
16
+ found: found.join(', '),
17
+ }));
18
+ }
19
+ }
@@ -25,3 +25,8 @@ export interface CompSigner {
25
25
  * (the studio's approval save commits it on its own); returns what the file holds.
26
26
  */
27
27
  export declare function approveComp(root: string, signer: CompSigner, write?: boolean): CompRecord;
28
+ /**
29
+ * A host authority's grant for the comp the page showed, recorded as the studio's own record: only
30
+ * a person's signatures (no agent, no AI) on this comp's pictures. Writes it when `write`.
31
+ */
32
+ export declare function compGrantRecord(root: string, approval: Approval, write?: boolean): CompRecord;
@@ -76,6 +76,28 @@ export function approveComp(root, signer, write = true) {
76
76
  writeRecord(root, record);
77
77
  return record;
78
78
  }
79
+ /**
80
+ * A host authority's grant for the comp the page showed, recorded as the studio's own record: only
81
+ * a person's signatures (no agent, no AI) on this comp's pictures. Writes it when `write`.
82
+ */
83
+ export function compGrantRecord(root, approval, write = true) {
84
+ const comp = newestComp(root);
85
+ if (!comp)
86
+ throw new ApprovalRefusal(compT('comp.missing'));
87
+ if (!comp.report.scenes.length)
88
+ throw new ApprovalRefusal(compT('comp.empty'));
89
+ if (compApproved(readCompApproval(root), comp))
90
+ throw new ApprovalRefusal(compT('comp.approved'));
91
+ if (approval.kind !== 'comp' ||
92
+ approval.signatures.some((s) => s.agent !== undefined || s.ai !== undefined))
93
+ throw new ApprovalRefusal(compT('comp.person'));
94
+ if (approval.signatures.some((s) => s.fingerprint !== comp.fingerprint))
95
+ throw new ApprovalRefusal(compT('comp.changed'));
96
+ const record = { folder: comp.folder, approval };
97
+ if (write)
98
+ writeRecord(root, record);
99
+ return record;
100
+ }
79
101
  function writeRecord(root, record) {
80
102
  const file = join(root, COMP_FILE);
81
103
  mkdirSync(join(root, 'prototype', 'versions'), { recursive: true });
@@ -53,10 +53,11 @@ export declare function buildImages(here: Local, where: {
53
53
  }, product: ProductConfig, { text, source }: {
54
54
  text: string;
55
55
  source: string;
56
- }, { json, log, tag }: {
56
+ }, { json, log, tag, packages, }: {
57
57
  json: boolean;
58
58
  log: (line: string) => void;
59
59
  tag?: string;
60
+ packages?: readonly string[];
60
61
  }): Promise<{
61
62
  tags: string[];
62
63
  built: {
@@ -8,6 +8,7 @@ import { join, relative } from 'node:path';
8
8
  import { createGzip } from 'node:zlib';
9
9
  import { builtImage, containersOf } from '../services/compose.js';
10
10
  import { stopTree } from '../ui/runner.js';
11
+ import { packagesFailed } from './system-packages.js';
11
12
  /** The Dockerfile's name inside the build context (added to the commit's files). */
12
13
  export const DOCKERFILE = 'ape.Dockerfile';
13
14
  /** The image is never built from prototype screenshots (most of a repository's size). */
@@ -111,11 +112,18 @@ export const local = {
111
112
  * moment never takes this one's place), then each container with a Dockerfile from its folder of
112
113
  * the same commit, under the same source. Answers the tags to ship, the product's first.
113
114
  */
114
- export async function buildImages(here, where, product, { text, source }, { json, log, tag = source }) {
115
+ export async function buildImages(here, where, product, { text, source }, { json, log, tag = source, packages = [], }) {
115
116
  const { root, workspace, sha, platform } = where;
116
117
  const image = `${product.name}:${tag}`;
117
118
  log('Building the image...');
118
- await here.build(workspace, sha, text, image, platform, json);
119
+ try {
120
+ await here.build(workspace, sha, text, image, platform, json);
121
+ }
122
+ catch (error) {
123
+ if (!packages.length)
124
+ throw error;
125
+ throw new Error(`${error.message} ${packagesFailed(packages)}`);
126
+ }
119
127
  const containers = containersOf(product.processes).filter((c) => c.build);
120
128
  const tags = [image];
121
129
  for (const c of containers) {
@@ -1,5 +1,6 @@
1
1
  import { type DeployResult } from './deploy-result.ts';
2
2
  import { type RemoteRead, type RemoteRun } from './ssh.ts';
3
+ import { type PackageReader } from './system-packages.ts';
3
4
  export interface LocalDeployOptions {
4
5
  /** The approval file. */
5
6
  approval: string;
@@ -10,6 +11,8 @@ export interface LocalDeployDeps {
10
11
  read?: RemoteRead;
11
12
  now?: () => Date;
12
13
  log?: (line: string) => void;
14
+ /** Reads the image's system packages (`system-packages.ts`); this machine's Docker when unset. */
15
+ readPackages?: PackageReader;
13
16
  }
14
17
  /** `ape deploy --local`. Answers how it ended, as `ape deploy` does. */
15
18
  export declare function deployLocal(image: string, options: LocalDeployOptions, deps?: LocalDeployDeps): Promise<DeployResult>;
@@ -11,6 +11,7 @@ import { deployScript, parseState, stateScript } from './deploy-script.js';
11
11
  import { intakeWarnings } from './deploy-warnings.js';
12
12
  import { SCRIPT_COMMAND } from './script.js';
13
13
  import { here } from './ssh.js';
14
+ import { imagePackages } from './system-packages.js';
14
15
  /** `ape deploy --local`. Answers how it ended, as `ape deploy` does. */
15
16
  export async function deployLocal(image, options, deps = {}) {
16
17
  const machine = here(options.json ? 'stderr' : 'show');
@@ -36,6 +37,14 @@ export async function deployLocal(image, options, deps = {}) {
36
37
  log(`Deploying ${product} at ${approval.commit.slice(0, 12)} on this machine (${state.api}), as approved until ${approval.expires}.`);
37
38
  result.warnings = intakeWarnings(await run(SCRIPT_COMMAND, deployScript(product, state, { ref: image, approved: approval.image })));
38
39
  printIntakeWarnings(result.warnings, log);
40
+ // What the approved image holds, read by its ID once the deploy proved that is what runs; a
41
+ // failed read is said and leaves null, never a guess.
42
+ try {
43
+ result.systemPackages = await imagePackages(approval.image, deps.readPackages);
44
+ }
45
+ catch (error) {
46
+ log(error instanceof Error ? error.message : String(error));
47
+ }
39
48
  log(`Deployed: ${state.api} runs the approved image and answers healthy.`);
40
49
  return end({ result: 'deployed' });
41
50
  }
@@ -0,0 +1,5 @@
1
+ import type { ImagePlan } from './image.ts';
2
+ /** The folder with the lockfile: the product's, or the repository the product sits in. */
3
+ export declare function workspaceOf(root: string): string;
4
+ /** The image's plan: where the product, its API, its console and its web app are, and what they're called. */
5
+ export declare function imagePlan(root: string, workspace: string, site: Pick<ImagePlan, 'name' | 'commit' | 'systemPackages'>): ImagePlan;
@@ -0,0 +1,56 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, join, relative } from 'node:path';
3
+ import { apiFolder } from '../dev.js';
4
+ import { surfaceDir } from '../prototype/export.js';
5
+ // Where the product, its API, console and web app are, for the server image (split from deploy.ts).
6
+ const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'));
7
+ /** The folder with the lockfile: the product's, or the repository the product sits in. */
8
+ export function workspaceOf(root) {
9
+ for (let dir = root;; dir = dirname(dir)) {
10
+ if (existsSync(join(dir, 'pnpm-lock.yaml')))
11
+ return dir;
12
+ if (dirname(dir) === dir)
13
+ throw new Error(`No pnpm-lock.yaml in ${root} or above.`);
14
+ }
15
+ }
16
+ /** The image's plan: where the product, its API, its console and its web app are, and what they're called. */
17
+ export function imagePlan(root, workspace, site) {
18
+ const from = (dir) => relative(workspace, dir).replaceAll('\\', '/') || '.';
19
+ const product = from(root);
20
+ const api = from(join(root, apiFolder(root)));
21
+ const admin = surfaceDir(root, 'admin');
22
+ if (!admin)
23
+ throw new Error(`No admin console in ${root} (admin/ or apps/admin/).`);
24
+ const app = surfaceDir(root, 'app');
25
+ const apiPackage = readJson(join(workspace, api, 'package.json'));
26
+ if (!apiPackage.dependencies?.['@buffcore/cli']) {
27
+ 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.`);
28
+ }
29
+ const pnpm = /^pnpm@(\d+\.\d+\.\d+)/.exec(readJson(join(workspace, 'package.json')).packageManager ?? '');
30
+ if (!pnpm)
31
+ throw new Error(`${workspace}/package.json must name pnpm in packageManager.`);
32
+ const names = {
33
+ product: readJson(join(root, 'package.json')).name,
34
+ api: apiPackage.name,
35
+ admin: readJson(join(admin, 'package.json')).name,
36
+ app: app && readJson(join(app, 'package.json')).name,
37
+ };
38
+ if (!names.product || !names.api || !names.admin || (app && !names.app))
39
+ throw new Error("The product's, API's, console's and web app's package.json need names.");
40
+ const { systemPackages, ...named } = site;
41
+ return {
42
+ ...named,
43
+ pnpm: pnpm[1],
44
+ dirs: { product, api, admin: from(admin), ...(app ? { app: from(app) } : {}) },
45
+ packages: {
46
+ product: names.product,
47
+ api: names.api,
48
+ admin: names.admin,
49
+ ...(names.app ? { app: names.app } : {}),
50
+ },
51
+ ...(apiPackage.dependencies?.['@buffcore/cli']?.startsWith('workspace:')
52
+ ? { sources: true }
53
+ : {}),
54
+ ...(systemPackages?.length ? { systemPackages } : {}),
55
+ };
56
+ }
@@ -22,6 +22,13 @@ export interface DeployResult {
22
22
  commit: string | null;
23
23
  /** The image's ID (`sha256:…`): the one built, or the one approved; null when none was. */
24
24
  image: string | null;
25
+ /**
26
+ * The system packages' installed versions in the image deployed (`server.systemPackages`), by
27
+ * name: `{}` for none. `--local` reads them from the approved image (its label names the list);
28
+ * `unchanged` from the image this computer built last time, when still here. Null when they
29
+ * couldn't be read, or nothing was built (refused).
30
+ */
31
+ systemPackages: Record<string, string> | null;
25
32
  /** What went wrong, in a sentence; null when it worked. */
26
33
  error: string | null;
27
34
  /** Unrevoked key counts (expired too), or an explicit unchecked warning; no credentials. */
@@ -30,6 +30,7 @@ export function tracking() {
30
30
  product: '',
31
31
  commit: null,
32
32
  image: null,
33
+ systemPackages: null,
33
34
  error: null,
34
35
  warnings: [{ kind: 'intake-unchecked' }],
35
36
  ms: 0,
@@ -39,6 +39,8 @@ export interface ServerState {
39
39
  deployKey?: string;
40
40
  /** The services the server's compose file runs (setup wrote it from `buffcore.config.ts`). */
41
41
  services?: string[];
42
+ /** The `hardening` its compose file was written for (`hardeningMark`); empty before hardening. */
43
+ hardening?: string;
42
44
  /** Whether the server's Caddyfile serves the web app (one from an older setup doesn't). */
43
45
  web?: boolean;
44
46
  }
@@ -5,7 +5,7 @@
5
5
  // stay in the server's .env, and only its addresses and the deploy key (a public key) are read
6
6
  // back. As in setup, a command that could read input reads /dev/null: the script itself is the input.
7
7
  import { health, migrationCheck, processChecks, SETTLE_SECONDS } from './deploy-checks.js';
8
- import { otherProducts, refuseOtherProduct, stackDir } from './files.js';
8
+ import { HARDENING_LINE, otherProducts, refuseOtherProduct, stackDir } from './files.js';
9
9
  import { CONSOLE_DIR, WEB_API_URL, WEB_DIR } from './image.js';
10
10
  import { imageCheckStep } from './image-check.js';
11
11
  import { configIdScript } from './image-id.js';
@@ -44,6 +44,7 @@ if grep -q 'tls internal' "$dir/Caddyfile"; then echo internal=yes; fi
44
44
  if grep -q '/srv/app' "$dir/Caddyfile"; then echo web=yes; fi
45
45
  cd "$dir"
46
46
  echo "services=$(docker compose config --services 2>/dev/null | tr '\\n' ' ')"
47
+ sed -n 's/^${HARDENING_LINE}/hardening=/p' compose.yml 2>/dev/null || true
47
48
  api=$(docker compose ps -q api 2>/dev/null || true)
48
49
  if [ -n "$api" ]; then
49
50
  echo "running=$(docker inspect --format '{{index .Config.Labels "ape.source"}}' "$api")"
@@ -80,7 +81,7 @@ export function parseState(output, destination, name) {
80
81
  running: value('running').replace('<no value>', ''),
81
82
  ...(commit ? { commit } : {}),
82
83
  deployKey: value('deploy_key'),
83
- ...(services.length ? { services } : {}),
84
+ ...(services.length ? { services, hardening: value('hardening') } : {}),
84
85
  ...(value('web') === 'yes' ? { web: true } : {}),
85
86
  };
86
87
  }
@@ -4,23 +4,22 @@ import { type Local } from './build.ts';
4
4
  import { checkDeploy } from './deploy-chain.ts';
5
5
  import { type DeployResult } from './deploy-result.ts';
6
6
  import { type ServerState } from './deploy-script.ts';
7
- import { type ImagePlan } from './image.ts';
7
+ import { type ImageReader } from './image-id.ts';
8
8
  import { type Output, type RemoteRead, type RemoteRun } from './ssh.ts';
9
+ import { type PackageReader } from './system-packages.ts';
9
10
  export interface DeployOptions {
10
11
  /** The SSH key, as `ssh -i`. */
11
12
  identity?: string;
12
13
  /** One line of JSON on stdout (`deploy-result.ts`); what the steps say goes to stderr. */
13
14
  json?: boolean;
14
15
  }
15
- /** The folder with the lockfile: the product's, or the repository the product sits in. */
16
- export declare function workspaceOf(root: string): string;
17
- /** The image's plan: where the product, its API, its console and its web app are, and what they're called. */
18
- export declare function imagePlan(root: string, workspace: string, site: Pick<ImagePlan, 'name' | 'commit'>): ImagePlan;
16
+ import { imagePlan, workspaceOf } from './deploy-plan.ts';
17
+ export { imagePlan, workspaceOf };
19
18
  /**
20
19
  * The server runs what `buffcore.config.ts` declares, since setup wrote its compose file from it:
21
20
  * a process added or removed since needs setup again, or it would quietly not run (or keep running).
22
21
  */
23
- export declare function checkStack(product: Pick<ProductConfig, 'processes'>, state: Pick<ServerState, 'services'>, destination: string): void;
22
+ export declare function checkStack(product: Pick<ProductConfig, 'processes' | 'hardening'>, state: Pick<ServerState, 'services' | 'hardening'>, destination: string): void;
24
23
  export interface DeployDeps {
25
24
  root?: string;
26
25
  remote?: (destination: string, identity?: string, output?: Output) => RemoteRun;
@@ -31,6 +30,10 @@ export interface DeployDeps {
31
30
  catalog?: CatalogDeps;
32
31
  /** Local checks before building; tests can stand in for git and pnpm as for Docker. */
33
32
  checks?: typeof checkDeploy;
33
+ /** Reads a local image's ID (`image-id.ts`); Docker when unset. */
34
+ readImage?: ImageReader;
35
+ /** Reads the built image's system package versions (`system-packages.ts`); Docker when unset. */
36
+ readPackages?: PackageReader;
34
37
  }
35
38
  /**
36
39
  * `ape deploy`. Read the server, build if it runs something else, ship, then the server's steps.
@@ -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