tslaws 0.10.0 → 1.1.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 (124) hide show
  1. package/README.md +13 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/badge.d.ts +64 -0
  4. package/dist/badge.js +121 -0
  5. package/dist/browser.d.ts +1 -1
  6. package/dist/browser.js +25 -5
  7. package/dist/bundled.js +2 -2
  8. package/dist/bundlerPlugins.d.ts +2 -0
  9. package/dist/bundlerPlugins.js +7 -0
  10. package/dist/certificates.d.ts +139 -0
  11. package/dist/certificates.js +433 -0
  12. package/dist/chc.d.ts +97 -0
  13. package/dist/chc.js +307 -0
  14. package/dist/check.d.ts +13 -1
  15. package/dist/check.js +218 -31
  16. package/dist/cli.d.ts +18 -0
  17. package/dist/cli.js +242 -34
  18. package/dist/compile.d.ts +15 -5
  19. package/dist/compile.js +203 -70
  20. package/dist/coverage.d.ts +38 -1
  21. package/dist/coverage.js +123 -19
  22. package/dist/e2eApi.js +3 -1
  23. package/dist/generators.js +12 -2
  24. package/dist/github.d.ts +49 -5
  25. package/dist/github.js +107 -24
  26. package/dist/githubCli.d.ts +28 -0
  27. package/dist/githubCli.js +1113 -212
  28. package/dist/hints.js +2 -1
  29. package/dist/init.js +42 -0
  30. package/dist/isolate.d.ts +33 -0
  31. package/dist/isolate.js +262 -0
  32. package/dist/isolatedCheck.d.ts +1 -0
  33. package/dist/isolatedCheck.js +16 -0
  34. package/dist/lawHost.d.ts +50 -0
  35. package/dist/lawHost.js +197 -0
  36. package/dist/lawRuntime.d.ts +45 -0
  37. package/dist/lawRuntime.js +321 -0
  38. package/dist/lock.d.ts +49 -9
  39. package/dist/lock.js +132 -21
  40. package/dist/mcp.js +28 -7
  41. package/dist/mutate.d.ts +4 -0
  42. package/dist/mutate.js +7 -1
  43. package/dist/plan.d.ts +1 -0
  44. package/dist/plan.js +4 -0
  45. package/dist/pluginHooks.d.ts +20 -0
  46. package/dist/pluginHooks.js +57 -0
  47. package/dist/pluginHost.d.ts +5 -0
  48. package/dist/pluginHost.js +43 -0
  49. package/dist/pluginWorker.d.ts +1 -0
  50. package/dist/pluginWorker.js +40 -0
  51. package/dist/plural.d.ts +2 -0
  52. package/dist/plural.js +4 -0
  53. package/dist/pool.d.ts +80 -7
  54. package/dist/pool.js +222 -11
  55. package/dist/projects.d.ts +43 -1
  56. package/dist/projects.js +283 -11
  57. package/dist/promote.d.ts +56 -2
  58. package/dist/promote.js +429 -13
  59. package/dist/property.js +5 -1
  60. package/dist/propertyWorker.js +9 -4
  61. package/dist/proposals.d.ts +52 -4
  62. package/dist/proposals.js +484 -21
  63. package/dist/reporters.js +5 -1
  64. package/dist/runtimeEnv.d.ts +13 -5
  65. package/dist/runtimeEnv.js +48 -10
  66. package/dist/sandbox.d.ts +98 -0
  67. package/dist/sandbox.js +673 -0
  68. package/dist/sandboxGuard.d.ts +56 -0
  69. package/dist/sandboxGuard.js +249 -0
  70. package/dist/seal.d.ts +9 -0
  71. package/dist/seal.js +426 -0
  72. package/dist/security/cli.d.ts +6 -0
  73. package/dist/security/cli.js +39 -0
  74. package/dist/security/cwe.d.ts +14 -0
  75. package/dist/security/cwe.js +40 -0
  76. package/dist/security/deps/cache.d.ts +28 -0
  77. package/dist/security/deps/cache.js +107 -0
  78. package/dist/security/deps/config.d.ts +16 -0
  79. package/dist/security/deps/config.js +43 -0
  80. package/dist/security/deps/imports.d.ts +4 -0
  81. package/dist/security/deps/imports.js +33 -0
  82. package/dist/security/deps/lockfiles.d.ts +23 -0
  83. package/dist/security/deps/lockfiles.js +153 -0
  84. package/dist/security/deps/osv.d.ts +66 -0
  85. package/dist/security/deps/osv.js +137 -0
  86. package/dist/security/deps/run.d.ts +54 -0
  87. package/dist/security/deps/run.js +135 -0
  88. package/dist/security/deps/severity.d.ts +26 -0
  89. package/dist/security/deps/severity.js +78 -0
  90. package/dist/security/generators.d.ts +9 -0
  91. package/dist/security/generators.js +36 -0
  92. package/dist/security/index.d.ts +27 -0
  93. package/dist/security/index.js +18 -0
  94. package/dist/security/integers.d.ts +31 -0
  95. package/dist/security/integers.js +105 -0
  96. package/dist/security/law.d.ts +54 -0
  97. package/dist/security/law.js +54 -0
  98. package/dist/security/pathTraversal.d.ts +29 -0
  99. package/dist/security/pathTraversal.js +146 -0
  100. package/dist/security/prototypePollution.d.ts +30 -0
  101. package/dist/security/prototypePollution.js +142 -0
  102. package/dist/security/redirect.d.ts +21 -0
  103. package/dist/security/redirect.js +154 -0
  104. package/dist/security/redos.d.ts +21 -0
  105. package/dist/security/redos.js +93 -0
  106. package/dist/security/validation.d.ts +25 -0
  107. package/dist/security/validation.js +89 -0
  108. package/dist/security/xss.d.ts +21 -0
  109. package/dist/security/xss.js +90 -0
  110. package/dist/settings.d.ts +20 -0
  111. package/dist/settings.js +32 -0
  112. package/dist/smt.d.ts +37 -1
  113. package/dist/smt.js +277 -111
  114. package/dist/smtWorker.d.ts +1 -0
  115. package/dist/smtWorker.js +26 -0
  116. package/dist/solvers.d.ts +9 -0
  117. package/dist/solvers.js +11 -5
  118. package/dist/symbolic.d.ts +54 -1
  119. package/dist/symbolic.js +239 -13
  120. package/dist/tsconfigResolve.d.ts +28 -0
  121. package/dist/tsconfigResolve.js +141 -0
  122. package/dist/types.d.ts +33 -0
  123. package/hooks/claude-hook.mjs +2 -0
  124. package/package.json +19 -7
