@evomap/evolver-proxy 2.0.48 → 2.0.50

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 (41) hide show
  1. package/dist/bin/evolver-proxy.js +86 -50
  2. package/dist/daemon/backgroundCuration.d.ts +54 -0
  3. package/dist/daemon/backgroundCuration.js +159 -0
  4. package/dist/daemon/curationGit.d.ts +5 -0
  5. package/dist/daemon/curationGit.js +140 -0
  6. package/dist/daemon/distillMeasures.d.ts +59 -0
  7. package/dist/daemon/distillMeasures.js +139 -0
  8. package/dist/daemon/localRecall.d.ts +6 -1
  9. package/dist/daemon/localRecall.js +59 -6
  10. package/dist/daemon/observedEvidence.d.ts +43 -0
  11. package/dist/daemon/observedEvidence.js +116 -0
  12. package/dist/daemon/proxyDaemon.d.ts +19 -0
  13. package/dist/daemon/proxyDaemon.js +179 -30
  14. package/dist/daemon/recallContext.js +2 -1
  15. package/dist/lifecycle/claimNudge.js +1 -1
  16. package/dist/lifecycle/deployGuard.js +1 -1
  17. package/dist/lifecycle/legacyNodeId.js +1 -1
  18. package/dist/lifecycle/manager.js +1 -1
  19. package/dist/llm/index.js +1 -1
  20. package/dist/llm/server.js +1 -1
  21. package/dist/llm/traceBackfill.js +1 -1
  22. package/dist/llm/traceConfig.js +1 -1
  23. package/dist/llm/traceControl.js +1 -1
  24. package/dist/llm/traceEnvelope.js +1 -1
  25. package/dist/llm/traceSink.js +1 -1
  26. package/dist/llm/traceUploadPayload.js +1 -1
  27. package/dist/llm/upstream.js +1 -1
  28. package/dist/router/cachePassthrough.js +1 -1
  29. package/dist/router/features.js +1 -1
  30. package/dist/router/index.js +1 -1
  31. package/dist/router/messagesRoute.js +1 -1
  32. package/dist/router/modelRouter.js +1 -1
  33. package/dist/router/providerRoutes.js +1 -1
  34. package/dist/router/sseScan.js +1 -1
  35. package/dist/selfUpdate/bootstrap.js +40 -46
  36. package/dist/selfUpdate/bootstrapReadiness.js +15 -3
  37. package/dist/selfUpdate/migration.js +37 -22
  38. package/dist/selfUpdate/transaction.js +158 -59
  39. package/dist/selfUpdate/windowsUpdater.js +70 -10
  40. package/dist/sync/engine.js +1 -1
  41. package/package.json +3 -3
@@ -1,13 +1,12 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
2
  import { execFile } from 'node:child_process';
3
- import { constants, watch } from 'node:fs';
3
+ import { constants, fstatSync, watch } from 'node:fs';
4
4
  import { chmod, link, lstat, mkdir, open, realpath, rename, rm, writeFile, } from 'node:fs/promises';
5
5
  import { basename, dirname, isAbsolute, join, resolve, win32 } from 'node:path';
6
6
  import { promisify } from 'node:util';
7
- import { ops } from '@evomap/evolver-core';
7
+ import { assetstore, ops } from '@evomap/evolver-core';
8
8
  import { resolveSelfUpdateTarget } from './releaseBinary.js';
9
9
  import { SELF_UPDATE_FAILURE_CODES, selfUpdateFailure } from './failureCodes.js';
10
- import { selfUpdateFileMetadata } from './fileMetadata.js';
11
10
  import { bindWindowsManagedExecutable, prepareWindowsExecutableSwap, resolveWindowsUpdaterPaths, } from './windowsUpdater.js';
12
11
  const execFileAsync = promisify(execFile);
13
12
  const JOURNAL_SCHEMA_VERSION = 2;
@@ -95,6 +94,7 @@ export async function provisionStableUnixRecoveryController(options) {
95
94
  }
96
95
  const owner = await acquireLock(paths.lock, options.pid ?? process.pid, undefined, paths.stateRootIdentity);
97
96
  const notifyPublished = () => observeArtifactPublicationAliases(paths, () => options.onArtifactPublished?.(configuredControllerPath, configuredTemporaryPath));
97
+ let temporaryWritten = false;
98
98
  let retainClaimOnFailure = options.replaceExisting === false && options.artifactClaimPath !== undefined;
