Skip to content

Commit 5ddca80

Browse files
committed
feat: add reusable safe filesystem primitives
1 parent 8f72a1f commit 5ddca80

66 files changed

Lines changed: 12022 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.gitignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
dist/
2+
node_modules/
3+
coverage/
4+
*.tsbuildinfo

‎README.md‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
# @openclaw/fs-safe
2+
3+
Race-resistant root-bounded filesystem primitives for Node.js.
4+
5+
The package is for code that must operate on caller-controlled paths without letting symlinks,
6+
`..` traversal, hardlinks, path aliases, or rename races escape a configured root.
7+
8+
## Motivation
9+
10+
Most Node filesystem helpers make path handling convenient, but they do not give you a reusable
11+
security boundary. A check like `path.resolve(root, input).startsWith(root)` only validates a string
12+
snapshot. It does not pin the opened file, defend against symlink swaps between check and use, reject
13+
hardlinked aliases, or verify that a write still landed on the intended file after a rename.
14+
15+
OpenClaw has many places where an agent, plugin, archive, upload, or config file can supply a path.
16+
Each call site used to carry its own mix of "within root" checks, temp-file conventions, JSON helpers,
17+
archive extraction limits, and symlink policy. That made the product harder to audit: small differences
18+
in helper behavior mattered, and fixing one surface did not automatically improve the others.
19+
20+
`@openclaw/fs-safe` packages those patterns as one small set of primitives:
21+
22+
- define a trusted root once with `root()`, then use relative paths for reads, writes, moves, copies,
23+
directory creation, and removal
24+
- choose explicit policies for hardlinks and symlinks instead of threading boolean flags through every
25+
call site
26+
- use pinned/opened file identity checks where Node exposes enough platform support
27+
- use sibling-temp and atomic-replace helpers for writes that should not leave partially written files
28+
- extract archives with entry-count and byte limits, traversal checks, and symlink-safe staging
29+
30+
This is not a full sandbox and it does not replace OS permissions, containers, or process isolation.
31+
It is a library-level guardrail for the common case where trusted application code must safely touch
32+
untrusted paths inside a directory it owns.
33+
34+
## Install
35+
36+
```sh
37+
pnpm add @openclaw/fs-safe
38+
```
39+
40+
## API
41+
42+
```ts
43+
import { openRootFile, openPinnedFileSync, safeFileURLToPath, root } from "@openclaw/fs-safe";
44+
45+
const fs = await root("/safe/workspace", {
46+
hardlinks: "reject",
47+
nonBlockingRead: true,
48+
mkdir: true,
49+
});
50+
51+
await fs.write("notes/today.txt", "hello\n");
52+
await fs.create("notes/README.md", "seed\n");
53+
const text = await fs.readText("notes/today.txt");
54+
const config = await fs.readJson("config.json");
55+
await fs.copyFrom("/tmp/upload.png", "uploads/upload.png");
56+
await fs.move("notes/today.txt", "notes/archive/today.txt");
57+
```
58+
59+
Use `read()` and `open()` when you need metadata or a `FileHandle`:
60+
61+
```ts
62+
const { buffer, realPath, stat } = await fs.read("notes/today.txt");
63+
const opened = await fs.open("notes/today.txt");
64+
```
65+
66+
Lower-level primitives are available from named subpaths:
67+
68+
```ts
69+
import { root } from "@openclaw/fs-safe/root";
70+
import { isPathInside } from "@openclaw/fs-safe/path";
71+
import { FsSafeError } from "@openclaw/fs-safe/errors";
72+
import { readJsonFile, readJsonFileStrict, writeJsonAtomic } from "@openclaw/fs-safe/json";
73+
import { replaceFileAtomic, movePathWithCopyFallback } from "@openclaw/fs-safe/atomic";
74+
import { createPrivateTempWorkspace, createTempFileTarget } from "@openclaw/fs-safe/temp";
75+
import { extractArchive } from "@openclaw/fs-safe/archive";
76+
```
77+
78+
`readJsonFile()` returns `null` when the file cannot be read or parsed.
79+
`readJsonFileStrict()` throws read and parse errors.
80+
81+
Archive extraction keeps ZIP/TAR handling behind one API and exposes lower-level preflight helpers for
82+
callers that need to enforce the same limits before doing custom work:
83+
84+
```ts
85+
import { extractArchive, resolveArchiveKind } from "@openclaw/fs-safe/archive";
86+
87+
const kind = resolveArchiveKind(uploadPath);
88+
if (!kind) {
89+
throw new Error(`unsupported archive: ${uploadPath}`);
90+
}
91+
await extractArchive({
92+
archivePath: uploadPath,
93+
destDir: "/safe/workspace/plugin",
94+
kind,
95+
timeoutMs: 15_000,
96+
limits: {
97+
maxArchiveBytes: 256 * 1024 * 1024,
98+
maxEntries: 50_000,
99+
},
100+
});
101+
```
102+
103+
`replaceFileAtomic()` and `replaceFileAtomicSync()` write a sibling temp file and
104+
then replace the destination. They support rename retry/fallback behavior,
105+
existing-mode preservation, optional temp-file and parent-directory fsync,
106+
injected filesystem ops for tests, and a `beforeRename` hook for backup/observer
107+
workflows. `writeSiblingTempFile()` covers stream/download producers that need
108+
to decide the final sibling path after writing a temp file.
109+
110+
```ts
111+
import { pathScope } from "@openclaw/fs-safe";
112+
113+
const uploads = pathScope("/safe/uploads", { label: "uploads directory" });
114+
const files = await uploads.files(["photo.jpg"]);
115+
const target = await uploads.writable("report.pdf");
116+
```
117+
118+
## Safety Model
119+
120+
- root-bounded APIs resolve paths against a configured root and reject canonical escapes
121+
- reads open with `O_NOFOLLOW` where available and verify fd/path identity before returning
122+
- writes use pinned parent-directory helpers and atomic replacement on POSIX, with verified post-write identity
123+
- remove and mkdir use fd-relative Python syscalls on POSIX, with legacy fallback when the helper cannot spawn
124+
- archive extraction rejects traversal paths and blocked link types, enforces entry and byte budgets,
125+
and merges through the same safe-open boundary checks used by direct writes
126+
- optional internal subpath exports expose pinned helper modules used by OpenClaw tests
127+
128+
## Design Notes
129+
130+
The public surface is intentionally organized by job, not by implementation detail:
131+
132+
- `root()` and `SafeRoot` are the preferred API for application code
133+
- `/path` exposes canonical path checks and scoped path helpers
134+
- `/json`, `/atomic`, `/temp`, and `/archive` expose focused building blocks for code that already has
135+
a trusted absolute path
136+
- `/errors` provides the canonical `FsSafeError` type for downstream `instanceof` checks
137+
- `/internal/*` is reserved for helper processes and tests, not general application imports
138+
139+
When two helpers have different failure semantics, the name says so. For example, `readJsonFile()`
140+
returns `null` on missing or invalid JSON for legacy state files, while `readJsonFileStrict()` throws
141+
for install manifests and other inputs where parse failure should stop the operation.
142+
143+
## Limitations
144+
145+
- Windows support uses the safest Node-level behavior available, but some fd-relative POSIX hardening is
146+
unavailable there.
147+
- Hardlink rejection depends on platform metadata and should be treated as a defense-in-depth policy,
148+
not an authorization model.
149+
- The package does not sanitize file contents or validate archive payload semantics beyond filesystem
150+
safety constraints.

