Skip to content

Commit efd64bc

Browse files
fix(javascript): match source-map originals that name parent directories (morluto#1215)
* fix(javascript): match source-map originals that name parent directories * fix(javascript): resolve parent segments against the source map's directory * fix(javascript): resolve source originals against their map location * fix(javascript): preserve URI and empty source map path semantics * fix(javascript): separate source URL paths from opaque URI payloads * fix(javascript): preserve filesystem names during URI classification * style(javascript): format source URI presence guard * fix(javascript): resolve source map references with URL semantics * fix(javascript): preserve literal UNC source map paths --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
1 parent ffaf55f commit efd64bc

4 files changed

Lines changed: 713 additions & 75 deletions

File tree

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { posix } from "node:path";
2+
import { fileURLToPath, pathToFileURL } from "node:url";
3+
4+
interface SourceMapPath {
5+
readonly value: string;
6+
readonly scope: "artifact-relative" | "suffix";
7+
}
8+
9+
/** Resolve a source-map URL reference without changing its recorded identity. */
10+
export const resolveJavaScriptSourceMapPath = (
11+
source: string,
12+
mapPath?: string,
13+
): SourceMapPath | null => {
14+
const portable = source.replaceAll("\\", "/");
15+
const windowsPath = /^[a-z]:\//iu.test(portable) || source.startsWith("\\\\");
16+
// Preserve parent traversal rather than letting URL resolution clamp at '/'.
17+
const anchor = `/${"source/".repeat(portable.split("/").length + 1)}`;
18+
const directory = posix.join(
19+
anchor,
20+
posix.dirname(mapPath?.replaceAll("\\", "/") ?? "."),
21+
);
22+
const base = pathToFileURL(`${directory}/`, { windows: false });
23+
const absolute = windowsPath ? windowsFileUrl(source) : URL.parse(source);
24+
const resolved = windowsPath ? absolute : URL.parse(source, base);
25+
if (
26+
resolved === null ||
27+
!resolved.pathname.startsWith("/") ||
28+
resolved.pathname.endsWith("/")
29+
)
30+
return null;
31+
const relative =
32+
absolute === null
33+
? !portable.startsWith("/")
34+
: absolute.href !== resolved.href;
35+
const path = decodedUrlPath(resolved);
36+
if (path === null) return null;
37+
const value = relative
38+
? posix.relative(anchor, path)
39+
: path.replace(/^\/+/, "");
40+
if (value === "" || value === ".." || value.startsWith("../")) return null;
41+
return {
42+
value,
43+
scope: relative && mapPath !== undefined ? "artifact-relative" : "suffix",
44+
};
45+
};
46+
47+
const windowsFileUrl = (path: string): URL | null => {
48+
try {
49+
return pathToFileURL(path, { windows: true });
50+
} catch (cause: unknown) {
51+
if (cause instanceof TypeError) return null;
52+
throw cause;
53+
}
54+
};
55+
56+
const decodedUrlPath = (url: URL): string | null => {
57+
// Encoded separators must not manufacture a different filesystem hierarchy.
58+
if (/%(?:2f|5c)/iu.test(url.pathname)) return null;
59+
try {
60+
if (url.protocol === "file:")
61+
return fileURLToPath(url, {
62+
windows: url.hostname !== "" && url.hostname !== "localhost",
63+
}).replaceAll("\\", "/");
64+
return `${url.host}${decodeURIComponent(url.pathname)}`;
65+
} catch (cause: unknown) {
66+
if (cause instanceof URIError || cause instanceof TypeError) return null;
67+
throw cause;
68+
}
69+
};

‎src/domain/javascript/sourceToBundleComparison.test.ts‎

Lines changed: 43 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
createJavaScriptApplicationNode,
66
} from "./javascriptApplicationGraph.js";
77
import { createHistoricalSourceGraph } from "../referenceSourceGraph.js";
8+
import { compareCodePoints } from "../canonicalOrdering.js";
89
import { compareSourceToBundle } from "./sourceToBundleComparison.js";
910
import {
1011
SOURCE_TO_BUNDLE_SIGNAL_WEIGHTS,
@@ -187,44 +188,47 @@ describe("source to bundle digest changes", () => {
187188
});
188189

189190
describe("source to bundle path syntax", () => {
190-
it.each(["src/modified#part.ts", "src/modified?part.ts"])(
191-
"preserves literal filesystem punctuation in %s",
192-
(path) => {
193-
const node = moduleNode("punctuated", { path });
194-
const graph = createJavaScriptApplicationGraph({
195-
schema: "JavaScriptApplicationGraph",
196-
root_node_ids: [node.node_id],
197-
nodes: [node],
198-
edges: [],
199-
coverage: {
200-
status: "complete",
201-
truncated: false,
202-
omitted_count: 0,
203-
limits: [],
204-
},
205-
limitations: [],
206-
});
207-
const result = compareSourceToBundle({
208-
reference: historicalGraph("complete", [path]),
209-
application: {
210-
evidenceId: EVIDENCE_ID,
211-
rootArtifactSha256: HASH.artifact,
212-
graph,
213-
},
214-
});
215-
expect(item(result, path)).toMatchObject({
216-
status: "unknown",
217-
current_node_ids: [node.node_id],
218-
candidates: [
219-
expect.objectContaining({
220-
signals: expect.arrayContaining([
221-
expect.objectContaining({ kind: "current-path-exact" }),
222-
]),
223-
}),
224-
],
225-
});
226-
},
227-
);
191+
it.each([
192+
"src/modified#part.ts",
193+
"src/modified?part.ts",
194+
"pkg:app/src/modified#part.ts",
195+
"pkg:app/src/modified?part.ts",
196+
"data:/src/modified.ts",
197+
])("preserves literal filesystem punctuation in %s", (path) => {
198+
const node = moduleNode("punctuated", { path });
199+
const graph = createJavaScriptApplicationGraph({
200+
schema: "JavaScriptApplicationGraph",
201+
root_node_ids: [node.node_id],
202+
nodes: [node],
203+
edges: [],
204+
coverage: {
205+
status: "complete",
206+
truncated: false,
207+
omitted_count: 0,
208+
limits: [],
209+
},
210+
limitations: [],
211+
});
212+
const result = compareSourceToBundle({
213+
reference: historicalGraph("complete", [path]),
214+
application: {
215+
evidenceId: EVIDENCE_ID,
216+
rootArtifactSha256: HASH.artifact,
217+
graph,
218+
},
219+
});
220+
expect(item(result, path)).toMatchObject({
221+
status: "unknown",
222+
current_node_ids: [node.node_id],
223+
candidates: [
224+
expect.objectContaining({
225+
signals: expect.arrayContaining([
226+
expect.objectContaining({ kind: "current-path-exact" }),
227+
]),
228+
}),
229+
],
230+
});
231+
});
228232

229233
it.each([
230234
"https://example.test/src/modified.ts?revision=2#section",
@@ -347,7 +351,7 @@ const historicalGraph = (
347351
content_state: "hashed" as const,
348352
limitations: [],
349353
})),
350-
],
354+
].sort((left, right) => compareCodePoints(left.path, right.path)),
351355
relationships: [],
352356
parse_failures: [],
353357
exclusions: [],

‎src/domain/javascript/sourceToBundleSignals.ts‎

Lines changed: 76 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
type SourceToBundleSignal,
1010
} from "./sourceToBundleComparisonSchemas.js";
1111
import { isDigest } from "../digests.js";
12+
import { resolveJavaScriptSourceMapPath } from "./javascriptSourceMapPaths.js";
1213

