|
| 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. |
0 commit comments