@openclaw/fs-safe 0.19.0 → 0.21.0

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 (142) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +24 -6
  3. package/dist/advanced.d.ts +4 -0
  4. package/dist/advanced.js +2 -0
  5. package/dist/archive-plan.d.ts +2 -7
  6. package/dist/archive-read.js +9 -18
  7. package/dist/archive-zip-entry.d.ts +11 -11
  8. package/dist/archive-zip-entry.js +3 -35
  9. package/dist/archive-zip-integrity.d.ts +2 -2
  10. package/dist/archive-zip-integrity.js +2 -12
  11. package/dist/archive-zip-loader.d.ts +7 -3
  12. package/dist/archive-zip-loader.js +10 -9
  13. package/dist/archive-zip-preflight.d.ts +2 -1
  14. package/dist/archive-zip-preflight.js +16 -7
  15. package/dist/archive.js +17 -16
  16. package/dist/atomic.d.ts +1 -1
  17. package/dist/directory-receipt.js +5 -7
  18. package/dist/effective-uid.js +1 -4
  19. package/dist/errors.d.ts +3 -1
  20. package/dist/errors.js +3 -2
  21. package/dist/file-lock-sync-root-held.js +1 -4
  22. package/dist/file-store.d.ts +4 -7
  23. package/dist/json-document-store.d.ts +4 -9
  24. package/dist/local-file-access.js +2 -5
  25. package/dist/move-path-cleanup.js +4 -4
  26. package/dist/native-binding.d.ts +28 -1
  27. package/dist/native-staged-symlink.d.ts +13 -0
  28. package/dist/native-staged-symlink.js +303 -0
  29. package/dist/owner-dacl-batch-worker.d.ts +1 -0
  30. package/dist/owner-dacl-batch-worker.js +54 -0
  31. package/dist/owner-dacl-batch.d.ts +5 -0
  32. package/dist/owner-dacl-batch.js +64 -0
  33. package/dist/owner-dacl.d.ts +2 -0
  34. package/dist/owner-dacl.js +3 -0
  35. package/dist/path.js +17 -1
  36. package/dist/permission-exec.js +3 -6
  37. package/dist/permissions-public.d.ts +1 -0
  38. package/dist/permissions-public.js +1 -0
  39. package/dist/pinned-mutation-admission.d.ts +0 -1
  40. package/dist/pinned-open.d.ts +0 -1
  41. package/dist/pinned-open.js +1 -2
  42. package/dist/publish-copy-stage.js +4 -0
  43. package/dist/read-opened-file.d.ts +2 -5
  44. package/dist/regular-file.js +3 -3
  45. package/dist/replace-file-buffer.d.ts +4 -0
  46. package/dist/replace-file-buffer.js +36 -0
  47. package/dist/replace-file-copy-fallback.d.ts +3 -2
  48. package/dist/replace-file-copy-fallback.js +66 -38
  49. package/dist/replace-file-descriptor.d.ts +4 -0
  50. package/dist/replace-file-descriptor.js +9 -1
  51. package/dist/replace-file-destination.d.ts +17 -0
  52. package/dist/replace-file-destination.js +61 -0
  53. package/dist/replace-file-mutation.d.ts +26 -0
  54. package/dist/replace-file-mutation.js +47 -0
  55. package/dist/replace-file-temp-owner.d.ts +2 -2
  56. package/dist/replace-file-temp-owner.js +16 -4
  57. package/dist/replace-file-types.d.ts +55 -0
  58. package/dist/replace-file-types.js +1 -0
  59. package/dist/replace-file.d.ts +3 -55
  60. package/dist/replace-file.js +29 -10
  61. package/dist/retained-file-types.d.ts +61 -0
  62. package/dist/retained-file-types.js +1 -0
  63. package/dist/retained-file.d.ts +3 -0
  64. package/dist/retained-file.js +121 -0
  65. package/dist/root-directory-entry.d.ts +9 -0
  66. package/dist/root-directory-entry.js +28 -0
  67. package/dist/root-directory-list.d.ts +7 -1
  68. package/dist/root-directory-list.js +48 -23
  69. package/dist/root-handle-context.d.ts +4 -0
  70. package/dist/root-handle-context.js +12 -0
  71. package/dist/root-impl.d.ts +3 -3
  72. package/dist/root-impl.js +8 -5
  73. package/dist/root-observed-path.d.ts +0 -1
  74. package/dist/root-observed-path.js +0 -3
  75. package/dist/root-path-observation.d.ts +4 -11
  76. package/dist/root-path.js +7 -10
  77. package/dist/root-walk.d.ts +19 -12
  78. package/dist/root-walk.js +49 -18
  79. package/dist/root-write-admission.js +0 -2
  80. package/dist/safe-path-segment.d.ts +1 -0
  81. package/dist/safe-path-segment.js +8 -2
  82. package/dist/secure-file.js +3 -2
  83. package/dist/sidecar-lock.js +5 -3
  84. package/dist/staged-symlink-types.d.ts +49 -0
  85. package/dist/staged-symlink-types.js +1 -0
  86. package/dist/symlink-parents.js +58 -7
  87. package/dist/temp-target.js +5 -2
  88. package/dist/temp-workspace-admission.js +22 -21
  89. package/dist/temp-workspace-child-admission.d.ts +1 -1
  90. package/dist/temp-workspace-child-admission.js +14 -9
  91. package/dist/temp-workspace-owner.js +4 -9
  92. package/dist/temp-workspace-ownership.d.ts +8 -0
  93. package/dist/temp-workspace-ownership.js +52 -0
  94. package/dist/test-hooks.d.ts +3 -0
  95. package/dist/text-atomic.d.ts +2 -1
  96. package/dist/text-atomic.js +2 -0
  97. package/dist/trash.js +27 -1
  98. package/dist/walk.d.ts +2 -5
  99. package/dist/watch-alias.d.ts +6 -0
  100. package/dist/watch-alias.js +80 -0
  101. package/dist/watch-hints.d.ts +8 -0
  102. package/dist/watch-hints.js +77 -0
  103. package/dist/watch-native.d.ts +32 -0
  104. package/dist/watch-native.js +56 -0
  105. package/dist/watch-scan.d.ts +24 -0
  106. package/dist/watch-scan.js +269 -0
  107. package/dist/watch-types.d.ts +58 -0
  108. package/dist/watch-types.js +1 -0
  109. package/dist/watch.d.ts +5 -0
  110. package/dist/watch.js +502 -0
  111. package/dist/windows-owner.d.ts +0 -1
  112. package/dist/windows-owner.js +0 -1
  113. package/dist/windows-security-bridge.cs +6 -4
  114. package/dist/windows-security-bridge.ps1 +78 -3
  115. package/dist/windows-security-command.d.ts +8 -0
  116. package/dist/windows-security-command.js +66 -12
  117. package/dist/windows-security-facts.d.ts +3 -0
  118. package/dist/windows-security-facts.js +4 -0
  119. package/docs/advanced.md +4 -2
  120. package/docs/archive.md +8 -0
  121. package/docs/atomic.md +72 -3
  122. package/docs/contributing.md +35 -0
  123. package/docs/durability.md +7 -0
  124. package/docs/index.md +1 -0
  125. package/docs/install.md +28 -0
  126. package/docs/native-helper.md +14 -4
  127. package/docs/native.md +45 -1
  128. package/docs/permissions.md +66 -0
  129. package/docs/public-api.md +7 -1
  130. package/docs/retained-file.md +113 -0
  131. package/docs/root.md +6 -1
  132. package/docs/security-model.md +4 -1
  133. package/docs/sidecar-lock.md +2 -0
  134. package/docs/staged-symlink.md +123 -0
  135. package/docs/store.md +3 -1
  136. package/docs/temp.md +24 -4
  137. package/docs/testing.md +88 -0
  138. package/docs/types.md +6 -0
  139. package/docs/walk.md +22 -1
  140. package/docs/watch.md +184 -0
  141. package/docs/writing.md +10 -0
  142. package/package.json +13 -9
