Skip to content
Merged
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
57 changes: 50 additions & 7 deletions src/schemas/shared.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import path from 'node:path';
import { z } from 'zod';

export const ZoneNameSchema = z
Expand All @@ -17,12 +16,56 @@ export const ZoneNameSchema = z
message: 'zone name cannot end with an underscore',
});

// Reduce to the final path segment before stripping reserved characters so
// path-traversal sequences (../, absolute paths, alt-separators) cannot escape
// the working directory once getAbsAndEnsureDir → path.resolve runs downstream.
// path.basename only splits on the platform's native separator, so the regex
// must still strip backslashes for POSIX hosts receiving Windows-shaped input.
// Allow legitimate relative subfolders (e.g. "output/data.json") while still
// refusing to escape the working directory. Unlike a blanket path.basename(),
// this preserves directory structure the caller asked for and only rejects
// genuinely dangerous input, with a clear error instead of a silent rewrite:
// - absolute paths (POSIX "/etc/x", Windows "C:\x" or UNC "\\host\share")
// - ".." segments anywhere in the path
// Backslashes are always treated as separators (not just on Windows), so a
// Windows-shaped traversal payload can't slip through on a POSIX host by
// switching separator style. This is the lexical half of the defense; the
// filesystem-level half (containment + symlink-escape check against the
// actual write target) lives in utils/files.ts's getAbsAndEnsureDir, since
// some callers (e.g. BaseResult.save()) accept a raw path that never passes
// through this schema at all.
const RESERVED_CHARS = /[<>:"|?*]/g;
const ABSOLUTE_PATH = /^\/|^[a-zA-Z]:\//;

export const FilenameSchema = z
.string()
.min(1)
.transform((v) => path.basename(v).replace(/[<>:"\\|?*]/g, '_'));
.transform((v, ctx) => {
const normalized = v.replace(/\\/g, '/');

if (ABSOLUTE_PATH.test(normalized)) {
ctx.addIssue({
code: 'custom',
message: 'absolute paths are not allowed in filename',
});
return z.NEVER;
}

const segments: string[] = [];
for (const raw of normalized.split('/')) {
if (raw === '' || raw === '.') continue;
if (raw === '..') {
ctx.addIssue({
code: 'custom',
message: 'filename must not contain ".." path segments',
});
return z.NEVER;
}
segments.push(raw.replace(RESERVED_CHARS, '_'));
}

if (segments.length === 0) {
ctx.addIssue({
code: 'custom',
message: 'filename must not be empty',
});
return z.NEVER;
}

return segments.join('/');
});
73 changes: 69 additions & 4 deletions src/utils/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,80 @@ export const getFilename = (
return `brightdata_content_${Date.now()}.${format}`;
};

export const getAbsAndEnsureDir = async (filename: string) => {
/**
* Resolve `filename` against `baseDir` (default: cwd) and ensure its parent
* directory exists — refusing to write outside `baseDir` for *relative*
* inputs, while still honoring an explicit absolute path.
*
* Some callers (e.g. `BaseResult.save()`) accept a raw path that never
* passes through `FilenameSchema`, so containment can't be assumed to have
* been checked already. But an absolute path is a deliberate choice by the
* calling code (the same trust model as calling `fs.writeFile` directly) —
* `.save()` is a general-purpose "write here" API, not a sanitized-filename
* option, and has always accepted arbitrary absolute destinations. So
* containment is only enforced for relative inputs, where escaping `baseDir`
* (e.g. "../../etc/passwd") can only mean traversal, never an intentional
* absolute destination. Two layers, both skipped for absolute input:
* 1. Lexical containment — `path.resolve` the candidate and confirm it's
* still under `baseDir`. Cheap, catches the common cases, but is purely
* string-based and blind to symlinks.
* 2. Real-path containment — after creating the parent directory, resolve
* both the real (symlink-free) parent and the real base, and re-check
* containment. This catches a subfolder that is (or contains) a symlink
* pointing outside `baseDir`, which layer 1 cannot see.
*/
export const getAbsAndEnsureDir = async (
filename: string,
baseDir: string = process.cwd(),
): Promise<string> => {
const resolvedBase = path.resolve(baseDir);
const isExplicitAbsolute = path.isAbsolute(filename);
const candidate = path.resolve(resolvedBase, filename);

if (
!isExplicitAbsolute &&
candidate !== resolvedBase &&
!candidate.startsWith(resolvedBase + path.sep)
) {
throw new FSError(
`refusing to write outside the working directory: ${filename}`,
);
}

try {
const target = path.resolve(filename);
await fs.mkdir(path.dirname(target), { recursive: true });
return target;
await fs.mkdir(path.dirname(candidate), { recursive: true });
} catch (e: unknown) {
const msg = `failed to create dirs ${filename}:`;
throw new FSError(`${msg} ${(e as Error).message}`);
}

if (isExplicitAbsolute) {
return candidate;
}

let realParent: string;
let realBase: string;
try {
[realParent, realBase] = await Promise.all([
fs.realpath(path.dirname(candidate)),
fs.realpath(resolvedBase),
]);
} catch (e: unknown) {
throw new FSError(
`failed to resolve real path for ${filename}: ${(e as Error).message}`,
);
}

if (
realParent !== realBase &&
!realParent.startsWith(realBase + path.sep)
) {
throw new FSError(
`refusing to write outside the working directory (symlink escape): ${filename}`,
);
}

return path.join(realParent, path.basename(candidate));
};

export const writeContent = async (content: string, filename: string) => {
Expand Down
Loading