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,142 @@
1
+ // CWE-1321: merge, set and parse functions never change Object.prototype (or Array.prototype, Function.prototype).
2
+ import * as fc from 'fast-check';
3
+ import { show } from "./cwe.js";
4
+ import { securityLaw } from "./law.js";
5
+ /** The property every payload tries to plant. */
6
+ export const marker = 'tslawsPolluted';
7
+ const dangerous = ['__proto__', 'constructor', 'prototype'];
8
+ // Key chains that reach a shared prototype from a plain object, from an array and from a function.
9
+ const chains = [
10
+ ['__proto__'],
11
+ ['constructor', 'prototype'],
12
+ ['__proto__', '__proto__'],
13
+ ['a', '__proto__'],
14
+ ['a', 'constructor', 'prototype'],
15
+ ['a', 'b', '__proto__'],
16
+ ['constructor', 'prototype', 'constructor', 'prototype'],
17
+ ];
18
+ function nest(keys, leaf) {
19
+ return JSON.stringify(keys.reduceRight((inner, key) => ({ [key]: inner }), leaf));
20
+ }
21
+ /** JSON objects whose keys walk to a shared prototype and plant `tslawsPolluted`; `JSON.parse` makes `__proto__` an own key. */
22
+ export function pollutionPayloads() {
23
+ const chain = fc
24
+ .tuple(fc.array(fc.constantFrom('a', 'b', ...dangerous), { maxLength: 2 }), fc.constantFrom(...chains))
25
+ .map(([lead, tail]) => [...lead, ...tail]);
26
+ return fc
27
+ .oneof({ weight: 5, arbitrary: chain.map((keys) => nest(keys, { [marker]: 'yes' })) }, { weight: 2, arbitrary: chain.map((keys) => nest(keys, [{ [marker]: 'yes' }])) }, { weight: 2, arbitrary: chain.map((keys) => `{"keep":1,"list":[${nest(keys, { [marker]: 'yes' })}]}`) })
28
+ .map((text) => text);
29
+ }
30
+ /** Dotted paths that walk through a prototype key to `tslawsPolluted`. */
31
+ export function pollutionPaths() {
32
+ return fc
33
+ .tuple(fc.array(fc.constantFrom('a', 'b'), { maxLength: 2 }), fc.constantFrom(...chains))
34
+ .map(([lead, tail]) => [...lead, ...tail, marker].join('.'));
35
+ }
36
+ /** The fixed JSON attacks `merge` and `parse` laws check on every call. */
37
+ export const pollutionCorpus = [
38
+ `{"__proto__":{"${marker}":"yes"}}`,
39
+ `{"constructor":{"prototype":{"${marker}":"yes"}}}`,
40
+ `{"a":{"__proto__":{"${marker}":"yes"}}}`,
41
+ `{"a":{"constructor":{"prototype":{"${marker}":"yes"}}}}`,
42
+ `{"list":[{"__proto__":{"${marker}":"yes"}}]}`,
43
+ `{"__proto__":{"__proto__":{"${marker}":"yes"}}}`,
44
+ ].map((text) => text);
45
+ /** The fixed paths `set` laws check on every call. */
46
+ export const pollutionPathCorpus = [
47
+ `__proto__.${marker}`,
48
+ `constructor.prototype.${marker}`,
49
+ `a.__proto__.${marker}`,
50
+ `a.constructor.prototype.${marker}`,
51
+ `__proto__.__proto__.${marker}`,
52
+ ].map((text) => text);
53
+ const shared = [
54
+ ['Object.prototype', Object.prototype],
55
+ ['Array.prototype', Array.prototype],
56
+ ['Function.prototype', Function.prototype],
57
+ ];
58
+ function save() {
59
+ return shared.map(([name, target]) => {
60
+ const props = new Map();
61
+ for (const key of Reflect.ownKeys(target))
62
+ props.set(key, Object.getOwnPropertyDescriptor(target, key));
63
+ return [name, target, props];
64
+ });
65
+ }
66
+ function same(a, b) {
67
+ return (Object.is(a.value, b.value) &&
68
+ a.get === b.get &&
69
+ a.set === b.set &&
70
+ a.writable === b.writable &&
71
+ a.enumerable === b.enumerable);
72
+ }
73
+ /** What changed on the shared prototypes since `save`; puts them back so one failure does not poison the process. */
74
+ function restore(saved) {
75
+ let found;
76
+ for (const [name, target, props] of saved) {
77
+ for (const key of Reflect.ownKeys(target)) {
78
+ const now = Object.getOwnPropertyDescriptor(target, key);
79
+ const before = props.get(key);
80
+ if (before !== undefined && same(before, now))
81
+ continue;
82
+ found ??= `${name}.${String(key)} was ${before === undefined ? 'added' : 'changed'}`;
83
+ try {
84
+ if (before === undefined)
85
+ delete target[key];
86
+ else
87
+ Object.defineProperty(target, key, before);
88
+ }
89
+ catch {
90
+ // A frozen prototype cannot be written, so nothing changed.
91
+ }
92
+ }
93
+ }
94
+ return found;
95
+ }
96
+ function guarded(input, call, act) {
97
+ const saved = save();
98
+ try {
99
+ act();
100
+ }
101
+ catch {
102
+ // A function that refuses the input is safe; only a change to a prototype counts.
103
+ }
104
+ const changed = restore(saved);
105
+ if (changed !== undefined)
106
+ return { detail: `${call}(${show(input)}) polluted: ${changed}` };
107
+ return undefined;
108
+ }
109
+ /** CWE-1321 for `merge(target, source)`: merging parsed hostile JSON into an object must leave the shared prototypes alone. */
110
+ export function prototypeSafeMerge(merge) {
111
+ return securityLaw({
112
+ id: 'prototype-safe-merge',
113
+ cwe: ['CWE-1321'],
114
+ title: 'a merge never changes Object.prototype on __proto__ or constructor.prototype keys',
115
+ input: pollutionPayloads(),
116
+ corpus: pollutionCorpus,
117
+ verdict: (input) => guarded(input, 'merge', () => void merge({}, JSON.parse(input))),
118
+ });
119
+ }
120
+ /** CWE-1321 for `set(target, path, value)`: a path through `__proto__` or `constructor.prototype` must not reach a shared prototype. */
121
+ export function prototypeSafeSet(set, options = {}) {
122
+ const asArray = options.pathFormat === 'array';
123
+ return securityLaw({
124
+ id: 'prototype-safe-set',
125
+ cwe: ['CWE-1321'],
126
+ title: 'a path setter never changes Object.prototype on __proto__ or constructor.prototype paths',
127
+ input: pollutionPaths(),
128
+ corpus: pollutionPathCorpus,
129
+ verdict: (input) => guarded(input, 'set', () => void set({}, asArray ? input.split('.') : input, 'yes')),
130
+ });
131
+ }
132
+ /** CWE-1321 for `parse(text)`: parsing hostile JSON (a parser that merges, revives or assigns by key) must leave the shared prototypes alone. */
133
+ export function prototypeSafeParse(parse) {
134
+ return securityLaw({
135
+ id: 'prototype-safe-parse',
136
+ cwe: ['CWE-1321'],
137
+ title: 'a parser never changes Object.prototype on __proto__ or constructor.prototype keys',
138
+ input: pollutionPayloads(),
139
+ corpus: pollutionCorpus,
140
+ verdict: (input) => guarded(input, 'parse', () => void parse(input)),
141
+ });
142
+ }
@@ -0,0 +1,21 @@
1
+ import * as fc from 'fast-check';
2
+ import type { SecurityLaw } from './law.ts';
3
+ /** A hostile redirect target for a law parameter: `law safe(u: RedirectTarget) => redirects.holds(u)`. */
4
+ export type RedirectTarget = string & {
5
+ readonly __tslawsRedirect: true;
6
+ };
7
+ /** The fixed attacks `holds` checks on every call, for the trusted host name. */
8
+ export declare function redirectCorpus(trusted: string, allow?: readonly string[]): string[];
9
+ export declare function redirectTargets(trusted?: string, allow?: readonly string[]): fc.Arbitrary<RedirectTarget>;
10
+ export interface OpenRedirectOptions {
11
+ /** The origin of the app, as in `https://app.example`. Relative targets resolve against it. */
12
+ origin: string;
13
+ /** Other places a redirect may go: host names (`accounts.example`, `*.example.org`) or origins (`https://pay.example`). */
14
+ allow?: readonly string[];
15
+ }
16
+ /**
17
+ * CWE-601. `redirect(target)` returns the URL to redirect to. Read the way a browser reads a `Location` header (the
18
+ * WHATWG URL rules: backslashes, tabs, `//host` and the like), it must be on `origin` or on the allowlist, or the
19
+ * function must refuse by throwing or returning nothing.
20
+ */
21
+ export declare function openRedirect(redirect: (target: string) => unknown, options: OpenRedirectOptions): SecurityLaw<RedirectTarget>;
@@ -0,0 +1,154 @@
1
+ // CWE-601: a redirect target is on the same origin or on an allowlist.
2
+ import * as fc from 'fast-check';
3
+ import { show } from "./cwe.js";
4
+ import { securityLaw } from "./law.js";
5
+ const schemes = [
6
+ '',
7
+ '/',
8
+ '//',
9
+ '///',
10
+ '////',
11
+ '\\\\',
12
+ '/\\',
13
+ '\\/',
14
+ 'http:',
15
+ 'https:',
16
+ 'http://',
17
+ 'https://',
18
+ 'https:/',
19
+ 'http:\\\\',
20
+ '//\t',
21
+ '/\t/',
22
+ ' //',
23
+ '\t//',
24
+ '\n//',
25
+ '%2f%2f',
26
+ '/%2f',
27
+ '/%5c',
28
+ '/./',
29
+ '//.',
30
+ 'javascript:',
31
+ 'data:text/html,',
32
+ 'vbscript:',
33
+ ];
34
+ const paths = ['', '/', '/home', '/login?next=/', '?x=1', '#frag', '/%2e%2e/x', '//x'];
35
+ /** Host names of the allowlist entries (a wildcard becomes a sample host) and lookalikes of them. */
36
+ function allowedHosts(allow) {
37
+ return allow.flatMap((entry) => {
38
+ const host = entry.includes('://') ? new URL(entry).hostname : entry.replace(/^\*\./, 'sub.');
39
+ return [host, `${host}.evil.example`, `evil${host}`, host.replace(/^sub\./, '')];
40
+ });
41
+ }
42
+ /** Hosts that look like `trusted` or hide an attacker's, for the trusted host name `trusted`. */
43
+ function hosts(trusted, allow = []) {
44
+ return [
45
+ ...allowedHosts(allow),
46
+ 'evil.example',
47
+ 'evil.example@',
48
+ '@evil.example',
49
+ `${trusted}@evil.example`,
50
+ `${trusted}.evil.example`,
51
+ `evil.example/.${trusted}`,
52
+ `evil.example#.${trusted}`,
53
+ `evil.example?.${trusted}`,
54
+ `evil.example\\.${trusted}`,
55
+ `evil.example%2f.${trusted}`,
56
+ `evil.example:80@${trusted}`,
57
+ `evil。example`,
58
+ `${trusted}。evil.example`,
59
+ '127.0.0.1',
60
+ '[::1]',
61
+ '0x7f.1',
62
+ trusted,
63
+ `evil${trusted}`,
64
+ `${trusted}evil.example`,
65
+ ];
66
+ }
67
+ /** The fixed attacks `holds` checks on every call, for the trusted host name. */
68
+ export function redirectCorpus(trusted, allow = []) {
69
+ return [
70
+ ...allowedHosts(allow).flatMap((host) => [`http://${host}`, `https://${host}`, `//${host}`]),
71
+ '//evil.example',
72
+ '///evil.example',
73
+ '////evil.example',
74
+ 'https://evil.example',
75
+ 'https:evil.example',
76
+ 'https:/evil.example',
77
+ '/\\evil.example',
78
+ '\\\\evil.example',
79
+ 'http:\\\\evil.example',
80
+ '/%09/evil.example',
81
+ '\t//evil.example',
82
+ ' //evil.example',
83
+ `//evil.example@${trusted}`,
84
+ `https://${trusted}@evil.example`,
85
+ `https://${trusted}.evil.example`,
86
+ `https://evil.example#@${trusted}`,
87
+ `https://evil.example\\@${trusted}`,
88
+ 'javascript:alert(1)',
89
+ 'data:text/html,<script>alert(1)</script>',
90
+ ];
91
+ }
92
+ export function redirectTargets(trusted = 'app.example', allow = []) {
93
+ return fc
94
+ .oneof({
95
+ weight: 8,
96
+ arbitrary: fc
97
+ .tuple(fc.constantFrom(...schemes), fc.constantFrom(...hosts(trusted, allow)), fc.constantFrom(...paths))
98
+ .map(([scheme, host, path]) => scheme + host + path),
99
+ }, { weight: 1, arbitrary: fc.string() })
100
+ .map((u) => u);
101
+ }
102
+ function allowed(url, origin, allow) {
103
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
104
+ return false;
105
+ if (url.origin === origin.origin)
106
+ return true;
107
+ return allow.some((entry) => {
108
+ if (entry.includes('://'))
109
+ return url.origin === new URL(entry).origin;
110
+ if (entry.startsWith('*.'))
111
+ return url.hostname.endsWith(entry.slice(1)) && url.hostname.length > entry.length - 1;
112
+ return url.hostname === entry.toLowerCase();
113
+ });
114
+ }
115
+ /**
116
+ * CWE-601. `redirect(target)` returns the URL to redirect to. Read the way a browser reads a `Location` header (the
117
+ * WHATWG URL rules: backslashes, tabs, `//host` and the like), it must be on `origin` or on the allowlist, or the
118
+ * function must refuse by throwing or returning nothing.
119
+ */
120
+ export function openRedirect(redirect, options) {
121
+ const origin = new URL(options.origin);
122
+ const allow = options.allow ?? [];
123
+ return securityLaw({
124
+ id: 'open-redirect',
125
+ cwe: ['CWE-601'],
126
+ title: 'a redirect target is same-origin or on the allowlist',
127
+ input: redirectTargets(origin.hostname, allow),
128
+ corpus: redirectCorpus(origin.hostname, allow),
129
+ verdict: (input) => {
130
+ let result;
131
+ try {
132
+ result = redirect(input);
133
+ }
134
+ catch {
135
+ return undefined;
136
+ }
137
+ if (result === undefined || result === null || result === false)
138
+ return undefined;
139
+ const text = String(result);
140
+ let url;
141
+ try {
142
+ url = new URL(text, origin);
143
+ }
144
+ catch {
145
+ return undefined;
146
+ }
147
+ return allowed(url, origin, allow)
148
+ ? undefined
149
+ : {
150
+ detail: `redirect(${show(input)}) returned ${show(text)}, which goes to ${url.origin} (allowed: ${[origin.origin, ...allow].join(', ')})`,
151
+ };
152
+ },
153
+ });
154
+ }
@@ -0,0 +1,21 @@
1
+ import * as fc from 'fast-check';
2
+ import type { SecurityLaw } from './law.ts';
3
+ /** An attack: `pump` repeated to a length, then `suffix`. For a law parameter: `law fast(a: RedosAttack) => redos.holds(a)`. */
4
+ export interface RedosAttack {
5
+ pump: string;
6
+ suffix: string;
7
+ }
8
+ export declare function redosAttacks(): fc.Arbitrary<RedosAttack>;
9
+ export interface RedosOptions {
10
+ /** The most one call may take, in milliseconds. Default 100. */
11
+ budgetMs?: number;
12
+ /** The longest input to try, in characters. Default 20000. */
13
+ maxLength?: number;
14
+ }
15
+ /**
16
+ * CWE-400 and CWE-1333. `fn(text)` must return within `budgetMs` for every attack at every length up to `maxLength`.
17
+ * The attack grows in steps and stops at the first one over budget, so a pattern that backtracks exponentially is
18
+ * caught at a length of a few dozen characters. The function must be synchronous: the check times it, and cannot
19
+ * interrupt a call that never returns. An exception does not fail the law.
20
+ */
21
+ export declare function redos(fn: (text: string) => unknown, options?: RedosOptions): SecurityLaw<RedosAttack>;
@@ -0,0 +1,93 @@
1
+ // CWE-400 / CWE-1333: a function finishes under a time budget on adversarial long inputs.
2
+ import * as fc from 'fast-check';
3
+ import { performance } from 'node:perf_hooks';
4
+ import { show } from "./cwe.js";
5
+ import { securityLaw } from "./law.js";
6
+ const pumps = [
7
+ 'a',
8
+ 'aa',
9
+ 'ab',
10
+ 'a ',
11
+ ' ',
12
+ '0',
13
+ '1',
14
+ '-',
15
+ '.',
16
+ 'a.',
17
+ 'a@',
18
+ '<',
19
+ '>',
20
+ '"',
21
+ "'",
22
+ '\\',
23
+ '(',
24
+ 'a,',
25
+ 'a=',
26
+ '\t',
27
+ '\n',
28
+ 'x-',
29
+ '_',
30
+ '1.',
31
+ 'é',
32
+ ];
33
+ const suffixes = ['!', '', '\0', 'x', '@', '/', '\n', '#', '?', '$', ' ', '1', '"'];
34
+ /** Character counts tried in turn: small steps first, where an exponential pattern shows itself before it hangs, then large. */
35
+ const ladder = [8, 12, 16, 20, 24, 28, 32, 48, 64, 128, 512, 2048, 8192, 32768, 131072];
36
+ export function redosAttacks() {
37
+ return fc.record({ pump: fc.constantFrom(...pumps), suffix: fc.constantFrom(...suffixes) });
38
+ }
39
+ function build(attack, length) {
40
+ if (attack.pump === '')
41
+ return attack.suffix;
42
+ return attack.pump.repeat(Math.ceil(length / attack.pump.length)).slice(0, length) + attack.suffix;
43
+ }
44
+ /**
45
+ * CWE-400 and CWE-1333. `fn(text)` must return within `budgetMs` for every attack at every length up to `maxLength`.
46
+ * The attack grows in steps and stops at the first one over budget, so a pattern that backtracks exponentially is
47
+ * caught at a length of a few dozen characters. The function must be synchronous: the check times it, and cannot
48
+ * interrupt a call that never returns. An exception does not fail the law.
49
+ */
50
+ export function redos(fn, options = {}) {
51
+ const budget = options.budgetMs ?? 100;
52
+ const maxLength = options.maxLength ?? 20000;
53
+ const lengths = [...ladder.filter((n) => n < maxLength), maxLength];
54
+ const slow = (attack) => {
55
+ for (const length of lengths) {
56
+ const text = build(attack, length);
57
+ const start = performance.now();
58
+ try {
59
+ fn(text);
60
+ }
61
+ catch {
62
+ // A refusal is fast enough.
63
+ }
64
+ const took = performance.now() - start;
65
+ if (took > budget)
66
+ return {
67
+ detail: `fn took ${took.toFixed(0)} ms (budget ${budget} ms) on ${text.length} characters: ${show(attack.pump)} repeated, then ${show(attack.suffix)}`,
68
+ };
69
+ }
70
+ return undefined;
71
+ };
72
+ // The fixed attacks are checked once per law, not on every generated input.
73
+ let corpusVerdict = 'unchecked';
74
+ const corpus = () => {
75
+ if (corpusVerdict === 'unchecked') {
76
+ corpusVerdict = undefined;
77
+ for (const pump of pumps)
78
+ for (const suffix of ['!', '', 'x']) {
79
+ corpusVerdict = slow({ pump, suffix });
80
+ if (corpusVerdict !== undefined)
81
+ return corpusVerdict;
82
+ }
83
+ }
84
+ return corpusVerdict;
85
+ };
86
+ return securityLaw({
87
+ id: 'redos',
88
+ cwe: ['CWE-400', 'CWE-1333'],
89
+ title: `a function finishes within ${budget} ms on adversarial long inputs`,
90
+ input: redosAttacks(),
91
+ verdict: (attack) => corpus() ?? slow(attack),
92
+ });
93
+ }
@@ -0,0 +1,25 @@
1
+ import * as fc from 'fast-check';
2
+ import type { SecurityLaw } from './law.ts';
3
+ /** An untrusted string for a law parameter: `law strict(s: UntrustedInput) => validation.holds(s)`. */
4
+ export type UntrustedInput = string & {
5
+ readonly __tslawsUntrusted: true;
6
+ };
7
+ /** Edge cases that slip past a loose pattern: line breaks, a null byte, padding, other scripts' digits, and overlong text. */
8
+ export declare const validationCorpus: readonly string[];
9
+ /** Variants of a valid example that a strict validator must still judge correctly. */
10
+ export declare function mutations(seed: string): string[];
11
+ export interface ValidationOptions<T> {
12
+ /** Valid examples; their mutations (a trailing newline, a null byte, other scripts' digits) are tried too. Strings only. */
13
+ seeds?: readonly string[];
14
+ /** Inputs to try instead of the built-in strings. Required when the validator takes something other than a string. */
15
+ input?: fc.Arbitrary<T>;
16
+ }
17
+ /**
18
+ * CWE-20. Every input `validator` accepts must satisfy `predicate`: the accepted set is a subset of the stated one.
19
+ * The validator may accept less than the predicate; that is not a failure. Both may throw, and a throw from the
20
+ * validator counts as a refusal.
21
+ */
22
+ export declare function inputValidation(validator: (input: string) => boolean, predicate: (input: string) => boolean, options?: ValidationOptions<UntrustedInput>): SecurityLaw<UntrustedInput>;
23
+ export declare function inputValidation<T>(validator: (input: T) => boolean, predicate: (input: T) => boolean, options: ValidationOptions<T> & {
24
+ input: fc.Arbitrary<T>;
25
+ }): SecurityLaw<T>;
@@ -0,0 +1,89 @@
1
+ // CWE-20: a validator accepts only inputs that satisfy a stated predicate.
2
+ import * as fc from 'fast-check';
3
+ import { show } from "./cwe.js";
4
+ import { securityLaw } from "./law.js";
5
+ import { htmlCorpus } from "./xss.js";
6
+ import { pathCorpus } from "./pathTraversal.js";
7
+ /** Edge cases that slip past a loose pattern: line breaks, a null byte, padding, other scripts' digits, and overlong text. */
8
+ export const validationCorpus = [
9
+ '',
10
+ ' ',
11
+ '\n',
12
+ '\r\n',
13
+ '\0',
14
+ '0',
15
+ '-1',
16
+ '1e3',
17
+ '0x10',
18
+ '٣٢',
19
+ '12',
20
+ '12\n',
21
+ '\n12',
22
+ '12\0',
23
+ ' 12',
24
+ '12 ',
25
+ '12;DROP TABLE users',
26
+ "' OR '1'='1",
27
+ 'a'.repeat(5000),
28
+ ...htmlCorpus,
29
+ ...pathCorpus,
30
+ ];
31
+ /** Variants of a valid example that a strict validator must still judge correctly. */
32
+ export function mutations(seed) {
33
+ return [
34
+ seed + '\n',
35
+ '\n' + seed,
36
+ seed + '\0',
37
+ seed + ' ',
38
+ ' ' + seed,
39
+ seed + seed,
40
+ seed.slice(1),
41
+ seed.slice(0, -1),
42
+ seed.toUpperCase(),
43
+ seed.toLowerCase(),
44
+ seed + ';',
45
+ "'" + seed,
46
+ seed + '%00',
47
+ seed.replace(/[0-9]/g, (d) => String.fromCodePoint(0x660 + Number(d))),
48
+ seed.replace(/[0-9]/g, (d) => String.fromCodePoint(0xff10 + Number(d))),
49
+ ];
50
+ }
51
+ export function inputValidation(validator, predicate, options = {}) {
52
+ const seeds = options.seeds ?? [];
53
+ const strings = fc.oneof({ weight: 4, arbitrary: fc.string({ unit: 'binary' }) }, { weight: 2, arbitrary: fc.constantFrom(...validationCorpus) }, ...(seeds.length > 0
54
+ ? [
55
+ {
56
+ weight: 4,
57
+ arbitrary: fc.constantFrom(...seeds).chain((seed) => fc.constantFrom(seed, ...mutations(seed))),
58
+ },
59
+ ]
60
+ : []));
61
+ const input = options.input ?? strings;
62
+ const corpus = options.input === undefined ? [...validationCorpus, ...seeds.flatMap((s) => [s, ...mutations(s)])] : [];
63
+ return securityLaw({
64
+ id: 'input-validation',
65
+ cwe: ['CWE-20'],
66
+ title: 'a validator accepts only inputs that satisfy the stated predicate',
67
+ input,
68
+ corpus,
69
+ verdict: (value) => {
70
+ let accepted;
71
+ try {
72
+ accepted = validator(value);
73
+ }
74
+ catch {
75
+ return undefined;
76
+ }
77
+ if (accepted !== true)
78
+ return undefined;
79
+ let stated;
80
+ try {
81
+ stated = predicate(value);
82
+ }
83
+ catch {
84
+ stated = false;
85
+ }
86
+ return stated ? undefined : { detail: `validator accepted ${show(value)}, which the predicate rejects` };
87
+ },
88
+ });
89
+ }
@@ -0,0 +1,21 @@
1
+ import * as fc from 'fast-check';
2
+ import type { SecurityLaw } from './law.ts';
3
+ /** A hostile string for a law parameter: `law safe(s: HtmlPayload) => escaping.holds(s)`. Generated by `htmlPayloads`. */
4
+ export type HtmlPayload = string & {
5
+ readonly __tslawsHtml: true;
6
+ };
7
+ export declare const htmlCorpus: readonly string[];
8
+ /**
9
+ * Strings heavy in the characters an escaper must handle, many of them repeated (an escaper that replaces only the
10
+ * first one fails on them).
11
+ */
12
+ export declare function htmlPayloads(): fc.Arbitrary<HtmlPayload>;
13
+ export interface HtmlEscapeOptions {
14
+ /**
15
+ * Where the output goes. `html` is element text: no `<`. `attribute` (the default) is a quoted attribute value: no
16
+ * `<`, `"`, `'` or backtick. `unquoted-attribute` also forbids whitespace, `=` and `>`.
17
+ */
18
+ context?: 'html' | 'attribute' | 'unquoted-attribute';
19
+ }
20
+ /** CWE-79. `escape(input)` must return a string without any character `context` forbids. A throw refuses the input. */
21
+ export declare function htmlEscaping(escape: (input: string) => unknown, options?: HtmlEscapeOptions): SecurityLaw<HtmlPayload>;
@@ -0,0 +1,90 @@
1
+ // CWE-79: an HTML escaper's output has no unescaped markup characters for the context it is used in.
2
+ import * as fc from 'fast-check';
3
+ import { show } from "./cwe.js";
4
+ import { securityLaw } from "./law.js";
5
+ export const htmlCorpus = [
6
+ '<script>alert(1)</script>',
7
+ '<img src=x onerror=alert(1)>',
8
+ '"><svg/onload=alert(1)>',
9
+ "'><script>alert(1)</script>",
10
+ "' onmouseover='alert(1)",
11
+ '" onfocus="alert(1)" autofocus="',
12
+ '`onmouseover=alert(1)',
13
+ '<a href="javascript:alert(1)">x</a>',
14
+ '</textarea><script>alert(1)</script>',
15
+ '<<script>script>',
16
+ '&lt;script&gt;',
17
+ '&#60;script&#62;',
18
+ '<',
19
+ '"',
20
+ "'",
21
+ '`',
22
+ '<<<<>>>>""""\'\'\'\'````',
23
+ ];
24
+ const pieces = [
25
+ '<',
26
+ '>',
27
+ '"',
28
+ "'",
29
+ '`',
30
+ '&',
31
+ '=',
32
+ ' ',
33
+ '/',
34
+ 'script',
35
+ 'img',
36
+ 'onerror',
37
+ 'alert(1)',
38
+ 'javascript:',
39
+ '&lt;',
40
+ '&#x3c;',
41
+ '
',
42
+ '\0',
43
+ 'a',
44
+ ];
45
+ /**
46
+ * Strings heavy in the characters an escaper must handle, many of them repeated (an escaper that replaces only the
47
+ * first one fails on them).
48
+ */
49
+ export function htmlPayloads() {
50
+ return fc
51
+ .oneof({
52
+ weight: 6,
53
+ arbitrary: fc.array(fc.constantFrom(...pieces), { minLength: 1, maxLength: 24 }).map((p) => p.join('')),
54
+ }, { weight: 2, arbitrary: fc.constantFrom(...htmlCorpus) }, { weight: 1, arbitrary: fc.string() })
55
+ .map((s) => s);
56
+ }
57
+ const forbidden = {
58
+ html: '<',
59
+ attribute: '<"\'`',
60
+ 'unquoted-attribute': '<>"\'` \t\n\r\f=',
61
+ };
62
+ /** CWE-79. `escape(input)` must return a string without any character `context` forbids. A throw refuses the input. */
63
+ export function htmlEscaping(escape, options = {}) {
64
+ const context = options.context ?? 'attribute';
65
+ const chars = forbidden[context];
66
+ return securityLaw({
67
+ id: 'html-escaping',
68
+ cwe: ['CWE-79'],
69
+ title: `an HTML escaper leaves no unescaped markup characters in ${context} context`,
70
+ input: htmlPayloads(),
71
+ corpus: htmlCorpus,
72
+ verdict: (input) => {
73
+ let out;
74
+ try {
75
+ out = escape(input);
76
+ }
77
+ catch {
78
+ return undefined;
79
+ }
80
+ if (typeof out !== 'string')
81
+ return { detail: `escape(${show(input)}) returned ${show(out)}, not a string` };
82
+ for (const ch of out)
83
+ if (chars.includes(ch))
84
+ return {
85
+ detail: `escape(${show(input)}) returned ${show(out)}, with an unescaped ${show(ch)} for ${context} context`,
86
+ };
87
+ return undefined;
88
+ },
89
+ });
90
+ }