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.
- package/README.md +7 -2
- package/bin/tslaws.js +8 -2
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +25 -5
- package/dist/bundled.js +2 -2
- package/dist/bundlerPlugins.d.ts +2 -0
- package/dist/bundlerPlugins.js +7 -0
- package/dist/certificates.d.ts +139 -0
- package/dist/certificates.js +433 -0
- package/dist/chc.d.ts +85 -0
- package/dist/chc.js +298 -0
- package/dist/check.d.ts +13 -1
- package/dist/check.js +211 -27
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +175 -34
- package/dist/compile.d.ts +15 -5
- package/dist/compile.js +198 -69
- package/dist/coverage.d.ts +38 -1
- package/dist/coverage.js +94 -12
- package/dist/e2eApi.js +3 -1
- package/dist/generators.js +12 -2
- package/dist/github.d.ts +49 -5
- package/dist/github.js +107 -24
- package/dist/githubCli.d.ts +28 -0
- package/dist/githubCli.js +1039 -211
- package/dist/hints.js +2 -1
- package/dist/init.js +42 -0
- package/dist/isolate.d.ts +28 -0
- package/dist/isolate.js +262 -0
- package/dist/isolatedCheck.d.ts +1 -0
- package/dist/isolatedCheck.js +16 -0
- package/dist/lawHost.d.ts +50 -0
- package/dist/lawHost.js +199 -0
- package/dist/lawRuntime.d.ts +39 -0
- package/dist/lawRuntime.js +242 -0
- package/dist/lock.d.ts +49 -9
- package/dist/lock.js +132 -21
- package/dist/mcp.js +28 -7
- package/dist/mutate.d.ts +4 -0
- package/dist/mutate.js +7 -1
- package/dist/plan.d.ts +1 -0
- package/dist/plan.js +4 -0
- package/dist/pluginHooks.d.ts +16 -0
- package/dist/pluginHooks.js +48 -0
- package/dist/pluginHost.d.ts +5 -0
- package/dist/pluginHost.js +43 -0
- package/dist/pluginWorker.d.ts +1 -0
- package/dist/pluginWorker.js +40 -0
- package/dist/plural.d.ts +2 -0
- package/dist/plural.js +4 -0
- package/dist/pool.d.ts +80 -7
- package/dist/pool.js +222 -11
- package/dist/projects.d.ts +43 -1
- package/dist/projects.js +283 -11
- package/dist/promote.d.ts +56 -2
- package/dist/promote.js +429 -13
- package/dist/property.js +5 -1
- package/dist/propertyWorker.js +7 -0
- package/dist/proposals.d.ts +52 -4
- package/dist/proposals.js +484 -21
- package/dist/reporters.js +5 -1
- package/dist/runtimeEnv.d.ts +13 -5
- package/dist/runtimeEnv.js +48 -10
- package/dist/sandbox.d.ts +98 -0
- package/dist/sandbox.js +673 -0
- package/dist/sandboxGuard.d.ts +56 -0
- package/dist/sandboxGuard.js +249 -0
- package/dist/seal.d.ts +9 -0
- package/dist/seal.js +426 -0
- package/dist/security/cli.d.ts +6 -0
- package/dist/security/cli.js +39 -0
- package/dist/security/cwe.d.ts +14 -0
- package/dist/security/cwe.js +40 -0
- package/dist/security/deps/cache.d.ts +28 -0
- package/dist/security/deps/cache.js +107 -0
- package/dist/security/deps/config.d.ts +16 -0
- package/dist/security/deps/config.js +43 -0
- package/dist/security/deps/imports.d.ts +4 -0
- package/dist/security/deps/imports.js +33 -0
- package/dist/security/deps/lockfiles.d.ts +23 -0
- package/dist/security/deps/lockfiles.js +153 -0
- package/dist/security/deps/osv.d.ts +66 -0
- package/dist/security/deps/osv.js +137 -0
- package/dist/security/deps/run.d.ts +54 -0
- package/dist/security/deps/run.js +135 -0
- package/dist/security/deps/severity.d.ts +26 -0
- package/dist/security/deps/severity.js +78 -0
- package/dist/security/generators.d.ts +9 -0
- package/dist/security/generators.js +36 -0
- package/dist/security/index.d.ts +27 -0
- package/dist/security/index.js +18 -0
- package/dist/security/integers.d.ts +31 -0
- package/dist/security/integers.js +105 -0
- package/dist/security/law.d.ts +54 -0
- package/dist/security/law.js +54 -0
- package/dist/security/pathTraversal.d.ts +29 -0
- package/dist/security/pathTraversal.js +146 -0
- package/dist/security/prototypePollution.d.ts +30 -0
- package/dist/security/prototypePollution.js +142 -0
- package/dist/security/redirect.d.ts +21 -0
- package/dist/security/redirect.js +154 -0
- package/dist/security/redos.d.ts +21 -0
- package/dist/security/redos.js +93 -0
- package/dist/security/validation.d.ts +25 -0
- package/dist/security/validation.js +89 -0
- package/dist/security/xss.d.ts +21 -0
- package/dist/security/xss.js +90 -0
- package/dist/settings.d.ts +20 -0
- package/dist/settings.js +32 -0
- package/dist/smt.d.ts +29 -1
- package/dist/smt.js +239 -107
- package/dist/smtWorker.d.ts +1 -0
- package/dist/smtWorker.js +26 -0
- package/dist/solvers.d.ts +9 -0
- package/dist/solvers.js +11 -5
- package/dist/symbolic.d.ts +54 -1
- package/dist/symbolic.js +239 -13
- package/dist/tsconfigResolve.d.ts +28 -0
- package/dist/tsconfigResolve.js +141 -0
- package/dist/types.d.ts +28 -0
- package/hooks/claude-hook.mjs +2 -0
- package/package.json +18 -6
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Severity } from './severity.ts';
|
|
2
|
+
export interface SecurityConfig {
|
|
3
|
+
/** Fail when an advisory is at or above this severity. Default `high`. */
|
|
4
|
+
failOn: Exclude<Severity, 'unknown'>;
|
|
5
|
+
/** Use only the cache and never touch the network. Default false. */
|
|
6
|
+
offline: boolean;
|
|
7
|
+
/** Keep answers in the per-user cache directory (`tslaws/osv-cache.json`). Default true. */
|
|
8
|
+
cache: boolean;
|
|
9
|
+
/** How long a cached answer stays fresh when online, in hours. Default 24. */
|
|
10
|
+
cacheTtlHours: number;
|
|
11
|
+
/** Advisory ids (GHSA, CVE or OSV) that a person has reviewed and accepted. They are listed but never fail. */
|
|
12
|
+
ignore: string[];
|
|
13
|
+
}
|
|
14
|
+
export declare const defaultSecurityConfig: SecurityConfig;
|
|
15
|
+
/** Validates `security` from tslaws.json; fills the defaults. */
|
|
16
|
+
export declare function parseSecurityConfig(raw: unknown): SecurityConfig;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// The `security` section of tslaws.json.
|
|
2
|
+
import { parseSeverity } from "./severity.js";
|
|
3
|
+
export const defaultSecurityConfig = {
|
|
4
|
+
failOn: 'high',
|
|
5
|
+
offline: false,
|
|
6
|
+
cache: true,
|
|
7
|
+
cacheTtlHours: 24,
|
|
8
|
+
ignore: [],
|
|
9
|
+
};
|
|
10
|
+
const keys = ['failOn', 'offline', 'cache', 'cacheTtlHours', 'ignore'];
|
|
11
|
+
/** Validates `security` from tslaws.json; fills the defaults. */
|
|
12
|
+
export function parseSecurityConfig(raw) {
|
|
13
|
+
const fail = (message) => {
|
|
14
|
+
throw new Error(`tslaws.json: security: ${message}`);
|
|
15
|
+
};
|
|
16
|
+
if (raw === undefined)
|
|
17
|
+
return { ...defaultSecurityConfig };
|
|
18
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
|
|
19
|
+
return fail('must be an object');
|
|
20
|
+
const object = raw;
|
|
21
|
+
for (const key of Object.keys(object))
|
|
22
|
+
if (!keys.includes(key))
|
|
23
|
+
fail(`unknown option "${key}"; supported options are ${keys.join(', ')}`);
|
|
24
|
+
const failOn = object.failOn === undefined ? defaultSecurityConfig.failOn : parseSeverity(object.failOn);
|
|
25
|
+
if (failOn === undefined || failOn === 'unknown')
|
|
26
|
+
fail(`"failOn" must be "low", "moderate", "high" or "critical", got ${JSON.stringify(object.failOn)}`);
|
|
27
|
+
for (const key of ['offline', 'cache'])
|
|
28
|
+
if (object[key] !== undefined && typeof object[key] !== 'boolean')
|
|
29
|
+
fail(`"${key}" must be true or false`);
|
|
30
|
+
const ttl = object.cacheTtlHours;
|
|
31
|
+
if (ttl !== undefined && (typeof ttl !== 'number' || !(ttl >= 0)))
|
|
32
|
+
fail('"cacheTtlHours" must be a number of hours');
|
|
33
|
+
const ignore = object.ignore;
|
|
34
|
+
if (ignore !== undefined && (!Array.isArray(ignore) || ignore.some((id) => typeof id !== 'string' || id === '')))
|
|
35
|
+
fail('"ignore" must be an array of advisory ids');
|
|
36
|
+
return {
|
|
37
|
+
failOn: failOn,
|
|
38
|
+
offline: object.offline ?? defaultSecurityConfig.offline,
|
|
39
|
+
cache: object.cache ?? defaultSecurityConfig.cache,
|
|
40
|
+
cacheTtlHours: ttl ?? defaultSecurityConfig.cacheTtlHours,
|
|
41
|
+
ignore: ignore ?? [],
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** The package a specifier names (`@scope/name` or `name`), or undefined for a relative path, a built-in or a URL. */
|
|
2
|
+
export declare function packageOf(specifier: string): string | undefined;
|
|
3
|
+
/** For each package imported (value imports only; `import type` loads nothing) by the files: how many files import it. */
|
|
4
|
+
export declare function collectImports(cwd: string, files: readonly string[]): Map<string, number>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// The npm packages the covered source files import, as a name and the number of files that import it.
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { builtinModules } from 'node:module';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { moduleSpecifiers } from "../../lawKinds.js";
|
|
6
|
+
const builtins = new Set(builtinModules.map((name) => name.replace(/^node:/, '').split('/')[0]));
|
|
7
|
+
/** The package a specifier names (`@scope/name` or `name`), or undefined for a relative path, a built-in or a URL. */
|
|
8
|
+
export function packageOf(specifier) {
|
|
9
|
+
if (specifier === '' || /^[./#]/.test(specifier) || /^[a-z][a-z0-9+.-]*:/i.test(specifier))
|
|
10
|
+
return undefined;
|
|
11
|
+
const parts = specifier.split('/');
|
|
12
|
+
const name = specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
13
|
+
if (name === '' || name === '@' || name.endsWith('/') || builtins.has(name))
|
|
14
|
+
return undefined;
|
|
15
|
+
return name;
|
|
16
|
+
}
|
|
17
|
+
/** For each package imported (value imports only; `import type` loads nothing) by the files: how many files import it. */
|
|
18
|
+
export function collectImports(cwd, files) {
|
|
19
|
+
const found = new Map();
|
|
20
|
+
for (const file of files) {
|
|
21
|
+
const names = new Set();
|
|
22
|
+
for (const specifier of moduleSpecifiers(readFileSync(join(cwd, file), 'utf8'), file)) {
|
|
23
|
+
if (specifier.typeOnly)
|
|
24
|
+
continue;
|
|
25
|
+
const name = packageOf(specifier.value);
|
|
26
|
+
if (name !== undefined)
|
|
27
|
+
names.add(name);
|
|
28
|
+
}
|
|
29
|
+
for (const name of names)
|
|
30
|
+
found.set(name, (found.get(name) ?? 0) + 1);
|
|
31
|
+
}
|
|
32
|
+
return new Map([...found].sort(([a], [b]) => a.localeCompare(b)));
|
|
33
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export interface Locked {
|
|
2
|
+
/** Which file the versions came from. */
|
|
3
|
+
source: string;
|
|
4
|
+
/** Every version of each package the lockfile resolves; the first is the one the project's own code sees, where the lockfile says. */
|
|
5
|
+
versions: Map<string, string[]>;
|
|
6
|
+
/** Packages the lockfile links to a folder in the workspace: private, not on npm. */
|
|
7
|
+
links: Set<string>;
|
|
8
|
+
}
|
|
9
|
+
/** package-lock.json and npm-shrinkwrap.json, lockfileVersion 1 to 3. */
|
|
10
|
+
export declare function parseNpmLock(text: string): Pick<Locked, 'versions' | 'links'>;
|
|
11
|
+
/** pnpm-lock.yaml: the keys of `packages:` in the v5 (`/name/1.2.3`), v6 (`/name@1.2.3`) and v9 (`name@1.2.3`) layouts. */
|
|
12
|
+
export declare function parsePnpmLock(text: string): Pick<Locked, 'versions' | 'links'>;
|
|
13
|
+
/** yarn.lock, classic (`version "1.2.3"`) and berry (`version: 1.2.3`). */
|
|
14
|
+
export declare function parseYarnLock(text: string): Pick<Locked, 'versions' | 'links'>;
|
|
15
|
+
/** bun.lock (text; JSON with comments and trailing commas): each `packages` entry starts with `name@version`. */
|
|
16
|
+
export declare function parseBunLock(text: string): Pick<Locked, 'versions' | 'links'>;
|
|
17
|
+
/** The nearest lockfile at or above `cwd` (a monorepo keeps one at its root), read; undefined when there is none. */
|
|
18
|
+
export declare function readLockfile(cwd: string): Locked | undefined;
|
|
19
|
+
/** The installed version of a package, from the nearest `node_modules/<name>/package.json`, plus whether it is a workspace link (a symlink to a folder outside node_modules, not a pnpm store link). */
|
|
20
|
+
export declare function installedVersion(cwd: string, name: string): {
|
|
21
|
+
version?: string;
|
|
22
|
+
link: boolean;
|
|
23
|
+
};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Versions of installed packages, from the project's lockfile (npm, pnpm, yarn or bun) or its node_modules.
|
|
2
|
+
import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { dirname, join, relative, resolve, sep } from 'node:path';
|
|
4
|
+
function add(map, name, version, first = false) {
|
|
5
|
+
const list = map.get(name) ?? [];
|
|
6
|
+
if (!list.includes(version)) {
|
|
7
|
+
if (first)
|
|
8
|
+
list.unshift(version);
|
|
9
|
+
else
|
|
10
|
+
list.push(version);
|
|
11
|
+
}
|
|
12
|
+
map.set(name, list);
|
|
13
|
+
}
|
|
14
|
+
/** package-lock.json and npm-shrinkwrap.json, lockfileVersion 1 to 3. */
|
|
15
|
+
export function parseNpmLock(text) {
|
|
16
|
+
const lock = JSON.parse(text);
|
|
17
|
+
const versions = new Map();
|
|
18
|
+
const links = new Set();
|
|
19
|
+
if (lock.packages !== undefined) {
|
|
20
|
+
for (const [path, entry] of Object.entries(lock.packages)) {
|
|
21
|
+
const at = path.lastIndexOf('node_modules/');
|
|
22
|
+
if (at < 0)
|
|
23
|
+
continue;
|
|
24
|
+
const name = path.slice(at + 'node_modules/'.length);
|
|
25
|
+
if (entry.link === true)
|
|
26
|
+
links.add(name);
|
|
27
|
+
else if (entry.version !== undefined)
|
|
28
|
+
add(versions, name, entry.version, at === 0);
|
|
29
|
+
}
|
|
30
|
+
return { versions, links };
|
|
31
|
+
}
|
|
32
|
+
const walk = (deps, top) => {
|
|
33
|
+
for (const [name, entry] of Object.entries(deps)) {
|
|
34
|
+
if (entry.version !== undefined)
|
|
35
|
+
add(versions, name, entry.version, top);
|
|
36
|
+
if (entry.dependencies !== undefined)
|
|
37
|
+
walk(entry.dependencies, false);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
walk(lock.dependencies ?? {}, true);
|
|
41
|
+
return { versions, links };
|
|
42
|
+
}
|
|
43
|
+
/** pnpm-lock.yaml: the keys of `packages:` in the v5 (`/name/1.2.3`), v6 (`/name@1.2.3`) and v9 (`name@1.2.3`) layouts. */
|
|
44
|
+
export function parsePnpmLock(text) {
|
|
45
|
+
const versions = new Map();
|
|
46
|
+
let inPackages = false;
|
|
47
|
+
for (const line of text.split(/\r?\n/)) {
|
|
48
|
+
if (/^\S/.test(line)) {
|
|
49
|
+
inPackages = /^packages:\s*$/.test(line);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (!inPackages)
|
|
53
|
+
continue;
|
|
54
|
+
const key = /^ {2}(?!\s)(.+?):\s*$/.exec(line)?.[1];
|
|
55
|
+
if (key === undefined)
|
|
56
|
+
continue;
|
|
57
|
+
const bare = key
|
|
58
|
+
.replace(/^['"]|['"]$/g, '')
|
|
59
|
+
.replace(/^\//, '')
|
|
60
|
+
.replace(/\(.*$/, '');
|
|
61
|
+
const modern = /^(@?[^@]+)@(\d[^\s_]*)$/.exec(bare);
|
|
62
|
+
const legacy = /^(@[^/]+\/[^/]+|[^/@]+)\/(\d[^_/]*)/.exec(bare);
|
|
63
|
+
const match = legacy ?? modern;
|
|
64
|
+
if (match !== null)
|
|
65
|
+
add(versions, match[1], match[2]);
|
|
66
|
+
}
|
|
67
|
+
return { versions, links: new Set() };
|
|
68
|
+
}
|
|
69
|
+
/** yarn.lock, classic (`version "1.2.3"`) and berry (`version: 1.2.3`). */
|
|
70
|
+
export function parseYarnLock(text) {
|
|
71
|
+
const versions = new Map();
|
|
72
|
+
let names = [];
|
|
73
|
+
for (const line of text.split(/\r?\n/)) {
|
|
74
|
+
if (line.startsWith('#') || line.trim() === '')
|
|
75
|
+
continue;
|
|
76
|
+
if (/^\S/.test(line) && line.trimEnd().endsWith(':')) {
|
|
77
|
+
names = line
|
|
78
|
+
.trimEnd()
|
|
79
|
+
.slice(0, -1)
|
|
80
|
+
.split(',')
|
|
81
|
+
.map((spec) => spec.trim().replace(/^['"]|['"]$/g, ''))
|
|
82
|
+
.filter((spec) => !/@(workspace|patch|link|portal|file):/.test(spec))
|
|
83
|
+
.map((spec) => spec.slice(0, spec.indexOf('@', 1)))
|
|
84
|
+
.filter((name) => name !== '');
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const version = /^ {2}version:? "?([^"\s]+)"?\s*$/.exec(line)?.[1];
|
|
88
|
+
if (version !== undefined) {
|
|
89
|
+
for (const name of new Set(names))
|
|
90
|
+
add(versions, name, version);
|
|
91
|
+
names = [];
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return { versions, links: new Set() };
|
|
95
|
+
}
|
|
96
|
+
/** bun.lock (text; JSON with comments and trailing commas): each `packages` entry starts with `name@version`. */
|
|
97
|
+
export function parseBunLock(text) {
|
|
98
|
+
const json = text.replace(/^\s*\/\/.*$/gm, '').replace(/,(\s*[}\]])/g, '$1');
|
|
99
|
+
const lock = JSON.parse(json);
|
|
100
|
+
const versions = new Map();
|
|
101
|
+
for (const entry of Object.values(lock.packages ?? {})) {
|
|
102
|
+
const ident = entry[0];
|
|
103
|
+
if (typeof ident !== 'string')
|
|
104
|
+
continue;
|
|
105
|
+
const at = ident.indexOf('@', 1);
|
|
106
|
+
const version = at > 0 ? ident.slice(at + 1) : '';
|
|
107
|
+
if (/^\d/.test(version))
|
|
108
|
+
add(versions, ident.slice(0, at), version);
|
|
109
|
+
}
|
|
110
|
+
return { versions, links: new Set() };
|
|
111
|
+
}
|
|
112
|
+
const lockfiles = [
|
|
113
|
+
['package-lock.json', parseNpmLock],
|
|
114
|
+
['npm-shrinkwrap.json', parseNpmLock],
|
|
115
|
+
['pnpm-lock.yaml', parsePnpmLock],
|
|
116
|
+
['yarn.lock', parseYarnLock],
|
|
117
|
+
['bun.lock', parseBunLock],
|
|
118
|
+
];
|
|
119
|
+
/** The nearest lockfile at or above `cwd` (a monorepo keeps one at its root), read; undefined when there is none. */
|
|
120
|
+
export function readLockfile(cwd) {
|
|
121
|
+
for (let dir = resolve(cwd), depth = 0; depth < 8; dir = dirname(dir), depth += 1) {
|
|
122
|
+
for (const [name, parse] of lockfiles) {
|
|
123
|
+
const path = join(dir, name);
|
|
124
|
+
if (existsSync(path))
|
|
125
|
+
return { source: name, ...parse(readFileSync(path, 'utf8')) };
|
|
126
|
+
}
|
|
127
|
+
if (dirname(dir) === dir)
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
return undefined;
|
|
131
|
+
}
|
|
132
|
+
/** The installed version of a package, from the nearest `node_modules/<name>/package.json`, plus whether it is a workspace link (a symlink to a folder outside node_modules, not a pnpm store link). */
|
|
133
|
+
export function installedVersion(cwd, name) {
|
|
134
|
+
for (let dir = resolve(cwd), depth = 0; depth < 8; dir = dirname(dir), depth += 1) {
|
|
135
|
+
const folder = join(dir, 'node_modules', ...name.split('/'));
|
|
136
|
+
if (existsSync(folder)) {
|
|
137
|
+
// pnpm links registry packages from its store (inside a node_modules folder); only a link that leaves
|
|
138
|
+
// node_modules is a workspace package.
|
|
139
|
+
const link = lstatSync(folder).isSymbolicLink() && !relative(dir, realpathSync(folder)).split(sep).includes('node_modules');
|
|
140
|
+
try {
|
|
141
|
+
const version = JSON.parse(readFileSync(join(folder, 'package.json'), 'utf8'))
|
|
142
|
+
.version;
|
|
143
|
+
return { version: typeof version === 'string' ? version : undefined, link };
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return { link };
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (dirname(dir) === dir)
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
return { link: false };
|
|
153
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { Severity } from './severity.ts';
|
|
2
|
+
export declare const osvBase = "https://api.osv.dev";
|
|
3
|
+
/** The part of `fetch` the client uses, so a test can pass a mock. */
|
|
4
|
+
export type FetchLike = (url: string, init: {
|
|
5
|
+
method: string;
|
|
6
|
+
headers: Record<string, string>;
|
|
7
|
+
body?: string;
|
|
8
|
+
signal?: AbortSignal;
|
|
9
|
+
}) => Promise<{
|
|
10
|
+
ok: boolean;
|
|
11
|
+
status: number;
|
|
12
|
+
json(): Promise<unknown>;
|
|
13
|
+
}>;
|
|
14
|
+
export interface PackageRef {
|
|
15
|
+
name: string;
|
|
16
|
+
version: string;
|
|
17
|
+
}
|
|
18
|
+
/** The parts of an OSV record the report uses; this is also what the cache keeps. */
|
|
19
|
+
export interface Vuln {
|
|
20
|
+
id: string;
|
|
21
|
+
aliases?: string[];
|
|
22
|
+
summary?: string;
|
|
23
|
+
severity?: {
|
|
24
|
+
type?: string;
|
|
25
|
+
score?: string;
|
|
26
|
+
}[];
|
|
27
|
+
database_specific?: {
|
|
28
|
+
severity?: unknown;
|
|
29
|
+
};
|
|
30
|
+
affected?: {
|
|
31
|
+
package?: {
|
|
32
|
+
name?: string;
|
|
33
|
+
ecosystem?: string;
|
|
34
|
+
};
|
|
35
|
+
ranges?: {
|
|
36
|
+
type?: string;
|
|
37
|
+
events?: Record<string, string>[];
|
|
38
|
+
}[];
|
|
39
|
+
ecosystem_specific?: {
|
|
40
|
+
severity?: unknown;
|
|
41
|
+
};
|
|
42
|
+
}[];
|
|
43
|
+
}
|
|
44
|
+
export interface Advisory {
|
|
45
|
+
/** The OSV id, usually a GHSA id. */
|
|
46
|
+
id: string;
|
|
47
|
+
cve: string[];
|
|
48
|
+
ghsa: string[];
|
|
49
|
+
summary: string;
|
|
50
|
+
severity: Severity;
|
|
51
|
+
/** The versions that fix it, for the installed version. */
|
|
52
|
+
fixed: string[];
|
|
53
|
+
url: string;
|
|
54
|
+
}
|
|
55
|
+
/** The advisory ids that affect each package, in the order of `packages`. */
|
|
56
|
+
export declare function queryBatch(fetch: FetchLike, packages: readonly PackageRef[]): Promise<string[][]>;
|
|
57
|
+
/** One OSV record, by id. */
|
|
58
|
+
export declare function fetchVuln(fetch: FetchLike, id: string): Promise<Vuln>;
|
|
59
|
+
/** Keeps only the fields the report reads, for the cache. */
|
|
60
|
+
export declare function trimVuln(vuln: Vuln): Vuln;
|
|
61
|
+
/** Semver order: negative when `a` is lower. Prereleases sort below their release. */
|
|
62
|
+
export declare function compareVersions(a: string, b: string): number;
|
|
63
|
+
/** The versions of `name` that fix `vuln` for `version`: the `fixed` of the range that holds it, else every `fixed` listed. */
|
|
64
|
+
export declare function fixedVersions(vuln: Vuln, name: string, version: string): string[];
|
|
65
|
+
/** A record shaped for the report, for the package it was found on. */
|
|
66
|
+
export declare function toAdvisory(vuln: Vuln, ref: PackageRef): Advisory;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// A client for OSV (https://osv.dev). It sends package names, versions and advisory ids, and nothing else.
|
|
2
|
+
import { severityOf } from "./severity.js";
|
|
3
|
+
export const osvBase = 'https://api.osv.dev';
|
|
4
|
+
const maxBatch = 1000;
|
|
5
|
+
const maxPages = 20;
|
|
6
|
+
async function post(fetch, path, body) {
|
|
7
|
+
const response = await fetch(`${osvBase}${path}`, {
|
|
8
|
+
method: 'POST',
|
|
9
|
+
headers: { 'content-type': 'application/json' },
|
|
10
|
+
body: JSON.stringify(body),
|
|
11
|
+
signal: AbortSignal.timeout(30000),
|
|
12
|
+
});
|
|
13
|
+
if (!response.ok)
|
|
14
|
+
throw new Error(`OSV answered ${response.status} for ${path}`);
|
|
15
|
+
return response.json();
|
|
16
|
+
}
|
|
17
|
+
/** The advisory ids that affect each package, in the order of `packages`. */
|
|
18
|
+
export async function queryBatch(fetch, packages) {
|
|
19
|
+
const ids = packages.map(() => new Set());
|
|
20
|
+
for (let start = 0; start < packages.length; start += maxBatch) {
|
|
21
|
+
let pending = packages
|
|
22
|
+
.slice(start, start + maxBatch)
|
|
23
|
+
.map((p, i) => ({ index: start + i, ref: p, token: undefined }));
|
|
24
|
+
for (let page = 0; pending.length > 0 && page < maxPages; page += 1) {
|
|
25
|
+
const queries = pending.map(({ ref, token }) => ({
|
|
26
|
+
package: { name: ref.name, ecosystem: 'npm' },
|
|
27
|
+
version: ref.version,
|
|
28
|
+
...(token === undefined ? {} : { page_token: token }),
|
|
29
|
+
}));
|
|
30
|
+
const answer = (await post(fetch, '/v1/querybatch', { queries }));
|
|
31
|
+
const results = answer.results ?? [];
|
|
32
|
+
if (results.length !== pending.length)
|
|
33
|
+
throw new Error('OSV answered a different number of results than queries');
|
|
34
|
+
const next = [];
|
|
35
|
+
results.forEach((result, i) => {
|
|
36
|
+
const item = pending[i];
|
|
37
|
+
for (const vuln of result.vulns ?? [])
|
|
38
|
+
ids[item.index].add(vuln.id);
|
|
39
|
+
if (result.next_page_token !== undefined)
|
|
40
|
+
next.push({ ...item, token: result.next_page_token });
|
|
41
|
+
});
|
|
42
|
+
pending = next;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return ids.map((set) => [...set]);
|
|
46
|
+
}
|
|
47
|
+
/** One OSV record, by id. */
|
|
48
|
+
export async function fetchVuln(fetch, id) {
|
|
49
|
+
const response = await fetch(`${osvBase}/v1/vulns/${encodeURIComponent(id)}`, {
|
|
50
|
+
method: 'GET',
|
|
51
|
+
headers: { accept: 'application/json' },
|
|
52
|
+
signal: AbortSignal.timeout(30000),
|
|
53
|
+
});
|
|
54
|
+
if (!response.ok)
|
|
55
|
+
throw new Error(`OSV answered ${response.status} for ${id}`);
|
|
56
|
+
return trimVuln((await response.json()));
|
|
57
|
+
}
|
|
58
|
+
/** Keeps only the fields the report reads, for the cache. */
|
|
59
|
+
export function trimVuln(vuln) {
|
|
60
|
+
return {
|
|
61
|
+
id: vuln.id,
|
|
62
|
+
aliases: vuln.aliases,
|
|
63
|
+
summary: vuln.summary,
|
|
64
|
+
severity: vuln.severity,
|
|
65
|
+
database_specific: vuln.database_specific?.severity === undefined ? undefined : { severity: vuln.database_specific.severity },
|
|
66
|
+
affected: vuln.affected?.map((a) => ({
|
|
67
|
+
package: a.package === undefined ? undefined : { name: a.package.name, ecosystem: a.package.ecosystem },
|
|
68
|
+
ranges: a.ranges?.map((r) => ({ type: r.type, events: r.events })),
|
|
69
|
+
ecosystem_specific: a.ecosystem_specific?.severity === undefined ? undefined : { severity: a.ecosystem_specific.severity },
|
|
70
|
+
})),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function parts(version) {
|
|
74
|
+
const [core = '', pre = ''] = version.replace(/^v/, '').split(/\+/, 1)[0].split(/-(.*)/s);
|
|
75
|
+
return { core: core.split('.').map((n) => Number.parseInt(n, 10) || 0), pre };
|
|
76
|
+
}
|
|
77
|
+
/** Semver order: negative when `a` is lower. Prereleases sort below their release. */
|
|
78
|
+
export function compareVersions(a, b) {
|
|
79
|
+
const x = parts(a);
|
|
80
|
+
const y = parts(b);
|
|
81
|
+
for (let i = 0; i < Math.max(x.core.length, y.core.length); i += 1) {
|
|
82
|
+
const d = (x.core[i] ?? 0) - (y.core[i] ?? 0);
|
|
83
|
+
if (d !== 0)
|
|
84
|
+
return d;
|
|
85
|
+
}
|
|
86
|
+
if (x.pre === y.pre)
|
|
87
|
+
return 0;
|
|
88
|
+
if (x.pre === '')
|
|
89
|
+
return 1;
|
|
90
|
+
if (y.pre === '')
|
|
91
|
+
return -1;
|
|
92
|
+
return x.pre < y.pre ? -1 : 1;
|
|
93
|
+
}
|
|
94
|
+
/** The versions of `name` that fix `vuln` for `version`: the `fixed` of the range that holds it, else every `fixed` listed. */
|
|
95
|
+
export function fixedVersions(vuln, name, version) {
|
|
96
|
+
const hit = new Set();
|
|
97
|
+
const all = new Set();
|
|
98
|
+
for (const affected of vuln.affected ?? []) {
|
|
99
|
+
if (affected.package?.name !== name || affected.package.ecosystem?.toLowerCase() !== 'npm')
|
|
100
|
+
continue;
|
|
101
|
+
for (const range of affected.ranges ?? []) {
|
|
102
|
+
if (range.type === 'GIT')
|
|
103
|
+
continue;
|
|
104
|
+
let start;
|
|
105
|
+
for (const event of range.events ?? []) {
|
|
106
|
+
if (event.introduced !== undefined) {
|
|
107
|
+
start = event.introduced;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const { fixed, last_affected: last } = event;
|
|
111
|
+
if (fixed === undefined && last === undefined)
|
|
112
|
+
continue;
|
|
113
|
+
if (fixed !== undefined)
|
|
114
|
+
all.add(fixed);
|
|
115
|
+
const aboveStart = start === undefined || start === '0' || compareVersions(version, start) >= 0;
|
|
116
|
+
const belowEnd = fixed !== undefined ? compareVersions(version, fixed) < 0 : compareVersions(version, last) <= 0;
|
|
117
|
+
if (aboveStart && belowEnd && fixed !== undefined)
|
|
118
|
+
hit.add(fixed);
|
|
119
|
+
start = undefined;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return [...(hit.size > 0 ? hit : all)].sort(compareVersions);
|
|
124
|
+
}
|
|
125
|
+
/** A record shaped for the report, for the package it was found on. */
|
|
126
|
+
export function toAdvisory(vuln, ref) {
|
|
127
|
+
const names = [vuln.id, ...(vuln.aliases ?? [])];
|
|
128
|
+
return {
|
|
129
|
+
id: vuln.id,
|
|
130
|
+
cve: names.filter((n) => n.startsWith('CVE-')),
|
|
131
|
+
ghsa: names.filter((n) => n.startsWith('GHSA-')),
|
|
132
|
+
summary: vuln.summary ?? '',
|
|
133
|
+
severity: severityOf(vuln),
|
|
134
|
+
fixed: fixedVersions(vuln, ref.name, ref.version),
|
|
135
|
+
url: `https://osv.dev/vulnerability/${vuln.id}`,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { SecurityConfig } from './config.ts';
|
|
2
|
+
import type { Advisory, FetchLike, PackageRef } from './osv.ts';
|
|
3
|
+
export interface DepsOptions {
|
|
4
|
+
cwd: string;
|
|
5
|
+
/** `cover` globs of tslaws.json; without them, every non-laws source file. */
|
|
6
|
+
cover?: string[];
|
|
7
|
+
/** Project-relative paths of nested projects: their files belong to them, not to this run. */
|
|
8
|
+
skip?: string[];
|
|
9
|
+
config?: SecurityConfig;
|
|
10
|
+
/** Flags that beat the config. */
|
|
11
|
+
failOn?: SecurityConfig['failOn'];
|
|
12
|
+
offline?: boolean;
|
|
13
|
+
noCache?: boolean;
|
|
14
|
+
fetch?: FetchLike;
|
|
15
|
+
now?: () => number;
|
|
16
|
+
}
|
|
17
|
+
export interface Finding extends Advisory {
|
|
18
|
+
name: string;
|
|
19
|
+
version: string;
|
|
20
|
+
/** Listed in `security.ignore`: shown, never fails. */
|
|
21
|
+
ignored: boolean;
|
|
22
|
+
}
|
|
23
|
+
export interface DepsReport {
|
|
24
|
+
failOn: SecurityConfig['failOn'];
|
|
25
|
+
offline: boolean;
|
|
26
|
+
/** `package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`, `bun.lock` or `node_modules`. */
|
|
27
|
+
source: string;
|
|
28
|
+
/** The packages checked and how many covered files import each. */
|
|
29
|
+
packages: (PackageRef & {
|
|
30
|
+
files: number;
|
|
31
|
+
})[];
|
|
32
|
+
findings: Finding[];
|
|
33
|
+
/** Imported packages with no version in the lockfile or node_modules (a path alias, or not installed). */
|
|
34
|
+
unresolved: string[];
|
|
35
|
+
/** Offline runs: packages the cache has no answer for. */
|
|
36
|
+
unchecked: string[];
|
|
37
|
+
/** True when a finding that is not ignored is at or above `failOn`. */
|
|
38
|
+
failed: boolean;
|
|
39
|
+
}
|
|
40
|
+
/** Resolves the imported packages to name and version through the lockfile, falling back to node_modules. */
|
|
41
|
+
export declare function resolvePackages(cwd: string, imported: Map<string, number>): {
|
|
42
|
+
source: string;
|
|
43
|
+
packages: (PackageRef & {
|
|
44
|
+
files: number;
|
|
45
|
+
})[];
|
|
46
|
+
unresolved: string[];
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Collects the packages the covered code imports and asks OSV about each name and version. Only `name` and `version`
|
|
50
|
+
* go over the network (and the advisory ids it answers with); no source code, path or project name does.
|
|
51
|
+
*/
|
|
52
|
+
export declare function checkDeps(options: DepsOptions): Promise<DepsReport>;
|
|
53
|
+
/** The report as text for a terminal. */
|
|
54
|
+
export declare function renderDeps(report: DepsReport): string;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// `tslaws security deps`: the npm packages the covered code imports, checked against OSV.
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { coverFiles } from "../../coverage.js";
|
|
5
|
+
import { noCache, openCache } from "./cache.js";
|
|
6
|
+
import { defaultSecurityConfig } from "./config.js";
|
|
7
|
+
import { collectImports } from "./imports.js";
|
|
8
|
+
import { installedVersion, readLockfile } from "./lockfiles.js";
|
|
9
|
+
import { fetchVuln, queryBatch, toAdvisory } from "./osv.js";
|
|
10
|
+
import { severityRank } from "./severity.js";
|
|
11
|
+
const semverLike = /^\d+\.\d+\.\d+/;
|
|
12
|
+
/** Resolves the imported packages to name and version through the lockfile, falling back to node_modules. */
|
|
13
|
+
export function resolvePackages(cwd, imported) {
|
|
14
|
+
const lock = readLockfile(cwd);
|
|
15
|
+
let own;
|
|
16
|
+
try {
|
|
17
|
+
own = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8')).name;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
// No package.json.
|
|
21
|
+
}
|
|
22
|
+
const packages = [];
|
|
23
|
+
const unresolved = [];
|
|
24
|
+
for (const [name, files] of imported) {
|
|
25
|
+
if (name === own)
|
|
26
|
+
continue;
|
|
27
|
+
const installed = installedVersion(cwd, name);
|
|
28
|
+
// A workspace package is private, so it is neither checked nor sent anywhere.
|
|
29
|
+
if (installed.link || lock?.links.has(name) === true)
|
|
30
|
+
continue;
|
|
31
|
+
let versions = lock?.versions.get(name) ?? [];
|
|
32
|
+
if (versions.length === 0 && installed.version !== undefined) {
|
|
33
|
+
versions = [installed.version];
|
|
34
|
+
}
|
|
35
|
+
versions = versions.filter((v) => semverLike.test(v));
|
|
36
|
+
if (versions.length === 0)
|
|
37
|
+
unresolved.push(name);
|
|
38
|
+
for (const version of versions)
|
|
39
|
+
packages.push({ name, version, files });
|
|
40
|
+
}
|
|
41
|
+
return { source: lock?.source ?? 'node_modules', packages, unresolved };
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Collects the packages the covered code imports and asks OSV about each name and version. Only `name` and `version`
|
|
45
|
+
* go over the network (and the advisory ids it answers with); no source code, path or project name does.
|
|
46
|
+
*/
|
|
47
|
+
export async function checkDeps(options) {
|
|
48
|
+
const config = options.config ?? defaultSecurityConfig;
|
|
49
|
+
const failOn = options.failOn ?? config.failOn;
|
|
50
|
+
const offline = options.offline ?? config.offline;
|
|
51
|
+
const now = (options.now ?? Date.now)();
|
|
52
|
+
const cache = options.noCache === true || !config.cache ? noCache : openCache();
|
|
53
|
+
const fetch = options.fetch ?? globalThis.fetch;
|
|
54
|
+
const freshness = { now, ttlMs: config.cacheTtlHours * 3600_000, stale: offline };
|
|
55
|
+
const skip = options.skip ?? [];
|
|
56
|
+
const files = coverFiles(options.cwd, options.cover ?? ['**']).filter((file) => !skip.some((dir) => file === dir || file.startsWith(`${dir}/`)));
|
|
57
|
+
const { source, packages, unresolved } = resolvePackages(options.cwd, collectImports(options.cwd, files));
|
|
58
|
+
const ids = new Map();
|
|
59
|
+
const missing = [];
|
|
60
|
+
for (const p of packages) {
|
|
61
|
+
const known = cache.ids(`${p.name}@${p.version}`, freshness);
|
|
62
|
+
if (known === undefined)
|
|
63
|
+
missing.push(p);
|
|
64
|
+
else
|
|
65
|
+
ids.set(`${p.name}@${p.version}`, known);
|
|
66
|
+
}
|
|
67
|
+
const unchecked = [];
|
|
68
|
+
if (missing.length > 0 && offline)
|
|
69
|
+
unchecked.push(...missing.map((p) => `${p.name}@${p.version}`));
|
|
70
|
+
else if (missing.length > 0) {
|
|
71
|
+
const answers = await queryBatch(fetch, missing);
|
|
72
|
+
missing.forEach((p, i) => {
|
|
73
|
+
ids.set(`${p.name}@${p.version}`, answers[i]);
|
|
74
|
+
cache.setIds(`${p.name}@${p.version}`, answers[i], now);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const findings = [];
|
|
78
|
+
const vulns = new Map();
|
|
79
|
+
for (const p of packages) {
|
|
80
|
+
for (const id of ids.get(`${p.name}@${p.version}`) ?? []) {
|
|
81
|
+
if (!vulns.has(id)) {
|
|
82
|
+
let vuln = cache.advisory(id, freshness);
|
|
83
|
+
if (vuln === undefined && !offline) {
|
|
84
|
+
vuln = await fetchVuln(fetch, id);
|
|
85
|
+
cache.setAdvisory(id, vuln, now);
|
|
86
|
+
}
|
|
87
|
+
vulns.set(id, vuln);
|
|
88
|
+
}
|
|
89
|
+
const vuln = vulns.get(id);
|
|
90
|
+
if (vuln === undefined) {
|
|
91
|
+
unchecked.push(`${p.name}@${p.version} (${id})`);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const advisory = toAdvisory(vuln, p);
|
|
95
|
+
const ignored = config.ignore.some((entry) => entry === advisory.id || advisory.cve.includes(entry) || advisory.ghsa.includes(entry));
|
|
96
|
+
findings.push({ ...advisory, name: p.name, version: p.version, ignored });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (!offline)
|
|
100
|
+
cache.save();
|
|
101
|
+
findings.sort((a, b) => severityRank(b.severity) - severityRank(a.severity) || a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
|
|
102
|
+
return {
|
|
103
|
+
failOn,
|
|
104
|
+
offline,
|
|
105
|
+
source,
|
|
106
|
+
packages,
|
|
107
|
+
findings,
|
|
108
|
+
unresolved,
|
|
109
|
+
unchecked,
|
|
110
|
+
failed: findings.some((f) => !f.ignored && severityRank(f.severity) >= severityRank(failOn)),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/** The report as text for a terminal. */
|
|
114
|
+
export function renderDeps(report) {
|
|
115
|
+
const lines = [];
|
|
116
|
+
const names = new Set(report.packages.map((p) => p.name));
|
|
117
|
+
lines.push(`security deps: ${names.size} package${names.size === 1 ? '' : 's'} (${report.packages.length} version${report.packages.length === 1 ? '' : 's'}) imported by covered code, from ${report.source}${report.offline ? ', offline (cache only)' : ''}`);
|
|
118
|
+
for (const f of report.findings) {
|
|
119
|
+
const ids = [...new Set([f.id, ...f.cve, ...f.ghsa])];
|
|
120
|
+
const fixed = f.fixed.length > 0 ? `fixed in ${f.fixed.join(', ')}` : 'no fixed version listed';
|
|
121
|
+
const ranked = f.severity;
|
|
122
|
+
lines.push(`${f.ignored ? 'ignored ' : severityRank(ranked) >= severityRank(report.failOn) ? 'FAIL ' : 'warn '}${ranked.padEnd(8)} ${f.name}@${f.version} ${ids.join(' ')} ${fixed}`);
|
|
123
|
+
if (f.summary !== '')
|
|
124
|
+
lines.push(` ${f.summary}`);
|
|
125
|
+
}
|
|
126
|
+
if (report.unresolved.length > 0)
|
|
127
|
+
lines.push(`not checked, no version found: ${report.unresolved.join(', ')} (a path alias, or not installed)`);
|
|
128
|
+
if (report.unchecked.length > 0)
|
|
129
|
+
lines.push(`not checked, not in the cache (offline): ${report.unchecked.join(', ')}`);
|
|
130
|
+
const failing = report.findings.filter((f) => !f.ignored && severityRank(f.severity) >= severityRank(report.failOn));
|
|
131
|
+
lines.push(report.failed
|
|
132
|
+
? `${failing.length} advisor${failing.length === 1 ? 'y' : 'ies'} at or above ${report.failOn}: failed`
|
|
133
|
+
: `${report.findings.length} advisor${report.findings.length === 1 ? 'y' : 'ies'}, none at or above ${report.failOn}: passed`);
|
|
134
|
+
return `${lines.join('\n')}\n`;
|
|
135
|
+
}
|