Skip to content

Commit 62275ec

Browse files
committed
fix: make plugin boundary scanner linear and complete
1 parent 65c4c31 commit 62275ec

2 files changed

Lines changed: 216 additions & 27 deletions

File tree

‎scripts/lib/guard-inventory-utils.mjs‎

Lines changed: 95 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -119,40 +119,108 @@ export function writeLine(stream, text) {
119119
stream.write(`${text}\n`);
120120
}
121121

122+
function hasSupplementalModuleReference(ts, source, acceptSpecifier) {
123+
const checkUrl = source.includes("new") && source.includes("import") && source.includes("meta");
124+
const interpolationStart = source.indexOf("${");
125+
const checkRequire =
126+
interpolationStart >= 0 &&
127+
(source.includes("require") || source.indexOf("\\u", interpolationStart + 2) >= 0);
128+
const interpolatedSlash =
129+
interpolationStart < 0 ? -1 : source.indexOf("/", interpolationStart + 2);
130+
const checkTemplateImport =
131+
interpolatedSlash >= 0 && source.indexOf("import", interpolatedSlash + 1) >= 0;
132+
const checkNamespaceExport =
133+
source.includes("export") && source.includes("*") && source.includes("as");
134+
if (!checkUrl && !checkRequire && !checkTemplateImport && !checkNamespaceExport) {
135+
return false;
136+
}
137+
138+
const scanner = ts.createScanner(
139+
ts.ScriptTarget.Latest,
140+
true,
141+
ts.LanguageVariant.Standard,
142+
source,
143+
);
144+
const kinds = ts.SyntaxKind;
145+
const templateBraceDepths = [];
146+
const scanAcceptedSpecifier = () => {
147+
const token = scanner.scan();
148+
return (
149+
(token === kinds.StringLiteral || token === kinds.NoSubstitutionTemplateLiteral) &&
150+
acceptSpecifier(scanner.getTokenValue())
151+
);
152+
};
153+
154+
for (let token = scanner.scan(); token !== kinds.EndOfFileToken; token = scanner.scan()) {
155+
if (
156+
checkUrl &&
157+
token === kinds.NewKeyword &&
158+
scanner.lookAhead(
159+
() =>
160+
scanner.scan() === kinds.Identifier &&
161+
scanner.getTokenValue() === "URL" &&
162+
scanner.scan() === kinds.OpenParenToken &&
163+
scanAcceptedSpecifier(),
164+
)
165+
) {
166+
return true;
167+
}
168+
if (
169+
checkRequire &&
170+
(token === kinds.RequireKeyword ||
171+
(token === kinds.Identifier && scanner.getTokenValue() === "require")) &&
172+
scanner.lookAhead(() => scanner.scan() === kinds.OpenParenToken && scanAcceptedSpecifier())
173+
) {
174+
return true;
175+
}
176+
if (
177+
checkNamespaceExport &&
178+
token === kinds.ExportKeyword &&
179+
scanner.lookAhead(() => {
180+
let next = scanner.scan();
181+
if (next === kinds.TypeKeyword) {
182+
next = scanner.scan();
183+
}
184+
return next === kinds.AsteriskToken && scanner.scan() === kinds.AsKeyword;
185+
})
186+
) {
187+
return true;
188+
}
189+
190+
// A context-free slash may start a regexp whose `}` would corrupt interpolation tracking.
191+
if (
192+
templateBraceDepths.length > 0 &&
193+
(token === kinds.SlashToken || token === kinds.SlashEqualsToken)
194+
) {
195+
return true;
196+
}
197+
198+
// Resume after each nested interpolation; otherwise template tails swallow later imports.
199+
if (token === kinds.TemplateHead) {
200+
templateBraceDepths.push(0);
201+
} else if (token === kinds.OpenBraceToken && templateBraceDepths.length > 0) {
202+
templateBraceDepths[templateBraceDepths.length - 1] += 1;
203+
} else if (token === kinds.CloseBraceToken && templateBraceDepths.length > 0) {
204+
const index = templateBraceDepths.length - 1;
205+
if (templateBraceDepths[index] > 0) {
206+
templateBraceDepths[index] -= 1;
207+
} else if (scanner.reScanTemplateToken(false) === kinds.TemplateTail) {
208+
templateBraceDepths.pop();
209+
}
210+
}
211+
}
212+
213+
return false;
214+
}
215+
122216
/** Lexically reject clean files before parsing candidate module-boundary violations. */
123217
export function collectModuleReferencesFromSource(source, options = {}) {
124218
const ts = options.ts ?? (cachedTypeScript ??= require("typescript"));
125219
const acceptSpecifier = options.acceptSpecifier ?? (() => true);
126220
const candidates = ts.preProcessFile(source, true, true).importedFiles;
127-
const mayContainImportMetaUrl =
128-
source.includes("new") &&
129-
source.includes("import") &&
130-
source.includes("meta") &&
131-
[
132-
...source.matchAll(
133-
/\bnew(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)+[A-Za-z_$\\][\w$\\{}]*(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*\((?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*(["'\x60])((?:\\[\s\S]|(?!\1)[^\\])*)\1/gu,
134-
),
135-
].some((match) => match[2].includes("\\") || acceptSpecifier(match[2]));
136-
// The TypeScript preprocessor visits imports, but not require calls, in template expressions.
137-
const mayContainEmbeddedRequire =
138-
source.includes("$") &&
139-
source.includes("{") &&
140-
source.includes("require") &&
141-
[
142-
...source.matchAll(
143-
/\brequire(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*\((?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*(["'\x60])((?:\\[\s\S]|(?!\1)[^\\])*)\1/gu,
144-
),
145-
].some((match) => match[2].includes("\\") || acceptSpecifier(match[2]));
146-
// TypeScript's lexical preprocessor omits namespace re-exports, so never drop that edge.
147-
const mayContainNamespaceExport =
148-
/\bexport(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*(?:type(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*)?\*(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*as\b/u.test(
149-
source,
150-
);
151221
if (
152222
!candidates.some(({ fileName }) => acceptSpecifier(fileName)) &&
153-
!mayContainImportMetaUrl &&
154-
!mayContainEmbeddedRequire &&
155-
!mayContainNamespaceExport
223+
!hasSupplementalModuleReference(ts, source, acceptSpecifier)
156224
) {
157225
return [];
158226
}

‎test/architecture-smells.test.ts‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,17 @@ describe("architecture boundary module reference scanner", () => {
2727
templateQuote,
2828
kind: "dynamic-import",
2929
},
30+
{
31+
name: "dynamic import after a regexp brace inside template interpolation",
32+
source: 'const message = `${/}/.test("safe") ? import("../../src/private.js") : null}`',
33+
kind: "dynamic-import",
34+
},
35+
{
36+
name: "commented dynamic import after a regexp character-class brace",
37+
source:
38+
'const message = `${/[}]/.test("safe") ? import /* gap */ ("../../src/private.js", { with: { type: "json" } }) : null}`',
39+
kind: "dynamic-import",
40+
},
3041
{
3142
name: "CommonJS require",
3243
source: 'require("../../src/private.js")',
@@ -42,6 +53,46 @@ describe("architecture boundary module reference scanner", () => {
4253
templateQuote,
4354
kind: "commonjs-require",
4455
},
56+
{
57+
name: "CommonJS require inside nested template interpolation",
58+
source: 'const message = `outer ${`inner ${require("../../src/private.js")}`} tail`',
59+
kind: "commonjs-require",
60+
},
61+
{
62+
name: "CommonJS require with a Unicode-escaped first character inside interpolation",
63+
source: 'const message = `${\\u0072equire("../../src/private.js")}`',
64+
kind: "commonjs-require",
65+
},
66+
{
67+
name: "CommonJS require with a Unicode-escaped middle character inside interpolation",
68+
source: 'const message = `${r\\u0065quire("../../src/private.js")}`',
69+
kind: "commonjs-require",
70+
},
71+
{
72+
name: "CommonJS require with a Unicode-escaped braced character inside interpolation",
73+
source: 'const message = `${\\u{72}equire("../../src/private.js")}`',
74+
kind: "commonjs-require",
75+
},
76+
{
77+
name: "CommonJS require with a Unicode-escaped last character inside interpolation",
78+
source: 'const message = `${requir\\u0065("../../src/private.js")}`',
79+
kind: "commonjs-require",
80+
},
81+
{
82+
name: "CommonJS require after a regexp brace inside template interpolation",
83+
source: 'const message = `${/}/.test("safe") ? require("../../src/private.js") : null}`',
84+
kind: "commonjs-require",
85+
},
86+
{
87+
name: "CommonJS require after a regexp character-class brace inside interpolation",
88+
source: 'const message = `${/[}]/.test("safe") ? require("../../src/private.js") : null}`',
89+
kind: "commonjs-require",
90+
},
91+
{
92+
name: "CommonJS require after division inside template interpolation",
93+
source: 'const message = `${(24 / 2) ? require("../../src/private.js") : null}`',
94+
kind: "commonjs-require",
95+
},
4596
{
4697
name: "TypeScript import-equals require",
4798
source: 'import privateModule = require("../../src/private.js")',
@@ -57,6 +108,23 @@ describe("architecture boundary module reference scanner", () => {
57108
source: 'new \\u0055RL("../../src/private.js", import.meta.url)',
58109
kind: "import-meta-url",
59110
},
111+
{
112+
name: "import.meta URL with a template specifier",
113+
source: "new URL(`../../src/private.js`, import.meta.url)",
114+
kind: "import-meta-url",
115+
},
116+
{
117+
name: "import.meta URL following a completed template interpolation",
118+
source:
119+
'const message = `prefix ${"allowed"} tail`; new URL("../../src/private.js", import.meta.url)',
120+
kind: "import-meta-url",
121+
},
122+
{
123+
name: "import.meta URL after a regexp brace inside template interpolation",
124+
source:
125+
'const message = `${/}/.test("safe") ? new URL("../../src/private.js", import.meta.url) : null}`',
126+
kind: "import-meta-url",
127+
},
60128
{
61129
name: "runtime namespace re-export",
62130
source: 'export /* gap */ * /* gap */ as privateModule from "../../src/private.js"',
@@ -67,6 +135,12 @@ describe("architecture boundary module reference scanner", () => {
67135
source: 'export type * as privateModule from "../../src/private.js"',
68136
kind: "export",
69137
},
138+
{
139+
name: "namespace re-export following nested template interpolations",
140+
source:
141+
'const message = `outer ${`inner ${1}`} tail`; export * as privateModule from "../../src/private.js"',
142+
kind: "export",
143+
},
70144
{
71145
name: "TypeScript import type",
72146
source: 'type PrivateModule = typeof import("../../src/private.js")',
@@ -98,11 +172,58 @@ describe("architecture boundary module reference scanner", () => {
98172
).toEqual([]);
99173
});
100174

175+
it.each([
176+
'const message = `${(24 / 2) ? require("../../src/allowed.js") : null}`',
177+
'const message = `${/}/.test("safe") ? require("../../src/allowed.js") : null}`',
178+
'const message = `${\\u0072equire("../../src/allowed.js")}`',
179+
'const message = `${/}/.test("safe") ? import("../../src/allowed.js") : null}`',
180+
])("keeps ordinary division and regexp fallback free of false positives", (source) => {
181+
expect(
182+
collectModuleReferencesFromSource(source, {
183+
acceptSpecifier: (specifier) => specifier === forbiddenPath,
184+
}),
185+
).toEqual([]);
186+
});
187+
101188
it("preserves the actual source line for multiline guarded imports", () => {
102189
expect(
103190
collectModuleReferencesFromSource('\n\nimport /* comment */ "../../src/private.js";', {
104191
acceptSpecifier: (specifier) => specifier === forbiddenPath,
105192
}),
106193
).toEqual([{ kind: "import", line: 3, specifier: forbiddenPath }]);
107194
});
195+
196+
it.each([
197+
{
198+
name: "import.meta URL",
199+
createSource: (comments: string) =>
200+
"new /*" + comments + '! URL("../../src/allowed.js", import.meta.url)',
201+
},
202+
{
203+
name: "embedded CommonJS require",
204+
createSource: (comments: string) =>
205+
"const message = " +
206+
templateQuote +
207+
"$" +
208+
"{require /*" +
209+
comments +
210+
'! ("../../src/allowed.js")}' +
211+
templateQuote,
212+
},
213+
{
214+
name: "namespace re-export",
215+
createSource: (comments: string) =>
216+
"export /*" + comments + '! * as privateModule from "../../src/allowed.js"',
217+
},
218+
])("scans hostile repeated comments in linear time for $name", ({ createSource }) => {
219+
const source = createSource("*//*".repeat(8_192));
220+
const startedAt = performance.now();
221+
222+
expect(
223+
collectModuleReferencesFromSource(source, {
224+
acceptSpecifier: (specifier) => specifier === forbiddenPath,
225+
}),
226+
).toEqual([]);
227+
expect(performance.now() - startedAt).toBeLessThan(1_000);
228+
});
108229
});

0 commit comments

Comments
 (0)