Skip to content

Commit 9afa11f

Browse files
ref(cli): Share path containment helpers and document replaceFile
- Move the containment check and the reference resolver from the wasm prepare step into src/lib/path-utils.ts (isPathInside, isRemoteUrl, resolveLocalReference), and use them where sourcemap inject, snapshot archive extraction and the DSN home-directory guard repeated the logic. - Explain in replaceFile why it writes a temp file and renames it. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
1 parent c5a1697 commit 9afa11f

7 files changed

Lines changed: 123 additions & 57 deletions

File tree

‎packages/cli/src/lib/dsn/project-root.ts‎

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@
1515

1616
import { opendir, readFile, stat } from "node:fs/promises";
1717
import { homedir, tmpdir } from "node:os";
18-
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
18+
import { dirname, join, resolve } from "node:path";
1919
import pLimit from "p-limit";
2020
import picomatch from "picomatch";
21+
import { isPathInside } from "../path-utils.js";
2122
import { anyTrue } from "../promises.js";
2223
import {
2324
applyGlobalFallbacks,
@@ -410,18 +411,10 @@ export function getStopBoundary(): string {
410411
* `~/.aws`, …) that must never be touched.
411412
*/
412413
export function isHomeOrAncestor(dir: string): boolean {
413-
// Normalize both sides through resolve() so a trailing slash or other
414+
// isPathInside resolves both sides, so a trailing slash or other
414415
// non-canonical form of $HOME (getStopBoundary returns homedir() raw)
415-
// can't make the equality and relative() checks disagree and fail open.
416-
const home = resolve(getStopBoundary());
417-
const resolvedDir = resolve(dir);
418-
if (resolvedDir === home) {
419-
return true;
420-
}
421-
// `dir` is an ancestor of home when the path from dir → home doesn't
422-
// climb back out (no leading "..") and stays relative.
423-
const rel = relative(resolvedDir, home);
424-
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
416+
// can't make the check fail open.
417+
return isPathInside(dir, getStopBoundary());
425418
}
426419

427420
/**

‎packages/cli/src/lib/path-utils.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Path checks shared by commands that follow references found inside files
3+
* (sourcemap directives, WebAssembly `external_debug_info` pointers) or unpack
4+
* archives, and must not step outside a directory.
5+
*/
6+
7+
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
8+
9+
/**
10+
* Whether `path` is `root` itself or sits below it.
11+
*
12+
* Segment-aware, so `/dist-backup` is not inside `/dist` and a name such as
13+
* `..config` is not mistaken for a parent step. Both sides are resolved first.
14+
*/
15+
export function isPathInside(root: string, path: string): boolean {
16+
const rel = relative(resolve(root), resolve(path));
17+
return !(rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel));
18+
}
19+
20+
/** Whether a reference is an `http(s)` URL rather than a local path. */
21+
export function isRemoteUrl(reference: string): boolean {
22+
return reference.startsWith("http://") || reference.startsWith("https://");
23+
}
24+
25+
/**
26+
* Resolve a reference found inside `fromFile` to a local path.
27+
*
28+
* Relative references are taken against the file's own directory, the way a
29+
* browser or debugger reads them. Remote URLs have no local file, so they
30+
* resolve to `null`.
31+
*/
32+
export function resolveLocalReference(
33+
fromFile: string,
34+
reference: string,
35+
): string | null {
36+
return isRemoteUrl(reference) ? null : resolve(dirname(fromFile), reference);
37+
}

‎packages/cli/src/lib/replace-file.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@ import { rename, rm, stat, writeFile } from "node:fs/promises";
1414
/**
1515
* Atomically replace `path` with `data`.
1616
*
17+
* Temp file plus rename is on purpose, not an in-place write:
18+
* - A crash or full disk can't leave a half-written module, or a half-written
19+
* companion that is the only copy of a module's DWARF.
20+
* - Rename gives `path` a new inode, so other hard links to the old file keep
21+
* their contents instead of being rewritten too.
22+
* - Stripping changes the file's length, so an in-place write would have to
23+
* truncate anyway.
24+
*
1725
* @param path - Existing file to replace
1826
* @param data - New contents
1927
*/

‎packages/cli/src/lib/snapshots/archive.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@
88
*/
99

