@ours.network/install 1.2.1-nightly.9 → 2.0.1

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 (67) hide show
  1. package/GATEWAY_SETUP.md +178 -0
  2. package/README.md +564 -11
  3. package/ROOTLESS_PODMAN_VALIDATION.md +210 -0
  4. package/assets/Dockerfile +18 -15
  5. package/assets/Dockerfile.gateway +5 -0
  6. package/assets/docker-compose.yaml +8 -1
  7. package/assets/fleet-settings.example.json +48 -0
  8. package/assets/gateway-entrypoint.sh +37 -0
  9. package/assets/release-lock.json +1263 -4538
  10. package/assets/release.json +32 -24
  11. package/assets/scripts/build/build-common.mjs +10 -1
  12. package/assets/scripts/build/build-sdk.mjs +6 -1
  13. package/assets/scripts/maintenance/build-context.mjs +1 -1
  14. package/assets/scripts/maintenance/daemon-owner.mjs +15 -0
  15. package/assets/scripts/maintenance/docker-layout-conversion.mjs +22 -7
  16. package/assets/scripts/maintenance/recover-notifications.mjs +36 -0
  17. package/assets/scripts/maintenance/release-graph.mjs +1 -1
  18. package/assets/scripts/maintenance/state-operation.mjs +76 -8
  19. package/assets/scripts/runtime/README.md +7 -0
  20. package/assets/scripts/runtime/client-setup.mjs +105 -20
  21. package/assets/scripts/runtime/daemon-client-prefix.mjs +115 -0
  22. package/assets/scripts/runtime/dependency-ready.mjs +13 -0
  23. package/assets/scripts/runtime/diagnostics.mjs +72 -0
  24. package/assets/scripts/runtime/entrypoint.sh +5 -1
  25. package/assets/scripts/runtime/health-messenger.mjs +7 -6
  26. package/assets/scripts/runtime/healthcheck.mjs +49 -15
  27. package/assets/scripts/runtime/notifications-gateway.mjs +90 -0
  28. package/assets/scripts/runtime/recover.mjs +202 -0
  29. package/assets/scripts/runtime/start-cowork.sh +5 -0
  30. package/assets/scripts/runtime/start-messenger.sh +29 -4
  31. package/assets/scripts/runtime/start-telegram.sh +5 -0
  32. package/assets/scripts/runtime/supervise.mjs +35 -0
  33. package/assets/sources.json +49 -33
  34. package/install.mjs +12 -2
  35. package/install.sh +5 -2
  36. package/lib/boot-readiness.mjs +96 -0
  37. package/lib/build-transition.mjs +16 -0
  38. package/lib/client-cli.mjs +12 -2
  39. package/lib/container-engine.mjs +127 -0
  40. package/lib/diagnostics.mjs +1 -0
  41. package/lib/docker-conversion-runtime.mjs +7 -4
  42. package/lib/docker-layout-installation.mjs +2 -1
  43. package/lib/docker-recovery.mjs +60 -0
  44. package/lib/docker-runtime-repair.mjs +49 -14
  45. package/lib/effects.mjs +462 -136
  46. package/lib/gateway-transition.mjs +87 -0
  47. package/lib/gateway.mjs +227 -0
  48. package/lib/legacy-migration.mjs +13 -2
  49. package/lib/orchestrate-uninstall.mjs +23 -6
  50. package/lib/orchestrate.mjs +282 -38
  51. package/lib/ownership.mjs +63 -0
  52. package/lib/plan.mjs +37 -11
  53. package/lib/podman-preflight.mjs +40 -0
  54. package/lib/product.mjs +69 -0
  55. package/lib/removal-plan.mjs +437 -0
  56. package/lib/removal.mjs +749 -0
  57. package/lib/security-versions.mjs +38 -0
  58. package/lib/server-onboarding.mjs +182 -16
  59. package/lib/server-ports.mjs +17 -0
  60. package/lib/setup-options.mjs +119 -29
  61. package/lib/setup.mjs +86 -15
  62. package/lib/target.mjs +24 -8
  63. package/lib/uninstall.mjs +2 -2
  64. package/lib/usage.mjs +35 -9
  65. package/lib/welcome.mjs +219 -0
  66. package/lib/workspace-setup.mjs +164 -0
  67. package/package.json +5 -3
