refactor(security): centralize path guard helpers

This commit is contained in:
Peter Steinberger
2026-02-21 19:54:19 +01:00
parent 6ffca36284
commit ed960ba4eb
5 changed files with 178 additions and 102 deletions

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { isNotFoundPathError, isPathInside } from "../infra/path-guards.js";
const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
const HTTP_URL_RE = /^https?:\/\//i;
@@ -129,8 +130,7 @@ async function assertNoSymlinkEscape(
current = target;
}
} catch (err) {
const anyErr = err as { code?: string };
if (anyErr.code === "ENOENT") {
if (isNotFoundPathError(err)) {
return;
}
throw err;
@@ -146,14 +146,6 @@ async function tryRealpath(value: string): Promise<string> {
}
}
function isPathInside(root: string, target: string): boolean {
const relative = path.relative(root, target);
if (!relative || relative === "") {
return true;
}
return !(relative.startsWith("..") || path.isAbsolute(relative));
}
function shortPath(value: string) {
if (value.startsWith(os.homedir())) {
return `~${value.slice(os.homedir().length)}`;