-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathdriver.ts
More file actions
291 lines (257 loc) · 7.53 KB
/
driver.ts
File metadata and controls
291 lines (257 loc) · 7.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import * as fs from "node:fs/promises";
import * as fsSync from "node:fs";
import path from "node:path";
import {
filterEnv,
} from "@secure-exec/core/internal/shared/permissions";
import { ModuleAccessFileSystem } from "./module-access.js";
import { NodeExecutionDriver } from "./execution-driver.js";
import {
createDefaultNetworkAdapter,
isPrivateIp,
} from "./default-network-adapter.js";
export type { DefaultNetworkAdapterOptions } from "./default-network-adapter.js";
import type {
OSConfig,
ProcessConfig,
} from "@secure-exec/core/internal/shared/api-types";
import type {
Permissions,
VirtualFileSystem,
} from "@secure-exec/core";
import { KernelError, O_CREAT, O_EXCL, O_TRUNC } from "@secure-exec/core";
import type {
CommandExecutor,
NetworkAdapter,
NodeRuntimeDriverFactory,
SystemDriver,
} from "@secure-exec/core";
import type { ModuleAccessOptions } from "./module-access.js";
/** Options for assembling a Node.js-backed SystemDriver. */
export interface NodeDriverOptions {
filesystem?: VirtualFileSystem;
moduleAccess?: ModuleAccessOptions;
networkAdapter?: NetworkAdapter;
commandExecutor?: CommandExecutor;
permissions?: Permissions;
useDefaultNetwork?: boolean;
/** Loopback ports that bypass SSRF checks when using the default network adapter (`useDefaultNetwork: true`). */
loopbackExemptPorts?: number[];
processConfig?: ProcessConfig;
osConfig?: OSConfig;
/** Include Node.js shims (fs, http, process, Buffer, etc.) on globalThis. Default: true. */
includeNodeShims?: boolean;
}
export interface NodeRuntimeDriverFactoryOptions {
createIsolate?(memoryLimit: number): unknown;
}
/** Thin VFS adapter that delegates directly to `node:fs/promises`. */
export class NodeFileSystem implements VirtualFileSystem {
prepareOpenSync(filePath: string, flags: number): boolean {
const hasCreate = (flags & O_CREAT) !== 0;
const hasExcl = (flags & O_EXCL) !== 0;
const hasTrunc = (flags & O_TRUNC) !== 0;
const exists = fsSync.existsSync(filePath);
if (hasCreate && hasExcl && exists) {
throw new KernelError("EEXIST", `file already exists, open '${filePath}'`);
}
let created = false;
if (!exists && hasCreate) {
fsSync.mkdirSync(path.dirname(filePath), { recursive: true });
fsSync.writeFileSync(filePath, new Uint8Array(0));
created = true;
}
if (hasTrunc) {
try {
fsSync.truncateSync(filePath, 0);
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code === "ENOENT") {
throw new KernelError("ENOENT", `no such file or directory, open '${filePath}'`);
}
if (err.code === "EISDIR") {
throw new KernelError("EISDIR", `illegal operation on a directory, open '${filePath}'`);
}
throw error;
}
}
return created;
}
async readFile(path: string): Promise<Uint8Array> {
return fs.readFile(path);
}
async readTextFile(path: string): Promise<string> {
return fs.readFile(path, "utf8");
}
async readDir(path: string): Promise<string[]> {
return fs.readdir(path);
}
async readDirWithTypes(
path: string,
): Promise<Array<{ name: string; isDirectory: boolean }>> {
const entries = await fs.readdir(path, { withFileTypes: true });
return entries.map((entry) => ({
name: entry.name,
isDirectory: entry.isDirectory(),
}));
}
async writeFile(path: string, content: string | Uint8Array): Promise<void> {
await fs.writeFile(path, content);
}
async createDir(path: string): Promise<void> {
await fs.mkdir(path);
}
async mkdir(path: string, _options?: { recursive?: boolean }): Promise<void> {
await fs.mkdir(path, { recursive: true });
}
async exists(path: string): Promise<boolean> {
try {
await fs.access(path);
return true;
} catch {
return false;
}
}
async stat(path: string) {
const info = await fs.stat(path);
return {
mode: info.mode,
size: info.size,
isDirectory: info.isDirectory(),
isSymbolicLink: false,
atimeMs: info.atimeMs,
mtimeMs: info.mtimeMs,
ctimeMs: info.ctimeMs,
birthtimeMs: info.birthtimeMs,
ino: info.ino,
nlink: info.nlink,
uid: info.uid,
gid: info.gid,
};
}
async removeFile(path: string): Promise<void> {
await fs.unlink(path);
}
async removeDir(path: string): Promise<void> {
await fs.rmdir(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
await fs.rename(oldPath, newPath);
}
async symlink(target: string, linkPath: string): Promise<void> {
await fs.symlink(target, linkPath);
}
async readlink(path: string): Promise<string> {
return fs.readlink(path);
}
async lstat(path: string) {
const info = await fs.lstat(path);
return {
mode: info.mode,
size: info.size,
isDirectory: info.isDirectory(),
isSymbolicLink: info.isSymbolicLink(),
atimeMs: info.atimeMs,
mtimeMs: info.mtimeMs,
ctimeMs: info.ctimeMs,
birthtimeMs: info.birthtimeMs,
ino: info.ino,
nlink: info.nlink,
uid: info.uid,
gid: info.gid,
};
}
async link(oldPath: string, newPath: string): Promise<void> {
await fs.link(oldPath, newPath);
}
async chmod(path: string, mode: number): Promise<void> {
await fs.chmod(path, mode);
}
async chown(path: string, uid: number, gid: number): Promise<void> {
await fs.chown(path, uid, gid);
}
async utimes(path: string, atime: number, mtime: number): Promise<void> {
await fs.utimes(path, atime, mtime);
}
async truncate(path: string, length: number): Promise<void> {
await fs.truncate(path, length);
}
async realpath(path: string): Promise<string> {
return fs.realpath(path);
}
async pread(path: string, offset: number, length: number): Promise<Uint8Array> {
const handle = await fs.open(path, "r");
try {
const buf = new Uint8Array(length);
const { bytesRead } = await handle.read(buf, 0, length, offset);
return buf.slice(0, bytesRead);
} finally {
await handle.close();
}
}
async pwrite(path: string, offset: number, data: Uint8Array): Promise<void> {
const handle = await fs.open(path, "r+");
try {
await handle.write(data, 0, data.length, offset);
} finally {
await handle.close();
}
}
}
/**
* Assemble a SystemDriver from Node.js-native adapters. Wraps the filesystem
* in a ModuleAccessFileSystem overlay and keeps capabilities deny-by-default
* unless explicit permissions are provided.
*/
export function createNodeDriver(options: NodeDriverOptions = {}): SystemDriver {
const filesystem = new ModuleAccessFileSystem(
options.filesystem,
options.moduleAccess ?? {},
);
const permissions = options.permissions;
const networkAdapter = options.networkAdapter
? options.networkAdapter
: options.useDefaultNetwork
? createDefaultNetworkAdapter(
options.loopbackExemptPorts?.length
? { initialExemptPorts: options.loopbackExemptPorts }
: undefined,
)
: undefined;
return {
filesystem,
network: networkAdapter,
commandExecutor: options.commandExecutor,
permissions,
runtime: {
process: {
...(options.processConfig ?? {}),
},
os: {
...(options.osConfig ?? {}),
},
// @ts-ignore-next-line — internal field used by NodeExecutionDriver to gate bridge shims
...(options.includeNodeShims !== undefined
? { includeNodeShims: options.includeNodeShims }
: {}),
},
};
}
export function createNodeRuntimeDriverFactory(
options: NodeRuntimeDriverFactoryOptions = {},
): NodeRuntimeDriverFactory {
return {
createRuntimeDriver: (runtimeOptions) =>
new NodeExecutionDriver({
...runtimeOptions,
createIsolate: options.createIsolate,
}),
};
}
export {
createDefaultNetworkAdapter,
filterEnv,
isPrivateIp,
NodeExecutionDriver,
};
export type { ModuleAccessOptions };