Add virtual unzip command to ShellTool

This commit is contained in:
Alex Gleason committed 2025-09-23 21:04:27 -05:00
1 parent be13d563c4
commit 4881480679
5 files changed
+529 -3

No files matched your search

+2 -1
View File
@@ -25,4 +25,5 @@ export { TrCommand } from './tr';
export { UniqCommand } from './uniq';
export { WcCommand } from './wc';
export { WhoamiCommand } from './whoami';
export { WhichCommand } from './which';
export { WhichCommand } from './which';
export { UnzipCommand } from './unzip';
+303
View File
@@ -0,0 +1,303 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import JSZip from 'jszip';
import { UnzipCommand } from './unzip';
import type { JSRuntimeFS } from '../JSRuntime';
// Mock filesystem
const createMockFS = (): JSRuntimeFS => ({
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
mkdir: vi.fn(),
stat: vi.fn(),
lstat: vi.fn(),
unlink: vi.fn(),
rmdir: vi.fn(),
rename: vi.fn(),
readlink: vi.fn(),
symlink: vi.fn(),
});
describe('UnzipCommand', () => {
let mockFS: JSRuntimeFS;
let command: UnzipCommand;
beforeEach(() => {
mockFS = createMockFS();
command = new UnzipCommand(mockFS);
});
const createTestZip = async (files: Record<string, string | Uint8Array>): Promise<Uint8Array> => {
const zip = new JSZip();
for (const [path, content] of Object.entries(files)) {
if (path.endsWith('/')) {
zip.folder(path.slice(0, -1));
} else {
zip.file(path, content);
}
}
return zip.generateAsync({ type: 'uint8array' });
};
it('should show usage when no arguments provided', async () => {
const result = await command.execute([], '/home');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('missing archive operand');
expect(result.stderr).toContain('Usage:');
});
it('should show error for invalid options', async () => {
const result = await command.execute(['-x', 'test.zip'], '/home');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("invalid option '-x'");
});
it('should show error for non-existent archive', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
const result = await command.execute(['nonexistent.zip'], '/home');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('No such file or directory');
});
it('should show error when trying to unzip a directory', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
const result = await command.execute(['testdir'], '/home');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('Is a directory');
});
it('should list archive contents with -l option', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World',
'dir1/': '',
'dir1/file2.txt': 'Test content'
});
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
const result = await command.execute(['-l', 'test.zip'], '/home');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Archive: test.zip');
expect(result.stdout).toContain('file1.txt');
expect(result.stdout).toContain('dir1/');
expect(result.stdout).toContain('dir1/file2.txt');
});
it('should extract files to current directory', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World'
});
// Mock file operations - keep it simple
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await command.execute(['test.zip'], '/home');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Archive: test.zip');
expect(result.stdout).toContain('inflating: file1.txt');
// Verify writeFile was called for extracted files
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array));
});
it('should handle command line options correctly', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World'
});
// Test -d option
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await command.execute(['-d', 'extract', 'test.zip'], '/home');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('inflating: file1.txt');
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/extract/file1.txt', expect.any(Uint8Array));
});
it('should handle overwrite option', async () => {
const zipData = await createTestZip({
'file1.txt': 'New content'
});
// Mock file exists scenario
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
// Without -o option, should fail
const resultWithoutOverwrite = await command.execute(['test.zip'], '/home');
expect(resultWithoutOverwrite.exitCode).toBe(1);
expect(resultWithoutOverwrite.stderr).toContain('File exists (use -o to overwrite)');
// Reset mocks
vi.clearAllMocks();
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
// With -o option, should succeed
const resultWithOverwrite = await command.execute(['-o', 'test.zip'], '/home');
expect(resultWithOverwrite.exitCode).toBe(0);
expect(resultWithOverwrite.stdout).toContain('inflating: file1.txt');
});
it('should prevent extraction outside allowed directories', async () => {
// Since JSZip normalizes paths during creation, we'll test the security logic
// by mocking the internal zip.files object to simulate a malicious ZIP
const zipData = await createTestZip({
'normal.txt': 'safe content'
});
// Mock the zip loading to return a ZIP with malicious paths
const originalLoadAsync = JSZip.loadAsync;
vi.spyOn(JSZip, 'loadAsync').mockImplementation(async () => {
const zip = new JSZip();
// Simulate malicious ZIP file entries that would escape the directory
(zip as unknown as { files: Record<string, { name: string; dir: boolean; async: () => Promise<Uint8Array> }> }).files = {
'../../../etc/passwd': {
name: '../../../etc/passwd',
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])),
},
'../../outside.txt': {
name: '../../outside.txt',
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6])),
},
'normal.txt': {
name: 'normal.txt',
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9])),
}
};
return zip;
});
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await command.execute(['test.zip'], '/home/user');
// Should return error because some files were skipped
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('Path is outside allowed directories');
expect(result.stderr).toContain('../../../etc/passwd');
expect(result.stderr).toContain('../../outside.txt');
// Should only extract the safe file
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/user/normal.txt', expect.any(Uint8Array));
expect(mockFS.writeFile).toHaveBeenCalledTimes(1);
// Restore the original method
JSZip.loadAsync = originalLoadAsync;
});
it('should allow extraction to /tmp directory', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World'
});
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockRejectedValueOnce(new Error('ENOENT')) // extraction dir doesn't exist
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
const result = await command.execute(['-d', '/tmp', 'test.zip'], '/home/user');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('inflating: file1.txt');
expect(mockFS.writeFile).toHaveBeenCalledWith('/tmp/file1.txt', expect.any(Uint8Array));
});
it('should reject extraction directory outside allowed paths', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World'
});
// Mock that the archive exists and provide zip data
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
const result = await command.execute(['-d', '/etc', 'test.zip'], '/home/user');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("extraction directory '/etc' is outside allowed paths");
});
it('should support quiet mode with -q flag', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World',
'dir1/': '',
'dir1/file2.txt': 'Test content'
});
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
const result = await command.execute(['-q', 'test.zip'], '/home');
expect(result.exitCode).toBe(0);
// In quiet mode, should not show archive header or extraction messages
expect(result.stdout).toBe('');
// But files should still be extracted
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array));
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/dir1/file2.txt', expect.any(Uint8Array));
});
});
+220
View File
@@ -0,0 +1,220 @@
import { join, dirname, normalize } from "path-browserify";
import JSZip from "jszip";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'unzip' command
* Extract files from ZIP archives
*/
export class UnzipCommand implements ShellCommand {
name = 'unzip';
description = 'Extract files from ZIP archives';
usage = 'unzip [-d directory] [-o] [-l] [-q] archive.zip';
private fs: JSRuntimeFS;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
if (args.length === 0) {
return createErrorResult(`${this.name}: missing archive operand\nUsage: ${this.usage}`);
}
let archivePath = '';
let extractDir = cwd;
let overwrite = false;
let listOnly = false;
let quiet = false;
// Parse command line options
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-d' && i + 1 < args.length) {
// Extract to specific directory
extractDir = args[i + 1];
i++; // Skip next argument
} else if (arg === '-o') {
// Overwrite existing files
overwrite = true;
} else if (arg === '-l') {
// List archive contents only
listOnly = true;
} else if (arg === '-q') {
// Quiet mode - suppress output
quiet = true;
} else if (arg.startsWith('-')) {
return createErrorResult(`${this.name}: invalid option '${arg}'\nUsage: ${this.usage}`);
} else {
// This should be the archive path
archivePath = arg;
}
}
if (!archivePath) {
return createErrorResult(`${this.name}: no archive specified\nUsage: ${this.usage}`);
}
try {
// Resolve archive path
let absoluteArchivePath: string;
if (archivePath.startsWith('/') || archivePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(archivePath)) {
absoluteArchivePath = archivePath;
} else {
absoluteArchivePath = join(cwd, archivePath);
}
// Check if archive exists
try {
const stats = await this.fs.stat(absoluteArchivePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${archivePath}: Is a directory`);
}
} catch {
return createErrorResult(`${this.name}: ${archivePath}: No such file or directory`);
}
// Read the ZIP file
const zipData = await this.fs.readFile(absoluteArchivePath);
const zip = await JSZip.loadAsync(zipData);
// Resolve extraction directory
let absoluteExtractDir: string;
if (extractDir.startsWith('/') || extractDir.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(extractDir)) {
absoluteExtractDir = extractDir;
} else {
absoluteExtractDir = join(cwd, extractDir);
}
// Security check: ensure extraction directory is within allowed paths
if (!this.isPathAllowed(absoluteExtractDir, cwd)) {
return createErrorResult(`${this.name}: extraction directory '${extractDir}' is outside allowed paths (cwd or /tmp)`);
}
if (listOnly) {
// List contents only
const entries: string[] = [];
zip.forEach((relativePath, file) => {
const date = file.date || new Date();
const type = file.dir ? 'd' : '-';
const sizeStr = file.dir ? '0' : '?';
entries.push(`${type}rw-r--r-- 1 user user ${sizeStr.padStart(8)} ${date.toISOString().slice(0, 19).replace('T', ' ')} ${relativePath}`);
});
return createSuccessResult(`Archive: ${archivePath}\n${entries.join('\n')}`);
}
// Create extraction directory if it doesn't exist
try {
await this.fs.stat(absoluteExtractDir);
} catch {
await this.fs.mkdir(absoluteExtractDir, { recursive: true });
}
const extractedFiles: string[] = [];
const errors: string[] = [];
// Extract all files
for (const [relativePath, file] of Object.entries(zip.files)) {
const extractPath = join(absoluteExtractDir, relativePath);
// Security check: ensure each file path is within allowed directories
if (!this.isPathAllowed(extractPath, cwd)) {
errors.push(`${this.name}: ${relativePath}: Path is outside allowed directories (skipped for security)`);
continue;
}
try {
if (file.dir) {
// Create directory
await this.fs.mkdir(extractPath, { recursive: true });
if (!quiet) {
extractedFiles.push(` creating: ${relativePath}`);
}
} else {
// Check if file exists and handle overwrite
if (!overwrite) {
try {
await this.fs.stat(extractPath);
errors.push(`${this.name}: ${relativePath}: File exists (use -o to overwrite)`);
continue;
} catch {
// File doesn't exist, proceed with extraction
}
}
// Create parent directories if needed
const parentDir = dirname(extractPath);
try {
await this.fs.stat(parentDir);
} catch {
await this.fs.mkdir(parentDir, { recursive: true });
}
// Extract file content
const content = await file.async('uint8array');
await this.fs.writeFile(extractPath, content);
if (!quiet) {
extractedFiles.push(` inflating: ${relativePath}`);
}
}
} catch (error) {
errors.push(`${this.name}: ${relativePath}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
let output = '';
if (!quiet) {
output = `Archive: ${archivePath}\n`;
if (extractedFiles.length > 0) {
output += extractedFiles.join('\n');
}
}
if (errors.length > 0) {
if (!quiet && extractedFiles.length > 0) {
output += '\n';
}
return createErrorResult(output + '\n' + errors.join('\n'));
}
return createSuccessResult(output);
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('corrupted') || error.message.includes('invalid')) {
return createErrorResult(`${this.name}: ${archivePath}: Archive is corrupted or invalid`);
} else {
return createErrorResult(`${this.name}: ${archivePath}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${archivePath}: Unknown error`);
}
}
}
/**
* Check if a path is within allowed extraction directories (cwd or /tmp and their subdirectories)
*/
private isPathAllowed(extractPath: string, cwd: string): boolean {
// Normalize the paths without using resolve() since we're in browser environment
const normalizedPath = normalize(extractPath);
const normalizedCwd = normalize(cwd);
const tmpPath = '/tmp';
// Ensure paths are absolute for comparison
const absolutePath = normalizedPath.startsWith('/') ? normalizedPath : normalize(join(normalizedCwd, normalizedPath));
const absoluteCwd = normalizedCwd.startsWith('/') ? normalizedCwd : '/' + normalizedCwd;
// Check if path is within cwd or /tmp
return absolutePath.startsWith(absoluteCwd + '/') ||
absolutePath === absoluteCwd ||
absolutePath.startsWith(tmpPath + '/') ||
absolutePath === tmpPath;
}
}