@@ -34,8 +34,18 @@ export async function publishClientCli(effects, packagePath, { policy = {}, isol
34
34
  const acquisitionRoot = dirname(dirname(dirname(packageRoot)));
35
35
  privateAcquisition(effects.home, acquisitionRoot);
36
36
  const retained = JSON.parse(readFileSync(join(acquisitionRoot, 'sources.json')));
37
- if (releaseBinding(retained)?.scope !== 'host-cli') throw new Error('Unrecognized private CLI entry');
37
+ const binding = releaseBinding(retained);
38
+ if (binding && binding.scope !== 'host-cli') throw new Error('Unrecognized private CLI entry');
38
39
  verifyReleaseGraph(acquisitionRoot, retained);
40
+ if (!binding) {
41
+ // Development selections publish through npm's global package entry.
42
+ // Require that exact retained selection and global target on retry;
43
+ // integrity-bound private host CLI releases keep their stricter path.
44
+ const npmRoot = (await effects.run('npm', ['root', '--global'])).stdout.trim();
45
+ const selected = retained.packages?.['@ours.network/cli'];
46
+ const pkg = JSON.parse(readFileSync(join(packageRoot, 'package.json')));
47
+ if (!isAbsolute(npmRoot) || realpathSync(join(npmRoot, '@ours.network/cli')) !== packageRoot || selected?.type !== 'npm' || selected.version !== pkg.version) throw new Error('Unrecognized private CLI entry');
48
+ }
39
49
  const pkg = JSON.parse(readFileSync(join(packageRoot, 'package.json')));
40
50
  if (pkg.name !== '@ours.network/cli' || resolve(packageRoot, pkg.bin?.ours ?? '') !== resolved) throw new Error('Unrecognized private CLI target');
41
51
  } else {
@@ -78,7 +88,7 @@ export async function publishClientCli(effects, packagePath, { policy = {}, isol
78
88
  if (sdk.name !== '@ours.network/sdk' || sdk.version !== policy.release.packages['@ours.network/sdk'].version) throw new Error('Private CLI SDK differs from selection');
79
89
  mkdirSync(dirname(entry), { recursive: true });
80
90
  const binDir = lstatSync(dirname(entry));
81
- if (!binDir.isDirectory() || binDir.uid !== process.getuid() || (binDir.mode & 0o022)) throw new Error('CLI bin directory must be owned and not writable by others');
91
+ if (!binDir.isDirectory() || binDir.uid !== process.getuid() || (binDir.mode & 0o022)) throw new Error(`CLI bin directory ${dirname(entry)} must be owned by you and not writable by group or others; run chmod go-w on it, or point npm's global prefix at a directory you own`);
82
92
  const current = stat(entry);
83
93
  if (before ? !current || current.dev !== before.dev || current.ino !== before.ino : current) throw new Error('CLI entry changed during publication');
84
94
  const staged = entry + '.' + randomUUID();
@@ -0,0 +1,127 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { isAbsolute, resolve } from 'node:path';
3
+
4
+ export const engineName = record => record.containerEngine === undefined ? 'docker' : record.containerEngine;
5
+ const path = value => typeof value === 'string' && isAbsolute(value) && resolve(value) === value && !/[\x00-\x1f]/.test(value);
6
+ export function validateContainerEngine(record) {
7
+ const engine = engineName(record);
8
+ if (!['docker', 'podman'].includes(engine) || (record.mode !== 'docker' && (record.containerEngine !== undefined || record.containerBinding !== undefined))) throw new Error('Invalid container engine selection');
9
+ const b = record.containerBinding;
10
+ if (engine === 'docker') {
11
+ if (b !== undefined) throw new Error('Unexpected Docker backend binding');
12
+ return;
13
+ }
14
+ if (!b || b.version !== 1 || !Number.isInteger(b.uid) || b.uid <= 0 || !path(b.graphRoot) || !path(b.runRoot)
15
+ || !/^[a-f0-9]{64}$/.test(b.namespaceDigest ?? '') || !path(b.socket) || !path(b.provider) || typeof b.driver !== 'string' || !/^[a-z0-9]+$/.test(b.driver)
16
+ || Object.keys(b).some(k => !['version', 'uid', 'graphRoot', 'runRoot', 'socket', 'provider', 'driver', 'namespaceDigest'].includes(k))) throw new Error('Invalid rootless Podman backend binding');
17
+ }
18
+ function podmanEnvironment(record, env, uid) {
19
+ validateContainerEngine(record);
20
+ const b = record.containerBinding;
21
+ if (uid !== b.uid) throw new Error('Podman installation belongs to another rootless owner');
22
+ for (const key of ['CONTAINER_HOST', 'CONTAINER_CONNECTION', 'CONTAINERS_STORAGE_CONF', 'CONTAINERS_CONF', 'PODMAN_USERNS', 'STORAGE_DRIVER', 'STORAGE_OPTS']) {
23
+ if (env[key]) throw new Error(`${key} conflicts with the retained local Podman backend`);
24
+ }
25
+ if ((env.OURS_PODMAN_SOCKET && env.OURS_PODMAN_SOCKET !== b.socket) || env.DOCKER_CONTEXT || (env.DOCKER_HOST && env.DOCKER_HOST !== `unix://${b.socket}`)
26
+ || (env.PODMAN_COMPOSE_PROVIDER && env.PODMAN_COMPOSE_PROVIDER !== b.provider)) throw new Error('Environment conflicts with the retained Podman backend/provider');
27
+ return { DOCKER_CONTEXT: undefined, DOCKER_HOST: `unix://${b.socket}`, PODMAN_COMPOSE_PROVIDER: b.provider, PODMAN_COMPOSE_WARNING_LOGS: 'false' };
28
+ }
29
+ /** The only container command boundary. Legacy records keep their Docker path. */
30
+ export async function runContainer(effects, record, args, options = {}) {
31
+ if (engineName(record) === 'docker') return effects.run('docker', args, options);
32
+ const env = { ...(effects.env ?? {}), ...(options.env ?? {}) };
33
+ const selected = podmanEnvironment(record, env, process.getuid?.());
34
+ const b = record.containerBinding;
35
+ if (args[0] === 'build' && !args.some(arg => arg === '--format' || arg.startsWith('--format='))) args = ['build', '--format', 'docker', ...args.slice(1)];
36
+ // Docker reports a missing object as 1; Podman inspect uses 125. Probe exact
37
+ // existence separately so transport/permission failures are never absence.
38
+ if (['image', 'volume'].includes(args[0]) && args[1] === 'inspect' && options.allowCodes?.includes(1)) {
39
+ const found = await runContainer(effects, record, [args[0], 'exists', args.at(-1)], { ...options, allowCodes: [1] });
40
+ if (found.code === 1) return { code: 1, stdout: '', ok: false };
41
+ }
42
+ // Native commands and the Compose provider must address the SAME local store.
43
+ const prefix = args[0] === 'compose' ? ['--remote', '--url', `unix://${b.socket}`] : ['--remote=false', '--root', b.graphRoot, '--runroot', b.runRoot, '--storage-driver', b.driver];
44
+ const result = await effects.run('podman', [...prefix, ...args],
45
+ { ...options, env: { ...options.env, ...selected } });
46
+ if (args[0] === 'image' && args[1] === 'inspect' && !args.includes('--format') && result.code === 0) {
47
+ const images = JSON.parse(result.stdout);
48
+ for (const value of images) if (/^[a-f0-9]{64}$/.test(value.Id)) value.Id = `sha256:${value.Id}`;
49
+ return { ...result, stdout: JSON.stringify(images) };
50
+ }
51
+ return result;
52
+ }
53
+ export function namespaceDigest(info) {
54
+ const maps = info.host?.idMappings;
55
+ const normalized = ['uidmap', 'gidmap'].map(key => {
56
+ const rows = maps?.[key];
57
+ if (!Array.isArray(rows) || !rows.length) throw new Error('Podman user namespace mappings are unavailable');
58
+ return rows.map(row => {
59
+ const values = [row.container_id, row.host_id, row.size];
60
+ if (values.some(value => !Number.isInteger(value) || value < 0) || row.size < 1) throw new Error('Invalid Podman namespace mapping');
61
+ return values;
62
+ }).sort((a, b) => a[0] - b[0]);
63
+ });
64
+ return createHash('sha256').update(JSON.stringify(normalized)).digest('hex');
65
+ }
66
+ export async function bindPodman(effects, record) {
67
+ if (effects.platform.platform !== 'linux' || process.getuid?.() === 0) throw new Error('Podman server installation requires a non-root Linux user');
68
+ const env = effects.env ?? {};
69
+ const provider = record.containerBinding?.provider ?? env.PODMAN_COMPOSE_PROVIDER;
70
+ if (!path(provider)) throw new Error('Set PODMAN_COMPOSE_PROVIDER to an absolute standalone Docker Compose executable path');
71
+ // Reject ambient redirection before even probing an unbound store.
72
+ for (const key of ['CONTAINER_HOST', 'CONTAINER_CONNECTION', 'CONTAINERS_STORAGE_CONF', 'CONTAINERS_CONF', 'PODMAN_USERNS', 'STORAGE_DRIVER', 'STORAGE_OPTS', 'DOCKER_CONTEXT']) {
73
+ if (env[key]) throw new Error(`${key} conflicts with local rootless Podman`);
74
+ }
75
+ const info = JSON.parse((await effects.run('podman', ['--remote=false', 'info', '--format', 'json'])).stdout);
76
+ if (info.host?.security?.rootless !== true) throw new Error('Podman must report rootless=true');
77
+ const socket = record.containerBinding?.socket ?? env.OURS_PODMAN_SOCKET ?? info.host.remoteSocket?.path;
78
+ const observed = { version: 1, uid: process.getuid(), graphRoot: info.store?.graphRoot, runRoot: info.store?.runRoot, driver: info.store?.graphDriverName, socket, provider, namespaceDigest: namespaceDigest(info) };
79
+ validateContainerEngine({ ...record, containerBinding: observed });
80
+ if (record.containerBinding && Object.keys(observed).some(k => observed[k] !== record.containerBinding[k])) throw new Error('Podman backend differs from retained installation');
81
+ podmanEnvironment({ ...record, containerBinding: observed }, env, process.getuid());
82
+ const api = JSON.parse((await effects.run('podman', ['--remote', '--url', `unix://${socket}`, 'info', '--format', 'json'])).stdout);
83
+ if (api.host?.security?.rootless !== true || api.store?.graphRoot !== observed.graphRoot || api.store?.runRoot !== observed.runRoot || api.store?.graphDriverName !== observed.driver || namespaceDigest(api) !== observed.namespaceDigest) throw new Error('Podman socket does not address the selected rootless storage; enable the user podman.socket');
84
+ const version = (await effects.run(provider, ['version', '--short'])).stdout.trim();
85
+ const match = /^v?(\d+)\.(\d+)\./.exec(version);
86
+ if (!match || +match[1] < 2 || (+match[1] === 2 && +match[2] < 35)) throw new Error('Standalone Docker Compose 2.35+ is required');
87
+ record.containerBinding = observed;
88
+ }
89
+
90
+ /** Resolve Compose rather than maintaining a second, drifting build definition. */
91
+ export function nativeBuildCommands(config, services, env = {}) {
92
+ const commands = [], seen = new Set();
93
+ for (const name of services) {
94
+ const service = config.services?.[name], build = service?.build;
95
+ if (!build || typeof build !== 'object' || !path(build.context) || !service.image) throw new Error(`Missing resolved build definition for ${name}`);
96
+ const supported = ['context', 'dockerfile', 'target', 'args', 'secrets', 'cache_from', 'cache_to', 'platforms', 'labels', 'no_cache', 'pull'];
97
+ if (Object.keys(build).some(k => !supported.includes(k))) throw new Error(`Unsupported Podman build option for ${name}`);
98
+ const args = ['build', '--format', 'docker', '--layers', '--file', resolve(build.context, build.dockerfile ?? 'Dockerfile'), '--tag', service.image];
99
+ if (build.target) args.push('--target', build.target);
100
+ const platforms = build.platforms ?? (service.platform ? [service.platform] : []);
101
+ if (platforms.length > 1) throw new Error('Multi-platform Podman builds are not supported');
102
+ if (platforms.length) args.push('--platform', platforms[0]);
103
+ for (const [key, value] of Object.entries(build.args ?? {})) {
104
+ if (value === null) throw new Error(`Unresolved build argument: ${key}`);
105
+ args.push('--build-arg', `${key}=${value}`);
106
+ }
107
+ for (const [key, value] of Object.entries(build.labels ?? {})) args.push('--label', `${key}=${value}`);
108
+ for (const key of ['cache_from', 'cache_to']) for (const value of build[key] ?? []) args.push('--' + key.replace('_', '-'), value);
109
+ if (build.no_cache) args.push('--no-cache');
110
+ if (build.pull) args.push('--pull=always');
111
+ for (const secret of build.secrets ?? []) {
112
+ const source = typeof secret === 'string' ? secret : secret.source;
113
+ const id = typeof secret === 'string' ? source : secret.target ?? source;
114
+ const definition = config.secrets?.[source];
115
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new Error('Invalid build secret ID');
116
+ if (definition?.environment) {
117
+ // Native local Podman supports type=env; values never enter argv/files.
118
+ if (env[definition.environment]) args.push('--secret', `id=${id},type=env,env=${definition.environment}`);
119
+ } else if (definition?.file && path(definition.file)) args.push('--secret', `id=${id},src=${definition.file}`);
120
+ else throw new Error(`Unsupported build secret: ${source}`);
121
+ }
122
+ args.push(build.context);
123
+ const key = JSON.stringify(args);
124
+ if (!seen.has(key)) { seen.add(key); commands.push(args); }
125
+ }
126
+ return commands;
127
+ }
@@ -0,0 +1 @@
1
+ export { redactDiagnostic, commandFailure, installerFailure } from '../assets/scripts/runtime/diagnostics.mjs';
@@ -1,3 +1,5 @@
1
+ import { runContainer } from './container-engine.mjs';
2
+ import { isPluginOnly } from './product.mjs';
1
3
  import * as fs from 'node:fs';
2
4
  import { join } from 'node:path';
3
5
  import { randomUUID } from 'node:crypto';
@@ -33,7 +35,7 @@ ENTRYPOINT ["node", "/opt/ours/docker/state-operation.mjs"]
33
35
  `);
34
36
  // Build maintenance first: both targets inherit the same retained runtime.
35
37
  for (const target of ['maintenance', 'runtime']) {
36
- await effects.run('docker', ['build', '--platform', 'linux/amd64', '--target', target,
38
+ await runContainer(effects, record, ['build', '--platform', 'linux/amd64', '--target', target,
37
39
  '--tag', `${record.project}:${target}`, context]);
38
40
  }
39
41
  atomicWriteConfig(compose, fs.readFileSync(join(assets, 'docker-compose.yaml')));
@@ -63,7 +65,8 @@ export async function runDockerConversion(record, selected, operation, label, ef
63
65
  }
64
66
  } else {
65
67
  addMount('storage', '/var/lib/ours', 'state/daemon', true);
66
- addMount('storage', '/var/lib/ours-cowork', 'state/cowork', false);
68
+ // A collaboration-tools installation has no Cowork state to mount.
69
+ if (!isPluginOnly(record)) addMount('storage', '/var/lib/ours-cowork', 'state/cowork', false);
67
70
  }
68
71
  const definition = {
69
72
  services: {
@@ -73,7 +76,7 @@ export async function runDockerConversion(record, selected, operation, label, ef
73
76
  network_mode: 'none', read_only: true, cap_drop: ['ALL'],
74
77
  security_opt: ['no-new-privileges:true'], tmpfs: ['/tmp:rw,nosuid,nodev,noexec,size=64m,mode=1777'],
75
78
  entrypoint: ['node', '/opt/ours/docker/docker-layout-conversion.mjs'],
76
- environment: { HOME: '/tmp', OURS_DAEMON_ID: record.instanceId },
79
+ environment: { HOME: '/tmp', OURS_DAEMON_ID: record.instanceId, OURS_SERVER_APPLICATIONS: isPluginOnly(record) ? 'daemon' : '' },
77
80
  volumes: mounts,
78
81
  },
79
82
  },
@@ -82,7 +85,7 @@ export async function runDockerConversion(record, selected, operation, label, ef
82
85
  const path = join(record.root, `.conversion-compose-${randomUUID()}.json`);
83
86
  try {
84
87
  fs.writeFileSync(path, JSON.stringify(definition), { mode: 0o600, flag: 'wx' });
85
- const result = await effects.run('docker', ['compose', '--file', path, '--project-name', record.project,
88
+ const result = await runContainer(effects, record, ['compose', '--file', path, '--project-name', record.project,
86
89
  'run', '--rm', '--no-deps', '-T', 'state-operation', operation, ...(label ? [label] : [])]);
87
90
  if (operation === 'cleanup') {
88
91
  const summary = JSON.parse(result.stdout);
@@ -1,3 +1,4 @@
1
+ import { runContainer } from './container-engine.mjs';
1
2
  import * as fs from 'node:fs';
2
3
  import { join, basename } from 'node:path';
3
4
  import { randomUUID } from 'node:crypto';
@@ -46,7 +47,7 @@ export async function convertDockerInstallation(record, operation, effects) {
46
47
  await effects.serverLifecycle(record, 'start', running);
47
48
  const cleanup = await effects.runDockerConversion(record, volumes, 'cleanup');
48
49
  if (cleanup.emptyVolumes.length) {
49
- await effects.run('docker', ['volume', 'rm', ...cleanup.emptyVolumes.map(alias => volumes.sources[alias])]);
50
+ await runContainer(effects, record, ['volume', 'rm', ...cleanup.emptyVolumes.map(alias => volumes.sources[alias])]);
50
51
  }
51
52
  try {
52
53
  const stat = fs.lstatSync(source.configPath);
@@ -0,0 +1,60 @@
1
+ import { readFileSync, lstatSync, realpathSync, existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { atomicWriteConfig } from './config.mjs';
4
+ import { engineName, runContainer } from './container-engine.mjs';
5
+ import { isPluginOnly } from './product.mjs';
6
+
7
+ const assets = new URL('../assets/', import.meta.url);
8
+ const files = ['scripts/runtime/recover.mjs', 'scripts/runtime/dependency-ready.mjs', 'scripts/runtime/healthcheck.mjs',
9
+ ...['entrypoint.sh', 'start-telegram.sh', 'start-cowork.sh', 'start-messenger.sh'].map(f => `scripts/runtime/${f}`)];
10
+ const owned = (path, directory = false) => {
11
+ const s = lstatSync(path);
12
+ if (!(directory ? s.isDirectory() : s.isFile()) || s.uid !== process.getuid() || (!directory && s.nlink !== 1)
13
+ || realpathSync(path) !== path || (s.mode & 0o7000)) throw new Error('Unsafe retained recovery delivery');
14
+ };
15
+ /** Refresh installer-owned runtime scripts without changing source selection or state. */
16
+ export function refreshDockerRecovery(record) {
17
+ for (const dir of [record.root, record.workDir, join(record.workDir, 'scripts'), join(record.workDir, 'scripts/runtime')]) owned(dir, true);
18
+ const marker = join(record.workDir, '.recovery-rebuild');
19
+ let changed = false;
20
+ const replace = (name, bytes) => {
21
+ const path = join(record.workDir, name);
22
+ if (existsSync(path)) { owned(path); if (readFileSync(path).equals(bytes)) return; }
23
+ // Persist before edits, so interruption cannot reuse an image lacking recovery.
24
+ atomicWriteConfig(marker, 'required\n'); changed = true;
25
+ atomicWriteConfig(path, bytes.toString());
26
+ };
27
+ // Plugin-only daemons also serve the client prefix from the image.
28
+ const selected = isPluginOnly(record) ? [...files, 'scripts/runtime/daemon-client-prefix.mjs'] : files;
29
+ for (const name of selected) replace(name, readFileSync(new URL(name, assets)));
30
+ const dockerfile = join(record.workDir, 'Dockerfile'); owned(dockerfile);
31
+ const text = readFileSync(dockerfile, 'utf8');
32
+ const line = 'COPY --chmod=644 scripts/runtime/recover.mjs scripts/runtime/dependency-ready.mjs /opt/ours/docker/';
33
+ if (!text.includes('scripts/runtime/recover.mjs')) replace('Dockerfile', Buffer.from(text.replace('FROM node:24 AS maintenance', `${line}\nFROM node:24 AS maintenance`)));
34
+ const prefixLine = 'COPY --chmod=644 scripts/runtime/daemon-client-prefix.mjs /opt/ours/docker/daemon-client-prefix.mjs';
35
+ if (isPluginOnly(record) && !readFileSync(dockerfile, 'utf8').includes(prefixLine)) replace('Dockerfile', Buffer.from(readFileSync(dockerfile, 'utf8').replace('FROM node:24 AS maintenance', `${prefixLine}\nFROM node:24 AS maintenance`)));
36
+ return changed || existsSync(marker);
37
+ }
38
+
39
+ /** An overlay also applies to retained Compose files, with one-shot jobs untouched. */
40
+ export function recoveryCompose(record) {
41
+ return { services: Object.fromEntries(record.services.map(name => [name, { restart: 'unless-stopped' }])) };
42
+ }
43
+
44
+ /** Change only exact project-owned long-running containers; never start/recreate. */
45
+ export async function reconcileDockerRecovery(record, effects) {
46
+ if (engineName(record) !== 'docker') return;
47
+ const query = await runContainer(effects, record, ['ps', '-aq', '--no-trunc', '--filter', `label=com.docker.compose.project=${record.project}`]);
48
+ const ids = query.stdout.split(/\s+/).filter(Boolean);
49
+ if (!ids.length) return;
50
+ const inspected = JSON.parse((await runContainer(effects, record, ['inspect', ...ids])).stdout);
51
+ const selected = [];
52
+ for (const c of inspected) {
53
+ const labels = c.Config?.Labels;
54
+ if (labels?.['com.docker.compose.project'] !== record.project) throw new Error('Recovery container project ownership differs');
55
+ if (!record.services.includes(labels['com.docker.compose.service']) || labels['com.docker.compose.oneoff']?.toLowerCase() !== 'false') continue;
56
+ if (!ids.includes(c.Id)) throw new Error('Recovery container identity differs');
57
+ if (c.HostConfig?.RestartPolicy?.Name !== 'unless-stopped') selected.push(c.Id);
58
+ }
59
+ if (selected.length) await runContainer(effects, record, ['update', '--restart', 'unless-stopped', ...selected]);
60
+ }
@@ -1,5 +1,6 @@
1
+ import { engineName, runContainer } from './container-engine.mjs';
1
2
  /** Qualify cached images before reuse; repair only the known root-owned 0600 policy. */
2
- import { lstatSync, readFileSync, writeFileSync, mkdtempSync, rmSync, realpathSync, openSync, closeSync, fstatSync, fchmodSync, constants } from 'node:fs';
3
+ import { existsSync, readdirSync, lstatSync, readFileSync, writeFileSync, mkdtempSync, rmSync, realpathSync, openSync, closeSync, fstatSync, fchmodSync, constants } from 'node:fs';
3
4
  import { join } from 'node:path';
4
5
  import { createHash, randomUUID } from 'node:crypto';
5
6
  import { isDeepStrictEqual } from 'node:util';
@@ -11,6 +12,7 @@ const fail = message => { throw new Error(`Docker runtime verification refused:
11
12
  const imageId = value => /^sha256:[0-9a-f]{64}$/.test(value ?? '');
12
13
 
13
14
  export function refreshDockerPolicyCopy(record) {
15
+ let rebuildScripts = false;
14
16
  if (record.workDir !== join(record.root, 'runtime')) fail('Unsafe retained Dockerfile: runtime directory differs from installation record');
15
17
  for (const directory of [record.root, record.workDir]) {
16
18
  const stat = lstatSync(directory);
@@ -35,7 +37,32 @@ export function refreshDockerPolicyCopy(record) {
35
37
  const current = lstatSync(path);
36
38
  if (current.dev !== stat.dev || current.ino !== stat.ino || current.nlink !== 1) fail('Unsafe retained Dockerfile: file changed during normalization');
37
39
  const oldLine = /^COPY sources\.json \/opt\/ours\/sources\.json$/m;
38
- if (oldLine.test(text)) atomicWriteConfig(path, text.replace(oldLine, 'COPY --chmod=644 sources.json /opt/ours/sources.json'));
40
+ let updated = text.replace(oldLine, 'COPY --chmod=644 sources.json /opt/ours/sources.json');
41
+ // Only the shipped script COPY instructions are normalized. Existing image
42
+ // repair remains narrow; a private build context needs an actual rebuild.
43
+ const beforeScripts = updated;
44
+ const shipped = readFileSync(new URL('../assets/Dockerfile', import.meta.url), 'utf8');
45
+ const scriptCopies = new Map(shipped.split('\n').filter(line => line.startsWith('COPY --chmod=644 scripts/')).map(line => [line.replace(' --chmod=644', ''), line]));
46
+ updated = updated.split('\n').map(line => scriptCopies.get(line) || line).join('\n');
47
+ if (updated !== beforeScripts) {
48
+ for (const directory of ['scripts/maintenance', 'scripts/runtime']) {
49
+ const base = join(record.workDir, directory);
50
+ const dir = lstatSync(base);
51
+ if (!dir.isDirectory() || dir.uid !== process.getuid() || realpathSync(base) !== base) fail('Unsafe retained scripts directory');
52
+ for (const name of readdirSync(base)) {
53
+ if (!/\.(?:mjs|sh)$/.test(name)) continue;
54
+ const file = join(base, name), st = lstatSync(file);
55
+ if (!st.isFile() || st.nlink !== 1 || st.uid !== process.getuid() || realpathSync(file) !== file) fail('Unsafe retained script file');
56
+ if (!(st.mode & 0o004)) rebuildScripts = true;
57
+ }
58
+ }
59
+ }
60
+ // Store the need across an interrupted build. It is cleared only after the
61
+ // rebuilt image passes the same nonroot release/runtime qualification.
62
+ const marker = join(record.workDir, '.script-permissions-rebuild');
63
+ if (rebuildScripts) atomicWriteConfig(marker, 'required\n');
64
+ if (updated !== text) atomicWriteConfig(path, updated);
65
+ return rebuildScripts || existsSync(marker);
39
66
  } finally { closeSync(fd); }
40
67
  }
41
68
 
@@ -66,7 +93,7 @@ export async function qualifyDockerRuntime(record, effects) {
66
93
  if (![uid, gid].every(n => Number.isInteger(n) && n > 0)) fail('non-root runtime UID/GID required');
67
94
  const tag = `${record.project}:runtime`;
68
95
  const inspect = async target => {
69
- const { stdout } = await effects.run('docker', ['image', 'inspect', target], { timeout: 60000 });
96
+ const { stdout } = await runContainer(effects, record, ['image', 'inspect', target], { timeout: 60000 });
70
97
  const [value] = JSON.parse(stdout);
71
98
  if (!imageId(value?.Id) || !Array.isArray(value.RootFS?.Layers) || value.Config?.Labels?.['network.ours.build-context'] !== '1') fail('image lacks recognized build metadata');
72
99
  return value;
@@ -74,51 +101,59 @@ export async function qualifyDockerRuntime(record, effects) {
74
101
  const probe = async (id, user) => {
75
102
  const name = `ours-runtime-probe-${randomUUID()}`;
76
103
  try {
77
- const result = await effects.run('docker', ['run', '--rm', '--name', name, '--read-only', '--network', 'none', '--cap-drop', 'ALL',
104
+ const result = await runContainer(effects, record, ['run', '--rm', '--name', name, '--read-only', '--network', 'none', '--cap-drop', 'ALL',
78
105
  '--security-opt', 'no-new-privileges:true', '--pids-limit', '64', '--memory', '256m', '--user', user, '--entrypoint', 'node', id, '-e', probeScript],
79
106
  { allowCodes: [1, 74], timeout: 60000 });
80
107
  return { code: result.code, report: result.code === 0 ? JSON.parse(result.stdout) : null };
81
108
  } catch (error) {
82
109
  // A killed Docker client can leave its own bounded probe container behind.
83
- try { await effects.run('docker', ['rm', '-f', name], { allowCodes: [1], timeout: 10000 }); } catch {}
110
+ try { await runContainer(effects, record, ['rm', '-f', name], { allowCodes: [1], timeout: 10000 }); } catch {}
84
111
  throw error;
85
112
  }
86
113
  };
87
114
  const policy = readFileSync(record.sourcesPath), expectedHash = digest(policy);
88
- const check = (report, mode) => {
89
- if (!report || report.mode !== mode || report.uid !== 0 || report.gid !== 0 || !report.regular || report.links !== 1 || report.policyHash !== expectedHash) fail('image policy differs from retained selection or expected permissions');
115
+ const check = (report, mode, stage) => {
116
+ const expected = { mode, uid: 0, gid: 0, regular: true, links: 1, policyHash: expectedHash };
117
+ const mismatched = Object.keys(expected).filter(key => report?.[key] !== expected[key]);
118
+ if (mismatched.length) {
119
+ // Only fixed field names, a bounded numeric mode and a comparison boolean
120
+ // enter diagnostics. Never disclose policy content, hashes or probe output.
121
+ const observedMode = Number.isInteger(report?.mode) && report.mode >= 0 && report.mode <= 0o7777
122
+ ? report.mode.toString(8).padStart(4, '0') : 'invalid';
123
+ fail(`image policy verification failed (stage=${stage}; engine=${engineName(record)}; mismatched=${mismatched.join(',')}; mode=${observedMode}; expectedMode=${mode.toString(8).padStart(4, '0')}; policyMatch=${report?.policyHash === expectedHash})`);
124
+ }
90
125
  };
91
126
  const original = await inspect(tag);
92
127
  const ordinary = await probe(original.Id, `${uid}:${gid}`);
93
- if (ordinary.code === 0) { check(ordinary.report, 0o644); return; }
128
+ if (ordinary.code === 0) { check(ordinary.report, 0o644, 'ordinary'); return; }
94
129
  if (ordinary.code !== 74) fail('cached image is unusable; automatic repair only supports the known source-policy permission defect');
95
130
  const privileged = await probe(original.Id, '0:0');
96
131
  if (privileged.code !== 0) fail('original release graph could not be verified');
97
- check(privileged.report, 0o600);
132
+ check(privileged.report, 0o600, 'privileged');
98
133
  effects.out?.('Repairing cached Docker image permissions; keeping the selected packages and stored data.');
99
134
  const directory = mkdtempSync(join(record.root, '.image-permissions-'));
100
135
  const name = `ours-permission-repair-${randomUUID()}`, baseTag = `${name}:base`, candidateTag = `${name}:candidate`;
101
136
  try {
102
137
  // Unique local alias transports the immutable ID into BuildKit. The resulting
103
138
  // layer ancestry and complete execution config are checked before publication.
104
- await effects.run('docker', ['image', 'tag', original.Id, baseTag]);
139
+ await runContainer(effects, record, ['image', 'tag', original.Id, baseTag]);
105
140
  if ((await inspect(baseTag)).Id !== original.Id) fail('repair base image changed');
106
141
  writeFileSync(join(directory, 'sources.json'), policy, { mode: 0o600, flag: 'wx' });
107
142
  writeFileSync(join(directory, 'Dockerfile'), `FROM ${baseTag}\nCOPY --chmod=644 sources.json ${policyPath}\n`, { mode: 0o600, flag: 'wx' });
108
- await effects.run('docker', ['build', '--network=none', '--pull=false', '--tag', candidateTag, directory], { stream: true, timeout: 120000 });
143
+ await runContainer(effects, record, ['build', '--network=none', '--pull=false', '--tag', candidateTag, directory], { stream: true, timeout: 120000 });
109
144
  const candidate = await inspect(candidateTag);
110
145
  if (!isDeepStrictEqual(candidate.Config, original.Config) || !isDeepStrictEqual(candidate.RootFS.Layers.slice(0, original.RootFS.Layers.length), original.RootFS.Layers)
111
146
  || candidate.RootFS.Layers.length !== original.RootFS.Layers.length + 1) fail('repair changed image execution settings or ancestry');
112
147
  const verified = await probe(candidate.Id, `${uid}:${gid}`);
113
148
  if (verified.code !== 0) fail('repaired image did not pass runtime verification');
114
- check(verified.report, 0o644);
149
+ check(verified.report, 0o644, 'repaired');
115
150
  if (!isDeepStrictEqual(verified.report.records, privileged.report.records)) fail('repair changed build provenance');
116
151
  if ((await inspect(tag)).Id !== original.Id) fail('selected image changed during repair; retry setup');
117
- await effects.run('docker', ['image', 'tag', candidate.Id, tag]);
152
+ await runContainer(effects, record, ['image', 'tag', candidate.Id, tag]);
118
153
  effects.out?.('Cached Docker image repaired and verified; continuing setup.');
119
154
  } finally {
120
155
  for (const temporary of [candidateTag, baseTag]) {
121
- try { await effects.run('docker', ['image', 'rm', temporary], { allowCodes: [1], timeout: 10000 }); } catch {}
156
+ try { await runContainer(effects, record, ['image', 'rm', temporary], { allowCodes: [1], timeout: 10000 }); } catch {}
122
157
  }
123
158
  rmSync(directory, { recursive: true, force: true });
124
159
  }