@ours.network/install 2.1.4 → 2.1.7

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/effects.mjs CHANGED
@@ -37,6 +37,8 @@ import { classifyStateDir } from './detect.mjs';
37
37
  import { isPluginOnly, serverRole, pluginOnlyCompose, PLUGIN_ONLY_COMPOSE } from './product.mjs';
38
38
  import { OWNERS_FILE, OWNED_IMAGES_FILE, addOwner, ownedImagesRecord, changedImages } from './ownership.mjs';
39
39
  import { IMAGE_TARGETS } from './removal-plan.mjs';
40
+ import { copyDockerAssets, writeMaintenancePackage } from './docker-context.mjs';
41
+ import { readPackagedImages, selectServerImages, pullServerImages, rememberGeneration, pruneGenerations, policyBytes, policyHash } from './image-acquisition.mjs';
40
42
  import { BASE_RECORDS, CONTEXT, readBuildRecords, equalBuildRecords, initializeBuildMarker } from '../assets/scripts/maintenance/build-context.mjs';
41
43
  import { hostCliPolicy, releaseBinding, verifyReleaseGraph, verifyRuntimeRelease } from '../assets/scripts/maintenance/release-graph.mjs';
42
44
 
@@ -598,7 +600,6 @@ export function networkEffects(effects) {
598
600
  const baseEnv = (record) => ({
599
601
  OURS_DAEMON_ID: record.instanceId,
600
602
  OURS_IMAGE: `${record.project}:runtime`,
601
- OURS_GATEWAY_IMAGE: `${record.project}:gateway`,
602
603
  OURS_MAINTENANCE_IMAGE: `${record.project}:maintenance`,
603
604
  OURS_UID: String(record.uid ?? 1000), OURS_GID: String(record.gid ?? 1000),
604
605
  OURS_HOST_PORT: String(record.port ?? 3050),
@@ -607,9 +608,7 @@ export function networkEffects(effects) {
607
608
  OURS_MESSENGER_IDENTITY: record.messengerIdentity ?? '',
608
609
  });
609
610
  const composeArgs = (record, args) => [
610
- 'compose', '--project-directory', record.workDir, '--file', join(record.workDir,
611
- record.schema === 1 && existsSync(join(record.workDir, 'docker-compose.legacy.yaml'))
612
- ? 'docker-compose.legacy.yaml' : 'docker-compose.yaml'),
611
+ 'compose', '--project-directory', record.workDir, '--file', join(record.workDir, 'docker-compose.yaml'),
613
612
  ...(record.gateway ? ['--file', join(record.workDir, 'docker-compose.gateway.yaml')] : []),
614
613
  ...(existsSync(join(record.workDir, 'compose.recovery.json')) ? ['--file', join(record.workDir, 'compose.recovery.json')] : []),
615
614
  ...(engineName(record) === 'podman' ? ['--file', join(record.workDir, 'compose.podman.json')] : []),
@@ -822,35 +821,38 @@ export function networkEffects(effects) {
822
821
  }
823
822
  }
824
823
  },
825
- async prepareLegacyDockerImport(record) {
826
- if (record.mode === 'docker') await compose(record, ['build', 'legacy-import'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
827
- },
828
- async importLegacyDockerState(record) {
829
- if (record.mode !== 'docker') return;
830
- const source = join(record.root, 'storage', 'state');
831
- if (source.includes(':')) throw new Error('Docker migration requires an installation path without colon characters');
832
- await compose(record, ['run', '--rm', '--no-deps', '-T', '--volume', `${source}:/legacy-import:ro`,
833
- '--env', `OURS_LEGACY_TARGET_ROOT=${record.root}`, 'legacy-import']);
834
- },
835
- async initializeSelection(record, manifest, { retainConfig = false } = {}) {
824
+ async initializeSelection(record, manifest) {
836
825
  if (typeof manifest === 'string') manifest = JSON.parse(readFileSync(manifest, 'utf8'));
837
826
  selectSourcePackages(manifest, serverRole(record));
838
827
  const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
839
828
  ensurePrivateDirectory(record.root);
840
- if (record.schema === 2) {
841
- for (const path of [join(record.root, 'storage'), installationPaths(record).state, installationPaths(record).daemon]) ensurePrivateDirectory(path);
842
- }
843
- if (!retainConfig || !existsSync(record.sourcesPath)) writePrivateNew(record.sourcesPath, bytes);
844
- else if (!readFileSync(record.sourcesPath).equals(bytes)) throw new Error('Migration source selection changed');
845
- if (!retainConfig) writePrivateNew(record.configPath, JSON.stringify({ stateDir: record.mode === 'docker' ? '/var/lib/ours' : installationPaths(record).daemon, port: record.port, apiVisibility: 'owner' }, null, 2) + '\n');
829
+ for (const path of [join(record.root, 'storage'), installationPaths(record).state, installationPaths(record).daemon]) ensurePrivateDirectory(path);
830
+ writePrivateNew(record.sourcesPath, bytes);
831
+ writePrivateNew(record.configPath, JSON.stringify({ stateDir: record.mode === 'docker' ? '/var/lib/ours' : installationPaths(record).daemon, port: record.port, apiVisibility: 'owner' }, null, 2) + '\n');
846
832
  },
847
833
  async qualifyDockerRuntime(record) { return qualifyDockerRuntime(record, effects); },
834
+ /** Name this project's runtime and maintenance images: published digests, else an explicit local build. */
835
+ async acquireServerImages(record, { rebuild = false } = {}) {
836
+ const present = async target => (await container(record, ['image', 'inspect', `${record.project}:${target}`], { allowCodes: [1] })).code === 0;
837
+ if (!rebuild && await present('runtime') && await present('maintenance')) return;
838
+ const role = serverRole(record), policy = effects.packagedSourcePolicy();
839
+ const packaged = readPackagedImages(releaseBinding(policy));
840
+ const plan = selectServerImages({ root: record.root, sourcesPath: record.sourcesPath, role, packaged, buildLocally: env.OURS_BUILD_LOCALLY === '1',
841
+ releasedHash: releaseBinding(policy) ? policyHash(policyBytes(await resolveSourcePolicy(policy, role))) : undefined });
842
+ if (plan.kind === 'pull') {
843
+ await pullServerImages(effects, record, plan.entry);
844
+ // Retained before its sources.json is switched in, so repair finds the same generation.
845
+ if (plan.remember) rememberGeneration(record.root, plan.hash, plan.entry);
846
+ return;
847
+ }
848
+ effects.out?.(`Building the server images locally: ${plan.reason}.`);
849
+ const build = { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } };
850
+ if (rebuild || !await present('runtime')) await compose(record, ['build', 'daemon'], build);
851
+ if (!await present('maintenance')) await compose(record, ['build', 'state-operation'], build);
852
+ },
848
853
  async prepareGateway(record) {
849
854
  atomicWriteConfig(join(record.workDir, 'docker-compose.gateway.yaml'), gatewayCompose(record));
850
855
  atomicWriteConfig(join(record.workDir, 'nginx.conf'), gatewayNginx(record));
851
- atomicWriteConfig(join(record.workDir, 'gateway-entrypoint.sh'), readFileSync(join(INSTALLER_ASSETS, 'gateway-entrypoint.sh'), 'utf8'));
852
- atomicWriteConfig(join(record.workDir, 'Dockerfile.gateway'), readFileSync(join(INSTALLER_ASSETS, 'Dockerfile.gateway'), 'utf8'));
853
- await compose(record, ['build', 'gateway'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
854
856
  },
855
857
  async removeGatewayContainer(record) { await compose(record, ['rm', '-f', 'gateway']); },
856
858
  async verifyGateway(record) {
@@ -878,15 +880,9 @@ export function networkEffects(effects) {
878
880
  },
879
881
  async prepareInstallation(record, { runtimeOnly = false } = {}) {
880
882
  if (!runtimeOnly) await reportBootReadiness(effects, record);
881
- let copied = false;
882
- if (!existsSync(record.workDir)) {
883
- cpSync(INSTALLER_ASSETS, record.workDir, { recursive: true, errorOnExist: true, force: false });
884
- chmodSync(record.workDir, 0o700);
885
- copied = true;
886
- }
883
+ if (!existsSync(record.workDir)) copyDockerAssets(record.workDir);
887
884
  const retained = readFileSync(record.sourcesPath);
888
885
  const materialized = join(record.workDir, 'sources.json');
889
- if (copied) rmSync(materialized);
890
886
  if (!existsSync(materialized)) writePrivateNew(materialized, retained);
891
887
  else if (!readFileSync(materialized).equals(retained)) throw new Error('Materialized sources differ from retained selection');
892
888
  if (record.mode === 'docker') {
@@ -900,19 +896,14 @@ export function networkEffects(effects) {
900
896
  if (record.gateway) {
901
897
  atomicWriteConfig(join(record.workDir, 'docker-compose.gateway.yaml'), gatewayCompose(record));
902
898
  atomicWriteConfig(join(record.workDir, 'nginx.conf'), gatewayNginx(record));
903
- for (const file of ['Dockerfile.gateway', 'gateway-entrypoint.sh']) atomicWriteConfig(join(record.workDir, file), readFileSync(join(INSTALLER_ASSETS, file), 'utf8'));
904
899
  }
905
- // The installer owns these dependencies in both installation modes.
906
- const { dependencies } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
907
- writeFileSync(join(record.workDir, 'scripts/maintenance/package.json'), JSON.stringify({ private: true, type: 'module', dependencies }, null, 2) + '\n', { mode: 0o600 });
908
- const image = await container(record, ['image', 'inspect', `${record.project}:runtime`], { allowCodes: [1] });
909
- if (image.code !== 0 || rebuildPrivateScripts || rebuildRecovery) await compose(record, ['build', 'daemon'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
900
+ writeMaintenancePackage(record.workDir);
901
+ await effects.acquireServerImages(record, { rebuild: rebuildPrivateScripts || rebuildRecovery });
910
902
  await effects.qualifyDockerRuntime(record);
911
903
  if (rebuildPrivateScripts) rmSync(join(record.workDir, '.script-permissions-rebuild'));
912
904
  if (rebuildRecovery) rmSync(join(record.workDir, '.recovery-rebuild'));
913
905
  if (record.gateway) {
914
906
  await effects.qualifyGatewayRuntime(record);
915
- await compose(record, ['build', 'gateway'], { stream: true, env: { BUILDKIT_PROGRESS: 'plain' } });
916
907
  }
917
908
  if (runtimeOnly) return;
918
909
  await effects.prepareServerVolumes(record);
@@ -950,8 +941,8 @@ export function networkEffects(effects) {
950
941
  },
951
942
  async prepareServerBuild(record, args) {
952
943
  validateInstallation(record, record.root);
953
- if (record.schema !== 2 || record.layoutConversion || !['update', 'rebuild'].includes(args.operation)) {
954
- throw new Error('Select a converted installation for update or rebuild');
944
+ if (!['update', 'rebuild'].includes(args.operation)) {
945
+ throw new Error('Select an installation for update or rebuild');
955
946
  }
956
947
  const sources = args.operation === 'update'
957
948
  ? (args.resolvedSources
@@ -969,7 +960,6 @@ export function networkEffects(effects) {
969
960
  writePrivateNew(candidate.sourcesPath, sources);
970
961
  await effects.prepareInstallation(candidate, { runtimeOnly: true });
971
962
  if (candidate.mode === 'docker') {
972
- await compose(candidate, ['build', 'state-operation']);
973
963
  // The candidate's project name is new for this build: every image under it was
974
964
  // built now. Record them with the installation so removal can prove them.
975
965
  await effects.recordOwnedImages(record, await effects.imageIds(candidate));
@@ -1108,7 +1098,7 @@ export function networkEffects(effects) {
1108
1098
  if (record.mode === 'docker') {
1109
1099
  const proven = effects.ownedImages(record);
1110
1100
  const before = await effects.imageIds(record);
1111
- for (const target of ['runtime', 'maintenance', ...(record.gateway ? ['gateway'] : [])]) {
1101
+ for (const target of ['runtime', 'maintenance']) {
1112
1102
  const retained = `${candidate.project}:previous-${target}`;
1113
1103
  const found = await container(record, ['image', 'inspect', retained], { allowCodes: [1] });
1114
1104
  if (found.code !== 0) {
@@ -1121,7 +1111,7 @@ export function networkEffects(effects) {
1121
1111
  }
1122
1112
  // The candidate project name is a random per-build name kept in the private
1123
1113
  // record; its images were built by this update.
1124
- Object.assign(built, Object.fromEntries(Object.entries(await effects.imageIds(candidate, ['runtime', 'maintenance', ...(record.gateway ? ['gateway'] : [])]))
1114
+ Object.assign(built, Object.fromEntries(Object.entries(await effects.imageIds(candidate, ['runtime', 'maintenance']))
1125
1115
  .map(([tag, id]) => [`${record.project}:${tag.slice(candidate.project.length + 1)}`, id])));
1126
1116
  }
1127
1117
  if (!existsSync(previous)) {
@@ -1136,11 +1126,14 @@ export function networkEffects(effects) {
1136
1126
  renameSync(candidate.workDir, record.workDir);
1137
1127
  } else privateDirectory(record.workDir);
1138
1128
  if (record.mode === 'docker') {
1139
- for (const target of ['runtime', 'maintenance', ...(record.gateway ? ['gateway'] : [])]) {
1129
+ for (const target of ['runtime', 'maintenance']) {
1140
1130
  await container(candidate, ['tag', `${candidate.project}:${target}`, `${record.project}:${target}`]);
1141
1131
  }
1142
1132
  }
1133
+ const previousPolicy = policyHash(readFileSync(record.sourcesPath));
1143
1134
  atomicWriteConfig(record.sourcesPath, readFileSync(candidate.sourcesPath));
1135
+ // The new generation was retained before this switch; keep it and the one it replaces.
1136
+ if (record.mode === 'docker') pruneGenerations(record.root, [policyHash(readFileSync(record.sourcesPath)), previousPolicy]);
1144
1137
  if (record.mode === 'docker') await effects.recordOwnedImages(record, built);
1145
1138
  },
1146
1139
  /** Current image IDs of this project's tags (only those that exist). */
@@ -1164,11 +1157,9 @@ export function networkEffects(effects) {
1164
1157
  if (next) atomicWriteConfig(path, next);
1165
1158
  },
1166
1159
  async validateServerBuildState(record) {
1167
- if (record.mode === 'docker') {
1168
- return effects.runDockerConversion(record, { target: `${record.project}_server-storage` }, 'validate');
1169
- }
1170
- const { validateConvertedPackageState } = await import('./layout-conversion.mjs');
1171
- validateConvertedPackageState(record);
1160
+ const { validateDockerState, validatePackageState } = await import('./state-validation.mjs');
1161
+ if (record.mode === 'docker') return validateDockerState(record, effects);
1162
+ validatePackageState(record);
1172
1163
  },
1173
1164
  async discardServerBuild(candidate) {
1174
1165
  if (candidate.mode === 'docker') {
@@ -1240,7 +1231,6 @@ export function networkEffects(effects) {
1240
1231
  }
1241
1232
  },
1242
1233
  async serverMaintenance(record, args) {
1243
- if (record.schema !== 2 || record.layoutConversion) throw new Error('Finish managed layout conversion before maintenance');
1244
1234
  if (!['server', 'daemon', 'telegram', 'cowork', 'messenger'].includes(args.domain) || !['backup', 'restore', 'reset'].includes(args.operation) || (args.domain === 'server' && args.operation === 'reset')) {
1245
1235
  throw new Error('Addressed shared-state maintenance is not yet available');
1246
1236
  }
@@ -1268,130 +1258,11 @@ export function networkEffects(effects) {
1268
1258
  }
1269
1259
  await effects.serverLifecycle(record, 'start', running);
1270
1260
  },
1271
- async selectConversionVolumes(record, { allowMissingSources = false } = {}) {
1272
- if (record.schema !== 1 || record.mode !== 'docker') {
1273
- throw new Error('Select the recorded legacy Docker source');
1274
- }
1275
- const result = await compose(record, ['config', '--format', 'json']);
1276
- const configuration = JSON.parse(result.stdout);
1277
- const sources = {};
1278
- const inspectOwned = async (name, key, optional = false) => {
1279
- if (typeof name !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(name)) {
1280
- throw new Error('Invalid conversion volume name');
1281
- }
1282
- const result = await container(record, ['volume', 'inspect', '--format', '{{json .}}', name], {
1283
- ...(optional ? { allowCodes: [1] } : {}),
1284
- });
1285
- if (result.code !== 0) {
1286
- if (optional) {
1287
- const inventory = await container(record, ['volume', 'ls', '--format', '{{.Name}}']);
1288
- if (inventory.code === 0 && !inventory.stdout.split(/\s+/).includes(name)) return false;
1289
- }
1290
- throw new Error(`Source volume is missing or unavailable: ${name}`);
1291
- }
1292
- const volume = JSON.parse(result.stdout);
1293
- if (volume.Name !== name || volume.Labels?.['com.docker.compose.project'] !== record.project
1294
- || volume.Labels?.['com.docker.compose.volume'] !== key) {
1295
- throw new Error(`Conversion volume ownership differs: ${name}`);
1296
- }
1297
- if (volume.Driver !== 'local' || Object.keys(volume.Options ?? {}).length) {
1298
- throw new Error(`External or custom volume storage requires explicit ownership resolution: ${name}`);
1299
- }
1300
- return true;
1301
- };
1302
- for (const service of SERVER_SERVICES) {
1303
- const mounts = configuration.services?.[service]?.volumes ?? [];
1304
- const selected = [{ key: `${service}-state`, alias: service,
1305
- target: service === 'daemon' ? '/var/lib/ours' : `/var/lib/ours-${service}`, subpath: 'data' }];
1306
- if (service !== 'daemon') selected.push({
1307
- key: `${service}-credential`, alias: `${service}-credential`, target: `/credentials/${service}`,
1308
- });
1309
- for (const selection of selected) {
1310
- const mount = mounts.find(mount => mount.target === selection.target);
1311
- const declared = configuration.volumes?.[selection.key];
1312
- if (mount?.type !== 'volume' || mount.source !== selection.key
1313
- || mount.volume?.subpath !== selection.subpath || !declared || declared.external) {
1314
- throw new Error(`Unexpected legacy source mount for ${selection.alias}`);
1315
- }
1316
- if ((declared.driver && declared.driver !== 'local') || Object.keys(declared.driver_opts ?? {}).length) {
1317
- throw new Error(`External or custom volume storage requires explicit ownership resolution: ${selection.key}`);
1318
- }
1319
- if (!await inspectOwned(declared.name, selection.key, allowMissingSources)) continue;
1320
- if (Object.values(sources).includes(declared.name)) throw new Error('Conversion source volumes alias each other');
1321
- sources[selection.alias] = declared.name;
1322
- }
1323
- }
1324
- const target = `${record.project}_server-storage`;
1325
- if (Object.values(sources).includes(target)) throw new Error('Conversion destination aliases a source volume');
1326
- const targetExists = await inspectOwned(target, 'server-storage', true);
1327
- if (targetExists && !record.layoutConversion) throw new Error('Unreserved conversion destination already exists');
1328
- return { sources, target, targetExists };
1329
- },
1330
- async prepareDockerConversionRuntime(record) {
1331
- const { prepareDockerConversionRuntime } = await import('./docker-conversion-runtime.mjs');
1332
- await prepareDockerConversionRuntime(record, effects, INSTALLER_ASSETS);
1333
- },
1334
- async runDockerConversion(record, volumes, operation, label) {
1335
- const { runDockerConversion } = await import('./docker-conversion-runtime.mjs');
1336
- return runDockerConversion(record, volumes, operation, label, effects);
1337
- },
1338
- async convertDockerInstallation(record, operation) {
1339
- const { convertDockerInstallation } = await import('./docker-layout-installation.mjs');
1340
- return convertDockerInstallation(record, operation, effects);
1341
- },
1342
1261
  async confirmDockerWritersStopped(record) {
1343
1262
  await requireCleanContainerExit(record, record.services);
1344
1263
  },
1345
- async prepareLegacyPackageSource(record) {
1346
- await ownerCommand(record, 'cowork', 'prepare-backup');
1347
- },
1348
- async retainConvertedPackageAuthority(record, daemon) {
1349
- await effects.run(bin(record, existsSync(bin(record, 'ours-daemon')) ? 'ours-daemon' : 'ours'), [
1350
- 'config', 'access-retain', '--config', record.configPath,
1351
- '--target-state-dir', daemon, '--json',
1352
- ], { env: localEnv(record), sensitive: true });
1353
- },
1354
- async convertPackageInstallation(record, operation) {
1355
- const { convertPackageInstallation } = await import('./layout-conversion.mjs');
1356
- return convertPackageInstallation(record, operation, effects);
1357
- },
1358
- async stopPendingConversion(record) {
1359
- validateInstallation(record, record.root);
1360
- if (!record.layoutConversion) throw new Error('Select a pending layout conversion');
1361
- const source = record.layoutConversion.sourceRecord;
1362
- const selections = record.schema === 1 ? [source] : [record, source];
1363
- for (const selection of selections) {
1364
- if (record.mode === 'docker') {
1365
- await effects.serverLifecycle(selection, 'stop', SERVER_SERVICES);
1366
- } else {
1367
- // Cleanup can already have removed former state. Never recreate it.
1368
- const paths = installationPaths(selection);
1369
- const retired = record.schema === 2 && selection === source;
1370
- const selected = selection.services.filter(service => {
1371
- if (!existsSync(paths[service])) return false;
1372
- // Published conversion already retired old registrations. Partial
1373
- // cleanup may leave directories without usable owner configuration.
1374
- if (!retired || service === 'messenger') return true;
1375
- return existsSync(service === 'daemon' ? selection.configPath : join(paths[service], 'config.json'));
1376
- });
1377
- await nativeLifecycle(selection, 'stop', selected, { effects, localEnv, ownerCommand, bin, stopSelections: selections });
1378
- }
1379
- }
1380
- },
1381
- async retireLegacyServices(record) {
1382
- if (record.schema !== 1 || !['packages', 'docker'].includes(record.mode)) {
1383
- throw new Error('Select a legacy managed installation for service retirement');
1384
- }
1385
- if (record.mode === 'docker') {
1386
- await effects.serverLifecycle(record, 'stop');
1387
- await requireCleanContainerExit(record, record.services);
1388
- await compose(record, ['rm', '-f', ...record.services]);
1389
- return;
1390
- }
1391
- await nativeLifecycle(record, 'retire', record.services, { effects, localEnv, ownerCommand, bin });
1392
- },
1393
1264
  async serverUninstall(record) {
1394
- if (record.schema !== 2 || record.layoutConversion || record.buildTransition) throw new Error('Complete retained installation transitions before uninstall');
1265
+ if (record.buildTransition) throw new Error('Complete retained installation transitions before uninstall');
1395
1266
  if (record.mode === 'docker') {
1396
1267
  await effects.serverLifecycle(record, 'stop');
1397
1268
  await requireCleanContainerExit(record, record.services);
@@ -1659,7 +1530,7 @@ export function networkEffects(effects) {
1659
1530
  };
1660
1531
  }
1661
1532
 
1662
- async function nativeLifecycle(record, operation, selected, { effects, localEnv, ownerCommand, bin, stopSelections }) {
1533
+ async function nativeLifecycle(record, operation, selected, { effects, localEnv, ownerCommand, bin }) {
1663
1534
  const linux = effects.platform.platform === 'linux';
1664
1535
  const daemonState = installationPaths(record).daemon;
1665
1536
  const daemonService = linux ? unitNameForStateDir(daemonState) : launchdLabelForStateDir(daemonState);
@@ -1681,8 +1552,7 @@ async function nativeLifecycle(record, operation, selected, { effects, localEnv,
1681
1552
  if (service === 'daemon') continue;
1682
1553
  if (existsSync(plan.path)) {
1683
1554
  const text = readFileSync(plan.path, 'utf8');
1684
- const allowedStates = stopSelections?.map(selection => installationPaths(selection)[service]) ?? [plan.state];
1685
- if (service === 'messenger' ? !text.includes(messenger.marker) : !allowedStates.includes(consumerServiceState(text, service, effects.platform.platform))) throw new Error(`Refusing unrelated existing ${service} service: ${plan.path}`);
1555
+ if (service === 'messenger' ? !text.includes(messenger.marker) : consumerServiceState(text, service, effects.platform.platform) !== plan.state) throw new Error(`Refusing unrelated existing ${service} service: ${plan.path}`);
1686
1556
  }
1687
1557
  }
1688
1558
  const manager = async (service, op) => {
@@ -1741,7 +1611,7 @@ async function nativeLifecycle(record, operation, selected, { effects, localEnv,
1741
1611
  if (observed.code === 0) throw new Error('Selected daemon service is still loaded or active; authority operation refused');
1742
1612
  }
1743
1613
  }
1744
- if ((await nativeLifecycle(record, 'status', selected, { effects, localEnv, ownerCommand, bin, stopSelections })).length) throw new Error('Selected writers did not stop');
1614
+ if ((await nativeLifecycle(record, 'status', selected, { effects, localEnv, ownerCommand, bin })).length) throw new Error('Selected writers did not stop');
1745
1615
  if (operation === 'retire') {
1746
1616
  // Daemon registration removal belongs to its existing uninstall-service command.
1747
1617
  // Consumer definitions were checked against this installation before any stop.
package/lib/gateway.mjs CHANGED
@@ -1,3 +1,9 @@
1
+ import { readFileSync } from 'node:fs';
2
+ /** Upstream gateway image; generated config is passed in Compose, so nothing is built locally. */
3
+ export const GATEWAY_IMAGE='nginx:1.28-alpine@sha256:a8b39bd9cf0f83869a2162827a0caf6137ddf759d50a171451b335cecc87d236';
4
+ const GATEWAY_ENTRYPOINT=readFileSync(new URL('../assets/gateway-entrypoint.sh',import.meta.url),'utf8');
5
+ // JSON strings are YAML double-quoted scalars; $$ keeps Compose from interpolating.
6
+ const composeString=value=>JSON.stringify(value).replaceAll('$','$$$$');
1
7
  /** One public URL; fixed same-origin service paths are never supplied by a peer. */
2
8
  export const GATEWAY_SERVICES = Object.freeze({daemon:'/daemon',cowork:'/cowork',telegram:'/tg-connector',messenger:'/messenger'});
3
9
  /** Notifications run inside the Messenger container when its runtime ships the service. */
@@ -44,10 +50,10 @@ export function gatewayCompose(record) {
44
50
  OURS_MESSENGER_PUBLIC_ORIGIN: ${JSON.stringify(origin)}
45
51
  OURS_MESSENGER_BASE_PATH: ${JSON.stringify(prefix + "/messenger/")}
46
52
  gateway:
47
- image: "\${OURS_GATEWAY_IMAGE:-${record.project}:gateway}"
48
- build:
49
- context: .
50
- dockerfile: Dockerfile.gateway
53
+ image: "${GATEWAY_IMAGE}"
54
+ entrypoint: ["/bin/sh", "-ec", ${composeString(GATEWAY_ENTRYPOINT)}]
55
+ environment:
56
+ OURS_GATEWAY_TEMPLATE: ${composeString(gatewayNginx(record))}
51
57
  user: "101:101"
52
58
  read_only: true
53
59
  cap_drop: [ALL]
@@ -0,0 +1,164 @@
1
+ /** Published server images: descriptor validation, generation selection and digest-bound pulls. */
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { basename, dirname, join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { isDeepStrictEqual } from 'node:util';
7
+ import { atomicWriteConfig } from './config.mjs';
8
+ import { runContainer } from './container-engine.mjs';
9
+
10
+ export const IMAGE_REPOSITORIES = Object.freeze({ runtime: 'docker.io/adaptframework/ours-runtime', maintenance: 'docker.io/adaptframework/ours-maintenance' });
11
+ export const IMAGE_TARGETS = Object.freeze(Object.keys(IMAGE_REPOSITORIES));
12
+ export const IMAGE_ROLES = Object.freeze(['server', 'daemon']);
13
+ export const IMAGE_PLATFORM = 'linux/amd64';
14
+ /** Generated at release packing; development checkouts have none and build locally. */
15
+ export const PACKAGED_IMAGES = fileURLToPath(new URL('../assets/images.json', import.meta.url));
16
+ export const IMAGES_FILE = 'images.json';
17
+ /** npm packages ship only the `files` whitelist: a published installer has no test/ directory. */
18
+ export const PUBLISHED_INSTALLER = !existsSync(fileURLToPath(new URL('../test/', import.meta.url)));
19
+ const DIGEST = /^sha256:[0-9a-f]{64}$/, HASH = /^[0-9a-f]{64}$/;
20
+
21
+ export const policyHash = bytes => createHash('sha256').update(bytes).digest('hex');
22
+ /** The exact bytes the installer retains as sources.json for a resolved selection. */
23
+ export const policyBytes = policy => Buffer.from(`${JSON.stringify(policy, null, 2)}\n`);
24
+
25
+ const object = value => value && typeof value === 'object' && !Array.isArray(value);
26
+ function exactKeys(value, keys, what) {
27
+ if (!object(value) || Object.keys(value).sort().join() !== [...keys].sort().join()) throw new Error(`Invalid image descriptor: ${what}`);
28
+ }
29
+ function validateTarget(target, value) {
30
+ exactKeys(value, ['repository', 'index', 'manifest', 'config'], target);
31
+ if (value.repository !== IMAGE_REPOSITORIES[target] || ![value.index, value.manifest, value.config].every(digest => DIGEST.test(digest))) {
32
+ throw new Error(`Invalid image descriptor: ${target}`);
33
+ }
34
+ }
35
+ function validateBinding(value, what) {
36
+ if (!['stable', 'nightly'].includes(value.channel) || typeof value.installerVersion !== 'string' || !value.installerVersion
37
+ || !/^[0-9a-f]{40}$/.test(value.commit) || value.platform !== IMAGE_PLATFORM) throw new Error(`Invalid image descriptor: ${what}`);
38
+ }
39
+
40
+ /** The packaged descriptor: both roles, fixed repositories, bound to the packaged release. */
41
+ export function validateImagesManifest(value, release) {
42
+ exactKeys(value, ['schema', 'channel', 'installerVersion', 'commit', 'platform', 'variants'], 'manifest');
43
+ if (value.schema !== 1) throw new Error('Invalid image descriptor: manifest');
44
+ validateBinding(value, 'manifest');
45
+ if (release && (value.channel !== release.channel || value.installerVersion !== release.installerVersion)) {
46
+ throw new Error('Image descriptor does not belong to the packaged release');
47
+ }
48
+ exactKeys(value.variants, IMAGE_ROLES, 'variants');
49
+ for (const role of IMAGE_ROLES) {
50
+ const variant = value.variants[role];
51
+ exactKeys(variant, ['policySha256', ...IMAGE_TARGETS], role);
52
+ if (!HASH.test(variant.policySha256)) throw new Error(`Invalid image descriptor: ${role}`);
53
+ for (const target of IMAGE_TARGETS) validateTarget(target, variant[target]);
54
+ }
55
+ return value;
56
+ }
57
+
58
+ export function readPackagedImages(release, path = PACKAGED_IMAGES) {
59
+ if (!existsSync(path)) return null;
60
+ return validateImagesManifest(JSON.parse(readFileSync(path, 'utf8')), release);
61
+ }
62
+
63
+ /** One retained generation: what a role's selection was installed from. */
64
+ export function generationEntry(manifest, role) {
65
+ const { channel, installerVersion, commit, platform } = manifest;
66
+ return { role, channel, installerVersion, commit, platform, ...Object.fromEntries(IMAGE_TARGETS.map(target => [target, manifest.variants[role][target]])) };
67
+ }
68
+ function validateEntry(entry) {
69
+ exactKeys(entry, ['role', 'channel', 'installerVersion', 'commit', 'platform', ...IMAGE_TARGETS], 'generation');
70
+ if (!IMAGE_ROLES.includes(entry.role)) throw new Error('Invalid image descriptor: generation');
71
+ validateBinding(entry, 'generation');
72
+ for (const target of IMAGE_TARGETS) validateTarget(target, entry[target]);
73
+ }
74
+
75
+ /** An update candidate is staged in <root>/.build-*; its generations belong to the installation. */
76
+ export const imagesRoot = root => basename(root).startsWith('.build-') ? dirname(root) : root;
77
+
78
+ export function readGenerations(root) {
79
+ const path = join(imagesRoot(root), IMAGES_FILE);
80
+ if (!existsSync(path)) return {};
81
+ const store = JSON.parse(readFileSync(path, 'utf8'));
82
+ exactKeys(store, ['schema', 'generations'], 'retained generations');
83
+ if (store.schema !== 1 || !object(store.generations)) throw new Error('Invalid image descriptor: retained generations');
84
+ for (const [hash, entry] of Object.entries(store.generations)) {
85
+ if (!HASH.test(hash)) throw new Error('Invalid image descriptor: retained generations');
86
+ validateEntry(entry);
87
+ }
88
+ return store.generations;
89
+ }
90
+ function writeGenerations(root, generations) {
91
+ atomicWriteConfig(join(imagesRoot(root), IMAGES_FILE), JSON.stringify({ schema: 1, generations }, null, 2) + '\n');
92
+ }
93
+ /** Added before its sources.json is retained, so every retained selection keeps its generation. */
94
+ export function rememberGeneration(root, hash, entry) {
95
+ validateEntry(entry);
96
+ const generations = readGenerations(root);
97
+ if (generations[hash] && !isDeepStrictEqual(generations[hash], entry)) throw new Error('A different image generation is already retained for this selection');
98
+ if (!generations[hash]) writeGenerations(root, { ...generations, [hash]: entry });
99
+ }
100
+ /** After sources.json is replaced: keep the active and previous selections only. */
101
+ export function pruneGenerations(root, keep) {
102
+ const generations = readGenerations(root);
103
+ const kept = Object.fromEntries(Object.entries(generations).filter(([hash]) => keep.includes(hash)));
104
+ if (Object.keys(kept).length !== Object.keys(generations).length) writeGenerations(root, kept);
105
+ }
106
+
107
+ /**
108
+ * Decide where a selection's images come from, keyed only by the retained policy hash:
109
+ * its own retained generation, else the packaged release, else an explicit local build.
110
+ * A released selection whose published descriptor is missing or mismatched is an error.
111
+ */
112
+ export function selectServerImages({ root, sourcesPath, role, packaged, releasedHash, published = PUBLISHED_INSTALLER, buildLocally = false }) {
113
+ if (!IMAGE_ROLES.includes(role)) throw new Error(`Unsupported image role: ${role}`);
114
+ if (buildLocally) return { kind: 'build', reason: 'local build requested with OURS_BUILD_LOCALLY=1' };
115
+ const hash = policyHash(readFileSync(sourcesPath));
116
+ const retained = readGenerations(root)[hash];
117
+ if (retained) {
118
+ if (retained.role !== role) throw new Error('Retained image generation belongs to a different installation role');
119
+ return { kind: 'pull', hash, entry: retained };
120
+ }
121
+ if (packaged?.variants[role].policySha256 === hash) return { kind: 'pull', hash, entry: generationEntry(packaged, role), remember: true };
122
+ if ((packaged || published) && releasedHash === hash) throw new Error(packaged ? 'The published image descriptor does not match this release selection; reinstall the installer package'
123
+ : 'This installer package lacks its published image descriptor; reinstall the installer package');
124
+ return { kind: 'build', reason: packaged ? 'the selected packages differ from this installer release (custom sources or an earlier installation)' : 'this installer has no published images (development checkout)' };
125
+ }
126
+
127
+ const pairScript = `
128
+ const fs = require('node:fs'), crypto = require('node:crypto');
129
+ const hash = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
130
+ const records = Object.fromEntries(['package.json', 'package-lock.json', 'dependency-tree.json', 'build-context.json', 'sources.json'].map(name => [name, hash('/opt/ours/' + name)]));
131
+ const vendor = '/opt/ours/docker/vendor';
132
+ for (const name of fs.readdirSync(vendor).sort()) records['vendor/' + name] = hash(vendor + '/' + name);
133
+ console.log(JSON.stringify(records));
134
+ `;
135
+ /** Runtime and maintenance must carry one npm tree, one policy and one vendor set. */
136
+ export async function verifyImagePair(effects, record, refs) {
137
+ const reports = [];
138
+ for (const ref of refs) {
139
+ const result = await runContainer(effects, record, ['run', '--rm', '--network', 'none', '--read-only', '--cap-drop', 'ALL',
140
+ '--security-opt', 'no-new-privileges:true', '--user', `${record.uid ?? 1000}:${record.gid ?? 1000}`, '--entrypoint', 'node', ref, '-e', pairScript], { timeout: 60000 });
141
+ reports.push(JSON.parse(result.stdout));
142
+ }
143
+ if (!isDeepStrictEqual(reports[0], reports[1])) throw new Error('Published runtime and maintenance images do not share one build');
144
+ }
145
+
146
+ /** Pull each image by its published index digest and name it for this installation project. */
147
+ export async function pullServerImages(effects, record, entry, { project = record.project } = {}) {
148
+ for (const target of IMAGE_TARGETS) {
149
+ const published = entry[target], ref = `${published.repository}@${published.index}`;
150
+ effects.out?.(`Downloading the published ${target} image (${published.repository.replace(/^docker\.io\//, '')})…`);
151
+ try { await runContainer(effects, record, ['pull', '--platform', entry.platform, ref], { stream: true, timeout: 1800000 }); }
152
+ catch (error) {
153
+ throw new Error(`Could not download the published ${target} image ${ref}. Check the network connection; if Docker Hub's anonymous pull limit was reached, run "docker login" and retry. To build from source instead, rerun with OURS_BUILD_LOCALLY=1.`, { cause: error });
154
+ }
155
+ const [value] = JSON.parse((await runContainer(effects, record, ['image', 'inspect', ref])).stdout);
156
+ // Engines name a pulled image by its config, platform manifest or index digest.
157
+ const repository = published.repository.replace(/^docker\.io\//, '');
158
+ if (![published.config, published.manifest, published.index].includes(value?.Id)
159
+ || !(value.RepoDigests ?? []).some(digest => digest.replace(/^docker\.io\//, '') === `${repository}@${published.index}`)
160
+ || value.Config?.Labels?.['network.ours.build-context'] !== '1') throw new Error(`The downloaded ${target} image does not match its published digest`);
161
+ await runContainer(effects, record, ['tag', ref, `${project}:${target}`]);
162
+ }
163
+ await verifyImagePair(effects, record, IMAGE_TARGETS.map(target => `${project}:${target}`));
164
+ }