@openclaw/matrix 2026.11.10-beta.3 → 2026.12.1-beta.1

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 (149) hide show
  1. package/node_modules/@openclaw/fs-safe/CHANGELOG.md +57 -0
  2. package/node_modules/@openclaw/fs-safe/README.md +6 -0
  3. package/node_modules/@openclaw/fs-safe/dist/archive-parser.wasm +0 -0
  4. package/node_modules/@openclaw/fs-safe/dist/atomic-io.d.ts +1 -0
  5. package/node_modules/@openclaw/fs-safe/dist/atomic-io.js +10 -0
  6. package/node_modules/@openclaw/fs-safe/dist/bounded-read.d.ts +1 -1
  7. package/node_modules/@openclaw/fs-safe/dist/bounded-read.js +15 -4
  8. package/node_modules/@openclaw/fs-safe/dist/directory-guard.js +11 -2
  9. package/node_modules/@openclaw/fs-safe/dist/drvfs-parent.d.ts +6 -0
  10. package/node_modules/@openclaw/fs-safe/dist/drvfs-parent.js +38 -0
  11. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-acquisition.d.ts +1 -1
  12. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-acquisition.js +2 -2
  13. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-acquire.js +13 -8
  14. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-io.js +13 -0
  15. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-mutation.d.ts +2 -2
  16. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-mutation.js +34 -24
  17. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-stale-admission.js +7 -2
  18. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync.js +20 -20
  19. package/node_modules/@openclaw/fs-safe/dist/file-observation.d.ts +13 -2
  20. package/node_modules/@openclaw/fs-safe/dist/file-observation.js +8 -4
  21. package/node_modules/@openclaw/fs-safe/dist/file-store-sync-write.d.ts +1 -0
  22. package/node_modules/@openclaw/fs-safe/dist/file-store-sync-write.js +11 -1
  23. package/node_modules/@openclaw/fs-safe/dist/file-store-write-options.d.ts +2 -0
  24. package/node_modules/@openclaw/fs-safe/dist/file-store-write-options.js +17 -0
  25. package/node_modules/@openclaw/fs-safe/dist/file-store.d.ts +2 -1
  26. package/node_modules/@openclaw/fs-safe/dist/file-store.js +12 -16
  27. package/node_modules/@openclaw/fs-safe/dist/guest-native-python.js +1 -1
  28. package/node_modules/@openclaw/fs-safe/dist/guest.js +3 -4
  29. package/node_modules/@openclaw/fs-safe/dist/json-document-store.d.ts +2 -0
  30. package/node_modules/@openclaw/fs-safe/dist/json-document-store.js +1 -0
  31. package/node_modules/@openclaw/fs-safe/dist/json-store.js +1 -0
  32. package/node_modules/@openclaw/fs-safe/dist/json.d.ts +5 -2
  33. package/node_modules/@openclaw/fs-safe/dist/json.js +6 -2
  34. package/node_modules/@openclaw/fs-safe/dist/local-file-descriptor.js +16 -10
  35. package/node_modules/@openclaw/fs-safe/dist/native-binding.d.ts +6 -0
  36. package/node_modules/@openclaw/fs-safe/dist/native-pinned-write.js +4 -0
  37. package/node_modules/@openclaw/fs-safe/dist/native-staged-file-metadata.d.ts +20 -0
  38. package/node_modules/@openclaw/fs-safe/dist/native-staged-file-metadata.js +18 -0
  39. package/node_modules/@openclaw/fs-safe/dist/native-staged-file.d.ts +3 -18
  40. package/node_modules/@openclaw/fs-safe/dist/native-staged-file.js +48 -24
  41. package/node_modules/@openclaw/fs-safe/dist/opened-file-failure.js +19 -7
  42. package/node_modules/@openclaw/fs-safe/dist/output.d.ts +1 -0
  43. package/node_modules/@openclaw/fs-safe/dist/output.js +3 -0
  44. package/node_modules/@openclaw/fs-safe/dist/path-policy.js +4 -1
  45. package/node_modules/@openclaw/fs-safe/dist/permissions-windows.js +35 -10
  46. package/node_modules/@openclaw/fs-safe/dist/pinned-open.d.ts +9 -2
  47. package/node_modules/@openclaw/fs-safe/dist/pinned-open.js +42 -23
  48. package/node_modules/@openclaw/fs-safe/dist/pinned-write-staged.js +85 -34
  49. package/node_modules/@openclaw/fs-safe/dist/pinned-write-types.d.ts +3 -0
  50. package/node_modules/@openclaw/fs-safe/dist/pinned-write.js +4 -0
  51. package/node_modules/@openclaw/fs-safe/dist/prepare-directory-mode.d.ts +1 -0
  52. package/node_modules/@openclaw/fs-safe/dist/prepare-directory-mode.js +1 -1
  53. package/node_modules/@openclaw/fs-safe/dist/private-temp-workspace.js +2 -2
  54. package/node_modules/@openclaw/fs-safe/dist/publication-recovery.d.ts +24 -0
  55. package/node_modules/@openclaw/fs-safe/dist/publication-recovery.js +151 -0
  56. package/node_modules/@openclaw/fs-safe/dist/publish-copy-stage.d.ts +1 -0
  57. package/node_modules/@openclaw/fs-safe/dist/publish-copy-stage.js +2 -1
  58. package/node_modules/@openclaw/fs-safe/dist/realpath.d.ts +1 -1
  59. package/node_modules/@openclaw/fs-safe/dist/realpath.js +22 -11
  60. package/node_modules/@openclaw/fs-safe/dist/replace-file-descriptor.d.ts +1 -0
  61. package/node_modules/@openclaw/fs-safe/dist/replace-file-descriptor.js +5 -0
  62. package/node_modules/@openclaw/fs-safe/dist/replace-file-temp-owner.d.ts +7 -0
  63. package/node_modules/@openclaw/fs-safe/dist/replace-file-temp-owner.js +75 -2
  64. package/node_modules/@openclaw/fs-safe/dist/replace-file-types.d.ts +2 -0
  65. package/node_modules/@openclaw/fs-safe/dist/replace-file.js +14 -10
  66. package/node_modules/@openclaw/fs-safe/dist/root-context.js +28 -12
  67. package/node_modules/@openclaw/fs-safe/dist/root-copy.js +1 -0
  68. package/node_modules/@openclaw/fs-safe/dist/root-create-input.js +2 -2
  69. package/node_modules/@openclaw/fs-safe/dist/root-file-final-admission.d.ts +4 -0
  70. package/node_modules/@openclaw/fs-safe/dist/root-file-final-admission.js +53 -36
  71. package/node_modules/@openclaw/fs-safe/dist/root-file-open-batch-sync.js +3 -1
  72. package/node_modules/@openclaw/fs-safe/dist/root-file.d.ts +2 -1
  73. package/node_modules/@openclaw/fs-safe/dist/root-file.js +24 -13
  74. package/node_modules/@openclaw/fs-safe/dist/root-impl.js +17 -1
  75. package/node_modules/@openclaw/fs-safe/dist/root-options.d.ts +4 -2
  76. package/node_modules/@openclaw/fs-safe/dist/root-path.d.ts +1 -1
  77. package/node_modules/@openclaw/fs-safe/dist/root-path.js +2 -1
  78. package/node_modules/@openclaw/fs-safe/dist/root-read-admission.js +31 -9
  79. package/node_modules/@openclaw/fs-safe/dist/root-write-admission.js +6 -2
  80. package/node_modules/@openclaw/fs-safe/dist/secret-file.d.ts +1 -0
  81. package/node_modules/@openclaw/fs-safe/dist/secret-file.js +2 -0
  82. package/node_modules/@openclaw/fs-safe/dist/sibling-staged-file.d.ts +1 -0
  83. package/node_modules/@openclaw/fs-safe/dist/sibling-staged-file.js +84 -4
  84. package/node_modules/@openclaw/fs-safe/dist/sibling-temp.d.ts +1 -0
  85. package/node_modules/@openclaw/fs-safe/dist/sibling-temp.js +2 -0
  86. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-acquire.js +22 -15
  87. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-publication.d.ts +22 -0
  88. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-publication.js +303 -0
  89. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-reclaim.d.ts +2 -0
  90. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-reclaim.js +9 -1
  91. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-root.d.ts +8 -0
  92. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-root.js +37 -3
  93. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-staging.d.ts +14 -0
  94. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-staging.js +155 -0
  95. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-stale-admission.js +7 -2
  96. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-write.d.ts +10 -0
  97. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-write.js +143 -0
  98. package/node_modules/@openclaw/fs-safe/dist/temp-target.js +28 -7
  99. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-admission.d.ts +2 -2
  100. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-admission.js +34 -18
  101. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-child-admission.d.ts +1 -1
  102. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-child-admission.js +13 -3
  103. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-ownership.js +1 -1
  104. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-types.d.ts +9 -0
  105. package/node_modules/@openclaw/fs-safe/dist/test-hooks.d.ts +6 -0
  106. package/node_modules/@openclaw/fs-safe/dist/text-atomic.d.ts +1 -1
  107. package/node_modules/@openclaw/fs-safe/dist/text-atomic.js +1 -0
  108. package/node_modules/@openclaw/fs-safe/dist/windows-owner.d.ts +1 -0
  109. package/node_modules/@openclaw/fs-safe/dist/windows-owner.js +2 -1
  110. package/node_modules/@openclaw/fs-safe/dist/windows-security-helper.exe +0 -0
  111. package/node_modules/@openclaw/fs-safe/docs/advanced.md +6 -1
  112. package/node_modules/@openclaw/fs-safe/docs/atomic.md +64 -0
  113. package/node_modules/@openclaw/fs-safe/docs/contributing.md +69 -0
  114. package/node_modules/@openclaw/fs-safe/docs/file-store.md +2 -0
  115. package/node_modules/@openclaw/fs-safe/docs/json-store.md +2 -0
  116. package/node_modules/@openclaw/fs-safe/docs/json.md +2 -0
  117. package/node_modules/@openclaw/fs-safe/docs/output.md +2 -0
  118. package/node_modules/@openclaw/fs-safe/docs/permissions.md +20 -7
  119. package/node_modules/@openclaw/fs-safe/docs/reading.md +24 -9
  120. package/node_modules/@openclaw/fs-safe/docs/root.md +2 -0
  121. package/node_modules/@openclaw/fs-safe/docs/security-model.md +2 -0
  122. package/node_modules/@openclaw/fs-safe/docs/sidecar-lock.md +12 -7
  123. package/node_modules/@openclaw/fs-safe/docs/staged-file.md +2 -0
  124. package/node_modules/@openclaw/fs-safe/docs/temp-isolation-reference.md +73 -0
  125. package/node_modules/@openclaw/fs-safe/docs/temp.md +65 -0
  126. package/node_modules/@openclaw/fs-safe/docs/testing.md +1 -0
  127. package/node_modules/@openclaw/fs-safe/docs/writing.md +2 -0
  128. package/node_modules/@openclaw/fs-safe/package.json +25 -20
  129. package/node_modules/@openclaw/fs-safe-darwin-arm64/fs-safe-native.node +0 -0
  130. package/node_modules/@openclaw/fs-safe-darwin-arm64/package.json +1 -1
  131. package/node_modules/@openclaw/fs-safe-darwin-x64/fs-safe-native.node +0 -0
  132. package/node_modules/@openclaw/fs-safe-darwin-x64/package.json +1 -1
  133. package/node_modules/@openclaw/fs-safe-freebsd-arm64/fs-safe-native.node +0 -0
  134. package/node_modules/@openclaw/fs-safe-freebsd-arm64/package.json +1 -1
  135. package/node_modules/@openclaw/fs-safe-freebsd-x64/fs-safe-native.node +0 -0
  136. package/node_modules/@openclaw/fs-safe-freebsd-x64/package.json +1 -1
  137. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/fs-safe-native.node +0 -0
  138. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/package.json +1 -1
  139. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/fs-safe-native.node +0 -0
  140. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/package.json +1 -1
  141. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/fs-safe-native.node +0 -0
  142. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/package.json +1 -1
  143. package/node_modules/@openclaw/fs-safe-linux-x64-musl/fs-safe-native.node +0 -0
  144. package/node_modules/@openclaw/fs-safe-linux-x64-musl/package.json +1 -1
  145. package/node_modules/@openclaw/fs-safe-win32-arm64-msvc/fs-safe-native.node +0 -0
  146. package/node_modules/@openclaw/fs-safe-win32-arm64-msvc/package.json +1 -1
  147. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/fs-safe-native.node +0 -0
  148. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/package.json +1 -1
  149. package/package.json +5 -5