@@ -58,14 +58,11 @@ function dataProperty(value, name) {
58
58
  }
59
59
  return undefined;
60
60
  }
61
- function caughtPrimitiveDisplay(value) {
62
- if (value !== null && (typeof value === "object" || typeof value === "function"))
63
- return undefined;
64
- return primitiveString(value);
65
- }
66
61
  /** Formats only caught permission-query failures without invoking user code. */
67
62
  export function formatCaughtPermissionFailure(error) {
68
- const primitive = caughtPrimitiveDisplay(error);
63
+ const primitive = error !== null && (typeof error === "object" || typeof error === "function")
64
+ ? undefined
65
+ : primitiveString(error);
69
66
  if (primitive !== undefined)
70
67
  return formatBoundedCaughtDetail(primitive);
71
68
  if (!isInspectableCaughtObject(error)) {
@@ -2,3 +2,4 @@ export { formatOctal, formatPermissionDetail, formatPermissionRemediation, inspe
2
2
  export type { PermissionCommandFailure } from "./permission-exec.js";
3
3
  export { createPrivateDirectory, type CreatePrivateDirectoryOptions, } from "./private-directory.js";
4
4
  export { readOwnerAndDacl, type OwnerAndDaclResult, type WindowsAccessControlEntry, type WindowsAceFlags, } from "./owner-dacl.js";
5
+ export { readOwnerAndDaclBatch } from "./owner-dacl-batch.js";
@@ -1,3 +1,4 @@
1
1
  export { formatOctal, formatPermissionDetail, formatPermissionRemediation, inspectPathPermissions, isGroupReadable, isGroupWritable, isWorldReadable, isWorldWritable, modeBits, safeStat, } from "./permissions.js";
2
2
  export { createPrivateDirectory, } from "./private-directory.js";
3
3
  export { readOwnerAndDacl, } from "./owner-dacl.js";
4
+ export { readOwnerAndDaclBatch } from "./owner-dacl-batch.js";
@@ -9,7 +9,6 @@ export type PinnedMutationPolicySnapshot = Readonly<{
9
9
  export declare function snapshotPinnedMutationPolicy(denyMutations: DenyMutationPolicy | undefined, mutationSymlinks: MutationSymlinkPolicy | undefined): PinnedMutationPolicySnapshot | undefined;
10
10
  export declare function preparePinnedWriteMutationAdmission(params: {
11
11
  rootReal: string;
12
- rootWithSep: string;
13
12
  rootIdentity?: RootBoundaryIdentity;
14
13
  resolvedTargetPath: string;
15
14
  defaultRelativeParentPath: string;
@@ -14,7 +14,6 @@ export type PinnedOpenSyncResult = {
14
14
  export type PinnedOpenSyncAllowedType = "file" | "directory";
15
15
  export type PinnedOpenSyncFinalAdmission = (params: {
16
16
  path: string;
17
- preRealpathIdentity: fs.BigIntStats;
18
17
  descriptorIdentity: fs.BigIntStats;
19
18
  }) => string;
20
19
  export type PinnedOpenSyncFs = Pick<typeof fs, "constants" | "lstatSync" | "realpathSync" | "openSync" | "fstatSync" | "closeSync">;
@@ -53,14 +53,13 @@ export function openPinnedFileSync(params) {
53
53
  assertAllowedStat(stat, allowedType, statPolicy);
54
54
  return stat;
55
55
  }, preOpenStat);
56
- const pathIdentity = inspectFileIdentitySync(() => {
56
+ inspectFileIdentitySync(() => {
57
57
  const stat = ioFs.lstatSync(realPath, { bigint: true });
58
58
  assertAllowedStat(stat, allowedType, statPolicy);
59
59
  return stat;
60
60
  }, identity);
61
61
  const admittedPath = params.finalAdmission?.({
62
62
  path: realPath,
63
- preRealpathIdentity: pathIdentity,
64
63
  descriptorIdentity: identity,
65
64
  }) ?? realPath;
66
65
  const opened = { ok: true, path: admittedPath, fd, stat: openedStat, identity };
@@ -22,6 +22,10 @@ export function publishCopyStage(params) {
22
22
  // Caller authority checks can synchronously replace a parent or staged entry.
23
23
  if (params.assertBeforeMutation)
24
24
  assertCurrent();
25
+ // An observed collision needs no dispatch; errno after a link attempt remains ambiguous.
26
+ if (fs.lstatSync(targetPath, { throwIfNoEntry: false })) {
27
+ throw new FsSafeError("already-exists", "destination already exists");
28
+ }
25
29
  params.onPublicationAttempt?.();
26
30
  fs.linkSync(temporaryPath, targetPath);
27
31
  let observerRejected = false;
@@ -7,12 +7,9 @@ export type ReadResult = {
7
7
  realPath: string;
8
8
  stat: Stats;
9
9
  };
10
- type OpenedFile = {
10
+ type OpenedFile = Omit<ReadResult & {
11
11
  handle: FileHandle;
12
- containment: ContainmentGuarantee;
13
- realPath: string;
14
- stat: Stats;
15
- };
12
+ }, "buffer">;
16
13
  export declare function readOpenedFileSafely(params: {
17
14
  opened: OpenedFile;
18
15
  maxBytes?: number;
@@ -208,10 +208,10 @@ function inspectAppendPath(filePath) {
208
208
  }
209
209
  function prepareRegularAppend(filePath, rejectSymlinkParents) {
210
210
  if (rejectSymlinkParents === true) {
211
- const resolvedDir = resolvePathPreservingWindowsRoot(path.dirname(filePath));
211
+ const unresolvedDir = path.dirname(filePath);
212
212
  assertNoSymlinkParentsSync({
213
- rootDir: path.parse(resolvedDir).root,
214
- targetPath: resolvedDir,
213
+ rootDir: path.parse(resolvePathPreservingWindowsRoot(unresolvedDir)).root,
214
+ targetPath: unresolvedDir,
215
215
  allowMissing: false,
216
216
  allowRootChildSymlink: true,
217
217
  requireDirectories: true,
@@ -0,0 +1,4 @@
1
+ import type syncFs from "node:fs";
2
+ import type { FileHandle } from "node:fs/promises";
3
+ export declare function writeAtomicDestination(handle: FileHandle, data: Buffer, beforeWrite?: () => Promise<void>, assertBeforeMutation?: () => void, onWriting?: () => void): Promise<void>;
4
+ export declare function writeAtomicDestinationSync(fsModule: Pick<typeof syncFs, "ftruncateSync" | "writeSync">, fd: number, data: Buffer, beforeWrite?: () => void, onWriting?: () => void): void;
@@ -0,0 +1,36 @@
1
+ export async function writeAtomicDestination(handle, data, beforeWrite, assertBeforeMutation, onWriting) {
2
+ if (beforeWrite)
3
+ await beforeWrite();
4
+ assertBeforeMutation?.();
5
+ await handle.truncate(0);
6
+ onWriting?.();
7
+ let written = 0;
8
+ while (written < data.length) {
9
+ if (beforeWrite)
10
+ await beforeWrite();
11
+ assertBeforeMutation?.();
12
+ const result = await handle.write(data, written, data.length - written, written);
13
+ if (result.bytesWritten === 0)
14
+ throw new Error("Copy fallback write made no progress");
15
+ written += result.bytesWritten;
16
+ }
17
+ if (beforeWrite)
18
+ await beforeWrite();
19
+ assertBeforeMutation?.();
20
+ await handle.truncate(data.length);
21
+ }
22
+ export function writeAtomicDestinationSync(fsModule, fd, data, beforeWrite, onWriting) {
23
+ beforeWrite?.();
24
+ fsModule.ftruncateSync(fd, 0);
25
+ onWriting?.();
26
+ let written = 0;
27
+ while (written < data.length) {
28
+ beforeWrite?.();
29
+ const bytesWritten = fsModule.writeSync(fd, data, written, data.length - written, written);
30
+ if (bytesWritten === 0)
31
+ throw new Error("Copy fallback write made no progress");
32
+ written += bytesWritten;
33
+ }
34
+ beforeWrite?.();
35
+ fsModule.ftruncateSync(fd, data.length);
36
+ }
@@ -1,4 +1,5 @@
1
1
  import syncFs, { type BigIntStats } from "node:fs";
2
+ import { AtomicMutation } from "./replace-file-mutation.js";
2
3
  export type ReplaceFileDestinationHardlinkPolicy = "reject";
3
4
  export type ReplaceFileCopyFallbackRestorePolicy = "restore-original" | "none";
4
5
  export type ReplaceFileAtomicRestoreCleanup = "restored" | "restore-failed";
@@ -9,9 +10,8 @@ type AsyncFallbackFs = {
9
10
  lstat: typeof import("node:fs/promises").lstat;
10
11
  open: typeof import("node:fs/promises").open;
11
12
  rm: typeof import("node:fs/promises").rm;
12
- unlink: typeof import("node:fs/promises").unlink;
13
13
  };
14
- type SyncFallbackFs = Pick<typeof syncFs, "closeSync" | "fstatSync" | "fsyncSync" | "ftruncateSync" | "lstatSync" | "openSync" | "readSync" | "rmSync" | "unlinkSync" | "writeSync">;
14
+ type SyncFallbackFs = Pick<typeof syncFs, "closeSync" | "fstatSync" | "fsyncSync" | "ftruncateSync" | "lstatSync" | "openSync" | "readSync" | "rmSync" | "writeSync">;
15
15
  export declare function assertDestinationHardlinkPolicy(fsModule: AsyncFallbackFs, dest: string, policy?: ReplaceFileDestinationHardlinkPolicy): Promise<void>;
16
16
  export declare function assertDestinationHardlinkPolicySync(fsModule: SyncFallbackFs, dest: string, policy?: ReplaceFileDestinationHardlinkPolicy): void;
17
17
  export declare function copyFallbackReplace(params: {
@@ -23,6 +23,7 @@ export declare function copyFallbackReplace(params: {
23
23
  maxRestoreBytes?: number;
24
24
  expectedSourceIdentity?: BigIntStats;
25
25
  sync: boolean;
26
+ mutation?: AtomicMutation;
26
27
  }): Promise<void>;
27
28
  export declare function copyFallbackReplaceSync(params: Omit<Parameters<typeof copyFallbackReplace>[0], "fsModule"> & {
28
29
  fsModule: SyncFallbackFs;
@@ -6,6 +6,9 @@ import { inspectFileIdentity, inspectFileIdentitySync } from "./strict-file-iden
6
6
  import { readOwnedCopySource, readOwnedCopySourceSync } from "./replace-file-copy-source.js";
7
7
  import { resolveReadOpenFlags } from "./read-open-flags.js";
8
8
  import { hasErrorCode } from "./file-cleanup.js";
9
+ import { writeAtomicDestination, writeAtomicDestinationSync } from "./replace-file-buffer.js";
10
+ import { AtomicMutation } from "./replace-file-mutation.js";
11
+ import { captureAtomicDestination, captureAtomicDestinationSync } from "./replace-file-destination.js";
9
12
  const SUPPORTS_NOFOLLOW = process.platform !== "win32" && "O_NOFOLLOW" in syncFs.constants;
10
13
  const NOFOLLOW = SUPPORTS_NOFOLLOW ? syncFs.constants.O_NOFOLLOW : 0;
11
14
  const OPEN_READ_FLAGS = resolveReadOpenFlags();
@@ -44,7 +47,7 @@ function inspectPinnedDestinationSync(fsModule, fd, dest, admission, hardlinks)
44
47
  inspectFileIdentitySync(() => admitDestinationKind(fsModule.lstatSync(dest, { bigint: true }), opened, dest, admission), opened);
45
48
  assertDestinationLinks(opened, dest, admission, hardlinks);
46
49
  }
47
- async function openPinnedDestination(fsModule, dest, admission, hardlinks) {
50
+ async function openPinnedDestination(fsModule, dest, admission, hardlinks, mutation) {
48
51
  let preview;
49
52
  try {
50
53
  preview = fsModule === fs ? syncFs.lstatSync(dest) : await fsModule.lstat(dest);
@@ -61,6 +64,7 @@ async function openPinnedDestination(fsModule, dest, admission, hardlinks) {
61
64
  if (admission === "restore" && preview.isSymbolicLink()) {
62
65
  throw new FsSafeError("symlink", `Refusing copy fallback through symlink destination: ${dest}`);
63
66
  }
67
+ mutation?.assert();
64
68
  const handle = await fsModule.open(dest, admission === "restore" ? OPEN_READ_WRITE_FLAGS : OPEN_READ_FLAGS);
65
69
  try {
66
70
  if (fsModule === fs)
@@ -82,7 +86,7 @@ async function openPinnedDestination(fsModule, dest, admission, hardlinks) {
82
86
  throw error;
83
87
  }
84
88
  }
85
- function openPinnedDestinationSync(fsModule, dest, admission, hardlinks) {
89
+ function openPinnedDestinationSync(fsModule, dest, admission, hardlinks, mutation) {
86
90
  let preview;
87
91
  try {
88
92
  preview = fsModule.lstatSync(dest);
@@ -97,6 +101,7 @@ function openPinnedDestinationSync(fsModule, dest, admission, hardlinks) {
97
101
  if (admission === "restore" && preview.isSymbolicLink()) {
98
102
  throw new FsSafeError("symlink", `Refusing copy fallback through symlink destination: ${dest}`);
99
103
  }
104
+ mutation?.assert();
100
105
  const fd = fsModule.openSync(dest, admission === "restore" ? OPEN_READ_WRITE_FLAGS : OPEN_READ_FLAGS);
101
106
  try {
102
107
  inspectPinnedDestinationSync(fsModule, fd, dest, admission, hardlinks);
@@ -148,28 +153,6 @@ function readRestoreSnapshotSync(fsModule, fd, maxBytes, stat) {
148
153
  return bytesRead;
149
154
  }, restoreReadOptions(stat, maxBytes));
150
155
  }
151
- async function writeAll(handle, data) {
152
- await handle.truncate(0);
153
- let written = 0;
154
- while (written < data.length) {
155
- const result = await handle.write(data, written, data.length - written, written);
156
- if (result.bytesWritten === 0)
157
- throw new Error("Copy fallback write made no progress");
158
- written += result.bytesWritten;
159
- }
160
- await handle.truncate(data.length);
161
- }
162
- function writeAllSync(fsModule, fd, data) {
163
- fsModule.ftruncateSync(fd, 0);
164
- let written = 0;
165
- while (written < data.length) {
166
- const bytesWritten = fsModule.writeSync(fd, data, written, data.length - written, written);
167
- if (bytesWritten === 0)
168
- throw new Error("Copy fallback write made no progress");
169
- written += bytesWritten;
170
- }
171
- fsModule.ftruncateSync(fd, data.length);
172
- }
173
156
  function restoreFailure(writeError, cleanup, restoreError) {
174
157
  const primary = writeError instanceof Error ? writeError : new Error(String(writeError));
175
158
  const details = { cleanup };
@@ -180,23 +163,29 @@ function restoreFailure(writeError, cleanup, restoreError) {
180
163
  ? `Atomic copy fallback failed; original destination restored: ${primary.message}`
181
164
  : `Atomic copy fallback failed and original restoration failed: ${primary.message}`, { cause, details });
182
165
  }
183
- async function replacePinnedWithRestore(fsModule, handle, replacement, maxRestoreBytes, replacementMode) {
166
+ async function replacePinnedWithRestore(fsModule, handle, replacement, maxRestoreBytes, replacementMode, destination, mutation) {
184
167
  const originalStat = fsModule === fs ? syncFs.fstatSync(handle.fd) : await handle.stat();
185
168
  const originalMode = originalStat.mode;
186
169
  const original = await readRestoreSnapshot(handle, maxRestoreBytes, originalStat);
187
170
  try {
188
- await writeAll(handle, replacement);
171
+ await writeAtomicDestination(handle, replacement, destination?.beforeWrite, destination?.assertBeforeMutation, destination?.writing);
172
+ if (destination)
173
+ await destination.verify();
189
174
  await handle.chmod(replacementMode);
190
175
  await handle.sync();
191
176
  }
192
177
  catch (writeError) {
178
+ mutation.rethrowRefusal();
193
179
  try {
194
- await writeAll(handle, original);
180
+ await writeAtomicDestination(handle, original, destination?.beforeWrite, destination?.assertBeforeMutation, destination?.writing);
181
+ if (destination)
182
+ await destination.verify();
195
183
  await handle.chmod(originalMode);
196
184
  await handle.sync();
197
185
  throw restoreFailure(writeError, "restored");
198
186
  }
199
187
  catch (restoreError) {
188
+ mutation.rethrowRefusal();
200
189
  if (restoreError instanceof FsSafeError && restoreError.details?.cleanup === "restored") {
201
190
  throw restoreError;
202
191
  }
@@ -204,23 +193,27 @@ async function replacePinnedWithRestore(fsModule, handle, replacement, maxRestor
204
193
  }
205
194
  }
206
195
  }
207
- function replacePinnedWithRestoreSync(fsModule, fd, replacement, maxRestoreBytes, replacementMode, fchmodSync) {
196
+ function replacePinnedWithRestoreSync(fsModule, fd, replacement, maxRestoreBytes, replacementMode, fchmodSync, destination, mutation) {
208
197
  const originalStat = fsModule.fstatSync(fd);
209
198
  const originalMode = originalStat.mode;
210
199
  const original = readRestoreSnapshotSync(fsModule, fd, maxRestoreBytes, originalStat);
211
200
  try {
212
- writeAllSync(fsModule, fd, replacement);
201
+ writeAtomicDestinationSync(fsModule, fd, replacement, destination?.beforeWrite, destination?.writing);
202
+ destination?.verify();
213
203
  fchmodSync?.(fd, replacementMode);
214
204
  fsModule.fsyncSync(fd);
215
205
  }
216
206
  catch (writeError) {
207
+ mutation?.rethrowRefusal();
217
208
  try {
218
- writeAllSync(fsModule, fd, original);
209
+ writeAtomicDestinationSync(fsModule, fd, original, destination?.beforeWrite, destination?.writing);
210
+ destination?.verify();
219
211
  fchmodSync?.(fd, originalMode);
220
212
  fsModule.fsyncSync(fd);
221
213
  throw restoreFailure(writeError, "restored");
222
214
  }
223
215
  catch (restoreError) {
216
+ mutation?.rethrowRefusal();
224
217
  if (restoreError instanceof FsSafeError && restoreError.details?.cleanup === "restored") {
225
218
  throw restoreError;
226
219
  }
@@ -229,6 +222,7 @@ function replacePinnedWithRestoreSync(fsModule, fd, replacement, maxRestoreBytes
229
222
  }
230
223
  }
231
224
  export async function copyFallbackReplace(params) {
225
+ const mutation = params.mutation ?? new AtomicMutation({});
232
226
  const source = await readOwnedCopySource({
233
227
  fsModule: params.fsModule,
234
228
  src: params.src,
@@ -237,12 +231,16 @@ export async function copyFallbackReplace(params) {
237
231
  const { replacement } = source;
238
232
  let destHandle = null;
239
233
  let closeRequiredForSuccess = false;
234
+ let completed = false;
235
+ let destination;
240
236
  try {
241
237
  if (params.restore === "restore-original") {
242
- const pinned = await openPinnedDestination(params.fsModule, params.dest, "restore", params.destinationHardlinks);
238
+ const pinned = await openPinnedDestination(params.fsModule, params.dest, "restore", params.destinationHardlinks, mutation);
243
239
  if (pinned) {
244
240
  destHandle = pinned;
245
- await replacePinnedWithRestore(params.fsModule, destHandle, replacement, params.maxRestoreBytes, source.mode);
241
+ if (mutation.active)
242
+ destination = await captureAtomicDestination(params.fsModule, pinned, params.dest, mutation, params.destinationHardlinks === "reject");
243
+ await replacePinnedWithRestore(params.fsModule, destHandle, replacement, params.maxRestoreBytes, source.mode, destination, mutation);
246
244
  }
247
245
  }
248
246
  if (!destHandle) {
@@ -260,16 +258,31 @@ export async function copyFallbackReplace(params) {
260
258
  }
261
259
  if (destStat) {
262
260
  await assertDestinationHardlinkPolicy(params.fsModule, params.dest, params.destinationHardlinks);
261
+ mutation.assert();
263
262
  await params.fsModule.rm(params.dest, { force: true });
263
+ mutation.removed(params.dest);
264
264
  }
265
+ mutation.assert();
265
266
  destHandle = await params.fsModule.open(params.dest, OPEN_WRITE_EXCLUSIVE_FLAGS, source.mode & 0o777);
266
- await destHandle.writeFile(replacement);
267
+ if (mutation.active) {
268
+ destination = await captureAtomicDestination(params.fsModule, destHandle, params.dest, mutation, params.destinationHardlinks === "reject");
269
+ destination.writing();
270
+ await writeAtomicDestination(destHandle, replacement, destination.beforeWrite, destination.assertBeforeMutation);
271
+ await destination.verify();
272
+ }
273
+ else {
274
+ await destHandle.writeFile(replacement);
275
+ }
267
276
  await destHandle.chmod(source.mode);
268
277
  if (params.sync) {
269
278
  await destHandle.sync();
270
279
  }
271
280
  closeRequiredForSuccess = !params.sync;
272
281
  }
282
+ if (destination)
283
+ await destination.verify();
284
+ destination?.published();
285
+ completed = true;
273
286
  }
274
287
  finally {
275
288
  if (destHandle) {
@@ -277,7 +290,7 @@ export async function copyFallbackReplace(params) {
277
290
  await destHandle.close();
278
291
  }
279
292
  catch (closeError) {
280
- if (closeRequiredForSuccess) {
293
+ if (closeRequiredForSuccess && completed) {
281
294
  throw closeError;
282
295
  }
283
296
  }
@@ -285,6 +298,7 @@ export async function copyFallbackReplace(params) {
285
298
  }
286
299
  }
287
300
  export function copyFallbackReplaceSync(params) {
301
+ const mutation = params.mutation ?? new AtomicMutation({});
288
302
  const source = readOwnedCopySourceSync({
289
303
  fsModule: params.fsModule,
290
304
  src: params.src,
@@ -293,12 +307,16 @@ export function copyFallbackReplaceSync(params) {
293
307
  const { replacement } = source;
294
308
  let destFd;
295
309
  let closeRequiredForSuccess = false;
310
+ let completed = false;
311
+ let destination;
296
312
  try {
297
313
  if (params.restore === "restore-original") {
298
- const pinned = openPinnedDestinationSync(params.fsModule, params.dest, "restore", params.destinationHardlinks);
314
+ const pinned = openPinnedDestinationSync(params.fsModule, params.dest, "restore", params.destinationHardlinks, mutation);
299
315
  if (pinned !== null) {
300
316
  destFd = pinned;
301
- replacePinnedWithRestoreSync(params.fsModule, destFd, replacement, params.maxRestoreBytes, source.mode, params.fchmodSync);
317
+ if (mutation.active)
318
+ destination = captureAtomicDestinationSync(params.fsModule, pinned, params.dest, mutation, params.destinationHardlinks === "reject");
319
+ replacePinnedWithRestoreSync(params.fsModule, destFd, replacement, params.maxRestoreBytes, source.mode, params.fchmodSync, destination, mutation);
302
320
  }
303
321
  }
304
322
  if (destFd === undefined) {
@@ -315,16 +333,26 @@ export function copyFallbackReplaceSync(params) {
315
333
  }
316
334
  if (destStat) {
317
335
  assertDestinationHardlinkPolicySync(params.fsModule, params.dest, params.destinationHardlinks);
336
+ mutation.assert();
318
337
  params.fsModule.rmSync(params.dest, { force: true });
338
+ mutation.removed(params.dest);
319
339
  }
340
+ mutation.assert();
320
341
  destFd = params.fsModule.openSync(params.dest, OPEN_WRITE_EXCLUSIVE_FLAGS, source.mode & 0o777);
321
- writeAllSync(params.fsModule, destFd, replacement);
342
+ if (mutation.active)
343
+ destination = captureAtomicDestinationSync(params.fsModule, destFd, params.dest, mutation, params.destinationHardlinks === "reject");
344
+ destination?.writing();
345
+ writeAtomicDestinationSync(params.fsModule, destFd, replacement, destination?.beforeWrite);
346
+ destination?.verify();
322
347
  params.fchmodSync?.(destFd, source.mode);
323
348
  if (params.sync) {
324
349
  params.fsModule.fsyncSync(destFd);
325
350
  }
326
351
  closeRequiredForSuccess = !params.sync;
327
352
  }
353
+ destination?.verify();
354
+ destination?.published();
355
+ completed = true;
328
356
  }
329
357
  finally {
330
358
  if (destFd !== undefined) {
@@ -332,7 +360,7 @@ export function copyFallbackReplaceSync(params) {
332
360
  params.fsModule.closeSync(destFd);
333
361
  }
334
362
  catch (closeError) {
335
- if (closeRequiredForSuccess) {
363
+ if (closeRequiredForSuccess && completed) {
336
364
  throw closeError;
337
365
  }
338
366
  }
@@ -1,6 +1,7 @@
1
1
  import syncFs, { type BigIntStats } from "node:fs";
2
2
  import fs, { type FileHandle } from "node:fs/promises";
3
3
  import { type DirectoryModeOwner } from "./directory-mode-node.js";
4
+ import type { AtomicMutation } from "./replace-file-mutation.js";
4
5
  type AsyncTempFileSystem = Pick<typeof fs, "lstat" | "open" | "writeFile">;
5
6
  type SyncTempFileSystem = Pick<typeof syncFs, "closeSync" | "fstatSync" | "fsyncSync" | "lstatSync" | "openSync" | "writeFileSync">;
6
7
  export type SyncFchmod = (fd: number, mode: number) => void;
@@ -11,6 +12,7 @@ export declare function pinDirectoryForMode(params: {
11
12
  dirPath: string;
12
13
  /** Compatibility for best-effort directory modes; admission and close still fail closed. */
13
14
  ignoreChmodError?: boolean;
15
+ mutation?: AtomicMutation;
14
16
  }): Promise<DirectoryModeOwner | undefined>;
15
17
  export declare function applyDirectoryMode(params: Parameters<typeof pinDirectoryForMode>[0] & {
16
18
  mode: number;
@@ -20,6 +22,7 @@ export declare function applyDirectoryModeSync(params: {
20
22
  dirPath: string;
21
23
  mode: number;
22
24
  fchmodSync?: SyncFchmod;
25
+ mutation?: AtomicMutation;
23
26
  }): void;
24
27
  export declare function writeTempFile(params: {
25
28
  fsModule: AsyncTempFileSystem;
@@ -28,6 +31,7 @@ export declare function writeTempFile(params: {
28
31
  mode: number;
29
32
  sync: boolean;
30
33
  onIdentity?: (identity: BigIntStats) => void;
34
+ mutation?: AtomicMutation;
31
35
  }): Promise<{
32
36
  handle: FileHandle;
33
37
  identity: BigIntStats;
@@ -73,7 +73,10 @@ export async function pinDirectoryForMode(params) {
73
73
  : await inspectFileIdentity(async () => assertDirectory(await handle.stat({ bigint: true }), params.dirPath), expected);
74
74
  return Number(opened.mode & 4095n);
75
75
  },
76
- chmod: (mode) => handle.chmod(mode),
76
+ chmod: (mode) => {
77
+ params.mutation?.assert();
78
+ return handle.chmod(mode);
79
+ },
77
80
  close: () => handle.close(),
78
81
  ignoreChmodError: params.ignoreChmodError,
79
82
  });
@@ -103,6 +106,7 @@ export function applyDirectoryModeSync(params) {
103
106
  try {
104
107
  inspectFileIdentitySync(() => assertDirectory(params.fsModule.fstatSync(fd, { bigint: true }), params.dirPath), expected);
105
108
  // chmod ignores file-type bits; mask so raw stat modes are tolerated.
109
+ params.mutation?.assert();
106
110
  params.fchmodSync?.(fd, params.mode & 0o7777);
107
111
  }
108
112
  finally {
@@ -110,6 +114,7 @@ export function applyDirectoryModeSync(params) {
110
114
  }
111
115
  }
112
116
  export async function writeTempFile(params) {
117
+ params.mutation?.assert();
113
118
  const handle = await params.fsModule.open(params.tempPath, "wx", params.mode);
114
119
  try {
115
120
  // Custom adapters retain their async-only metadata contract.
@@ -117,6 +122,7 @@ export async function writeTempFile(params) {
117
122
  ? syncFs.fstatSync(handle.fd, { bigint: true }) : handle.stat({ bigint: true });
118
123
  const identity = await inspectFileIdentity(inspect);
119
124
  params.onIdentity?.(identity);
125
+ params.mutation?.assert();
120
126
  await params.fsModule.writeFile(handle, params.content);
121
127
  await handle.chmod(params.mode);
122
128
  if (params.sync) {
@@ -136,10 +142,12 @@ export async function writeTempFile(params) {
136
142
  }
137
143
  }
138
144
  export function writeTempFileSync(params) {
145
+ params.mutation?.assert();
139
146
  const fd = params.fsModule.openSync(params.tempPath, "wx", params.mode);
140
147
  try {
141
148
  const identity = inspectFileIdentitySync(() => params.fsModule.fstatSync(fd, { bigint: true }));
142
149
  params.onIdentity?.(identity);
150
+ params.mutation?.assert();
143
151
  params.fsModule.writeFileSync(fd, params.content);
144
152
  params.fchmodSync?.(fd, params.mode);
145
153
  if (params.sync) {
@@ -0,0 +1,17 @@
1
+ import fsSync from "node:fs";
2
+ import fs, { type FileHandle } from "node:fs/promises";
3
+ import type { AtomicMutation } from "./replace-file-mutation.js";
4
+ /** Borrow the writer's descriptor; never adopt an identity from a later pathname open. */
5
+ export declare function captureAtomicDestination(fsModule: Pick<typeof fs, "lstat">, handle: FileHandle, pathname: string, mutation: AtomicMutation, rejectHardlinks: boolean): Promise<{
6
+ verify: () => Promise<void>;
7
+ writing: () => void;
8
+ beforeWrite: () => Promise<void>;
9
+ assertBeforeMutation: () => void;
10
+ published: () => void;
11
+ }>;
12
+ export declare function captureAtomicDestinationSync(fsModule: Pick<typeof fsSync, "lstatSync" | "fstatSync">, fd: number, pathname: string, mutation: AtomicMutation, rejectHardlinks: boolean): {
13
+ verify: () => void;
14
+ writing: () => void;
15
+ beforeWrite: () => void;
16
+ published: () => void;
17
+ };
@@ -0,0 +1,61 @@
1
+ import fsSync, {} from "node:fs";
2
+ import fs, {} from "node:fs/promises";
3
+ import { FsSafeError } from "./errors.js";
4
+ import { inspectFileIdentity, inspectFileIdentitySync } from "./strict-file-identity.js";
5
+ function regular(stat, pathname, rejectHardlinks) {
6
+ if (stat.isSymbolicLink() || !stat.isFile()) {
7
+ throw new FsSafeError("path-mismatch", `Atomic replace destination changed: ${pathname}`);
8
+ }
9
+ if (rejectHardlinks && stat.nlink !== 1n) {
10
+ throw new FsSafeError("hardlink", `Hardlinked atomic replace destination not allowed: ${pathname}`);
11
+ }
12
+ return stat;
13
+ }
14
+ /** Borrow the writer's descriptor; never adopt an identity from a later pathname open. */
15
+ export async function captureAtomicDestination(fsModule, handle, pathname, mutation, rejectHardlinks) {
16
+ const inspect = () => fsModule === fs
17
+ ? fsSync.fstatSync(handle.fd, { bigint: true }) : handle.stat({ bigint: true });
18
+ const identity = await inspectFileIdentity(inspect);
19
+ regular(identity, pathname, rejectHardlinks);
20
+ const verify = async () => {
21
+ try {
22
+ await inspectFileIdentity(async () => regular(await inspect(), pathname, rejectHardlinks), identity);
23
+ await inspectFileIdentity(async () => regular(await fsModule.lstat(pathname, { bigint: true }), pathname, rejectHardlinks), identity);
24
+ }
25
+ catch (error) {
26
+ mutation.refuse(error);
27
+ }
28
+ };
29
+ return {
30
+ verify,
31
+ writing: () => mutation.destination("writing", pathname, identity),
32
+ beforeWrite: async () => {
33
+ mutation.assert();
34
+ await verify();
35
+ },
36
+ assertBeforeMutation: () => mutation.assert(),
37
+ published: () => mutation.destination("published", pathname, identity),
38
+ };
39
+ }
40
+ export function captureAtomicDestinationSync(fsModule, fd, pathname, mutation, rejectHardlinks) {
41
+ const identity = inspectFileIdentitySync(() => fsModule.fstatSync(fd, { bigint: true }));
42
+ regular(identity, pathname, rejectHardlinks);
43
+ const verify = () => {
44
+ try {
45
+ inspectFileIdentitySync(() => regular(fsModule.fstatSync(fd, { bigint: true }), pathname, rejectHardlinks), identity);
46
+ inspectFileIdentitySync(() => regular(fsModule.lstatSync(pathname, { bigint: true }), pathname, rejectHardlinks), identity);
47
+ }
48
+ catch (error) {
49
+ mutation.refuse(error);
50
+ }
51
+ };
52
+ return {
53
+ verify,
54
+ writing: () => mutation.destination("writing", pathname, identity),
55
+ beforeWrite: () => {
56
+ mutation.assert();
57
+ verify();
58
+ },
59
+ published: () => mutation.destination("published", pathname, identity),
60
+ };
61
+ }
@@ -0,0 +1,26 @@
1
+ import type { BigIntStats } from "node:fs";
2
+ export type ReplaceFileAtomicDestinationState = Readonly<{
3
+ state: "removed";
4
+ path: string;
5
+ }> | Readonly<{
6
+ state: "writing" | "published";
7
+ path: string;
8
+ dev: bigint;
9
+ ino: bigint;
10
+ }>;
11
+ export type AtomicMutationOptions = {
12
+ /** Recheck live authority before new effects; retained descriptor completion may settle. */
13
+ assertBeforeMutation?: () => void;
14
+ /** Retain observed destination facts even when later completion fails. */
15
+ onDestinationState?: (state: ReplaceFileAtomicDestinationState) => void;
16
+ };
17
+ export declare class AtomicMutation {
18
+ #private;
19
+ readonly active: boolean;
20
+ constructor(options: AtomicMutationOptions);
21
+ rethrowRefusal(): void;
22
+ refuse(error: unknown): never;
23
+ assert(): void;
24
+ destination(state: "writing" | "published", path: string, identity: BigIntStats): void;
25
+ removed(path: string): void;
26
+ }