1314
type SourceFile = Extract<
1415
HistoricalSourceGraph["entries"][number],
@@ -23,6 +24,8 @@ type CurrentPathKind =
2324
interface CurrentPath {
2425
readonly kind: CurrentPathKind;
2526
readonly value: string;
27+
/** Artifact-relative map resolution identifies one path, not its suffixes. */
28+
readonly allowSuffix: boolean;
2629
}
2730

2831
interface CurrentProjection {
@@ -93,7 +96,9 @@ export const buildSourceToBundleCandidateIndex = (
9396
for (const digest of projection.digests)
9497
addIndexValue(byDigest, digest, projection.node.node_id);
9598
for (const path of projection.paths) {
96-
for (const suffix of pathSuffixes(path.value))
99+
for (const suffix of path.allowSuffix
100+
? pathSuffixes(path.value)
101+
: [path.value])
97102
addIndexValue(byPathSuffix, suffix, projection.node.node_id);
98103
addIndexValue(
99104
byBasename,
@@ -169,16 +174,41 @@ const projectCurrentNode = (node: ApplicationNode): CurrentProjection => {
169174
if (node.identity.strategy === "source-map-original") {
170175
if (node.identity.source_sha256 !== null)
171176
digests.add(node.identity.source_sha256);
172-
addPath(paths, "source-map-original", node.identity.original_source);
177+
const mapLocations = node.observations.flatMap(({ evidence }) =>
178+
evidence.extractor.operation === "parse-local-source-map" &&
179+
evidence.location.available &&
180+
evidence.location.value.kind === "artifact-path"
181+
? [evidence.location.value.path]
182+
: [],
183+
);
184+
if (mapLocations.length === 0)
185+
addPath(paths, "source-map-original", node.identity.original_source);
186+
for (const mapPath of mapLocations)
187+
addPath(
188+
paths,
189+
"source-map-original",
190+
node.identity.original_source,
191+
mapPath,
192+
);
173193
}
174194
if (node.identity.strategy === "canonical-path")
175195
addPath(paths, "canonical-path", node.identity.path);
176196
for (const observation of node.observations) {
177197
const sourceDigest = observation.properties.source_sha256;
178198
if (typeof sourceDigest === "string" && isDigest(sourceDigest))
179199
digests.add(sourceDigest);
180-
for (const key of PATH_PROPERTIES)
181-
addJsonPath(paths, observation.properties[key]);
200+
for (const key of PATH_PROPERTIES) {
201+
const location = observation.evidence.location;
202+
const mapPath =
203+
node.identity.strategy === "source-map-original" &&
204+
observation.evidence.extractor.operation === "parse-local-source-map" &&
205+
(key === "source" || key === "original_source") &&
206+
location.available &&
207+
location.value.kind === "artifact-path"
208+
? location.value.path
209+
: undefined;
210+
addJsonPath(paths, observation.properties[key], mapPath);
211+
}
182212
}
183213
return {
184214
node,
@@ -212,7 +242,10 @@ const candidateSignals = (
212242
signals.push(signal("current-path-exact", source.path, exactPaths));
213243
const suffixPaths = otherPaths
214244
.filter(
215-
({ value }) => value !== source.path && value.endsWith(`/${source.path}`),
245+
({ value, allowSuffix }) =>
246+
allowSuffix &&
247+
value !== source.path &&
248+
value.endsWith(`/${source.path}`),
216249
)
217250
.map(({ value }) => value);
218251
if (suffixPaths.length > 0)
@@ -259,45 +292,70 @@ const matchingPaths = (
259292
): string[] =>
260293
currentPaths
261294
.filter(
262-
({ value }) => value === sourcePath || value.endsWith(`/${sourcePath}`),
295+
({ value, allowSuffix }) =>
296+
value === sourcePath ||
297+
(allowSuffix && value.endsWith(`/${sourcePath}`)),
263298
)
264299
.map(({ value }) => value);
265300

266-
const addJsonPath = (paths: CurrentPath[], value: unknown): void => {
267-
if (typeof value === "string") addPath(paths, "observation-path", value);
301+
const addJsonPath = (
302+
paths: CurrentPath[],
303+
value: unknown,
304+
mapPath?: string,
305+
): void => {
306+
if (typeof value === "string")
307+
addPath(paths, "observation-path", value, mapPath);
268308
};
269309

270310
const addPath = (
271311
paths: CurrentPath[],
272312
kind: CurrentPathKind,
273313
raw: string,
314+
mapPath?: string,
274315
): void => {
316+
if (kind === "source-map-original" || mapPath !== undefined) {
317+
const resolved = resolveJavaScriptSourceMapPath(raw, mapPath);
318+
if (resolved !== null)
319+
paths.push({
320+
kind,
321+
value: resolved.value,
322+
allowSuffix: resolved.scope === "suffix",
323+
});
324+
return;
325+
}
275326
const value = normalizeCurrentPath(raw);
276-
if (value !== null) paths.push({ kind, value });
327+
if (value !== null) paths.push({ kind, value, allowSuffix: true });
277328
};
278329

279-
/** Matches a `scheme://...` URL prefix; bare filesystem paths keep `?`/`#`. */
280330
const SCHEME_URL = /^[a-z][a-z0-9+.-]*:\/\//iu;
281-
/** Matches a `scheme://...` URL prefix with any run of slashes, for stripping. */
282331
const SCHEME_URL_PREFIX = /^[a-z][a-z0-9+.-]*:\/\/+/iu;
283332

284333
const normalizeCurrentPath = (raw: string): string | null => {
285334
const withoutQuery = SCHEME_URL.test(raw)
286335
? (raw.split(/[?#]/u, 1)[0] ?? "")
287336
: raw;
288-
const withoutScheme = withoutQuery.replace(SCHEME_URL_PREFIX, "");
289-
const parts = withoutScheme
290-
.replaceAll("\\", "/")
291-
.split("/")
292-
.filter((part) => part !== "" && part !== ".");
293-
if (parts.length === 0 || parts.includes("..")) return null;
337+
const portable = withoutQuery
338+
.replace(SCHEME_URL_PREFIX, "")
339+
.replaceAll("\\", "/");
340+
const parts: string[] = [];
341+
for (const part of portable.split("/")) {
342+
if (part === "" || part === ".") continue;
343+
if (part === "..") {
344+
if (parts.length === 0) return null;
345+
parts.pop();
346+
} else parts.push(part);
347+
}
348+
if (parts.length === 0) return null;
294349
return parts.join("/");
295350
};
296351

297352
const uniquePaths = (paths: readonly CurrentPath[]): CurrentPath[] =>
298353
[
299354
...new Map(
300-
paths.map((path) => [`${path.kind}\0${path.value}`, path]),
355+
paths.map((path) => [
356+
`${path.kind}\0${path.value}\0${String(path.allowSuffix)}`,
357+
path,
358+
]),
301359
).values(),
302360
].sort((left, right) =>
303361
compareCodePoints(

0 commit comments

Comments
 (0)