1010
import { createWriteStream, mkdirSync } from "node:fs";
11-
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
11+
import { dirname, resolve } from "node:path";
1212
import { Unzip, UnzipInflate, UnzipPassThrough } from "fflate";
1313
import { logger } from "../logger.js";
14+
import { isPathInside } from "../path-utils.js";
1415

1516
const log = logger.withTag("snapshots.extract");
1617

@@ -25,8 +26,7 @@ function safeEntryDest(root: string, name: string): string | null {
2526
return null;
2627
}
2728
const dest = resolve(root, name);
28-
const rel = relative(root, dest);
29-
if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
29+
if (!isPathInside(root, dest)) {
3030
log.warn(`Skipping unsafe archive entry: ${name}`);
3131
return null;
3232
}

‎packages/cli/src/lib/sourcemap/inject.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,13 @@
66
*/
77

88
import { open, readFile, stat } from "node:fs/promises";
9-
import { dirname, relative, resolve as resolvePath, sep } from "node:path";
9+
import { dirname, relative, resolve as resolvePath } from "node:path";
1010
import type ignore from "ignore";
1111
import picomatch from "picomatch";
1212
import { NODE_MODULES_DIRNAME } from "../constants.js";
1313
import { ValidationError } from "../errors.js";
1414
import { logger } from "../logger.js";
15+
import { isPathInside, isRemoteUrl } from "../path-utils.js";
1516
import { isLikelyBinary } from "../scan/binary.js";
1617
import { buildIgnoreMatcher, walkFiles } from "../scan/index.js";
1718
import {
@@ -518,7 +519,7 @@ export function parseSourceMappingDirective(
518519
let kind: SourceMappingDirective["kind"] = "external";
519520
if (isInlineSourcemapUrl(value)) {
520521
kind = "inline";
521-
} else if (value.startsWith("http://") || value.startsWith("https://")) {
522+
} else if (isRemoteUrl(value)) {
522523
kind = "remote";
523524
}
524525
return { kind, value };
@@ -702,9 +703,8 @@ export async function discoverFilePairs(
702703
* Guards against `sourceMappingURL` directives that resolve outside the
703704
* upload directory (e.g. `"../../other/app.js.map"`). Convention-based maps
704705
* (`foo.js.map`) are always adjacent and inline maps live inside the JS file,
705-
* so both are inherently in-dir. The trailing separator prevents prefix
706-
* collisions (e.g. `/dist` vs `/dist-backup`); `path.sep` keeps it correct on
707-
* Windows.
706+
* so both are inherently in-dir. The check is segment-aware, so `/dist`
707+
* does not contain `/dist-backup`.
708708
*/
709709
function isMapInsideDir(
710710
map: MapSource,
@@ -714,8 +714,7 @@ function isMapInsideDir(
714714
if (map.kind === "inline") {
715715
return true;
716716
}
717-
const dirPrefix = absDir.endsWith(sep) ? absDir : `${absDir}${sep}`;
718-
if (map.mapPath.startsWith(dirPrefix)) {
717+
if (isPathInside(absDir, map.mapPath)) {
719718
return true;
720719
}
721720
log.debug(

‎packages/cli/src/lib/wasm/prepare.ts‎

Lines changed: 5 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,9 @@ import {
2424
rm,
2525
writeFile,
2626
} from "node:fs/promises";
27-
import {
28-
basename,
29-
dirname,
30-
isAbsolute,
31-
join,
32-
relative,
33-
resolve,
34-
sep,
35-
} from "node:path";
27+
import { basename, dirname, join, relative, resolve, sep } from "node:path";
3628
import { logger } from "../logger.js";
29+
import { isPathInside, resolveLocalReference } from "../path-utils.js";
3730
import { replaceFile } from "../replace-file.js";
3831
import {
3932
assertWasmHeader,
@@ -404,29 +397,6 @@ function skipRecommendation(quality: DebugQuality): string | null {
404397
return null;
405398
}
406399

407-
/**
408-
* Resolve an `external_debug_info` URL to a local path.
409-
*
410-
* Remote URLs have no local companion to check, so they resolve to nothing.
411-
* Relative paths are taken against the module's own directory, which is how the
412-
* companion filename written during a split is meant to be read.
413-
*/
414-
function resolveExternalDebugPath(
415-
wasmPath: string,
416-
url: string,
417-
): string | null {
418-
if (url.startsWith("http://") || url.startsWith("https://")) {
419-
return null;
420-
}
421-
return isAbsolute(url) ? url : join(dirname(wasmPath), url);
422-
}
423-
424-
/** Whether `path` is `root` or sits below it. */
425-
function isInside(root: string, path: string): boolean {
426-
const rel = relative(resolve(root), resolve(path));
427-
return !(rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel));
428-
}
429-
430400
/**
431401
* Resolve an `external_debug_info` URL to a local file this run may read,
432402
* stamp, and upload.
@@ -439,15 +409,15 @@ function localExternalDebugPath(
439409
url: string,
440410
options: PrepareOptions,
441411
): string | null {
442-
const path = resolveExternalDebugPath(wasmPath, url);
412+
const path = resolveLocalReference(wasmPath, url);
443413
if (!path) {
444414
return null;
445415
}
446416
const roots = [dirname(wasmPath), ...(options.roots ?? [])];
447417
if (options.outDir) {
448418
roots.push(options.outDir);
449419
}
450-
if (roots.some((root) => isInside(root, path))) {
420+
if (roots.some((root) => isPathInside(root, path))) {
451421
return path;
452422
}
453423
log.warn(
@@ -567,7 +537,7 @@ async function countCompanionReferences(
567537
const counts = new Map<string, number>();
568538
for (const path of paths) {
569539
const url = await readExternalDebugInfoFromFile(path);
570-
const companion = url && resolveExternalDebugPath(path, url);
540+
const companion = url && resolveLocalReference(path, url);
571541
if (companion && resolve(companion) !== resolve(path)) {
572542
const key = resolve(companion);
573543
counts.set(key, (counts.get(key) ?? 0) + 1);
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Tests for the shared path containment and reference helpers.
3+
*/
4+
5+
import { join, resolve } from "node:path";
6+
import { describe, expect, test } from "vitest";
7+
import {
8+
isPathInside,
9+
isRemoteUrl,
10+
resolveLocalReference,
11+
} from "../../src/lib/path-utils.js";
12+
13+
describe("isPathInside", () => {
14+
test("accepts the root itself and paths below it", () => {
15+
expect(isPathInside("/dist", "/dist")).toBe(true);
16+
expect(isPathInside("/dist", "/dist/app/main.js")).toBe(true);
17+
expect(isPathInside("/dist/", "/dist/app")).toBe(true);
18+
});
19+
20+
test("rejects parents, siblings and prefix look-alikes", () => {
21+
expect(isPathInside("/dist", "/")).toBe(false);
22+
expect(isPathInside("/dist", "/dist-backup/app.js")).toBe(false);
23+
expect(isPathInside("/dist", "/dist/../etc/passwd")).toBe(false);
24+
});
25+
26+
test("treats a name starting with two dots as a child", () => {
27+
expect(isPathInside("/dist", "/dist/..config")).toBe(true);
28+
});
29+
30+
test("resolves relative paths against the working directory", () => {
31+
expect(isPathInside(".", join(process.cwd(), "src"))).toBe(true);
32+
});
33+
});
34+
35+
describe("isRemoteUrl", () => {
36+
test("matches http and https only", () => {
37+
expect(isRemoteUrl("https://cdn.example.com/app.wasm")).toBe(true);
38+
expect(isRemoteUrl("http://cdn.example.com/app.wasm")).toBe(true);
39+
expect(isRemoteUrl("app.debug.wasm")).toBe(false);
40+
expect(isRemoteUrl("/abs/app.debug.wasm")).toBe(false);
41+
});
42+
});
43+
44+
describe("resolveLocalReference", () => {
45+
test("resolves relative references against the referring file", () => {
46+
expect(resolveLocalReference("/dist/app.wasm", "../symbols/app.wasm")).toBe(
47+
resolve("/symbols/app.wasm"),
48+
);
49+
});
50+
51+
test("keeps absolute references and drops remote ones", () => {
52+
expect(resolveLocalReference("/dist/app.wasm", "/abs/app.wasm")).toBe(
53+
resolve("/abs/app.wasm"),
54+
);
55+
expect(
56+
resolveLocalReference("/dist/app.wasm", "https://cdn/app.wasm"),
57+
).toBeNull();
58+
});
59+
});

0 commit comments

Comments
 (0)