Skip to content

Commit d43520b

Browse files
authored
fix: native fs-safe opt-in fails in bundled installs (#131939)
1 parent c8ddecd commit d43520b

3 files changed

Lines changed: 180 additions & 5 deletions

File tree

‎docs/gateway/security/secure-file-operations.md‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,18 @@ It is a **library guardrail** for trusted OpenClaw code that receives untrusted
1313

1414
OpenClaw sets fs-safe's optional native helper to **off** by default:
1515

16-
- native platform packages are optional and may be absent from minimal installs;
1716
- the guarded JavaScript paths support OpenClaw's normal filesystem operations;
1817
- disabling native loading keeps runtime behavior deterministic across desktop, Docker, CI, and bundled-app environments.
1918

19+
The OpenClaw package includes fs-safe's prebuilt native helpers for Linux x64/arm64 (glibc and musl), macOS x64/arm64, and Windows x64. No separate platform package, download, or compiler is needed. Loading these helpers remains optional.
20+
2021
OpenClaw only changes the _default_. An explicit setting always wins:
2122

2223
```bash
2324
# Default OpenClaw behavior: guarded JavaScript fs-safe paths.
2425
OPENCLAW_FS_SAFE_NATIVE_MODE=off
2526

26-
# Prefer native primitives when the platform package is installed.
27+
# Prefer native primitives when the bundled platform helper loads.
2728
OPENCLAW_FS_SAFE_NATIVE_MODE=auto
2829

2930
# Fail closed when an operation needs native support and the binding is unavailable.
@@ -52,16 +53,18 @@ This covers OpenClaw's normal threat model: trusted gateway code handling untrus
5253

5354
## What native acceleration adds
5455

55-
The optional platform package provides policy-free filesystem primitives used by fs-safe for create-only writes, guarded hard-link publication, asynchronous sidecar creation, and explicit no-replace rename publication. Linux uses `openat2` and `renameat2`; macOS uses descriptor-relative component checks and `renameatx_np`; Windows uses handle-relative operations and replacement-disabled rename.
56+
The bundled native helper provides policy-free filesystem primitives used by fs-safe for create-only writes, guarded hard-link publication, asynchronous sidecar creation, and explicit no-replace rename publication. Linux uses `openat2` and `renameat2`; macOS uses descriptor-relative component checks and `renameatx_np`; Windows uses handle-relative operations and replacement-disabled rename.
5657

5758
The TypeScript layer still owns policy, validation, retries, cleanup, and fallback decisions. Native support narrows filesystem race windows; it does not turn fs-safe into a sandbox.
5859

59-
If your deployment requires those native primitives, install the matching optional platform package and set:
60+
If your package deployment requires those native primitives, set:
6061

6162
```bash
6263
OPENCLAW_FS_SAFE_NATIVE_MODE=require
6364
```
6465

66+
In `require` mode, an unavailable or unloadable helper causes `helper-unavailable` instead of silently using the JavaScript path. Standalone portable worker bundles do not carry these native assets; their managed launch environment does not forward fs-safe mode overrides.
67+
6568
## Plugin and core guidance
6669

6770
- Plugin-facing file access should go through `openclaw/plugin-sdk/*` helpers, not raw `fs`, when a path comes from a message, model output, config, or plugin input.

‎test/scripts/tsdown-config.test.ts‎

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
// Tsdown config tests protect package artifact build contracts.
2+
import { spawnSync } from "node:child_process";
3+
import { createHash } from "node:crypto";
24
import fs from "node:fs";
5+
import { createRequire } from "node:module";
36
import path from "node:path";
47
import { build } from "tsdown";
58
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -39,7 +42,162 @@ const isWorkerRsyncReceiverConfig = (config: TsdownConfig) =>
3942
const isWorkerBuildConfig = (config: TsdownConfig) =>
4043
isWorkerDeployConfig(config) || isWorkerRsyncReceiverConfig(config);
4144

45+
function nativeAssetInventory(directory: string) {
46+
return fs
47+
.readdirSync(directory, { recursive: true, encoding: "utf8" })
48+
.filter((file) => fs.statSync(path.join(directory, file)).isFile())
49+
.toSorted()
50+
.map((file) => ({
51+
file,
52+
sha256: createHash("sha256")
53+
.update(fs.readFileSync(path.join(directory, file)))
54+
.digest("hex"),
55+
}));
56+
}
57+
58+
const FS_SAFE_CALLER_PROBE = `
59+
import assert from "node:assert/strict";
60+
import fs from "node:fs";
61+
import { createRequire } from "node:module";
62+
import path from "node:path";
63+
import { pathToFileURL } from "node:url";
64+
const [entry, observer, rootDir, mode, outcome] = process.argv.slice(1);
65+
const { root } = await import(pathToFileURL(entry).href);
66+
const { configureFsSafeNative, getFsSafeNativeConfig, FsSafeError } = await import(pathToFileURL(observer).href);
67+
assert.equal(getFsSafeNativeConfig().mode, mode === "configured" ? "off" : mode);
68+
if (mode === "configured") configureFsSafeNative({ mode: "require" });
69+
const scoped = await root(rootDir);
70+
if (outcome === "missing") {
71+
await assert.rejects(scoped.write("proof.txt", "native proof"), (error) => {
72+
assert(error instanceof FsSafeError);
73+
assert.equal(error.code, "helper-unavailable");
74+
assert.equal(error.cause?.code, "MODULE_NOT_FOUND");
75+
return true;
76+
});
77+
assert.deepEqual(fs.readdirSync(rootDir), []);
78+
} else {
79+
await scoped.write("proof.txt", "native proof");
80+
await scoped.create("created.txt", "create proof");
81+
assert.equal(fs.readFileSync(path.join(rootDir, "proof.txt"), "utf8"), "native proof");
82+
assert.equal(fs.readFileSync(path.join(rootDir, "created.txt"), "utf8"), "create proof");
83+
}
84+
const loaded = Object.keys(createRequire(import.meta.url).cache).filter((file) => file.endsWith("fs-safe-native.node"));
85+
assert.equal(loaded.length, outcome === "native" ? 1 : 0);
86+
if (loaded.length) assert(loaded[0].startsWith(path.dirname(rootDir) + path.sep));
87+
`;
88+
4289
describe("tsdown config", () => {
90+
it.each(["runtime", "worker"])(
91+
"preserves native fs-safe assets and policy in relocated %s output",
92+
async (target) => {
93+
const temporaryRoot = fs.realpathSync(createTempDir("openclaw-tsdown-fs-safe-"));
94+
const sourceRoot = path.join(temporaryRoot, "build");
95+
const relocatedRoot = path.join(temporaryRoot, "relocated");
96+
const require = createRequire(import.meta.url);
97+
const nativeSource = path.join(
98+
path.dirname(require.resolve("@openclaw/fs-safe/package.json")),
99+
"dist/native",
100+
);
101+
const sdkSource = path.resolve("src/plugin-sdk/memory-core-host-engine-fs.ts");
102+
const observerSource = path.join(temporaryRoot, "observer.ts");
103+
fs.writeFileSync(
104+
observerSource,
105+
[
106+
`export { root } from ${JSON.stringify(sdkSource)};`,
107+
`export { configureFsSafeNative, getFsSafeNativeConfig } from ${JSON.stringify(require.resolve("@openclaw/fs-safe/config"))};`,
108+
`export { FsSafeError } from ${JSON.stringify(require.resolve("@openclaw/fs-safe/errors"))};`,
109+
].join("\n"),
110+
);
111+
const worker = target === "worker";
112+
const selected = configs.find(
113+
worker ? isWorkerDeployConfig : (config) => config.name === TSDOWN_UNIFIED_CONFIG_GROUP,
114+
);
115+
expect(selected).toBeDefined();
116+
// Deliberately not named dist: the dependency's URL is relative to the
117+
// emitted loader, including the worker's extra directory component.
118+
const bundles = await build({
119+
...selected,
120+
config: false,
121+
entry: worker
122+
? { "worker/worker": observerSource }
123+
: { "plugin-sdk/memory-core-host-engine-fs": sdkSource, observer: observerSource },
124+
outDir: path.join(sourceRoot, "output"),
125+
dts: false,
126+
logLevel: "silent",
127+
});
128+
try {
129+
fs.writeFileSync(path.join(sourceRoot, "package.json"), '{"type":"module"}');
130+
fs.renameSync(sourceRoot, relocatedRoot);
131+
const entry = path.join(
132+
relocatedRoot,
133+
worker ? "output/worker/worker.mjs" : "output/plugin-sdk/memory-core-host-engine-fs.js",
134+
);
135+
const observer = worker ? entry : path.join(relocatedRoot, "output/observer.js");
136+
const nativeOutput = path.join(
137+
relocatedRoot,
138+
worker ? "output/dist/native" : "dist/native",
139+
);
140+
const probe = (
141+
name: string,
142+
mode: string,
143+
outcome: string,
144+
override: NodeJS.ProcessEnv = {},
145+
) => {
146+
const rootDir = path.join(relocatedRoot, name);
147+
fs.mkdirSync(rootDir);
148+
const result = spawnSync(
149+
process.execPath,
150+
[
151+
"--input-type=module",
152+
"--eval",
153+
FS_SAFE_CALLER_PROBE,
154+
entry,
155+
observer,
156+
rootDir,
157+
mode,
158+
outcome,
159+
],
160+
{
161+
cwd: relocatedRoot,
162+
encoding: "utf8",
163+
timeout: 30_000,
164+
env: {
165+
PATH: process.env.PATH,
166+
SystemRoot: process.env.SystemRoot,
167+
WINDIR: process.env.WINDIR,
168+
HOME: temporaryRoot,
169+
USERPROFILE: temporaryRoot,
170+
TMPDIR: temporaryRoot,
171+
TMP: temporaryRoot,
172+
TEMP: temporaryRoot,
173+
...override,
174+
},
175+
},
176+
);
177+
expect(result.error, name).toBeUndefined();
178+
expect(result.status, `${name}\n${result.stdout}\n${result.stderr}`).toBe(0);
179+
};
180+
for (const key of ["FS_SAFE_NATIVE_MODE", "OPENCLAW_FS_SAFE_NATIVE_MODE"]) {
181+
probe(key, "require", "native", { [key]: "require" });
182+
}
183+
probe("shared-config", "configured", "native");
184+
probe("default", "off", "fallback");
185+
const assets = nativeAssetInventory(nativeSource);
186+
expect(assets).toHaveLength(7);
187+
expect(nativeAssetInventory(nativeOutput)).toEqual(assets);
188+
fs.rmSync(nativeOutput, { recursive: true });
189+
probe("missing", "require", "missing", { FS_SAFE_NATIVE_MODE: "require" });
190+
for (const mode of ["off", "auto"]) {
191+
probe(mode, mode, "fallback", { FS_SAFE_NATIVE_MODE: mode });
192+
}
193+
} finally {
194+
for (const bundle of bundles) {
195+
await bundle[Symbol.asyncDispose]();
196+
}
197+
}
198+
},
199+
);
200+
43201
it.each(
44202
["runtime", "declarations", "worker", "receiver"].flatMap((target) =>
45203
[false, true].map((verbose) => ({ target, verbose })),

‎tsdown.config.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// tsdown config defines package build entrypoints and output options.
22
import fs from "node:fs";
3-
import { isBuiltin } from "node:module";
3+
import { createRequire, isBuiltin } from "node:module";
44
import path from "node:path";
55
import type { UserConfig } from "tsdown";
66
import {
@@ -171,11 +171,24 @@ function nodeBuildConfig(
171171
};
172172
}
173173

174+
function fsSafeNativeCopy(entryDirectory: string): UserConfig["copy"] {
175+
const packageRoot = path.dirname(
176+
createRequire(import.meta.url).resolve("@openclaw/fs-safe/package.json"),
177+
);
178+
return ({ outDir }) => ({
179+
from: path.join(packageRoot, "dist/native"),
180+
// fs-safe resolves ../dist/native from its emitted loader. Preserve that
181+
// layout, including the inline worker's extra directory, and every target.
182+
to: path.resolve(outDir, entryDirectory, "..", "dist"),
183+
});
184+
}
185+
174186
function workerDeployBuildConfig(): UserConfig {
175187
return {
176188
name: TSDOWN_UNIFIED_CONFIG_GROUP,
177189
entry: { "worker/worker": "src/worker/worker-deploy-entry.ts" },
178190
outDir: "dist",
191+
copy: fsSafeNativeCopy("worker"),
179192
dts: false,
180193
env,
181194
define: {
@@ -760,6 +773,7 @@ const configs = [
760773
// and bundled hooks in one graph so runtime singletons are emitted once.
761774
entry: unifiedDistEntries,
762775
deps: unifiedDeps,
776+
copy: fsSafeNativeCopy("."),
763777
plugins: [createStateSchemaInlinePlugin()],
764778
},
765779
false,

0 commit comments

Comments
 (0)