@clawkeepers/gatekeeper-fs 0.1.0-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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ControlStackAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,206 @@
1
+ OpenClaw OS
2
+ Copyright (c) 2026 ControlStackAI
3
+ Original project contributions are licensed under the MIT License; see LICENSE.
4
+ Third-party and adapted material retains its applicable license terms.
5
+
6
+ OpenClaw (https://github.com/openclaw/openclaw) provides the separately installed,
7
+ unmodified agent runtime, Gateway and public plugin interfaces. Its pinned
8
+ v2026.9.2 license is MIT, copyright (c) 2026 OpenClaw Foundation; its own
9
+ THIRD_PARTY_NOTICES.md applies to incorporated upstream dependencies.
10
+
11
+ Cloudflare OS (https://github.com/cloudflare/cloudflare-os), by Cloudflare and
12
+ its contributors, provides architectural foundations and adapted material:
13
+ capability introductions, gatekeepers, approval/simulation contracts, observers,
14
+ and kernel review/authoring guidance. OpenClaw OS contributors modified these
15
+ contracts and documents for a self-hosted, single-process, tool-calling plugin
16
+ runtime. Cloudflare OS Starter (https://github.com/cloudflare/cloudflare-os-starter)
17
+ informed wrapper-owned customization and the upgrade discipline.
18
+
19
+ Cloudflare OS and Cloudflare OS Starter are Apache-2.0 licensed. Their retained
20
+ material is not relicensed by the project's MIT license. The applicable Apache
21
+ License 2.0 text is reproduced below. The original source distribution includes
22
+ further provenance in docs/acknowledgments.md. Other dependencies retain their
23
+ respective licenses and notices, including generated THIRD-PARTY-NOTICES for
24
+ bundled dependencies.
25
+
26
+ This is an independent project, not an upstream-endorsed product. No affiliation,
27
+ endorsement or rights to upstream trademarks are implied.
28
+
29
+ --- Apache License 2.0: retained Cloudflare material ---
30
+
31
+ Apache License
32
+ Version 2.0, January 2004
33
+ http://www.apache.org/licenses/
34
+
35
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
36
+
37
+ 1. Definitions.
38
+
39
+ "License" shall mean the terms and conditions for use, reproduction,
40
+ and distribution as defined by Sections 1 through 9 of this document.
41
+
42
+ "Licensor" shall mean the copyright owner or entity authorized by
43
+ the copyright owner that is granting the License.
44
+
45
+ "Legal Entity" shall mean the union of the acting entity and all
46
+ other entities that control, are controlled by, or are under common
47
+ control with that entity. For the purposes of this definition,
48
+ "control" means (i) the power, direct or indirect, to cause the
49
+ direction or management of such entity, whether by contract or
50
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
51
+ outstanding shares, or (iii) beneficial ownership of such entity.
52
+
53
+ "You" (or "Your") shall mean an individual or Legal Entity
54
+ exercising permissions granted by this License.
55
+
56
+ "Source" form shall mean the preferred form for making modifications,
57
+ including but not limited to software source code, documentation
58
+ source, and configuration files.
59
+
60
+ "Object" form shall mean any form resulting from mechanical
61
+ transformation or translation of a Source form, including but
62
+ not limited to compiled object code, generated documentation,
63
+ and conversions to other media types.
64
+
65
+ "Work" shall mean the work of authorship, whether in Source or
66
+ Object form, made available under the License, as indicated by a
67
+ copyright notice that is included in or attached to the work
68
+ (an example is provided in the Appendix below).
69
+
70
+ "Derivative Works" shall mean any work, whether in Source or Object
71
+ form, that is based on (or derived from) the Work and for which the
72
+ editorial revisions, annotations, elaborations, or other modifications
73
+ represent, as a whole, an original work of authorship. For the purposes
74
+ of this License, Derivative Works shall not include works that remain
75
+ separable from, or merely link (or bind by name) to the interfaces of,
76
+ the Work and Derivative Works thereof.
77
+
78
+ "Contribution" shall mean any work of authorship, including
79
+ the original version of the Work and any modifications or additions
80
+ to that Work or Derivative Works thereof, that is intentionally
81
+ submitted to Licensor for inclusion in the Work by the copyright owner
82
+ or by an individual or Legal Entity authorized to submit on behalf of
83
+ the copyright owner. For the purposes of this definition, "submitted"
84
+ means any form of electronic, verbal, or written communication sent
85
+ to the Licensor or its representatives, including but not limited to
86
+ communication on electronic mailing lists, source code control systems,
87
+ and issue tracking systems that are managed by, or on behalf of, the
88
+ Licensor for the purpose of discussing and improving the Work, but
89
+ excluding communication that is conspicuously marked or otherwise
90
+ designated in writing by the copyright owner as "Not a Contribution."
91
+
92
+ "Contributor" shall mean Licensor and any individual or Legal Entity
93
+ on behalf of whom a Contribution has been received by Licensor and
94
+ subsequently incorporated within the Work.
95
+
96
+ 2. Grant of Copyright License. Subject to the terms and conditions of
97
+ this License, each Contributor hereby grants to You a perpetual,
98
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
99
+ copyright license to reproduce, prepare Derivative Works of,
100
+ publicly display, publicly perform, sublicense, and distribute the
101
+ Work and such Derivative Works in Source or Object form.
102
+
103
+ 3. Grant of Patent License. Subject to the terms and conditions of
104
+ this License, each Contributor hereby grants to You a perpetual,
105
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
106
+ (except as stated in this section) patent license to make, have made,
107
+ use, offer to sell, sell, import, and otherwise transfer the Work,
108
+ where such license applies only to those patent claims licensable
109
+ by such Contributor that are necessarily infringed by their
110
+ Contribution(s) alone or by combination of their Contribution(s)
111
+ with the Work to which such Contribution(s) was submitted. If You
112
+ institute patent litigation against any entity (including a
113
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
114
+ or a Contribution incorporated within the Work constitutes direct
115
+ or contributory patent infringement, then any patent licenses
116
+ granted to You under this License for that Work shall terminate
117
+ as of the date such litigation is filed.
118
+
119
+ 4. Redistribution. You may reproduce and distribute copies of the
120
+ Work or Derivative Works thereof in any medium, with or without
121
+ modifications, and in Source or Object form, provided that You
122
+ meet the following conditions:
123
+
124
+ (a) You must give any other recipients of the Work or
125
+ Derivative Works a copy of this License; and
126
+
127
+ (b) You must cause any modified files to carry prominent notices
128
+ stating that You changed the files; and
129
+
130
+ (c) You must retain, in the Source form of any Derivative Works
131
+ that You distribute, all copyright, patent, trademark, and
132
+ attribution notices from the Source form of the Work,
133
+ excluding those notices that do not pertain to any part of
134
+ the Derivative Works; and
135
+
136
+ (d) If the Work includes a "NOTICE" text file as part of its
137
+ distribution, then any Derivative Works that You distribute must
138
+ include a readable copy of the attribution notices contained
139
+ within such NOTICE file, excluding those notices that do not
140
+ pertain to any part of the Derivative Works, in at least one
141
+ of the following places: within a NOTICE text file distributed
142
+ as part of the Derivative Works; within the Source form or
143
+ documentation, if provided along with the Derivative Works; or,
144
+ within a display generated by the Derivative Works, if and
145
+ wherever such third-party notices normally appear. The contents
146
+ of the NOTICE file are for informational purposes only and
147
+ do not modify the License. You may add Your own attribution
148
+ notices within Derivative Works that You distribute, alongside
149
+ or as an addendum to the NOTICE text from the Work, provided
150
+ that such additional attribution notices cannot be construed
151
+ as modifying the License.
152
+
153
+ You may add Your own copyright statement to Your modifications and
154
+ may provide additional or different license terms and conditions
155
+ for use, reproduction, or distribution of Your modifications, or
156
+ for any such Derivative Works as a whole, provided Your use,
157
+ reproduction, and distribution of the Work otherwise complies with
158
+ the conditions stated in this License.
159
+
160
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
161
+ any Contribution intentionally submitted for inclusion in the Work
162
+ by You to the Licensor shall be under the terms and conditions of
163
+ this License, without any additional terms or conditions.
164
+ Notwithstanding the above, nothing herein shall supersede or modify
165
+ the terms of any separate license agreement you may have executed
166
+ with Licensor regarding such Contributions.
167
+
168
+ 6. Trademarks. This License does not grant permission to use the trade
169
+ names, trademarks, service marks, or product names of the Licensor,
170
+ except as required for reasonable and customary use in describing the
171
+ origin of the Work and reproducing the content of the NOTICE file.
172
+
173
+ 7. Disclaimer of Warranty. Unless required by applicable law or
174
+ agreed to in writing, Licensor provides the Work (and each
175
+ Contributor provides its Contributions) on an "AS IS" BASIS,
176
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
177
+ implied, including, without limitation, any warranties or conditions
178
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
179
+ PARTICULAR PURPOSE. You are solely responsible for determining the
180
+ appropriateness of using or redistributing the Work and assume any
181
+ risks associated with Your exercise of permissions under this License.
182
+
183
+ 8. Limitation of Liability. In no event and under no legal theory,
184
+ whether in tort (including negligence), contract, or otherwise,
185
+ unless required by applicable law (such as deliberate and grossly
186
+ negligent acts) or agreed to in writing, shall any Contributor be
187
+ liable to You for damages, including any direct, indirect, special,
188
+ incidental, or consequential damages of any character arising as a
189
+ result of this License or out of the use or inability to use the
190
+ Work (including but not limited to damages for loss of goodwill,
191
+ work stoppage, computer failure or malfunction, or any and all
192
+ other commercial damages or losses), even if such Contributor
193
+ has been advised of the possibility of such damages.
194
+
195
+ 9. Accepting Warranty or Additional Liability. While redistributing
196
+ the Work or Derivative Works thereof, You may choose to offer,
197
+ and charge a fee for, acceptance of support, warranty, indemnity,
198
+ or other liability obligations and/or rights consistent with this
199
+ License. However, in accepting such obligations, You may act only
200
+ on Your own behalf and on Your sole responsibility, not on behalf
201
+ of any other Contributor, and only if You agree to indemnify,
202
+ defend, and hold each Contributor harmless for any liability
203
+ incurred by, or claims asserted against, such Contributor by reason
204
+ of your accepting any such warranty or additional liability.
205
+
206
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,25 @@
1
+ # @clawkeepers/gatekeeper-fs
2
+
3
+ Phase 3's first driver, currently at the **STOP 2 account/resource checkpoint**.
4
+ No OAuth or external credentials. Explicit `config.roots` is an allowlist; empty roots
5
+ deny all introductions. The kernel, not this package, authenticates the operator and
6
+ activates grants. Accounts are per-operator and revocable; no account lookup auto-grants access.
7
+
8
+ Implemented: original local-file URL validation, component-aware root containment,
9
+ symlink-component refusal, directory identity capture/revalidation, account revocation,
10
+ constructor-bound `KitGatekeeper` resources, metadata and deployment inputs. Titles omit host
11
+ paths. `resourceKey` is a canonical URL for private kernel storage, not an agent-facing title.
12
+
13
+ **No list/read/write operation is executable.** Session creation, action application and
14
+ observer verification fail closed. Directory identity checks establish an introduction-time
15
+ binding only; they are not a replacement-race defense for file I/O. The later use/apply
16
+ implementation must prove confinement (including hardlinks and parent replacement) or deny.
17
+ No check-then-open/realpath-only I/O is permitted by the approved contract.
18
+
19
+ The approved tools remain `gk_fs_dir_list`, `gk_fs_file_read`, `gk_fs_file_write`.
20
+ After STOP 2: kernel authorization, race-confined bounded UTF-8 I/O, pending overlays,
21
+ external-edit refusal on apply, and owner-only audience enforcement. Strategy `low-stakes`
22
+ does not grant sharing; no revert or automatic-write policy is offered.
23
+
24
+ Focused checkpoint: `scripts/vm/test.sh phase-3 installed fs-boundary` from the disposable
25
+ VM driver. This is explicitly **not full Phase 3 acceptance** and installs no runtime plugin.
@@ -0,0 +1,8 @@
1
+ {
2
+ "inputs": [],
3
+ "setupSteps": [
4
+ "Configure explicit absolute directory roots in plugins.entries.gatekeeper-fs.config.roots; the empty default denies access.",
5
+ "Only a trusted kernel operator introduction may activate a directory grant.",
6
+ "File operations remain disabled at the STOP 2 authoring checkpoint. No external credentials are needed."
7
+ ]
8
+ }
@@ -0,0 +1,17 @@
1
+ import * as openclaw_plugin_sdk_plugin_entry from 'openclaw/plugin-sdk/plugin-entry';
2
+
3
+ declare const _default: Omit<{
4
+ id: string;
5
+ name: string;
6
+ description: string;
7
+ kind?: openclaw_plugin_sdk_plugin_entry.OpenClawPluginDefinition["kind"];
8
+ configSchema?: openclaw_plugin_sdk_plugin_entry.OpenClawPluginConfigSchema | (() => openclaw_plugin_sdk_plugin_entry.OpenClawPluginConfigSchema);
9
+ reload?: openclaw_plugin_sdk_plugin_entry.OpenClawPluginDefinition["reload"];
10
+ nodeHostCommands?: openclaw_plugin_sdk_plugin_entry.OpenClawPluginDefinition["nodeHostCommands"];
11
+ securityAuditCollectors?: openclaw_plugin_sdk_plugin_entry.OpenClawPluginDefinition["securityAuditCollectors"];
12
+ register: NonNullable<openclaw_plugin_sdk_plugin_entry.OpenClawPluginDefinition["register"]>;
13
+ }, "configSchema"> & {
14
+ configSchema: openclaw_plugin_sdk_plugin_entry.OpenClawPluginConfigSchema;
15
+ };
16
+
17
+ export { _default as default };
package/dist/index.js ADDED
@@ -0,0 +1,571 @@
1
+ // src/index.ts
2
+ import { defineGatekeeper } from "@clawkeepers/gatekeeper-kit";
3
+
4
+ // src/vendor.ts
5
+ import { createHash as createHash3 } from "crypto";
6
+ import { join as join4 } from "path";
7
+
8
+ // src/account.ts
9
+ import { createHash as createHash2 } from "crypto";
10
+ import { join as join3 } from "path";
11
+
12
+ // src/directory.ts
13
+ import { join as join2 } from "path";
14
+ import { Value } from "typebox/value";
15
+ import { KitGatekeeper, OverlayStore } from "@clawkeepers/gatekeeper-kit";
16
+
17
+ // src/paths.ts
18
+ import { lstatSync } from "fs";
19
+ import { pathToFileURL } from "url";
20
+ function denied() {
21
+ return new Error("Filesystem resource unavailable.");
22
+ }
23
+ function directoryPath(value) {
24
+ if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//") || /[\\\u0000-\u001f\u007f]/u.test(value) || Buffer.byteLength(value, "utf8") > 4096 || Buffer.from(value, "utf8").toString("utf8") !== value) throw denied();
25
+ const path = value.length > 1 && value.endsWith("/") ? value.slice(0, -1) : value;
26
+ if (path !== "/" && path.slice(1).split("/").some((part) => !part || part === "." || part === "..")) throw denied();
27
+ return path;
28
+ }
29
+ function directoryUrl(value) {
30
+ if (typeof value !== "string" || value.length > 12300 || !value.startsWith("file:///") || /[?#\\\u0000-\u0020\u007f]/u.test(value) || /%(?:2f|5c)/iu.test(value)) throw denied();
31
+ try {
32
+ return directoryPath(decodeURIComponent(value.slice("file://".length)));
33
+ } catch {
34
+ throw denied();
35
+ }
36
+ }
37
+ function contains(root, path) {
38
+ return root === "/" || path === root || path.startsWith(`${root}/`);
39
+ }
40
+ function configuredRoots(config) {
41
+ if (Object.keys(config).some((key) => key !== "roots")) throw denied();
42
+ const roots = config.roots === void 0 ? [] : config.roots;
43
+ if (!Array.isArray(roots)) throw denied();
44
+ return [...new Set(roots.map(directoryPath))];
45
+ }
46
+ function identity(path) {
47
+ const stat = lstatSync(path, { bigint: true });
48
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw denied();
49
+ return { path, dev: stat.dev, ino: stat.ino };
50
+ }
51
+ var DirectoryBinding = class _DirectoryBinding {
52
+ constructor(path) {
53
+ this.path = path;
54
+ const paths = ["/"];
55
+ if (path !== "/") {
56
+ let current = "";
57
+ for (const part of path.slice(1).split("/")) {
58
+ current += `/${part}`;
59
+ paths.push(current);
60
+ }
61
+ }
62
+ this.chain = paths.map(identity);
63
+ this.assertCurrent();
64
+ }
65
+ chain;
66
+ /** Capture only existing directories, rejecting symlink components including those above the root. */
67
+ static capture(path) {
68
+ try {
69
+ return new _DirectoryBinding(directoryPath(path));
70
+ } catch {
71
+ throw denied();
72
+ }
73
+ }
74
+ /** Reject replacement/removal of the root, target, or any ancestor since introduction. */
75
+ assertCurrent() {
76
+ try {
77
+ for (const before of this.chain) {
78
+ const now = identity(before.path);
79
+ if (before.dev !== now.dev || before.ino !== now.ino) throw denied();
80
+ }
81
+ } catch {
82
+ throw denied();
83
+ }
84
+ }
85
+ /** Match a safely opened directory to the captured resource, not merely its current pathname. */
86
+ assertDescriptor(stat) {
87
+ const captured = this.chain.at(-1);
88
+ if (!stat.isDirectory() || stat.dev !== captured.dev || stat.ino !== captured.ino) throw denied();
89
+ }
90
+ /** Persistent instance identity includes every ancestor; replacement never inherits old pending actions. */
91
+ fingerprint() {
92
+ return JSON.stringify(this.chain.map(({ path, dev, ino }) => [path, String(dev), String(ino)]));
93
+ }
94
+ /** Private kernel resource identity, never an agent-facing title or tool result. */
95
+ key() {
96
+ return pathToFileURL(this.path).href;
97
+ }
98
+ };
99
+
100
+ // src/resources.ts
101
+ var fsResources = [{
102
+ type: "dir",
103
+ urlPattern: "file:///:path+",
104
+ title: "Directory",
105
+ description: "Read and write text files inside one directory tree.",
106
+ grantable: true,
107
+ observerStrategy: "low-stakes",
108
+ tools: ["gk_fs_dir_list", "gk_fs_file_read", "gk_fs_file_write"]
109
+ }];
110
+
111
+ // src/tools.ts
112
+ import { Type } from "typebox";
113
+ import { GrantHandle } from "@clawkeepers/shared";
114
+ var closed = { additionalProperties: false };
115
+ var relativePath = Type.String({ minLength: 1, maxLength: 4096 });
116
+ var fsTools = [
117
+ {
118
+ name: "gk_fs_dir_list",
119
+ resourceType: "dir",
120
+ kind: "observation",
121
+ description: "List the immediate files and folders in the directory or a relative subdirectory.",
122
+ parameters: Type.Object({ grant: GrantHandle, subpath: Type.Optional(relativePath) }, closed),
123
+ outputSchema: Type.Object({ entries: Type.Array(Type.Object({
124
+ name: Type.String(),
125
+ kind: Type.Enum(["file", "directory", "unavailable"])
126
+ }, closed), { maxItems: 1e3 }) }, closed)
127
+ },
128
+ {
129
+ name: "gk_fs_file_read",
130
+ resourceType: "dir",
131
+ kind: "observation",
132
+ description: "Read a UTF-8 text file of up to 1 MiB at a relative path inside the directory.",
133
+ parameters: Type.Object({ grant: GrantHandle, path: relativePath }, closed),
134
+ outputSchema: Type.Object({ path: relativePath, content: Type.String({ maxLength: 1048576 }) }, closed)
135
+ },
136
+ {
137
+ name: "gk_fs_file_write",
138
+ resourceType: "dir",
139
+ kind: "action",
140
+ description: "Create or replace a UTF-8 text file of up to 1 MiB at a relative path inside the directory.",
141
+ parameters: Type.Object({
142
+ grant: GrantHandle,
143
+ path: relativePath,
144
+ content: Type.String({ maxLength: 1048576 })
145
+ }, closed),
146
+ outputSchema: Type.Object({ path: relativePath, bytes: Type.Integer({ minimum: 0, maximum: 1048576 }) }, closed)
147
+ }
148
+ ];
149
+
150
+ // src/io.ts
151
+ import { constants as C, closeSync, fstatSync, lstatSync as lstatSync2, openSync, opendirSync, readSync, readlinkSync } from "fs";
152
+ import { TextDecoder } from "util";
153
+ import { createHash } from "crypto";
154
+ var MAX_BYTES = 1048576;
155
+ function relativePath2(value) {
156
+ if (typeof value !== "string" || !value || value.startsWith("/") || /[\\\u0000-\u001f\u007f]/u.test(value) || Buffer.byteLength(value) > 4096 || Buffer.from(value).toString("utf8") !== value || value.split("/").some((part) => !part || part === "." || part === "..")) throw denied();
157
+ return value;
158
+ }
159
+ function textBytes(value) {
160
+ if (typeof value !== "string") throw denied();
161
+ const bytes = Buffer.from(value, "utf8");
162
+ if (bytes.length > MAX_BYTES || bytes.includes(0) || bytes.toString("utf8") !== value) throw denied();
163
+ return bytes;
164
+ }
165
+ var stamp = (s) => [s.dev, s.ino, s.nlink, s.size, s.mtimeNs, s.ctimeNs].join(":");
166
+ var regular = (s) => s.isFile() && s.nlink === 1n && s.size <= BigInt(MAX_BYTES);
167
+ var dirFlags = C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW;
168
+ var fdPath = (fd) => `/proc/self/fd/${fd}`;
169
+ var ConfinedIO = class {
170
+ constructor(binding) {
171
+ this.binding = binding;
172
+ }
173
+ withDirectory(subpath, fn) {
174
+ const descriptors = [];
175
+ try {
176
+ if (process.platform !== "linux" || !C.O_NOFOLLOW || !C.O_DIRECTORY) throw denied();
177
+ this.binding.assertCurrent();
178
+ let fd = openSync("/", dirFlags);
179
+ descriptors.push(fd);
180
+ for (const part of this.binding.path.split("/").filter(Boolean)) {
181
+ fd = openSync(`${fdPath(fd)}/${part}`, dirFlags);
182
+ descriptors.push(fd);
183
+ }
184
+ this.binding.assertDescriptor(fstatSync(fd, { bigint: true }));
185
+ let expected = this.binding.path;
186
+ if (subpath !== void 0) for (const part of relativePath2(subpath).split("/")) {
187
+ fd = openSync(`${fdPath(fd)}/${part}`, dirFlags);
188
+ descriptors.push(fd);
189
+ expected = expected === "/" ? `/${part}` : `${expected}/${part}`;
190
+ }
191
+ if (readlinkSync(fdPath(fd)) !== expected) throw denied();
192
+ const value = fn(fd);
193
+ this.binding.assertCurrent();
194
+ if (readlinkSync(fdPath(fd)) !== expected) throw denied();
195
+ return value;
196
+ } catch {
197
+ throw denied();
198
+ } finally {
199
+ for (const fd of descriptors.reverse()) closeSync(fd);
200
+ }
201
+ }
202
+ withParent(path, fn) {
203
+ const parts = relativePath2(path).split("/"), name = parts.pop();
204
+ return this.withDirectory(parts.length ? parts.join("/") : void 0, (fd) => fn(fd, name));
205
+ }
206
+ /** Bounded read from a no-follow, single-link regular-file descriptor. Missing alone returns null. */
207
+ read(path) {
208
+ return this.withParent(path, (parent, name) => {
209
+ let fd;
210
+ try {
211
+ fd = openSync(`${fdPath(parent)}/${name}`, C.O_RDONLY | C.O_NOFOLLOW | C.O_NONBLOCK);
212
+ } catch (error) {
213
+ if (error.code === "ENOENT") return null;
214
+ throw denied();
215
+ }
216
+ try {
217
+ const before = fstatSync(fd, { bigint: true });
218
+ if (!regular(before)) throw denied();
219
+ const bytes = Buffer.alloc(MAX_BYTES + 1);
220
+ let total = 0;
221
+ while (total < bytes.length) {
222
+ const n = readSync(fd, bytes, total, bytes.length - total, total);
223
+ if (n === 0) break;
224
+ total += n;
225
+ }
226
+ const after = fstatSync(fd, { bigint: true });
227
+ const named = lstatSync2(`${fdPath(parent)}/${name}`, { bigint: true });
228
+ if (total > MAX_BYTES || !regular(after) || stamp(before) !== stamp(after) || stamp(after) !== stamp(named)) throw denied();
229
+ const body = bytes.subarray(0, total);
230
+ if (body.includes(0)) throw denied();
231
+ const content = new TextDecoder("utf-8", { fatal: true }).decode(body);
232
+ return { content, stamp: `${stamp(after)}:${createHash("sha256").update(body).digest("hex")}` };
233
+ } finally {
234
+ closeSync(fd);
235
+ }
236
+ });
237
+ }
238
+ /** Never recurse or follow entry symlinks; oversized directories fail, without partial results. */
239
+ list(subpath) {
240
+ return this.withDirectory(subpath, (parent) => {
241
+ const dir = opendirSync(fdPath(parent), { encoding: "utf8", bufferSize: 32 });
242
+ const entries = [];
243
+ try {
244
+ for (let entry = dir.readSync(); entry; entry = dir.readSync()) {
245
+ relativePath2(entry.name);
246
+ if (entry.name.includes("/")) throw denied();
247
+ if (entries.length === 1e3) throw denied();
248
+ const stat = lstatSync2(`${fdPath(parent)}/${entry.name}`, { bigint: true });
249
+ entries.push({ name: entry.name, kind: stat.isDirectory() ? "directory" : stat.isFile() && stat.nlink === 1n ? "file" : "unavailable" });
250
+ }
251
+ } finally {
252
+ dir.closeSync();
253
+ }
254
+ return entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
255
+ });
256
+ }
257
+ /** Verify the parent exists through the same anchored walk, without returning file data. */
258
+ checkParent(path) {
259
+ this.withParent(path, () => void 0);
260
+ }
261
+ /** No supported atomic confined compare-and-publish primitive: all host writes deny. */
262
+ create(_path, _content, _privateDir) {
263
+ throw denied();
264
+ }
265
+ };
266
+
267
+ // src/state.ts
268
+ import { closeSync as closeSync2, constants as C2, fsyncSync, lstatSync as lstatSync3, mkdirSync, openSync as openSync2, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
269
+ import { randomBytes } from "crypto";
270
+ import { dirname, join } from "path";
271
+ function privateDirectory(path) {
272
+ try {
273
+ mkdirSync(path, { recursive: true, mode: 448 });
274
+ DirectoryBinding.capture(path);
275
+ const stat = lstatSync3(path);
276
+ if ((stat.mode & 63) !== 0 || process.getuid && stat.uid !== process.getuid()) throw denied();
277
+ return path;
278
+ } catch {
279
+ throw denied();
280
+ }
281
+ }
282
+ function readState(path) {
283
+ let fd;
284
+ try {
285
+ fd = openSync2(path, C2.O_RDONLY | C2.O_NOFOLLOW);
286
+ return JSON.parse(readFileSync(fd, "utf8"));
287
+ } catch (e) {
288
+ if (e.code === "ENOENT") return void 0;
289
+ throw denied();
290
+ } finally {
291
+ if (fd !== void 0) closeSync2(fd);
292
+ }
293
+ }
294
+ function writeState(path, value) {
295
+ const dir = privateDirectory(dirname(path)), temp = join(dir, `.state-${randomBytes(16).toString("hex")}`);
296
+ let fd;
297
+ try {
298
+ fd = openSync2(temp, C2.O_CREAT | C2.O_EXCL | C2.O_WRONLY | C2.O_NOFOLLOW, 384);
299
+ writeFileSync(fd, JSON.stringify(value));
300
+ fsyncSync(fd);
301
+ closeSync2(fd);
302
+ fd = void 0;
303
+ renameSync(temp, path);
304
+ fd = openSync2(dir, C2.O_RDONLY | C2.O_DIRECTORY | C2.O_NOFOLLOW);
305
+ fsyncSync(fd);
306
+ } catch {
307
+ throw denied();
308
+ } finally {
309
+ if (fd !== void 0) closeSync2(fd);
310
+ try {
311
+ unlinkSync(temp);
312
+ } catch (e) {
313
+ if (e.code !== "ENOENT") throw denied();
314
+ }
315
+ }
316
+ }
317
+
318
+ // src/directory.ts
319
+ var observation = (title) => ({ title, description: "Read within the bound directory.", prohibitAllSharing: true });
320
+ function describeWrite(p) {
321
+ const path = relativePath2(p.path), bytes = textBytes(p.content).length;
322
+ return {
323
+ title: "Write text file",
324
+ description: "Write text within the bound directory. Host application is currently unavailable because atomic path and external-edit protection cannot be guaranteed.",
325
+ implementsRevert: false,
326
+ autoApprovable: false,
327
+ awaitDecision: false,
328
+ preview: { path, bytes }
329
+ };
330
+ }
331
+ var FsDirectory = class extends KitGatekeeper {
332
+ constructor(binding, accountLive, stateDir) {
333
+ super(join2(privateDirectory(stateDir), "actions.json"));
334
+ this.binding = binding;
335
+ this.accountLive = accountLive;
336
+ this.stateDir = stateDir;
337
+ this.overlay = new OverlayStore(join2(stateDir, "overlay.json"));
338
+ this.io = new ConfinedIO(binding);
339
+ this.observations = {
340
+ gk_fs_dir_list: { describe: () => observation("List directory"), read: async (p) => this.list(p.subpath) },
341
+ gk_fs_file_read: { describe: () => observation("Read text file"), read: async (p) => this.read(relativePath2(p.path)) }
342
+ };
343
+ this.actions = { gk_fs_file_write: {
344
+ describe: describeWrite,
345
+ simulate: async (p, overlay, id) => {
346
+ this.live();
347
+ const path = relativePath2(p.path), content = textBytes(p.content).toString("utf8");
348
+ const effectPath = join2(this.stateDir, `effect-${id}.json`), recovered = readState(effectPath);
349
+ if (recovered !== void 0) {
350
+ if (!recovered || typeof recovered !== "object" || !("path" in recovered) || !("content" in recovered) || recovered.path !== path || recovered.content !== content) throw denied();
351
+ overlay.add({ actionId: id, kind: "fs.write", payload: recovered });
352
+ return { path, bytes: Buffer.byteLength(content) };
353
+ }
354
+ const original = this.refresh(path);
355
+ const earlier = this.effects().filter((effect2) => effect2.path === path).at(-1);
356
+ const effect = { path, content, baseline: earlier?.baseline ?? original?.stamp ?? null };
357
+ writeState(effectPath, effect);
358
+ overlay.add({ actionId: id, kind: "fs.write", payload: effect });
359
+ return { path, bytes: Buffer.byteLength(content) };
360
+ },
361
+ apply: async () => {
362
+ throw denied();
363
+ }
364
+ } };
365
+ }
366
+ resource = structuredClone(fsResources[0]);
367
+ overlay;
368
+ io;
369
+ live() {
370
+ this.accountLive();
371
+ this.binding.assertCurrent();
372
+ }
373
+ /** Revalidate bound identity; no contents in metadata. */
374
+ async describe() {
375
+ this.live();
376
+ return { resource: structuredClone(this.resource), title: "Directory", suggestedName: "DIRECTORY" };
377
+ }
378
+ effects() {
379
+ return this.overlay.list().map((entry) => {
380
+ if (entry.kind !== "fs.write" || !entry.payload || typeof entry.payload !== "object") throw denied();
381
+ const effect = entry.payload;
382
+ relativePath2(effect.path);
383
+ textBytes(effect.content);
384
+ if (effect.baseline !== null && typeof effect.baseline !== "string") throw denied();
385
+ return effect;
386
+ });
387
+ }
388
+ refresh(path) {
389
+ this.live();
390
+ const current = this.io.read(path);
391
+ const cachePath = join2(this.stateDir, "cache.json"), stored = readState(cachePath);
392
+ let cached;
393
+ if (stored !== void 0) {
394
+ if (!stored || typeof stored !== "object" || !("path" in stored) || !("value" in stored)) throw denied();
395
+ cached = stored;
396
+ }
397
+ if (cached?.path !== path || JSON.stringify(cached.value) !== JSON.stringify(current)) writeState(cachePath, { path, value: current });
398
+ return current;
399
+ }
400
+ read(path) {
401
+ this.live();
402
+ const current = this.refresh(path), pending = this.effects().filter((effect) => effect.path === path).at(-1);
403
+ if (!pending && !current) throw denied();
404
+ return { path, content: pending ? pending.content : current.content };
405
+ }
406
+ list(raw) {
407
+ this.live();
408
+ const subpath = raw === void 0 ? void 0 : relativePath2(raw);
409
+ const entries = new Map(this.io.list(subpath).map((entry) => [entry.name, entry]));
410
+ for (const effect of this.effects()) {
411
+ const parts = effect.path.split("/"), name = parts.pop();
412
+ if (parts.join("/") !== (subpath ?? "")) continue;
413
+ if (entries.has(name) && entries.get(name).kind !== "file") throw denied();
414
+ entries.set(name, { name, kind: "file" });
415
+ }
416
+ if (entries.size > 1e3) throw denied();
417
+ return { entries: [...entries.values()].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0) };
418
+ }
419
+ /** No automatic filesystem write policy is offered. */
420
+ async getAutoApprovableActions() {
421
+ this.live();
422
+ return [];
423
+ }
424
+ /** Queue authority is supplied only by kernel resolveGrant; sessions recheck liveness and closed schemas on every call. */
425
+ async startSession(queue) {
426
+ this.live();
427
+ const session = await super.startSession(queue);
428
+ return { close: () => session.close(), call: async (tool, params, ctx) => {
429
+ this.live();
430
+ const definition = fsTools.find((def) => def.name === tool);
431
+ if (!definition || !Value.Check(definition.parameters, params)) throw denied();
432
+ const value = await session.call(tool, params, ctx);
433
+ this.live();
434
+ if (!ctx.dryRun && definition.kind === "observation") {
435
+ await queue.authorizeObservation(observation(tool === "gk_fs_dir_list" ? "List directory" : "Read text file"));
436
+ this.live();
437
+ }
438
+ return value;
439
+ } };
440
+ }
441
+ /** Deny before touching the journal: rejection remains possible, and no uncertain host write is claimed. */
442
+ async applyAction(_id) {
443
+ this.live();
444
+ throw denied();
445
+ }
446
+ /** Retire a pending effect without modifying host files. */
447
+ async rejectAction(id) {
448
+ this.live();
449
+ await super.rejectAction(id);
450
+ this.live();
451
+ }
452
+ /** Revert support is deliberately not advertised. */
453
+ async revertAction(_id) {
454
+ throw denied();
455
+ }
456
+ };
457
+
458
+ // src/account.ts
459
+ var FsAccount = class {
460
+ constructor(roots, onRevoke, stateDir, protectedRoot) {
461
+ this.roots = roots;
462
+ this.onRevoke = onRevoke;
463
+ this.stateDir = stateDir;
464
+ this.protectedRoot = protectedRoot;
465
+ }
466
+ active = true;
467
+ directories = /* @__PURE__ */ new Map();
468
+ assertLive = () => {
469
+ if (!this.active) throw denied();
470
+ };
471
+ async describe() {
472
+ this.assertLive();
473
+ return { displayName: "Local filesystem" };
474
+ }
475
+ async getSupportedResources() {
476
+ this.assertLive();
477
+ return structuredClone(fsResources);
478
+ }
479
+ /** Validate an operator introduction; this produces no grant and never creates a session. */
480
+ async getGatekeeperFor(url) {
481
+ this.assertLive();
482
+ const path = directoryUrl(url);
483
+ if (contains(path, this.protectedRoot) || contains(this.protectedRoot, path)) throw denied();
484
+ const root = this.roots.find((candidate) => contains(candidate.path, path));
485
+ if (!root) throw denied();
486
+ root.assertCurrent();
487
+ const binding = DirectoryBinding.capture(path);
488
+ root.assertCurrent();
489
+ this.assertLive();
490
+ const resourceKey = binding.key();
491
+ const identityPath = join3(privateDirectory(this.stateDir), `binding-${createHash2("sha256").update(resourceKey).digest("hex")}.json`);
492
+ const fingerprint = binding.fingerprint(), previous = readState(identityPath);
493
+ if (previous !== void 0 && previous !== fingerprint) throw denied();
494
+ if (previous === void 0) writeState(identityPath, fingerprint);
495
+ let gatekeeper = this.directories.get(resourceKey);
496
+ if (!gatekeeper) {
497
+ gatekeeper = new FsDirectory(binding, this.assertLive, join3(this.stateDir, createHash2("sha256").update(binding.fingerprint()).digest("hex")));
498
+ this.directories.set(resourceKey, gatekeeper);
499
+ }
500
+ await gatekeeper.describe();
501
+ this.assertLive();
502
+ return { gatekeeper, resource: structuredClone(fsResources[0]), resourceKey };
503
+ }
504
+ /** Sharing is unavailable; strategy metadata is not evidence of observer access. */
505
+ async getVerifier() {
506
+ throw denied();
507
+ }
508
+ /** Retained resources keep this account's liveness guard and cannot survive revocation. */
509
+ async revoke() {
510
+ if (!this.active) return;
511
+ this.active = false;
512
+ this.directories.clear();
513
+ this.onRevoke();
514
+ }
515
+ async reconnect() {
516
+ throw denied();
517
+ }
518
+ };
519
+
520
+ // src/vendor.ts
521
+ var FsVendor = class {
522
+ constructor(ctx) {
523
+ this.ctx = ctx;
524
+ this.roots = configuredRoots(ctx.pluginConfig);
525
+ }
526
+ vendor = "fs";
527
+ apiVersion = 1;
528
+ roots;
529
+ accounts = /* @__PURE__ */ new Map();
530
+ async describe() {
531
+ return { title: "Filesystem", description: "Scoped host directories.", autoProvisionsAccount: true };
532
+ }
533
+ async connectAccount() {
534
+ throw denied();
535
+ }
536
+ async createAccount(operatorId) {
537
+ if (!operatorId || operatorId.length > 512 || /[\u0000-\u001f\u007f]/u.test(operatorId)) throw denied();
538
+ const existing = this.accounts.get(operatorId);
539
+ if (existing) return existing;
540
+ const account = new FsAccount(this.roots.map((root) => DirectoryBinding.capture(root)), () => {
541
+ if (this.accounts.get(operatorId) === account) this.accounts.delete(operatorId);
542
+ }, join4(this.ctx.stateDir, "os", "gatekeepers", "fs", createHash3("sha256").update(operatorId).digest("hex")), this.ctx.stateDir);
543
+ this.accounts.set(operatorId, account);
544
+ return account;
545
+ }
546
+ async getAccount(operatorId) {
547
+ return this.accounts.get(operatorId) ?? null;
548
+ }
549
+ async getSupportedResources() {
550
+ return structuredClone(fsResources);
551
+ }
552
+ async getTools() {
553
+ return structuredClone(fsTools);
554
+ }
555
+ };
556
+
557
+ // src/index.ts
558
+ var index_default = defineGatekeeper({
559
+ vendor: "fs",
560
+ apiVersion: 1,
561
+ id: "gatekeeper-fs",
562
+ name: "Filesystem Gatekeeper",
563
+ description: "Mediates agent access to specific host directories.",
564
+ createVendor: (ctx) => new FsVendor(ctx),
565
+ actions: { gk_fs_file_write: { describe: describeWrite } },
566
+ resources: fsResources,
567
+ tools: fsTools
568
+ });
569
+ export {
570
+ index_default as default
571
+ };
@@ -0,0 +1,30 @@
1
+ {
2
+ "id": "gatekeeper-fs",
3
+ "name": "Filesystem Gatekeeper",
4
+ "description": "Mediates agent access to specific host directories.",
5
+ "contracts": {
6
+ "tools": []
7
+ },
8
+ "activation": {
9
+ "onStartup": true
10
+ },
11
+ "configSchema": {
12
+ "type": "object",
13
+ "additionalProperties": false,
14
+ "properties": {
15
+ "roots": {
16
+ "type": "array",
17
+ "items": {
18
+ "type": "string"
19
+ }
20
+ }
21
+ }
22
+ },
23
+ "clawos": {
24
+ "gatekeeper": {
25
+ "vendor": "fs",
26
+ "apiVersion": 1
27
+ }
28
+ },
29
+ "version": "0.1.0-beta.1"
30
+ }
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@clawkeepers/gatekeeper-fs",
3
+ "version": "0.1.0-beta.1",
4
+ "description": "Scoped host-directory gatekeeper for OpenClaw OS.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "LICENSE",
11
+ "NOTICE",
12
+ "README.md",
13
+ "openclaw.plugin.json",
14
+ "deploy-inputs.json"
15
+ ],
16
+ "dependencies": {
17
+ "typebox": "1.1.39",
18
+ "@clawkeepers/shared": "0.1.0-beta.1",
19
+ "@clawkeepers/gatekeeper-kit": "0.1.0-beta.1"
20
+ },
21
+ "peerDependencies": {
22
+ "openclaw": ">=2026.9.2 <2026.11.0"
23
+ },
24
+ "devDependencies": {
25
+ "tsup": "8.5.0",
26
+ "typescript": "5.9.2",
27
+ "vitest": "3.2.4",
28
+ "@types/node": "22.18.0"
29
+ },
30
+ "openclaw": {
31
+ "extensions": [
32
+ "./dist/index.js"
33
+ ],
34
+ "compat": {
35
+ "pluginApi": ">=2026.9.2 <2026.11.0",
36
+ "minGatewayVersion": "2026.9.2"
37
+ },
38
+ "build": {
39
+ "openclawVersion": "2026.9.2",
40
+ "pluginSdkVersion": "2026.9.2"
41
+ }
42
+ },
43
+ "license": "MIT",
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/clawkeeper/openclaw-os.git",
47
+ "directory": "packages/gatekeeper-fs"
48
+ },
49
+ "private": false,
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "exports": {
54
+ ".": {
55
+ "types": "./dist/index.d.ts",
56
+ "import": "./dist/index.js"
57
+ }
58
+ },
59
+ "engines": {
60
+ "node": ">=22.22.3"
61
+ },
62
+ "scripts": {
63
+ "build": "tsup src/index.ts --format esm --dts --clean",
64
+ "test": "vitest run",
65
+ "typecheck": "tsc -p tsconfig.json --noEmit",
66
+ "validate": "node ../../scripts/check-plugin-metadata.mjs ."
67
+ }
68
+ }