@matatbread/matbot-gate-fs-node 0.0.0-stage → 0.5.0
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 +201 -0
- package/README.md +117 -2
- package/package.json +46 -3
- package/src/gate.ts +167 -0
- package/src/index.ts +63 -0
- package/src/paths.ts +290 -0
- package/src/wrap.ts +433 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Mat Woolf
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,118 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @matatbread/matbot-gate-fs-node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Puts each path a `tool_function` body's `node:fs` names to the permission gate.
|
|
4
|
+
|
|
5
|
+
Without it, a body that is granted `node:fs` (through the `tool_function.import` gate) can read and write every
|
|
6
|
+
path the matbot process can, including the `.env` vault and `.data` state. This plugin wraps the `node:fs`
|
|
7
|
+
and `node:fs/promises` modules a body receives (through the runner's `ImportedModuleWrapper` seam), so each
|
|
8
|
+
path the body names is asked about again:
|
|
9
|
+
|
|
10
|
+
- **`tool_function.fs-read`**, **`tool_function.fs-write`** and **`tool_function.fs-access`**: three
|
|
11
|
+
independent gates, so a grant to read a path doesn't allow changing it, and neither reading nor writing it
|
|
12
|
+
allows changing its permissions, owner or timestamps (`chmod`, `chown`, `utimes`), which is `fs-access`.
|
|
13
|
+
Writing includes creating, renaming and deleting.
|
|
14
|
+
- **subject `<function> <realpath>`**, keyed like the import gate's. Symlinks, `..` and relative paths are
|
|
15
|
+
resolved first, so a file has one subject however it is spelled, and a link can't lead out of a grant.
|
|
16
|
+
The realpath is the name as stored on disk, so on a volume that ignores case (macOS's default) `.ENV`
|
|
17
|
+
is asked about as `.env`. A subject you configure should be spelled as the path is stored; a **denial**
|
|
18
|
+
written in lower case also holds for every spelling on such a volume, including a file that does not
|
|
19
|
+
exist yet. Whether a volume ignores case is measured, once per device.
|
|
20
|
+
- **standing answers on offer:** the path itself, for this function or for **any** function (`* <path>`);
|
|
21
|
+
anything in its directory, for this function or for any function (`* <dir>/`). A directory grant covers everything below it. A body that moves
|
|
22
|
+
above it is asked again, and so is one that follows a symlink out of it, because the link is asked about
|
|
23
|
+
at its target. A grant for a file covers that file only, not `notes.txt.bak` beside it.
|
|
24
|
+
- **for this session or always:** "allow anything in `~/Photos/` for this session" is how a piece of work
|
|
25
|
+
reaches a directory without asking about every file, and without granting it for ever.
|
|
26
|
+
|
|
27
|
+
It uses the same `PermissionGate` and the same store of standing answers as every other gate, so there's no
|
|
28
|
+
separate setting. `gate_action` lists and clears these answers like any others. To pre-authorise, or to deny
|
|
29
|
+
outright, configure the gate:
|
|
30
|
+
|
|
31
|
+
```yaml
|
|
32
|
+
default_settings:
|
|
33
|
+
'@matatbread/matbot-default-gate':
|
|
34
|
+
'tool_function.fs-read': { '*': ['* /home/matt/project/src/'] }
|
|
35
|
+
'deny:tool_function.fs-read': { '*': ['* /home/matt/.ssh/', '* /home/matt/project/.env'] }
|
|
36
|
+
'deny:tool_function.fs-write': { '*': ['* /home/matt/project/'] }
|
|
37
|
+
'deny:tool_function.fs-access': { '*': ['* /home/matt/'] }
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`docs/SECURITY.md` (*A default setup for function bodies*) has a fuller example, including protecting
|
|
41
|
+
matbot's own files, which this plugin assumes nothing about.
|
|
42
|
+
|
|
43
|
+
`'*'` holds the answer everywhere. Where answers overlap, the most specific wins: the answer nearer the
|
|
44
|
+
path, then the one for this function before any function's. So a denial of a file or a directory inside a
|
|
45
|
+
granted one carves it out, whether the grant was for one function or for any, and a grant inside a denied
|
|
46
|
+
one reopens it. Nothing prompts you about a path a standing answer already allows, so a denial like that
|
|
47
|
+
is given with `gate_action deny`, which asks you to confirm it.
|
|
48
|
+
|
|
49
|
+
## Sync and async
|
|
50
|
+
|
|
51
|
+
- **Async calls** (`fs.promises.*`, `node:fs/promises`, and the callback form `fs.readFile(p, cb)`)
|
|
52
|
+
**ask**: a prompt appears when nothing standing decides. A refusal rejects, or reaches the callback, with
|
|
53
|
+
an `EACCES` error that says who refused. Questions within one invocation are asked one at a time, so a
|
|
54
|
+
`Promise.all` over a directory prompts once if the first answer covers the directory. An answer is
|
|
55
|
+
remembered for the rest of that invocation, so a refused path isn't asked about again on every pass of a
|
|
56
|
+
loop.
|
|
57
|
+
- **Sync calls** (`readFileSync`, `createReadStream`, …) **can't ask**: they block the thread a prompt
|
|
58
|
+
needs. They consult the answers in force when the body imported the module, plus any given since, and
|
|
59
|
+
throw `EACCES` when those don't allow the call. The error tells the body to use the async form so it can
|
|
60
|
+
be asked. A stream's later open is asynchronous, so a stream that has been repointed does ask, and a refusal
|
|
61
|
+
reaches it as an `error` event.
|
|
62
|
+
|
|
63
|
+
## What it is, and is not
|
|
64
|
+
|
|
65
|
+
A **guardrail** against an over-reaching body. It is **not a sandbox**.
|
|
66
|
+
|
|
67
|
+
**It holds against a body using the module**, which is what an over-eager model does. What is opened is what
|
|
68
|
+
was asked about, whatever the body then changes of its own:
|
|
69
|
+
|
|
70
|
+
- **A path is read once.** The string asked about is the one node gets, so a `Buffer` rewritten or a `URL`
|
|
71
|
+
reassigned after the call, even while a human is deciding, changes nothing. The same goes for a glob's
|
|
72
|
+
patterns and `cwd`, and for an options getter. A path that is not valid UTF-8 is refused, since no string
|
|
73
|
+
can name it.
|
|
74
|
+
- **A stream asks again when it opens**, about the path and flags as they stand then. Assigning `s.path` or
|
|
75
|
+
`s.flags`, or calling `Utf8Stream.reopen`, is asked about like any other call.
|
|
76
|
+
- **A flag is asked about as what it does.** `readFile(p, { flag: 'w' })` needs the write gate, because it
|
|
77
|
+
truncates. `open(p, 'r+')` needs both.
|
|
78
|
+
- **A link is followed.** A link changed while a question is open is asked about again at its new target, and a
|
|
79
|
+
dangling one is asked about at the file a write through it would create.
|
|
80
|
+
- **The module can't be read around or written through.** A property descriptor gives the guarded function, and
|
|
81
|
+
an assignment is refused. A stream's `constructor` is the guarded class, on a stream from a handle too.
|
|
82
|
+
- **Node's own classes are refused to a body.** A stream's or a watcher's class reached by walking prototypes,
|
|
83
|
+
and a file handle's own `chmod`, `chown` and `utimes`, refuse a body and say why. Host code still sees node's
|
|
84
|
+
own, so identity checks elsewhere in the process hold. This needs a runner whose `ImportedModuleWrapper` offers
|
|
85
|
+
`hideFromBody`, since only the runner knows which code is a body's. The node runner does; under one that does
|
|
86
|
+
not, these stay reachable, and everything else here still holds. (`util.inspect` names such a stream `Readable` rather
|
|
87
|
+
than `ReadStream`, being the one reader that looks past the property.)
|
|
88
|
+
- **A descriptor is the body's only if it opened it.** `read`, `write`, `fstat` and the other fd-based calls,
|
|
89
|
+
and a descriptor where a path goes, take only descriptors this invocation opened through the gate, until it
|
|
90
|
+
closes them. Any other number is a file the process has open for its own reasons. `fchmod`, `fchown` and
|
|
91
|
+
`futimes` ask `fs-access` about the file the descriptor was opened on.
|
|
92
|
+
- **A directory holding a denied path cannot be renamed**, since an answer names a path and the rename would
|
|
93
|
+
move the file out from under it. The error names the path and why. Only standing denials hold a rename up, so
|
|
94
|
+
it never asks about every file, and a link inside is moved rather than followed.
|
|
95
|
+
|
|
96
|
+
**It does not hold against code written to get past it.** Nothing here stops these, and a body shares matbot's
|
|
97
|
+
process, so no in-process wrapper can:
|
|
98
|
+
|
|
99
|
+
- **rewriting a built-in** the gate or the policy reads (`Map.prototype.get`, say), which is the tampering
|
|
100
|
+
`docs/SECURITY.md` describes;
|
|
101
|
+
- **a race**: a link repointed in the instant between the last look at a path and the kernel's own walk of it;
|
|
102
|
+
- **a hard link made outside matbot**, which is a second name for a file.
|
|
103
|
+
|
|
104
|
+
It also leaves these alone, by design:
|
|
105
|
+
|
|
106
|
+
- a **granted package** gets the raw `node:fs` (it is trusted as itself), so IO it does goes unasked;
|
|
107
|
+
- a body can reach another IO module (`node:child_process`), which this plugin doesn't touch;
|
|
108
|
+
- an operation that recurses (`rm`/`cp`/`readdir` with `recursive`, a `**` glob) on a granted directory acts on
|
|
109
|
+
what is inside it, including a path denied there. Keep what must never be reached outside any granted
|
|
110
|
+
directory.
|
|
111
|
+
|
|
112
|
+
Bounding what the **process** may touch, which is what holds against all of the above, is the deployment's job:
|
|
113
|
+
the OS user matbot runs as, a container, or node's `--permission` model (`--allow-fs-read` / `--allow-fs-write`).
|
|
114
|
+
See `docs/SECURITY.md`.
|
|
115
|
+
|
|
116
|
+
Needs a `FunctionRunner` that offers `ImportedModuleWrapper`; the node runner,
|
|
117
|
+
`@matatbread/matbot-function-runner-node`, does. Without one it does nothing. It takes the service from whichever
|
|
118
|
+
runner registered it, and depends on the node runner for types only.
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@matatbread/matbot-gate-fs-node",
|
|
3
|
-
"
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
"matbotRuntime": [
|
|
4
|
+
"node"
|
|
5
|
+
],
|
|
6
|
+
"version": "0.5.0",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=24.0.0"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src"
|
|
12
|
+
],
|
|
13
|
+
"description": "Node-only: confines a tool_function body's node:fs access to permitted paths by wrapping the imported module through ImportedModuleWrapper. A guardrail against an over-reaching body, not a sandbox. Optional; needs a FunctionRunner that offers ImportedModuleWrapper.",
|
|
14
|
+
"keywords": [
|
|
15
|
+
"matbot",
|
|
16
|
+
"matbot-plugin",
|
|
17
|
+
"llm",
|
|
18
|
+
"ai",
|
|
19
|
+
"agent",
|
|
20
|
+
"typescript"
|
|
21
|
+
],
|
|
22
|
+
"license": "Apache-2.0",
|
|
23
|
+
"type": "module",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": "./src/index.ts"
|
|
26
|
+
},
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "git+https://github.com/MatAtBread/matbot.git",
|
|
30
|
+
"directory": "plugins/gate-fs-node"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@types/node": "^22.0.0"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@matatbread/matbot-plugin-api": "^0.5.0"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@matatbread/matbot-plugin-api": "^0.5.0",
|
|
43
|
+
"@matatbread/matbot-function-runner-node": "^0.5.0",
|
|
44
|
+
"typescript": "^6.0.3"
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"typecheck": "tsc --noEmit"
|
|
48
|
+
}
|
|
6
49
|
}
|
package/src/gate.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import * as path from 'node:path';
|
|
2
|
+
import { refusalMessage } from '@matatbread/matbot-plugin-api';
|
|
3
|
+
import type { ImportCaller, PermissionDecision, PermissionRequest, PermissionSnapshot } from '@matatbread/matbot-plugin-api';
|
|
4
|
+
import { caseInsensitiveAt, directoryOf, realResolve, refusal, type Access } from './paths.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The question a path is put as. Gate `fs-read` or `fs-write` (qualified by the consumer as
|
|
8
|
+
* `tool_function.fs-read`), subject `<function> <realpath>` — the same shape as the import gate's, so one
|
|
9
|
+
* policy files and reports both.
|
|
10
|
+
*
|
|
11
|
+
* Standing answers, narrowest first: this path, this path for ANY function, everything in its directory,
|
|
12
|
+
* and that directory for any function. The file for any function is what excludes one file from a directory
|
|
13
|
+
* granted (`deny:tool_function.fs-read`: `* /home/me/project/.env` inside `* /home/me/project/`), and it
|
|
14
|
+
* comes before the function's own directory so that, at the same depth, the file is the narrower answer.
|
|
15
|
+
* Subjects are a hierarchy at `path.sep` (`PermissionRequest.separators`), so a directory
|
|
16
|
+
* answer covers everything below it, whatever directory a later request is in. A body reaching ABOVE a
|
|
17
|
+
* granted directory is asked again. The realpath keeps that sound: a symlink inside a granted tree that
|
|
18
|
+
* points out of it is asked about at its target. The `*` form is also how an installation configures a
|
|
19
|
+
* directory for every function, allow or deny, under `default_settings:`
|
|
20
|
+
* (`'tool_function.fs-read': { '*': ['* /home/me/project/'] }`, `'deny:tool_function.fs-read': { '*': ['* /home/me/.ssh/'] }`).
|
|
21
|
+
* The most specific answer wins, so a configured deny carves a subtree out of a broader grant, and an allow
|
|
22
|
+
* of one directory reopens it inside a broader deny. "For this session" is how a piece of work reaches a
|
|
23
|
+
* directory without granting it for ever.
|
|
24
|
+
*/
|
|
25
|
+
/** How each gate's act is said: a prompt's verb, and what a refusal says may not be done. */
|
|
26
|
+
export const VERB: Readonly<Record<Access, string>> = { read: 'read', write: 'write to', access: 'change the permissions, owner or timestamps of' };
|
|
27
|
+
export const DOING: Readonly<Record<Access, string>> = { read: 'reading', write: 'writing to', access: 'changing the permissions, owner or timestamps of' };
|
|
28
|
+
export const DENIED: Readonly<Record<Access, string>> = {
|
|
29
|
+
read: 'which may not be read', write: 'which may not be written to', access: 'whose permissions, owner and timestamps may not be changed',
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export function fsRequest(caller: Pick<ImportCaller, 'fn' | 'who'>, access: Access, op: string, real: string): PermissionRequest {
|
|
33
|
+
const dir = directoryOf(real);
|
|
34
|
+
const verb = VERB[access];
|
|
35
|
+
const { fn, who } = caller;
|
|
36
|
+
// A subject ending at the separator covers everything below it, so an answer for the root — even for
|
|
37
|
+
// "this path", `/` itself — would be an answer for every path: path gating switched off, from a prompt
|
|
38
|
+
// about one file. That is removing this plugin, and is said so rather than offered.
|
|
39
|
+
const atRoot = dir === path.parse(real).root;
|
|
40
|
+
return {
|
|
41
|
+
gate: `fs-${access}`,
|
|
42
|
+
subject: `${fn} ${real}`,
|
|
43
|
+
label: `Allow ${who} to ${verb} **${real}** (\`fs.${op}\`)?` +
|
|
44
|
+
(access === 'write' ? ' Writing includes creating, changing and deleting.' : ''),
|
|
45
|
+
fallback: false,
|
|
46
|
+
standing: [
|
|
47
|
+
{ subject: `${fn} ${real}`, label: `${who} to ${verb} ${real}` },
|
|
48
|
+
{ subject: `* ${real}`, label: `ANY function to ${verb} ${real}` },
|
|
49
|
+
...(atRoot ? [] : [
|
|
50
|
+
{ subject: `${fn} ${dir}`, label: `${who} to ${verb} anything in ${dir}` },
|
|
51
|
+
{ subject: `* ${dir}`, label: `ANY function to ${verb} anything in ${dir}` },
|
|
52
|
+
]),
|
|
53
|
+
],
|
|
54
|
+
separators: [path.sep],
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* What one invocation has learnt, shared by every module it imports (`node:fs` and `node:fs/promises` are
|
|
60
|
+
* two imports and one body). `snapshot` is what its synchronous calls consult; `memo` holds the answers it
|
|
61
|
+
* obtained, so a body reading one file in a loop is asked once — and a refused one is not asked again on
|
|
62
|
+
* every pass; `queue` serialises the questions, so a `Promise.all` over a directory asks one at a time and
|
|
63
|
+
* each later one sees an "Always … in this directory" given to an earlier one instead of prompting too.
|
|
64
|
+
* `fds` holds the descriptors the body opened through the gate, each with the realpath it was opened on.
|
|
65
|
+
*/
|
|
66
|
+
export interface Decisions {
|
|
67
|
+
snapshot: PermissionSnapshot;
|
|
68
|
+
readonly memo: Map<string, PermissionDecision>;
|
|
69
|
+
queue: Promise<unknown>;
|
|
70
|
+
readonly fds: Map<number, OpenedFile>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A descriptor the body opened, as the gate saw it. An object, so a late `close` of one descriptor can tell it
|
|
74
|
+
* from the next file given the same number. */
|
|
75
|
+
export interface OpenedFile { readonly real: string }
|
|
76
|
+
|
|
77
|
+
const perCaller = new WeakMap<ImportCaller, Promise<Decisions>>();
|
|
78
|
+
|
|
79
|
+
/** The invocation's {@link Decisions}, made at its first import — which is async, so the snapshot its
|
|
80
|
+
* synchronous calls need is taken there, before the body holds the module. */
|
|
81
|
+
export function decisionsFor(caller: ImportCaller): Promise<Decisions> {
|
|
82
|
+
let got = perCaller.get(caller);
|
|
83
|
+
if (got === undefined) {
|
|
84
|
+
got = caller.snapshot().then(snapshot => ({ snapshot, memo: new Map(), queue: Promise.resolve(), fds: new Map() }));
|
|
85
|
+
perCaller.set(caller, got);
|
|
86
|
+
}
|
|
87
|
+
return got;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const keyOf = (req: PermissionRequest): string => `${req.gate}\0${req.subject}`;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* On a volume that ignores case, a standing DENIAL of the path spelled in lower case. A subject is the name
|
|
94
|
+
* as stored on disk, which is what an answer given at a prompt names; one typed into the configuration in
|
|
95
|
+
* another case would otherwise never match, and on such a volume it names the same file. Lower case is
|
|
96
|
+
* the one other spelling a policy that compares strings can be asked about, so a denial written that way
|
|
97
|
+
* holds for every spelling — of a file that does not exist yet, too, which has no stored name to resolve
|
|
98
|
+
* to. Only a denial: folding an ALLOW would let one spelling stand for another.
|
|
99
|
+
*/
|
|
100
|
+
function foldedDenial(st: Decisions, caller: ImportCaller, access: Access, op: string, real: string): PermissionDecision | undefined {
|
|
101
|
+
const lower = real.toLowerCase();
|
|
102
|
+
if (lower === real || !caseInsensitiveAt(real)) return undefined;
|
|
103
|
+
const d = st.snapshot(fsRequest(caller, access, op, lower));
|
|
104
|
+
return !d.allowed && d.source !== 'fallback' ? d : undefined;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The root itself: see {@link fsRequest}. */
|
|
108
|
+
function refuseRoot(real: string, op: string, arg: string): void {
|
|
109
|
+
if (real !== path.parse(real).root) return;
|
|
110
|
+
throw refusal(`fs.${op} of "${arg}": the filesystem root is not asked about, since any answer for it would be an answer ` +
|
|
111
|
+
'for every path. To stop gating the paths a function body touches, remove the gate-fs-node plugin.');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Ask, prompting if nothing standing decides. For an asynchronous operation. Resolves to the file the answer
|
|
115
|
+
* is about, which by then may not be where `arg` leads: see `whenAdmitted` in wrap.ts. */
|
|
116
|
+
export async function admit(st: Decisions, caller: ImportCaller, access: Access, op: string, arg: string): Promise<string> {
|
|
117
|
+
const real = realResolve(arg);
|
|
118
|
+
refuseRoot(real, op, arg);
|
|
119
|
+
const denied = foldedDenial(st, caller, access, op, real);
|
|
120
|
+
if (denied !== undefined) throw refusal(refusalMessage(denied, `fs.${op} of "${arg}"`));
|
|
121
|
+
const req = fsRequest(caller, access, op, real);
|
|
122
|
+
const key = keyOf(req);
|
|
123
|
+
let decision = st.memo.get(key);
|
|
124
|
+
if (decision === undefined) {
|
|
125
|
+
const asking = st.queue.then(async () => {
|
|
126
|
+
const earlier = st.memo.get(key);
|
|
127
|
+
if (earlier !== undefined) return earlier;
|
|
128
|
+
const d = await caller.gate(req);
|
|
129
|
+
// A human answered, and may have answered "Always…": the synchronous calls see it from here on.
|
|
130
|
+
if (d.source === 'user') st.snapshot = await caller.snapshot();
|
|
131
|
+
st.memo.set(key, d);
|
|
132
|
+
return d;
|
|
133
|
+
});
|
|
134
|
+
st.queue = asking.catch(() => {});
|
|
135
|
+
decision = await asking;
|
|
136
|
+
}
|
|
137
|
+
if (!decision.allowed) throw refusal(refusalMessage(decision, `fs.${op} of "${arg}"`));
|
|
138
|
+
return real;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* A standing refusal of `access` to `real`: one in force for this invocation, from the policy or answered
|
|
143
|
+
* earlier in it. Not "nobody has decided", which would be asked about, and might be allowed.
|
|
144
|
+
*/
|
|
145
|
+
export function standingDenial(st: Decisions, caller: ImportCaller, access: Access, op: string, real: string): PermissionDecision | undefined {
|
|
146
|
+
const req = fsRequest(caller, access, op, real);
|
|
147
|
+
const d = foldedDenial(st, caller, access, op, real) ?? st.memo.get(keyOf(req)) ?? st.snapshot(req);
|
|
148
|
+
return !d.allowed && d.source !== 'fallback' ? d : undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Consult what was decided in advance, never asking. For a synchronous operation, which cannot. */
|
|
152
|
+
export function admitSync(st: Decisions, caller: ImportCaller, access: Access, op: string, arg: string): void {
|
|
153
|
+
const real = realResolve(arg);
|
|
154
|
+
refuseRoot(real, op, arg);
|
|
155
|
+
const req = fsRequest(caller, access, op, real);
|
|
156
|
+
const decision = foldedDenial(st, caller, access, op, real) ?? st.memo.get(keyOf(req)) ?? st.snapshot(req);
|
|
157
|
+
if (decision.allowed) return;
|
|
158
|
+
if (decision.source === 'fallback') {
|
|
159
|
+
const async = op.endsWith('Sync') ? `fs.promises.${op.slice(0, -'Sync'.length)}` : 'the fs.promises form';
|
|
160
|
+
throw refusal(
|
|
161
|
+
`fs.${op} of "${arg}": not permitted for ${caller.who}. A synchronous call cannot ask for permission, ` +
|
|
162
|
+
`and no standing answer allows ${DOING[access]} it. Use ${async} (or the ` +
|
|
163
|
+
`callback form) to be asked, or have a standing answer given for tool_function.fs-${access}.`,
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
throw refusal(refusalMessage(decision, `fs.${op} of "${arg}"`));
|
|
167
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { PLUGIN_API_VERSION } from '@matatbread/matbot-plugin-api';
|
|
2
|
+
import type { MatbotMachine, MatbotPluginSpec } from '@matatbread/matbot-plugin-api';
|
|
3
|
+
import type { WrapperHandle } from '@matatbread/matbot-function-runner-node';
|
|
4
|
+
import { wrapFsModule, type HideFromBody } from './wrap.js';
|
|
5
|
+
import { decisionsFor } from './gate.js';
|
|
6
|
+
|
|
7
|
+
export { wrapFsModule, type HideFromBody } from './wrap.js';
|
|
8
|
+
export { admit, admitSync, decisionsFor, fsRequest, type Decisions } from './gate.js';
|
|
9
|
+
export { caseInsensitiveAt, directoryOf, openAccesses, realResolve, type Access } from './paths.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* gate-fs-node — puts each path a `tool_function` body's `node:fs` names to the permission gate.
|
|
13
|
+
*
|
|
14
|
+
* The import gate asks whether a body may import `node:fs` at all; once it may, the module is granted
|
|
15
|
+
* whole — every path matbot's user can reach, `.env` and `.data` included. This plugin registers an
|
|
16
|
+
* {@link ImportedModuleWrapper} for `node:fs` and `node:fs/promises`, so the module a body receives asks
|
|
17
|
+
* again per path: `tool_function.fs-read`, `fs-write` or `fs-access`, keyed by the function and the
|
|
18
|
+
* path's realpath, through the same `PermissionGate` and the same store of standing answers as the import
|
|
19
|
+
* itself. There is no list of its own — what a body may touch without being asked is a standing answer,
|
|
20
|
+
* given at a prompt or configured under `default_settings:` for the gate.
|
|
21
|
+
*
|
|
22
|
+
* An asynchronous call asks (a prompt when nothing standing decides); a synchronous one cannot — it
|
|
23
|
+
* blocks the very thread a prompt needs — so it consults the answers in force when the module was
|
|
24
|
+
* imported, plus any given since, and throws when they do not allow it.
|
|
25
|
+
*
|
|
26
|
+
* **What it is.** A guardrail against an OVER-REACHING body: what a call opens is what was asked about,
|
|
27
|
+
* whatever the body then changes of its own. It is NOT a sandbox against hostile code: a body can rewrite a
|
|
28
|
+
* built-in the gate reads; a granted PACKAGE gets the raw `node:fs` (it is trusted as itself); and code can reach another IO module
|
|
29
|
+
* (`node:child_process`). Bounding what the PROCESS may touch is the deployment's — the OS user matbot runs
|
|
30
|
+
* as, a container, or node's `--permission` model. See the README and docs/SECURITY.md.
|
|
31
|
+
*
|
|
32
|
+
* Needs a `FunctionRunner` that offers `ImportedModuleWrapper` (the node runner does). Without one, the
|
|
33
|
+
* `mounted.observe` never fires and the plugin does nothing.
|
|
34
|
+
*/
|
|
35
|
+
export const plugin: MatbotPluginSpec = {
|
|
36
|
+
apiVersion: PLUGIN_API_VERSION,
|
|
37
|
+
|
|
38
|
+
async setup(services: MatbotMachine) {
|
|
39
|
+
// Registered through the mount table so it follows the runner: replay seeds it against the runner
|
|
40
|
+
// present now, and a remount replaces this plugin's registration rather than adding a second (a
|
|
41
|
+
// reloaded runner keeps the wrappers it had). The handles are withdrawn in teardown(), since a wrapper
|
|
42
|
+
// is not a host-tracked surface.
|
|
43
|
+
for (const spec of ['node:fs', 'node:fs/promises'] as const) {
|
|
44
|
+
services.mounted.observe({ key: 'ImportedModuleWrapper', replay: true }, m => {
|
|
45
|
+
const wrapper = m.ImportedModuleWrapper!;
|
|
46
|
+
// The runner's, since only it knows what code is a body's. A runner that does not offer it leaves
|
|
47
|
+
// node's own classes reachable by walking a prototype; everything else here holds without it.
|
|
48
|
+
const hide: HideFromBody | undefined = wrapper.hideFromBody === undefined
|
|
49
|
+
? undefined : (owner, key, standIn) => wrapper.hideFromBody!(owner, key, standIn);
|
|
50
|
+
handles.get(spec)?.remove();
|
|
51
|
+
handles.set(spec, wrapper.wrapModule(spec, async (mod, ctx) =>
|
|
52
|
+
wrapFsModule(mod as object, spec === 'node:fs' ? 'fs' : 'promises', await decisionsFor(ctx.caller), ctx.caller, hide)));
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
|
|
57
|
+
async teardown() {
|
|
58
|
+
for (const h of handles.values()) h.remove();
|
|
59
|
+
handles.clear();
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const handles = new Map<string, WrapperHandle>();
|