@ours.network/install 1.2.1-nightly.2 → 1.2.1-nightly.21

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 (46) hide show
  1. package/GATEWAY_SETUP.md +178 -0
  2. package/README.md +337 -12
  3. package/ROOTLESS_PODMAN_VALIDATION.md +210 -0
  4. package/assets/Dockerfile +16 -12
  5. package/assets/Dockerfile.gateway +5 -0
  6. package/assets/docker-compose.yaml +21 -1
  7. package/assets/fleet-settings.example.json +48 -0
  8. package/assets/gateway-entrypoint.sh +37 -0
  9. package/assets/release-lock.json +1111 -4265
  10. package/assets/release.json +33 -19
  11. package/assets/scripts/build/build-common.mjs +1 -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 +7 -3
  16. package/assets/scripts/maintenance/release-graph.mjs +18 -1
  17. package/assets/scripts/maintenance/state-operation.mjs +4 -2
  18. package/assets/scripts/runtime/client-setup.mjs +3 -3
  19. package/assets/scripts/runtime/entrypoint.sh +1 -1
  20. package/assets/scripts/runtime/legacy-import.mjs +103 -0
  21. package/assets/sources.json +46 -28
  22. package/install.mjs +5 -1
  23. package/lib/build-transition.mjs +1 -0
  24. package/lib/client-cli.mjs +127 -0
  25. package/lib/container-engine.mjs +127 -0
  26. package/lib/docker-conversion-runtime.mjs +3 -2
  27. package/lib/docker-layout-installation.mjs +2 -1
  28. package/lib/docker-runtime-repair.mjs +152 -0
  29. package/lib/effects.mjs +276 -126
  30. package/lib/gateway-transition.mjs +87 -0
  31. package/lib/gateway.mjs +142 -0
  32. package/lib/legacy-migration.mjs +213 -0
  33. package/lib/legacy-state.mjs +205 -0
  34. package/lib/managed-cli.mjs +164 -0
  35. package/lib/orchestrate.mjs +114 -38
  36. package/lib/plan.mjs +22 -9
  37. package/lib/podman-preflight.mjs +40 -0
  38. package/lib/prompt.mjs +113 -119
  39. package/lib/server-onboarding.mjs +63 -16
  40. package/lib/setup-options.mjs +137 -35
  41. package/lib/setup.mjs +30 -16
  42. package/lib/target.mjs +24 -8
  43. package/lib/uninstall.mjs +2 -2
  44. package/lib/usage.mjs +9 -4
  45. package/lib/workspace-setup.mjs +83 -0
  46. package/package.json +4 -2
