tslaws 0.9.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 (123) hide show
  1. package/README.md +8 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +36 -7
  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 +215 -28
  14. package/dist/cli.d.ts +4 -0
  15. package/dist/cli.js +324 -41
  16. package/dist/compile.d.ts +17 -1
  17. package/dist/compile.js +244 -25
  18. package/dist/coverage.d.ts +55 -3
  19. package/dist/coverage.js +231 -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 +70 -0
  54. package/dist/projects.js +457 -0
  55. package/dist/promote.d.ts +56 -2
  56. package/dist/promote.js +429 -13
  57. package/dist/property.js +13 -2
  58. package/dist/propertyWorker.js +11 -1
  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 +32 -0
  63. package/dist/runtimeEnv.js +146 -0
  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/env.d.ts +17 -0
  122. package/hooks/claude-hook.mjs +2 -0
  123. package/package.json +22 -6
package/dist/hints.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { plural } from "./plural.js";
1
2
  /** The concrete next action for an agent that reads a result, or undefined when nothing needs doing. */
2
3
  export function hintFor(result) {
3
4
  switch (result.status) {
@@ -19,7 +20,7 @@ export function hintFor(result) {
19
20
  'array length and loop iterations up to --bound (default 4), int values within +-2^26. ' +
20
21
  'Raise the array and loop bound with `--bound N`. Passing; no action needed unless a person wants a full proof.');
21
22
  case 'tested':
22
- return (`Only property-tested${result.runs !== undefined ? ` (${result.runs} runs)` : ''}, not proved: ` +
23
+ return (`Only property-tested${result.runs !== undefined ? ` (${plural(result.runs, 'run')})` : ''}, not proved: ` +
23
24
  `the prover did not lower this law${result.method !== 'property' && result.method !== '' ? ` (${firstLine(result.method)})` : ''}. ` +
24
25
  'Passing; to get a proof, restrict the code to int/bigint/boolean/string and simple control flow. More inputs: `--runs N`.');
25
26
  case 'uncovered':
package/dist/init.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { nearestTsconfig } from "./tsconfigResolve.js";
4
5
  export const hookCommand = 'node node_modules/tslaws/hooks/claude-hook.mjs';
5
6
  export const agentsBegin = '<!-- tslaws:begin -->';
6
7
  export const agentsEnd = '<!-- tslaws:end -->';
@@ -32,6 +33,46 @@ function hasLawsFile(dir) {
32
33
  }
33
34
  return false;
34
35
  }
36
+ /** The nearest `package.json` in `dir` or above it. */
37
+ function nearestPackageJson(dir) {
38
+ for (let current = dir;; current = dirname(current)) {
39
+ const candidate = join(current, 'package.json');
40
+ if (existsSync(candidate))
41
+ return candidate;
42
+ if (dirname(current) === current)
43
+ return undefined;
44
+ }
45
+ }
46
+ /** A project that has none gets the ES-module defaults; one that has them is left as it is. */
47
+ function initModules(cwd) {
48
+ const out = [];
49
+ const pkg = nearestPackageJson(cwd);
50
+ if (pkg === undefined) {
51
+ writeFile(join(cwd, 'package.json'), `${JSON.stringify({ private: true, type: 'module' }, null, 2)}\n`);
52
+ out.push('wrote package.json (ES module project)');
53
+ }
54
+ else {
55
+ let type;
56
+ try {
57
+ type = JSON.parse(readFileSync(pkg, 'utf8')).type;
58
+ }
59
+ catch {
60
+ // An unreadable package.json is the project's to fix; init only reports what it found.
61
+ }
62
+ out.push(type === 'module'
63
+ ? 'kept package.json (already "type": "module")'
64
+ : 'kept package.json (no "type": "module"; add it to make the project an ES module)');
65
+ }
66
+ const config = nearestTsconfig(cwd);
67
+ if (config === undefined) {
68
+ const compilerOptions = { target: 'es2022', module: 'nodenext', strict: true, skipLibCheck: true, noEmit: true };
69
+ writeFile(join(cwd, 'tsconfig.json'), `${JSON.stringify({ compilerOptions }, null, 2)}\n`);
70
+ out.push('wrote tsconfig.json (module nodenext)');
71
+ }
72
+ else
73
+ out.push('kept tsconfig.json (exists)');
74
+ return out;
75
+ }
35
76
  function commandsOf(entries) {
36
77
  return entries.flatMap((e) => Array.isArray(e?.hooks) ? e.hooks.map((h) => String(h?.command)) : []);
37
78
  }
@@ -114,6 +155,7 @@ export function init(options) {
114
155
  writeFile(config, `${JSON.stringify({ cover: ['src/**/*.ts', '!src/**/*.laws.ts'] }, null, 2)}\n`);
115
156
  out.push('wrote tslaws.json');
116
157
  }
158
+ out.push(...initModules(cwd));
117
159
  const ignore = join(cwd, '.gitignore');
118
160
  const ignoreText = existsSync(ignore) ? readFileSync(ignore, 'utf8') : '';
119
161
  // `.tslaws/regressions` is left out on purpose: a team may commit the counterexamples it has found.
@@ -0,0 +1,28 @@
1
+ import type { CheckReport } from './check.ts';
2
+ import type { CheckOptions } from './types.ts';
3
+ /** The environment a law may see: the allowlisted names of `env`, minus any that name a credential. */
4
+ export declare function scrubbedEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
5
+ /**
6
+ * What the parent knows of a project without running any of it: the keys (`file::name`) of the laws its own compile found,
7
+ * of the laws the lock records, and of the functions marked exempt. A report may name only these.
8
+ */
9
+ export interface Expected {
10
+ laws: ReadonlySet<string>;
11
+ lock: ReadonlySet<string>;
12
+ exempt: ReadonlySet<string>;
13
+ }
14
+ /**
15
+ * A report as plain data, or an error. A child (or a results file) is untrusted, so each result is rebuilt from the fields
16
+ * checked here and everything else, certificates included, is dropped. The keys must be exactly the project's laws, plus
17
+ * the removals, exemptions and uncovered functions the parent's own view allows; nothing else is taken on trust. What a
18
+ * law says of itself (its status, a counterexample) is the law's own claim and stays one.
19
+ */
20
+ export declare function readReport(value: unknown, expected: Expected): CheckReport;
21
+ /** What the child is told: the options as data (no callbacks cross the boundary). */
22
+ export type ChildRequest = {
23
+ options: Omit<CheckOptions, 'onEvent'>;
24
+ enforceLock: boolean;
25
+ jobs?: number;
26
+ };
27
+ /** Runs `check(options, enforceLock)` in a credential-free child and returns its validated report. */
28
+ export declare function checkIsolated(options: CheckOptions, enforceLock: boolean, expected: Expected, env?: NodeJS.ProcessEnv): Promise<CheckReport>;
@@ -0,0 +1,262 @@
1
+ // Runs a check in a child process that holds no credentials. In GitHub mode the process that talks to GitHub holds a
2
+ // token, and a law (or any module a law imports) runs arbitrary code: in a worker thread it shares that process's
3
+ // memory, environment and `/proc/self/environ`. So the laws run here instead, in a child started with an allowlisted
4
+ // environment, and the parent receives the report over IPC as plain data and validates it before it acts on it.
5
+ //
6
+ // What this guarantees: no token is in the child's environment, its `/proc/self/environ` or its `process.env`, and a
7
+ // token that only the parent holds is never sent to it. What it does not: a child can still read the parent's
8
+ // `/proc/<pid>/environ` or memory (same user), which is why the action also runs the laws in a job that never holds
9
+ // the token (see docs/github.md and `--results-out`).
10
+ import { fork } from 'node:child_process';
11
+ import { lawKey } from "./lock.js";
12
+ import { budget, jobs } from "./pool.js";
13
+ /** Names a child may inherit. Everything else, tokens included, is dropped. */
14
+ const allowed = new Set([
15
+ 'PATH',
16
+ 'PATHEXT',
17
+ 'SYSTEMROOT',
18
+ 'WINDIR',
19
+ 'COMSPEC',
20
+ 'HOME',
21
+ 'USERPROFILE',
22
+ 'APPDATA',
23
+ 'LOCALAPPDATA',
24
+ 'PROGRAMFILES',
25
+ 'PROGRAMFILES(X86)',
26
+ 'PROGRAMDATA',
27
+ 'TEMP',
28
+ 'TMP',
29
+ 'TMPDIR',
30
+ 'LANG',
31
+ 'TZ',
32
+ 'CI',
33
+ 'NODE_ENV',
34
+ 'PLAYWRIGHT_BROWSERS_PATH',
35
+ ].map((name) => name.toUpperCase()));
36
+ const prefixes = ['TSC_LAWS_', 'TSLAWS_', 'TSC_TS_', 'LC_'];
37
+ /** A name that suggests a credential is dropped even under an allowed prefix. */
38
+ const secretName = /token|secret|password|passwd|credential|private|api[_-]?key|_key$/i;
39
+ /** Prefixes of the variables a GitHub runner sets, some of which carry credentials (ACTIONS_RUNTIME_TOKEN, ...). */
40
+ const runnerPrefixes = ['ACTIONS_', 'GITHUB_', 'GH_', 'RUNNER_', 'INPUT_'];
41
+ /** The environment a law may see: the allowlisted names of `env`, minus any that name a credential. */
42
+ export function scrubbedEnv(env) {
43
+ const out = {};
44
+ for (const [name, value] of Object.entries(env)) {
45
+ if (value === undefined)
46
+ continue;
47
+ const upper = name.toUpperCase();
48
+ if (runnerPrefixes.some((prefix) => upper.startsWith(prefix)))
49
+ continue;
50
+ if (secretName.test(name))
51
+ continue;
52
+ if (!allowed.has(upper) && !prefixes.some((prefix) => upper.startsWith(prefix)))
53
+ continue;
54
+ out[name] = value;
55
+ }
56
+ // Keep resource limits, and drop everything that loads code (--require, --import, --loader, ...).
57
+ const node = (env.NODE_OPTIONS ?? '')
58
+ .split(/\s+/)
59
+ .filter((flag) => /^--(max-old-space-size|max-semi-space-size|stack-size)=\d+$/.test(flag));
60
+ if (node.length > 0)
61
+ out.NODE_OPTIONS = node.join(' ');
62
+ return out;
63
+ }
64
+ const statuses = [
65
+ 'proved',
66
+ 'bounded',
67
+ 'tested',
68
+ 'open',
69
+ 'failed',
70
+ 'tampered',
71
+ 'uncovered',
72
+ 'error',
73
+ ];
74
+ const proposalReasons = ['added', 'changed', 'removed', 'level', 'exempt'];
75
+ const longest = { path: 1024, method: 200, text: 20000, assumptions: 100 };
76
+ /**
77
+ * A report as plain data, or an error. A child (or a results file) is untrusted, so each result is rebuilt from the fields
78
+ * checked here and everything else, certificates included, is dropped. The keys must be exactly the project's laws, plus
79
+ * the removals, exemptions and uncovered functions the parent's own view allows; nothing else is taken on trust. What a
80
+ * law says of itself (its status, a counterexample) is the law's own claim and stays one.
81
+ */
82
+ export function readReport(value, expected) {
83
+ const fail = (why) => {
84
+ throw new Error(`the check's report is not valid: ${why}`);
85
+ };
86
+ const object = (input, what) => {
87
+ if (typeof input !== 'object' || input === null || Array.isArray(input))
88
+ return fail(`${what} is not an object`);
89
+ return input;
90
+ };
91
+ const text = (input, what, max) => {
92
+ if (typeof input !== 'string')
93
+ return fail(`${what} is not text`);
94
+ if (input.length > max)
95
+ return fail(`${what} is longer than ${max} characters`);
96
+ return input;
97
+ };
98
+ const optionalText = (input, what, max) => input === undefined ? undefined : text(input, what, max);
99
+ const whole = (input, what, max) => {
100
+ if (typeof input !== 'number' || !Number.isSafeInteger(input) || input < 0 || input > max)
101
+ return fail(`${what} is not a whole number from 0 to ${max}`);
102
+ return input;
103
+ };
104
+ const known = (set, key) => set.has(key) || [...set].some((member) => member.startsWith(`${key}::`));
105
+ const report = object(value, 'the report');
106
+ if (!Array.isArray(report.results))
107
+ return fail('results is not a list');
108
+ if (report.results.length > 100000)
109
+ return fail('results is too long');
110
+ const compileDiagnostics = text(report.compileDiagnostics, 'compileDiagnostics', longest.text * 10);
111
+ for (const key of ['compileOk', 'lockMissing'])
112
+ if (typeof report[key] !== 'boolean')
113
+ return fail(`${key} is not a boolean`);
114
+ if (!Array.isArray(report.notices) || report.notices.length > 10000)
115
+ return fail('notices is not a list');
116
+ const notices = report.notices.map((n) => text(n, 'a notice', longest.text));
117
+ const results = [];
118
+ const seenLaws = new Set();
119
+ const seenUncovered = new Set();
120
+ for (const entry of report.results) {
121
+ const r = object(entry, 'a result');
122
+ const file = text(r.file, 'a result file', longest.path);
123
+ const name = text(r.name, 'a result name', longest.path);
124
+ const key = lawKey(file, name);
125
+ if (typeof r.status !== 'string' || !statuses.includes(r.status))
126
+ return fail('a result has no status');
127
+ const status = r.status;
128
+ const result = {
129
+ file,
130
+ name,
131
+ line: whole(r.line, 'a result line', 10_000_000),
132
+ status,
133
+ method: text(r.method, 'a result method', longest.method),
134
+ };
135
+ const message = optionalText(r.message, 'a message', longest.text);
136
+ const counterexample = optionalText(r.counterexample, 'a counterexample', longest.text);
137
+ if (message !== undefined)
138
+ result.message = message;
139
+ if (counterexample !== undefined)
140
+ result.counterexample = counterexample;
141
+ if (r.runs !== undefined)
142
+ result.runs = whole(r.runs, 'runs', 1_000_000_000);
143
+ if (r.seed !== undefined) {
144
+ // A seed may be negative (a 32-bit signed integer).
145
+ if (typeof r.seed !== 'number' || !Number.isSafeInteger(r.seed))
146
+ return fail('a seed is not a whole number');
147
+ result.seed = r.seed;
148
+ }
149
+ if (r.assumptions !== undefined) {
150
+ if (!Array.isArray(r.assumptions) || r.assumptions.length > longest.assumptions)
151
+ return fail('assumptions is not a short list');
152
+ result.assumptions = r.assumptions.map((a) => text(a, 'an assumption', longest.path));
153
+ }
154
+ if (r.screenshot !== undefined) {
155
+ const shot = text(r.screenshot, 'a screenshot path', longest.path);
156
+ // A path the parent could be led to read or upload: only one inside the project.
157
+ if (/^([/\\]|[A-Za-z]:)/.test(shot) || shot.split(/[/\\]/).includes('..'))
158
+ return fail('a screenshot path leaves the project');
159
+ result.screenshot = shot;
160
+ }
161
+ if (r.proposal !== undefined) {
162
+ const p = object(r.proposal, 'a proposal');
163
+ if (typeof p.reason !== 'string' || !proposalReasons.includes(p.reason))
164
+ return fail('a proposal has no reason');
165
+ if (typeof p.status !== 'string' ||
166
+ !statuses.includes(p.status) ||
167
+ p.status === 'tampered' ||
168
+ p.status === 'uncovered')
169
+ return fail('a proposal has no status');
170
+ const proposal = {
171
+ reason: p.reason,
172
+ status: p.status,
173
+ method: text(p.method, 'a proposal method', longest.method),
174
+ };
175
+ const proposalCounterexample = optionalText(p.counterexample, 'a proposal counterexample', longest.text);
176
+ const proposalMessage = optionalText(p.message, 'a proposal message', longest.text);
177
+ if (proposalCounterexample !== undefined)
178
+ proposal.counterexample = proposalCounterexample;
179
+ if (proposalMessage !== undefined)
180
+ proposal.message = proposalMessage;
181
+ result.proposal = proposal;
182
+ }
183
+ if (status === 'uncovered') {
184
+ if (seenUncovered.has(key))
185
+ return fail(`${key} is reported twice`);
186
+ seenUncovered.add(key);
187
+ }
188
+ else {
189
+ const kind = result.proposal?.reason;
190
+ const allowed = expected.laws.has(key) ||
191
+ (status === 'tampered' && kind === 'removed' && known(expected.lock, key)) ||
192
+ (status === 'tampered' && kind === 'exempt' && known(expected.exempt, key));
193
+ if (!allowed)
194
+ return fail(`${key} is not a law of this project`);
195
+ const identity = `${key}\0${kind === 'removed' || kind === 'exempt' ? kind : ''}`;
196
+ if (seenLaws.has(identity))
197
+ return fail(`${key} is reported twice`);
198
+ seenLaws.add(identity);
199
+ }
200
+ results.push(result);
201
+ }
202
+ const got = new Set(results.filter((r) => r.status !== 'uncovered').map((r) => lawKey(r.file, r.name)));
203
+ for (const key of expected.laws)
204
+ if (!got.has(key))
205
+ return fail(`${key} has no result`);
206
+ const compileOk = report.compileOk;
207
+ const lockMissing = report.lockMissing;
208
+ return {
209
+ results,
210
+ compileDiagnostics,
211
+ compileOk,
212
+ lockMissing,
213
+ notices,
214
+ // The parent decides this itself from the results it has kept.
215
+ ok: compileOk &&
216
+ !lockMissing &&
217
+ results.every((r) => r.status === 'proved' || r.status === 'bounded' || r.status === 'tested'),
218
+ };
219
+ }
220
+ /** Runs `check(options, enforceLock)` in a credential-free child and returns its validated report. */
221
+ export function checkIsolated(options, enforceLock, expected, env = process.env) {
222
+ // The child is a slot of the budget while it runs, and it is handed the budget's size, not a fresh one of its own.
223
+ return budget.run(() => forkCheck(options, enforceLock, expected, env));
224
+ }
225
+ function forkCheck(options, enforceLock, expected, env) {
226
+ const extension = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
227
+ const { onEvent: _onEvent, ...data } = options;
228
+ return new Promise((resolve, reject) => {
229
+ const child = fork(new URL(`./isolatedCheck${extension}`, import.meta.url), [], {
230
+ env: scrubbedEnv(env),
231
+ execArgv: process.execArgv,
232
+ serialization: 'advanced',
233
+ stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
234
+ windowsHide: true,
235
+ });
236
+ let settled = false;
237
+ const done = (finish) => {
238
+ if (settled)
239
+ return;
240
+ settled = true;
241
+ child.kill();
242
+ finish();
243
+ };
244
+ child.on('message', (message) => {
245
+ done(() => {
246
+ if (message.error !== undefined)
247
+ reject(new Error(message.error));
248
+ else {
249
+ try {
250
+ resolve(readReport(message.report, expected));
251
+ }
252
+ catch (error) {
253
+ reject(error);
254
+ }
255
+ }
256
+ });
257
+ });
258
+ child.on('error', (error) => done(() => reject(error)));
259
+ child.on('exit', (code, signal) => done(() => reject(new Error(`the check process ended without a report (${signal ?? `exit ${code}`})`))));
260
+ child.send({ options: data, enforceLock, jobs: jobs() });
261
+ });
262
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,16 @@
1
+ // The child that `checkIsolated` (isolate.ts) starts: runs one check with the environment it was given, which holds no
2
+ // credentials, and sends the report back to the parent. It never talks to GitHub.
3
+ import { check } from "./check.js";
4
+ import { configureJobs } from "./pool.js";
5
+ process.once('message', async (request) => {
6
+ let reply;
7
+ try {
8
+ configureJobs({ flag: request.jobs });
9
+ reply = { report: await check(request.options, request.enforceLock) };
10
+ }
11
+ catch (error) {
12
+ reply = { error: error instanceof Error ? error.message : String(error) };
13
+ }
14
+ // Z3's worker threads would keep the process alive, so leave once the reply is on its way.
15
+ process.send(reply, () => process.exit(0));
16
+ });
@@ -0,0 +1,50 @@
1
+ import { type Plan } from './plan.ts';
2
+ import { type ImportMetaEnv } from './runtimeEnv.ts';
3
+ import { type GuardConfig } from './sandboxGuard.ts';
4
+ import type { CheckOptions, ManifestLaw } from './types.ts';
5
+ /** A reviewed file as the parent transformed it, or why it could not. */
6
+ export type Prepared = {
7
+ code: string;
8
+ } | {
9
+ error: string;
10
+ };
11
+ /**
12
+ * What the parent sends. `configure` comes first and once: it fixes the reviewed set and hands over `token`, a secret that
13
+ * every later request must carry. The process takes a request from no one else, so code that runs inside it cannot make one.
14
+ */
15
+ export type HostRequest = {
16
+ type: 'configure';
17
+ token: string;
18
+ guard: GuardConfig;
19
+ transforms: Record<string, Prepared>;
20
+ } | {
21
+ type: 'run';
22
+ token: string;
23
+ id: number;
24
+ outDir: string;
25
+ law: ManifestLaw;
26
+ plans: Plan[];
27
+ options: CheckOptions;
28
+ env: ImportMetaEnv;
29
+ } | {
30
+ type: 'holds';
31
+ token: string;
32
+ id: number;
33
+ outDir: string;
34
+ law: ManifestLaw;
35
+ inputs: unknown[];
36
+ env: ImportMetaEnv;
37
+ };
38
+ /** What it answers: `phase` says whether the law could not be loaded or failed while it ran. */
39
+ export type HostReply = {
40
+ id: number;
41
+ outcome: unknown;
42
+ async: boolean;
43
+ } | {
44
+ id: number;
45
+ holds: boolean;
46
+ } | {
47
+ id: number;
48
+ error: string;
49
+ phase: 'load' | 'run';
50
+ };
@@ -0,0 +1,199 @@
1
+ // The process a sandboxed law runs in (see sandbox.ts, which starts it under Node's permission model). It loads one law
2
+ // at a time, runs its property test or replays one input, and answers over IPC with plain data. It starts no process
3
+ // or thread, writes nothing and loads only what the parent reviewed (sandboxGuard.ts): a file that needs transforming
4
+ // (TypeScript source, a project format) was transformed by the parent and is looked up here.
5
+ import { readFileSync } from 'node:fs';
6
+ import { createRequire } from 'node:module';
7
+ import { join } from 'node:path';
8
+ import { installLawRuntime, loadResolver, runtimeFile, useTransforms } from "./lawRuntime.js";
9
+ import { arbitraryOf } from "./plan.js";
10
+ import { isDiscard, jsPath, runLaw, summarise } from "./propertyRun.js";
11
+ import { installLoaderHooks, setImportMetaEnv } from "./runtimeEnv.js";
12
+ import { Guard, installGuard, normal } from "./sandboxGuard.js";
13
+ // Compiled laws are CommonJS, loaded with `require` so that a recompiled law can be dropped from `require.cache`.
14
+ const require = createRequire(import.meta.url);
15
+ const guard = new Guard();
16
+ let secret;
17
+ const transformed = new Map();
18
+ const loaded = new Map();
19
+ let guarded = false;
20
+ // The channel is the only way out. Keep it, and take it from the code that runs here so it cannot answer for the host.
21
+ // `process.send` calls `this._send`, which lockDown hides, so the inner function is kept as well.
22
+ const sendRaw = process._send.bind(process);
23
+ const send = (message) => sendRaw(message, undefined, {}, undefined);
24
+ const forbidden = (what) => {
25
+ throw Object.assign(new Error(`tslaws sandbox: ${what} is not available to a law`), { code: 'ERR_TSLAWS_SANDBOX' });
26
+ };
27
+ const ErrorClass = Error;
28
+ const captureStackTrace = Error.captureStackTrace.bind(Error);
29
+ /** Whether the code that called the accessor that called this is Node's own (`node:internal/...`), not a file of a law. */
30
+ function askedByNode() {
31
+ const limit = ErrorClass.stackTraceLimit;
32
+ const prepare = ErrorClass.prepareStackTrace;
33
+ ErrorClass.stackTraceLimit = 3;
34
+ ErrorClass.prepareStackTrace = (_error, sites) => sites;
35
+ try {
36
+ const holder = {};
37
+ captureStackTrace(holder, askedByNode);
38
+ const sites = holder.stack ?? [];
39
+ // Frame 0 is the accessor; frame 1 is whoever read or wrote the property.
40
+ const name = sites[1]?.getFileName();
41
+ return typeof name === 'string' && name.startsWith('node:');
42
+ }
43
+ finally {
44
+ ErrorClass.prepareStackTrace = prepare;
45
+ ErrorClass.stackTraceLimit = limit;
46
+ }
47
+ }
48
+ /** Removes the ways around the guard that need no permission: the internals, signals, the channel and the network. */
49
+ function lockDown() {
50
+ const hide = (target, name, value) => {
51
+ Object.defineProperty(target, name, { value, writable: false, configurable: false });
52
+ };
53
+ hide(process, 'binding', () => forbidden('process.binding'));
54
+ hide(process, 'dlopen', () => forbidden('process.dlopen'));
55
+ hide(process, 'kill', () => forbidden('process.kill'));
56
+ // The channel to the parent is this file's alone: nothing here may use it, listen on it or put a message on it.
57
+ // (Accessors that answer nothing and take nothing: Node itself assigns to some of these when the channel closes.)
58
+ // Node's own code still reads and writes them (to close the channel, say), and it is told by the frame that asks: a
59
+ // read from a file of a law is answered with nothing.
60
+ const own = process;
61
+ for (const name of ['send', '_send', 'channel', '_channel']) {
62
+ let value = own[name];
63
+ Object.defineProperty(process, name, {
64
+ get: () => (askedByNode() ? value : undefined),
65
+ set: (next) => {
66
+ if (askedByNode())
67
+ value = next;
68
+ },
69
+ configurable: false,
70
+ });
71
+ }
72
+ // Nor may a listener see the requests (the secret is in them) or be put in place of ours. `emit` stays: Node uses it, and
73
+ // a message made up with it has no secret.
74
+ const messages = new Set(['message', 'internalMessage']);
75
+ const emitter = process;
76
+ for (const name of ['on', 'addListener', 'once', 'prependListener', 'prependOnceListener']) {
77
+ const original = emitter[name].bind(process);
78
+ hide(process, name, (event, ...rest) => messages.has(String(event)) ? process : original(event, ...rest));
79
+ }
80
+ for (const name of ['off', 'removeListener']) {
81
+ const original = emitter[name].bind(process);
82
+ hide(process, name, (event, ...rest) => messages.has(String(event)) ? process : original(event, ...rest));
83
+ }
84
+ const removeAll = emitter.removeAllListeners.bind(process);
85
+ hide(process, 'removeAllListeners', (event) => {
86
+ if (event === undefined) {
87
+ for (const name of process.eventNames())
88
+ if (!messages.has(String(name)))
89
+ removeAll(name);
90
+ }
91
+ else if (!messages.has(String(event)))
92
+ removeAll(event);
93
+ return process;
94
+ });
95
+ for (const name of ['listeners', 'rawListeners']) {
96
+ const original = emitter[name].bind(process);
97
+ hide(process, name, (event) => (messages.has(String(event)) ? [] : original(event)));
98
+ }
99
+ const events = process._events;
100
+ const names = process.eventNames.bind(process);
101
+ hide(process, 'eventNames', () => names().filter((name) => !messages.has(String(name))));
102
+ // Our own listener stays where it is, whatever is done to the table that holds it.
103
+ if (events !== undefined && 'message' in events)
104
+ Object.defineProperty(events, 'message', { value: events.message, writable: false, configurable: false });
105
+ // Nothing may open a socket, and the globals that do are the way past the module list.
106
+ for (const name of ['fetch', 'WebSocket', 'EventSource'])
107
+ hide(globalThis, name, () => forbidden(name));
108
+ }
109
+ function lookup(kind, file) {
110
+ const prepared = transformed.get(`${kind}:${normal(file)}`);
111
+ if (prepared === undefined)
112
+ throw Object.assign(new Error(`tslaws sandbox: ${file} was not prepared before the law started, so it is not in the reviewed set`), { code: 'ERR_TSLAWS_SANDBOX' });
113
+ if ('error' in prepared)
114
+ throw new Error(prepared.error);
115
+ return prepared.code;
116
+ }
117
+ function load(outDir, law, env, fresh) {
118
+ const key = `${outDir}\0${law.file}\0${law.symbol ?? law.name}`;
119
+ const known = loaded.get(key);
120
+ if (!fresh && known !== undefined)
121
+ return known;
122
+ setImportMetaEnv(env);
123
+ installLoaderHooks();
124
+ useTransforms({
125
+ source: (file) => lookup('ts', file),
126
+ plugin: (file, _cwd, _plugins, format) => lookup(format, file),
127
+ });
128
+ installLawRuntime(JSON.parse(readFileSync(join(outDir, runtimeFile), 'utf8')));
129
+ // Before the guard: the resolver loads TypeScript, which needs Node modules that no law may load.
130
+ loadResolver();
131
+ // From here on only reviewed files load. Installed after the runtime's own hooks, so it sees what they resolve.
132
+ if (!guarded) {
133
+ guarded = true;
134
+ installGuard(guard);
135
+ lockDown();
136
+ }
137
+ // The process outlives a check, and the code may have been recompiled since the last one.
138
+ for (const file of Object.keys(require.cache))
139
+ if (file.startsWith(outDir))
140
+ delete require.cache[file];
141
+ const fn = require(jsPath(outDir, law.file))[law.symbol ?? law.name];
142
+ if (typeof fn !== 'function')
143
+ throw new Error('compiled module does not export the law');
144
+ loaded.set(key, fn);
145
+ return fn;
146
+ }
147
+ const message = (error) => (error instanceof Error ? error.message : String(error));
148
+ // The parent is the only reason to run: when its channel closes, so does this process.
149
+ // It ends by draining, not by `process.exit` (which joins V8's background threads and can hang, see #78); a law that keeps
150
+ // the loop busy is cut off after a moment by the kill captured before the laws could take it away.
151
+ const killSelf = process.kill.bind(process);
152
+ process.on('disconnect', () => {
153
+ process.exitCode = 0;
154
+ setTimeout(() => killSelf(process.pid, 'SIGKILL'), 3000).unref();
155
+ });
156
+ process.on('message', async (request) => {
157
+ if (typeof request !== 'object' || request === null)
158
+ return;
159
+ if (request.type === 'configure') {
160
+ // Once, and first: before any law code is loaded. A later one is not the parent's.
161
+ if (secret !== undefined || typeof request.token !== 'string' || request.token.length < 16)
162
+ return;
163
+ secret = request.token;
164
+ guard.configure(request.guard);
165
+ for (const [key, code] of Object.entries(request.transforms))
166
+ transformed.set(key, code);
167
+ return;
168
+ }
169
+ if (secret === undefined || request.token !== secret)
170
+ return;
171
+ const { id } = request;
172
+ let fn;
173
+ try {
174
+ fn = load(request.outDir, request.law, request.env, request.type === 'run');
175
+ }
176
+ catch (error) {
177
+ send({ id, error: message(error), phase: 'load' });
178
+ return;
179
+ }
180
+ try {
181
+ if (request.type === 'holds') {
182
+ let holds;
183
+ try {
184
+ holds = (await fn(...request.inputs)) !== false;
185
+ }
186
+ catch (error) {
187
+ holds = isDiscard(error);
188
+ }
189
+ send({ id, holds });
190
+ return;
191
+ }
192
+ const generators = request.plans.map(arbitraryOf);
193
+ const outcome = summarise(await runLaw(fn, generators, request.options), request.options);
194
+ send({ id, outcome, async: fn.constructor.name === 'AsyncFunction' });
195
+ }
196
+ catch (error) {
197
+ send({ id, error: message(error), phase: 'run' });
198
+ }
199
+ });