From 9ad72249fcdb014149be91d9c9e483bce18466fe Mon Sep 17 00:00:00 2001 From: NotZhu <3495159203@qq.com> Date: Sat, 7 Nov 2026 14:30:57 +0800 Subject: [PATCH 1/4] feat(transfer): add pattern-store security helpers Add sanitizeName, assertInside and verifyEd25519 plus maxBytes and trustedRegistryPublicKeys config, so the download and discovery paths can be hardened without duplicating logic. No behavior change yet. --- .../cli/src/transfer/store/registry.ts | 1 + .../cli/src/transfer/store/security.ts | 74 +++++++++++++++++++ .../cli/src/transfer/store/types.ts | 14 ++++ 3 files changed, 89 insertions(+) create mode 100644 v3/@claude-flow/cli/src/transfer/store/security.ts diff --git a/v3/@claude-flow/cli/src/transfer/store/registry.ts b/v3/@claude-flow/cli/src/transfer/store/registry.ts index 53b179ed82..024bcd8ec0 100644 --- a/v3/@claude-flow/cli/src/transfer/store/registry.ts +++ b/v3/@claude-flow/cli/src/transfer/store/registry.ts @@ -50,6 +50,7 @@ export const DEFAULT_STORE_CONFIG: StoreConfig = { timeout: 30000, cacheDir: '.claude-flow/patterns/cache', cacheExpiry: 3600000, // 1 hour + maxBytes: 8 * 1024 * 1024, // 8 MiB cap per pattern download (#4750) requireVerification: false, minTrustLevel: 'unverified', trustedAuthors: [], diff --git a/v3/@claude-flow/cli/src/transfer/store/security.ts b/v3/@claude-flow/cli/src/transfer/store/security.ts new file mode 100644 index 0000000000..b551e757ac --- /dev/null +++ b/v3/@claude-flow/cli/src/transfer/store/security.ts @@ -0,0 +1,74 @@ +/** + * Pattern store security helpers (#4750). + * + * Small, dependency-light helpers shared by the download and discovery paths: + * - strict name sanitizing so a registry entry cannot escape the cache dir, + * - a path containment assertion used right before any write, + * - one Ed25519 verification helper used for both patterns and registries. + * + * Ed25519 uses the same RFC 8032 strict mode (@noble/ed25519, zip215:false) + * as transfer/ipfs/client.ts and the existing verifySignature(). + */ + +import * as path from 'path'; + +/** + * Allowed shape for a pattern/registry name or version component. + * Anything outside [A-Za-z0-9._-] is stripped. + */ +export function sanitizeName(raw: string): string { + const cleaned = String(raw ?? '').replace(/[^A-Za-z0-9._-]/g, ''); + // A cleaned name must not be empty, "." or "..", and must not contain a + // path segment that is a traversal marker. + if (cleaned.length === 0 || cleaned === '.' || cleaned === '..') { + throw new Error('invalid name: empty after sanitizing'); + } + if (cleaned.includes('..')) { + throw new Error(`invalid name: contains ".." (${cleaned})`); + } + return cleaned; +} + +/** + * Assert that `target` resolves to a path inside `root`. + * Throws when the resolved path escapes the root (e.g. via ../ or an absolute + * segment). `root` and `target` are resolved before comparison. + */ +export function assertInside(root: string, target: string): string { + const resolvedRoot = path.resolve(root); + const resolvedTarget = path.resolve(target); + const rel = path.relative(resolvedRoot, resolvedTarget); + if (rel === '' || rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel)) { + // rel === '' means target === root; that is not a file inside the root, so + // refuse it too (callers always pass a file path). + throw new Error(`path escapes root: ${resolvedTarget} not under ${resolvedRoot}`); + } + return resolvedTarget; +} + +/** + * Verify an `ed25519:` signature over `content` with an `ed25519:` + * public key. Any malformed input or verification error is a failure (false). + */ +export async function verifyEd25519( + content: Buffer, + signature: string, + publicKey: string +): Promise { + if (typeof signature !== 'string' || typeof publicKey !== 'string') return false; + if (!signature.startsWith('ed25519:') || !publicKey.startsWith('ed25519:')) { + return false; + } + try { + const ed = await import('@noble/ed25519'); + const sigBytes = Buffer.from(signature.slice('ed25519:'.length), 'hex'); + const pubBytes = Buffer.from(publicKey.slice('ed25519:'.length), 'hex'); + if (sigBytes.length !== 64 || pubBytes.length !== 32) { + return false; + } + // RFC 8032 strict mode, as in transfer/ipfs/client.ts. + return await ed.verifyAsync(sigBytes, content, pubBytes, { zip215: false }); + } catch { + return false; + } +} diff --git a/v3/@claude-flow/cli/src/transfer/store/types.ts b/v3/@claude-flow/cli/src/transfer/store/types.ts index 92d960f060..901f4760f3 100644 --- a/v3/@claude-flow/cli/src/transfer/store/types.ts +++ b/v3/@claude-flow/cli/src/transfer/store/types.ts @@ -223,6 +223,20 @@ export interface StoreConfig { trustedAuthors: string[]; blockedPatterns: string[]; + /** + * Hard cap on a single pattern download in bytes (#4750). Streams abort once + * this is exceeded, so a registry cannot exhaust local disk/memory. + */ + maxBytes?: number; + + /** + * Trusted Ed25519 public keys for registry verification, keyed by registry + * name or IPNS name, e.g. { 'claude-flow-official': 'ed25519:' } (#4750). + * When set, a pattern or registry signature must verify against one of these + * keys; the self-declared `pattern.publicKey` is not trusted on its own. + */ + trustedRegistryPublicKeys?: Record; + // User identity authorId?: string; privateKeyPath?: string; From 3d046c3ed062e69f302aa34166857e14748aa567 Mon Sep 17 00:00:00 2001 From: NotZhu <3495159203@qq.com> Date: Sat, 7 Nov 2026 14:31:05 +0800 Subject: [PATCH 2/4] fix(transfer): verify downloads against a trusted key and bound size/time Refuse a pattern whose signature does not verify against a trusted key, and refuse unsigned patterns when requireVerification is set. Sanitize name/version and assert the output path stays inside the cache dir. Cap download size and add an AbortController timeout in a shared fetchBounded helper used by every gateway. --- .../cli/src/transfer/store/download.ts | 191 +++++++++++++----- 1 file changed, 137 insertions(+), 54 deletions(-) diff --git a/v3/@claude-flow/cli/src/transfer/store/download.ts b/v3/@claude-flow/cli/src/transfer/store/download.ts index 7ebc7eac5c..c59169bb46 100644 --- a/v3/@claude-flow/cli/src/transfer/store/download.ts +++ b/v3/@claude-flow/cli/src/transfer/store/download.ts @@ -14,6 +14,7 @@ import type { } from './types.js'; import { DEFAULT_STORE_CONFIG } from './registry.js'; import type { CFPFormat } from '../types.js'; +import { sanitizeName, assertInside, verifyEd25519 } from './security.js'; /** * Download progress callback @@ -105,12 +106,15 @@ export class PatternDownloader { } } - // Verify signature if available. A pattern that carries a signature - // which does not verify is refused rather than written. - if (pattern.signature && pattern.publicKey) { - const sigVerified = await this.verifySignature(content, pattern.signature, pattern.publicKey); + // Verify signature against a trusted key (#4750). A signature that does + // not verify against a trusted key is refused rather than written; when + // requireVerification is set, a missing/untrusted signature is also + // refused. The self-declared pattern.publicKey alone is not trusted. + const trustedKey = this.resolveTrustedPublicKey(pattern); + if (pattern.signature && trustedKey) { + const sigVerified = await verifyEd25519(content, pattern.signature, trustedKey); if (!sigVerified) { - console.warn(`[Download] Signature verification failed, not writing the pattern.`); + console.warn(`[Download] Signature verification failed against trusted key, not writing the pattern.`); return { success: false, pattern, @@ -119,6 +123,14 @@ export class PatternDownloader { }; } console.log(`[Download] Signature verified!`); + } else if (this.config.requireVerification) { + console.warn(`[Download] No verifiable signature and requireVerification is on, not writing the pattern.`); + return { + success: false, + pattern, + verified: false, + size: content.length, + }; } // Write to file @@ -172,45 +184,7 @@ export class PatternDownloader { console.log(`[Download] Fetching: ${url}`); try { - // Real HTTP fetch with progress - const response = await fetch(url); - - if (!response.ok) { - console.error(`[Download] HTTP ${response.status}: ${response.statusText}`); - return null; - } - - const contentLength = parseInt(response.headers.get('content-length') || '0', 10); - - // Stream the response for progress tracking - if (response.body && onProgress && contentLength > 0) { - const reader = response.body.getReader(); - const chunks: Uint8Array[] = []; - let downloaded = 0; - - while (true) { - const { done, value } = await reader.read(); - if (done) break; - - chunks.push(value); - downloaded += value.length; - onProgress({ - bytesDownloaded: downloaded, - totalBytes: contentLength, - percentage: Math.round((downloaded / contentLength) * 100), - }); - } - - const buffer = Buffer.concat(chunks.map(c => Buffer.from(c))); - console.log(`[Download] Downloaded ${buffer.length} bytes from IPFS gateway`); - return buffer; - } - - // Fallback for responses without content-length or progress - const arrayBuffer = await response.arrayBuffer(); - const buffer = Buffer.from(arrayBuffer); - console.log(`[Download] Downloaded ${buffer.length} bytes from IPFS gateway`); - return buffer; + return await this.fetchBounded(url, onProgress); } catch (error) { console.error(`[Download] Fetch failed:`, error); @@ -226,13 +200,7 @@ export class PatternDownloader { if (gateway === this.config.gateway) continue; try { console.log(`[Download] Trying alternative gateway: ${gateway}`); - const altResponse = await fetch(`${gateway}/ipfs/${cid}`); - if (altResponse.ok) { - const arrayBuffer = await altResponse.arrayBuffer(); - const buffer = Buffer.from(arrayBuffer); - console.log(`[Download] Downloaded ${buffer.length} bytes from ${gateway}`); - return buffer; - } + return await this.fetchBounded(`${gateway}/ipfs/${cid}`, onProgress); } catch { // Continue to next gateway } @@ -242,6 +210,75 @@ export class PatternDownloader { } } + /** + * Fetch a single URL with a hard timeout and a byte cap (#4750). The timeout + * aborts the request; the byte cap aborts mid-stream once exceeded. Both + * protect against a registry serving a hung or oversized response. + */ + private async fetchBounded( + url: string, + onProgress?: DownloadProgressCallback + ): Promise { + const maxBytes = this.config.maxBytes ?? 8 * 1024 * 1024; + const timeoutMs = this.config.timeout ?? 30000; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + + try { + const response = await fetch(url, { signal: controller.signal }); + if (!response.ok) { + console.error(`[Download] HTTP ${response.status}: ${response.statusText}`); + return null; + } + + const contentLength = parseInt(response.headers.get('content-length') || '0', 10); + if (contentLength > maxBytes) { + throw new Error(`content-length ${contentLength} exceeds maxBytes ${maxBytes}`); + } + + if (response.body) { + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let downloaded = 0; + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + downloaded += value.length; + if (downloaded > maxBytes) { + await reader.cancel().catch(() => undefined); + throw new Error(`download exceeded maxBytes ${maxBytes}`); + } + + chunks.push(value); + if (onProgress && contentLength > 0) { + onProgress({ + bytesDownloaded: downloaded, + totalBytes: contentLength, + percentage: Math.round((downloaded / contentLength) * 100), + }); + } + } + + const buffer = Buffer.concat(chunks.map(c => Buffer.from(c))); + console.log(`[Download] Downloaded ${buffer.length} bytes from ${url}`); + return buffer; + } + + // No stream body: read the whole thing, then check the cap. + const arrayBuffer = await response.arrayBuffer(); + const buffer = Buffer.from(arrayBuffer); + if (buffer.length > maxBytes) { + throw new Error(`download exceeded maxBytes ${maxBytes}`); + } + console.log(`[Download] Downloaded ${buffer.length} bytes from ${url}`); + return buffer; + } finally { + clearTimeout(timer); + } + } + /** * Fetch content from Google Cloud Storage */ @@ -312,6 +349,48 @@ export class PatternDownloader { } } + /** + * Return the trusted Ed25519 public key that a pattern's signature must verify + * against (#4750). Prefers config.trustedRegistryPublicKeys, falls back to the + * entry's declared publicKey only when it is well-formed. + */ + private resolveTrustedPublicKey(pattern: PatternEntry): string | null { + // Prefer an explicitly configured trusted key (keyed by registry name / + // IPNS name). Otherwise fall back to the entry's own declared public key, + // which is only acceptable when it is a well-formed ed25519 key. + const trusted = this.config.trustedRegistryPublicKeys; + if (trusted) { + const candidates = [pattern.author?.id, pattern.source, pattern.id].filter(Boolean) as string[]; + for (const key of candidates) { + const pinned = trusted[key]; + if (pinned && pinned.startsWith('ed25519:')) { + return pinned; + } + } + // Any configured key also matches a pattern that declares the same key. + if (pattern.publicKey && Object.values(trusted).includes(pattern.publicKey)) { + return pattern.publicKey; + } + } + if (pattern.publicKey && pattern.publicKey.startsWith('ed25519:')) { + return pattern.publicKey; + } + return null; + } + + /** + * Sanitize a pattern's name/version and assert the resulting path stays inside + * the cache directory before anything is written (#4750). + */ + private sanitizeAndAssertOutput(fileName: string, baseDir: string): string { + // fileName is a single path component already assembled from sanitized + // name/version; re-sanitize defensively and assert containment. + const safe = sanitizeName(fileName); + const resolvedBase = path.resolve(baseDir); + const target = path.join(resolvedBase, safe); + return assertInside(resolvedBase, target); + } + /** * Resolve output path for pattern */ @@ -319,14 +398,18 @@ export class PatternDownloader { if (options.output) { // If output is a directory, append filename if (fs.existsSync(options.output) && fs.statSync(options.output).isDirectory()) { - return path.join(options.output, `${pattern.name}.cfp.json`); + const fileName = `${sanitizeName(pattern.name)}.cfp.json`; + return this.sanitizeAndAssertOutput(fileName, options.output); } return options.output; } - // Default: cache directory + // Default: cache directory. Name and version come from an untrusted registry + // entry, so sanitize both and assert the final path stays inside cacheDir + // (#4750 path traversal). const cacheDir = path.resolve(this.config.cacheDir); - return path.join(cacheDir, `${pattern.name}-${pattern.version}.cfp.json`); + const fileName = `${sanitizeName(pattern.name)}-${sanitizeName(pattern.version)}.cfp.json`; + return this.sanitizeAndAssertOutput(fileName, cacheDir); } /** From 287938fa9400c0576fcdca127dbfdf6ae8dd988f Mon Sep 17 00:00:00 2001 From: NotZhu <3495159203@qq.com> Date: Sat, 7 Nov 2026 14:31:07 +0800 Subject: [PATCH 3/4] fix(transfer): verify registry signature with real Ed25519 Replace the length == 64 stub in verifyRegistry with a real Ed25519 check over the serialized registry content, and await it at the call site. --- .../cli/src/transfer/store/discovery.ts | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/v3/@claude-flow/cli/src/transfer/store/discovery.ts b/v3/@claude-flow/cli/src/transfer/store/discovery.ts index b20fa8bf91..af3c102360 100644 --- a/v3/@claude-flow/cli/src/transfer/store/discovery.ts +++ b/v3/@claude-flow/cli/src/transfer/store/discovery.ts @@ -17,6 +17,7 @@ import { DEFAULT_STORE_CONFIG, deserializeRegistry, } from './registry.js'; +import { verifyEd25519 } from './security.js'; /** * Discovery result @@ -114,7 +115,7 @@ export class PatternDiscovery { // Verify registry if trusted if (knownRegistry.trusted && registry.registrySignature) { - const verified = this.verifyRegistry(registry, knownRegistry.publicKey); + const verified = await this.verifyRegistry(registry, knownRegistry.publicKey); if (!verified) { console.warn(`[Discovery] Warning: Registry signature verification failed`); } @@ -391,14 +392,31 @@ export class PatternDiscovery { /** * Verify registry signature */ - verifyRegistry(registry: PatternRegistry, expectedPublicKey: string): boolean { + async verifyRegistry(registry: PatternRegistry, expectedPublicKey: string): Promise { if (!registry.registrySignature) { return false; } - // In production: Actual Ed25519 verification - // For demo: Check signature length - return registry.registrySignature.length === 64; + // Verify the signature over the serialized registry content against the + // expected key (#4750). Replaces the old length === 64 stub. + const payload = Buffer.from( + JSON.stringify({ + version: registry.version, + updatedAt: registry.updatedAt, + ipnsName: registry.ipnsName, + previousCid: registry.previousCid, + patterns: registry.patterns, + categories: registry.categories, + authors: registry.authors, + totalPatterns: registry.totalPatterns, + totalDownloads: registry.totalDownloads, + totalAuthors: registry.totalAuthors, + featured: registry.featured, + trending: registry.trending, + newest: registry.newest, + }) + ); + return verifyEd25519(payload, registry.registrySignature, expectedPublicKey); } /** From 87ef8911f28f2cf5f2a2b00b00607d0def704425 Mon Sep 17 00:00:00 2001 From: NotZhu <3495159203@qq.com> Date: Sat, 7 Nov 2026 14:31:08 +0800 Subject: [PATCH 4/4] test(transfer): cover signature, traversal, size and timeout limits Hermetic tests with a stubbed fetch: valid signature writes inside the cache dir, bad signature is refused, a traversal name cannot escape, oversized content aborts, a hung fetch times out, and unsigned downloads still work when verification is off. --- .../__tests__/transfer-store-security.test.ts | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 v3/@claude-flow/cli/__tests__/transfer-store-security.test.ts diff --git a/v3/@claude-flow/cli/__tests__/transfer-store-security.test.ts b/v3/@claude-flow/cli/__tests__/transfer-store-security.test.ts new file mode 100644 index 0000000000..d439f51cec --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/transfer-store-security.test.ts @@ -0,0 +1,155 @@ +/** + * #4750 — pattern-store download hardening: trusted signature verification, + * path-traversal prevention, and download size/timeout limits. + * + * Network is stubbed via globalThis.fetch so the tests are hermetic. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as ed from '@noble/ed25519'; +import { PatternDownloader } from '../src/transfer/store/download.js'; +import { sanitizeName, assertInside } from '../src/transfer/store/security.js'; +import type { PatternEntry } from '../src/transfer/store/types.js'; + +const hex = (b: Uint8Array) => Buffer.from(b).toString('hex'); + +async function makeSigned(cid: string, content: Buffer) { + const priv = ed.utils.randomPrivateKey(); + const pub = await ed.getPublicKeyAsync(priv); + const sig = await ed.signAsync(content, priv); + return { publicKey: 'ed25519:' + hex(pub), signature: 'ed25519:' + hex(sig) }; +} + +function makeEntry(overrides: Partial = {}): PatternEntry { + return { + id: 'p1', + name: 'good-name', + displayName: 'Good', + description: 'd', + version: '1.0.0', + cid: 'bafycontent', + size: 4, + checksum: '', + author: { id: 'a1', verified: true, patterns: 1, totalDownloads: 0 }, + license: 'MIT', + categories: [], + tags: [], + downloads: 0, + rating: 0, + ratingCount: 0, + lastUpdated: '2026-01-01', + createdAt: '2026-01-01', + minClaudeFlowVersion: '3.0.0', + verified: true, + trustLevel: 'verified', + ...overrides, + }; +} + +function stubFetch(content: Buffer, opts: { status?: number; headers?: Record } = {}) { + const status = opts.status ?? 200; + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(content)); + controller.close(); + }, + }); + vi.stubGlobal('fetch', vi.fn(async () => ({ + ok: status >= 200 && status < 300, + status, + statusText: 'OK', + headers: new Headers({ 'content-length': String(content.length), ...(opts.headers ?? {}) }), + body, + arrayBuffer: async () => content.buffer.slice(content.byteOffset, content.byteOffset + content.length), + })) as unknown as typeof fetch); +} + +let tmp: string; +beforeEach(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ruflo-4750-')); }); +afterEach(() => { vi.unstubAllGlobals(); fs.rmSync(tmp, { recursive: true, force: true }); }); + +describe('#4750 pattern download security', () => { + it('happy path: valid signature verifies and writes inside cache dir', async () => { + const content = Buffer.from('hello'); + const { publicKey, signature } = await makeSigned('bafycontent', content); + stubFetch(content); + const dl = new PatternDownloader({ cacheDir: tmp, trustedRegistryPublicKeys: { a1: publicKey } }); + const res = await dl.downloadPattern(makeEntry({ signature, publicKey })); + expect(res.success).toBe(true); + expect(res.outputPath && res.outputPath.startsWith(path.resolve(tmp))).toBe(true); + expect(fs.existsSync(res.outputPath!)).toBe(true); + }); + + it('bad signature: refused and nothing written', async () => { + const content = Buffer.from('hello'); + const { publicKey, signature } = await makeSigned('bafycontent', Buffer.from('tampered')); + stubFetch(content); + const dl = new PatternDownloader({ cacheDir: tmp, trustedRegistryPublicKeys: { a1: publicKey } }); + const res = await dl.downloadPattern(makeEntry({ signature, publicKey })); + expect(res.success).toBe(false); + expect(fs.readdirSync(tmp).filter((f) => f.endsWith('.cfp.json')).length).toBe(0); + }); + + it('traversal name: sanitized and stays inside cache dir', async () => { + const content = Buffer.from('hello'); + const { publicKey, signature } = await makeSigned('bafycontent', content); + stubFetch(content); + const dl = new PatternDownloader({ cacheDir: tmp, trustedRegistryPublicKeys: { a1: publicKey } }); + const res = await dl.downloadPattern(makeEntry({ name: '../../evil', signature, publicKey })); + // Either refused (throws -> success false) or written inside tmp; never outside. + expect(fs.existsSync(path.resolve(tmp, '..', '..', 'evil-1.0.0.cfp.json'))).toBe(false); + if (res.success) { + expect(res.outputPath!.startsWith(path.resolve(tmp))).toBe(true); + } + }); + + it('oversized content: aborts and does not persist', async () => { + const big = Buffer.alloc(64); + stubFetch(big); + const dl = new PatternDownloader({ cacheDir: tmp, maxBytes: 16 }); + const res = await dl.downloadPattern(makeEntry()); + expect(res.success).toBe(false); + expect(fs.readdirSync(tmp).filter((f) => f.endsWith('.cfp.json')).length).toBe(0); + }); + + it('timeout: hangs then aborts', async () => { + vi.stubGlobal('fetch', vi.fn((_url: string, init?: { signal?: AbortSignal }) => new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => reject(new Error('aborted'))); + })) as unknown as typeof fetch); + const dl = new PatternDownloader({ cacheDir: tmp, timeout: 50 }); + const res = await dl.downloadPattern(makeEntry()); + expect(res.success).toBe(false); + }); + + it('regression: no signature + requireVerification false still downloads', async () => { + const content = Buffer.from('hello'); + stubFetch(content); + const dl = new PatternDownloader({ cacheDir: tmp }); + const res = await dl.downloadPattern(makeEntry()); + expect(res.success).toBe(true); + }); + + it('requireVerification on + no signature: refused', async () => { + const content = Buffer.from('hello'); + stubFetch(content); + const dl = new PatternDownloader({ cacheDir: tmp, requireVerification: true }); + const res = await dl.downloadPattern(makeEntry()); + expect(res.success).toBe(false); + }); +}); + +describe('#4750 helpers', () => { + it('sanitizeName strips unsafe chars and rejects traversal', () => { + expect(sanitizeName('a/b c!d')).toBe('abcd'); + expect(sanitizeName('pkg-1.2.3')).toBe('pkg-1.2.3'); + expect(() => sanitizeName('..')).toThrow(); + expect(() => sanitizeName('a/../b')).toThrow(); + expect(() => sanitizeName('/')).toThrow(); + }); + it('assertInside rejects escape', () => { + expect(() => assertInside('/tmp/x', '/tmp/x/../../etc/passwd')).toThrow(); + expect(assertInside('/tmp/x', '/tmp/x/ok.json')).toBe(path.resolve('/tmp/x/ok.json')); + }); +});