‎package.json‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
{
2+
"name": "@openclaw/fs-safe",
3+
"version": "0.0.0",
4+
"description": "Race-resistant root-bounded filesystem primitives for Node.js.",
5+
"license": "MIT",
6+
"repository": {
7+
"type": "git",
8+
"url": "https://github.com/openclaw/fs-safe.git"
9+
},
10+
"files": [
11+
"dist",
12+
"README.md",
13+
"LICENSE"
14+
],
15+
"type": "module",
16+
"sideEffects": false,
17+
"exports": {
18+
".": {
19+
"types": "./dist/index.d.ts",
20+
"default": "./dist/index.js"
21+
},
22+
"./root": {
23+
"types": "./dist/root.d.ts",
24+
"default": "./dist/root.js"
25+
},
26+
"./path": {
27+
"types": "./dist/path.d.ts",
28+
"default": "./dist/path.js"
29+
},
30+
"./json": {
31+
"types": "./dist/json.d.ts",
32+
"default": "./dist/json.js"
33+
},
34+
"./temp": {
35+
"types": "./dist/temp.d.ts",
36+
"default": "./dist/temp.js"
37+
},
38+
"./atomic": {
39+
"types": "./dist/atomic.d.ts",
40+
"default": "./dist/atomic.js"
41+
},
42+
"./archive": {
43+
"types": "./dist/archive.d.ts",
44+
"default": "./dist/archive.js"
45+
},
46+
"./errors": {
47+
"types": "./dist/errors.d.ts",
48+
"default": "./dist/errors.js"
49+
},
50+
"./types": {
51+
"types": "./dist/types.d.ts",
52+
"default": "./dist/types.js"
53+
},
54+
"./test-hooks": {
55+
"types": "./dist/test-hooks.d.ts",
56+
"default": "./dist/test-hooks.js"
57+
},
58+
"./internal/pinned-open": {
59+
"types": "./dist/pinned-open.d.ts",
60+
"default": "./dist/pinned-open.js"
61+
},
62+
"./internal/pinned-path": {
63+
"types": "./dist/pinned-path.d.ts",
64+
"default": "./dist/pinned-path.js"
65+
},
66+
"./internal/pinned-write": {
67+
"types": "./dist/pinned-write.d.ts",
68+
"default": "./dist/pinned-write.js"
69+
}
70+
},
71+
"scripts": {
72+
"build": "tsc -p tsconfig.json",
73+
"prepack": "pnpm build",
74+
"test": "vitest run",
75+
"check": "pnpm build && pnpm test"
76+
},
77+
"dependencies": {
78+
"jszip": "^3.10.1",
79+
"tar": "7.5.13"
80+
},
81+
"devDependencies": {
82+
"@types/node": "^22.15.19",
83+
"typescript": "^5.8.3",
84+
"vitest": "^3.1.4"
85+
},
86+
"engines": {
87+
"node": ">=20.11"
88+
}
89+
}

0 commit comments

Comments
 (0)