@@ -16,11 +16,13 @@ import { assertPinnedWriteMode, pinnedWriteModeAssertion, preparePinnedWriteMode
16
16
  import { publishCopyStage } from "./publish-copy-stage.js";
17
17
  import { openPublicationHandle } from "./publication-handle.js";
18
18
  import { resolveReadOpenFlags } from "./read-open-flags.js";
19
- import { cleanupPinnedFilePath } from "./file-cleanup.js";
19
+ import { cleanupPinnedFilePath, hasErrorCode } from "./file-cleanup.js";
20
20
  import { assertFinalSymlinkRejected } from "./root-symlink-policy.js";
21
21
  import { createStagedFileReceipt, settleStagedFile } from "./staged-file-settlement.js";
22
22
  import { getFsSafeTestHooks } from "./test-hooks.js";
23
23
  import { restoreCopyMetadata } from "./copy-metadata.js";
24
+ import { assertRecoveredFile, recoverAfterHiddenRename, shouldPrepareDrvfsRecovery } from "./publication-recovery.js";
25
+ import { retainDrvfsParent } from "./drvfs-parent.js";
24
26
  export async function runPinnedStagedWrite(params, parentPath, parentGuard) {
25
27
  const verifyPosixMode = process.platform !== "win32" &&
26
28
  (params.verifyPosixMode === true || params.private === true);
@@ -38,11 +40,45 @@ export async function runPinnedStagedWrite(params, parentPath, parentGuard) {
38
40
  let readHandle;
39
41
  let handoffCloseFailure;
40
42
  let renamed = false;
43
+ let recoveryParent;
44
+ let recoveryIdentity;
45
+ let recoveryContent;
41
46
  const completeCreate = params.overwrite === false && params.input.kind !== "file" && params.input.stageBeforePublish === true;
42
47
  let receipt;
43
48
  let publication = Object.freeze({ status: "not-published" });
44
49
  let phase = "prepare";
45
50
  let failure;
51
+ const observePublished = () => {
52
+ try {
53
+ return fsSync.lstatSync(targetPath, { bigint: true });
54
+ }
55
+ catch (error) {
56
+ if (!hasErrorCode(error, "ENOENT") || !handle || !recoveryParent)
57
+ throw error;
58
+ const previous = handle;
59
+ return (async () => {
60
+ // DrvFS reveals the name only after the operation releases its writer.
61
+ readHandle = await recoverAfterHiddenRename({
62
+ closeWriter: () => { handle = undefined; return previous.close(); },
63
+ parentFd: recoveryParent.fd,
64
+ reopen: async () => {
65
+ recoveryParent.assertCurrent();
66
+ const reopened = await openPublicationHandle(targetPath, recoveryIdentity);
67
+ try {
68
+ assertRecoveredFile(reopened.fd, recoveryIdentity, recoveryContent);
69
+ recoveryParent.assertCurrent();
70
+ return reopened;
71
+ }
72
+ catch (error) {
73
+ await reopened.close();
74
+ throw error;
75
+ }
76
+ },
77
+ });
78
+ return fsSync.lstatSync(targetPath, { bigint: true });
79
+ })();
80
+ }
81
+ };
46
82
  try {
47
83
  params.assertBeforeMutation?.();
48
84
  assertExclusiveCreateLeaf(tempPath);
@@ -95,6 +131,14 @@ export async function runPinnedStagedWrite(params, parentPath, parentGuard) {
95
131
  const canHandoff = process.platform !== "win32" &&
96
132
  ((params.mode & 0o400) !== 0 ||
97
133
  (process.platform === "linux" && (process.arch === "x64" || process.arch === "arm64")));
134
+ if (shouldPrepareDrvfsRecovery(params.allowDrvfsRenameRecovery)) {
135
+ recoveryParent = retainDrvfsParent(parentPath, parentGuard.stat.dev);
136
+ if (recoveryParent)
137
+ recoveryIdentity = fsSync.fstatSync(handle.fd, { bigint: true });
138
+ if (recoveryParent && params.input.kind === "buffer")
139
+ recoveryContent = typeof params.input.data === "string"
140
+ ? Buffer.from(params.input.data, params.input.encoding) : Buffer.from(params.input.data);
141
+ }
98
142
  phase = "publish";
99
143
  await withAsyncDirectoryGuards([parentGuard], async () => {
100
144
  assertFinalSymlinkRejected(targetPath, params.rejectFinalSymlink);
@@ -113,6 +157,7 @@ export async function runPinnedStagedWrite(params, parentPath, parentGuard) {
113
157
  publication = Object.freeze({ status: "published", staged: receipt, basename: params.basename, overwrite: false });
114
158
  params.onPublished?.(identity);
115
159
  },
160
+ afterRename: recoveryParent ? observePublished : undefined,
116
161
  beforeTemporaryUnlink: !canHandoff ? undefined : async () => {
117
162
  readHandle = await openPublicationHandle(targetPath, expectedTempStat);
118
163
  // Keep the destination pinned while closing the stage's NFS dentry.
@@ -136,7 +181,8 @@ export async function runPinnedStagedWrite(params, parentPath, parentGuard) {
136
181
  await getFsSafeTestHooks()?.afterPinnedWriteFallbackRename?.(targetPath);
137
182
  if (params.sync !== false)
138
183
  await syncDirectoryBestEffort(parentPath);
139
- const targetStat = fsSync.lstatSync(targetPath, { bigint: true });
184
+ const observed = observePublished();
185
+ const targetStat = observed instanceof Promise ? await observed : observed;
140
186
  if (targetStat.isSymbolicLink()) {
141
187
  throw new FsSafeError("path-mismatch", "fallback target changed during write");
142
188
  }
@@ -174,39 +220,44 @@ export async function runPinnedStagedWrite(params, parentPath, parentGuard) {
174
220
  throw error;
175
221
  }
176
222
  finally {
177
- const preservedPreparation = params.private && !handle && hasPreservedCreationArtifacts(failure?.error);
178
- if (completeCreate || preservedPreparation) {
179
- await settleStagedFile({
180
- temporaryBasename: path.basename(tempPath), publication, phase, failure,
181
- cleanup: async () => {
182
- if (preservedPreparation)
183
- return "preserved";
184
- if (publication.status === "indeterminate")
185
- return "preserved";
186
- if (renamed) {
187
- return failure?.error instanceof FsSafeError && failure.error.details?.cleanup === "failed"
188
- ? "failed" : "not-needed";
223
+ try {
224
+ const preservedPreparation = params.private && !handle && hasPreservedCreationArtifacts(failure?.error);
225
+ if (completeCreate || preservedPreparation) {
226
+ await settleStagedFile({
227
+ temporaryBasename: path.basename(tempPath), publication, phase, failure,
228
+ cleanup: async () => {
229
+ if (preservedPreparation)
230
+ return "preserved";
231
+ if (publication.status === "indeterminate")
232
+ return "preserved";
233
+ if (renamed) {
234
+ return failure?.error instanceof FsSafeError && failure.error.details?.cleanup === "failed"
235
+ ? "failed" : "not-needed";
236
+ }
237
+ return handle ? await cleanupPinnedFilePath({
238
+ pathname: tempPath, handle, identity: tempIdentity, parentGuard, throwOnCleanupError: true,
239
+ }) : "not-needed";
240
+ },
241
+ close: [async () => { await readHandle?.close(); }, async () => {
242
+ await handle?.close();
243
+ if (handoffCloseFailure)
244
+ throw handoffCloseFailure.error;
245
+ }],
246
+ });
247
+ }
248
+ else
249
+ try {
250
+ if (!renamed && handle) {
251
+ await cleanupPinnedFilePath({ pathname: tempPath, handle, identity: tempIdentity, parentGuard });
189
252
  }
190
- return handle ? await cleanupPinnedFilePath({
191
- pathname: tempPath, handle, identity: tempIdentity, parentGuard, throwOnCleanupError: true,
192
- }) : "not-needed";
193
- },
194
- close: [async () => { await readHandle?.close(); }, async () => {
195
- await handle?.close();
196
- if (handoffCloseFailure)
197
- throw handoffCloseFailure.error;
198
- }],
199
- });
200
- }
201
- else
202
- try {
203
- if (!renamed && handle) {
204
- await cleanupPinnedFilePath({ pathname: tempPath, handle, identity: tempIdentity, parentGuard });
205
253
  }
206
- }
207
- finally {
208
- await readHandle?.close().catch(() => undefined);
209
- await handle?.close().catch(() => undefined);
210
- }
254
+ finally {
255
+ await readHandle?.close().catch(() => undefined);
256
+ await handle?.close().catch(() => undefined);
257
+ }
258
+ }
259
+ finally {
260
+ recoveryParent?.close();
261
+ }
211
262
  }
212
263
  }
@@ -12,6 +12,7 @@ export type PinnedWriteInput = {
12
12
  kind: "buffer";
13
13
  data: string | Buffer;
14
14
  encoding?: BufferEncoding;
15
+ sidecar?: boolean;
15
16
  stageBeforePublish?: boolean;
16
17
  } | {
17
18
  kind: "stream";
@@ -63,11 +64,13 @@ export type PinnedWriteParams = {
63
64
  strictFileSync?: boolean;
64
65
  overwrite?: boolean;
65
66
  assertBeforeMutation?: () => void;
67
+ assertSidecarCleanupCandidate?: (candidate: string) => void;
66
68
  rejectFinalSymlink?: boolean;
67
69
  maxBytes?: number;
68
70
  input: PinnedWriteInput;
69
71
  rootIdentity?: FileIdentityStat;
70
72
  mutationAdmission?: PinnedWriteMutationAdmission;
73
+ allowDrvfsRenameRecovery?: boolean;
71
74
  onRenameIdentityMismatch?: "verify-content";
72
75
  onPublished?: (identity: PublishedWriteIdentity) => void;
73
76
  verifyPublished?: (fd: number, identity: PublishedWriteIdentity, parentGuard: AnyAsyncDirectoryGuard, nativeParent?: NativeWriteParent) => Promise<void>;
@@ -22,6 +22,7 @@ import { assertPinnedWriteMode, preparePinnedWriteMode } from "./pinned-write-mo
22
22
  import { runPinnedStagedWrite } from "./pinned-write-staged.js";
23
23
  import { assertFinalSymlinkRejected } from "./root-symlink-policy.js";
24
24
  import { assertNoWindowsPathAlias } from "./windows-path-alias.js";
25
+ import { writeSidecarAtParent } from "./sidecar-lock-write.js";
25
26
  import { copyLinkAtParent } from "./copy-link.js";
26
27
  function assertSafeBasename(basename) {
27
28
  if (!basename ||
@@ -227,6 +228,9 @@ async function runPinnedWriteFallback(params) {
227
228
  }
228
229
  if (params.input.kind === "link")
229
230
  return await copyLinkAtParent(params, params.input, parentGuard);
231
+ if (params.input.kind === "buffer" && params.input.sidecar) {
232
+ return await writeSidecarAtParent(params, parentGuard);
233
+ }
230
234
  if (params.overwrite === false && params.input.kind !== "file" && !params.input.stageBeforePublish) {
231
235
  const assertBeforeMutation = () => {
232
236
  assertFinalSymlinkRejected(targetPath, params.rejectFinalSymlink);
@@ -6,4 +6,5 @@ export declare function prepareDirectoryMode(io: AtomicIo, params: {
6
6
  mode: number | "preserve";
7
7
  mutation?: AtomicMutation;
8
8
  ignoreChmodError?: boolean;
9
+ allowDrvfsRenameRecovery?: boolean;
9
10
  }): Procedure<void>;
@@ -33,7 +33,7 @@ export function* prepareDirectoryMode(io, params) {
33
33
  const parent = path.dirname(params.dirPath);
34
34
  if (parent === params.dirPath)
35
35
  throw error;
36
- yield* prepareDirectoryMode(io, { ...params, dirPath: parent });
36
+ yield* prepareDirectoryMode(io, { ...params, dirPath: parent, allowDrvfsRenameRecovery: false });
37
37
  params.mutation?.assert();
38
38
  try {
39
39
  yield* io.mkdirExclusive(params.dirPath, 0o700);
@@ -169,7 +169,7 @@ function registerTempWorkspace(dir, retainedChild, capability, admission, dirMod
169
169
  }
170
170
  async function createTempWorkspace(options, scopedPrefix = false) {
171
171
  const { rootDir, dirMode, mode, cleanupSafety } = tempWorkspaceSettings(options);
172
- const admission = await admitTempWorkspaceRoot(rootDir);
172
+ const admission = await admitTempWorkspaceRoot(rootDir, options.trustedWritableAncestors);
173
173
  const root = admission.dir;
174
174
  const childPrefix = tempWorkspaceChildPrefix(root, options, scopedPrefix);
175
175
  const capability = new TempWorkspaceCleanupCapability(root, cleanupSafety, admission, dirMode);
@@ -260,7 +260,7 @@ export async function withTempWorkspace(options, run) {
260
260
  }
261
261
  function createTempWorkspaceSync(options, scopedPrefix = false) {
262
262
  const { rootDir, dirMode, mode, cleanupSafety } = tempWorkspaceSettings(options);
263
- const admission = admitTempWorkspaceRootSync(rootDir);
263
+ const admission = admitTempWorkspaceRootSync(rootDir, options.trustedWritableAncestors);
264
264
  const root = admission.dir;
265
265
  const childPrefix = tempWorkspaceChildPrefix(root, options, scopedPrefix);
266
266
  const capability = new TempWorkspaceCleanupCapability(root, cleanupSafety, admission, dirMode);
@@ -0,0 +1,24 @@
1
+ import fs from "node:fs";
2
+ import type { NativeBinding } from "./native-binding.js";
3
+ /** Other platforms keep their existing path even when the option is enabled. */
4
+ export declare function shouldPrepareDrvfsRecovery(enabled: boolean | undefined, dev?: bigint): boolean;
5
+ /** Negative evidence only: a stale/reused device number can only disable recovery. */
6
+ export declare function mayPrepareDrvfsRecoveryAtFd(parentFd: number, dev: bigint): boolean;
7
+ /** No sampling or positive cache: the retained directory's exact mount owns admission. */
8
+ export declare function admitsDrvfsRenameRecoveryAtFd(parentFd: number): boolean;
9
+ /** Exact metadata is necessary but cannot exclude inode reuse after the final close. */
10
+ export declare function assertRecoveredPublication(actual: fs.BigIntStats, expected: fs.BigIntStats): void;
11
+ export declare function recoverAfterHiddenRename<T>(params: {
12
+ closeWriter: () => Promise<void>;
13
+ reopen: () => Promise<T>;
14
+ parentFd: number;
15
+ retain?: (recovered: T) => Promise<void>;
16
+ dispose?: (recovered: T) => Promise<void>;
17
+ }): Promise<T>;
18
+ export declare function recoverAfterHiddenRenameSync<T>(params: {
19
+ closeWriter: () => void;
20
+ reopen: () => T;
21
+ parentFd: number;
22
+ }): T;
23
+ export declare function assertRecoveredFile(fd: number, expected: fs.BigIntStats, content?: Uint8Array): void;
24
+ export declare function reopenRecoveredNativeFile(binding: NativeBinding, parentFd: number, basename: string, expected: fs.BigIntStats, content?: Uint8Array): number;
@@ -0,0 +1,151 @@
1
+ import fs from "node:fs";
2
+ import { nativeOpenFlags } from "./native-operations.js";
3
+ import { readFileDescriptorBoundedSync } from "./bounded-read.js";
4
+ import { FsSafeError } from "./errors.js";
5
+ import { hasErrorCode } from "./file-cleanup.js";
6
+ import { getFsSafeTestHooks } from "./test-hooks.js";
7
+ import { sleep, sleepSync } from "./timing.js";
8
+ import { getNativeBinding } from "./native.js";
9
+ const non9pDevices = new Set();
10
+ /** Other platforms keep their existing path even when the option is enabled. */
11
+ export function shouldPrepareDrvfsRecovery(enabled, dev) {
12
+ if (enabled !== true)
13
+ return false;
14
+ // Synthetic mount evidence must not inherit observations from the real host.
15
+ if (getFsSafeTestHooks()?.drvfsMountObservation)
16
+ return true;
17
+ if (process.platform !== "linux")
18
+ return false;
19
+ if (dev === undefined)
20
+ return true;
21
+ // Linux 9p allocates anonymous devices (major zero), never block devices.
22
+ if (((dev >> 8n) & 0xfffn) !== 0n || ((dev >> 32n) & 0xfffff000n) !== 0n)
23
+ return false;
24
+ return !non9pDevices.has(dev);
25
+ }
26
+ /** Negative evidence only: a stale/reused device number can only disable recovery. */
27
+ export function mayPrepareDrvfsRecoveryAtFd(parentFd, dev) {
28
+ if (!shouldPrepareDrvfsRecovery(true, dev))
29
+ return false;
30
+ if (getFsSafeTestHooks()?.drvfsMountObservation)
31
+ return true;
32
+ try {
33
+ if (getNativeBinding()?.is9pFilesystem?.(parentFd) === false) {
34
+ non9pDevices.add(dev);
35
+ return false;
36
+ }
37
+ }
38
+ catch { /* Unavailable evidence preserves full recovery-time verification. */ }
39
+ return true;
40
+ }
41
+ /** No sampling or positive cache: the retained directory's exact mount owns admission. */
42
+ export function admitsDrvfsRenameRecoveryAtFd(parentFd) {
43
+ try {
44
+ const hook = getFsSafeTestHooks()?.drvfsMountObservation;
45
+ if (!hook && process.platform !== "linux")
46
+ return false;
47
+ if (!Number.isInteger(parentFd) || parentFd < 0)
48
+ return false;
49
+ const observation = hook ? hook(parentFd) : (() => {
50
+ if (fs.statfsSync("/proc/self/fd", { bigint: true }).type !== 0x9fa0n)
51
+ return undefined;
52
+ // statfs follows this kernel-owned descriptor alias to the retained parent.
53
+ return {
54
+ magic: fs.statfsSync(`/proc/self/fd/${parentFd}`, { bigint: true }).type,
55
+ fdinfo: fs.readFileSync(`/proc/self/fdinfo/${parentFd}`, "utf8"),
56
+ mountinfo: fs.readFileSync("/proc/self/mountinfo", "utf8"),
57
+ };
58
+ })();
59
+ if (!observation || observation.magic !== 0x01021997n)
60
+ return false;
61
+ const ids = [...observation.fdinfo.matchAll(/^mnt_id:\s*(\d+)\s*$/gm)];
62
+ if (ids.length !== 1)
63
+ return false;
64
+ const entries = observation.mountinfo.split("\n").filter(line => line.split(" ")[0] === ids[0][1]);
65
+ if (entries.length !== 1)
66
+ return false;
67
+ const [before, after, extra] = entries[0].split(" - ");
68
+ if (!before || !after || extra !== undefined || before.split(" ").length < 6)
69
+ return false;
70
+ const fields = after.split(" ");
71
+ return fields.length === 3 && fields[0] === "9p" &&
72
+ fields[2].split(",").some(option => option === "aname=drvfs" || option.startsWith("aname=drvfs;"));
73
+ }
74
+ catch {
75
+ return false;
76
+ }
77
+ }
78
+ /** Exact metadata is necessary but cannot exclude inode reuse after the final close. */
79
+ export function assertRecoveredPublication(actual, expected) {
80
+ if (!actual.isFile() || actual.isSymbolicLink() || actual.nlink !== 1n ||
81
+ actual.dev !== expected.dev || actual.ino !== expected.ino || actual.size !== expected.size ||
82
+ actual.mode !== expected.mode || actual.uid !== expected.uid || actual.gid !== expected.gid) {
83
+ throw new FsSafeError("path-mismatch", "published file changed during DrvFS recovery");
84
+ }
85
+ }
86
+ export async function recoverAfterHiddenRename(params) {
87
+ if (!admitsDrvfsRenameRecoveryAtFd(params.parentFd)) {
88
+ throw new FsSafeError("path-mismatch", "hidden rename recovery requires a verified DrvFS mount");
89
+ }
90
+ await params.closeWriter();
91
+ for (let attempt = 0;; attempt++) {
92
+ let recovered;
93
+ try {
94
+ recovered = await params.reopen();
95
+ }
96
+ catch (error) {
97
+ if (!hasErrorCode(error, "ENOENT") || attempt === 4)
98
+ throw error;
99
+ await sleep(20);
100
+ continue;
101
+ }
102
+ try {
103
+ await params.retain?.(recovered);
104
+ }
105
+ catch (error) {
106
+ await params.dispose?.(recovered).catch(() => undefined);
107
+ throw error;
108
+ }
109
+ return recovered;
110
+ }
111
+ }
112
+ export function recoverAfterHiddenRenameSync(params) {
113
+ if (!admitsDrvfsRenameRecoveryAtFd(params.parentFd)) {
114
+ throw new FsSafeError("path-mismatch", "hidden rename recovery requires a verified DrvFS mount");
115
+ }
116
+ params.closeWriter();
117
+ for (let attempt = 0;; attempt++) {
118
+ try {
119
+ return params.reopen();
120
+ }
121
+ catch (error) {
122
+ if (!hasErrorCode(error, "ENOENT") || attempt === 4)
123
+ throw error;
124
+ sleepSync(20);
125
+ }
126
+ }
127
+ }
128
+ export function assertRecoveredFile(fd, expected, content) {
129
+ assertRecoveredPublication(fs.fstatSync(fd, { bigint: true }), expected);
130
+ if (content && !readFileDescriptorBoundedSync(fd, content.byteLength).equals(content)) {
131
+ throw new FsSafeError("path-mismatch", "published content changed during DrvFS recovery");
132
+ }
133
+ assertRecoveredPublication(fs.fstatSync(fd, { bigint: true }), expected);
134
+ }
135
+ export function reopenRecoveredNativeFile(binding, parentFd, basename, expected, content) {
136
+ if (!binding.openBeneath || !binding.closeOwnedFd || !binding.stagedFileMatches) {
137
+ throw new FsSafeError("helper-unavailable", "native DrvFS recovery requires descriptor-relative verification");
138
+ }
139
+ const fd = binding.openBeneath(parentFd, basename, nativeOpenFlags(fs.constants.O_RDONLY | fs.constants.O_NONBLOCK)).fd;
140
+ try {
141
+ assertRecoveredFile(fd, expected, content);
142
+ if (!binding.stagedFileMatches(parentFd, basename, fd)) {
143
+ throw new FsSafeError("path-mismatch", "published name changed during DrvFS recovery");
144
+ }
145
+ return fd;
146
+ }
147
+ catch (error) {
148
+ binding.closeOwnedFd(fd);
149
+ throw error;
150
+ }
151
+ }
@@ -11,4 +11,5 @@ export declare function publishCopyStage(params: {
11
11
  onPublicationAttempt?: () => void;
12
12
  onPublished?: (identity: PublishedWriteIdentity) => void;
13
13
  beforeTemporaryUnlink?: () => Promise<void>;
14
+ afterRename?: () => BigIntStats | Promise<BigIntStats>;
14
15
  }): Promise<void>;
@@ -55,7 +55,8 @@ export async function publishCopyStage(params) {
55
55
  if (fs.lstatSync(temporaryPath, { throwIfNoEntry: false })) {
56
56
  throw new FsSafeError("path-mismatch", "renamed copy stage still exists");
57
57
  }
58
- const target = fs.lstatSync(targetPath, { bigint: true });
58
+ const observed = params.afterRename?.();
59
+ const target = observed instanceof Promise ? await observed : observed ?? fs.lstatSync(targetPath, { bigint: true });
59
60
  if (!target.isFile() || target.isSymbolicLink() || target.nlink !== 1n ||
60
61
  !sameFileIdentityForCleanup(target, identity)) {
61
62
  throw new FsSafeError("path-mismatch", "renamed copy target changed after publication");
@@ -1,5 +1,5 @@
1
1
  export declare const realpathSync: ((input: string) => string) & {
2
2
  native: (input: string) => string;
3
3
  };
4
- /** Async on Node; retain runtime-specific native canonicalization guarantees. */
4
+ /** POSIX async canonicalization retains Bun's native path and record-lock semantics. */
5
5
  export declare function realpathNative(input: string): Promise<string>;
@@ -8,6 +8,15 @@ import { getFsSafeNativeConfig } from "./native-config.js";
8
8
  import { isWindowsAppContainer } from "./windows-appcontainer.js";
9
9
  const runtimePlatform = process.versions.bun ? platform() : undefined;
10
10
  const bunPosix = runtimePlatform === "darwin" || runtimePlatform === "linux" ? runtimePlatform : undefined;
11
+ function nativeResult(input, result) {
12
+ if (result.path !== undefined)
13
+ return result.path;
14
+ const errno = -(result.errno);
15
+ const code = getSystemErrorName(errno);
16
+ throw Object.assign(new Error(`${code}: realpath '${input}'`), {
17
+ code, errno, syscall: "realpath", path: input,
18
+ });
19
+ }
11
20
  function resolve(input, native) {
12
21
  if (native && process.platform === "win32") {
13
22
  try {
@@ -54,14 +63,7 @@ function resolve(input, native) {
54
63
  const binding = getNativeBinding();
55
64
  if (binding?.canonicalizePath) {
56
65
  // Ordinary resolution normalizes both the input and each expanded symlink.
57
- const result = binding.canonicalizePath(input, !native);
58
- if (result.path !== undefined)
59
- return result.path;
60
- const errno = -(result.errno);
61
- const code = getSystemErrorName(errno);
62
- throw Object.assign(new Error(`${code}: realpath '${input}'`), {
63
- code, errno, syscall: "realpath", path: input,
64
- });
66
+ return nativeResult(input, binding.canonicalizePath(input, !native));
65
67
  }
66
68
  if (getFsSafeNativeConfig().mode === "require") {
67
69
  throw new FsSafeError("helper-unavailable", "native fs-safe canonicalization is unavailable");
@@ -74,10 +76,19 @@ function resolve(input, native) {
74
76
  export const realpathSync = Object.assign((input) => resolve(input, false), {
75
77
  native: (input) => resolve(input, true),
76
78
  });
77
- /** Async on Node; retain runtime-specific native canonicalization guarantees. */
79
+ /** POSIX async canonicalization retains Bun's native path and record-lock semantics. */
78
80
  export async function realpathNative(input) {
79
- if (bunPosix)
80
- return realpathSync.native(input);
81
+ if (bunPosix) {
82
+ if (input.includes("\0")) {
83
+ throw Object.assign(new TypeError("realpath input must not contain null bytes"), { code: "ERR_INVALID_ARG_VALUE" });
84
+ }
85
+ const binding = getNativeBinding();
86
+ if (binding?.canonicalizePathAsync)
87
+ return nativeResult(input, await binding.canonicalizePathAsync(input, false));
88
+ if (binding?.canonicalizePath || getFsSafeNativeConfig().mode === "require") {
89
+ throw new FsSafeError("helper-unavailable", "native fs-safe canonicalization is unavailable");
90
+ }
91
+ }
81
92
  try {
82
93
  return await asyncFs.realpath(input);
83
94
  }
@@ -6,6 +6,7 @@ export declare function applyDirectoryMode(io: AtomicIo, params: {
6
6
  dirPath: string;
7
7
  mode: number | "preserve";
8
8
  expectedIdentity?: BigIntStats;
9
+ allowDrvfsRenameRecovery?: boolean;
9
10
  ignoreChmodError?: boolean;
10
11
  mutation?: AtomicMutation;
11
12
  }): Procedure<void>;
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
3
3
  import { FsSafeError } from "./errors.js";
4
4
  import { inspectFileIdentity, inspectFileIdentitySync } from "./strict-file-identity.js";
5
5
  import { ownDirectoryMode } from "./directory-mode-node.js";
6
+ import { mayPrepareDrvfsRecoveryAtFd } from "./publication-recovery.js";
6
7
  import { inspectAtomicIdentity, wait } from "./atomic-io.js";
7
8
  function parentCloseFailure(primary, closeError) {
8
9
  return primary ? new AggregateError([primary.error, closeError], "Atomic parent preparation and close failed") : closeError;
@@ -66,6 +67,8 @@ async function pinDirectoryForMode(params) {
66
67
  ignoreChmodError: params.ignoreChmodError,
67
68
  });
68
69
  await owner.verify();
70
+ if (params.allowDrvfsRenameRecovery)
71
+ mayPrepareDrvfsRecoveryAtFd(handle.fd, expected.dev);
69
72
  return owner;
70
73
  }
71
74
  catch (error) {
@@ -112,6 +115,8 @@ export function* applyDirectoryMode(io, params) {
112
115
  let primary;
113
116
  try {
114
117
  inspectAtomicIdentity(io, () => file.statExact(), expected, false, admit);
118
+ if (params.allowDrvfsRenameRecovery)
119
+ mayPrepareDrvfsRecoveryAtFd(file.fd, expected.dev);
115
120
  if (params.mode !== "preserve") {
116
121
  params.mutation?.assert();
117
122
  file.chmod(params.mode & 0o7777);
@@ -10,11 +10,18 @@ export declare class AtomicTempOwner {
10
10
  private resource;
11
11
  private recordedIdentity;
12
12
  private exists;
13
+ private recoveryParent?;
14
+ private recoveryIdentity?;
15
+ private recoveryContent?;
16
+ private recovered;
13
17
  private readonly unregister;
14
18
  constructor(pathname: string, io: AtomicIo);
15
19
  start(): void;
16
20
  readonly onIdentity: (identity: BigIntStats) => void;
17
21
  get identity(): BigIntStats;
22
+ get canRecoverHiddenRename(): boolean;
23
+ get fd(): number;
24
+ prepareRecovery(content: string | Uint8Array, directory?: string, filesystemChecked?: boolean): Procedure<void>;
18
25
  markRenamed(): void;
19
26
  private takeResource;
20
27
  adopt(temp: {