session-control-boundary.mjs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import { readdir, readFile } from "node:fs/promises";
  2. import path from "node:path";
  3. import { pathToFileURL } from "node:url";
  4. import ts from "typescript";
  5. const CORE = "packages/session-control/src/";
  6. const ENVIRONMENT_NAMES = new Set([
  7. "process",
  8. "window",
  9. "document",
  10. "navigator",
  11. "global",
  12. "globalThis",
  13. "self",
  14. "fetch",
  15. "XMLHttpRequest",
  16. "WebSocket",
  17. "Worker",
  18. "localStorage",
  19. "sessionStorage",
  20. "Date",
  21. "performance",
  22. "crypto",
  23. "setTimeout",
  24. "setInterval",
  25. "setImmediate",
  26. "eval",
  27. "Function",
  28. "require",
  29. ]);
  30. /** 补上 lint 不检查的动态 import 与 globalThis 绕过;只约束本功能核心,不改变宿主 adapter。 */
  31. export function checkSessionControlSource(file, source) {
  32. const normalized = file.replaceAll("\\", "/");
  33. if (!normalized.startsWith(CORE) || /\.(?:test|spec)\.ts$/.test(normalized)) return [];
  34. const tree = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
  35. const diagnostics = [];
  36. const report = (node, message) => {
  37. diagnostics.push({
  38. file,
  39. line: tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1,
  40. message,
  41. });
  42. };
  43. const checkImport = (node, value) => {
  44. if (!ts.isStringLiteralLike(value)) {
  45. report(node, "Computed imports are not allowed in the control core");
  46. return;
  47. }
  48. const specifier = value.text;
  49. if (specifier === "zod") return;
  50. let target;
  51. if (specifier.startsWith("#session-control/"))
  52. target = `${CORE}${specifier.slice("#session-control/".length)}`;
  53. else if (specifier.startsWith("."))
  54. target = path.posix.normalize(path.posix.join(path.posix.dirname(normalized), specifier));
  55. else {
  56. report(node, `External implementation dependency is forbidden: ${specifier}`);
  57. return;
  58. }
  59. if (!target.startsWith(CORE)) {
  60. report(node, `Import escapes the control core: ${specifier}`);
  61. return;
  62. }
  63. const sourceSurface = normalized.match(/\/application\/(cli|app)\//)?.[1];
  64. // 目录入口与 index 文件具有同一依赖边界,不能用省略文件名绕过。
  65. const targetSurface = target.match(/\/application\/(cli|app)(?:\/|$)/)?.[1];
  66. if (sourceSurface && targetSurface && sourceSurface !== targetSurface)
  67. report(node, "CLI and App use cases cannot import one another");
  68. if (
  69. (target === `${CORE}testing` || target.startsWith(`${CORE}testing/`)) &&
  70. !normalized.startsWith(`${CORE}testing/`)
  71. )
  72. report(node, "Production control code cannot import testing utilities");
  73. };
  74. const isPropertyName = (node) => {
  75. const parent = node.parent;
  76. return (
  77. (ts.isPropertyAccessExpression(parent) && parent.name === node) ||
  78. ((ts.isPropertyAssignment(parent) ||
  79. ts.isPropertySignature(parent) ||
  80. ts.isMethodDeclaration(parent)) &&
  81. parent.name === node)
  82. );
  83. };
  84. const visit = (node) => {
  85. if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier)
  86. checkImport(node, node.moduleSpecifier);
  87. if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
  88. // 核心没有延迟装载的职责,禁动态 import 避免静态依赖门禁被绕过。
  89. report(node, "Dynamic imports belong in host adapters");
  90. }
  91. if (ts.isImportEqualsDeclaration(node))
  92. report(node, "CommonJS imports belong in host adapters");
  93. if (ts.isIdentifier(node) && ENVIRONMENT_NAMES.has(node.text) && !isPropertyName(node))
  94. report(node, `Inject environment capability instead of using ${node.text}`);
  95. if (
  96. ts.isPropertyAccessExpression(node) &&
  97. ts.isIdentifier(node.expression) &&
  98. node.expression.text === "Math" &&
  99. node.name.text === "random"
  100. )
  101. report(node, "Request identity must not depend on ambient randomness");
  102. if (
  103. ts.isElementAccessExpression(node) &&
  104. ts.isIdentifier(node.expression) &&
  105. node.expression.text === "Math" &&
  106. (!ts.isStringLiteralLike(node.argumentExpression) ||
  107. node.argumentExpression.text === "random")
  108. )
  109. report(node, "Computed or random Math access is forbidden in the control core");
  110. if (
  111. ts.isVariableDeclaration(node) &&
  112. node.initializer &&
  113. ts.isIdentifier(node.initializer) &&
  114. node.initializer.text === "Math"
  115. ) {
  116. if (
  117. !ts.isObjectBindingPattern(node.name) ||
  118. node.name.elements.some(
  119. (element) =>
  120. element.dotDotDotToken ||
  121. (element.propertyName ?? element.name).getText(tree) === "random",
  122. )
  123. )
  124. report(node, "Do not alias ambient Math randomness");
  125. }
  126. ts.forEachChild(node, visit);
  127. };
  128. visit(tree);
  129. return diagnostics;
  130. }
  131. async function checkFiles(root, directory) {
  132. const entries = await readdir(directory, { withFileTypes: true });
  133. const results = await Promise.all(
  134. entries.map(async (entry) => {
  135. const file = path.join(directory, entry.name);
  136. if (entry.isDirectory()) return checkFiles(root, file);
  137. if (!entry.isFile() || !entry.name.endsWith(".ts") || entry.name.endsWith(".d.ts")) return [];
  138. return checkSessionControlSource(path.relative(root, file), await readFile(file, "utf8"));
  139. }),
  140. );
  141. return results.flat();
  142. }
  143. if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
  144. const root = path.resolve(import.meta.dirname, "../..");
  145. const diagnostics = await checkFiles(root, path.join(root, CORE));
  146. for (const item of diagnostics) console.error(`${item.file}:${item.line}: ${item.message}`);
  147. if (diagnostics.length) process.exitCode = 1;
  148. else console.log("session-control: isolated core dependency checks passed");
  149. }