typescript-virtual-container 1.1.3 → 1.1.5

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/HONEYPOT.md +358 -0
  3. package/README.md +471 -16
  4. package/dist/SSHMimic/exec.d.ts.map +1 -1
  5. package/dist/SSHMimic/exec.js +8 -2
  6. package/dist/SSHMimic/index.d.ts +3 -1
  7. package/dist/SSHMimic/index.d.ts.map +1 -1
  8. package/dist/SSHMimic/index.js +21 -4
  9. package/dist/SSHMimic/sftp.d.ts +48 -0
  10. package/dist/SSHMimic/sftp.d.ts.map +1 -0
  11. package/dist/SSHMimic/sftp.js +595 -0
  12. package/dist/VirtualFileSystem/index.d.ts +8 -5
  13. package/dist/VirtualFileSystem/index.d.ts.map +1 -1
  14. package/dist/VirtualFileSystem/index.js +152 -154
  15. package/dist/VirtualShell/index.d.ts +8 -1
  16. package/dist/VirtualShell/index.d.ts.map +1 -1
  17. package/dist/VirtualShell/index.js +22 -5
  18. package/dist/VirtualShell/shell.d.ts.map +1 -1
  19. package/dist/VirtualShell/shell.js +7 -0
  20. package/dist/VirtualUserManager/index.d.ts +3 -1
  21. package/dist/VirtualUserManager/index.d.ts.map +1 -1
  22. package/dist/VirtualUserManager/index.js +34 -1
  23. package/dist/commands/exit.d.ts.map +1 -1
  24. package/dist/commands/exit.js +1 -0
  25. package/dist/honeypot.d.ts +132 -0
  26. package/dist/honeypot.d.ts.map +1 -0
  27. package/dist/honeypot.js +289 -0
  28. package/dist/index.d.ts +4 -2
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +3 -2
  31. package/dist/standalone.js +10 -1
  32. package/examples/README.md +210 -0
  33. package/examples/honeypot-audit.ts +180 -0
  34. package/examples/honeypot-export.ts +253 -0
  35. package/examples/honeypot-quickstart.ts +110 -0
  36. package/package.json +1 -1
  37. package/src/Honeypot/index.ts +422 -0
  38. package/src/SSHMimic/exec.ts +18 -12
  39. package/src/SSHMimic/index.ts +29 -8
  40. package/src/SSHMimic/sftp.ts +853 -0
  41. package/src/VirtualFileSystem/index.ts +167 -190
  42. package/src/VirtualShell/index.ts +25 -9
  43. package/src/VirtualShell/shell.ts +7 -0
  44. package/src/VirtualUserManager/index.ts +41 -3
  45. package/src/commands/exit.ts +1 -0
  46. package/src/index.ts +8 -1
  47. package/src/standalone.ts +11 -1
  48. package/tests/sftp.test.ts +319 -0
  49. package/tests/ssh-exec.test.ts +45 -0
