@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/src/wrap.ts
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
import * as nodeFs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { refusalMessage } from '@matatbread/matbot-plugin-api';
|
|
4
|
+
import type { ImportCaller } from '@matatbread/matbot-plugin-api';
|
|
5
|
+
import type { ImportedModuleWrapper } from '@matatbread/matbot-function-runner-node';
|
|
6
|
+
import { FD_CALLS, FLAG_OPTION, fsPathArgs, GLOB, globBases, openAccesses, PATHLESS, realResolve, refusal, toPath, type Access } from './paths.js';
|
|
7
|
+
import { admit, admitSync, DENIED, standingDenial, type Decisions, type OpenedFile } from './gate.js';
|
|
8
|
+
|
|
9
|
+
/** `node:fs` members that return synchronously though their names have no `Sync`: they cannot wait for an
|
|
10
|
+
* answer, so they are treated as synchronous calls. (`watch`'s listener is not a completion callback.) */
|
|
11
|
+
const RETURNS_SYNC = new Set(['watch', 'watchFile']);
|
|
12
|
+
|
|
13
|
+
/** `node:fs` members that return a promise though they live on the callback surface. */
|
|
14
|
+
const RETURNS_PROMISE = new Set(['openAsBlob']);
|
|
15
|
+
|
|
16
|
+
/** `node:fs/promises` members that return an async iterator, not a promise: the question is asked before
|
|
17
|
+
* the first item rather than before the call returns. */
|
|
18
|
+
const RETURNS_ITERATOR = new Set(['glob', 'watch']);
|
|
19
|
+
|
|
20
|
+
/** How many times a call is asked about again because a link on the way to its file keeps changing. */
|
|
21
|
+
const MAX_ASKS = 4;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* A call as it will be made: the arguments node is handed, with each path reduced to the string that was
|
|
25
|
+
* asked about, and what to ask. Nothing the body still holds is passed on where it could change what is
|
|
26
|
+
* opened, because the question and the call are apart by a tick at least, and by a human's whole answer at
|
|
27
|
+
* most: a `Buffer` rewritten, a `URL`'s `pathname` assigned, an array of patterns or an options getter
|
|
28
|
+
* answering differently the second time.
|
|
29
|
+
*/
|
|
30
|
+
interface Call {
|
|
31
|
+
args: unknown[];
|
|
32
|
+
checks: readonly (readonly [path: string, access: Access])[];
|
|
33
|
+
/** Run once the call is admitted, in the tick it is made: what has to hold of the filesystem as it is then. */
|
|
34
|
+
before?: () => void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A descriptor this invocation did not open through the gate. */
|
|
38
|
+
function notOpened(fd: number, op: string, who: string): Error {
|
|
39
|
+
return refusal(`fs.${op} of descriptor ${fd}: it was not opened by ${who} through node:fs, so it is not available. ` +
|
|
40
|
+
'A function may use only the descriptors it opens, and only until it closes them.');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* A stand-in for something of node's a body reaches by walking a prototype rather than by name: `.constructor`
|
|
45
|
+
* of a stream is node's own class, which opens any file unasked. It keeps the name and the `prototype`, so
|
|
46
|
+
* `x instanceof s.constructor` still holds, and refuses to be called or constructed.
|
|
47
|
+
*/
|
|
48
|
+
function standIn(name: string, prototype: unknown, instead: string): unknown {
|
|
49
|
+
const f = function (): never {
|
|
50
|
+
throw refusal(`${name}, reached through a prototype, is not available to a function body: it is node's own, ` +
|
|
51
|
+
`and would reach a file without asking. ${instead}`);
|
|
52
|
+
};
|
|
53
|
+
Object.defineProperty(f, 'name', { value: name });
|
|
54
|
+
Object.defineProperty(f, 'prototype', { value: prototype });
|
|
55
|
+
return f;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The runner's way to hide a property from a body ({@link ImportedModuleWrapper.hideFromBody}). */
|
|
59
|
+
export type HideFromBody = NonNullable<ImportedModuleWrapper['hideFromBody']>;
|
|
60
|
+
|
|
61
|
+
/** The class of `obj` (a stream, a watcher), hidden from bodies on its prototype. Host code is unaffected. */
|
|
62
|
+
function hideClassOf(hide: HideFromBody | undefined, proto: object, instead: string): void {
|
|
63
|
+
const cls = (proto as { constructor?: unknown }).constructor;
|
|
64
|
+
if (hide === undefined || typeof cls !== 'function') return;
|
|
65
|
+
hide(proto, 'constructor', standIn(cls.name, proto, instead));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The metadata a handle's methods change, which `fs-access` decides. */
|
|
69
|
+
const HANDLE_ACCESS = ['chmod', 'chown', 'utimes'] as const;
|
|
70
|
+
type Prepare = (args: readonly unknown[]) => Call;
|
|
71
|
+
|
|
72
|
+
/** The handles this plugin handed out: the one object that is not a path where a path goes
|
|
73
|
+
* (`fsp.readFile(handle)`), told apart by identity, since anything a body can spell it can also fake. */
|
|
74
|
+
const handles = new WeakSet<object>();
|
|
75
|
+
|
|
76
|
+
const copied = (o: unknown): unknown => typeof o === 'object' && o !== null ? { ...o } : o;
|
|
77
|
+
|
|
78
|
+
/** A stream's options as node reads them, read once. */
|
|
79
|
+
function streamOptions(o: unknown): Record<string, unknown> {
|
|
80
|
+
if (typeof o === 'string') return { encoding: o };
|
|
81
|
+
return o === undefined || o === null ? {} : { ...o as object };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The stream classes open their file on a later tick, from properties the body can assign, and `Utf8Stream`
|
|
86
|
+
* reopens on request — so a check of what the constructor was given says nothing about what is opened. All
|
|
87
|
+
* three take the fs they open with as an option, so they are given this invocation's, and every open they
|
|
88
|
+
* ever make is an ordinary guarded call: it asks about the path and flags as they stand when it happens. That
|
|
89
|
+
* also leaves no reference to the raw module on the stream. A body's own `fs` option is its own code, and is
|
|
90
|
+
* left in place; a `FileHandle` as `fd` opens nothing and refuses to be combined with one.
|
|
91
|
+
*/
|
|
92
|
+
type CheckFd = (fd: number) => void;
|
|
93
|
+
|
|
94
|
+
const STREAMS = {
|
|
95
|
+
ReadStream: fileStream('r'),
|
|
96
|
+
WriteStream: fileStream('w'),
|
|
97
|
+
Utf8Stream: (args: readonly unknown[], gatedFs: object, checkFd: CheckFd): Call => {
|
|
98
|
+
const opts = streamOptions(args[0]);
|
|
99
|
+
const given = opts['fd'] ?? opts['dest'];
|
|
100
|
+
if (typeof given === 'number') checkFd(given);
|
|
101
|
+
const target = toPath(given);
|
|
102
|
+
if (target === undefined) return { args: [{ ...opts, fs: opts['fs'] || gatedFs }], checks: [] };
|
|
103
|
+
const { fd: _fd, ...rest } = opts;
|
|
104
|
+
const accesses = opts['flags'] !== undefined ? openAccesses(opts['flags']) : ['write'] as const;
|
|
105
|
+
return { args: [{ ...rest, dest: target, fs: opts['fs'] || gatedFs }], checks: accesses.map(a => [target, a] as const) };
|
|
106
|
+
},
|
|
107
|
+
} as const;
|
|
108
|
+
type StreamName = keyof typeof STREAMS;
|
|
109
|
+
|
|
110
|
+
function fileStream(defaultFlags: string) {
|
|
111
|
+
return (args: readonly unknown[], gatedFs: object, checkFd: CheckFd): Call => {
|
|
112
|
+
const opts = streamOptions(args[1]);
|
|
113
|
+
const fd = opts['fd'];
|
|
114
|
+
if (typeof fd === 'number') checkFd(fd);
|
|
115
|
+
if (fd !== undefined && fd !== null) {
|
|
116
|
+
return { args: [undefined, typeof fd === 'object' ? opts : { ...opts, fs: opts['fs'] || gatedFs }], checks: [] };
|
|
117
|
+
}
|
|
118
|
+
const p = toPath(args[0]);
|
|
119
|
+
return {
|
|
120
|
+
args: [p ?? args[0], { ...opts, fs: opts['fs'] || gatedFs }],
|
|
121
|
+
checks: p === undefined ? [] : openAccesses(opts['flags'] ?? defaultFlags).map(a => [p, a] as const),
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Every name by which `node:fs` offers a stream class. */
|
|
127
|
+
const STREAM_NAMES = new Map<string, StreamName>([
|
|
128
|
+
['ReadStream', 'ReadStream'], ['FileReadStream', 'ReadStream'],
|
|
129
|
+
['WriteStream', 'WriteStream'], ['FileWriteStream', 'WriteStream'],
|
|
130
|
+
['Utf8Stream', 'Utf8Stream'],
|
|
131
|
+
]);
|
|
132
|
+
|
|
133
|
+
const STREAM_CALLS = new Map<string, StreamName>([['createReadStream', 'ReadStream'], ['createWriteStream', 'WriteStream']]);
|
|
134
|
+
|
|
135
|
+
interface GatedStream {
|
|
136
|
+
cls: new (...args: unknown[]) => unknown;
|
|
137
|
+
make: (op: string, args: unknown[]) => unknown;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const gatedStreams = new WeakMap<Decisions, Map<StreamName, GatedStream>>();
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* A stream class for one invocation. One per invocation and per class, so `instanceof` holds across the names
|
|
144
|
+
* a class has and the ways to reach it. Its instances inherit from a prototype whose `constructor` is this,
|
|
145
|
+
* because a stream's `constructor` is a name like any other: left alone, `new s.constructor(path)` is node's
|
|
146
|
+
* own class, asking nobody.
|
|
147
|
+
*/
|
|
148
|
+
function gatedStream(name: StreamName, st: Decisions, caller: ImportCaller, hide: HideFromBody | undefined): GatedStream {
|
|
149
|
+
let classes = gatedStreams.get(st);
|
|
150
|
+
if (classes === undefined) gatedStreams.set(st, classes = new Map());
|
|
151
|
+
const had = classes.get(name);
|
|
152
|
+
if (had !== undefined) return had;
|
|
153
|
+
|
|
154
|
+
const raw = (nodeFs as unknown as Record<string, new (...a: unknown[]) => unknown>)[name]!;
|
|
155
|
+
hideClassOf(hide, raw.prototype as object, `Use fs.${name} or the call that makes one, from the module you imported.`);
|
|
156
|
+
const gatedFs = wrapFsModule(nodeFs, 'fs', st, caller, hide);
|
|
157
|
+
const checkFd: CheckFd = fd => { if (!st.fds.has(fd)) throw notOpened(fd, name, caller.who); };
|
|
158
|
+
const construct = (op: string, args: unknown[], newTarget: object): unknown => {
|
|
159
|
+
const call = STREAMS[name](args, gatedFs, checkFd);
|
|
160
|
+
for (const [p, access] of call.checks) admitSync(st, caller, access, op, p);
|
|
161
|
+
return Reflect.construct(raw, call.args, newTarget as new (...a: unknown[]) => unknown);
|
|
162
|
+
};
|
|
163
|
+
// Called, too, which these classes allow.
|
|
164
|
+
const Gated = function (this: unknown, ...args: unknown[]): unknown {
|
|
165
|
+
return construct(name, args, new.target ?? Gated);
|
|
166
|
+
} as unknown as GatedStream['cls'];
|
|
167
|
+
Object.defineProperty(Gated, 'name', { value: name, configurable: true });
|
|
168
|
+
Gated.prototype = Object.create(raw.prototype as object, { constructor: { value: Gated, writable: true, configurable: true } }) as object;
|
|
169
|
+
|
|
170
|
+
const made: GatedStream = { cls: Gated, make: (op, args) => construct(op, args, Gated) };
|
|
171
|
+
classes.set(name, made);
|
|
172
|
+
return made;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Wrap an `fs`-shaped module in a Proxy that puts each path a call names to the gate before the real call
|
|
177
|
+
* runs, hands through what is known to take no path (constants, fd-based calls, `Dirent`…), and refuses any
|
|
178
|
+
* other function — one node added since the table was written (see {@link PATHLESS}).
|
|
179
|
+
*
|
|
180
|
+
* How a call is asked depends on whether it can wait:
|
|
181
|
+
* - a promise (`node:fs/promises`, `fs.promises`, `openAsBlob`) or a completion callback (`fs.readFile(p,
|
|
182
|
+
* cb)`) can, so it ASKS — a prompt when nothing standing decides — and a refusal rejects or reaches the
|
|
183
|
+
* callback as an `EACCES` error, as any fs failure would;
|
|
184
|
+
* - a synchronous call (`readFileSync`, `createReadStream`) cannot, so it consults the answers in force
|
|
185
|
+
* and THROWS when they do not allow it, saying how to be asked.
|
|
186
|
+
*
|
|
187
|
+
* What it holds against is a body USING the module, with nothing shared changed: see "What it is, and is not"
|
|
188
|
+
* in the README for the deliberate interference it does not.
|
|
189
|
+
*
|
|
190
|
+
* `hide` is the runner's {@link ImportedModuleWrapper.hideFromBody}. Without it node's own stream and watcher
|
|
191
|
+
* classes, and a file handle's own metadata methods, stay reachable to a body that walks a prototype.
|
|
192
|
+
*/
|
|
193
|
+
export function wrapFsModule<T extends object>(mod: T, kind: 'fs' | 'promises', st: Decisions, caller: ImportCaller, hide?: HideFromBody): T {
|
|
194
|
+
const withSync = kind === 'fs';
|
|
195
|
+
const pathArgs = fsPathArgs(withSync);
|
|
196
|
+
const globNames = new Set<string>(withSync ? GLOB : GLOB.filter(n => !n.endsWith('Sync')));
|
|
197
|
+
|
|
198
|
+
const prepareFor = (prop: string): Prepare | undefined => {
|
|
199
|
+
const fdUse = withSync ? FD_CALLS.get(prop) : undefined;
|
|
200
|
+
if (fdUse !== undefined) {
|
|
201
|
+
return given => {
|
|
202
|
+
const fd = given[0];
|
|
203
|
+
// Not a number: node rejects it, as it would have.
|
|
204
|
+
if (typeof fd !== 'number') return { args: [...given], checks: [] };
|
|
205
|
+
const opened = st.fds.get(fd);
|
|
206
|
+
if (opened === undefined) throw notOpened(fd, prop, caller.who);
|
|
207
|
+
return {
|
|
208
|
+
args: [...given],
|
|
209
|
+
checks: fdUse === 'access' ? [[opened.real, 'access']] : [],
|
|
210
|
+
...(fdUse === 'close' ? { before: () => { if (st.fds.get(fd) === opened) st.fds.delete(fd); } } : {}),
|
|
211
|
+
};
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
const indices = pathArgs.get(prop);
|
|
215
|
+
if (indices !== undefined) {
|
|
216
|
+
const flagAt = FLAG_OPTION.get(prop)?.[0];
|
|
217
|
+
const renames = prop === 'rename' || prop === 'renameSync';
|
|
218
|
+
return given => {
|
|
219
|
+
const args = [...given];
|
|
220
|
+
if (flagAt !== undefined) args[flagAt] = copied(args[flagAt]);
|
|
221
|
+
const read = new Map<number, string | undefined>();
|
|
222
|
+
const checks: (readonly [string, Access])[] = [];
|
|
223
|
+
for (const [i, access] of indices(args)) {
|
|
224
|
+
if (!read.has(i)) {
|
|
225
|
+
const arg = args[i];
|
|
226
|
+
// A descriptor where a path can go (`readFile(fd)`) is one the body must have opened.
|
|
227
|
+
if (typeof arg === 'number' && !st.fds.has(arg)) throw notOpened(arg, prop, caller.who);
|
|
228
|
+
const p = typeof arg === 'object' && arg !== null && handles.has(arg) ? undefined : toPath(arg);
|
|
229
|
+
read.set(i, p);
|
|
230
|
+
if (p !== undefined) args[i] = p;
|
|
231
|
+
}
|
|
232
|
+
const p = read.get(i);
|
|
233
|
+
if (p !== undefined) checks.push([p, access]);
|
|
234
|
+
}
|
|
235
|
+
const from = read.get(0);
|
|
236
|
+
return { args, checks, ...(renames && from !== undefined ? { before: () => refuseDeniedBeneath(from, prop) } : {}) };
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
if (globNames.has(prop)) {
|
|
240
|
+
return given => {
|
|
241
|
+
const patterns = Array.isArray(given[0]) ? [...given[0] as unknown[]] : given[0];
|
|
242
|
+
const opts = copied(given[1]) as { cwd?: unknown } | undefined;
|
|
243
|
+
const cwd = typeof opts === 'object' && opts !== null ? toPath(opts.cwd) : undefined;
|
|
244
|
+
if (cwd !== undefined) opts!.cwd = cwd;
|
|
245
|
+
return { args: [patterns, opts, ...given.slice(2)], checks: globBases(patterns, cwd).map(base => [base, 'read'] as const) };
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
return undefined;
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* A rename moves everything below its source, and an answer names a path, so a denial of something inside
|
|
253
|
+
* would no longer name it. Refused when anything inside is under a standing denial of any of the three gates,
|
|
254
|
+
* saying which and why. Undecided paths do not hold it up, so no rename asks about every file. A link is
|
|
255
|
+
* moved and not what it points at, so the walk does not follow one. Read in the tick of the call, with the
|
|
256
|
+
* filesystem as the rename will find it.
|
|
257
|
+
*/
|
|
258
|
+
const refuseDeniedBeneath = (arg: string, op: string): void => {
|
|
259
|
+
let isDir = false;
|
|
260
|
+
try { isDir = nodeFs.lstatSync(path.resolve(arg)).isDirectory(); } catch { /* not there: the rename reports it */ }
|
|
261
|
+
if (!isDir) return;
|
|
262
|
+
const pending = [realResolve(arg)];
|
|
263
|
+
for (let dir = pending.pop(); dir !== undefined; dir = pending.pop()) {
|
|
264
|
+
let entries: nodeFs.Dirent[];
|
|
265
|
+
try { entries = nodeFs.readdirSync(dir, { withFileTypes: true }); } catch { continue; }
|
|
266
|
+
for (const entry of entries) {
|
|
267
|
+
if (entry.isSymbolicLink()) continue;
|
|
268
|
+
const p = path.join(dir, entry.name);
|
|
269
|
+
for (const access of ['read', 'write', 'access'] as const) {
|
|
270
|
+
const denied = standingDenial(st, caller, access, op, p);
|
|
271
|
+
if (denied !== undefined) {
|
|
272
|
+
throw refusal(refusalMessage(denied,
|
|
273
|
+
`fs.${op} of "${arg}" would move "${p}", ${DENIED[access]}, out from under that answer`));
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (entry.isDirectory()) pending.push(p);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
/** A descriptor the body now holds, so it may use it, recorded with the file it was opened on. */
|
|
282
|
+
const opened = (fd: unknown, call: Call): OpenedFile | undefined => {
|
|
283
|
+
if (typeof fd !== 'number') return undefined;
|
|
284
|
+
const entry: OpenedFile = { real: realResolve(call.checks[0]?.[0] ?? '') };
|
|
285
|
+
st.fds.set(fd, entry);
|
|
286
|
+
return entry;
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Ask each path in turn (so a two-path call asks its questions one at a time), then run `act` in the same
|
|
291
|
+
* tick as the last look at where the paths lead. An answer is about a file, and a symlink on the way to it
|
|
292
|
+
* can be repointed while the question is open — by a body with write access beside it, deterministically,
|
|
293
|
+
* since it runs first. So a call whose path no longer leads where it did is asked about again. The window
|
|
294
|
+
* this leaves is the one between the look and the kernel's own walk of the path, which no path check closes.
|
|
295
|
+
*/
|
|
296
|
+
const whenAdmitted = async <R>(call: Call, op: string, act: () => R): Promise<R> => {
|
|
297
|
+
for (let asks = 0; asks < MAX_ASKS; asks++) {
|
|
298
|
+
const answered: string[] = [];
|
|
299
|
+
for (const [p, access] of call.checks) answered.push(await admit(st, caller, access, op, p));
|
|
300
|
+
if (call.checks.every(([p], i) => realResolve(p) === answered[i])) { call.before?.(); return act(); }
|
|
301
|
+
}
|
|
302
|
+
throw refusal(`fs.${op} of "${call.checks[0]?.[0]}": where this path leads keeps changing, so it cannot be asked about.`);
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* A handle's own stream methods are the classes by another name, so they make the gated ones. Its descriptor
|
|
307
|
+
* is the body's until the handle closes. The methods that change metadata ask `fs-access` about the file it was
|
|
308
|
+
* opened on, and the prototype's own versions of them are hidden from bodies, since they work on a handle
|
|
309
|
+
* opened only for reading.
|
|
310
|
+
*/
|
|
311
|
+
const handedOut = (h: nodeFs.promises.FileHandle, call: Call): object => {
|
|
312
|
+
handles.add(h);
|
|
313
|
+
const fd = h.fd;
|
|
314
|
+
const entry = opened(fd, call)!;
|
|
315
|
+
// A FileHandle is an EventEmitter that says when it closes, which its type declarations leave out.
|
|
316
|
+
(h as unknown as NodeJS.EventEmitter).once('close', () => { if (st.fds.get(fd) === entry) st.fds.delete(fd); });
|
|
317
|
+
const made = (name: StreamName, op: string) => (o?: object) =>
|
|
318
|
+
gatedStream(name, st, caller, hide).make(op, [undefined, { ...o, fd: h }]);
|
|
319
|
+
const proto = Object.getPrototypeOf(h) as Record<string, (...a: unknown[]) => unknown>;
|
|
320
|
+
const metadata = Object.fromEntries(HANDLE_ACCESS.map(m => {
|
|
321
|
+
const own = proto[m]!;
|
|
322
|
+
hide?.(proto, m, standIn(`FileHandle.${m}`, undefined, `Call handle.${m}(…) on the handle, which asks.`));
|
|
323
|
+
return [m, { value: async (...a: unknown[]): Promise<unknown> => {
|
|
324
|
+
await admit(st, caller, 'access', `FileHandle.${m}`, entry.real);
|
|
325
|
+
return Reflect.apply(own, h, a);
|
|
326
|
+
} }];
|
|
327
|
+
}));
|
|
328
|
+
Object.defineProperties(h, {
|
|
329
|
+
createReadStream: { value: made('ReadStream', 'createReadStream') },
|
|
330
|
+
createWriteStream: { value: made('WriteStream', 'createWriteStream') },
|
|
331
|
+
...metadata,
|
|
332
|
+
});
|
|
333
|
+
return h;
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
const guard = (fn: (...a: unknown[]) => unknown, op: string, prepare: Prepare) => {
|
|
337
|
+
if (kind === 'promises' && RETURNS_ITERATOR.has(op)) {
|
|
338
|
+
return async function* (...args: unknown[]): AsyncGenerator<unknown> {
|
|
339
|
+
const call = prepare(args);
|
|
340
|
+
yield* await whenAdmitted(call, op, () => Reflect.apply(fn, mod, call.args) as AsyncIterable<unknown>);
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
if (kind === 'promises' || RETURNS_PROMISE.has(op)) {
|
|
344
|
+
return async (...args: unknown[]): Promise<unknown> => {
|
|
345
|
+
const call = prepare(args);
|
|
346
|
+
const result = await whenAdmitted(call, op, () => Reflect.apply(fn, mod, call.args));
|
|
347
|
+
return op === 'open' ? handedOut(result as nodeFs.promises.FileHandle, call) : result;
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
const callSync = (args: unknown[]): unknown => {
|
|
351
|
+
const call = prepare(args);
|
|
352
|
+
for (const [p, access] of call.checks) admitSync(st, caller, access, op, p);
|
|
353
|
+
call.before?.();
|
|
354
|
+
const result = Reflect.apply(fn, mod, call.args);
|
|
355
|
+
if (op === 'openSync') opened(result, call);
|
|
356
|
+
// A watcher's class makes a watcher of anything, asking nobody; the one handed back is already watching.
|
|
357
|
+
if (op === 'watch' || op === 'watchFile') hideClassOf(hide, Object.getPrototypeOf(result) as object, `Use fs.${op}, which asks.`);
|
|
358
|
+
return result;
|
|
359
|
+
};
|
|
360
|
+
if (op.endsWith('Sync') || RETURNS_SYNC.has(op)) return (...args: unknown[]): unknown => callSync(args);
|
|
361
|
+
return (...args: unknown[]): unknown => {
|
|
362
|
+
const cb = args[args.length - 1];
|
|
363
|
+
// No completion callback: node rejects the call itself, so let it, after the synchronous check.
|
|
364
|
+
if (typeof cb !== 'function') return callSync(args);
|
|
365
|
+
// `exists` answers with a boolean, not an error, so a refusal reads as absent rather than present.
|
|
366
|
+
const fail = (e: unknown) => { (cb as (e: unknown) => void)(op === 'exists' ? false : e); };
|
|
367
|
+
let call: Call;
|
|
368
|
+
// In the caller's tick, or the path would be read after whatever the caller does next. A bad one is
|
|
369
|
+
// reported on a later tick, as a completion callback always is.
|
|
370
|
+
try { call = prepare(args); }
|
|
371
|
+
catch (e) { queueMicrotask(() => fail(e)); return undefined; }
|
|
372
|
+
if (op === 'open') {
|
|
373
|
+
// The descriptor it calls back with is the body's from then on.
|
|
374
|
+
const done = cb as (e: unknown, fd?: unknown) => void;
|
|
375
|
+
call.args[call.args.length - 1] = (e: unknown, fd?: unknown) => { if (e == null) opened(fd, call); done(e, fd); };
|
|
376
|
+
}
|
|
377
|
+
whenAdmitted(call, op, () => {
|
|
378
|
+
// Node throws a bad argument synchronously, which here is inside a promise the caller never
|
|
379
|
+
// sees: uncaught, it is an unhandled rejection that takes the process down. The callback is
|
|
380
|
+
// the one place the caller is listening.
|
|
381
|
+
try { Reflect.apply(fn, mod, call.args); } catch (e) { fail(e); }
|
|
382
|
+
}).catch(fail);
|
|
383
|
+
return undefined;
|
|
384
|
+
};
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
const member = (target: T, prop: string | symbol, receiver: unknown): unknown => {
|
|
388
|
+
const value = Reflect.get(target, prop, receiver);
|
|
389
|
+
if (typeof prop !== 'string' || typeof value !== 'function') {
|
|
390
|
+
if (typeof value === 'object' && value !== null) {
|
|
391
|
+
// `node:fs` exposes its promises API here; wrap it with the promises surface, sharing this
|
|
392
|
+
// invocation's answers.
|
|
393
|
+
if (prop === 'promises') return wrapFsModule(value as object, 'promises', st, caller, hide);
|
|
394
|
+
// A module namespace's CommonJS view: the whole module again, and the spelling
|
|
395
|
+
// `(await import('node:fs')).default` reaches for by habit.
|
|
396
|
+
if (prop === 'default') return wrapFsModule(value as object, kind, st, caller, hide);
|
|
397
|
+
}
|
|
398
|
+
return value;
|
|
399
|
+
}
|
|
400
|
+
if (withSync) {
|
|
401
|
+
const cls = STREAM_NAMES.get(prop);
|
|
402
|
+
if (cls !== undefined) return gatedStream(cls, st, caller, hide).cls;
|
|
403
|
+
const opens = STREAM_CALLS.get(prop);
|
|
404
|
+
if (opens !== undefined) return (...args: unknown[]) => gatedStream(opens, st, caller, hide).make(prop, args);
|
|
405
|
+
}
|
|
406
|
+
const prepare = prepareFor(prop);
|
|
407
|
+
if (prepare !== undefined) return guard(value as (...a: unknown[]) => unknown, prop, prepare);
|
|
408
|
+
if (PATHLESS.has(prop)) return value;
|
|
409
|
+
const unknown = (): never => {
|
|
410
|
+
throw refusal(`fs.${prop} is not available to ${caller.who}: whether it reaches a path is not known, so ` +
|
|
411
|
+
'nothing would ask about it. Use another fs call.');
|
|
412
|
+
};
|
|
413
|
+
return kind === 'promises' ? async () => unknown() : unknown;
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
// The module behind this Proxy is matbot's own, so it can be read only as guarded members and not written
|
|
417
|
+
// through: with no trap, a descriptor hands back the raw function, and an assignment reaches every other
|
|
418
|
+
// caller of `node:fs` in the process.
|
|
419
|
+
const self: T = new Proxy(mod, {
|
|
420
|
+
get: member,
|
|
421
|
+
getOwnPropertyDescriptor(target, prop) {
|
|
422
|
+
const d = Reflect.getOwnPropertyDescriptor(target, prop);
|
|
423
|
+
if (d === undefined) return undefined;
|
|
424
|
+
return { value: member(target, prop, self), writable: d.writable ?? false, enumerable: d.enumerable ?? false, configurable: d.configurable ?? false };
|
|
425
|
+
},
|
|
426
|
+
set: () => false,
|
|
427
|
+
defineProperty: () => false,
|
|
428
|
+
deleteProperty: () => false,
|
|
429
|
+
setPrototypeOf: () => false,
|
|
430
|
+
preventExtensions: () => false,
|
|
431
|
+
});
|
|
432
|
+
return self;
|
|
433
|
+
}
|