99
99
  try {
100
100
  await assertStateRootIdentity(paths);
@@ -118,14 +118,16 @@ export async function provisionStableUnixRecoveryController(options) {
118
118
  throw error;
119
119
  }
120
120
  }
121
- const targetIdentity = await assertRegularNonSymlink(paths.targetPath, 'target');
122
- const targetBytes = await readRegularFile(paths.targetPath);
121
+ const targetStat = await assertRegularNonSymlink(paths.targetPath, 'target');
122
+ const targetIdentity = { dev: targetStat.dev, ino: targetStat.ino, birthtimeNs: targetStat.birthtimeNs };
123
+ const targetBytes = await readRegularFile(paths.targetPath, targetIdentity);
123
124
  await writeExclusiveFile(temporaryPath, targetBytes, 0o700, ownershipReceiptPath
124
125
  ? {
125
126
  ownershipReceiptPath,
126
127
  onClaimCreated: notifyPublished,
127
128
  }
128
129
  : undefined);
130
+ temporaryWritten = true;
129
131
  await assertSameFileIdentity(paths.targetPath, targetIdentity);
130
132
  if (options.replaceExisting === false) {
131
133
  await link(temporaryPath, controllerPath);
@@ -148,7 +150,7 @@ export async function provisionStableUnixRecoveryController(options) {
148
150
  return controllerPath;
149
151
  }
150
152
  finally {
151
- if (!retainClaimOnFailure) {
153
+ if (!retainClaimOnFailure && temporaryWritten) {
152
154
  try {
153
155
  await assertStateRootIdentity(paths);
154
156
  if (ownershipReceiptPath)
@@ -230,6 +232,7 @@ export async function provisionStableWindowsRecoveryController(options, processE
230
232
  }
231
233
  const owner = await acquireLock(paths.lock, options.pid ?? process.pid, undefined, paths.stateRootIdentity);
232
234
  const notifyPublished = () => observeArtifactPublicationAliases(paths, () => options.onArtifactPublished?.(configuredControllerPath, configuredTemporaryPath));
235
+ let temporaryWritten = false;
233
236
  let retainClaimOnFailure = options.replaceExisting === false && options.artifactClaimPath !== undefined;
234
237
  try {
235
238
  await assertStateRootIdentity(paths);
@@ -261,14 +264,16 @@ export async function provisionStableWindowsRecoveryController(options, processE
261
264
  throw error;
262
265
  }
263
266
  }
264
- const targetIdentity = await assertRegularNonSymlink(paths.targetPath, 'target');
265
- const targetBytes = await readRegularFile(paths.targetPath);
267
+ const targetStat = await assertRegularNonSymlink(paths.targetPath, 'target');
268
+ const targetIdentity = { dev: targetStat.dev, ino: targetStat.ino, birthtimeNs: targetStat.birthtimeNs };
269
+ const targetBytes = await readRegularFile(paths.targetPath, targetIdentity);
266
270
  await writeExclusiveFile(temporaryPath, targetBytes, 0o700, ownershipReceiptPath
267
271
  ? {
268
272
  ownershipReceiptPath,
269
273
  onClaimCreated: notifyPublished,
270
274
  }
271
275
  : undefined);
276
+ temporaryWritten = true;
272
277
  await assertSameFileIdentity(paths.targetPath, targetIdentity);
273
278
  if (options.replaceExisting !== false) {
274
279
  try {
@@ -301,7 +306,7 @@ export async function provisionStableWindowsRecoveryController(options, processE
301
306
  return controllerPath;
302
307
  }
303
308
  finally {
304
- if (!retainClaimOnFailure) {
309
+ if (!retainClaimOnFailure && temporaryWritten) {
305
310
  try {
306
311
  await assertStateRootIdentity(paths);
307
312
  if (ownershipReceiptPath)
@@ -417,8 +422,9 @@ export async function beginDurableSelfUpdate(targetVersion, options) {
417
422
  const backupName = `${journal.transaction_id}.backup`;
418
423
  const backupPath = join(paths.backups, backupName);
419
424
  const targetStat = await assertRegularNonSymlink(paths.targetPath, 'target');
425
+ const targetIdentity = { dev: targetStat.dev, ino: targetStat.ino, birthtimeNs: targetStat.birthtimeNs };
420
426
  const targetMode = Number(targetStat.mode) & 0o777;
421
- await copyRegularFile(paths.targetPath, backupPath, targetMode);
427
+ await copyRegularFile(paths.targetPath, backupPath, targetMode, targetIdentity);
422
428
  await persist('backed_up', { backup_name: backupName });
423
429
  if ((options.platform ?? process.platform) === 'win32') {
424
430
  try {
@@ -456,7 +462,7 @@ export async function beginDurableSelfUpdate(targetVersion, options) {
456
462
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REJECTED_VERIFICATION, 'staged_artifact_changed_after_verification');
457
463
  }
458
464
  await writeExclusiveFile(installTmp, stagedBytes, targetMode);
459
- await assertSameFileIdentity(paths.targetPath, targetStat);
465
+ await assertSameFileIdentity(paths.targetPath, targetIdentity);
460
466
  await rename(installTmp, paths.targetPath);
461
467
  await persist('installed');
462
468
  }
@@ -1061,10 +1067,17 @@ async function assertDirectoryNonSymlink(path) {
1061
1067
  await realpath(path);
1062
1068
  }
1063
1069
  async function assertRegularNonSymlink(path, kind) {
1064
- const info = await lstat(path);
1070
+ const info = await lstat(path, { bigint: true });
1065
1071
  if (info.isSymbolicLink() || !info.isFile()) {
1066
1072
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, `${kind}_not_regular`);
1067
1073
  }
1074
+ if (process.platform === 'win32' && info.dev === 0n) {
1075
+ const witnessed = captureSelfUpdateFileIdentity(path, `${kind}_changed_during_capture`);
1076
+ if (witnessed.ino !== info.ino || witnessed.birthtimeNs !== info.birthtimeNs) {
1077
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, `${kind}_changed_during_capture`);
1078
+ }
1079
+ Object.assign(info, { dev: witnessed.dev });
1080
+ }
1068
1081
  return info;
1069
1082
  }
1070
1083
  async function moveRegularFile(source, destination, mode) {
@@ -1080,61 +1093,138 @@ async function moveRegularFile(source, destination, mode) {
1080
1093
  await rm(source, { force: true });
1081
1094
  }
1082
1095
  }
1083
- async function copyRegularFile(source, destination, mode) {
1084
- await writeExclusiveFile(destination, await readRegularFile(source), mode);
1096
+ function captureSelfUpdateFileIdentity(path, detail) {
1097
+ try {
1098
+ return assetstore.captureRegularAssetFileIdentity(path);
1099
+ }
1100
+ catch (error) {
1101
+ if (isUnsafeAssetFileIdentity(error)) {
1102
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, detail, { cause: error });
1103
+ }
1104
+ throw error;
1105
+ }
1085
1106
  }
1086
- async function readRegularFile(source) {
1107
+ function isUnsafeAssetFileIdentity(error) {
1108
+ return isErrno(error, 'UNSAFE_ASSET_STORE_PATH');
1109
+ }
1110
+ async function copyRegularFile(source, destination, mode, expected) {
1111
+ await writeExclusiveFile(destination, await readRegularFile(source, expected), mode);
1112
+ }
1113
+ async function readRegularFile(source, expected) {
1114
+ const before = expected ?? captureSelfUpdateFileIdentity(source, 'source_not_regular');
1087
1115
  const sourceHandle = await open(source, constants.O_RDONLY | noFollowFlag());
1088
1116
  try {
1089
- const sourceStat = await sourceHandle.stat();
1090
- if (!sourceStat.isFile())
1091
- throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, 'source_not_regular');
1092
- return await sourceHandle.readFile();
1117
+ assetstore.assertOpenedRegularAssetFile(sourceHandle.fd, source, before);
1118
+ const bytes = await sourceHandle.readFile();
1119
+ assetstore.assertOpenedRegularAssetFile(sourceHandle.fd, source, before);
1120
+ return bytes;
1121
+ }
1122
+ catch (error) {
1123
+ if (isUnsafeAssetFileIdentity(error)) {
1124
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, 'source_changed_during_read', { cause: error });
1125
+ }
1126
+ throw error;
1093
1127
  }
1094
1128
  finally {
1095
1129
  await sourceHandle.close().catch(() => { });
1096
1130
  }
1097
1131
  }
1132
+ async function readBoundedFile(handle, maxBytes) {
1133
+ const bytes = Buffer.allocUnsafe(maxBytes + 1);
1134
+ let offset = 0;
1135
+ while (offset < bytes.byteLength) {
1136
+ const { bytesRead } = await handle.read(bytes, offset, bytes.byteLength - offset, null);
1137
+ if (bytesRead === 0)
1138
+ break;
1139
+ offset += bytesRead;
1140
+ }
1141
+ return bytes.subarray(0, offset);
1142
+ }
1143
+ function assertExclusivePublicationIdentity(fd, path, expected, detail) {
1144
+ try {
1145
+ assetstore.assertOpenedRegularAssetFile(fd, path, expected, 'write');
1146
+ }
1147
+ catch (error) {
1148
+ if (isUnsafeAssetFileIdentity(error)) {
1149
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, detail, { cause: error });
1150
+ }
1151
+ throw error;
1152
+ }
1153
+ }
1154
+ function sameNativeFileIdentity(actual, expected) {
1155
+ return actual.dev === expected.dev && actual.ino === expected.ino && actual.birthtimeNs === expected.birthtimeNs;
1156
+ }
1157
+ function sameExclusiveFileSnapshot(actual, expected) {
1158
+ return actual.isFile() && !actual.isSymbolicLink() && actual.nlink === 1n
1159
+ && sameNativeFileIdentity(actual, expected) && actual.size === expected.size
1160
+ && actual.mode === expected.mode && actual.uid === expected.uid && actual.gid === expected.gid
1161
+ && actual.mtimeNs === expected.mtimeNs && actual.ctimeNs === expected.ctimeNs;
1162
+ }
1163
+ async function discardExclusiveFile(path, directoryIdentity, snapshot) {
1164
+ if (!snapshot)
1165
+ return;
1166
+ try {
1167
+ await assertDirectoryIdentity(dirname(path), directoryIdentity);
1168
+ const current = assetstore.captureRegularAssetFileSnapshot(path, constants.O_WRONLY);
1169
+ if (!sameExclusiveFileSnapshot(current, snapshot))
1170
+ return;
1171
+ await rm(path, { force: true });
1172
+ await syncDirectoryDurably(dirname(path));
1173
+ }
1174
+ catch { /* Retain receipts whose ownership or file version can no longer be proven. */ }
1175
+ }
1098
1176
  async function writeExclusiveFile(destination, bytes, mode, publication) {
1099
1177
  const stagingPath = await directoryCreationPath(publication?.ownershipReceiptPath ?? destination);
1178
+ const stagingDirectory = dirname(stagingPath);
1179
+ const stagingDirectoryIdentity = await readDirectoryIdentity(stagingDirectory);
1100
1180
  if (publication
1101
1181
  && dirname(resolve(publication.ownershipReceiptPath)) !== dirname(resolve(destination))) {
1102
1182
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, 'bootstrap_controller_ownership_receipt_outside_directory');
1103
1183
  }
1104
- let stagingCreated = false;
1105
1184
  let claimPublished = false;
1106
- const destinationHandle = await open(stagingPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, mode);
1107
- stagingCreated = true;
1185
+ let completed = false;
1186
+ let cleanupSnapshot;
1187
+ const destinationHandle = await open(stagingPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollowFlag(), mode);
1108
1188
  try {
1189
+ // Capture the created inode from the held FD before the first fallible await.
1190
+ const created = fstatSync(destinationHandle.fd, { bigint: true });
1191
+ if (created.isFile() && created.size === 0n && created.nlink === 1n)
1192
+ cleanupSnapshot = created;
1193
+ const openedIdentity = { dev: created.dev, ino: created.ino, birthtimeNs: created.birthtimeNs };
1194
+ const opened = await destinationHandle.stat({ bigint: true });
1195
+ if (!opened.isFile() || !sameNativeFileIdentity(opened, openedIdentity)) {
1196
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, 'destination_not_regular');
1197
+ }
1198
+ assertExclusivePublicationIdentity(destinationHandle.fd, stagingPath, openedIdentity, 'destination_changed_during_write');
1199
+ // An interrupted write has unknown bytes; retain it unless a complete version is captured.
1200
+ cleanupSnapshot = undefined;
1109
1201
  await destinationHandle.writeFile(bytes);
1110
1202
  await destinationHandle.chmod(mode);
1203
+ cleanupSnapshot = fstatSync(destinationHandle.fd, { bigint: true });
1111
1204
  await destinationHandle.sync();
1205
+ await assertDirectoryIdentity(stagingDirectory, stagingDirectoryIdentity);
1112
1206
  if (publication) {
1113
1207
  await syncDirectoryDurably(dirname(destination));
1114
- const [opened, receipt] = await Promise.all([
1115
- destinationHandle.stat({ bigint: true }),
1116
- selfUpdateFileMetadata(publication.ownershipReceiptPath, constants.O_WRONLY),
1117
- ]);
1118
- if (!opened.isFile() || opened.dev <= 0n || opened.ino <= 0n
1119
- || receipt.dev !== opened.dev || receipt.ino !== opened.ino) {
1208
+ if (opened.dev <= 0n || opened.ino <= 0n) {
1120
1209
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, 'bootstrap_controller_ownership_receipt_mismatch');
1121
1210
  }
1211
+ assertExclusivePublicationIdentity(destinationHandle.fd, publication.ownershipReceiptPath, openedIdentity, 'bootstrap_controller_ownership_receipt_mismatch');
1122
1212
  await link(stagingPath, await directoryCreationPath(destination));
1123
1213
  await syncDirectoryDurably(dirname(destination));
1124
1214
  claimPublished = true;
1125
- const claim = await selfUpdateFileMetadata(destination, constants.O_WRONLY);
1126
- if (claim.dev !== opened.dev || claim.ino !== opened.ino) {
1127
- throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, 'bootstrap_controller_claim_receipt_mismatch');
1128
- }
1215
+ await assertDirectoryIdentity(stagingDirectory, stagingDirectoryIdentity);
1216
+ assertExclusivePublicationIdentity(destinationHandle.fd, destination, openedIdentity, 'bootstrap_controller_claim_receipt_mismatch');
1129
1217
  await publication.onClaimCreated();
1130
1218
  }
1219
+ else {
1220
+ assertExclusivePublicationIdentity(destinationHandle.fd, stagingPath, openedIdentity, 'destination_changed_during_write');
1221
+ }
1222
+ completed = true;
1131
1223
  }
1132
1224
  finally {
1133
1225
  await destinationHandle.close().catch(() => { });
1134
- if (publication && stagingCreated && !claimPublished) {
1135
- await rm(stagingPath, { force: true }).catch(() => { });
1136
- await syncDirectoryDurably(dirname(stagingPath)).catch(() => { });
1137
- }
1226
+ if (!completed && !claimPublished)
1227
+ await discardExclusiveFile(stagingPath, stagingDirectoryIdentity, cleanupSnapshot);
1138
1228
  }
1139
1229
  }
1140
1230
  async function restoreBackup(paths, journal, force = false) {
@@ -1181,34 +1271,41 @@ async function writeJournal(path, journal) {
1181
1271
  }
1182
1272
  async function readJournal(path) {
1183
1273
  let journalHandle;
1274
+ let identity;
1184
1275
  try {
1185
- const pathInfo = await selfUpdateFileMetadata(path);
1186
- if (pathInfo.isSymbolicLink() || !pathInfo.isFile()) {
1187
- throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, 'unsafe_journal');
1188
- }
1276
+ identity = captureSelfUpdateFileIdentity(path, 'unsafe_journal');
1189
1277
  journalHandle = await open(path, constants.O_RDONLY | noFollowFlag());
1190
1278
  }
1191
1279
  catch (error) {
1192
- if (isErrno(error, 'ENOENT'))
1280
+ if (isErrno(error, 'ENOENT') && !identity)
1193
1281
  return undefined;
1282
+ if (isErrno(error, 'ENOENT') || isErrno(error, 'ELOOP')) {
1283
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, 'unsafe_journal', { cause: error });
1284
+ }
1194
1285
  throw error;
1195
1286
  }
1196
1287
  try {
1288
+ assetstore.assertOpenedRegularAssetFile(journalHandle.fd, path, identity);
1197
1289
  const info = await journalHandle.stat({ bigint: true });
1198
- const currentPathInfo = await selfUpdateFileMetadata(path);
1199
- if (!info.isFile()
1200
- || currentPathInfo.isSymbolicLink()
1201
- || !currentPathInfo.isFile()
1202
- || currentPathInfo.dev !== info.dev
1203
- || currentPathInfo.ino !== info.ino
1204
- || info.size > BigInt(MAX_JOURNAL_BYTES)) {
1290
+ if (info.size > BigInt(MAX_JOURNAL_BYTES)) {
1291
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, 'unsafe_journal');
1292
+ }
1293
+ const bytes = await readBoundedFile(journalHandle, MAX_JOURNAL_BYTES);
1294
+ assetstore.assertOpenedRegularAssetFile(journalHandle.fd, path, identity);
1295
+ if (bytes.byteLength > MAX_JOURNAL_BYTES) {
1205
1296
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, 'unsafe_journal');
1206
1297
  }
1207
- const parsed = JSON.parse(await journalHandle.readFile('utf8'));
1298
+ const parsed = JSON.parse(bytes.toString('utf8'));
1208
1299
  if (!isJournal(parsed))
1209
1300
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.RECOVERY_REQUIRED, 'invalid_journal');
1210
1301
  return parsed;
1211
1302
  }
1303
+ catch (error) {
1304
+ if (isUnsafeAssetFileIdentity(error)) {
1305
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, 'unsafe_journal', { cause: error });
1306
+ }
1307
+ throw error;
1308
+ }
1212
1309
  finally {
1213
1310
  await journalHandle.close().catch(() => { });
1214
1311
  }
@@ -1378,17 +1475,17 @@ async function readLockGeneration(path) {
1378
1475
  async function readLockOwner(path) {
1379
1476
  let handle;
1380
1477
  try {
1381
- const before = await selfUpdateFileMetadata(path);
1382
- if (before.isSymbolicLink() || !before.isFile() || before.size > 4096n)
1478
+ const before = await lstat(path);
1479
+ if (before.isSymbolicLink() || !before.isFile() || before.size > 4_096)
1383
1480
  return undefined;
1481
+ const identity = assetstore.captureRegularAssetFileIdentity(path);
1384
1482
  handle = await open(path, constants.O_RDONLY | noFollowFlag());
1483
+ assetstore.assertOpenedRegularAssetFile(handle.fd, path, identity);
1385
1484
  const opened = await handle.stat({ bigint: true });
1386
- if (!opened.isFile()
1387
- || opened.size > 4096n
1388
- || opened.dev !== before.dev
1389
- || opened.ino !== before.ino)
1485
+ if (opened.size > 4096n)
1390
1486
  return undefined;
1391
- const bytes = await handle.readFile();
1487
+ const bytes = await readBoundedFile(handle, 4_096);
1488
+ assetstore.assertOpenedRegularAssetFile(handle.fd, path, identity);
1392
1489
  if (bytes.byteLength > 4_096)
1393
1490
  return undefined;
1394
1491
  const parsed = JSON.parse(bytes.toString('utf8'));
@@ -1404,7 +1501,8 @@ async function readLockOwner(path) {
1404
1501
  : undefined;
1405
1502
  }
1406
1503
  catch (error) {
1407
- if (isErrno(error, 'ENOENT') || isErrno(error, 'ELOOP') || error instanceof SyntaxError)
1504
+ if (isUnsafeAssetFileIdentity(error)
1505
+ || isErrno(error, 'ENOENT') || isErrno(error, 'ELOOP') || error instanceof SyntaxError)
1408
1506
  return undefined;
1409
1507
  throw error;
1410
1508
  }
@@ -1451,8 +1549,9 @@ function processAlive(pid) {
1451
1549
  }
1452
1550
  }
1453
1551
  async function assertSameFileIdentity(path, expected) {
1454
- const current = await assertRegularNonSymlink(path, 'target');
1455
- if (Number(current.dev) !== Number(expected.dev) || Number(current.ino) !== Number(expected.ino)) {
1552
+ await assertRegularNonSymlink(path, 'target');
1553
+ const current = captureSelfUpdateFileIdentity(path, 'target_changed_during_update');
1554
+ if (!sameNativeFileIdentity(current, expected)) {
1456
1555
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.UNSAFE_UPDATE_PATH, 'target_changed_during_update');
1457
1556
  }
1458
1557
  }
@@ -3,6 +3,7 @@ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
3
3
  import { constants } from 'node:fs';
4
4
  import { link, lstat, mkdir, open, realpath, rename, rm, } from 'node:fs/promises';
5
5
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, win32 } from 'node:path';
6
+ import { assetstore, util } from '@evomap/evolver-core';
6
7
  import { SELF_UPDATE_FAILURE_CODES, SelfUpdateFailureError, selfUpdateFailure, } from './failureCodes.js';
7
8
  import { selfUpdateFileMetadata } from './fileMetadata.js';
8
9
  export const WINDOWS_UPDATER_WORKER_ARG = '--evolver-windows-updater-worker';
@@ -330,12 +331,12 @@ async function readWorkItem(workItemPath) {
330
331
  const handle = await openNoFollow(workItemPath, constants.O_RDONLY);
331
332
  try {
332
333
  const opened = await handle.stat({ bigint: true });
333
- if (!sameStatIdentity(opened, snapshot)) {
334
+ if (!sameStatIdentity(opened, snapshot, handle.fd)) {
334
335
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED, 'windows_updater_pending_changed');
335
336
  }
336
337
  const raw = await handle.readFile({ encoding: 'utf8' });
337
338
  const after = await handle.stat({ bigint: true });
338
- if (!sameStatIdentity(after, snapshot)) {
339
+ if (!sameStatIdentity(after, snapshot, handle.fd)) {
339
340
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED, 'windows_updater_pending_changed');
340
341
  }
341
342
  return parseWorkItem(JSON.parse(raw));
@@ -399,6 +400,22 @@ function parseIdentity(value) {
399
400
  assertSha256(identity.sha256, 'identity_sha256');
400
401
  return identity;
401
402
  }
403
+ function captureUpdaterFileIdentity(path, label) {
404
+ try {
405
+ return assetstore.captureRegularAssetFileIdentity(path);
406
+ }
407
+ catch (error) {
408
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED, `windows_updater_${label}`, { cause: error });
409
+ }
410
+ }
411
+ function assertUpdaterFileIdentity(fd, path, expected, label, access = 'read') {
412
+ try {
413
+ assetstore.assertOpenedRegularAssetFile(fd, path, expected, access);
414
+ }
415
+ catch (error) {
416
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED, `windows_updater_${label}`, { cause: error });
417
+ }
418
+ }
402
419
  async function snapshotRegularFile(path, label, maxBytes) {
403
420
  const cleanPath = assertAbsoluteCleanPath(path, label);
404
421
  const before = await selfUpdateFileMetadata(cleanPath).catch((error) => {
@@ -412,14 +429,25 @@ async function snapshotRegularFile(path, label, maxBytes) {
412
429
  if (maxBytes !== undefined && before.size > BigInt(maxBytes)) {
413
430
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED, `windows_updater_${label}_too_large`);
414
431
  }
432
+ const identity = captureUpdaterFileIdentity(cleanPath, `${label}_opened`);
415
433
  const handle = await openNoFollow(cleanPath, constants.O_RDONLY);
416
434
  try {
435
+ assertUpdaterFileIdentity(handle.fd, cleanPath, identity, `${label}_opened`);
417
436
  const opened = await handle.stat({ bigint: true });
418
- assertStatIdentity(before, opened, `${label}_opened`);
437
+ assertOpenedStatIdentity(before, opened, `${label}_opened`, cleanPath, handle.fd);
419
438
  const digest = await hashHandle(handle, maxBytes);
420
439
  const after = await handle.stat({ bigint: true });
421
440
  assertStatIdentity(opened, after, `${label}_changed`);
422
- return identityFromStat(after, digest);
441
+ const currentPathInfo = await lstat(cleanPath, { bigint: true });
442
+ if (!currentPathInfo.isFile() || currentPathInfo.isSymbolicLink()) {
443
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED, `windows_updater_${label}_changed`);
444
+ }
445
+ assertOpenedStatIdentity(currentPathInfo, after, `${label}_changed`, cleanPath, handle.fd);
446
+ assertUpdaterFileIdentity(handle.fd, cleanPath, identity, `${label}_changed`);
447
+ const snapshot = identityFromStat(after, digest);
448
+ if (process.platform === 'win32' && after.dev === 0n)
449
+ snapshot.dev = util.readWindowsDescriptorIdentity(handle.fd).dev.toString();
450
+ return snapshot;
423
451
  }
424
452
  finally {
425
453
  await handle.close();
@@ -438,15 +466,26 @@ async function assertHelperLaunchSnapshot(path, expected) {
438
466
  }
439
467
  }
440
468
  async function copyRegularFileExclusive(sourcePath, destinationPath, expectedSource, mode) {
469
+ const sourceIdentity = captureUpdaterFileIdentity(sourcePath, 'source_changed');
441
470
  const source = await openNoFollow(sourcePath, constants.O_RDONLY);
442
471
  let destination;
472
+ let destinationIdentity;
443
473
  let operationError;
444
474
  try {
475
+ assertUpdaterFileIdentity(source.fd, sourcePath, sourceIdentity, 'source_changed');
445
476
  const openedSource = await source.stat({ bigint: true });
446
- if (!sameStatIdentity(openedSource, expectedSource)) {
477
+ if (!sameStatIdentity(openedSource, expectedSource, source.fd)) {
447
478
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED, 'windows_updater_source_changed');
448
479
  }
449
- destination = await open(destinationPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, mode);
480
+ destination = await open(destinationPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), mode);
481
+ const openedDestination = await destination.stat({ bigint: true });
482
+ if (!openedDestination.isFile()) {
483
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED, 'windows_updater_destination_not_regular');
484
+ }
485
+ destinationIdentity = {
486
+ dev: openedDestination.dev, ino: openedDestination.ino, birthtimeNs: openedDestination.birthtimeNs,
487
+ };
488
+ assertUpdaterFileIdentity(destination.fd, destinationPath, destinationIdentity, 'destination_changed', 'write');
450
489
  const hash = createHash('sha256');
451
490
  const buffer = Buffer.allocUnsafe(COPY_BUFFER_BYTES);
452
491
  let position = 0;
@@ -463,10 +502,12 @@ async function copyRegularFileExclusive(sourcePath, destinationPath, expectedSou
463
502
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED, 'windows_updater_source_digest_changed');
464
503
  }
465
504
  const afterSource = await source.stat({ bigint: true });
466
- if (!sameStatIdentity(afterSource, expectedSource)) {
505
+ if (!sameStatIdentity(afterSource, expectedSource, source.fd)) {
467
506
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED, 'windows_updater_source_changed');
468
507
  }
508
+ assertUpdaterFileIdentity(source.fd, sourcePath, sourceIdentity, 'source_changed');
469
509
  await destination.sync();
510
+ assertUpdaterFileIdentity(destination.fd, destinationPath, destinationIdentity, 'destination_changed', 'write');
470
511
  }
471
512
  catch (error) {
472
513
  operationError = error;
@@ -481,7 +522,16 @@ async function copyRegularFileExclusive(sourcePath, destinationPath, expectedSou
481
522
  }
482
523
  }
483
524
  if (operationError !== undefined) {
484
- await removeBestEffort(destinationPath);
525
+ if (destinationIdentity) {
526
+ try {
527
+ const current = assetstore.captureRegularAssetFileIdentity(destinationPath, 'write');
528
+ if (current.dev === destinationIdentity.dev && current.ino === destinationIdentity.ino
529
+ && current.birthtimeNs === destinationIdentity.birthtimeNs) {
530
+ await removeBestEffort(destinationPath);
531
+ }
532
+ }
533
+ catch { /* Never remove an unverified or replaced destination. */ }
534
+ }
485
535
  throw operationError;
486
536
  }
487
537
  }
@@ -732,6 +782,15 @@ function assertAbsoluteCleanPath(path, label) {
732
782
  }
733
783
  return cleanPath;
734
784
  }
785
+ function assertOpenedStatIdentity(named, opened, label, path, fd) {
786
+ if (process.platform === 'win32' && named.dev === 0n && !util.sameWindowsOpenedPathIdentity(path, opened, fd)) {
787
+ throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED, `windows_updater_${label}`);
788
+ }
789
+ // Only a native-proven path-vs-handle mapping differs; persisted and handle identities stay strict.
790
+ const mapped = process.platform === 'win32' && named.dev === 0n
791
+ ? { ...named, dev: opened.dev } : named;
792
+ assertStatIdentity(mapped, opened, label);
793
+ }
735
794
  function assertStatIdentity(left, right, label) {
736
795
  if (left.dev !== right.dev
737
796
  || left.ino !== right.ino
@@ -752,8 +811,9 @@ function assertDirectoryIdentity(left, right, label) {
752
811
  throw selfUpdateFailure(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED, `windows_updater_${label}`);
753
812
  }
754
813
  }
755
- function sameStatIdentity(stat, identity) {
756
- const strictLegacyIdentity = stat.dev.toString() === identity.dev
814
+ function sameStatIdentity(stat, identity, fd) {
815
+ const native = process.platform === 'win32' && stat.dev === 0n ? util.readWindowsDescriptorIdentity(fd) : stat;
816
+ const strictLegacyIdentity = native.ino === stat.ino && native.dev.toString() === identity.dev
757
817
  && stat.ino.toString() === identity.ino
758
818
  && stat.size.toString() === identity.size
759
819
  && stat.mtimeNs.toString() === identity.mtime_ns