package/dist/chc.js ADDED
@@ -0,0 +1,307 @@
1
+ // Loop invariants by constrained Horn clauses (CHC). The symbolic executor (symbolic.ts) turns each loop into an
2
+ // unknown predicate over the loop variables and three kinds of clause:
3
+ //
4
+ // entry the state on entering the loop satisfies Inv
5
+ // step Inv, the loop condition and one pass of the body give Inv on the next state
6
+ // query Inv with the condition false, and every other fact, make the law and its obligations hold
7
+ //
8
+ // Z3's Spacer engine looks for an Inv that satisfies all of them. A solution is not trusted on Spacer's word: the
9
+ // invariants it printed are put back into the clauses and plain Z3 must show each implication valid. When Eldarica
10
+ // (`eld`) or Golem is installed it solves the same system too; a solver that says there is no solution where Spacer
11
+ // found one is a disagreement, and the law is then reported as unknown rather than proved.
12
+ import { spawn } from 'node:child_process';
13
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { extname, join } from 'node:path';
16
+ import { budget, lowerPriority } from "./pool.js";
17
+ /**
18
+ * The Z3 worker fell over: it threw, ran out of memory or exited, as opposed to answering `unknown` or running out of
19
+ * time. A proof must not read it as "no verdict", because that would quietly fall back to the bounded proof.
20
+ */
21
+ export class SolverCrash extends Error {
22
+ }
23
+ const unknown = (reason) => ({ kind: 'unknown', reason });
24
+ /** Floating point and strings are outside what the CHC engines decide: the unrolled proof handles those. */
25
+ const unmodelled = /FloatingPoint|\bfp\.|to_fp|\bstr\.|\bString\b|\bre\./;
26
+ function expand(text, shared) {
27
+ let out = text;
28
+ // A shared term may name an earlier one, so expand until nothing is left.
29
+ for (let round = 0; round <= shared.size && /\b_s\d+\b/.test(out); round += 1)
30
+ out = out.replace(/\b_s\d+\b/g, (name) => shared.get(name) ?? name);
31
+ return out;
32
+ }
33
+ const closed = (system, text) => {
34
+ const body = expand(text, system.shared);
35
+ if (system.constants.length === 0)
36
+ return body;
37
+ return `(forall (${system.constants.map((c) => `(${c.name} ${c.sort})`).join(' ')}) ${body})`;
38
+ };
39
+ /** The SMT-LIB script Spacer (and any other CHC solver) reads. */
40
+ export function hornText(system, timeoutMs) {
41
+ return [
42
+ ...(timeoutMs === undefined ? [] : [`(set-option :timeout ${timeoutMs})`]),
43
+ '(set-logic HORN)',
44
+ ...system.predicates.map((p) => `(declare-fun ${p.name} (${p.sorts.join(' ')}) Bool)`),
45
+ ...system.clauses.map((clause) => `(assert ${closed(system, clause)})`),
46
+ '(check-sat)',
47
+ ].join('\n');
48
+ }
49
+ // ---- reading Z3's model --------------------------------------------------------------------------------------
50
+ /** The top-level s-expressions of `text`, each as text. */
51
+ function topLevel(text) {
52
+ const out = [];
53
+ let depth = 0;
54
+ let start = -1;
55
+ let quoted = false;
56
+ for (let i = 0; i < text.length; i += 1) {
57
+ const ch = text[i];
58
+ if (ch === '"')
59
+ quoted = !quoted;
60
+ if (quoted)
61
+ continue;
62
+ if (ch === '(') {
63
+ if (depth === 0)
64
+ start = i;
65
+ depth += 1;
66
+ }
67
+ else if (ch === ')') {
68
+ depth -= 1;
69
+ if (depth === 0 && start >= 0)
70
+ out.push(text.slice(start, i + 1));
71
+ }
72
+ else if (depth === 0 && !/\s/.test(ch)) {
73
+ const end = text.slice(i).search(/[\s()]/);
74
+ out.push(text.slice(i, end < 0 ? text.length : i + end));
75
+ i += (end < 0 ? text.length - i : end) - 1;
76
+ }
77
+ }
78
+ return out;
79
+ }
80
+ /** The elements of one list `( a b (c d) )`. */
81
+ function children(list) {
82
+ return topLevel(list.trim().slice(1, -1));
83
+ }
84
+ /** The `define-fun` of each predicate in a model, by name. */
85
+ function modelDefinitions(model) {
86
+ let items = topLevel(model);
87
+ // Z3 wraps the definitions in one list.
88
+ if (items.length === 1 && items[0].startsWith('(') && !items[0].startsWith('(define-fun'))
89
+ items = children(items[0]);
90
+ const out = new Map();
91
+ for (const item of items) {
92
+ const parts = item.startsWith('(define-fun') ? children(item) : [];
93
+ if (parts.length >= 5)
94
+ out.set(parts[1], item);
95
+ }
96
+ return out;
97
+ }
98
+ /** The invariant as text over the source names: `Inv(s, i, n) := (and ...)`. */
99
+ function describe(predicate, definition, index) {
100
+ const parts = children(definition);
101
+ const body = parts[parts.length - 1].replace(/\s+/g, ' ');
102
+ const named = body.replace(/\bx!(\d+)/g, (_, k) => predicate.names[Number(k)] ?? `x!${k}`);
103
+ return `loop ${index + 1} invariant over (${predicate.names.join(', ')}): ${named}`;
104
+ }
105
+ /** `term` with every application of a defined predicate replaced by its body, the arguments put in for the parameters. */
106
+ function inlineApplications(term, definitions) {
107
+ if (!term.startsWith('('))
108
+ return term;
109
+ const parts = children(term);
110
+ const head = parts[0];
111
+ const definition = head === undefined ? undefined : definitions.get(head);
112
+ const rest = parts.map((part) => inlineApplications(part, definitions));
113
+ if (definition === undefined)
114
+ return `(${rest.join(' ')})`;
115
+ const args = rest.slice(1);
116
+ if (args.length !== definition.params.length)
117
+ throw new Error(`${head} is applied to the wrong number of arguments`);
118
+ const bound = new Map(definition.params.map((param, i) => [param, args[i]]));
119
+ const put = (text) => {
120
+ if (!text.startsWith('('))
121
+ return bound.get(text) ?? text;
122
+ return `(${children(text).map(put).join(' ')})`;
123
+ };
124
+ return put(definition.body);
125
+ }
126
+ /**
127
+ * The SMT-LIB problem that proves a loop proof, from the Horn text and the invariants of a `HornCertification`: every
128
+ * constant of the clauses declared, each invariant put in place of its predicate, and one assertion that some clause
129
+ * fails. It has no quantifiers and no unknown predicate, so cvc5 can refute it with an Alethe proof and Carcara can check
130
+ * that proof. Because some constant can break one clause exactly when some constant breaks a clause, the problem is
131
+ * unsatisfiable exactly when every clause holds for every value, that is, when the invariants are inductive and make the
132
+ * law hold. Undefined when the invariants do not match the predicates the text declares.
133
+ */
134
+ export function certificationProblem(horn, invariants) {
135
+ try {
136
+ const definitions = new Map();
137
+ for (const item of topLevel(invariants)) {
138
+ const parts = children(item);
139
+ if (parts[0] !== 'define-fun' || parts.length !== 5 || !parts[2].startsWith('('))
140
+ return undefined;
141
+ definitions.set(parts[1], { params: children(parts[2]).map((param) => children(param)[0]), body: parts[4] });
142
+ }
143
+ const predicates = new Set();
144
+ const constants = new Map();
145
+ const clauses = [];
146
+ for (const item of topLevel(horn)) {
147
+ const parts = children(item);
148
+ if (parts[0] === 'declare-fun')
149
+ predicates.add(parts[1]);
150
+ if (parts[0] !== 'assert')
151
+ continue;
152
+ let body = parts[1];
153
+ if (body.startsWith('(forall')) {
154
+ const quantified = children(body);
155
+ for (const binder of children(quantified[1])) {
156
+ const [name, sort] = children(binder);
157
+ constants.set(name, sort);
158
+ }
159
+ body = quantified[2];
160
+ }
161
+ clauses.push(body);
162
+ }
163
+ if (predicates.size !== definitions.size || [...predicates].some((name) => !definitions.has(name)))
164
+ return undefined;
165
+ if (clauses.length === 0)
166
+ return undefined;
167
+ return [
168
+ ...[...constants].map(([name, sort]) => `(declare-const ${name} ${sort})`),
169
+ `(assert (or ${clauses.map((clause) => `(not ${inlineApplications(clause, definitions)})`).join(' ')}))`,
170
+ '(check-sat)',
171
+ ].join('\n');
172
+ }
173
+ catch {
174
+ return undefined;
175
+ }
176
+ }
177
+ /** Plain Z3 checks each clause with the printed invariants in place of the unknowns; true when every one is valid. */
178
+ async function verified(system, definitions, engine, timeoutMs) {
179
+ const query = [
180
+ `(set-option :timeout ${timeoutMs})`,
181
+ ...system.predicates.map((p) => definitions.get(p.name)),
182
+ ...system.clauses.flatMap((clause) => [
183
+ '(push 1)',
184
+ `(assert (not ${closed(system, clause)}))`,
185
+ '(check-sat)',
186
+ '(pop 1)',
187
+ ]),
188
+ ].join('\n');
189
+ const { out } = await engine.z3(query, '', timeoutMs);
190
+ const answers = out
191
+ .split('\n')
192
+ .map((line) => line.trim())
193
+ .filter((line) => line !== '');
194
+ if (answers.length === system.clauses.length && answers.every((line) => line === 'unsat'))
195
+ return undefined;
196
+ return `plain Z3 could not check the invariants Spacer found (${answers.join(', ') || 'no answer'})`;
197
+ }
198
+ /**
199
+ * Looks for an invariant for every loop in `system`, verifies it, and has the installed CHC solvers confirm it.
200
+ * Never throws: anything that goes wrong is an `unknown` verdict, and the caller falls back to unrolling. A crash of the
201
+ * Z3 worker is the exception to that fallback: it is a `crash` verdict, which the caller reports instead.
202
+ */
203
+ export async function solveHorn(system, engine, timeoutMs) {
204
+ const query = hornText(system, timeoutMs);
205
+ if (unmodelled.test(query))
206
+ return unknown('a loop uses floating-point numbers or strings, which CHC solving does not model');
207
+ try {
208
+ const { out, vals } = await engine.z3(query, '(get-model)', timeoutMs);
209
+ const first = out.split('\n')[0]?.trim() ?? '';
210
+ if (first === 'unsat')
211
+ return { kind: 'unsafe' };
212
+ if (first !== 'sat')
213
+ return unknown(`Spacer gave up (${first === '' ? 'no answer' : first.slice(0, 80)})`);
214
+ const definitions = modelDefinitions(vals);
215
+ const missing = system.predicates.find((p) => !definitions.has(p.name));
216
+ if (missing !== undefined)
217
+ return unknown(`Spacer printed no invariant for ${missing.name}`);
218
+ const problem = await verified(system, definitions, engine, timeoutMs);
219
+ if (problem !== undefined)
220
+ return unknown(problem);
221
+ const notes = [];
222
+ for (const other of await engine.external(hornText(system), timeoutMs)) {
223
+ if (other.answer === 'sat')
224
+ notes.push(`${other.solver} agrees`);
225
+ else if (other.answer === 'unsat')
226
+ return {
227
+ kind: 'disagree',
228
+ reason: `Spacer found invariants but ${other.solver} says the loops can break the law: the solvers disagree`,
229
+ };
230
+ else
231
+ notes.push(`${other.solver} did not confirm (${other.detail ?? other.answer})`);
232
+ }
233
+ const invariants = system.predicates.map((p, i) => describe(p, definitions.get(p.name), i));
234
+ const certification = {
235
+ horn: hornText(system),
236
+ invariants: system.predicates.map((p) => definitions.get(p.name)).join('\n'),
237
+ };
238
+ return { kind: 'safe', invariants, notes, certification };
239
+ }
240
+ catch (error) {
241
+ if (error instanceof SolverCrash)
242
+ return { kind: 'crash', reason: error.message };
243
+ return unknown(error.message);
244
+ }
245
+ }
246
+ const externals = [
247
+ { name: 'Eldarica', env: 'TSLAWS_ELDARICA', command: 'eld', args: (ms) => [`-t:${Math.ceil(ms / 1000)}`] },
248
+ { name: 'Golem', env: 'TSLAWS_GOLEM', command: 'golem', args: () => [] },
249
+ ];
250
+ /** Binaries that could not be started, so a missing solver costs one failed start per run, not one per law. */
251
+ const missing = new Set();
252
+ /** A path ending in .js, .mjs or .cjs is a Node script and runs under the current Node (the tests use one as a mock). */
253
+ function start(path, args) {
254
+ return ['.js', '.mjs', '.cjs'].includes(extname(path))
255
+ ? { file: process.execPath, args: [path, ...args] }
256
+ : { file: path, args };
257
+ }
258
+ function runExternal(solver, path, query, timeoutMs) {
259
+ const dir = mkdtempSync(join(tmpdir(), 'tslaws-chc-'));
260
+ const file = join(dir, 'system.smt2');
261
+ writeFileSync(file, `${query}\n`);
262
+ const { file: bin, args } = start(path, [...solver.args(timeoutMs), file]);
263
+ return new Promise((resolve) => {
264
+ let stdout = '';
265
+ let finished = false;
266
+ const done = (answer) => {
267
+ if (finished)
268
+ return;
269
+ finished = true;
270
+ clearTimeout(timer);
271
+ rmSync(dir, { recursive: true, force: true });
272
+ resolve(answer);
273
+ };
274
+ const child = spawn(bin, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
275
+ lowerPriority(child.pid);
276
+ const timer = setTimeout(() => {
277
+ child.kill();
278
+ done({ solver: solver.name, answer: 'timeout', detail: `no answer within ${timeoutMs} ms` });
279
+ }, timeoutMs + 3000);
280
+ child.stdout.setEncoding('utf8').on('data', (chunk) => (stdout += chunk));
281
+ child.stderr.resume();
282
+ child.on('error', (error) => {
283
+ if (error.code === 'ENOENT' || error.code === 'EACCES') {
284
+ missing.add(path);
285
+ done(undefined);
286
+ }
287
+ else
288
+ done({ solver: solver.name, answer: 'error', detail: error.message });
289
+ });
290
+ child.on('close', () => {
291
+ const first = stdout.trim().split('\n')[0]?.trim() ?? '';
292
+ if (first === 'sat' || first === 'unsat' || first === 'unknown')
293
+ done({ solver: solver.name, answer: first });
294
+ else
295
+ done({ solver: solver.name, answer: 'error', detail: first === '' ? 'no answer' : first.slice(0, 80) });
296
+ });
297
+ });
298
+ }
299
+ /** Runs each installed solver (`TSLAWS_ELDARICA` and `TSLAWS_GOLEM`, else `eld` and `golem` on the PATH) on the system. */
300
+ export async function runExternalSolvers(query, timeoutMs) {
301
+ // One extra slot for each solver past the first; with none free they run one after another.
302
+ const answers = await budget.portfolio(externals.map((solver) => async () => {
303
+ const path = process.env[solver.env] ?? solver.command;
304
+ return missing.has(path) ? undefined : runExternal(solver, path, query, timeoutMs);
305
+ }));
306
+ return answers.filter((answer) => answer !== undefined);
307
+ }
package/dist/check.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { CheckOptions, LawResult } from './types.ts';
1
+ import { type CertificateRecord } from './certificates.ts';
2
+ import type { CheckOptions, LawResult, ManifestLaw } from './types.ts';
2
3
  export interface CheckReport {
3
4
  results: LawResult[];
4
5
  compileDiagnostics: string;
@@ -11,4 +12,15 @@ export interface CheckReport {
11
12
  }
12
13
  /** The `@tslaws-exempt` functions of the project, for `tslaws accept` to record. */
13
14
  export declare function exemptionsOf(options: CheckOptions): string[];
15
+ /**
16
+ * The hash of each SMT-LIB problem the prover would send for each law now, rebuilt from the compiled code without
17
+ * running a solver. A certificate is for a law only while its problem hash is one of these.
18
+ */
19
+ export declare function problemHashesOf(options: CheckOptions, laws: ManifestLaw[]): Map<string, Set<string>>;
20
+ /**
21
+ * The certificates `tslaws accept` writes into the lock. The ones in the old lock stay only while their law and their
22
+ * problem are unchanged. The ones `tslaws check --certify` left in the sidecar file enter only after `verifyRecord`
23
+ * passes: the file is not trusted. Every record turned away is reported through `say`.
24
+ */
25
+ export declare function certificatesToAccept(options: CheckOptions, laws: ManifestLaw[], held: Record<string, CertificateRecord> | undefined, say: (text: string) => void): Promise<Record<string, CertificateRecord>>;
14
26
  export declare function check(options: CheckOptions, enforceLock: boolean): Promise<CheckReport>;