@@ -0,0 +1,87 @@
1
+ import { existsSync, lstatSync, readFileSync, unlinkSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { gatewayAddress } from './gateway.mjs';
4
+ import { validateInstallation } from './plan.mjs';
5
+ import { atomicWriteConfig, snapshotConfig, restoreConfig } from './config.mjs';
6
+
7
+ // Called under the installation lock. No stored state or credentials are changed.
8
+ export async function enableGateway(record, args, effects) {
9
+ validateInstallation(record, record.root);
10
+ if (record.mode !== 'docker' || record.schema !== 2 || record.buildTransition || record.layoutConversion)
11
+ throw new Error('Gateway migration requires a settled schema-2 Docker installation');
12
+ const journal = join(record.root, 'gateway-transition.json');
13
+ const recordPath = join(record.root, 'installation.json');
14
+ const profilePath = join(effects.home, '.ours-client', 'profile.json');
15
+ const paths = [recordPath, ...['docker-compose.gateway.yaml', 'nginx.conf', 'Dockerfile.gateway'].map(name => join(record.workDir, name)), profilePath];
16
+ const snapshot = path => {
17
+ if (existsSync(path)) {
18
+ const stat = lstatSync(path);
19
+ if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid() || (stat.mode & (path === profilePath || path === journal || path === recordPath ? 0o077 : 0o022)))
20
+ throw new Error('Gateway migration requires private owned configuration files');
21
+ }
22
+ return snapshotConfig(path);
23
+ };
24
+ async function rollback(saved) {
25
+ const phase = value => { saved.phase = value; atomicWriteConfig(journal, JSON.stringify(saved, null, 2) + '\n'); };
26
+ if (saved.phase === 'switching') phase('rollback-stopping');
27
+ if (saved.phase === 'rollback-stopping') {
28
+ await effects.serverLifecycle(saved.candidate, 'stop');
29
+ await effects.removeGatewayContainer(saved.candidate);
30
+ phase('rollback-restoring');
31
+ }
32
+ if (saved.phase === 'preparing') phase('rollback-restoring');
33
+ if (saved.phase === 'rollback-restoring') {
34
+ for (let i = 0; i < paths.length; i++) restoreConfig(paths[i], saved.snapshots[i]);
35
+ phase('rollback-restarting');
36
+ }
37
+ await effects.serverLifecycle(saved.original, 'start', saved.running);
38
+ unlinkSync(journal);
39
+ }
40
+ if (existsSync(journal)) {
41
+ snapshot(journal);
42
+ const saved = JSON.parse(readFileSync(journal, 'utf8'));
43
+ validateInstallation(saved.original, record.root);
44
+ validateInstallation(saved.candidate, record.root);
45
+ if (saved.schema !== 1 || !['preparing', 'switching', 'rollback-stopping', 'rollback-restoring', 'rollback-restarting'].includes(saved.phase) || !Array.isArray(saved.snapshots) || saved.snapshots.length !== paths.length
46
+ || !Array.isArray(saved.running) || saved.running.some(name => !saved.original.services.includes(name)))
47
+ throw new Error('Invalid retained gateway transition; operator recovery required');
48
+ await rollback(saved);
49
+ throw new Error('Interrupted gateway migration rolled back; repeat gateway-enable to begin a new migration');
50
+ }
51
+ if (record.gateway) {
52
+ if (args.serverUrl && args.serverUrl !== gatewayAddress(record).base) throw new Error('Gateway URL is already configured; refusing implicit URL replacement');
53
+ await effects.verifyGateway(record);
54
+ return record;
55
+ }
56
+ const candidate = { ...record, gateway: { version: 1, ...(args.serverUrl ? { serverUrl: args.serverUrl } : {}) }, services: [...record.services, 'gateway'] };
57
+ validateInstallation(candidate, record.root);
58
+ const current = effects.readManagedClientProfile();
59
+ const selected = current?.expectedInstanceId === record.instanceId && current.endpoint === `http://127.0.0.1:${record.port}`;
60
+ const saved = { schema: 1, phase: 'preparing', original: record, candidate, snapshots: paths.map(snapshot), running: await effects.serverLifecycle(record, 'status') };
61
+ // Reject old service artifacts before stopping the working deployment.
62
+ await effects.qualifyGatewayRuntime(candidate);
63
+ if (selected) await effects.qualifyInstalledGatewayClient(current);
64
+ atomicWriteConfig(journal, JSON.stringify(saved, null, 2) + '\n');
65
+ try {
66
+ await effects.prepareGateway(candidate);
67
+ saved.phase = 'switching';
68
+ atomicWriteConfig(journal, JSON.stringify(saved, null, 2) + '\n');
69
+ await effects.serverLifecycle(record, 'stop');
70
+ await effects.serverLifecycle(candidate, 'start', [...new Set([...saved.running, 'daemon', 'cowork', 'gateway'])]);
71
+ await effects.verifyGateway(candidate);
72
+ if (selected) {
73
+ const serverUrl = gatewayAddress(candidate).base;
74
+ atomicWriteConfig(profilePath, JSON.stringify({ ...current, serverUrl, endpoint: serverUrl + '/daemon' }, null, 2) + '\n');
75
+ }
76
+ // Preserve the running/stopped selection; gateway follows a running daemon.
77
+ const keep = [...saved.running, ...(saved.running.includes('daemon') ? ['gateway'] : [])];
78
+ await effects.serverLifecycle(candidate, 'stop', candidate.services.filter(name => !keep.includes(name)));
79
+ atomicWriteConfig(recordPath, JSON.stringify(candidate, null, 2) + '\n');
80
+ unlinkSync(journal);
81
+ return candidate;
82
+ } catch (cause) {
83
+ try { await rollback(saved); }
84
+ catch (rollbackError) { throw new AggregateError([cause, rollbackError], 'Gateway migration and rollback failed; retained journal requires gateway-enable recovery'); }
85
+ throw new Error('Gateway migration failed; previous routing, profile and service selection restored', { cause });
86
+ }
87
+ }
@@ -0,0 +1,142 @@
1
+ /** One public URL; fixed same-origin service paths are never supplied by a peer. */
2
+ export const GATEWAY_SERVICES = Object.freeze({daemon:'/daemon',cowork:'/cowork',telegram:'/tg-connector',messenger:'/messenger'});
3
+ export function serverBase(value) {
4
+ if(typeof value!=='string'||/[\s\\?#]/.test(value)||!/^https?:\/\//.test(value))throw new Error('Server URL must be an HTTP or HTTPS base URL');
5
+ const url=new URL(value);
6
+ if(url.username||url.password)throw new Error('Server URL cannot contain credentials');
7
+ return url.origin+url.pathname.replace(/\/+$/,'');
8
+ }
9
+ export function gatewayDiscovery(record) {
10
+ return {schema:1,instanceId:record.instanceId,services:GATEWAY_SERVICES,capabilities:['ours.gateway-v1','cowork.http-management-v1']};
11
+ }
12
+ export function validateGatewayDiscovery(url,value,credentialPath) {
13
+ const base=serverBase(url);
14
+ if(value?.schema!==1||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(value.instanceId??'')
15
+ ||!Array.isArray(value.capabilities)||!value.capabilities.includes('ours.gateway-v1')||!value.capabilities?.includes('cowork.http-management-v1')
16
+ ||Object.keys(GATEWAY_SERVICES).some(key=>value.services?.[key]!==GATEWAY_SERVICES[key]))throw new Error('Incompatible server gateway discovery');
17
+ return {serverUrl:base,endpoint:base+'/daemon',expectedInstanceId:value.instanceId,credentialPath};
18
+ }
19
+ export function gatewayAddress(record) {
20
+ const base = serverBase(record.gateway?.serverUrl ?? `http://127.0.0.1:${record.port}`);
21
+ const url = new URL(base);
22
+ if (!/^\/(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]*$/.test(url.pathname)) throw new Error('Gateway base path must contain plain URL path segments');
23
+ return { base, origin: url.origin, prefix: url.pathname.replace(/\/$/, '') };
24
+ }
25
+ export function gatewayCompose(record) {
26
+ const { origin, prefix } = gatewayAddress(record);
27
+ return `services:
28
+ daemon:
29
+ ports: !reset []
30
+ telegram:
31
+ ports: !reset []
32
+ environment:
33
+ OURS_TG_CONTROL_HOST: "0.0.0.0"
34
+ cowork:
35
+ ports: !reset []
36
+ environment:
37
+ OURS_COWORK_HTTP_MANAGEMENT: "1"
38
+ OURS_COWORK_PUBLIC_ORIGIN: ${JSON.stringify(origin)}
39
+ messenger:
40
+ ports: !reset []
41
+ environment:
42
+ OURS_MESSENGER_PUBLIC_ORIGIN: ${JSON.stringify(origin)}
43
+ OURS_MESSENGER_BASE_PATH: ${JSON.stringify(prefix + "/messenger/")}
44
+ gateway:
45
+ image: "\${OURS_GATEWAY_IMAGE:-${record.project}:gateway}"
46
+ build:
47
+ context: .
48
+ dockerfile: Dockerfile.gateway
49
+ user: "101:101"
50
+ read_only: true
51
+ cap_drop: [ALL]
52
+ security_opt: [no-new-privileges:true]
53
+ tmpfs: ["/tmp:rw,nosuid,nodev,noexec,size=32m,mode=1777"]
54
+ networks: [ours]
55
+ ports:
56
+ - {target: 8080, published: "${record.port}", host_ip: "127.0.0.1"}
57
+ restart: unless-stopped
58
+ stop_grace_period: 10s
59
+ healthcheck:
60
+ test: [CMD, wget, -q, -O, /dev/null, http://127.0.0.1:8080/healthz]
61
+ interval: 5s
62
+ timeout: 3s
63
+ retries: 6
64
+ `;
65
+ }
66
+ export function gatewayNginx(record) {
67
+ const { prefix: basePath } = gatewayAddress(record);
68
+ const routes=[['daemon',3050],['cowork',record.coworkPort??3052],['telegram',3051],['messenger',8420]];
69
+ const upstream=Object.fromEntries(routes);
70
+ for(const port of Object.values(upstream))if(!Number.isInteger(port)||port<1||port>65535)throw new Error('Invalid gateway upstream port');
71
+ const route=(name,servicePath)=> { const prefix=basePath+servicePath; return`location ${prefix}/ {
72
+ set $upstream_${name} http://${name}:${upstream[name]};
73
+ rewrite ^${prefix}/(.*)$ /$1 break;
74
+ proxy_pass $upstream_${name};
75
+ proxy_set_header Host $http_host;
76
+ proxy_set_header X-Forwarded-Proto $scheme;
77
+ proxy_set_header Upgrade $http_upgrade;
78
+ proxy_set_header Connection $connection_upgrade;
79
+ proxy_http_version 1.1;
80
+ proxy_buffering off;
81
+ proxy_read_timeout 300s;
82
+ }`; };
83
+ return `worker_processes 1;
84
+ pid /tmp/nginx.pid;
85
+ error_log /dev/stderr warn;
86
+ events { worker_connections 1024; }
87
+ http {
88
+ access_log off;
89
+ client_body_temp_path /tmp/client;
90
+ proxy_temp_path /tmp/proxy;
91
+ fastcgi_temp_path /tmp/fastcgi;
92
+ uwsgi_temp_path /tmp/uwsgi;
93
+ scgi_temp_path /tmp/scgi;
94
+ proxy_next_upstream off;
95
+ resolver @@OURS_RESOLVERS@@ valid=5s;
96
+ map $http_upgrade $connection_upgrade { default upgrade; '' close; }
97
+ server {
98
+ listen 8080;
99
+ server_name _;
100
+ client_max_body_size 64m;
101
+ location = /healthz { return 200 'ok'; }
102
+ location = ${basePath}/.well-known/ours { default_type application/json; return 200 '${JSON.stringify(gatewayDiscovery(record))}'; }
103
+ location = / { return 302 ${basePath}/messenger/; }
104
+ location = ${basePath}/daemon { return 308 ${basePath}/daemon/; }
105
+ location = ${basePath}/cowork { return 308 ${basePath}/cowork/; }
106
+ location = ${basePath}/tg-connector { return 308 ${basePath}/tg-connector/; }
107
+ location = ${basePath}/messenger { return 308 ${basePath}/messenger/; }
108
+ # Never publish the unauthenticated loopback browser RPC. Management has its
109
+ # own application-level credential check and rejects browser-origin requests.
110
+ location = ${basePath}/cowork/rpc { return 403; }
111
+ location ${basePath}/cowork/management/ {
112
+ client_max_body_size 1m;
113
+ set $management http://cowork:${upstream.cowork};
114
+ rewrite ^${basePath}/cowork/(.*)$ /$1 break;
115
+ proxy_pass $management;
116
+ proxy_set_header Host $http_host;
117
+ proxy_http_version 1.1;
118
+ proxy_read_timeout 60s;
119
+ }
120
+ ${route('daemon','/daemon')}
121
+ ${route('cowork','/cowork')}
122
+ # Telegram's control API is local-only; no unauthenticated remote proxy.
123
+ location ${basePath}/tg-connector/ {
124
+ auth_request /_server_auth;
125
+ set $telegram http://telegram:3051;
126
+ rewrite ^${basePath}/tg-connector/(.*)$ /$1 break;
127
+ proxy_pass $telegram;
128
+ }
129
+ location = /_server_auth {
130
+ internal;
131
+ set $auth http://daemon:3050/identities;
132
+ proxy_pass $auth;
133
+ proxy_pass_request_body off;
134
+ proxy_set_header Content-Length "";
135
+ proxy_set_header X-Ours-Api-Token $http_x_ours_api_token;
136
+ }
137
+ ${route('messenger','/messenger')}
138
+ location / { return 404; }
139
+ }
140
+ }
141
+ `;
142
+ }
@@ -0,0 +1,213 @@
1
+ /** Local-only migration: preserve opaque daemon state and retire its old launcher. */
2
+ import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync } from 'node:fs';
3
+ import { join, basename } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { inspectLegacyState, stageLegacyState, withLegacyStateLock, ensureLegacyLockSupport } from './legacy-state.mjs';
6
+ import { inspectManagedCli, installManagedCli } from './managed-cli.mjs';
7
+ import { atomicWriteConfig } from './config.mjs';
8
+ import { classifyUnit, unitPathForStateDir, validateInstallation } from './plan.mjs';
9
+
10
+ const journalPath = root => join(root, 'legacy-migration.json');
11
+ const parse = result => JSON.parse(result.stdout);
12
+ const phases = ['prepared', 'stopped', 'copied', 'activating', 'verified', 'complete'];
13
+ function readJournal(root) {
14
+ const path = journalPath(root);
15
+ if (!existsSync(path)) return null;
16
+ const j = JSON.parse(readFileSync(path));
17
+ if (j.schema !== 1 || j.targetRoot !== root || !phases.includes(j.phase) || !Array.isArray(j.identities)) throw new Error('Invalid legacy migration journal');
18
+ return j;
19
+ }
20
+ // Legacy cutover publishes a Docker/package launcher; Podman cutover is not supported.
21
+ function rejectPodmanMigration(options, effects, ...records) {
22
+ if (options.containerEngine === 'podman' || records.some(record => record?.containerEngine === 'podman')
23
+ || effects.readJson(join(options.stateDir, 'installation.json'))?.containerEngine === 'podman') {
24
+ throw new Error('Legacy migration to Podman is not supported. Use a fresh Podman installation or migrate with Docker/packages.');
25
+ }
26
+ }
27
+ function selection(source) {
28
+ return { env: { OURS_CONFIG: source.configPath, OURS_STATE_DIR: source.stateDir, OURS_PORT: String(source.config.port ?? 3050), OURS_API_TOKEN: undefined, OURS_DAEMON_ID: undefined, OURS_DAEMON_URL: undefined, OURS_DAEMON_CREDENTIAL_PATH: undefined }, sensitive: true };
29
+ }
30
+ async function oldCommand(effects, source, args, options = {}) {
31
+ return effects.run(source.originalProgram ?? 'ours', [...args, '--config', source.configPath, '--state-dir', source.stateDir, '--json'], { ...selection(source), ...options });
32
+ }
33
+ function validateIdentities(rows, source) {
34
+ if (!Array.isArray(rows) || !rows.length || rows.some(r => !['root', 'role'].includes(r.kind) || typeof r.cid !== 'string' || !r.cid || typeof r.name !== 'string')) throw new Error('Legacy identities are not fully restored; migration requires a healthy source daemon');
35
+ const roots = rows.filter(r => r.kind === 'root');
36
+ if (roots.length !== 1 || roots[0].name !== source.rootName) throw new Error('Legacy Human identity does not match its stored root');
37
+ return rows.map(({ name, kind, cid }) => ({ name, kind, cid })).sort((a,b) => a.name.localeCompare(b.name));
38
+ }
39
+
40
+ export async function inspectLegacyMigration(options, effects, deps = {}) {
41
+ const journal = readJournal(options.stateDir);
42
+ rejectPodmanMigration(options, effects, journal?.record, options.legacyPlan?.journal?.record);
43
+ const inspect = deps.inspectLegacyState ?? inspectLegacyState;
44
+ await (deps.ensureLegacyLockSupport ?? ensureLegacyLockSupport)();
45
+ const cliPlan = options.dryRun ? null : await (deps.inspectManagedCli ?? inspectManagedCli)(effects, options.stateDir);
46
+ if (journal) {
47
+ if (journal.sourceConfig !== options.migrateFrom) throw new Error('Another legacy source is already selected for this target');
48
+ return { journal, cliPlan, source: journal.phase === 'complete' ? null : { ...inspect(options.migrateFrom, options.stateDir), originalProgram: cliPlan?.originalProgram } };
49
+ }
50
+ const source = { ...inspect(options.migrateFrom, options.stateDir), originalProgram: cliPlan?.originalProgram };
51
+ if (options.mode === 'docker' && options.stateDir.includes(':')) throw new Error('Docker migration requires an installation path without colon characters');
52
+ if (effects.readJson(join(options.stateDir, 'installation.json'))) throw new Error('Legacy migration requires a new managed installation root');
53
+ if (existsSync(options.stateDir) && readdirSync(options.stateDir).length) throw new Error('Legacy migration target must be empty');
54
+ if (options.dryRun) return { source, journal: { schema: 1, sourceConfig: source.configPath, sourceStateDir: source.stateDir, targetRoot: options.stateDir, phase: 'prepared', identities: [], service: null } };
55
+ // The owning CLI verifies endpoint, process and state directory. No PID guessing.
56
+ const status = parse(await oldCommand(effects, source, ['daemon', 'status']));
57
+ if (status.state !== 'running' || status.stateDir !== source.stateDir) throw new Error('Start the legacy daemon before migration so its identities can be verified');
58
+ const identities = validateIdentities(parse(await oldCommand(effects, source, ['identity', 'list'])), source);
59
+ const service = parse(await oldCommand(effects, source, ['daemon', 'uninstall-service', '--dry-run']));
60
+ if (service.conflict) {
61
+ const legacy = effects.platform?.platform === 'linux' && source.stateDir === join(effects.home, '.ours')
62
+ ? unitPathForStateDir(source.stateDir, effects.home) : null;
63
+ if (!legacy?.ok || legacy.path !== service.serviceFile || classifyUnit(effects.readText(legacy.path)).kind !== 'legacy') {
64
+ throw new Error('Legacy boot service ownership could not be verified: ' + service.conflict.message);
65
+ }
66
+ service.legacyUnit = legacy.unit;
67
+ }
68
+ return { source, cliPlan, journal: { schema: 1, sourceConfig: source.configPath, sourceStateDir: source.stateDir, targetRoot: options.stateDir,
69
+ phase: 'prepared', identities, service, sourcePort: source.config.port ?? 3050 } };
70
+ }
71
+
72
+ export async function prepareMigrationCliRuntime(record, effects) {
73
+ const root = join(record.root, 'launcher-runtime');
74
+ const entry = join(root, 'node_modules', '@ours.network', 'install', 'install.mjs');
75
+ const ready = join(root, '.ready');
76
+ if (existsSync(ready) && existsSync(entry)) return entry;
77
+ mkdirSync(root, { recursive: true, mode: 0o700 });
78
+ effects.out('Preparing permanent management commands so ours will keep working after this installer exits.');
79
+ const packageRoot = fileURLToPath(new URL('..', import.meta.url));
80
+ const packed = parse(await effects.run('npm', ['pack', packageRoot, '--ignore-scripts', '--pack-destination', root, '--json']));
81
+ if (!Array.isArray(packed) || packed.length !== 1 || typeof packed[0].filename !== 'string' || basename(packed[0].filename) !== packed[0].filename) throw new Error('Cannot prepare the persistent installer package');
82
+ await effects.run('npm', ['install', '--prefix', root, '--prefer-offline', '--ignore-scripts', '--no-audit', '--no-fund', join(root, packed[0].filename)], { stream: true });
83
+ if (!existsSync(entry)) throw new Error('Persistent installer entry is missing');
84
+ await effects.run(process.execPath, [entry, '--help']);
85
+ atomicWriteConfig(ready, 'ready\n');
86
+ return entry;
87
+ }
88
+
89
+ /** Called under the normal installation lock; retries never overwrite imported state. */
90
+ export async function executeLegacyMigration(args, effects, install, deps = {}) {
91
+ const retainedJournal = readJournal(args.stateDir);
92
+ rejectPodmanMigration(args, effects, retainedJournal?.record, args.legacyPlan?.journal?.record);
93
+ const stage = deps.stageLegacyState ?? stageLegacyState;
94
+ const lock = deps.withLegacyStateLock ?? withLegacyStateLock;
95
+ const save = (root, value) => (deps.atomicWriteConfig ?? atomicWriteConfig)(journalPath(root), JSON.stringify(value, null, 2) + '\n');
96
+ const prepareCli = deps.prepareMigrationCliRuntime ?? prepareMigrationCliRuntime;
97
+ const inspected = args.legacyPlan ?? await inspectLegacyMigration(args, effects, deps);
98
+ let journal = retainedJournal ?? inspected.journal;
99
+ rejectPodmanMigration(args, effects, journal?.record);
100
+ if (journal.phase === 'complete') {
101
+ const retained = effects.readJson(join(args.stateDir, 'installation.json'));
102
+ inspected.cliPlan.installerPath = await prepareCli(retained, effects);
103
+ await (deps.installManagedCli ?? installManagedCli)(retained, inspected.cliPlan, effects);
104
+ const rows = validateIdentities(parse(await effects.run('ours', ['identity', 'list', '--json'])), { rootName: journal.identities.find(row => row.kind === 'root')?.name });
105
+ if (JSON.stringify(rows) !== JSON.stringify(journal.identities)) throw new Error('Completed migration identity verification failed; no replacement Human was created');
106
+ effects.out('Legacy migration already completed; retained identities verified.');
107
+ return 0;
108
+ }
109
+ const source = inspected.source;
110
+ let record;
111
+ let sourceLock;
112
+ let activationAttempted = phases.indexOf(journal.phase) >= phases.indexOf('activating');
113
+ const wrapped = { ...effects,
114
+ newInstallation(root, mode) {
115
+ if (journal.record) {
116
+ if (journal.record.root !== root || journal.record.mode !== mode) throw new Error('Migration target selection changed');
117
+ return validateInstallation(journal.record, root);
118
+ }
119
+ return effects.newInstallation(root, mode);
120
+ },
121
+ async initializeSelection(selected, manifest) {
122
+ record = selected;
123
+ selected.legacyMigrationSource = args.migrateFrom;
124
+ journal.record = selected;
125
+ journal.sourcePolicy = args.sourcePolicy;
126
+ journal.sourceManifest = manifest;
127
+ save(selected.root, journal);
128
+ effects.writeJson(join(selected.root, 'installation.json'), JSON.stringify(selected, null, 2) + '\n');
129
+ await effects.initializeSelection(selected, manifest, { retainConfig: true });
130
+ },
131
+ async serverPreflight(selected, operation, options) {
132
+ if (journal.record && !existsSync(selected.sourcesPath)) {
133
+ if (!journal.sourceManifest) throw new Error('Migration journal lacks its retained package selection');
134
+ await effects.initializeSelection(selected, journal.sourceManifest, { retainConfig: true });
135
+ }
136
+ return effects.serverPreflight(selected, operation, options);
137
+ },
138
+ async prepareInstallation(selected) {
139
+ record = selected;
140
+ if (!existsSync(selected.sourcesPath)) {
141
+ const manifest = journal.sourceManifest ?? await effects.resolveSourcePolicy(args.sourcePolicy, 'server');
142
+ await effects.initializeSelection(selected, manifest, { retainConfig: true });
143
+ }
144
+ await effects.prepareInstallation(selected, { runtimeOnly: true });
145
+ if (selected.mode === 'docker') await effects.prepareLegacyDockerImport(selected);
146
+ inspected.cliPlan.installerPath = await prepareCli(selected, effects);
147
+ journal.cliInstallerPath = inspected.cliPlan.installerPath;
148
+ if (activationAttempted) await effects.serverLifecycle(selected, 'stop');
149
+ // Backups contain secrets; the enclosing installation is private.
150
+ const backup = join(selected.root, 'legacy-backup');
151
+ mkdirSync(backup, { mode: 0o700, recursive: true });
152
+ const configBackup = join(backup, 'config.json');
153
+ if (!existsSync(configBackup)) writeFileSync(configBackup, readFileSync(source.configPath), { flag: 'wx', mode: 0o600 });
154
+ if (journal.service.serviceFile && existsSync(journal.service.serviceFile) && !existsSync(join(backup, 'service'))) {
155
+ writeFileSync(join(backup, 'service'), readFileSync(journal.service.serviceFile), { flag: 'wx', mode: 0o600 });
156
+ }
157
+ save(selected.root, journal);
158
+ if (!activationAttempted) {
159
+ effects.out('Migration: retire the old boot service and stop its daemon.');
160
+ if (journal.service.legacyUnit) await effects.run('systemctl', ['--user', 'disable', '--now', journal.service.legacyUnit]);
161
+ else await oldCommand(effects, source, ['daemon', 'uninstall-service', '--yes']);
162
+ await oldCommand(effects, source, ['daemon', 'stop']);
163
+ journal.phase = 'stopped'; save(selected.root, journal);
164
+ }
165
+ // Hold the SDK-compatible owner lock until activation finishes, including failures.
166
+ sourceLock = await lock(source.stateDir);
167
+ effects.out('Migration: copy retained identities, keys, history and session state.');
168
+ stage(source, selected);
169
+ if (selected.mode === 'docker') await effects.importLegacyDockerState(selected);
170
+ if (!activationAttempted) { journal.phase = 'copied'; save(selected.root, journal); }
171
+ await effects.prepareInstallation(selected);
172
+ },
173
+ async serverLifecycle(selected, operation, services) {
174
+ if (operation === 'start') {
175
+ activationAttempted = true;
176
+ journal.phase = 'activating'; save(selected.root, journal);
177
+ }
178
+ return effects.serverLifecycle(selected, operation, services);
179
+ },
180
+ async serverEnsureIdentity(selected) {
181
+ const rows = await effects.serverListIdentities(selected);
182
+ const actual = validateIdentities(rows, source);
183
+ if (JSON.stringify(actual) !== JSON.stringify(journal.identities)) throw new Error('Migrated identities differ from the source; no replacement Human was created');
184
+ journal.phase = 'verified'; save(selected.root, journal);
185
+ const root = actual.find(r => r.kind === 'root');
186
+ return { ...root, created: false };
187
+ },
188
+ };
189
+ try {
190
+ const result = await install({ ...args, migrate: true }, wrapped);
191
+ if (result !== 0) throw new Error('Migrated server setup did not complete');
192
+ // Publish an explicit host profile; a daemon --config file is not a client profile.
193
+ const directory = join(record.root, 'legacy-client');
194
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
195
+ const credentialPath = join(directory, 'credential');
196
+ if (!existsSync(credentialPath)) await effects.serverAccess(record, 'access-issue', { output: credentialPath });
197
+ const profile = { endpoint: `http://127.0.0.1:${record.port}`, expectedInstanceId: record.instanceId, credentialPath };
198
+ atomicWriteConfig(join(directory, 'profile.json'), JSON.stringify(profile, null, 2) + '\n');
199
+ await (deps.installManagedCli ?? installManagedCli)(record, inspected.cliPlan, effects);
200
+ const defaultRows = validateIdentities(parse(await effects.run('ours', ['identity', 'list', '--json'])), source);
201
+ if (JSON.stringify(defaultRows) !== JSON.stringify(journal.identities)) throw new Error('Default ours command does not select the migrated identities');
202
+ journal.phase = 'complete'; save(record.root, journal);
203
+ effects.out(`Migration complete. Original state remains at ${source.stateDir}; original config/service are backed up in ${join(record.root, 'legacy-backup')}. Do not start the original state alongside the migrated daemon.`);
204
+ return 0;
205
+ } catch (error) {
206
+ if (record && activationAttempted) {
207
+ try { await effects.serverLifecycle(record, 'stop'); }
208
+ catch { throw new Error(`Migration activation failed and destination shutdown could not be confirmed. Keep the source stopped; repair this same target. ${error.message}`); }
209
+ throw new Error(`Migration paused after activation; source remains stopped to avoid diverging identity sessions. Repeat the same migration command to repair the retained target. ${error.message}`);
210
+ }
211
+ throw new Error(`Migration paused before activation; source data is retained. Repeat the same migration command. ${error.message}`);
212
+ } finally { await sourceLock?.close(); }
213
+ }
@@ -0,0 +1,205 @@
1
+ import * as fs from 'node:fs';
2
+ import * as net from 'node:net';
3
+ import { homedir } from 'node:os';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { dirname, join, resolve, isAbsolute, sep } from 'node:path';
6
+ import { installationPaths } from './plan.mjs';
7
+ import { copyPrivateTree, scanSource } from '../assets/scripts/maintenance/state-archive.mjs';
8
+ import { publishNoReplace } from '../assets/scripts/maintenance/state-native.mjs';
9
+
10
+ const MARKER = '.ours-legacy-import.json';
11
+ const uid = () => process.getuid();
12
+ const ownership = () => ({ uid: uid(), gid: process.getgid() });
13
+ function canonical(path) {
14
+ if (typeof path !== 'string' || !isAbsolute(path) || resolve(path) !== path) throw Error('Legacy migration requires normalized absolute paths');
15
+ let cursor = path;
16
+ while (true) {
17
+ try { if (fs.realpathSync(cursor) !== cursor) throw Error('Legacy migration refuses symlink paths'); return path; }
18
+ catch (error) { if (error.code !== 'ENOENT') throw error; const parent = dirname(cursor); if (parent === cursor) throw error; cursor = parent; }
19
+ }
20
+ }
21
+ function privatePath(path, directory = false) {
22
+ canonical(path); const stat = fs.lstatSync(path);
23
+ if (!(directory ? stat.isDirectory() : stat.isFile()) || stat.uid !== uid()
24
+ || (stat.mode & 0o7777) !== (directory ? 0o700 : 0o600) || (!directory && stat.nlink !== 1))
25
+ throw Error('Legacy migration requires private owner-only regular files and directories');
26
+ return stat;
27
+ }
28
+ function objectFile(path) {
29
+ privatePath(path); const value = JSON.parse(fs.readFileSync(path, 'utf8'));
30
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw Error('Legacy configuration must be an object');
31
+ return value;
32
+ }
33
+ const contains = (parent, child) => parent === child || child.startsWith(parent + sep);
34
+ function inspectRoot(stateDir) {
35
+ const root = objectFile(join(stateDir, 'root.json'));
36
+ if (root.v !== 1 || typeof root.name !== 'string' || !root.name || root.name !== root.name.trim()
37
+ || root.name.normalize('NFC') !== root.name || root.name.length > 64 || /[\x00-\x1f\x7f/\\]/.test(root.name)
38
+ || ['.', '..', 'contact-book', 'root.json', 'bindings.json'].includes(root.name)) throw Error('Legacy root marker is invalid');
39
+ privatePath(join(stateDir, root.name), true);
40
+ for (const file of ['identity.key', 'state_data.bin']) if (privatePath(join(stateDir, root.name, file)).size === 0) throw Error('Legacy root identity is incomplete');
41
+ // CID and hierarchy are packet facts, not fields in root.json. The caller
42
+ // must compare authenticated identity-list results before/after activation.
43
+ return root.name;
44
+ }
45
+ export function inspectLegacyState(configPath, targetRoot) {
46
+ canonical(configPath); canonical(targetRoot);
47
+ const config = objectFile(configPath);
48
+ const defaultState = join(homedir(), '.ours');
49
+ if (config.stateDir === undefined && configPath !== join(defaultState, 'config.json')) throw Error('Custom legacy config requires explicit stateDir');
50
+ const stateDir = config.stateDir === undefined ? canonical(defaultState) : canonical(config.stateDir);
51
+ privatePath(stateDir, true);
52
+ if (contains(stateDir, targetRoot) || contains(targetRoot, stateDir) || contains(targetRoot, configPath)) throw Error('Legacy source and target roots must be disjoint');
53
+ if (config.database && (typeof config.database !== 'object' || Array.isArray(config.database)
54
+ || (config.database.provider !== undefined && config.database.provider !== 'sqlite') || config.database.url))
55
+ throw Error('Legacy migration does not support external or non-SQLite history');
56
+ const entries = scanSource(stateDir, ownership());
57
+ if (entries.some(entry => entry.name.split('/').includes('.ours-provenance'))) throw Error('Legacy unmanaged migration does not support existing build provenance');
58
+ if (entries.some(entry => entry.name.endsWith('/history-postgresql.json'))) throw Error('Legacy migration cannot copy external PostgreSQL history');
59
+ if (fs.existsSync(join(stateDir, '.mcp'))) privatePath(join(stateDir, '.mcp'), true);
60
+ if (config.networkMcp !== undefined) {
61
+ const mcp = config.networkMcp;
62
+ if (!mcp || typeof mcp !== 'object' || Array.isArray(mcp)
63
+ || mcp.applicationConfigPath !== join(stateDir, '.mcp/config.json')
64
+ || !mcp.profile || mcp.profile.credentialPath !== join(stateDir, 'daemon-token'))
65
+ throw Error('Legacy migration requires embedded MCP configuration and credentials; external MCP paths are unsupported');
66
+ }
67
+ if (config.apiTokenDeliveryFiles !== undefined && (!Array.isArray(config.apiTokenDeliveryFiles)
68
+ || config.apiTokenDeliveryFiles.some(path => path !== join(stateDir, 'daemon-token'))))
69
+ throw Error('Legacy migration does not support external token delivery paths');
70
+ return { configPath, stateDir, config, rootCid: null, rootName: inspectRoot(stateDir) };
71
+ }
72
+ const receipt = (source, record) => ({ sourceStateDir: source.stateDir, sourceConfigPath: source.configPath, targetRoot: record.root, rootName: source.rootName });
73
+ function writePrivate(path, value) {
74
+ fs.writeFileSync(path, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 }); fs.chmodSync(path, 0o600);
75
+ }
76
+
77
+ function publishLegacyMcp(source, destination, expected, profile) {
78
+ canonical(destination);
79
+ if (fs.existsSync(destination)) {
80
+ privatePath(destination, true);
81
+ if (fs.existsSync(join(destination, MARKER))) {
82
+ if (JSON.stringify(objectFile(join(destination, MARKER))) !== JSON.stringify(expected)) throw Error('Legacy MCP destination receipt mismatch');
83
+ return;
84
+ }
85
+ if (fs.readdirSync(destination).length) throw Error('Legacy MCP destination must be absent or empty');
86
+ }
87
+ const staging = join(dirname(destination), `.legacy-mcp-${randomUUID()}`);
88
+ try {
89
+ const embedded = join(source.stateDir, '.mcp');
90
+ if (fs.existsSync(embedded)) copyPrivateTree(embedded, staging, ownership());
91
+ else fs.mkdirSync(staging, { mode: 0o700 });
92
+ writePrivate(join(staging, 'profile.json'), profile);
93
+ writePrivate(join(staging, MARKER), expected);
94
+ scanSource(staging, ownership());
95
+ if (fs.existsSync(destination)) fs.rmdirSync(destination);
96
+ publishNoReplace(staging, destination);
97
+ } finally { fs.rmSync(staging, { recursive: true, force: true }); }
98
+ }
99
+
100
+ // Caller excludes source writers and owns installation exclusion through activation.
101
+ export function stageLegacyState(source, record) {
102
+ if (record.schema !== 2 || !['packages', 'docker'].includes(record.mode)
103
+ || !Number.isInteger(record.port) || record.port < 1 || record.port > 65535) throw Error('Unsupported legacy migration destination');
104
+ const fresh = inspectLegacyState(source.configPath, record.root);
105
+ if (fresh.stateDir !== source.stateDir || fresh.rootName !== source.rootName) throw Error('Legacy source selection changed');
106
+ const paths = installationPaths(record);
107
+ const destination = paths.daemon, parent = dirname(destination);
108
+ canonical(destination); privatePath(parent, true);
109
+ const expected = receipt(fresh, record);
110
+ if (fs.existsSync(destination)) {
111
+ privatePath(destination, true);
112
+ if (fs.existsSync(join(destination, MARKER))) {
113
+ const saved = objectFile(join(destination, MARKER));
114
+ if (JSON.stringify(saved) !== JSON.stringify(expected) || inspectRoot(destination) !== fresh.rootName) throw Error('Legacy destination receipt does not match selected source');
115
+ const mcpReceipt = objectFile(join(paths.mcp, MARKER));
116
+ if (JSON.stringify(mcpReceipt) !== JSON.stringify(expected)) throw Error('Legacy MCP destination receipt does not match selected source');
117
+ return { ...expected, destination, reused: true };
118
+ }
119
+ if (fs.readdirSync(destination).length) throw Error('Legacy destination must be absent or empty');
120
+ }
121
+ const staging = join(parent, `.legacy-${randomUUID()}`);
122
+ try {
123
+ copyPrivateTree(fresh.stateDir, staging, ownership());
124
+ // Preserve the untouched source as the rollback copy. Only copied PID hints
125
+ // are discarded; opaque identities, authority, SQLite sidecars all survive.
126
+ for (const name of ['ours-cli-daemon.json', 'daemon.pid', 'startup-progress.json']) fs.rmSync(join(staging, name), { force: true });
127
+ const config = structuredClone(fresh.config);
128
+ config.stateDir = record.mode === 'docker' ? '/var/lib/ours' : destination;
129
+ config.port = record.mode === 'docker' ? 3050 : record.port; config.apiVisibility = 'owner';
130
+ delete config.apiToken; delete config.apiTokenDeliveryFiles;
131
+ config.networkMcp = {
132
+ profile: { endpoint: `http://127.0.0.1:${config.port}`, expectedInstanceId: record.instanceId, credentialPath: join(config.stateDir, 'daemon-token') },
133
+ applicationConfigPath: record.mode === 'docker' ? '/var/lib/ours-mcp/config.json' : join(paths.mcp, 'config.json'),
134
+ };
135
+ // Publish MCP separately before daemon publication. Its receipt allows a
136
+ // retry after an interrupted second rename, without overwriting live data.
137
+ publishLegacyMcp(fresh, paths.mcp, expected, config.networkMcp.profile);
138
+ writePrivate(join(staging, 'config.json'), config); writePrivate(join(staging, MARKER), expected);
139
+ scanSource(staging, ownership());
140
+ if (fs.existsSync(destination)) fs.rmdirSync(destination); // succeeds only for the empty skeleton
141
+ publishNoReplace(staging, destination);
142
+ return { ...expected, destination, reused: false };
143
+ } finally { fs.rmSync(staging, { recursive: true, force: true }); }
144
+ }
145
+
146
+ let Database;
147
+ export async function ensureLegacyLockSupport() {
148
+ if (!['linux', 'darwin'].includes(process.platform) || typeof process.getuid !== 'function') throw Error('Legacy migration requires Linux/macOS source locking');
149
+ try { ({ DatabaseSync: Database } = await import('node:sqlite')); }
150
+ catch { throw Error('Legacy migration requires Node with node:sqlite support; upgrade Node before stopping the source daemon'); }
151
+ }
152
+
153
+ // Protocol adapted from SDK src/internal/state-root-lock.ts: permanent SQLite
154
+ // guard serializes stale socket probe/unlink/rebind; socket ownership lasts for
155
+ // the callback. Never replace the guard inode or unlink on ambiguous probes.
156
+ function lockDirectory(path) {
157
+ try { fs.mkdirSync(path, { mode: 0o700 }); } catch (error) { if (error.code !== 'EEXIST') throw error; }
158
+ privatePath(path, true);
159
+ }
160
+ function probe(path) {
161
+ return new Promise(resolveProbe => {
162
+ const socket = net.createConnection(path); let finished = false;
163
+ const done = result => { if (finished) return; finished = true; socket.destroy(); resolveProbe(result); };
164
+ socket.setTimeout(1000);
165
+ socket.once('connect', () => done('live'));
166
+ socket.once('timeout', () => done('ambiguous'));
167
+ socket.once('error', error => done(['ECONNREFUSED', 'ENOENT'].includes(error.code) ? 'stale' : 'ambiguous'));
168
+ });
169
+ }
170
+ async function socketLock(stateDir, path) {
171
+ for (let attempt = 0; attempt < 8; attempt++) {
172
+ const server = net.createServer(socket => { socket.on('error', () => {}); socket.end(JSON.stringify({ pid: process.pid, stateDir, startedAt: new Date().toISOString() }) + '\n'); });
173
+ try {
174
+ await new Promise((accept, reject) => { server.once('error', reject); server.listen(path, () => { server.removeListener('error', reject); accept(); }); });
175
+ server.unref(); return server;
176
+ } catch (error) {
177
+ try { server.close(); } catch { /* not listening */ }
178
+ if (error.code !== 'EADDRINUSE') throw error;
179
+ const result = await probe(path);
180
+ if (result !== 'stale') throw Error(`Legacy source lock is ${result}; refusing to remove a potentially live owner`);
181
+ try { fs.unlinkSync(path); } catch (failure) { if (failure.code !== 'ENOENT') throw failure; }
182
+ }
183
+ }
184
+ throw Error('Could not acquire legacy source lock');
185
+ }
186
+ export async function withLegacyStateLock(stateDir, callback) {
187
+ await ensureLegacyLockSupport(); canonical(stateDir); privatePath(stateDir, true);
188
+ const base = `/tmp/ours-${uid()}`; lockDirectory(base); lockDirectory(join(base, 'locks'));
189
+ const path = join(base, 'locks', createHash('sha256').update(stateDir).digest('hex') + '.sock');
190
+ if (Buffer.byteLength(path) > 103) throw Error('Legacy lock socket path exceeds portable limit');
191
+ const guardPath = path + '.guard';
192
+ try { const fd = fs.openSync(guardPath, fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600); fs.closeSync(fd); }
193
+ catch (error) { if (error.code !== 'EEXIST') throw error; }
194
+ const before = privatePath(guardPath), guard = new Database(guardPath); let server;
195
+ try {
196
+ const after = privatePath(guardPath);
197
+ if (before.dev !== after.dev || before.ino !== after.ino || before.mode !== after.mode || before.uid !== after.uid) throw Error('Legacy acquisition guard changed');
198
+ guard.exec('PRAGMA busy_timeout=0; BEGIN EXCLUSIVE'); server = await socketLock(stateDir, path);
199
+ } finally { guard.close(); }
200
+ let closed = false;
201
+ const close = async () => { if (closed) return; closed = true; await new Promise(resolveClose => server.close(resolveClose)); };
202
+ if (callback === undefined) return { stateDir, close };
203
+ try { return await callback(); }
204
+ finally { await close(); }
205
+ }