Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"@langchain/core": "^0.3.40",
"axios": "1.7.4",
"fast-glob": "^3.3.3",
"fflate": "^0.8.2",
"glob": "9.3.5",
"ink": "^6.8.0",
"inquirer": "^6.2.0",
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 36 additions & 0 deletions src/lib/__tests__/wizard-tools.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { zipSync, strToU8 } from 'fflate';
import {
ASK_BATCH_THRESHOLD,
DEFAULT_ASK_MAX_QUESTIONS,
Expand Down Expand Up @@ -343,3 +344,38 @@ describe('evaluateAskCap', () => {
});
});
});

describe('extractZipTo', () => {
let dir: string;

beforeEach(() => {
dir = makeTmpDir();
});

afterEach(() => {
cleanup(dir);
});

it('writes nested files in-process without shelling out to unzip', () => {
const zip = zipSync({
'SKILL.md': strToU8('# skill'),
'references/guide.md': strToU8('details'),
});

__test.extractZipTo(zip, dir);

expect(fs.readFileSync(path.join(dir, 'SKILL.md'), 'utf8')).toBe('# skill');
expect(
fs.readFileSync(path.join(dir, 'references', 'guide.md'), 'utf8'),
).toBe('details');
});

it('rejects zip-slip entries that escape the destination', () => {
const zip = zipSync({ '../escape.md': strToU8('pwned') });

expect(() => __test.extractZipTo(zip, dir)).toThrow(/unsafe path/i);
expect(fs.existsSync(path.join(path.dirname(dir), 'escape.md'))).toBe(
false,
);
});
});
52 changes: 35 additions & 17 deletions src/lib/wizard-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@

import path from 'path';
import fs from 'fs';
import { execFileSync } from 'child_process';
import axios from 'axios';
import { unzipSync } from 'fflate';
import { z } from 'zod';
import { logToFile } from '@utils/debug';
import { analytics } from '@utils/analytics';
import { skillTmpPath } from '@utils/paths';
import type { PackageManagerDetector } from './detection/package-manager';
import {
AUDIT_CHECKS_FILE,
Expand Down Expand Up @@ -84,31 +84,30 @@ export async function fetchSkillMenu(
* Download and extract a skill.
* By default installs to `<installDir>/.claude/skills/<id>/`.
* Pass `skillsRoot` to override the base directory (e.g. `.posthog/skills`).
*
* Downloads the zip into memory and extracts it in-process. This stays
* cross-platform: the earlier `curl`/`unzip` shell-out broke on Windows,
* which ships neither an `unzip` binary nor a `/tmp` directory.
*/
export function downloadSkill(
export async function downloadSkill(
skillEntry: SkillEntry,
installDir: string,
skillsRoot?: string,
): { success: boolean; error?: string } {
): Promise<{ success: boolean; error?: string }> {
const skillDir = skillsRoot
? path.join(installDir, skillsRoot, skillEntry.id)
: path.join(installDir, '.claude', 'skills', skillEntry.id);
const tmpFile = skillTmpPath(skillEntry.id);

try {
fs.mkdirSync(skillDir, { recursive: true });
execFileSync('curl', ['-sL', skillEntry.downloadUrl, '-o', tmpFile], {
timeout: 30000,
});
execFileSync('unzip', ['-o', tmpFile, '-d', skillDir], {

const resp = await axios.get<ArrayBuffer>(skillEntry.downloadUrl, {
responseType: 'arraybuffer',
timeout: 30000,
});
extractZipTo(new Uint8Array(resp.data), skillDir);

fs.writeFileSync(path.join(skillDir, '.posthog-wizard'), '');
try {
fs.unlinkSync(tmpFile);
} catch {
/* ignore cleanup errors */
}

logToFile(
`downloadSkill: installed ${skillEntry.id} from ${skillEntry.downloadUrl}`,
Expand All @@ -120,6 +119,24 @@ export function downloadSkill(
}
}

/**
* Extract a zip archive's bytes into `destDir`. Rejects entries whose path
* escapes `destDir` (zip-slip) before writing anything to disk.
*/
function extractZipTo(zip: Uint8Array, destDir: string): void {
const entries = unzipSync(zip);
for (const [name, data] of Object.entries(entries)) {
if (name.endsWith('/')) continue; // directory entry; parents made on demand
const dest = path.join(destDir, name);
const rel = path.relative(destDir, dest);
if (rel.startsWith('..') || path.isAbsolute(rel)) {
throw new Error(`unsafe path in skill archive: ${name}`);
}
fs.mkdirSync(path.dirname(dest), { recursive: true });
fs.writeFileSync(dest, data);
}
}

/**
* Structured result for installSkillById.
* - `ok`: the skill was fetched and extracted; `path` is where it lives
Expand Down Expand Up @@ -154,7 +171,7 @@ export async function installSkillById(
.find((s) => s.id === skillId);
if (!skill) return { kind: 'skill-not-found', skillId };

const result = downloadSkill(skill, installDir, skillsRoot);
const result = await downloadSkill(skill, installDir, skillsRoot);
if (!result.success) {
return { kind: 'download-failed', message: result.error ?? 'unknown' };
}
Expand Down Expand Up @@ -735,7 +752,7 @@ export async function createWizardToolsServer(options: WizardToolsOptions) {
'Skill ID from the skill menu (e.g., "integration-nextjs-app-router")',
),
},
(args: { skillId: string }) => {
async (args: { skillId: string }) => {
if (!/^[a-z0-9][a-z0-9_-]*$/.test(args.skillId)) {
return {
content: [
Expand Down Expand Up @@ -763,7 +780,7 @@ export async function createWizardToolsServer(options: WizardToolsOptions) {
};
}

const result = downloadSkill(skill, workingDirectory);
const result = await downloadSkill(skill, workingDirectory);
if (result.success) {
return {
content: [
Expand Down Expand Up @@ -1150,4 +1167,5 @@ export const __test = {
applyAuditUpdates,
makeMutex,
AUDIT_CHECKS_FILE,
extractZipTo,
};
2 changes: 1 addition & 1 deletion src/ui/tui/screens/health/HealthCheckScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export const HealthCheckScreen = ({ store }: HealthCheckScreenProps) => {
s.id.startsWith(prefix),
);
for (const skill of skills) {
downloadSkill(skill, store.session.installDir, '.posthog/skills');
await downloadSkill(skill, store.session.installDir, '.posthog/skills');
}
}
setDownloaded(true);
Expand Down
4 changes: 0 additions & 4 deletions src/utils/paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@ export const WIZARD_YARA_REPORT_FILE = join(
TMP,
'posthog-wizard-yara-report.json',
);
/** Temp path for a skill download zip. */
export function skillTmpPath(skillId: string): string {
return join(TMP, `posthog-skill-${skillId}.zip`);
}

/**
* Strip an absolute installDir prefix off a project file path so the UI
Expand Down
Loading