tslaws 0.10.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +7 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +25 -5
  5. package/dist/bundled.js +2 -2
  6. package/dist/bundlerPlugins.d.ts +2 -0
  7. package/dist/bundlerPlugins.js +7 -0
  8. package/dist/certificates.d.ts +139 -0
  9. package/dist/certificates.js +433 -0
  10. package/dist/chc.d.ts +85 -0
  11. package/dist/chc.js +298 -0
  12. package/dist/check.d.ts +13 -1
  13. package/dist/check.js +211 -27
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +175 -34
  16. package/dist/compile.d.ts +15 -5
  17. package/dist/compile.js +198 -69
  18. package/dist/coverage.d.ts +38 -1
  19. package/dist/coverage.js +94 -12
  20. package/dist/e2eApi.js +3 -1
  21. package/dist/generators.js +12 -2
  22. package/dist/github.d.ts +49 -5
  23. package/dist/github.js +107 -24
  24. package/dist/githubCli.d.ts +28 -0
  25. package/dist/githubCli.js +1039 -211
  26. package/dist/hints.js +2 -1
  27. package/dist/init.js +42 -0
  28. package/dist/isolate.d.ts +28 -0
  29. package/dist/isolate.js +262 -0
  30. package/dist/isolatedCheck.d.ts +1 -0
  31. package/dist/isolatedCheck.js +16 -0
  32. package/dist/lawHost.d.ts +50 -0
  33. package/dist/lawHost.js +199 -0
  34. package/dist/lawRuntime.d.ts +39 -0
  35. package/dist/lawRuntime.js +242 -0
  36. package/dist/lock.d.ts +49 -9
  37. package/dist/lock.js +132 -21
  38. package/dist/mcp.js +28 -7
  39. package/dist/mutate.d.ts +4 -0
  40. package/dist/mutate.js +7 -1
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +4 -0
  43. package/dist/pluginHooks.d.ts +16 -0
  44. package/dist/pluginHooks.js +48 -0
  45. package/dist/pluginHost.d.ts +5 -0
  46. package/dist/pluginHost.js +43 -0
  47. package/dist/pluginWorker.d.ts +1 -0
  48. package/dist/pluginWorker.js +40 -0
  49. package/dist/plural.d.ts +2 -0
  50. package/dist/plural.js +4 -0
  51. package/dist/pool.d.ts +80 -7
  52. package/dist/pool.js +222 -11
  53. package/dist/projects.d.ts +43 -1
  54. package/dist/projects.js +283 -11
  55. package/dist/promote.d.ts +56 -2
  56. package/dist/promote.js +429 -13
  57. package/dist/property.js +5 -1
  58. package/dist/propertyWorker.js +7 -0
  59. package/dist/proposals.d.ts +52 -4
  60. package/dist/proposals.js +484 -21
  61. package/dist/reporters.js +5 -1
  62. package/dist/runtimeEnv.d.ts +13 -5
  63. package/dist/runtimeEnv.js +48 -10
  64. package/dist/sandbox.d.ts +98 -0
  65. package/dist/sandbox.js +673 -0
  66. package/dist/sandboxGuard.d.ts +56 -0
  67. package/dist/sandboxGuard.js +249 -0
  68. package/dist/seal.d.ts +9 -0
  69. package/dist/seal.js +426 -0
  70. package/dist/security/cli.d.ts +6 -0
  71. package/dist/security/cli.js +39 -0
  72. package/dist/security/cwe.d.ts +14 -0
  73. package/dist/security/cwe.js +40 -0
  74. package/dist/security/deps/cache.d.ts +28 -0
  75. package/dist/security/deps/cache.js +107 -0
  76. package/dist/security/deps/config.d.ts +16 -0
  77. package/dist/security/deps/config.js +43 -0
  78. package/dist/security/deps/imports.d.ts +4 -0
  79. package/dist/security/deps/imports.js +33 -0
  80. package/dist/security/deps/lockfiles.d.ts +23 -0
  81. package/dist/security/deps/lockfiles.js +153 -0
  82. package/dist/security/deps/osv.d.ts +66 -0
  83. package/dist/security/deps/osv.js +137 -0
  84. package/dist/security/deps/run.d.ts +54 -0
  85. package/dist/security/deps/run.js +135 -0
  86. package/dist/security/deps/severity.d.ts +26 -0
  87. package/dist/security/deps/severity.js +78 -0
  88. package/dist/security/generators.d.ts +9 -0
  89. package/dist/security/generators.js +36 -0
  90. package/dist/security/index.d.ts +27 -0
  91. package/dist/security/index.js +18 -0
  92. package/dist/security/integers.d.ts +31 -0
  93. package/dist/security/integers.js +105 -0
  94. package/dist/security/law.d.ts +54 -0
  95. package/dist/security/law.js +54 -0
  96. package/dist/security/pathTraversal.d.ts +29 -0
  97. package/dist/security/pathTraversal.js +146 -0
  98. package/dist/security/prototypePollution.d.ts +30 -0
  99. package/dist/security/prototypePollution.js +142 -0
  100. package/dist/security/redirect.d.ts +21 -0
  101. package/dist/security/redirect.js +154 -0
  102. package/dist/security/redos.d.ts +21 -0
  103. package/dist/security/redos.js +93 -0
  104. package/dist/security/validation.d.ts +25 -0
  105. package/dist/security/validation.js +89 -0
  106. package/dist/security/xss.d.ts +21 -0
  107. package/dist/security/xss.js +90 -0
  108. package/dist/settings.d.ts +20 -0
  109. package/dist/settings.js +32 -0
  110. package/dist/smt.d.ts +29 -1
  111. package/dist/smt.js +239 -107
  112. package/dist/smtWorker.d.ts +1 -0
  113. package/dist/smtWorker.js +26 -0
  114. package/dist/solvers.d.ts +9 -0
  115. package/dist/solvers.js +11 -5
  116. package/dist/symbolic.d.ts +54 -1
  117. package/dist/symbolic.js +239 -13
  118. package/dist/tsconfigResolve.d.ts +28 -0
  119. package/dist/tsconfigResolve.js +141 -0
  120. package/dist/types.d.ts +28 -0
  121. package/hooks/claude-hook.mjs +2 -0
  122. package/package.json +18 -6
