@ours.network/install 2.1.4 → 2.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/setup.mjs CHANGED
@@ -1,10 +1,9 @@
1
1
  import { validateGatewayClientProfile } from './target.mjs';
2
2
  import { gatewayAddress } from './gateway.mjs';
3
- import { inspectLegacyMigration } from './legacy-migration.mjs';
4
3
  import { join } from 'node:path';
5
4
  import { parseSetupArgs, collectSetupOptions, validateSetupOptions } from './setup-options.mjs';
6
5
  import { parseNetworkArgs, validateHostProfile, InstallUsageError } from './target.mjs';
7
- import { clientPackageNames, validateInstallation } from './plan.mjs';
6
+ import { clientPackageNames, validateInstallation, refuseOldLayout } from './plan.mjs';
8
7
  import { runServerCommand, runClientCommand } from './orchestrate.mjs';
9
8
  import { banner, heading, info, ok, warn, progress } from './ui.mjs';
10
9
  import { isCancel } from './prompt.mjs';
@@ -44,23 +43,14 @@ export async function prepareSetupPlan(options, effects) {
44
43
  if (effects.env?.[name]?.trim()) throw new InstallUsageError(`${name} conflicts with the selected client profile. Clear this override before full-stack/client setup; nothing was changed.`);
45
44
  }
46
45
  }
47
- if (options.scope !== 'client' && !options.migrateFrom) validateIdentityName(options.identityName);
46
+ if (options.scope !== 'client') validateIdentityName(options.identityName);
48
47
  if (options.fleetSettingsPath) validateFleetSettings(readObject(effects, options.fleetSettingsPath, 'Fleet settings'));
49
48
  const policy = options.sources ? readObject(effects, options.sources, 'Source policy') : effects.packagedSourcePolicy();
50
49
  plan.sourcePolicy = policy;
