forked from hyperlight-dev/hyperagent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
632 lines (576 loc) · 21.3 KB
/
index.ts
File metadata and controls
632 lines (576 loc) · 21.3 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
// ── fs-write plugin ──────────────────────────────────────────────────
//
// Write-only filesystem access jailed to a SINGLE base directory.
// Guest JavaScript loads via: const fs = require("host:fs-write")
//
// Security model:
// - ONE base directory. Everything is scoped to it. Period.
// - If no baseDir is configured, we create a temp dir under
// os.tmpdir() — you get a sandbox, not the whole filesystem.
// - All paths are resolved to absolute; path traversal (..) is
// collapsed by resolve() then rejected if it escapes.
// - Symlinks are REJECTED outright (lstatSync + O_NOFOLLOW). The
// pre-check catches known symlinks; O_NOFOLLOW on the actual
// open() call closes the TOCTOU window for the leaf component.
// - Dotfiles are ALWAYS blocked — no configuration, no exceptions.
// - File size is capped and enforced cumulatively on append.
// - Entry creation is capped (maxEntries) — prevents inode/disk
// exhaustion from runaway writes. Tracks files + dirs combined.
// - mkdir creates a SINGLE directory — no recursive creation.
// - No delete operations — writes are create/overwrite/append only.
// - No read operations — use the companion fs-read plugin.
// - Error messages are sanitised — no raw OS paths leak to the guest.
//
// Split from the original fs-access plugin to allow independent
// approval of read vs write capabilities. This plugin contains ONLY
// write operations (writeFile, appendFile, mkdir). For read operations,
// see the companion fs-read plugin.
//
//
// ─────────────────────────────────────────────────────────────────────
import {
writeFileSync,
mkdirSync,
lstatSync,
fstatSync,
realpathSync,
existsSync,
openSync,
closeSync,
constants as FS_CONSTANTS,
} from "node:fs";
import { resolve, dirname, join } from "node:path";
import { tmpdir } from "node:os";
import { randomBytes } from "node:crypto";
import { validatePath, safeNumericConfig } from "../shared/path-jail.js";
import type { ConfigSchema, ConfigValues } from "../plugin-schema-types.js";
// ── Plugin Schema (source of truth) ─────────────────────────────────
/**
* Configuration schema for the fs-write plugin.
* This is the single source of truth — config types are derived from it.
*/
export const SCHEMA = {
baseDir: {
type: "string" as const,
description:
"Absolute path to the single base directory for all filesystem operations. If omitted, a unique temp directory is created automatically. Must not be a symlink.",
maxLength: 4096,
promptKey: true,
},
maxWriteSizeKb: {
type: "number" as const,
description:
"Maximum per-file cumulative size for writes/appends in kilobytes. Cumulative for appends (existing + new). Set to 0 to block non-empty writes. Clamped to 51200 (50 MB).",
default: 20480,
minimum: 0,
maximum: 51200,
},
maxEntries: {
type: "number" as const,
description:
"Maximum number of files and directories that can be created (combined total). Prevents inode/disk exhaustion from runaway writes. Set to 0 to block all creation. Clamped to 10000.",
default: 1000,
minimum: 0,
maximum: 10000,
},
} satisfies ConfigSchema;
// Hints are now in plugin.json (structured metadata).
// ── Configuration Types ─────────────────────────────────────────────
/** Configuration for the fs-write plugin (derived from SCHEMA). */
export type FsWriteConfig = ConfigValues<typeof SCHEMA>;
// ── Result Types ────────────────────────────────────────────────────
/** Result from writeFile() and appendFile(). */
export interface WriteResult {
/** True if write succeeded. */
ok?: boolean;
/** Error message if write failed. */
error?: string;
}
/** Result from mkdir(). */
export interface MkdirResult {
/** True if mkdir succeeded. */
ok?: boolean;
/** Error message if mkdir failed. */
error?: string;
}
// ── Constants ───────────────────────────────────────────────────────
/** Maximum allowed config value for size limits (50 MB). */
const MAX_SIZE_LIMIT_KB = 51200;
/**
* Maximum data accepted by a single writeFile/appendFile call (2 MB).
* Increased from 1MB to support larger single writes when output buffer is configured.
*/
const MAX_WRITE_CHUNK_KB = 2048;
/**
* Allowed encoding values for write operations.
*/
const ALLOWED_ENCODINGS = new Set(["utf8", "base64"]);
/** Maximum allowed config value for entry creation limit. */
const MAX_ENTRIES_LIMIT = 10000;
/** File creation mode — owner read/write only. */
const FILE_MODE = 0o600;
/** Length of random suffix for temp directory names. */
const TEMP_DIR_RANDOM_BYTES = 8;
// ── Host Function Interfaces ────────────────────────────────────────
/** The fs-write host functions interface. */
export interface FsWriteFunctions {
/** Write content to a file (creates or overwrites). */
writeFile: (path: string, content: string, encoding?: string) => WriteResult;
/** Append content to a file (creates if doesn't exist). */
appendFile: (path: string, content: string, encoding?: string) => WriteResult;
/** Write binary data to a file (throws on error). */
writeFileBinary: (
path: string,
data: Buffer | Uint8Array | ArrayBuffer,
) => WriteResult;
/** Append binary data to a file (throws on error). */
appendFileBinary: (
path: string,
data: Buffer | Uint8Array | ArrayBuffer,
) => WriteResult;
/** Create a directory (non-recursive). */
mkdir: (path: string) => MkdirResult;
}
/** Return type of createHostFunctions. */
export interface FsWriteHostFunctions {
"fs-write": FsWriteFunctions;
}
// ── Main Factory ────────────────────────────────────────────────────
/**
* Create the host functions for the fs-write plugin.
*
* SECURITY: This is a declarative API — the host calls this function
* and registers the returned functions itself. The plugin never gets
* access to the proto/sandbox object, closing the GAP 2 attack vector.
*
* @param config — Resolved plugin configuration
* @returns Host functions keyed by module name
*/
export function createHostFunctions(
config?: FsWriteConfig,
): FsWriteHostFunctions {
const cfg = config ?? {};
// ── Resolve the ONE base directory ───────────────────────────
let resolvedBase: string;
if (typeof cfg.baseDir === "string" && cfg.baseDir.trim().length > 0) {
const abs = resolve(cfg.baseDir.trim());
if (!existsSync(abs)) {
mkdirSync(abs, { recursive: true });
console.error(`[fs-write] Created baseDir: ${abs}`);
}
const lst = lstatSync(abs);
if (lst.isSymbolicLink()) {
throw new Error("[fs-write] baseDir must not be a symlink");
}
resolvedBase = realpathSync(abs);
} else {
const suffix = randomBytes(TEMP_DIR_RANDOM_BYTES).toString("hex");
resolvedBase = join(tmpdir(), `hyperlight-fs-${suffix}`);
mkdirSync(resolvedBase, { recursive: true });
console.error(
`[fs-write] No baseDir configured — using temp: ${resolvedBase}`,
);
}
const maxWriteBytes =
safeNumericConfig(cfg.maxWriteSizeKb, 20480, MAX_SIZE_LIMIT_KB) * 1024;
const maxWriteChunkBytes = MAX_WRITE_CHUNK_KB * 1024;
// O_NOFOLLOW atomically rejects symlinks at open() on POSIX.
// On Windows it doesn't exist — we rely on the lstatSync pre-check
// in validatePath() plus a post-open fstatSync/lstatSync comparison.
// The residual TOCTOU window is narrow and requires symlink creation
// privileges (SeCreateSymbolicLinkPrivilege or Developer Mode).
const O_NOFOLLOW = FS_CONSTANTS.O_NOFOLLOW ?? 0;
const maxEntries = Math.floor(
safeNumericConfig(cfg.maxEntries, 500, MAX_ENTRIES_LIMIT),
);
let entriesCreated = 0;
// ── Host function implementations ────────────────────────────
function writeFile(
filePath: string,
content: string,
encoding?: string,
): WriteResult {
const enc =
typeof encoding === "string" && ALLOWED_ENCODINGS.has(encoding)
? encoding
: "utf8";
const check = validatePath(filePath, resolvedBase);
if (!check.valid) {
return { error: check.error };
}
if (typeof content !== "string") {
return {
error:
"writeFile expects a string. For binary data (Uint8Array from " +
"createZip, etc.), use writeFileBinary(path, data) instead.",
};
}
const contentBytes =
enc === "base64"
? Math.ceil((content.length * 3) / 4)
: Buffer.byteLength(content, "utf8");
if (contentBytes > maxWriteChunkBytes) {
return {
error: `Content too large for single write: ${contentBytes} bytes exceeds per-call limit of ${MAX_WRITE_CHUNK_KB}KB. Split into multiple appendFile calls.`,
};
}
if (contentBytes > maxWriteBytes) {
return {
error: `Content too large: exceeds cumulative file write limit of ${maxWriteBytes / 1024}KB`,
};
}
let fd: number | undefined;
let isNew = false;
try {
const parentDir = dirname(check.realPath!);
if (!existsSync(parentDir)) {
return { error: "Parent directory does not exist" };
}
isNew = !existsSync(check.realPath!);
if (isNew) {
if (entriesCreated >= maxEntries) {
return {
error: `Entry limit reached: cannot create more than ${maxEntries} files/directories`,
};
}
entriesCreated++;
}
fd = openSync(
check.realPath!,
FS_CONSTANTS.O_WRONLY |
FS_CONSTANTS.O_CREAT |
FS_CONSTANTS.O_TRUNC |
FS_CONSTANTS.O_NOFOLLOW,
FILE_MODE,
);
const fdStat = fstatSync(fd);
if (!isNew && !fdStat.isFile()) {
return { error: "Not a regular file" };
}
if (enc === "base64") {
const buf = Buffer.from(content, "base64");
writeFileSync(fd, buf);
} else {
writeFileSync(fd, content, "utf8");
}
return { ok: true };
} catch (err: unknown) {
const e = err as NodeJS.ErrnoException | null;
if (isNew && !existsSync(check.realPath!)) entriesCreated--;
if (e?.code === "ENOENT") {
return { error: "Parent directory does not exist" };
}
if (e?.code === "ELOOP") {
return { error: "Access denied: symlinks are not permitted" };
}
return { error: "Write operation failed" };
} finally {
if (fd !== undefined) closeSync(fd);
}
}
function appendFile(
filePath: string,
content: string,
encoding?: string,
): WriteResult {
const enc =
typeof encoding === "string" && ALLOWED_ENCODINGS.has(encoding)
? encoding
: "utf8";
const check = validatePath(filePath, resolvedBase);
if (!check.valid) {
return { error: check.error };
}
if (typeof content !== "string") {
return {
error:
"appendFile expects a string. For binary data (Uint8Array), " +
"use appendFileBinary(path, data) instead.",
};
}
const contentBytes =
enc === "base64"
? Math.ceil((content.length * 3) / 4)
: Buffer.byteLength(content, "utf8");
if (contentBytes > maxWriteChunkBytes) {
return {
error: `Append content too large for single call: ${contentBytes} bytes exceeds per-call limit of ${MAX_WRITE_CHUNK_KB}KB. Split into smaller appendFile calls.`,
};
}
if (contentBytes > maxWriteBytes) {
return {
error: `Append would exceed cumulative file write limit of ${maxWriteBytes / 1024}KB`,
};
}
let fd: number | undefined;
let isNew = false;
try {
const parentDir = dirname(check.realPath!);
if (!existsSync(parentDir)) {
return { error: "Parent directory does not exist" };
}
isNew = !existsSync(check.realPath!);
if (isNew) {
if (entriesCreated >= maxEntries) {
return {
error: `Entry limit reached: cannot create more than ${maxEntries} files/directories`,
};
}
entriesCreated++;
}
fd = openSync(
check.realPath!,
FS_CONSTANTS.O_WRONLY |
FS_CONSTANTS.O_CREAT |
FS_CONSTANTS.O_APPEND |
FS_CONSTANTS.O_NOFOLLOW,
FILE_MODE,
);
const fdStat = fstatSync(fd);
if (!isNew && !fdStat.isFile()) {
return { error: "Not a regular file" };
}
if (fdStat.size + contentBytes > maxWriteBytes) {
return {
error: `Append would exceed cumulative file write limit of ${maxWriteBytes / 1024}KB (current: ${fdStat.size} bytes + new: ${contentBytes} bytes)`,
};
}
if (enc === "base64") {
const buf = Buffer.from(content, "base64");
writeFileSync(fd, buf);
} else {
writeFileSync(fd, content, "utf8");
}
return { ok: true };
} catch (err: unknown) {
const e = err as NodeJS.ErrnoException | null;
if (isNew && !existsSync(check.realPath!)) entriesCreated--;
if (e?.code === "ENOENT") {
return { error: "Parent directory does not exist" };
}
if (e?.code === "ELOOP") {
return { error: "Access denied: symlinks are not permitted" };
}
return { error: "Append operation failed" };
} finally {
if (fd !== undefined) closeSync(fd);
}
}
function writeFileBinary(
filePath: string,
data: Buffer | Uint8Array | ArrayBuffer | ArrayBufferView,
): WriteResult {
const check = validatePath(filePath, resolvedBase);
if (!check.valid) {
throw new Error(check.error);
}
let buf: Buffer;
if (Buffer.isBuffer(data)) {
buf = data;
} else if (data instanceof Uint8Array || ArrayBuffer.isView(data)) {
buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
} else if (data instanceof ArrayBuffer) {
buf = Buffer.from(data);
} else {
throw new Error(
"writeFileBinary expects binary data (Uint8Array from createZip, " +
"buildZip, etc.). For string content, use writeFile instead.",
);
}
const contentBytes = buf.length;
if (contentBytes > maxWriteChunkBytes) {
// Suggest exportToFile for PPTX/XLSX/DOCX files which can auto-chunk
const isPptx = filePath.toLowerCase().endsWith(".pptx");
const isOffice =
isPptx ||
filePath.toLowerCase().endsWith(".xlsx") ||
filePath.toLowerCase().endsWith(".docx");
const hint = isOffice
? ` For ${isPptx ? "PPTX" : "Office"} files, use exportToFile(pres, filename, fsWrite) from ha:pptx which handles chunking automatically.`
: " Split into multiple appendFileBinary calls.";
throw new Error(
`Content too large for single write: ${contentBytes} bytes exceeds ` +
`per-call limit of ${MAX_WRITE_CHUNK_KB}KB.${hint}`,
);
}
if (contentBytes > maxWriteBytes) {
throw new Error(
`Content too large: exceeds cumulative file write limit of ${maxWriteBytes / 1024}KB`,
);
}
let fd: number | undefined;
let isNew = false;
try {
const parentDir = dirname(check.realPath!);
if (!existsSync(parentDir)) {
throw new Error("Parent directory does not exist");
}
isNew = !existsSync(check.realPath!);
if (isNew) {
if (entriesCreated >= maxEntries) {
throw new Error(
`Entry limit reached: cannot create more than ${maxEntries} files/directories`,
);
}
entriesCreated++;
}
fd = openSync(
check.realPath!,
FS_CONSTANTS.O_WRONLY |
FS_CONSTANTS.O_CREAT |
FS_CONSTANTS.O_TRUNC |
FS_CONSTANTS.O_NOFOLLOW,
FILE_MODE,
);
const fdStat = fstatSync(fd);
if (!isNew && !fdStat.isFile()) {
throw new Error("Not a regular file");
}
writeFileSync(fd, buf);
return { ok: true };
} catch (err: unknown) {
const e = err as NodeJS.ErrnoException | null;
if (isNew && !existsSync(check.realPath!)) entriesCreated--;
if (e?.code === "ENOENT") {
throw new Error("Parent directory does not exist");
}
if (e?.code === "ELOOP") {
throw new Error("Access denied: symlinks are not permitted");
}
if (err instanceof Error && !("code" in err)) throw err;
throw new Error("Write operation failed");
} finally {
if (fd !== undefined) closeSync(fd);
}
}
function appendFileBinary(
filePath: string,
data: Buffer | Uint8Array | ArrayBuffer | ArrayBufferView,
): WriteResult {
const check = validatePath(filePath, resolvedBase);
if (!check.valid) {
throw new Error(check.error);
}
let buf: Buffer;
if (Buffer.isBuffer(data)) {
buf = data;
} else if (data instanceof Uint8Array || ArrayBuffer.isView(data)) {
buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
} else if (data instanceof ArrayBuffer) {
buf = Buffer.from(data);
} else {
throw new Error(
"appendFileBinary expects binary data (Uint8Array). " +
"For string content, use appendFile instead.",
);
}
const contentBytes = buf.length;
if (contentBytes > maxWriteChunkBytes) {
throw new Error(
`Append content too large for single call: ${contentBytes} bytes exceeds ` +
`per-call limit of ${MAX_WRITE_CHUNK_KB}KB. ` +
`Split into smaller appendFileBinary calls.`,
);
}
if (contentBytes > maxWriteBytes) {
throw new Error(
`Append would exceed cumulative file write limit of ${maxWriteBytes / 1024}KB`,
);
}
let fd: number | undefined;
let isNew = false;
try {
const parentDir = dirname(check.realPath!);
if (!existsSync(parentDir)) {
throw new Error("Parent directory does not exist");
}
isNew = !existsSync(check.realPath!);
if (isNew) {
if (entriesCreated >= maxEntries) {
throw new Error(
`Entry limit reached: cannot create more than ${maxEntries} files/directories`,
);
}
entriesCreated++;
}
fd = openSync(
check.realPath!,
FS_CONSTANTS.O_WRONLY |
FS_CONSTANTS.O_CREAT |
FS_CONSTANTS.O_APPEND |
FS_CONSTANTS.O_NOFOLLOW,
FILE_MODE,
);
const fdStat = fstatSync(fd);
if (!isNew && !fdStat.isFile()) {
throw new Error("Not a regular file");
}
if (fdStat.size + contentBytes > maxWriteBytes) {
throw new Error(
`Append would exceed cumulative file write limit of ` +
`${maxWriteBytes / 1024}KB (current: ${fdStat.size} bytes + new: ${contentBytes} bytes)`,
);
}
writeFileSync(fd, buf);
return { ok: true };
} catch (err: unknown) {
const e = err as NodeJS.ErrnoException | null;
if (isNew && !existsSync(check.realPath!)) entriesCreated--;
if (e?.code === "ENOENT") {
throw new Error("Parent directory does not exist");
}
if (e?.code === "ELOOP") {
throw new Error("Access denied: symlinks are not permitted");
}
if (err instanceof Error && !("code" in err)) throw err;
throw new Error("Append operation failed");
} finally {
if (fd !== undefined) closeSync(fd);
}
}
function mkdir(dirPath: string): MkdirResult {
const check = validatePath(dirPath, resolvedBase);
if (!check.valid) {
return { error: check.error };
}
try {
const parentDir = dirname(check.realPath!);
if (!existsSync(parentDir)) {
return { error: "Parent directory does not exist" };
}
if (entriesCreated >= maxEntries) {
return {
error: `Entry limit reached: cannot create more than ${maxEntries} files/directories`,
};
}
entriesCreated++;
mkdirSync(check.realPath!);
return { ok: true };
} catch (err: unknown) {
const e = err as NodeJS.ErrnoException | null;
if (entriesCreated > 0) entriesCreated--;
if (e?.code === "ENOENT") {
return { error: "Parent directory does not exist" };
}
if (e?.code === "EEXIST") {
return { error: "Directory already exists" };
}
return { error: "Mkdir operation failed" };
}
}
// Return the host functions keyed by module name
return {
"fs-write": {
writeFile,
appendFile,
writeFileBinary,
appendFileBinary,
mkdir,
},
};
}
// ── Test-only exports ────────────────────────────────────────────────
export {
validatePath as _validatePath,
safeNumericConfig as _safeNumericConfig,
};