@@ -0,0 +1,673 @@
1
+ // A hard runtime boundary for law execution. Laws, and the helpers a proposal brings, may be written by an agent, and a
2
+ // static check cannot fence in JavaScript. So node laws run in a child process (lawHost.ts) started under Node's permission
3
+ // model: it may read the project, its `node_modules` and the tslaws package and nothing else, write nothing, and start no
4
+ // process, worker, addon or WASI instance; code from strings is off (`--disallow-code-generation-from-strings`); and a
5
+ // module guard (sandboxGuard.ts) refuses to load anything the parent did not review. The parent trusts nothing that
6
+ // comes back: `readOutcome` rebuilds each answer field by field, as `readReport` does for a check's report (isolate.ts).
7
+ //
8
+ // What the process cannot do for itself, the parent does first, as trusted code: transform the reviewed files that Node
9
+ // cannot load as written (TypeScript source outside the build, files in a project format through `bundlerPlugins`) and
10
+ // hand over the result. What it cannot hold: laws that drive a browser need processes, so end-to-end laws run outside it
11
+ // (browser laws run in the page, behind the browser's own boundary), and so they are refused unless the person allows
12
+ // them (`--allow-e2e`). `--no-sandbox` turns it all off, with a warning.
13
+ import { fork } from 'node:child_process';
14
+ import { createHash, randomBytes } from 'node:crypto';
15
+ import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
16
+ import { homedir } from 'node:os';
17
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+ import ts from 'typescript';
20
+ import { lawEnv, readConfig } from "./coverage.js";
21
+ import { scrubbedEnv } from "./isolate.js";
22
+ import { runtimeOf, transformSource } from "./lawRuntime.js";
23
+ import { pluginExtensionNeeded } from "./pluginHooks.js";
24
+ import { transformPluginFile } from "./pluginHost.js";
25
+ import { budget, jobs, WorkerPool } from "./pool.js";
26
+ import { decodeExample } from "./regressions.js";
27
+ import { normal } from "./sandboxGuard.js";
28
+ import { sealedFiles } from "./seal.js";
29
+ import { nearestTsconfig } from "./tsconfigResolve.js";
30
+ /** The permission flag this Node has, or undefined when it has none (before Node 20). */
31
+ export function permissionFlag(version = process.versions.node) {
32
+ const [major = 0, minor = 0] = version.split('.').map(Number);
33
+ // `--permission` is the stable name from 22.13 and 23.5; earlier versions that have the model call it experimental.
34
+ if (major > 23 || (major === 23 && minor >= 5) || (major === 22 && minor >= 13))
35
+ return '--permission';
36
+ return major >= 20 ? '--experimental-permission' : undefined;
37
+ }
38
+ /** Whether the module guard can cover `import` as well as `require`: synchronous loader hooks came in 22.15 and 23.5. */
39
+ export function hasLoaderHooks(version = process.versions.node) {
40
+ const [major = 0, minor = 0] = version.split('.').map(Number);
41
+ return major > 23 || (major === 23 && minor >= 5) || (major === 22 && minor >= 15);
42
+ }
43
+ let warned = false;
44
+ /**
45
+ * Whether laws run in the sandbox for these options. Fails closed: a Node that cannot enforce the permission model is an
46
+ * error, not a quiet fallback, and `sandbox: false` (`--no-sandbox`) is the explicit way out and says what it gives up.
47
+ */
48
+ export function useSandbox(options, version = process.versions.node) {
49
+ if (options.sandbox === false) {
50
+ if (!warned) {
51
+ warned = true;
52
+ process.stderr.write('tslaws: warning: --no-sandbox: laws run with full access to this machine (files, processes and network). ' +
53
+ 'Use it only for laws and helpers you wrote or reviewed.\n');
54
+ }
55
+ return false;
56
+ }
57
+ // Both are needed: the permission model is the fence, and the hooks keep an `import()` inside the reviewed set.
58
+ if (permissionFlag(version) === undefined || !hasLoaderHooks(version))
59
+ throw new Error(`tslaws runs laws in a sandbox built on Node's permission model and loader hooks, which need Node 22.15, 23.5 or later (this is Node ${version}). ` +
60
+ 'Upgrade Node, or pass --no-sandbox to run the laws with full access to this machine.');
61
+ return true;
62
+ }
63
+ let warnedE2e = false;
64
+ /** Says once that end-to-end laws are running outside the sandbox because the person allowed it. */
65
+ export function warnE2e() {
66
+ if (warnedE2e)
67
+ return;
68
+ warnedE2e = true;
69
+ process.stderr.write('tslaws: warning: --allow-e2e: end-to-end laws run outside the sandbox, with full access to this machine ' +
70
+ '(files, processes and network). Use it only for laws and helpers you wrote or reviewed.\n');
71
+ }
72
+ /** Only these of the parent's own flags reach the process: resource limits and TypeScript support, never code loaders. */
73
+ const keptFlag = /^--(experimental-strip-types|experimental-transform-types|no-experimental-strip-types|max-old-space-size=\d+|max-semi-space-size=\d+|stack-size=\d+)$/;
74
+ /**
75
+ * The packages' trees: every `node_modules` above `from`, and the trees its symlinks (workspace packages) point to. A
76
+ * workspace links the project being checked into the root `node_modules` as well; that tree is the project, whose files
77
+ * are reviewed one by one, so it is not a package here (and neither is a tree inside it).
78
+ */
79
+ function modulesAbove(from, project) {
80
+ const modules = [];
81
+ const linked = [];
82
+ for (let dir = resolve(from);; dir = dirname(dir)) {
83
+ const modulesDir = join(dir, 'node_modules');
84
+ if (existsSync(modulesDir)) {
85
+ modules.push(modulesDir);
86
+ const scan = (parent, entries) => {
87
+ for (const entry of entries) {
88
+ const path = join(parent, entry.name);
89
+ if (entry.isSymbolicLink()) {
90
+ try {
91
+ const target = realpathSync(path);
92
+ const isProject = project === target || project.startsWith(target + sep) || target.startsWith(project + sep);
93
+ if (!target.startsWith(modulesDir) && !isProject)
94
+ linked.push(target);
95
+ }
96
+ catch {
97
+ // A link that points nowhere loads nothing.
98
+ }
99
+ }
100
+ else if (entry.isDirectory() && entry.name.startsWith('@'))
101
+ scan(path, readdirSync(path, { withFileTypes: true }));
102
+ }
103
+ };
104
+ scan(modulesDir, readdirSync(modulesDir, { withFileTypes: true }));
105
+ }
106
+ if (dirname(dir) === dir)
107
+ return { modules, linked };
108
+ }
109
+ }
110
+ const realOf = (path) => {
111
+ try {
112
+ return realpathSync(path);
113
+ }
114
+ catch {
115
+ return path;
116
+ }
117
+ };
118
+ /** The tslaws package: `src` or `dist` sits directly under it. */
119
+ const tslawsRoot = fileURLToPath(new URL('../', import.meta.url));
120
+ /** What of it the process loads: its code and its `package.json`, not whatever else sits in the package directory. */
121
+ const tslawsCode = [join(tslawsRoot, 'dist'), join(tslawsRoot, 'src'), join(tslawsRoot, 'package.json')];
122
+ /** The `--allow-fs-read` paths: the project, its `node_modules`, the tslaws package, and the trees workspace links lead to. */
123
+ export function readableBy(cwd, extra = []) {
124
+ const here = modulesAbove(cwd, resolve(cwd));
125
+ const there = modulesAbove(tslawsRoot, resolve(cwd));
126
+ return [
127
+ ...new Set([
128
+ resolve(cwd),
129
+ ...tslawsCode,
130
+ ...here.modules,
131
+ ...here.linked,
132
+ ...there.modules,
133
+ ...there.linked,
134
+ ...extra,
135
+ ]),
136
+ ];
137
+ }
138
+ /** The flags that make a process a sandbox, for a project at `cwd`. */
139
+ export function sandboxFlags(cwd, extra = []) {
140
+ const flag = permissionFlag();
141
+ if (flag === undefined)
142
+ throw new Error('this Node has no permission model');
143
+ return [
144
+ flag,
145
+ ...readableBy(cwd, extra).map((path) => `--allow-fs-read=${path}`),
146
+ '--disallow-code-generation-from-strings',
147
+ '--no-warnings',
148
+ ...process.execArgv.filter((flagged) => keptFlag.test(flagged)),
149
+ ];
150
+ }
151
+ const tsFamily = /\.[cm]?tsx?$/;
152
+ /**
153
+ * The files a law may load besides the build: the entries (what was compiled) and everything the seals of the laws cover,
154
+ * which is what the lock digests (see seal.ts): each laws file, and every module it imports, transitively, including files
155
+ * outside the project and workspace sources. A path computed at run time is not among them, so the guard refuses it.
156
+ */
157
+ export function reviewedFiles(cwd, entries, laws) {
158
+ const covered = sealedFiles(cwd, laws);
159
+ return [...new Set([...entries.map((file) => resolve(cwd, file)), ...covered])].filter((file) => existsSync(file));
160
+ }
161
+ /** The directories a manifest's `workspaces` name (`packages/*`, `apps/web`), as absolute paths. */
162
+ function workspaceDirs(dir) {
163
+ const field = readManifest(join(dir, 'package.json'))?.workspaces;
164
+ const list = Array.isArray(field) ? field : field?.packages;
165
+ if (!Array.isArray(list))
166
+ return [];
167
+ const found = [];
168
+ for (const entry of list) {
169
+ if (typeof entry !== 'string' || entry.startsWith('!'))
170
+ continue;
171
+ const star = entry.search(/[*?{[]/);
172
+ if (star < 0) {
173
+ found.push(resolve(dir, entry));
174
+ continue;
175
+ }
176
+ // `packages/*` and `packages/**`: the directories directly under the fixed part.
177
+ const base = resolve(dir, entry.slice(0, star).replace(/[\\/][^\\/]*$/, '') || '.');
178
+ try {
179
+ for (const child of readdirSync(base, { withFileTypes: true }))
180
+ if (child.isDirectory() && !child.name.startsWith('.'))
181
+ found.push(join(base, child.name));
182
+ }
183
+ catch {
184
+ // A pattern that matches nothing names nothing.
185
+ }
186
+ }
187
+ return found;
188
+ }
189
+ /** The directories the project's tsconfig sends module resolution to: its `paths` targets, `baseUrl` and `references`. */
190
+ function tsconfigDirs(cwd) {
191
+ const config = nearestTsconfig(cwd);
192
+ const dirs = [];
193
+ const options = runtimeOf(cwd)?.options;
194
+ for (const targets of Object.values(options?.paths ?? {}))
195
+ for (const target of Array.isArray(targets) ? targets : [])
196
+ if (typeof target === 'string')
197
+ dirs.push(resolve(cwd, target.replace(/[\\/]?\*.*$/, '') || '.'));
198
+ if (typeof options?.baseUrl === 'string')
199
+ dirs.push(resolve(cwd, options.baseUrl));
200
+ if (config !== undefined) {
201
+ const references = ts.readConfigFile(config, ts.sys.readFile).config?.references;
202
+ for (const reference of Array.isArray(references) ? references : []) {
203
+ const path = reference?.path;
204
+ if (typeof path === 'string')
205
+ dirs.push(resolve(dirname(config), path.replace(/tsconfig[^\\/]*\.json$/, '')));
206
+ }
207
+ }
208
+ return dirs;
209
+ }
210
+ const isInside = (dir, file) => {
211
+ const rel = relative(dir, file);
212
+ return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
213
+ };
214
+ /** The path as the file system has it: links followed, and the case Windows and macOS keep. Itself when it does not exist. */
215
+ function real(path) {
216
+ try {
217
+ return realpathSync.native(path);
218
+ }
219
+ catch {
220
+ return resolve(path);
221
+ }
222
+ }
223
+ /** Paths compare in one case on a file system that ignores it. */
224
+ const folds = process.platform === 'win32' || process.platform === 'darwin' || !ts.sys.useCaseSensitiveFileNames;
225
+ const fold = (path) => (folds ? path.toLowerCase() : path);
226
+ /**
227
+ * The first part of `path` that is a dotfile or a dot directory. A path inside the project is judged below the project,
228
+ * which is readable already wherever it sits. Any other path is judged below the home directory, or in full when it is not
229
+ * under it: what it shares with the project's own path says nothing about it (`~/.work/secret` beside `~/.work/proj`).
230
+ */
231
+ function dottedBelow(path, project) {
232
+ const home = real(homedir());
233
+ const base = isInside(fold(project), fold(path)) ? project : isInside(fold(home), fold(path)) ? home : undefined;
234
+ const parts = path.split(/[/\\]/);
235
+ const skip = base === undefined ? 0 : base.split(/[/\\]/).length;
236
+ return parts.slice(skip).find((part) => part.startsWith('.'));
237
+ }
238
+ /**
239
+ * Why the sandbox may not read below `root` (as the file system names it), or undefined when it may: a file system root,
240
+ * the home directory or a directory above it, or a place named by a dot (`~/.ssh`, `~/.config`). A root inside the project is
241
+ * judged below the project (it is readable already); any other root below the home directory (or in full).
242
+ */
243
+ function unreadableRoot(root, project) {
244
+ if (dirname(root) === root)
245
+ return 'is the root of a file system';
246
+ const home = real(homedir());
247
+ const toHome = relative(fold(root), fold(home));
248
+ if (toHome === '' || (toHome !== '..' && !toHome.startsWith(`..${sep}`) && !isAbsolute(toHome)))
249
+ return 'is the home directory or a directory above it';
250
+ const dotted = dottedBelow(root, project);
251
+ return dotted === undefined ? undefined : `sits in ${dotted}, a dotfile`;
252
+ }
253
+ /** What `grantOutside` told the person already, so a project that is checked again is not told again. */
254
+ const told = new Set();
255
+ const tell = (line) => {
256
+ if (told.has(line))
257
+ return;
258
+ told.add(line);
259
+ process.stderr.write(`tslaws: ${line}\n`);
260
+ };
261
+ /**
262
+ * The files of the reviewed set outside the project that the law process may read, by name. Only these are granted: the
263
+ * packages of the workspace (a `workspaces` field of the root `package.json`), the `paths`, `baseUrl` and `references`
264
+ * targets of the tsconfig, and the directories the person lists under `sandboxReads` in tslaws.json (the declared
265
+ * dependencies already sit in the `node_modules` trees). A dotfile, the home directory and a file system root are refused,
266
+ * as is any other file; each grant and each refusal is printed once.
267
+ */
268
+ export function grantOutside(cwd, outside) {
269
+ const roots = [];
270
+ for (let dir = resolve(cwd);; dir = dirname(dir)) {
271
+ for (const workspace of workspaceDirs(dir))
272
+ roots.push([workspace, 'a workspace package']);
273
+ if (dirname(dir) === dir)
274
+ break;
275
+ }
276
+ for (const dir of tsconfigDirs(cwd))
277
+ roots.push([dir, 'a target of the tsconfig']);
278
+ for (const path of readConfig(cwd).sandboxReads ?? [])
279
+ roots.push([resolve(cwd, path), '"sandboxReads" in tslaws.json']);
280
+ const project = real(cwd);
281
+ const places = roots.map(([root, why]) => ({ root: real(root), why }));
282
+ const granted = [];
283
+ const refused = [];
284
+ for (const file of outside) {
285
+ // What counts is where the file really is, so a link cannot lead from a named directory to a place that is not.
286
+ const actual = real(file);
287
+ const named = places.filter(({ root }) => isInside(fold(root), fold(actual)));
288
+ const dotted = dottedBelow(actual, project);
289
+ const hit = dotted === undefined ? named.find(({ root }) => unreadableRoot(root, project) === undefined) : undefined;
290
+ if (hit !== undefined) {
291
+ granted.push(file);
292
+ tell(`the law sandbox may read ${file} (${hit.why})`);
293
+ continue;
294
+ }
295
+ refused.push(file);
296
+ const [first] = [...named].sort((a, b) => b.root.length - a.root.length);
297
+ const why = first === undefined
298
+ ? undefined
299
+ : `${first.root} ${unreadableRoot(first.root, project) ?? `holds ${dotted}, a dotfile`}`;
300
+ tell(`the law sandbox may not read ${file}${why === undefined ? '' : ` (${why})`}; ` +
301
+ 'to allow it, name its directory under "sandboxReads" in tslaws.json');
302
+ }
303
+ return { granted, refused };
304
+ }
305
+ /** The dependency fields of a manifest that name packages the code may load. */
306
+ const dependencyFields = ['dependencies', 'optionalDependencies', 'peerDependencies'];
307
+ function readManifest(file) {
308
+ try {
309
+ return JSON.parse(readFileSync(file, 'utf8'));
310
+ }
311
+ catch {
312
+ return undefined;
313
+ }
314
+ }
315
+ const namesOf = (manifest, fields) => fields.flatMap((field) => {
316
+ const value = manifest?.[field];
317
+ return typeof value === 'object' && value !== null ? Object.keys(value) : [];
318
+ });
319
+ /**
320
+ * The packages the code may load: those the manifests declare (the project's `package.json` with its dev dependencies,
321
+ * and tslaws's own) and, from each one's manifest, what it declares in turn. Anything else in a `node_modules` was put
322
+ * there by something else, and is not trusted. A package that is a link to a directory outside `node_modules` (a workspace
323
+ * package) is source: its tree is trusted as a tree. The project itself is not a package; its files are reviewed one by one.
324
+ */
325
+ export function trustedPackages(cwd) {
326
+ const project = realOf(resolve(cwd));
327
+ const modules = new Set();
328
+ const linked = new Set();
329
+ const seen = new Set();
330
+ const find = (name, from) => {
331
+ for (let dir = from;; dir = dirname(dir)) {
332
+ const candidate = join(dir, 'node_modules', name);
333
+ if (existsSync(join(candidate, 'package.json')))
334
+ return realOf(candidate);
335
+ if (dirname(dir) === dir)
336
+ return undefined;
337
+ }
338
+ };
339
+ const visit = (name, from) => {
340
+ const dir = find(name, from);
341
+ if (dir === undefined || seen.has(dir))
342
+ return;
343
+ seen.add(dir);
344
+ if (/[\\/]node_modules[\\/]/.test(dir))
345
+ modules.add(normal(dir));
346
+ // The project's own files are reviewed one by one (through the seals), not as a tree.
347
+ else if (dir === project || dir.startsWith(project + sep))
348
+ return;
349
+ else
350
+ linked.add(dir);
351
+ for (const next of namesOf(readManifest(join(dir, 'package.json')), dependencyFields))
352
+ visit(next, dir);
353
+ };
354
+ const manifests = [
355
+ [project, [...dependencyFields, 'devDependencies']],
356
+ [tslawsRoot, dependencyFields],
357
+ ];
358
+ for (const [dir, fields] of manifests)
359
+ for (const name of namesOf(readManifest(join(dir, 'package.json')), fields))
360
+ visit(name, dir);
361
+ return { modules: [...modules], linked: [...linked] };
362
+ }
363
+ /**
364
+ * The reviewed set of a project after a build: the build's output, the files its laws reach, the packages, and the
365
+ * transformed text of what needs transforming. `outDir` is where the build wrote the output of `cwd`.
366
+ */
367
+ export function hostConfig(cwd, entries, outDir, laws) {
368
+ const files = reviewedFiles(cwd, entries, laws);
369
+ // What the process cannot read already (outside the project and outside the trees it is given) needs a grant, by name.
370
+ const trees = readableBy(cwd);
371
+ const { granted } = grantOutside(cwd, files.filter((file) => !trees.some((tree) => file === tree || isInside(tree, file))));
372
+ const base = join(cwd, '.tslaws', 'out');
373
+ const trusted = trustedPackages(cwd);
374
+ const guard = {
375
+ trees: [base],
376
+ files,
377
+ packages: [...tslawsCode, ...trusted.linked],
378
+ modules: trusted.modules,
379
+ };
380
+ const plugins = runtimeOf(cwd)?.bundlerPlugins ?? [];
381
+ const transforms = {};
382
+ const attempt = (key, make) => {
383
+ try {
384
+ transforms[key] = { code: make() };
385
+ }
386
+ catch (error) {
387
+ transforms[key] = { error: error instanceof Error ? error.message : String(error) };
388
+ }
389
+ };
390
+ const modules = files.some((file) => /\.m[jt]s$/.test(file));
391
+ for (const file of files) {
392
+ const at = normal(file);
393
+ const extension = extname(file);
394
+ if (pluginExtensionNeeded(extension)) {
395
+ attempt(`cjs:${at}`, () => transformPluginFile(file, cwd, plugins, 'cjs'));
396
+ if (modules)
397
+ attempt(`esm:${at}`, () => transformPluginFile(file, cwd, plugins, 'esm'));
398
+ }
399
+ else if (tsFamily.test(file)) {
400
+ // A file the build compiled loads from its output; only one it left alone loads as source.
401
+ const compiled = resolve(outDir, relative(cwd, file)).replace(/\.[cm]?tsx?$/, '.js');
402
+ if (!existsSync(compiled))
403
+ attempt(`ts:${at}`, () => transformSource(file, extension));
404
+ }
405
+ }
406
+ // The text of the transforms is part of the key: a process keeps what it was configured with, so edited source needs a new one.
407
+ const key = createHash('sha256')
408
+ .update(JSON.stringify([guard, transforms]))
409
+ .digest('hex');
410
+ return { guard, transforms, outside: granted, key };
411
+ }
412
+ // ---- the process -----------------------------------------------------------------------------------------------------
413
+ /** A law could not be loaded: the compiled module is missing, does not export the law, or loads something unreviewed. */
414
+ export class LawLoadError extends Error {
415
+ }
416
+ /** The largest text taken from a process, and the other limits `readOutcome` holds a reply to. */
417
+ const longest = { text: 20_000, encoded: 200_000, runs: 1_000_000_000 };
418
+ /**
419
+ * A property outcome as plain data, or an error. The process runs the law, so its answer is the law's claim and nothing
420
+ * more: each field is rebuilt from what is checked here, anything else is dropped, and a counterexample that the corpus
421
+ * could not read back is not kept.
422
+ */
423
+ export function readOutcome(value) {
424
+ const fail = (why) => {
425
+ throw new Error(`the law process sent an answer that is not valid: ${why}`);
426
+ };
427
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
428
+ return fail('the outcome is not an object');
429
+ const o = value;
430
+ const text = (input, what, max) => {
431
+ if (input === undefined)
432
+ return undefined;
433
+ if (typeof input !== 'string')
434
+ return fail(`${what} is not text`);
435
+ if (input.length > max)
436
+ return fail(`${what} is longer than ${max} characters`);
437
+ return input;
438
+ };
439
+ if (typeof o.failed !== 'boolean')
440
+ return fail('failed is not a boolean');
441
+ if (typeof o.numRuns !== 'number' || !Number.isSafeInteger(o.numRuns) || o.numRuns < 0 || o.numRuns > longest.runs)
442
+ return fail('numRuns is not a whole number');
443
+ // A seed may be negative (a 32-bit signed integer).
444
+ if (typeof o.seed !== 'number' || !Number.isSafeInteger(o.seed))
445
+ return fail('seed is not a whole number');
446
+ const outcome = { failed: o.failed, numRuns: o.numRuns, seed: o.seed };
447
+ const counterexample = text(o.counterexample, 'the counterexample', longest.text);
448
+ const message = text(o.message, 'the message', longest.text);
449
+ const stack = text(o.stack, 'the stack', longest.text);
450
+ const encoded = text(o.encoded, 'the encoded counterexample', longest.encoded);
451
+ if (counterexample !== undefined)
452
+ outcome.counterexample = counterexample;
453
+ if (message !== undefined)
454
+ outcome.message = message;
455
+ if (stack !== undefined)
456
+ outcome.stack = stack;
457
+ if (encoded !== undefined) {
458
+ try {
459
+ decodeExample(encoded);
460
+ outcome.encoded = encoded;
461
+ }
462
+ catch {
463
+ // Not something the corpus can replay: the failure is still reported, it is just not stored.
464
+ }
465
+ }
466
+ if (outcome.encoded !== undefined && typeof o.regression === 'boolean')
467
+ outcome.regression = o.regression;
468
+ return outcome;
469
+ }
470
+ const hostFile = new URL(`./lawHost${import.meta.url.endsWith('.ts') ? '.ts' : '.js'}`, import.meta.url);
471
+ /** A flag-restricted child that serves one request at a time (the pool hands it to one caller at once). */
472
+ class LawProcess {
473
+ child;
474
+ pending = new Map();
475
+ next = 1;
476
+ configKey;
477
+ /** Answers only requests that carry it. The process learns it from `configure` and no law can read it. */
478
+ token = randomBytes(24).toString('hex');
479
+ constructor(cwd, extra) {
480
+ this.child = fork(hostFile, [], {
481
+ // The allowlisted environment the token-free check process gets (see isolate.ts): no credential, no code loader.
482
+ env: scrubbedEnv(process.env),
483
+ execArgv: sandboxFlags(cwd, extra),
484
+ serialization: 'advanced',
485
+ stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
486
+ windowsHide: true,
487
+ });
488
+ // Neither the process nor its channel may keep the caller alive once the laws are done.
489
+ this.child.unref();
490
+ this.child.channel?.unref();
491
+ this.child.on('message', (reply) => {
492
+ const id = reply?.id;
493
+ const waiting = typeof id === 'number' ? this.pending.get(id) : undefined;
494
+ if (waiting === undefined)
495
+ return;
496
+ this.pending.delete(id);
497
+ waiting.resolve(reply);
498
+ });
499
+ const ended = (why) => {
500
+ for (const waiting of this.pending.values())
501
+ waiting.reject(new Error(why));
502
+ this.pending.clear();
503
+ };
504
+ this.child.on('error', (error) => ended(`the law process could not run: ${error.message}`));
505
+ this.child.on('exit', (code, signal) => ended(`the law process ended without an answer (${signal ?? `exit ${code}`})`));
506
+ }
507
+ /** Fixes what this process may load, once: it takes no second `configure`, so a changed set needs a new process. */
508
+ configure(config) {
509
+ if (this.configKey !== undefined) {
510
+ if (this.configKey !== config.key)
511
+ throw new Error('a law process is configured once');
512
+ return;
513
+ }
514
+ this.configKey = config.key;
515
+ this.child.send({
516
+ type: 'configure',
517
+ token: this.token,
518
+ guard: config.guard,
519
+ transforms: config.transforms,
520
+ });
521
+ }
522
+ request(make) {
523
+ const id = this.next++;
524
+ return new Promise((resolvePromise, reject) => {
525
+ this.pending.set(id, { resolve: resolvePromise, reject });
526
+ this.child.send({ ...make(id), token: this.token }, (error) => {
527
+ if (error !== null) {
528
+ this.pending.delete(id);
529
+ reject(error);
530
+ }
531
+ });
532
+ });
533
+ }
534
+ terminate() {
535
+ this.child.channel?.unref();
536
+ // Not the default SIGTERM: a law that handles it and then spins would never see it run, and would outlive the check.
537
+ this.child.kill('SIGKILL');
538
+ }
539
+ }
540
+ const pools = new Map();
541
+ /** How long a law process may sit unused before it ends. */
542
+ const idleMs = 5000;
543
+ /** The law processes alive now, across every project. */
544
+ export function liveSandboxProcesses() {
545
+ let live = 0;
546
+ for (const { pool } of pools.values())
547
+ live += pool.live;
548
+ return live;
549
+ }
550
+ /**
551
+ * Makes room for a process about to start: the cap is shared by every project, not held by each, so an idle process of
552
+ * another project (or configuration) ends when the budget is already spent. The pool counts the new one before it starts.
553
+ */
554
+ function startProcess(cwd, extra) {
555
+ const cap = jobs();
556
+ for (const { pool } of pools.values()) {
557
+ if (liveSandboxProcesses() <= cap)
558
+ break;
559
+ while (liveSandboxProcesses() > cap && pool.evictOne())
560
+ ;
561
+ }
562
+ return new LawProcess(cwd, extra);
563
+ }
564
+ function poolFor(cwd, extra) {
565
+ const key = JSON.stringify([resolve(cwd), extra]);
566
+ let entry = pools.get(key);
567
+ if (entry === undefined) {
568
+ entry = {
569
+ cwd: resolve(cwd),
570
+ pool: new WorkerPool(() => startProcess(cwd, extra), jobs, idleMs),
571
+ };
572
+ pools.set(key, entry);
573
+ }
574
+ return entry.pool;
575
+ }
576
+ /** Ends the idle law processes of a project and of any project below it, for a scratch copy about to be deleted. */
577
+ export function releaseSandbox(cwd) {
578
+ const top = resolve(cwd);
579
+ for (const [key, { cwd: at, pool }] of pools)
580
+ if (at === top || at.startsWith(top + sep)) {
581
+ pool.close();
582
+ pools.delete(key);
583
+ }
584
+ }
585
+ /** Starts `n` law processes ahead of the first law, so they load while the code compiles. */
586
+ export function warmSandbox(cwd, n) {
587
+ const pool = poolFor(cwd, []);
588
+ // The cap is shared: this project may warm only what the other projects have left.
589
+ pool.warm(Math.min(n, jobs() - (liveSandboxProcesses() - pool.live)));
590
+ }
591
+ /** Runs laws and replays inputs in sandboxed processes for one project, under one reviewed set. */
592
+ export class Sandbox {
593
+ pool;
594
+ config;
595
+ cwd;
596
+ constructor(cwd, config) {
597
+ this.cwd = cwd;
598
+ this.config = config;
599
+ // The files of the reviewed set that sit outside the project (reached through `paths`) are readable by name, and no more.
600
+ this.pool = poolFor(cwd, config.outside);
601
+ }
602
+ /** Sends one request to a process of its own, and gives up on it after `timeoutMs`. */
603
+ ask(timeoutMs, make) {
604
+ // A law process is a slot of the budget while it works; under the law that asked for it, that is the law's own slot.
605
+ return budget.run(() => this.askOnce(timeoutMs, make));
606
+ }
607
+ async askOnce(timeoutMs, make) {
608
+ let current = await this.pool.acquire();
609
+ // A process that was configured for another reviewed set (an earlier check) is not reused: it takes no second configure.
610
+ while (current.configKey !== undefined && current.configKey !== this.config.key) {
611
+ this.pool.discard(current);
612
+ current = await this.pool.acquire();
613
+ }
614
+ let timer;
615
+ try {
616
+ current.configure(this.config);
617
+ const timeout = new Promise((done) => {
618
+ timer = setTimeout(() => done('timeout'), timeoutMs);
619
+ });
620
+ const reply = await Promise.race([current.request(make), timeout]);
621
+ if (reply === 'timeout')
622
+ this.pool.discard(current);
623
+ else
624
+ this.pool.release(current);
625
+ return reply;
626
+ }
627
+ catch (error) {
628
+ this.pool.discard(current);
629
+ throw error;
630
+ }
631
+ finally {
632
+ clearTimeout(timer);
633
+ }
634
+ }
635
+ /** The property test of `law`, `'timeout'` when it does not finish; throws `LawLoadError` when it cannot be loaded. */
636
+ async run(outDir, law, options, plans) {
637
+ const reply = await this.ask(options.propertyTimeoutMs ?? 30000, (id) => ({
638
+ type: 'run',
639
+ id,
640
+ outDir,
641
+ law,
642
+ plans,
643
+ // Functions cannot cross to the process; it needs only the numbers.
644
+ options: { ...options, onEvent: undefined },
645
+ env: lawEnv(options.cwd, 'node'),
646
+ }));
647
+ if (reply === 'timeout')
648
+ return reply;
649
+ if ('error' in reply) {
650
+ if (typeof reply.error !== 'string' || reply.error.length > longest.text)
651
+ throw new Error('the law process sent an error that is not valid');
652
+ throw reply.phase === 'load' ? new LawLoadError(reply.error) : new Error(reply.error);
653
+ }
654
+ if (!('outcome' in reply) || typeof reply.async !== 'boolean')
655
+ throw new Error('the law process sent an answer that is not valid');
656
+ return { outcome: readOutcome(reply.outcome), async: reply.async };
657
+ }
658
+ /**
659
+ * Whether the law holds on `inputs` (a model the prover found), as the prover's replay needs it. A law that hangs or
660
+ * cannot be loaded counts as holding: the model is then not confirmed, and nothing is reported as refuted.
661
+ */
662
+ async holds(outDir, law, inputs, timeoutMs) {
663
+ const reply = await this.ask(timeoutMs, (id) => ({
664
+ type: 'holds',
665
+ id,
666
+ outDir,
667
+ law,
668
+ inputs,
669
+ env: lawEnv(this.cwd, 'node'),
670
+ }));
671
+ return reply === 'timeout' || 'error' in reply || !('holds' in reply) || reply.holds !== false;
672
+ }
673
+ }