51
- if (options.migrateFrom) {
52
- for (const name of ['OURS_API_TOKEN', 'OURS_API_VISIBILITY', 'OURS_STATE_DIR', 'OURS_PORT', 'OURS_DAEMON_ID', 'OURS_DATABASE_PROVIDER', 'OURS_DATABASE_URL']) {
53
- if (effects.env?.[name]?.trim()) throw new InstallUsageError(`${name} conflicts with legacy migration. Clear it before setup; nothing was changed.`);
54
- }
55
- plan.legacyPlan = await (effects.inspectLegacyMigration ?? inspectLegacyMigration)(options, effects);
56
- plan.sourcePolicy = plan.legacyPlan.journal.sourcePolicy ?? policy;
57
- plan.identityName = plan.legacyPlan.source?.rootName ?? plan.legacyPlan.journal.identities.find(row => row.kind === 'root')?.name;
58
- validateIdentityName(plan.identityName);
59
- }
60
50
  if (options.scope !== 'client') {
61
51
  const value = effects.readJson(join(options.stateDir, 'installation.json'));
62
52
  if (value) {
63
- plan.existing = validateInstallation(value, options.stateDir);
53
+ plan.existing = validateInstallation(refuseOldLayout(value, options.stateDir, effects.readJson), options.stateDir);
64
54
  // The kind of installation is retained exactly; it is never widened or narrowed implicitly.
65
55
  if (options.product !== undefined && options.product !== productOf(plan.existing))
66
56
  throw new InstallUsageError(`This folder contains ${PRODUCT_LABELS[productOf(plan.existing)].toLowerCase()}. It is kept as it is; nothing was changed. Use a separate empty folder for the other kind of installation, or remove this one first.`);
@@ -71,7 +61,7 @@ export async function prepareSetupPlan(options, effects) {
71
61
  if (options.explicitPorts?.includes(key) && options[key] !== plan.existing[key]) throw new InstallUsageError(`${key} conflicts with the retained installation`);
72
62
  plan[key] = plan.existing[key];
73
63
  }
74
- if (options.operation === 'install' && !options.migrateFrom) {
64
+ if (options.operation === 'install') {
75
65
  const retained = readObject(effects, plan.existing.sourcesPath, 'Retained source policy');
76
66
  plan.sourcePolicy = options.scope === 'server' ? retained : completeReleasePolicy(retained, options.sources ? policy : null);
77
67
  }
@@ -0,0 +1,98 @@
1
+ import * as fs from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { installationPaths, SERVER_SERVICES } from './plan.mjs';
5
+ import { runContainer } from './container-engine.mjs';
6
+ import { isPluginOnly } from './product.mjs';
7
+ import { scanSource } from '../assets/scripts/maintenance/state-archive.mjs';
8
+ import { recordNames, readBuildRecords } from '../assets/scripts/maintenance/build-context.mjs';
9
+
10
+ const PROVENANCE_DIRECTORY = '.ours-provenance';
11
+
12
+ function privateFile(path) {
13
+ const stat = fs.lstatSync(path);
14
+ if (!stat.isFile() || stat.uid !== process.getuid() || stat.gid !== process.getgid() || (stat.mode & 0o7777) !== 0o600) {
15
+ throw new Error(`Unsafe managed state file: ${path}`);
16
+ }
17
+ return fs.readFileSync(path);
18
+ }
19
+
20
+ function readConfig(path) {
21
+ const value = JSON.parse(privateFile(path));
22
+ if (!value || Array.isArray(value) || typeof value !== 'object') throw new Error('Managed configuration must be an object');
23
+ return value;
24
+ }
25
+
26
+ function pathExists(path) {
27
+ try { fs.lstatSync(path); return true; }
28
+ catch (error) { if (error.code === 'ENOENT') return false; throw error; }
29
+ }
30
+
31
+ /** Offline validation of stopped native state against the selected build. */
32
+ export function validatePackageState(record, tree = installationPaths(record).state) {
33
+ const paths = installationPaths(record);
34
+ const physical = path => join(tree, relative(paths.state, path));
35
+ scanSource(tree, { uid: process.getuid(), gid: process.getgid() });
36
+ const records = readBuildRecords(record.workDir);
37
+ const BUILD_RECORDS = recordNames(records);
38
+ for (const component of SERVER_SERVICES) {
39
+ const marker = join(physical(paths[component]), PROVENANCE_DIRECTORY);
40
+ if (fs.readdirSync(marker).sort().join() !== [...BUILD_RECORDS].sort().join()) {
41
+ throw new Error(`Incomplete ${component} provenance`);
42
+ }
43
+ for (const name of BUILD_RECORDS) {
44
+ if (!privateFile(join(marker, name)).equals(records[name])) {
45
+ throw new Error(`Stored ${component} differs from the selected build`);
46
+ }
47
+ }
48
+ const configPath = join(physical(paths[component]), 'config.json');
49
+ if (pathExists(configPath)) readConfig(configPath);
50
+ }
51
+ const daemon = readConfig(physical(paths.config));
52
+ const profile = readConfig(join(physical(paths.mcp), 'profile.json'));
53
+ if (daemon.stateDir !== paths.daemon || daemon.port !== record.port
54
+ || daemon.networkMcp?.applicationConfigPath !== join(paths.mcp, 'config.json')
55
+ || profile.expectedInstanceId !== record.instanceId
56
+ || profile.credentialPath !== join(paths.daemon, 'daemon-token')
57
+ || profile.endpoint !== `http://127.0.0.1:${record.port}`
58
+ || JSON.stringify(daemon.networkMcp.profile) !== JSON.stringify(profile)) {
59
+ throw new Error('Daemon/MCP deployment configuration is inconsistent');
60
+ }
61
+ if (pathExists(join(physical(paths.mcp), 'config.json'))) readConfig(join(physical(paths.mcp), 'config.json'));
62
+ if (readConfig(join(physical(paths.cowork), 'config.json')).stateDir !== paths.cowork) {
63
+ throw new Error('Cowork configuration selects another state directory');
64
+ }
65
+ for (const credential of [profile.credentialPath, ...Object.values(paths.credentials)]) {
66
+ if (!privateFile(physical(credential)).length) throw new Error('Managed credential is empty');
67
+ }
68
+ }
69
+
70
+ /** Offline validation of stopped Docker state in the selected maintenance image. */
71
+ export async function validateDockerState(record, effects) {
72
+ const mount = (target, subpath, readOnly) => ({ type: 'volume', source: 'storage', target, read_only: readOnly, volume: { nocopy: true, ...(subpath ? { subpath } : {}) } });
73
+ const definition = {
74
+ services: {
75
+ 'state-operation': {
76
+ image: `${record.project}:maintenance`, platform: 'linux/amd64',
77
+ user: `${record.uid ?? 1000}:${record.gid ?? 1000}`,
78
+ network_mode: 'none', read_only: true, cap_drop: ['ALL'],
79
+ security_opt: ['no-new-privileges:true'], tmpfs: ['/tmp:rw,nosuid,nodev,noexec,size=64m,mode=1777'],
80
+ // Retained maintenance images from earlier installers ship the same validate entrypoint.
81
+ entrypoint: ['node', '/opt/ours/docker/docker-layout-conversion.mjs'],
82
+ environment: { HOME: '/tmp', OURS_DAEMON_ID: record.instanceId, OURS_SERVER_APPLICATIONS: isPluginOnly(record) ? 'daemon' : '' },
83
+ // A collaboration-tools installation has no Cowork state to mount.
84
+ volumes: [mount('/storage'), mount('/var/lib/ours', 'state/daemon', true),
85
+ ...(isPluginOnly(record) ? [] : [mount('/var/lib/ours-cowork', 'state/cowork', false)])],
86
+ },
87
+ },
88
+ volumes: { storage: { external: true, name: `${record.project}_server-storage` } },
89
+ };
90
+ const path = join(record.root, `.validation-compose-${randomUUID()}.json`);
91
+ try {
92
+ fs.writeFileSync(path, JSON.stringify(definition), { mode: 0o600, flag: 'wx' });
93
+ await runContainer(effects, record, ['compose', '--file', path, '--project-name', record.project,
94
+ 'run', '--rm', '--no-deps', '-T', 'state-operation', 'validate']);
95
+ } finally {
96
+ fs.rmSync(path, { force: true });
97
+ }
98
+ }
package/lib/target.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { serverBase } from './gateway.mjs';
2
+ import { MIGRATE_FROM_UNSUPPORTED } from './plan.mjs';
2
3
  // ours-install v3 — argument handling and daemon detection.
3
4
  //
4
5
  // Pure argument handling and daemon-target selection. The orchestrator
@@ -491,6 +492,7 @@ export function parseNetworkArgs(argv) {
491
492
  const seen = new Set();
492
493
  for (let i = optionsStart; i < argv.length; i++) {
493
494
  const match = /^--([a-z-]+)(?:=(.*))?$/.exec(argv[i]);
495
+ if (match?.[1] === 'migrate-from') throw new InstallUsageError(MIGRATE_FROM_UNSUPPORTED);
494
496
  if (!match || !allowed.includes(match[1]) || seen.has(match[1])) throw new InstallUsageError(`Unexpected or repeated option: ${argv[i]}`);
495
497
  const [, name, inline] = match;
496
498
  seen.add(name);
package/lib/usage.mjs CHANGED
@@ -61,10 +61,8 @@ export const USAGE = `ours-install — interactive setup with optional CLI prese
61
61
  --server-url URL external gateway URL (Docker install; configure authenticated entry separately)
62
62
  --cowork-port N cowork port (default 3052)
63
63
  --messenger-port N messenger port (default 8420)
64
- --compatible required for server updates and legacy state migration
65
- --migrate-from CONFIG migrate an existing daemon into a new managed root; install only
66
- requires an absolute config path and --compatible
67
- --migrate explicit legacy credential migration; separate from --migrate-from
64
+ --compatible required for server updates
65
+ --migrate explicit legacy credential migration in the daemon configuration
68
66
  --dry-run show the validated plan without changing anything
69
67
  --help, -h show help
70
68
  --version, -V print installer version
package/lib/welcome.mjs CHANGED
@@ -11,7 +11,7 @@
11
11
  // installer underneath.
12
12
 
13
13
  import { join } from 'node:path';
14
- import { validateInstallation } from './plan.mjs';
14
+ import { validateInstallation, refuseOldLayout, UNSUPPORTED_LAYOUT } from './plan.mjs';
15
15
  import { productOf, isPluginOnly, PLUGIN_ONLY, PRODUCT_LABELS, PLUGIN_ONLY_INTEGRATIONS } from './product.mjs';
16
16
  import { validateSetupOptions, defaultHostname } from './setup-options.mjs';
17
17
  import { validateIdentityName } from './server-onboarding.mjs';
@@ -45,17 +45,15 @@ export function findInstallations(effects, extra = []) {
45
45
  const value = effects.readJson(join(root, 'installation.json'));
46
46
  if (!value) continue;
47
47
  try {
48
- const record = validateInstallation(value, root);
49
- const journal = record.legacyMigrationSource ? effects.readJson(join(root, 'legacy-migration.json')) : null;
50
- found.push({ root, record, product: productOf(record),
51
- pending: record.buildTransition ? record.buildTransition.operation : record.layoutConversion ? 'install'
52
- : record.legacyMigrationSource && journal?.phase !== 'complete' ? 'install' : null });
53
- } catch { found.push({ root, invalid: true }); }
48
+ const record = validateInstallation(refuseOldLayout(value, root, effects.readJson), root);
49
+ found.push({ root, record, product: productOf(record), pending: record.buildTransition ? record.buildTransition.operation : null });
50
+ } catch (error) { found.push({ root, invalid: true, ...(error.message === UNSUPPORTED_LAYOUT ? { old: true } : {}) }); }
54
51
  }
55
52
  return found;
56
53
  }
57
54
 
58
55
  function describe(item) {
56
+ if (item.old) return `An old Ours installation layout that is no longer supported (left unchanged): ${item.root}`;
59
57
  if (item.invalid) return `An Ours folder that could not be read: ${item.root}`;
60
58
  const engine = item.record.mode === 'packages' ? 'directly on this computer' : item.record.containerEngine === 'podman' ? 'in Podman' : 'in Docker';
61
59
  return `${PRODUCT_LABELS[item.product]} — folder ${item.root}, running ${engine}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ours.network/install",
3
- "version": "2.1.4",
3
+ "version": "2.1.6",
4
4
  "private": false,
5
5
  "description": "The all-in-one ours.network installer: one shared daemon, MCP, cowork, Telegram, Fleet initialization, harness plugins, Human identity, progress UI, and guided next steps.",
6
6
  "type": "module",
@@ -1,5 +0,0 @@
1
- FROM nginx:1.28-alpine@sha256:a8b39bd9cf0f83869a2162827a0caf6137ddf759d50a171451b335cecc87d236
2
- COPY --chmod=644 nginx.conf /etc/nginx/ours.conf.template
3
- COPY --chmod=644 gateway-entrypoint.sh /gateway-entrypoint.sh
4
- USER 101:101
5
- ENTRYPOINT ["/bin/sh", "/gateway-entrypoint.sh"]
@@ -1,103 +0,0 @@
1
- /** Import a stopped, read-only host migration stage into the managed Docker volume. */
2
- import * as fs from 'node:fs';
3
- import { dirname, join, resolve, isAbsolute } from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
- import { randomUUID } from 'node:crypto';
6
- // Repository layout and the maintenance image intentionally place this binding differently.
7
- const nativeModule = new URL('../maintenance/state-native.mjs', import.meta.url);
8
- const { publishNoReplace } = await import(fs.existsSync(nativeModule) ? nativeModule.href : new URL('./state-native.mjs', import.meta.url).href);
9
-
10
- const MARKER = '.ours-legacy-import.json';
11
- const COMPONENTS = ['mcp', 'daemon'];
12
- const fail = message => { throw Error(`Legacy volume import: ${message}`); };
13
- function canonical(path) {
14
- if (typeof path !== 'string' || !isAbsolute(path) || resolve(path) !== path) fail('paths must be normalized absolute paths');
15
- if (fs.realpathSync(path) !== path) fail('symlink paths are not supported');
16
- }
17
- function privateEntry(path, uid, gid, directory) {
18
- const stat = fs.lstatSync(path);
19
- if (!(directory ? stat.isDirectory() : stat.isFile()) || stat.isSymbolicLink()
20
- || stat.uid !== uid || stat.gid !== gid
21
- || (directory ? (stat.mode & 0o7777) !== 0o700 : ((stat.mode & 0o7077) !== 0 || !(stat.mode & 0o400)))
22
- || (!directory && stat.nlink !== 1)) fail('unsafe ownership, permissions, or linked state entry');
23
- return stat;
24
- }
25
- function scan(root, uid, gid) {
26
- const entries = [];
27
- function visit(path, relative) {
28
- const stat = fs.lstatSync(path), directory = stat.isDirectory();
29
- privateEntry(path, uid, gid, directory); entries.push({ relative, directory, mode: stat.mode & 0o700 });
30
- if (directory) for (const name of fs.readdirSync(path).sort()) visit(join(path, name), relative ? join(relative, name) : name);
31
- }
32
- canonical(root); visit(root, ''); return entries;
33
- }
34
- function readReceipt(root, uid, gid, targetRoot) {
35
- privateEntry(join(root, MARKER), uid, gid, false);
36
- const value = JSON.parse(fs.readFileSync(join(root, MARKER), 'utf8'));
37
- const keys = ['sourceStateDir', 'sourceConfigPath', 'targetRoot', 'rootName'];
38
- if (!value || typeof value !== 'object' || Array.isArray(value)
39
- || Object.keys(value).sort().join('\0') !== [...keys].sort().join('\0')
40
- || keys.some(key => typeof value[key] !== 'string' || !value[key])
41
- || value.targetRoot !== targetRoot
42
- || ['sourceStateDir', 'sourceConfigPath', 'targetRoot'].some(key => !isAbsolute(value[key]) || resolve(value[key]) !== value[key])) fail('invalid or mismatched migration receipt');
43
- return Object.fromEntries(keys.map(key => [key, value[key]]));
44
- }
45
- const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
46
- function existingDestination(path, expected, uid, gid, targetRoot) {
47
- if (!fs.existsSync(path)) return false;
48
- canonical(path); privateEntry(path, uid, gid, true);
49
- if (!fs.readdirSync(path).length) return false;
50
- if (!fs.existsSync(join(path, MARKER)) || !same(readReceipt(path, uid, gid, targetRoot), expected)) fail('nonmatching existing destination');
51
- return true;
52
- }
53
- function makeDirectory(path, uid, gid) {
54
- if (!fs.existsSync(path)) { fs.mkdirSync(path, { mode: 0o700 }); fs.chownSync(path, uid, gid); }
55
- canonical(path); privateEntry(path, uid, gid, true);
56
- }
57
-
58
- /** Caller holds installation exclusion and has stopped all destination writers. */
59
- export function importLegacyVolume({ sourceRoot = '/legacy-import', storageRoot = '/storage', targetRoot, uid, gid }) {
60
- if (![uid, gid].every(value => Number.isSafeInteger(value) && value >= 0)) fail('numeric target UID/GID required');
61
- if (typeof targetRoot !== 'string' || !isAbsolute(targetRoot) || resolve(targetRoot) !== targetRoot) fail('expected target root required');
62
- canonical(sourceRoot); canonical(storageRoot);
63
- const sourceOwner = fs.lstatSync(sourceRoot);
64
- privateEntry(sourceRoot, sourceOwner.uid, sourceOwner.gid, true);
65
- const sources = COMPONENTS.map(component => {
66
- const path = join(sourceRoot, component);
67
- const entries = scan(path, sourceOwner.uid, sourceOwner.gid);
68
- return { component, path, entries, receipt: readReceipt(path, sourceOwner.uid, sourceOwner.gid, targetRoot) };
69
- });
70
- if (!same(sources[0].receipt, sources[1].receipt)) fail('source daemon and MCP receipts differ');
71
- const rootStat = fs.lstatSync(storageRoot);
72
- const freshRoot = rootStat.isDirectory() && rootStat.uid === 0 && rootStat.gid === 0 && fs.readdirSync(storageRoot).length === 0;
73
- if (!freshRoot) privateEntry(storageRoot, uid, gid, true);
74
- const state = join(storageRoot, 'state');
75
- if (fs.existsSync(state)) { canonical(state); privateEntry(state, uid, gid, true); }
76
- // Validate every existing destination before changing even an empty volume.
77
- for (const source of sources) source.reused = existingDestination(join(state, source.component), source.receipt, uid, gid, targetRoot);
78
- if (freshRoot) { fs.chmodSync(storageRoot, 0o700); fs.chownSync(storageRoot, uid, gid); }
79
- makeDirectory(state, uid, gid);
80
- for (const source of sources) {
81
- if (source.reused) continue;
82
- const destination = join(state, source.component), staging = join(state, `.legacy-import-${randomUUID()}`);
83
- try {
84
- fs.cpSync(source.path, staging, { recursive: true, errorOnExist: true, force: false });
85
- for (const entry of [...source.entries].reverse()) {
86
- const path = entry.relative ? join(staging, entry.relative) : staging;
87
- fs.chmodSync(path, entry.mode); fs.chownSync(path, uid, gid);
88
- }
89
- scan(staging, uid, gid);
90
- if (!same(readReceipt(staging, uid, gid, targetRoot), source.receipt)) fail('copied receipt changed');
91
- if (fs.existsSync(destination)) fs.rmdirSync(destination); // empty skeleton only
92
- publishNoReplace(staging, destination);
93
- } finally { fs.rmSync(staging, { recursive: true, force: true }); }
94
- }
95
- return { imported: sources.filter(source => !source.reused).map(source => source.component), retained: sources.filter(source => source.reused).map(source => source.component) };
96
- }
97
-
98
- if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
99
- try {
100
- importLegacyVolume({ targetRoot: process.env.OURS_LEGACY_TARGET_ROOT, uid: Number(process.env.OURS_UID), gid: Number(process.env.OURS_GID) });
101
- console.log('Legacy daemon and MCP state imported into the selected volume.');
102
- } catch (error) { console.error(error.message); process.exitCode = 1; }
103
- }
@@ -1,100 +0,0 @@
1
- import { runContainer } from './container-engine.mjs';
2
- import { isPluginOnly } from './product.mjs';
3
- import * as fs from 'node:fs';
4
- import { join } from 'node:path';
5
- import { randomUUID } from 'node:crypto';
6
- import { atomicWriteConfig } from './config.mjs';
7
-
8
- /** Update installer assets while retaining the selected application build. */
9
- export async function prepareDockerConversionRuntime(record, effects, assets) {
10
- if (record.schema !== 1 || record.mode !== 'docker' || !/^ours-[a-z0-9]+$/.test(record.project)) {
11
- throw new Error('Select the legacy Docker runtime for conversion');
12
- }
13
- const compose = join(record.workDir, 'docker-compose.yaml');
14
- const legacy = join(record.workDir, 'docker-compose.legacy.yaml');
15
- if (!fs.existsSync(legacy)) {
16
- atomicWriteConfig(legacy, fs.readFileSync(compose));
17
- }
18
- const context = fs.mkdtempSync(join(record.root, '.conversion-build-'));
19
- try {
20
- fs.cpSync(join(assets, 'scripts/runtime'), join(context, 'runtime'), { recursive: true });
21
- fs.cpSync(join(assets, 'scripts/maintenance'), join(context, 'maintenance'), { recursive: true });
22
- const { dependencies } = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url)));
23
- fs.writeFileSync(join(context, 'package.json'), JSON.stringify({ private: true, type: 'module', dependencies }));
24
- fs.writeFileSync(join(context, 'Dockerfile'), `# syntax=docker/dockerfile:1
25
- FROM ${record.project}:runtime AS runtime
26
- COPY --chmod=644 runtime/ /opt/ours/docker/
27
- COPY --chmod=644 maintenance/release-graph.mjs /opt/ours/maintenance/release-graph.mjs
28
- FROM runtime AS maintenance
29
- USER 0:0
30
- COPY --chmod=644 maintenance/ /opt/ours/docker/
31
- COPY --chmod=644 package.json /opt/ours/docker/package.json
32
- RUN npm install --prefix /opt/ours/docker --omit=dev --ignore-scripts --no-audit --no-fund
33
- USER 1000:1000
34
- ENTRYPOINT ["node", "/opt/ours/docker/state-operation.mjs"]
35
- `);
36
- // Build maintenance first: both targets inherit the same retained runtime.
37
- for (const target of ['maintenance', 'runtime']) {
38
- await runContainer(effects, record, ['build', '--platform', 'linux/amd64', '--target', target,
39
- '--tag', `${record.project}:${target}`, context]);
40
- }
41
- atomicWriteConfig(compose, fs.readFileSync(join(assets, 'docker-compose.yaml')));
42
- } finally {
43
- fs.rmSync(context, { recursive: true, force: true });
44
- }
45
- }
46
-
47
- /** Run the existing maintenance service with the volumes selected by the installer. */
48
- export async function runDockerConversion(record, selected, operation, label, effects) {
49
- if (!['prepare', 'validate', 'cleanup'].includes(operation)) throw new Error('Unsupported Docker conversion operation');
50
- const volumes = { storage: { external: true, name: selected.target } };
51
- const mounts = [{ type: 'volume', source: 'storage', target: '/storage', volume: { nocopy: true } }];
52
- const addMount = (source, target, subpath, readOnly) => mounts.push({
53
- type: 'volume', source, target, read_only: readOnly,
54
- volume: { nocopy: true, ...(subpath ? { subpath } : {}) },
55
- });
56
- if (operation !== 'validate') {
57
- for (const [alias, name] of Object.entries(selected.sources)) {
58
- const source = `source-${alias}`;
59
- volumes[source] = { external: true, name };
60
- addMount(source, `/source/${alias}`, undefined, operation === 'prepare' && alias !== 'cowork');
61
- }
62
- if (operation === 'prepare') {
63
- addMount('source-daemon', '/var/lib/ours', 'data', true);
64
- addMount('source-cowork', '/var/lib/ours-cowork', 'data', false);
65
- }
66
- } else {
67
- addMount('storage', '/var/lib/ours', 'state/daemon', true);
68
- // A collaboration-tools installation has no Cowork state to mount.
69
- if (!isPluginOnly(record)) addMount('storage', '/var/lib/ours-cowork', 'state/cowork', false);
70
- }
71
- const definition = {
72
- services: {
73
- 'state-operation': {
74
- image: `${record.project}:maintenance`, platform: 'linux/amd64',
75
- user: `${record.uid ?? 1000}:${record.gid ?? 1000}`,
76
- network_mode: 'none', read_only: true, cap_drop: ['ALL'],
77
- security_opt: ['no-new-privileges:true'], tmpfs: ['/tmp:rw,nosuid,nodev,noexec,size=64m,mode=1777'],
78
- entrypoint: ['node', '/opt/ours/docker/docker-layout-conversion.mjs'],
79
- environment: { HOME: '/tmp', OURS_DAEMON_ID: record.instanceId, OURS_SERVER_APPLICATIONS: isPluginOnly(record) ? 'daemon' : '' },
80
- volumes: mounts,
81
- },
82
- },
83
- volumes,
84
- };
85
- const path = join(record.root, `.conversion-compose-${randomUUID()}.json`);
86
- try {
87
- fs.writeFileSync(path, JSON.stringify(definition), { mode: 0o600, flag: 'wx' });
88
- const result = await runContainer(effects, record, ['compose', '--file', path, '--project-name', record.project,
89
- 'run', '--rm', '--no-deps', '-T', 'state-operation', operation, ...(label ? [label] : [])]);
90
- if (operation === 'cleanup') {
91
- const summary = JSON.parse(result.stdout);
92
- if (!Array.isArray(summary.emptyVolumes) || summary.emptyVolumes.some(alias => !Object.hasOwn(selected.sources, alias))) {
93
- throw new Error('Invalid retired-volume cleanup result');
94
- }
95
- return summary;
96
- }
97
- } finally {
98
- fs.rmSync(path, { force: true });
99
- }
100
- }
@@ -1,63 +0,0 @@
1
- import { runContainer } from './container-engine.mjs';
2
- import * as fs from 'node:fs';
3
- import { join, basename } from 'node:path';
4
- import { randomUUID } from 'node:crypto';
5
- import { installationPaths, validateInstallation, SERVER_SERVICES } from './plan.mjs';
6
-
7
- /** The installation lock is held by the caller; installation.json selects the live side. */
8
- export async function convertDockerInstallation(record, operation, effects) {
9
- validateInstallation(record, record.root);
10
- if (record.mode !== 'docker' || (record.schema !== 1 && !record.layoutConversion)) {
11
- throw new Error('Select a legacy or pending Docker installation');
12
- }
13
- const source = record.layoutConversion?.sourceRecord ?? record;
14
- const published = record.schema === 2;
15
- const writeSelection = value => effects.writeJson(join(record.root, 'installation.json'), JSON.stringify(value, null, 2) + '\n');
16
- const volumes = await effects.selectConversionVolumes(
17
- { ...source, layoutConversion: record.layoutConversion }, { allowMissingSources: published });
18
- if (published && !volumes.targetExists) throw new Error('Published Docker state volume is missing');
19
-
20
- if (!published) {
21
- await effects.prepareDockerConversionRuntime(source);
22
- if (!record.layoutConversion) {
23
- record = { ...source, layoutConversion: {
24
- version: 1, sourceRecord: source,
25
- runningServices: await effects.serverLifecycle(source, 'status'),
26
- backupPath: join(source.root, 'storage/backups', `before-layout-2-${randomUUID()}`),
27
- } };
28
- writeSelection(record);
29
- }
30
- // The full tree includes all four component volumes, even when a component
31
- // is not selected for restart. Exclude every former managed writer.
32
- await effects.retireLegacyServices({ ...source, services: [...SERVER_SERVICES] });
33
- const target = { ...source, schema: 2 };
34
- target.configPath = installationPaths(target).config;
35
- // Preparation initializes only owned storage; it does not issue authority.
36
- await effects.prepareInstallation(target);
37
- await effects.runDockerConversion(source, volumes, 'prepare', basename(record.layoutConversion.backupPath));
38
- record = { ...target, layoutConversion: record.layoutConversion };
39
- writeSelection(record);
40
- } else {
41
- await effects.serverLifecycle(record, 'stop');
42
- await effects.confirmDockerWritersStopped(record);
43
- }
44
-
45
- await effects.runDockerConversion(record, volumes, 'validate');
46
- const running = ['install', 'start'].includes(operation) ? record.services : record.layoutConversion.runningServices;
47
- await effects.serverLifecycle(record, 'start', running);
48
- const cleanup = await effects.runDockerConversion(record, volumes, 'cleanup');
49
- if (cleanup.emptyVolumes.length) {
50
- await runContainer(effects, record, ['volume', 'rm', ...cleanup.emptyVolumes.map(alias => volumes.sources[alias])]);
51
- }
52
- try {
53
- const stat = fs.lstatSync(source.configPath);
54
- // Private host files may inherit a directory's group on macOS.
55
- if (!stat.isFile() || stat.uid !== process.getuid()
56
- || (stat.mode & 0o7777) !== 0o600) throw new Error('Unsafe former installer configuration');
57
- fs.unlinkSync(source.configPath);
58
- } catch (error) { if (error.code !== 'ENOENT') throw error; }
59
- const finished = { ...record };
60
- delete finished.layoutConversion;
61
- writeSelection(finished);
62
- return finished;
63
- }