@@ -0,0 +1,595 @@
1
+ /** biome-ignore-all lint/style/useNamingConvention: const as enum */
2
+ import { EventEmitter } from "node:events";
3
+ import * as path from "node:path";
4
+ import { Server as SshServer } from "ssh2";
5
+ import { VirtualShell } from "../VirtualShell";
6
+ import { loadOrCreateHostKey } from "./hostKey";
7
+ const SFTP_STATUS_CODE = {
8
+ OK: 0,
9
+ EOF: 1,
10
+ NO_SUCH_FILE: 2,
11
+ PERMISSION_DENIED: 3,
12
+ FAILURE: 4,
13
+ BAD_MESSAGE: 5,
14
+ NO_CONNECTION: 6,
15
+ CONNECTION_LOST: 7,
16
+ OP_UNSUPPORTED: 8,
17
+ };
18
+ const OPEN_MODE = {
19
+ READ: 0x00000001,
20
+ WRITE: 0x00000002,
21
+ APPEND: 0x00000004,
22
+ CREAT: 0x00000008,
23
+ TRUNC: 0x00000010,
24
+ EXCL: 0x00000020,
25
+ };
26
+ export class SftpMimic extends EventEmitter {
27
+ port;
28
+ server;
29
+ hostname;
30
+ shell;
31
+ vfs;
32
+ users;
33
+ nextHandleId = 0;
34
+ handles = new Map();
35
+ constructor({ port, hostname = "typescript-vm", shell, vfs, users, }) {
36
+ super();
37
+ this.port = port;
38
+ this.server = null;
39
+ this.hostname = hostname;
40
+ this.shell = null;
41
+ if (shell) {
42
+ this.vfs = shell.vfs;
43
+ this.users = shell.users;
44
+ this.hostname = shell.hostname;
45
+ this.shell = shell;
46
+ }
47
+ else if (vfs && users) {
48
+ this.vfs = vfs;
49
+ this.users = users;
50
+ }
51
+ else {
52
+ const defaultShell = new VirtualShell(hostname);
53
+ this.vfs = defaultShell.vfs;
54
+ this.users = defaultShell.users;
55
+ this.shell = defaultShell;
56
+ }
57
+ }
58
+ getVfs() {
59
+ return this.shell?.vfs ?? this.vfs;
60
+ }
61
+ getUsers() {
62
+ return this.shell?.users ?? this.users;
63
+ }
64
+ async start() {
65
+ const privateKey = loadOrCreateHostKey();
66
+ // Ensure VirtualShell is fully initialized before accepting connections
67
+ if (this.shell) {
68
+ await this.shell.ensureInitialized();
69
+ }
70
+ else {
71
+ // If using standalone VFS+Users, initialize users now
72
+ await this.users.initialize();
73
+ }
74
+ this.server = new SshServer({
75
+ hostKeys: [privateKey],
76
+ ident: `SSH-2.0-${this.hostname}`,
77
+ }, (client) => {
78
+ const allowedAuthMethods = [
79
+ "password",
80
+ "keyboard-interactive",
81
+ ];
82
+ let authUser = "root";
83
+ let sessionId = null;
84
+ let remoteAddress = "unknown";
85
+ this.emit("client:connect");
86
+ // Add error handling for the client
87
+ client.on("error", (error) => {
88
+ console.error(`[SFTP] Client error:`, error);
89
+ });
90
+ const acceptSession = (username) => {
91
+ authUser = username;
92
+ sessionId = this.getUsers().registerSession(authUser, remoteAddress).id;
93
+ const homeRoot = "/home";
94
+ if (!this.getVfs().exists(homeRoot)) {
95
+ this.getVfs().mkdir(homeRoot, 0o755);
96
+ }
97
+ const homePath = `/home/${authUser}`;
98
+ if (!this.getVfs().exists(homePath)) {
99
+ this.getVfs().mkdir(homePath, 0o755);
100
+ this.getVfs().writeFile(`${homePath}/README.txt`, `Welcome to ${this.hostname}`);
101
+ void this.getVfs().flushMirror();
102
+ }
103
+ };
104
+ client.on("authentication", (ctx) => {
105
+ const candidateUser = ctx.username || "root";
106
+ remoteAddress = ctx.ip ?? remoteAddress;
107
+ console.log(`[SFTP] Auth attempt: user=${candidateUser}, method=${ctx.method}, ip=${remoteAddress}`);
108
+ if (ctx.method === "password") {
109
+ if (!this.getUsers().verifyPassword(candidateUser, ctx.password ?? "")) {
110
+ this.emit("auth:failure", {
111
+ username: candidateUser,
112
+ remoteAddress,
113
+ });
114
+ ctx.reject(allowedAuthMethods);
115
+ return;
116
+ }
117
+ acceptSession(candidateUser);
118
+ this.emit("auth:success", { username: authUser, remoteAddress });
119
+ ctx.accept();
120
+ return;
121
+ }
122
+ if (ctx.method === "keyboard-interactive") {
123
+ const keyboardCtx = ctx;
124
+ keyboardCtx.prompt([{ prompt: "Password: ", echo: false }], (answers) => {
125
+ const password = answers[0] ?? "";
126
+ if (!this.getUsers().verifyPassword(candidateUser, password)) {
127
+ this.emit("auth:failure", {
128
+ username: candidateUser,
129
+ remoteAddress,
130
+ });
131
+ keyboardCtx.reject(allowedAuthMethods);
132
+ return;
133
+ }
134
+ acceptSession(candidateUser);
135
+ this.emit("auth:success", {
136
+ username: authUser,
137
+ remoteAddress,
138
+ });
139
+ keyboardCtx.accept();
140
+ });
141
+ return;
142
+ }
143
+ ctx.reject(allowedAuthMethods);
144
+ });
145
+ client.on("close", () => {
146
+ this.getUsers().unregisterSession(sessionId);
147
+ this.emit("client:disconnect", { user: authUser });
148
+ sessionId = null;
149
+ });
150
+ client.on("ready", () => {
151
+ client.on("session", (accept, _reject) => {
152
+ const session = accept();
153
+ // Add error handling for the session
154
+ session.on("error", (error) => {
155
+ console.error(`[SFTP] Session error for user=${authUser}:`, error);
156
+ });
157
+ session.on("sftp", (acceptSftp) => {
158
+ const sftp = acceptSftp();
159
+ this.attachSftpHandlers(sftp, authUser);
160
+ });
161
+ });
162
+ });
163
+ });
164
+ return new Promise((resolve, reject) => {
165
+ this.server?.once("error", (err) => reject(err));
166
+ this.server?.listen(this.port, "0.0.0.0", () => {
167
+ const address = this.server?.address();
168
+ const actualPort = address && typeof address === "object" && "port" in address
169
+ ? address.port
170
+ : this.port;
171
+ console.log(`SFTP Mimic listening on port ${actualPort}`);
172
+ this.emit("start", { port: actualPort });
173
+ resolve(actualPort);
174
+ });
175
+ });
176
+ }
177
+ stop() {
178
+ if (this.server) {
179
+ this.server.close(() => {
180
+ console.log("SFTP Mimic stopped");
181
+ this.emit("stop");
182
+ });
183
+ }
184
+ }
185
+ /**
186
+ * Resolves SFTP request paths with proper handling of relative paths.
187
+ * Relative paths (including ".") are resolved relative to the user's home directory.
188
+ * This is standard SFTP behavior where the "working directory" is always the home.
189
+ */
190
+ resolveRequestPath(requestPath, authUser) {
191
+ const homePath = `/home/${authUser}`;
192
+ // Empty path or "." → resolve to home directory
193
+ if (!requestPath || requestPath === ".") {
194
+ return homePath;
195
+ }
196
+ // Relative path (doesn't start with "/") → resolve relative to home
197
+ if (!requestPath.startsWith("/")) {
198
+ const joined = path.posix.join(homePath, requestPath);
199
+ return path.posix.normalize(joined);
200
+ }
201
+ // Absolute path → just normalize it
202
+ return path.posix.normalize(requestPath);
203
+ }
204
+ /**
205
+ * Verifies that a target path is confined within the user's home directory.
206
+ * This implements chroot-like behavior for security.
207
+ * @param targetPath - The normalized target path
208
+ * @param authUser - The authenticated username
209
+ * @returns true if path is within home, false if traversal attempt detected
210
+ */
211
+ isPathWithinHome(targetPath, authUser) {
212
+ const homePath = `/home/${authUser}`;
213
+ const normalized = path.posix.normalize(targetPath);
214
+ // Allow access to home directory itself
215
+ if (normalized === homePath) {
216
+ return true;
217
+ }
218
+ // Check if path is within home directory (starts with /home/username/)
219
+ if (normalized.startsWith(`${homePath}/`)) {
220
+ return true;
221
+ }
222
+ // Reject any attempt to escape home directory
223
+ return false;
224
+ }
225
+ createAttrs(node) {
226
+ const permissions = node.mode & 0o777;
227
+ const fileType = node.type === "directory" ? 0o040000 : 0o100000;
228
+ return {
229
+ mode: fileType | permissions,
230
+ size: node.type === "file" ? node.size : 0,
231
+ uid: 0,
232
+ gid: 0,
233
+ atime: Math.floor(node.createdAt.getTime() / 1000),
234
+ mtime: Math.floor(node.updatedAt.getTime() / 1000),
235
+ };
236
+ }
237
+ openHandle(handleValue) {
238
+ const handleId = ++this.nextHandleId;
239
+ const handle = Buffer.alloc(4);
240
+ handle.writeUInt32BE(handleId, 0);
241
+ this.handles.set(handle.toString("hex"), handleValue);
242
+ return handle;
243
+ }
244
+ getHandle(handle) {
245
+ return this.handles.get(handle.toString("hex"));
246
+ }
247
+ closeHandle(handle) {
248
+ this.handles.delete(handle.toString("hex"));
249
+ }
250
+ attachSftpHandlers(sftp, authUser) {
251
+ const getVfs = () => this.getVfs();
252
+ const getUsers = () => this.getUsers();
253
+ sftp.on("OPEN", (reqid, filename, flags) => {
254
+ const targetPath = this.resolveRequestPath(filename, authUser);
255
+ // Security: Confine to home directory
256
+ if (!this.isPathWithinHome(targetPath, authUser)) {
257
+ console.warn(`[SFTP] Path traversal attempt blocked: user=${authUser}, path=${targetPath}`);
258
+ sftp.status(reqid, SFTP_STATUS_CODE.PERMISSION_DENIED);
259
+ return;
260
+ }
261
+ const openMode = flags;
262
+ const _canRead = Boolean(openMode & OPEN_MODE.READ);
263
+ const _canWrite = Boolean(openMode & OPEN_MODE.WRITE || openMode & OPEN_MODE.APPEND);
264
+ const canCreate = Boolean(openMode & OPEN_MODE.CREAT);
265
+ const shouldTruncate = Boolean(openMode & OPEN_MODE.TRUNC);
266
+ try {
267
+ if (!getVfs().exists(targetPath)) {
268
+ if (!canCreate) {
269
+ sftp.status(reqid, SFTP_STATUS_CODE.NO_SUCH_FILE);
270
+ return;
271
+ }
272
+ getVfs().writeFile(targetPath, Buffer.alloc(0));
273
+ }
274
+ const stats = getVfs().stat(targetPath);
275
+ if (stats.type === "directory") {
276
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
277
+ return;
278
+ }
279
+ let buffer = Buffer.from(getVfs().readFile(targetPath), "utf8");
280
+ if (shouldTruncate) {
281
+ buffer = Buffer.alloc(0);
282
+ }
283
+ if (openMode & OPEN_MODE.APPEND) {
284
+ const handle = this.openHandle({
285
+ type: "file",
286
+ path: targetPath,
287
+ flags: openMode,
288
+ buffer,
289
+ });
290
+ sftp.handle(reqid, handle);
291
+ return;
292
+ }
293
+ const handle = this.openHandle({
294
+ type: "file",
295
+ path: targetPath,
296
+ flags: openMode,
297
+ buffer,
298
+ });
299
+ sftp.handle(reqid, handle);
300
+ }
301
+ catch (error) {
302
+ console.error("SFTP OPEN error:", error);
303
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
304
+ }
305
+ });
306
+ sftp.on("READ", (reqid, handle, offset, length) => {
307
+ const entry = this.getHandle(handle);
308
+ if (!entry || entry.type !== "file") {
309
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
310
+ return;
311
+ }
312
+ if (offset >= entry.buffer.length) {
313
+ sftp.status(reqid, SFTP_STATUS_CODE.EOF);
314
+ return;
315
+ }
316
+ const chunk = entry.buffer.slice(offset, offset + length);
317
+ sftp.data(reqid, chunk);
318
+ });
319
+ sftp.on("WRITE", async (reqid, handle, offset, data) => {
320
+ const entry = this.getHandle(handle);
321
+ if (!entry || entry.type !== "file") {
322
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
323
+ return;
324
+ }
325
+ const end = offset + data.length;
326
+ if (end > entry.buffer.length) {
327
+ const nextBuffer = Buffer.alloc(end);
328
+ entry.buffer.copy(nextBuffer, 0, 0, entry.buffer.length);
329
+ entry.buffer = nextBuffer;
330
+ }
331
+ data.copy(entry.buffer, offset);
332
+ sftp.status(reqid, SFTP_STATUS_CODE.OK);
333
+ });
334
+ sftp.on("FSTAT", (reqid, handle) => {
335
+ const entry = this.getHandle(handle);
336
+ if (!entry) {
337
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
338
+ return;
339
+ }
340
+ try {
341
+ const stats = getVfs().stat(entry.path);
342
+ sftp.attrs(reqid, this.createAttrs(stats));
343
+ }
344
+ catch {
345
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
346
+ }
347
+ });
348
+ sftp.on("CLOSE", async (reqid, handle) => {
349
+ const entry = this.getHandle(handle);
350
+ if (!entry) {
351
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
352
+ return;
353
+ }
354
+ if (entry.type === "file") {
355
+ try {
356
+ getUsers().assertWriteWithinQuota(authUser, entry.path, entry.buffer);
357
+ getVfs().writeFile(entry.path, entry.buffer);
358
+ void getVfs().flushMirror();
359
+ }
360
+ catch (error) {
361
+ console.error("SFTP CLOSE write error:", error);
362
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
363
+ this.closeHandle(handle);
364
+ return;
365
+ }
366
+ }
367
+ this.closeHandle(handle);
368
+ sftp.status(reqid, SFTP_STATUS_CODE.OK);
369
+ });
370
+ sftp.on("OPENDIR", (reqid, requestPath) => {
371
+ const targetPath = this.resolveRequestPath(requestPath, authUser);
372
+ // Security: Confine to home directory
373
+ if (!this.isPathWithinHome(targetPath, authUser)) {
374
+ console.warn(`[SFTP] Path traversal attempt blocked: user=${authUser}, path=${targetPath}`);
375
+ sftp.status(reqid, SFTP_STATUS_CODE.PERMISSION_DENIED);
376
+ return;
377
+ }
378
+ try {
379
+ const stats = getVfs().stat(targetPath);
380
+ if (stats.type !== "directory") {
381
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
382
+ return;
383
+ }
384
+ const entries = getVfs().list(targetPath);
385
+ const handle = this.openHandle({
386
+ type: "dir",
387
+ path: targetPath,
388
+ entries,
389
+ index: 0,
390
+ });
391
+ sftp.handle(reqid, handle);
392
+ }
393
+ catch {
394
+ sftp.status(reqid, SFTP_STATUS_CODE.NO_SUCH_FILE);
395
+ }
396
+ });
397
+ sftp.on("READDIR", (reqid, handle) => {
398
+ const entry = this.getHandle(handle);
399
+ if (!entry || entry.type !== "dir") {
400
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
401
+ return;
402
+ }
403
+ if (entry.index >= entry.entries.length) {
404
+ sftp.status(reqid, SFTP_STATUS_CODE.EOF);
405
+ return;
406
+ }
407
+ const filename = entry.entries[entry.index++];
408
+ const filePath = path.posix.join(entry.path, filename);
409
+ const stats = getVfs().stat(filePath);
410
+ const attrs = this.createAttrs(stats);
411
+ const longname = `${stats.type === "directory" ? "d" : "-"}${(stats.mode & 0o777).toString(8)} ${filename}`;
412
+ return sftp.name(reqid, [{ filename, longname, attrs }]);
413
+ });
414
+ sftp.on("STAT", (reqid, requestPath) => {
415
+ const targetPath = this.resolveRequestPath(requestPath, authUser);
416
+ // Security: Confine to home directory
417
+ if (!this.isPathWithinHome(targetPath, authUser)) {
418
+ console.warn(`[SFTP] Path traversal attempt blocked: user=${authUser}, path=${targetPath}`);
419
+ sftp.status(reqid, SFTP_STATUS_CODE.PERMISSION_DENIED);
420
+ return;
421
+ }
422
+ try {
423
+ const stats = getVfs().stat(targetPath);
424
+ sftp.attrs(reqid, this.createAttrs(stats));
425
+ }
426
+ catch {
427
+ sftp.status(reqid, SFTP_STATUS_CODE.NO_SUCH_FILE);
428
+ }
429
+ });
430
+ sftp.on("LSTAT", (reqid, requestPath) => {
431
+ const targetPath = this.resolveRequestPath(requestPath, authUser);
432
+ // Security: Confine to home directory
433
+ if (!this.isPathWithinHome(targetPath, authUser)) {
434
+ console.warn(`[SFTP] Path traversal attempt blocked: user=${authUser}, path=${targetPath}`);
435
+ sftp.status(reqid, SFTP_STATUS_CODE.PERMISSION_DENIED);
436
+ return;
437
+ }
438
+ try {
439
+ const stats = getVfs().stat(targetPath);
440
+ sftp.attrs(reqid, this.createAttrs(stats));
441
+ }
442
+ catch {
443
+ sftp.status(reqid, SFTP_STATUS_CODE.NO_SUCH_FILE);
444
+ }
445
+ });
446
+ sftp.on("FSETSTAT", (reqid, handle, attrs) => {
447
+ const entry = this.getHandle(handle);
448
+ if (!entry) {
449
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
450
+ return;
451
+ }
452
+ try {
453
+ if (attrs.mode !== undefined) {
454
+ getVfs().chmod(entry.path, attrs.mode);
455
+ }
456
+ sftp.status(reqid, SFTP_STATUS_CODE.OK);
457
+ }
458
+ catch {
459
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
460
+ }
461
+ });
462
+ sftp.on("SETSTAT", (reqid, requestPath, attrs) => {
463
+ const targetPath = this.resolveRequestPath(requestPath, authUser);
464
+ // Security: Confine to home directory
465
+ if (!this.isPathWithinHome(targetPath, authUser)) {
466
+ console.warn(`[SFTP] Path traversal attempt blocked: user=${authUser}, path=${targetPath}`);
467
+ sftp.status(reqid, SFTP_STATUS_CODE.PERMISSION_DENIED);
468
+ return;
469
+ }
470
+ try {
471
+ if (attrs.mode !== undefined) {
472
+ getVfs().chmod(targetPath, attrs.mode);
473
+ }
474
+ sftp.status(reqid, SFTP_STATUS_CODE.OK);
475
+ }
476
+ catch {
477
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
478
+ }
479
+ });
480
+ sftp.on("REALPATH", (reqid, requestPath) => {
481
+ const normalized = this.resolveRequestPath(requestPath, authUser);
482
+ // Security: Confine to home directory
483
+ if (!this.isPathWithinHome(normalized, authUser)) {
484
+ console.warn(`[SFTP] Path traversal attempt blocked: user=${authUser}, path=${normalized}`);
485
+ sftp.status(reqid, SFTP_STATUS_CODE.PERMISSION_DENIED);
486
+ return;
487
+ }
488
+ sftp.name(reqid, [
489
+ {
490
+ filename: normalized,
491
+ longname: normalized,
492
+ attrs: {
493
+ mode: 0o040755,
494
+ uid: 0,
495
+ gid: 0,
496
+ size: 0,
497
+ atime: 0,
498
+ mtime: 0,
499
+ },
500
+ },
501
+ ]);
502
+ });
503
+ sftp.on("MKDIR", (reqid, requestPath) => {
504
+ const targetPath = this.resolveRequestPath(requestPath, authUser);
505
+ // Security: Confine to home directory
506
+ if (!this.isPathWithinHome(targetPath, authUser)) {
507
+ console.warn(`[SFTP] Path traversal attempt blocked: user=${authUser}, path=${targetPath}`);
508
+ sftp.status(reqid, SFTP_STATUS_CODE.PERMISSION_DENIED);
509
+ return;
510
+ }
511
+ try {
512
+ getVfs().mkdir(targetPath, 0o755);
513
+ void getVfs().flushMirror();
514
+ sftp.status(reqid, SFTP_STATUS_CODE.OK);
515
+ }
516
+ catch {
517
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
518
+ }
519
+ });
520
+ sftp.on("RMDIR", (reqid, requestPath) => {
521
+ const targetPath = this.resolveRequestPath(requestPath, authUser);
522
+ // Security: Confine to home directory
523
+ if (!this.isPathWithinHome(targetPath, authUser)) {
524
+ console.warn(`[SFTP] Path traversal attempt blocked: user=${authUser}, path=${targetPath}`);
525
+ sftp.status(reqid, SFTP_STATUS_CODE.PERMISSION_DENIED);
526
+ return;
527
+ }
528
+ try {
529
+ getVfs().remove(targetPath, { recursive: false });
530
+ void getVfs().flushMirror();
531
+ sftp.status(reqid, SFTP_STATUS_CODE.OK);
532
+ }
533
+ catch {
534
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
535
+ }
536
+ });
537
+ sftp.on("REMOVE", (reqid, requestPath) => {
538
+ const targetPath = this.resolveRequestPath(requestPath, authUser);
539
+ // Security: Confine to home directory
540
+ if (!this.isPathWithinHome(targetPath, authUser)) {
541
+ console.warn(`[SFTP] Path traversal attempt blocked: user=${authUser}, path=${targetPath}`);
542
+ sftp.status(reqid, SFTP_STATUS_CODE.PERMISSION_DENIED);
543
+ return;
544
+ }
545
+ try {
546
+ getVfs().remove(targetPath, { recursive: false });
547
+ void getVfs().flushMirror();
548
+ sftp.status(reqid, SFTP_STATUS_CODE.OK);
549
+ }
550
+ catch {
551
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
552
+ }
553
+ });
554
+ sftp.on("RENAME", (reqid, oldPath, newPath) => {
555
+ const fromPath = this.resolveRequestPath(oldPath, authUser);
556
+ const toPath = this.resolveRequestPath(newPath, authUser);
557
+ // Security: Confine both source and destination to home directory
558
+ if (!this.isPathWithinHome(fromPath, authUser) ||
559
+ !this.isPathWithinHome(toPath, authUser)) {
560
+ console.warn(`[SFTP] Path traversal attempt blocked: user=${authUser}, from=${fromPath}, to=${toPath}`);
561
+ sftp.status(reqid, SFTP_STATUS_CODE.PERMISSION_DENIED);
562
+ return;
563
+ }
564
+ try {
565
+ getVfs().move(fromPath, toPath);
566
+ void getVfs().flushMirror();
567
+ sftp.status(reqid, SFTP_STATUS_CODE.OK);
568
+ }
569
+ catch {
570
+ sftp.status(reqid, SFTP_STATUS_CODE.FAILURE);
571
+ }
572
+ });
573
+ sftp.on("READLINK", (reqid) => {
574
+ sftp.status(reqid, SFTP_STATUS_CODE.OP_UNSUPPORTED);
575
+ });
576
+ sftp.on("SYMLINK", (reqid) => {
577
+ sftp.status(reqid, SFTP_STATUS_CODE.OP_UNSUPPORTED);
578
+ });
579
+ sftp.on("error", (error) => {
580
+ console.error(`[SFTP] Stream error for user=${authUser}:`, error);
581
+ });
582
+ sftp.on("close", () => {
583
+ console.log(`[SFTP] Stream closed for user=${authUser}`);
584
+ this.handles.clear();
585
+ });
586
+ sftp.on("end", () => {
587
+ console.log(`[SFTP] end event for user=${authUser}`);
588
+ this.handles.clear();
589
+ });
590
+ sftp.on("END", () => {
591
+ console.log(`[SFTP] END event for user=${authUser}`);
592
+ this.handles.clear();
593
+ });
594
+ }
595
+ }
@@ -1,3 +1,4 @@
1
+ import { EventEmitter } from "node:events";
1
2
  import type { RemoveOptions, VfsNodeStats, WriteFileOptions } from "../types/vfs";
2
3
  /**
3
4
  * In-memory virtual filesystem with tar.gz mirror persistence.
@@ -6,11 +7,13 @@ import type { RemoveOptions, VfsNodeStats, WriteFileOptions } from "../types/vfs
6
7
  * {@link VirtualFileSystem.restoreMirror} on startup and
7
8
  * {@link VirtualFileSystem.flushMirror} to persist pending changes.
8
9
  */
9
- declare class VirtualFileSystem {
10
- private readonly root;
11
- private readonly archivePath;
12
- private dirty;
13
- private computeNodeUsageBytes;
10
+ declare class VirtualFileSystem extends EventEmitter {
11
+ private readonly mirrorRoot;
12
+ private ensureMirrorRoot;
13
+ private resolveFsPath;
14
+ private detectGzipFile;
15
+ private computeDiskUsageBytes;
16
+ private renderTreeLines;
14
17
  /**
15
18
  * Creates a virtual filesystem instance.
16
19
  *
@@ -1 +1 @@
1
- {"version":3,"file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