@lintsure/core 0.1.3 → 0.3.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/dist/src/assessment.js +17 -5
- package/dist/src/guidance.js +1 -1
- package/dist/src/index.d.ts +6 -2
- package/dist/src/index.js +65 -14
- package/dist/src/knowledge/index.js +2 -1
- package/dist/src/knowledge/owasp-top10.d.ts +2 -0
- package/dist/src/knowledge/owasp-top10.js +93 -0
- package/dist/src/record.d.ts +71 -0
- package/dist/src/record.js +80 -0
- package/dist/src/review.d.ts +31 -0
- package/dist/src/review.js +71 -0
- package/dist/src/rules/index.js +34 -4
- package/dist/src/rules/owasp.d.ts +4 -0
- package/dist/src/rules/owasp.js +181 -0
- package/dist/src/sarif.d.ts +53 -0
- package/dist/src/sarif.js +27 -0
- package/dist/src/types.d.ts +33 -2
- package/package.json +1 -1
package/dist/src/assessment.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { DISCLAIMER, NOT_A_VERDICT, nextSteps } from "./index.js";
|
|
5
5
|
import { knowledge } from "./knowledge/index.js";
|
|
6
6
|
const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
7
|
-
const NAME = { "eu-ai-act": "EU AI Act", gdpr: "GDPR", soc2: "SOC 2", "iso-27001": "ISO/IEC 27001" };
|
|
7
|
+
const NAME = { "eu-ai-act": "EU AI Act", gdpr: "GDPR", soc2: "SOC 2", "iso-27001": "ISO/IEC 27001", "owasp-top10": "OWASP Top 10:2025" };
|
|
8
8
|
const STATUS = { gap: "Gap", partial: "Partial", met: "Met", outside: "Outside code" };
|
|
9
9
|
const SEV = ["high", "medium", "low"];
|
|
10
10
|
const SKIPPED = "node_modules, .git, dist, build, out, .output, .next, .nuxt, .svelte-kit, .astro, .vercel, .netlify, .wrangler, .turbo, .cache, venv, .venv, __pycache__, coverage";
|
|
@@ -14,8 +14,8 @@ function page(title, body, n, total, project) {
|
|
|
14
14
|
}
|
|
15
15
|
function findingCard(f, i) {
|
|
16
16
|
return `<article class="finding ${f.status}">
|
|
17
|
-
<p class="meta"><b class="st">${STATUS[f.status]}</b> · ${f.severity}
|
|
18
|
-
<h3>${
|
|
17
|
+
<p class="meta"><b class="st">${f.id} · ${f.status === "gap" ? "Finding" : "Observation"} (${STATUS[f.status]})</b> · risk level ${f.severity} · <code>${esc(f.ruleId)}</code></p>
|
|
18
|
+
<h3>${esc(f.title)}</h3>
|
|
19
19
|
<p class="where"><code>${esc(f.file)}:${f.line}</code></p>
|
|
20
20
|
<dl>
|
|
21
21
|
<dt>Rules it may affect</dt><dd>${f.controls.map((c) => `${NAME[c.framework]} ${esc(c.id)} (${esc(c.title)})`).join("<br>")}</dd>
|
|
@@ -30,14 +30,26 @@ export function toAssessmentHtml(r, opts) {
|
|
|
30
30
|
const n = (s) => r.findings.filter((f) => f.status === s).length;
|
|
31
31
|
const fws = r.frameworks;
|
|
32
32
|
const sorted = [...r.findings].sort((a, b) => SEV.indexOf(a.severity) - SEV.indexOf(b.severity));
|
|
33
|
+
const rec = r.record;
|
|
34
|
+
const RESULT = { finding: "Finding", observation: "Observation", "no issue found": "No issue found" };
|
|
35
|
+
const recordBody = rec ? `<p>A dated record of what this run checked and what it saw. It is a readiness record of an automated code check, not an audit.</p>
|
|
36
|
+
<table class="counts"><tr><th>Check points</th><th>Findings</th><th>Observations</th><th>Accepted</th><th>Fixed since baseline</th></tr>
|
|
37
|
+
<tr><td>${rec.counts.checkPoints}</td><td>${rec.counts.findings}</td><td>${rec.counts.observations}</td><td>${rec.counts.accepted}</td><td>${rec.counts.fixedSinceBaseline}</td></tr></table>
|
|
38
|
+
<p>Risk levels of open items: ${rec.counts.byRisk.high} high, ${rec.counts.byRisk.medium} medium, ${rec.counts.byRisk.low} low. A check point is one rule applied to one file (${rec.counts.rulesRun} rules ran).</p>
|
|
39
|
+
<h3>What applies, and why</h3><ul>${rec.applies.map((a) => `<li><b>${NAME[a.framework]}</b>: ${esc(a.why)}</li>`).join("")}</ul>
|
|
40
|
+
<h3>Results by control</h3><p class="small">Finding: a Gap the code itself shows. Observation: a Partial that depends on context a person must confirm. No issue found: the rules found nothing in the files they read, which does not mean the control is met.</p>
|
|
41
|
+
<table><tr><th>Framework</th><th>Control</th><th>Rules</th><th>Check points</th><th>Result</th><th>Items</th></tr>
|
|
42
|
+
${rec.byControl.map((b) => `<tr><td>${NAME[b.framework]}</td><td><code>${esc(b.control)}</code> ${esc(b.title)}</td><td>${b.rules.map((x) => `<code>${esc(x)}</code>`).join(" ")}</td><td>${b.checkPoints}</td><td>${RESULT[b.result]}</td><td>${b.findingIds.join(", ") || "-"}</td></tr>`).join("")}</table>` : "";
|
|
33
43
|
const cover = `<section class="page cover">
|
|
34
44
|
<p class="brand">Lintsure</p>
|
|
35
45
|
<h1>Readiness assessment</h1>
|
|
36
46
|
<p class="sub">${esc(project)}</p>
|
|
37
47
|
<table class="facts">
|
|
38
48
|
<tr><th>Date produced</th><td>${esc(opts.date)}</td></tr>
|
|
49
|
+
${rec ? `<tr><th>Record</th><td>${esc(rec.id)}, checked ${esc(rec.createdAt.replace("T", " ").slice(0, 19))} UTC</td></tr>` : ""}
|
|
50
|
+
${rec?.scope.commit ? `<tr><th>Code checked</th><td>${rec.scope.branch ? `branch <code>${esc(rec.scope.branch)}</code>, ` : ""}commit <code>${esc(rec.scope.commit)}</code></td></tr>` : ""}
|
|
39
51
|
<tr><th>Frameworks checked</th><td>${fws.map((f) => NAME[f]).join(", ") || "None"}</td></tr>
|
|
40
|
-
<tr><th>Files checked</th><td>${r.filesChecked}</td></tr>
|
|
52
|
+
<tr><th>Files checked</th><td>${r.filesChecked}${rec ? `, ${rec.counts.checkPoints} check points` : ""}</td></tr>
|
|
41
53
|
<tr><th>Rules version</th><td>${esc(r.rulesVersion)}</td></tr>
|
|
42
54
|
<tr><th>Status of this report</th><td><b>Draft.</b> Not complete until a qualified person reviews it and signs the review page.</td></tr>
|
|
43
55
|
</table>
|
|
@@ -84,7 +96,7 @@ ${r.outside.map((o) => `<tr><td>${NAME[o.framework]} <code>${esc(o.control)}</co
|
|
|
84
96
|
<tr><th>Overall notes</th><td class="tall"></td></tr><tr><th>Signature</th><td class="tall"></td></tr></table>
|
|
85
97
|
<p class="small">By signing, the reviewer confirms they reviewed this report. Signing does not turn it into an audit or certification.</p>`;
|
|
86
98
|
const pages = [
|
|
87
|
-
["Summary", summary], ["Scope and method", method], ["Possible issues and fixes", findingsBody],
|
|
99
|
+
["Summary", summary], ...(recordBody ? [["Readiness check record", recordBody]] : []), ["Scope and method", method], ["Possible issues and fixes", findingsBody],
|
|
88
100
|
["Framework by framework", byFramework || "<p>No frameworks were checked.</p>"], ["Work outside code", outside],
|
|
89
101
|
["What to do next", next], ["Human review and sign-off", signoff], ["Disclaimer", `<p>${esc(DISCLAIMER)}</p><p>${esc(NOT_A_VERDICT)}</p><p>Lintsure does not decide whether a framework applies to you or whether you meet it. A person makes the final call. Full disclaimer: https://lintsure.com/disclaimer</p>`],
|
|
90
102
|
];
|
package/dist/src/guidance.js
CHANGED
|
@@ -5,7 +5,7 @@ export const APPROVAL_RULES = `Before you do anything (edit, create or delete a
|
|
|
5
5
|
3. Where, exactly: the file and line, or the document and section.
|
|
6
6
|
4. The benefit to the user if they approve it.
|
|
7
7
|
Then ask the user to approve that one proposal and wait. Only a clear yes is approval. Silence, "maybe" or a question is not. Do only what was approved, then show what changed. One proposal at a time.`;
|
|
8
|
-
const NAMES = { "eu-ai-act": "EU AI Act", gdpr: "GDPR", soc2: "SOC 2", "iso-27001": "ISO 27001" };
|
|
8
|
+
const NAMES = { "eu-ai-act": "EU AI Act", gdpr: "GDPR", soc2: "SOC 2", "iso-27001": "ISO 27001", "owasp-top10": "OWASP Top 10" };
|
|
9
9
|
const refs = (cs) => cs.map((c) => `${NAMES[c.framework]} ${c.id}`).join(", ");
|
|
10
10
|
/** Lays a finding out as a proposal a person can approve or decline. */
|
|
11
11
|
export function proposalFor(f) {
|
package/dist/src/index.d.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { rules } from "./rules/index.js";
|
|
2
2
|
import type { FrameworkId, Report } from "./types.js";
|
|
3
|
+
export * from "./review.js";
|
|
4
|
+
export { toSarif } from "./sarif.js";
|
|
5
|
+
import { type RecordOptions } from "./record.js";
|
|
6
|
+
export * from "./record.js";
|
|
3
7
|
/** Heading above every proposed change, in every report. Tests check it is there for each finding. */
|
|
4
8
|
export declare const PROPOSAL_HEADING = "Proposed change. Nothing changes until you approve it.";
|
|
5
9
|
export * from "./types.js";
|
|
@@ -7,7 +11,7 @@ export { rules };
|
|
|
7
11
|
export * from "./guidance.js";
|
|
8
12
|
export { toAssessmentHtml } from "./assessment.js";
|
|
9
13
|
export * from "./knowledge/index.js";
|
|
10
|
-
export declare const RULES_VERSION = "0.
|
|
14
|
+
export declare const RULES_VERSION = "0.3.0";
|
|
11
15
|
/** Shown with every result, in every interface. Lintsure prepares; people decide. */
|
|
12
16
|
export declare const DISCLAIMER: string;
|
|
13
17
|
/** What a report must never be read as. Used in the report and by the MCP server. */
|
|
@@ -29,5 +33,5 @@ export declare function readConfig(root: string): Promise<{
|
|
|
29
33
|
export declare const SKIP_DIRS: string[];
|
|
30
34
|
/** Scout: list files to check, sorted so output order never depends on the file system. */
|
|
31
35
|
export declare function listFiles(root: string, ignore?: string[]): Promise<string[]>;
|
|
32
|
-
export declare function scan(root: string, frameworks?: FrameworkId[]): Promise<Report>;
|
|
36
|
+
export declare function scan(root: string, frameworks?: FrameworkId[], opts?: RecordOptions): Promise<Report>;
|
|
33
37
|
export declare function toMarkdown(r: Report): string;
|
package/dist/src/index.js
CHANGED
|
@@ -5,6 +5,11 @@ import { extname, join, relative, sep } from "node:path";
|
|
|
5
5
|
import { outsideFor } from "./knowledge/index.js";
|
|
6
6
|
import { rules } from "./rules/index.js";
|
|
7
7
|
import { proposalFor } from "./guidance.js";
|
|
8
|
+
import { applyReview, fingerprint, isOpen } from "./review.js";
|
|
9
|
+
export * from "./review.js";
|
|
10
|
+
export { toSarif } from "./sarif.js";
|
|
11
|
+
import { buildRecord } from "./record.js";
|
|
12
|
+
export * from "./record.js";
|
|
8
13
|
/** Heading above every proposed change, in every report. Tests check it is there for each finding. */
|
|
9
14
|
export const PROPOSAL_HEADING = "Proposed change. Nothing changes until you approve it.";
|
|
10
15
|
export * from "./types.js";
|
|
@@ -12,7 +17,7 @@ export { rules };
|
|
|
12
17
|
export * from "./guidance.js";
|
|
13
18
|
export { toAssessmentHtml } from "./assessment.js";
|
|
14
19
|
export * from "./knowledge/index.js";
|
|
15
|
-
export const RULES_VERSION = "0.
|
|
20
|
+
export const RULES_VERSION = "0.3.0";
|
|
16
21
|
/** Shown with every result, in every interface. Lintsure prepares; people decide. */
|
|
17
22
|
export const DISCLAIMER = "Lintsure is a readiness tool, not an audit, a certification or legal advice. " +
|
|
18
23
|
"Its rules reflect our reading of the publicly available text of each framework, and they check code only. " +
|
|
@@ -23,16 +28,19 @@ export const NOT_A_VERDICT = "These results do not mean you are compliant, certi
|
|
|
23
28
|
"Lintsure's rules found no problem in the files they read.";
|
|
24
29
|
/** Plain next steps, so a report always ends with what a person still needs to do. */
|
|
25
30
|
export function nextSteps(r) {
|
|
26
|
-
const
|
|
27
|
-
const
|
|
31
|
+
const open = r.findings.filter(isOpen);
|
|
32
|
+
const gaps = open.filter((f) => f.status === "gap").length;
|
|
33
|
+
const partial = open.filter((f) => f.status === "partial").length;
|
|
34
|
+
const expired = r.findings.filter((f) => f.accepted?.expired).length;
|
|
28
35
|
return [
|
|
29
36
|
gaps ? `Review the ${gaps} gap${gaps === 1 ? "" : "s"} and decide how to fix each one. Approve any change before it is made.` : "No gaps were found by the current rules. Keep checking as the code changes.",
|
|
30
37
|
partial ? `Check the ${partial} partial finding${partial === 1 ? "" : "s"}: each depends on context only you can confirm.` : "",
|
|
31
38
|
`Work through the ${r.outside.length} item${r.outside.length === 1 ? "" : "s"} that live outside code. Code checks alone are not enough for a full review.`,
|
|
39
|
+
expired ? `${expired} accepted finding${expired === 1 ? " is" : "s are"} past the review date. Look again, then renew the acceptance or fix it.` : "",
|
|
32
40
|
"Ask a qualified compliance professional to review the results before you rely on them.",
|
|
33
41
|
].filter(Boolean);
|
|
34
42
|
}
|
|
35
|
-
export const ALL_FRAMEWORKS = ["gdpr", "soc2", "iso-27001", "eu-ai-act"];
|
|
43
|
+
export const ALL_FRAMEWORKS = ["gdpr", "soc2", "iso-27001", "eu-ai-act", "owasp-top10"];
|
|
36
44
|
/** Reads the frameworks list from lintsure.config.yaml in the repo root, if there is one.
|
|
37
45
|
* Only the simple list form is supported:
|
|
38
46
|
* frameworks:
|
|
@@ -104,11 +112,13 @@ export async function listFiles(root, ignore = []) {
|
|
|
104
112
|
await walk(root);
|
|
105
113
|
return out.sort();
|
|
106
114
|
}
|
|
107
|
-
export async function scan(root, frameworks = ALL_FRAMEWORKS) {
|
|
115
|
+
export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
108
116
|
const active = rules.filter((r) => r.controls.some((c) => frameworks.includes(c.framework)));
|
|
109
117
|
const findings = [];
|
|
110
|
-
let filesChecked = 0;
|
|
111
|
-
|
|
118
|
+
let filesChecked = 0, checkPoints = 0;
|
|
119
|
+
const perRule = {};
|
|
120
|
+
const { ignore } = await readConfig(root);
|
|
121
|
+
for (const abs of await listFiles(root, ignore)) {
|
|
112
122
|
const ext = extname(abs) || (abs.endsWith(".env") ? ".env" : "");
|
|
113
123
|
const relevant = active.filter((r) => r.extensions.includes(ext));
|
|
114
124
|
if (!relevant.length)
|
|
@@ -121,17 +131,21 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS) {
|
|
|
121
131
|
if (lines.some((l) => l.length > MAX_LINE))
|
|
122
132
|
continue; // minified or generated
|
|
123
133
|
filesChecked++;
|
|
124
|
-
|
|
134
|
+
checkPoints += relevant.length; // one rule applied to one file is one check point
|
|
135
|
+
for (const r of relevant)
|
|
136
|
+
perRule[r.id] = (perRule[r.id] ?? 0) + 1;
|
|
137
|
+
const add = (r, line, status = r.status) => {
|
|
125
138
|
const controls = r.controls.filter((c) => frameworks.includes(c.framework));
|
|
126
139
|
findings.push({
|
|
127
|
-
ruleId: r.id, file, line, status
|
|
140
|
+
id: "", ruleId: r.id, file, line, status, severity: r.severity, title: r.title, controls, fix: r.fix, note: r.note,
|
|
128
141
|
proposal: proposalFor({ file, line, title: r.title, fix: r.fix, note: r.note, controls }),
|
|
142
|
+
fingerprint: fingerprint(r.id, file, lines[line - 1] ?? ""),
|
|
129
143
|
});
|
|
130
144
|
};
|
|
131
145
|
for (const r of relevant) {
|
|
132
146
|
if (r.test)
|
|
133
|
-
lines.forEach((text, i) => {
|
|
134
|
-
add(r, i + 1); });
|
|
147
|
+
lines.forEach((text, i) => { const hit = r.test(text); if (hit)
|
|
148
|
+
add(r, i + 1, hit === "partial" ? "partial" : r.status); });
|
|
135
149
|
if (r.fileTest)
|
|
136
150
|
for (const n of r.fileTest(lines))
|
|
137
151
|
add(r, n);
|
|
@@ -141,8 +155,10 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS) {
|
|
|
141
155
|
const seen = new Set();
|
|
142
156
|
const deduped = findings.filter((f) => { const k = `${f.ruleId}|${f.file}|${f.line}`; return seen.has(k) ? false : (seen.add(k), true); })
|
|
143
157
|
.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.ruleId.localeCompare(b.ruleId));
|
|
158
|
+
deduped.forEach((f, i) => { f.id = `F-${String(i + 1).padStart(3, "0")}`; });
|
|
144
159
|
const hit = new Set(deduped.map((f) => f.ruleId));
|
|
145
|
-
|
|
160
|
+
const now = opts.now ?? new Date();
|
|
161
|
+
const report = await applyReview({
|
|
146
162
|
rulesVersion: RULES_VERSION,
|
|
147
163
|
frameworks: [...frameworks].sort(),
|
|
148
164
|
findings: deduped,
|
|
@@ -151,21 +167,56 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS) {
|
|
|
151
167
|
outside: outsideFor(frameworks),
|
|
152
168
|
filesChecked,
|
|
153
169
|
disclaimer: DISCLAIMER,
|
|
154
|
-
};
|
|
170
|
+
}, root, now.toISOString().slice(0, 10));
|
|
171
|
+
report.record = await buildRecord(report, root, checkPoints, perRule, active.map((r) => r.id), active, ignore, { ...opts, now });
|
|
172
|
+
return report;
|
|
155
173
|
}
|
|
156
174
|
const LABEL = { gap: "Gap", partial: "Partial", met: "Met", outside: "Outside code" };
|
|
175
|
+
const acceptedLine = (a) => `> Accepted by ${a.by} on ${a.date}: ${a.reason}` + (a.expired ? ` (review date ${a.reviewBy} has passed: look at it again)` : a.reviewBy ? ` (review by ${a.reviewBy})` : "");
|
|
157
176
|
const ctl = (c) => c.map((x) => `${x.framework.toUpperCase()} ${x.id}`).join(" · ");
|
|
177
|
+
const RESULT = { finding: "Finding", observation: "Observation", "no issue found": "No issue found" };
|
|
178
|
+
/** The record block: identification, scope, what applies and why, counts, and results by control. */
|
|
179
|
+
function recordLines(r) {
|
|
180
|
+
const c = r.record;
|
|
181
|
+
if (!c)
|
|
182
|
+
return [];
|
|
183
|
+
const n = c.counts;
|
|
184
|
+
return [
|
|
185
|
+
"## Readiness check record", "",
|
|
186
|
+
"This is a readiness record of an automated code check, not an audit. It is a draft until a person reviews and signs it.", "",
|
|
187
|
+
"| | |", "|---|---|",
|
|
188
|
+
`| Record | ${c.id} |`, `| Date and time (UTC) | ${c.createdAt.replace("T", " ").slice(0, 19)} |`,
|
|
189
|
+
`| Tool | ${c.tool.name} ${c.tool.version}, run from ${c.source} |`,
|
|
190
|
+
`| Scope | \`${c.scope.folder}\`${c.scope.branch ? `, branch \`${c.scope.branch}\`` : ""}${c.scope.commit ? `, commit \`${c.scope.commit}\`` : ""} |`,
|
|
191
|
+
`| Files read | ${c.scope.filesRead}${c.scope.ignored.length ? ` (ignored by config: ${c.scope.ignored.map((x) => `\`${x}\``).join(", ")})` : ""} |`,
|
|
192
|
+
`| Check points | ${n.checkPoints} (${n.rulesRun} rules, each applied to every file it reads) |`,
|
|
193
|
+
`| Results | ${n.findings} finding${n.findings === 1 ? "" : "s"}, ${n.observations} observation${n.observations === 1 ? "" : "s"}, ${n.accepted} accepted, ${n.fixedSinceBaseline} fixed since baseline, ${n.outsideCode} outside-code items |`,
|
|
194
|
+
`| Risk levels | ${n.byRisk.high} high, ${n.byRisk.medium} medium, ${n.byRisk.low} low |`,
|
|
195
|
+
`| Reviewed by | ${c.review.reviewer ?? "Not yet reviewed"} |`, "",
|
|
196
|
+
"### What applies, and why", "",
|
|
197
|
+
...c.applies.map((a) => `- **${a.framework}**: ${a.why}`), "",
|
|
198
|
+
"### Results by control", "",
|
|
199
|
+
"A finding is a Gap the code itself shows. An observation is a Partial that depends on context a person must confirm. No issue found means the rules found nothing in the files they read, not that the control is met.", "",
|
|
200
|
+
"| Framework | Control | Rules | Check points | Result | Items |", "|---|---|---|---|---|---|",
|
|
201
|
+
...c.byControl.map((b) => `| ${b.framework} | ${b.control} ${b.title} | ${b.rules.join(", ")} | ${b.checkPoints} | ${RESULT[b.result]} | ${b.findingIds.join(", ") || "-"} |`), "",
|
|
202
|
+
];
|
|
203
|
+
}
|
|
158
204
|
export function toMarkdown(r) {
|
|
159
205
|
const lines = [
|
|
160
206
|
"# Lintsure report", "",
|
|
161
207
|
`Frameworks: ${r.frameworks.join(", ")} · Rules v${r.rulesVersion}`, "",
|
|
162
208
|
`> ${DISCLAIMER}`, "",
|
|
209
|
+
...recordLines(r),
|
|
163
210
|
`## Findings (${r.findings.length})`, "",
|
|
164
211
|
];
|
|
212
|
+
if (r.baseline)
|
|
213
|
+
lines.splice(lines.length - 2, 0, `Since the baseline of ${r.baseline.created}: ${r.baseline.newCount} new, ${r.baseline.fixed.length} fixed, ${r.baseline.unchangedCount} unchanged.`, "");
|
|
165
214
|
if (!r.findings.length)
|
|
166
215
|
lines.push("No issues found by the current rules.", "");
|
|
167
216
|
for (const f of r.findings)
|
|
168
|
-
lines.push(`### ${LABEL[f.status]} · \`${f.file}:${f.line}
|
|
217
|
+
lines.push(`### ${f.id} · ${f.status === "gap" ? "Finding" : "Observation"} (${LABEL[f.status]}) · \`${f.file}:${f.line}\`${f.change === "new" ? " · New since baseline" : ""}`, `**${f.title}** · Risk level: ${f.severity}`, "", ...(f.accepted ? [acceptedLine(f.accepted), ""] : []), `- Rules: ${ctl(f.controls)}`, `- Auditor note: ${f.note}`, "", `**${PROPOSAL_HEADING}**`, "", `- Where: \`${f.proposal.where}\``, `- What: ${f.proposal.what}`, `- Why: ${f.proposal.why}`, `- Benefit: ${f.proposal.benefit}`, "");
|
|
218
|
+
if (r.baseline?.fixed.length)
|
|
219
|
+
lines.push(`## Fixed since baseline (${r.baseline.fixed.length})`, "", ...r.baseline.fixed.map((x) => `- ${x.ruleId} in \`${x.file}\``), "");
|
|
169
220
|
lines.push(`## Met (${r.met.length})`, "", ...r.met.map((m) => `- ${m.title} · ${ctl(m.controls)}`), "");
|
|
170
221
|
lines.push(`## Outside code (${r.outside.length})`, "", "Code can't prove these. They still need to be done before a full review.", "", ...r.outside.map((o) => `- ${o.framework.toUpperCase()} ${o.control} · ${o.title}: ${o.evidence}`), "");
|
|
171
222
|
lines.push("## What to do next", "", ...nextSteps(r).map((s, i) => `${i + 1}. ${s}`), "");
|
|
@@ -2,8 +2,9 @@ import { euAiAct } from "./eu-ai-act.js";
|
|
|
2
2
|
import { gdpr } from "./gdpr.js";
|
|
3
3
|
import { iso27001 } from "./iso-27001.js";
|
|
4
4
|
import { soc2 } from "./soc2.js";
|
|
5
|
+
import { owaspTop10 } from "./owasp-top10.js";
|
|
5
6
|
export * from "./types.js";
|
|
6
|
-
export const knowledge = [euAiAct, gdpr, soc2, iso27001];
|
|
7
|
+
export const knowledge = [euAiAct, gdpr, soc2, iso27001, owaspTop10];
|
|
7
8
|
export const getKnowledge = (id) => knowledge.find((k) => k.id === id);
|
|
8
9
|
/** Classifier: suggest frameworks with a reason. The user confirms; nothing is auto-applied. */
|
|
9
10
|
export function classify(p) {
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Own-words summary of the OWASP Top 10:2025. The OWASP text is licensed CC BY-SA 4.0: we reference
|
|
2
|
+
// category ids, names and CWE numbers only, and describe each category in our own words.
|
|
3
|
+
// Not affiliated with or endorsed by the OWASP Foundation. OWASP is a trademark of the OWASP Foundation.
|
|
4
|
+
export const owaspTop10 = {
|
|
5
|
+
id: "owasp-top10",
|
|
6
|
+
name: "OWASP Top 10:2025",
|
|
7
|
+
kind: "standard",
|
|
8
|
+
summary: "The OWASP Top 10 is a widely used awareness list of the ten most serious kinds of web application security risk, built from real test data and a community survey. It isn't a law or a certification, but customers, security questionnaires and many other standards point to it. The 2025 edition adds software supply chain failures and the mishandling of errors.",
|
|
9
|
+
whoItAppliesTo: "Any team building a web application or API. It's voluntary, but often expected by business customers and referenced in security reviews.",
|
|
10
|
+
applies(p) {
|
|
11
|
+
if (p.b2bCustomers)
|
|
12
|
+
return "Business customers and security questionnaires often ask how you handle the OWASP Top 10.";
|
|
13
|
+
if (p.personalData)
|
|
14
|
+
return "You handle personal data in a web app, so the common web security risks apply.";
|
|
15
|
+
return null;
|
|
16
|
+
},
|
|
17
|
+
obligations: [
|
|
18
|
+
{ ref: "A01:2025", title: "Broken Access Control", inCode: "partly",
|
|
19
|
+
rules: ["path.user-input", "redirect.open", "ssrf.user-url", "csrf.disabled", "fs.world-writable", "cors.any-origin", "cookie.trusted-role"],
|
|
20
|
+
plain: "People must only reach the data and actions meant for them. This covers file paths, redirects, requests your server makes on a user's behalf (SSRF), forged requests from other sites, and permissions kept where users can change them.",
|
|
21
|
+
evidence: "A list of roles and what each may do, and tests showing one user can't read or change another user's data." },
|
|
22
|
+
{ ref: "A01:2025 (ownership checks)", title: "Every record is checked against the signed-in user", inCode: "no",
|
|
23
|
+
plain: "Whether each endpoint checks that the record belongs to the person asking (often called IDOR). A line-by-line code check can't tell; it needs design review and testing with two accounts.",
|
|
24
|
+
evidence: "Access control tests per role, or a penetration test report." },
|
|
25
|
+
{ ref: "A02:2025", title: "Security Misconfiguration", inCode: "partly",
|
|
26
|
+
rules: ["config.debug-on", "config.allowed-hosts-any", "config.default-secret-key", "xml.external-entities", "cors.any-origin", "session.cookie-insecure", "error.stack-to-client"],
|
|
27
|
+
plain: "Safe settings by default: debug off, real host names, strong secret keys, cookies marked secure, XML parsers that don't load outside files, and errors that don't reveal internals.",
|
|
28
|
+
evidence: "Production configuration and a hardening checklist." },
|
|
29
|
+
{ ref: "A02:2025 (deployed settings)", title: "Server, cloud and header configuration in production", inCode: "no",
|
|
30
|
+
plain: "What is actually running: server and cloud settings, open ports, default accounts, security headers on real responses. These need a scan of the deployed system.",
|
|
31
|
+
evidence: "Infrastructure configuration, a header scan and a cloud configuration review." },
|
|
32
|
+
{ ref: "A03:2025", title: "Software Supply Chain Failures", inCode: "partly",
|
|
33
|
+
rules: ["deps.unpinned-version", "deps.install-script", "ci.action-unpinned", "ci.prt-checkout-head"],
|
|
34
|
+
plain: "The code you didn't write: dependencies, build tools and CI. Versions should be pinned, install scripts shouldn't fetch code, CI actions should be pinned, and untrusted pull requests must not run with your secrets.",
|
|
35
|
+
evidence: "Lockfiles, CI workflow files and the dependency update process." },
|
|
36
|
+
{ ref: "A03:2025 (known vulnerabilities)", title: "Dependencies with known vulnerabilities", inCode: "no",
|
|
37
|
+
plain: "Whether any dependency version has a published vulnerability, and whether it's maintained. This needs vulnerability advisory data, which Lintsure doesn't download, so use a dependency scanner alongside it.",
|
|
38
|
+
evidence: "Dependency scanner results (for example npm audit, OSV-Scanner or Dependabot) and how alerts are handled." },
|
|
39
|
+
{ ref: "A04:2025", title: "Cryptographic Failures", inCode: "yes",
|
|
40
|
+
rules: ["crypto.weak-password-hash", "crypto.weak-random-token", "crypto.weak-cipher", "jwt.unverified", "transport.plain-http", "transport.tls-verify-off", "secret.in-source"],
|
|
41
|
+
plain: "Protect data with sound cryptography: HTTPS everywhere, certificate checks on, strong password hashing, modern ciphers, unpredictable tokens, signed tokens that are verified, and no keys in code.",
|
|
42
|
+
evidence: "Where data is encrypted in transit and at rest, and how keys are stored and rotated." },
|
|
43
|
+
{ ref: "A04:2025 (key management)", title: "Key management and encryption at rest", inCode: "no",
|
|
44
|
+
plain: "How encryption keys are created, stored, rotated and retired, and whether databases and backups are encrypted. These live in your infrastructure, not your code.",
|
|
45
|
+
evidence: "Key management procedure and storage encryption settings." },
|
|
46
|
+
{ ref: "A05:2025", title: "Injection", inCode: "yes",
|
|
47
|
+
rules: ["sql.string-built", "cmd.shell-built", "code.eval", "xss.raw-html", "template.user-string", "nosql.operator-input"],
|
|
48
|
+
plain: "Keep data and code apart, so input can't become part of a SQL query, a shell command, a template, HTML on the page or code that gets run.",
|
|
49
|
+
evidence: "Use of parameterised queries, output escaping, and code review practice." },
|
|
50
|
+
{ ref: "A06:2025", title: "Insecure Design", inCode: "partly",
|
|
51
|
+
rules: ["upload.unrestricted", "mass-assignment", "pii.in-url"],
|
|
52
|
+
plain: "Security planned in from the start: limits on uploads, only the fields users may change, sensitive data kept out of URLs. Most of this category is about design, not individual lines.",
|
|
53
|
+
evidence: "Design notes for sensitive features." },
|
|
54
|
+
{ ref: "A06:2025 (threat modelling)", title: "Threat modelling and abuse cases", inCode: "no",
|
|
55
|
+
plain: "Thinking through how a feature could be misused before building it: rate limits, business rule abuse, trust boundaries. Code checks can't show whether this happened.",
|
|
56
|
+
evidence: "Threat models or security design reviews for key features." },
|
|
57
|
+
{ ref: "A07:2025", title: "Authentication Failures", inCode: "partly",
|
|
58
|
+
rules: ["auth.hardcoded-password", "jwt.no-expiry", "jwt.unverified", "config.default-secret-key", "session.cookie-insecure", "secret.in-source", "transport.tls-verify-off"],
|
|
59
|
+
plain: "Logins and sessions that hold up: no passwords in code, strong secrets, tokens that expire and are verified, and session cookies protected from scripts and plain HTTP.",
|
|
60
|
+
evidence: "Login, session and token settings." },
|
|
61
|
+
{ ref: "A07:2025 (login protections)", title: "Brute-force protection, MFA and account recovery", inCode: "no",
|
|
62
|
+
plain: "Rate limiting and lockout on login, multi-factor authentication, and safe password reset flows. These need testing against the running app.",
|
|
63
|
+
evidence: "Login rate limit settings, MFA options, and password reset flow tests." },
|
|
64
|
+
{ ref: "A08:2025", title: "Software or Data Integrity Failures", inCode: "partly",
|
|
65
|
+
rules: ["deserialize.unsafe", "html.script-no-sri", "mass-assignment", "cookie.trusted-role", "ci.prt-checkout-head"],
|
|
66
|
+
plain: "Don't trust code or data you haven't checked: no unsafe deserialisation, integrity checks on third-party scripts, and no trust in values users can change.",
|
|
67
|
+
evidence: "How third-party scripts are loaded and how incoming data is parsed." },
|
|
68
|
+
{ ref: "A08:2025 (signed releases)", title: "Signed builds and updates", inCode: "no",
|
|
69
|
+
plain: "Whether builds, packages and updates are signed and verified from source to release.",
|
|
70
|
+
evidence: "Build signing and release verification steps." },
|
|
71
|
+
{ ref: "A09:2025", title: "Security Logging and Alerting Failures", inCode: "partly",
|
|
72
|
+
rules: ["log.secret", "log.injection", "pii.logged", "ai.call-not-logged"],
|
|
73
|
+
plain: "Logs that help instead of hurt: no secrets or personal data in them, no way to forge entries, and records of important events.",
|
|
74
|
+
evidence: "What is logged for logins, permission changes and admin actions." },
|
|
75
|
+
{ ref: "A09:2025 (alerting)", title: "Monitoring, alerting and incident response", inCode: "no",
|
|
76
|
+
plain: "Whether anyone is alerted when something suspicious happens, how long logs are kept, and how incidents are handled.",
|
|
77
|
+
evidence: "Alert rules, log retention settings and the incident response plan." },
|
|
78
|
+
{ ref: "A10:2025", title: "Mishandling of Exceptional Conditions", inCode: "partly",
|
|
79
|
+
rules: ["error.empty-catch", "error.stack-to-client", "config.debug-on"],
|
|
80
|
+
plain: "Errors handled on purpose: none silently ignored, none shown to users in detail, and failures that leave the system closed rather than open.",
|
|
81
|
+
evidence: "Error handling conventions and how failures are reported." },
|
|
82
|
+
{ ref: "A10:2025 (behaviour under failure)", title: "Safe behaviour when things fail", inCode: "no",
|
|
83
|
+
plain: "How the app behaves when a database, payment provider or other dependency is slow or down, and whether access checks fail closed. This needs testing under failure.",
|
|
84
|
+
evidence: "Failure and timeout tests." },
|
|
85
|
+
],
|
|
86
|
+
watchOut: [
|
|
87
|
+
"The Top 10 is an awareness list, not a complete standard. For detailed testing, OWASP publishes the Application Security Verification Standard (ASVS) and the Web Security Testing Guide (WSTG).",
|
|
88
|
+
"Many risks need a running app to test: access between users, login protections and deployed configuration. Code checks cover only part of each category.",
|
|
89
|
+
"Lintsure reads one line or one file at a time. Data passed through helpers in other files won't be followed, so some problems will be missed.",
|
|
90
|
+
"Saying an app is 'OWASP compliant' isn't meaningful. Describe what was checked and what wasn't.",
|
|
91
|
+
],
|
|
92
|
+
checkedOn: "2026-11-09",
|
|
93
|
+
};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { FrameworkId, Report, Severity } from "./types.js";
|
|
2
|
+
export type ControlResult = "finding" | "observation" | "no issue found";
|
|
3
|
+
export interface CheckRecord {
|
|
4
|
+
/** Stable id for this run, for example LS-20261108-1a2b3c. */
|
|
5
|
+
id: string;
|
|
6
|
+
/** When the check ran, ISO 8601 in UTC. */
|
|
7
|
+
createdAt: string;
|
|
8
|
+
kind: "readiness check record";
|
|
9
|
+
tool: {
|
|
10
|
+
name: "Lintsure";
|
|
11
|
+
version: string;
|
|
12
|
+
};
|
|
13
|
+
/** Which interface ran it: cli, mcp or ci. */
|
|
14
|
+
source: string;
|
|
15
|
+
scope: {
|
|
16
|
+
folder: string;
|
|
17
|
+
commit?: string;
|
|
18
|
+
branch?: string;
|
|
19
|
+
filesRead: number;
|
|
20
|
+
ignored: string[];
|
|
21
|
+
};
|
|
22
|
+
/** Each framework checked, and why it was included. */
|
|
23
|
+
applies: {
|
|
24
|
+
framework: FrameworkId;
|
|
25
|
+
why: string;
|
|
26
|
+
}[];
|
|
27
|
+
/** Every control the active rules cover, with its result. */
|
|
28
|
+
byControl: {
|
|
29
|
+
framework: FrameworkId;
|
|
30
|
+
control: string;
|
|
31
|
+
title: string;
|
|
32
|
+
rules: string[];
|
|
33
|
+
checkPoints: number;
|
|
34
|
+
result: ControlResult;
|
|
35
|
+
findingIds: string[];
|
|
36
|
+
}[];
|
|
37
|
+
counts: {
|
|
38
|
+
/** One rule applied to one file is one check point. */
|
|
39
|
+
checkPoints: number;
|
|
40
|
+
rulesRun: number;
|
|
41
|
+
/** Partial results: depend on context a person must confirm. */
|
|
42
|
+
observations: number;
|
|
43
|
+
/** Gap results: the code itself shows a problem. */
|
|
44
|
+
findings: number;
|
|
45
|
+
byRisk: Record<Severity, number>;
|
|
46
|
+
accepted: number;
|
|
47
|
+
fixedSinceBaseline: number;
|
|
48
|
+
outsideCode: number;
|
|
49
|
+
};
|
|
50
|
+
/** Filled in by a person. The record is a draft until then. */
|
|
51
|
+
review: {
|
|
52
|
+
reviewer: string | null;
|
|
53
|
+
date: string | null;
|
|
54
|
+
decision: string | null;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export interface RecordOptions {
|
|
58
|
+
/** Why each framework was checked. A string applies to all of them. */
|
|
59
|
+
why?: string | Partial<Record<FrameworkId, string>>;
|
|
60
|
+
source?: string;
|
|
61
|
+
/** Time of the run. Defaults to now; tests pass a fixed value. */
|
|
62
|
+
now?: Date;
|
|
63
|
+
}
|
|
64
|
+
export declare function buildRecord(r: Report, root: string, checkPoints: number, perRule: Record<string, number>, rulesRun: string[], ruleControls: {
|
|
65
|
+
id: string;
|
|
66
|
+
controls: {
|
|
67
|
+
framework: FrameworkId;
|
|
68
|
+
id: string;
|
|
69
|
+
title: string;
|
|
70
|
+
}[];
|
|
71
|
+
}[], ignored: string[], opts?: RecordOptions): Promise<CheckRecord>;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// The readiness check record: a dated, structured account of one run. What was checked, against which
|
|
2
|
+
// rules, what applies and why, how many check points, and what was found. It is a readiness record, not
|
|
3
|
+
// an audit: no auditor examined anything, and a person still has to review and sign it.
|
|
4
|
+
// It never contains source code.
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { readFile } from "node:fs/promises";
|
|
7
|
+
import { basename, join } from "node:path";
|
|
8
|
+
/** Reads the current commit and branch from .git without running git or using the network. */
|
|
9
|
+
async function gitInfo(root) {
|
|
10
|
+
try {
|
|
11
|
+
const head = (await readFile(join(root, ".git", "HEAD"), "utf8")).trim();
|
|
12
|
+
if (!head.startsWith("ref:"))
|
|
13
|
+
return { commit: head.slice(0, 12) };
|
|
14
|
+
const ref = head.slice(5).trim(), branch = ref.replace(/^refs\/heads\//, "");
|
|
15
|
+
try {
|
|
16
|
+
return { branch, commit: (await readFile(join(root, ".git", ref), "utf8")).trim().slice(0, 12) };
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
const packed = await readFile(join(root, ".git", "packed-refs"), "utf8").catch(() => "");
|
|
20
|
+
const line = packed.split(/\r?\n/).find((l) => l.endsWith(` ${ref}`));
|
|
21
|
+
return { branch, commit: line?.slice(0, 12) };
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export async function buildRecord(r, root, checkPoints, perRule, rulesRun, ruleControls, ignored, opts = {}) {
|
|
29
|
+
const now = opts.now ?? new Date();
|
|
30
|
+
const createdAt = now.toISOString();
|
|
31
|
+
const hash = createHash("sha256").update(createdAt + r.findings.map((f) => f.fingerprint).join(",")).digest("hex").slice(0, 6);
|
|
32
|
+
const why = (f) => typeof opts.why === "string" ? opts.why : opts.why?.[f] ?? "Checked by default: no framework list was given.";
|
|
33
|
+
const controls = new Map();
|
|
34
|
+
for (const rule of ruleControls)
|
|
35
|
+
for (const c of rule.controls) {
|
|
36
|
+
if (!r.frameworks.includes(c.framework))
|
|
37
|
+
continue;
|
|
38
|
+
const key = `${c.framework}|${c.id}`;
|
|
39
|
+
const row = controls.get(key) ?? { framework: c.framework, control: c.id, title: c.title, rules: [], checkPoints: 0, result: "no issue found", findingIds: [] };
|
|
40
|
+
row.rules.push(rule.id);
|
|
41
|
+
row.checkPoints += perRule[rule.id] ?? 0;
|
|
42
|
+
controls.set(key, row);
|
|
43
|
+
}
|
|
44
|
+
for (const f of r.findings) {
|
|
45
|
+
if (f.accepted && !f.accepted.expired)
|
|
46
|
+
continue;
|
|
47
|
+
for (const c of f.controls) {
|
|
48
|
+
const row = controls.get(`${c.framework}|${c.id}`);
|
|
49
|
+
if (!row)
|
|
50
|
+
continue;
|
|
51
|
+
row.findingIds.push(f.id);
|
|
52
|
+
if (f.status === "gap")
|
|
53
|
+
row.result = "finding";
|
|
54
|
+
else if (row.result !== "finding")
|
|
55
|
+
row.result = "observation";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const open = r.findings.filter((f) => !f.accepted || f.accepted.expired);
|
|
59
|
+
const byRisk = { high: 0, medium: 0, low: 0 };
|
|
60
|
+
for (const f of open)
|
|
61
|
+
byRisk[f.severity]++;
|
|
62
|
+
return {
|
|
63
|
+
id: `LS-${createdAt.slice(0, 10).replace(/-/g, "")}-${hash}`,
|
|
64
|
+
createdAt, kind: "readiness check record",
|
|
65
|
+
tool: { name: "Lintsure", version: r.rulesVersion },
|
|
66
|
+
source: opts.source ?? "cli",
|
|
67
|
+
scope: { folder: basename(root), ...(await gitInfo(root)), filesRead: r.filesChecked, ignored },
|
|
68
|
+
applies: r.frameworks.map((f) => ({ framework: f, why: why(f) })),
|
|
69
|
+
byControl: [...controls.values()].sort((a, b) => a.framework.localeCompare(b.framework) || a.control.localeCompare(b.control, undefined, { numeric: true })),
|
|
70
|
+
counts: {
|
|
71
|
+
checkPoints, rulesRun: rulesRun.length,
|
|
72
|
+
observations: open.filter((f) => f.status === "partial").length,
|
|
73
|
+
findings: open.filter((f) => f.status === "gap").length,
|
|
74
|
+
byRisk, accepted: r.findings.length - open.length,
|
|
75
|
+
fixedSinceBaseline: r.baseline?.fixed.length ?? 0,
|
|
76
|
+
outsideCode: r.outside.length,
|
|
77
|
+
},
|
|
78
|
+
review: { reviewer: null, date: null, decision: null },
|
|
79
|
+
};
|
|
80
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Finding, Report } from "./types.js";
|
|
2
|
+
export declare const BASELINE_FILE = ".lintsure/baseline.json";
|
|
3
|
+
export declare const ACCEPTED_FILE = ".lintsure/accepted.yaml";
|
|
4
|
+
/** A short one-way hash of the rule, file and the flagged line with spacing normalised. Moving the line keeps it; editing it changes it. */
|
|
5
|
+
export declare function fingerprint(ruleId: string, file: string, lineText: string): string;
|
|
6
|
+
export interface Baseline {
|
|
7
|
+
version: 1;
|
|
8
|
+
created: string;
|
|
9
|
+
findings: {
|
|
10
|
+
ruleId: string;
|
|
11
|
+
file: string;
|
|
12
|
+
fingerprint: string;
|
|
13
|
+
}[];
|
|
14
|
+
}
|
|
15
|
+
export interface AcceptedEntry {
|
|
16
|
+
rule: string;
|
|
17
|
+
where: string;
|
|
18
|
+
fingerprint: string;
|
|
19
|
+
reason: string;
|
|
20
|
+
accepted_by: string;
|
|
21
|
+
date: string;
|
|
22
|
+
review_by?: string;
|
|
23
|
+
}
|
|
24
|
+
/** The baseline to write for a report: every open finding, without code. Accepted findings are left out. */
|
|
25
|
+
export declare function toBaseline(r: Report, created: string): Baseline;
|
|
26
|
+
/** Reads the simple list form of accepted.yaml: "- key: value" items with indented "key: value" lines. */
|
|
27
|
+
export declare function parseAccepted(text: string): AcceptedEntry[];
|
|
28
|
+
/** Adds acceptances, new/unchanged marks and the list of fixed findings, from the repo's .lintsure/ files. */
|
|
29
|
+
export declare function applyReview(r: Report, root: string, today: string): Promise<Report>;
|
|
30
|
+
/** Findings still needing a decision: not accepted, or accepted but past the review date. */
|
|
31
|
+
export declare const isOpen: (f: Finding) => boolean;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Baseline and accepted findings, read from the repo's own .lintsure/ folder. Nothing is sent anywhere:
|
|
2
|
+
// these are files in the user's folder, and the user decides whether to commit them.
|
|
3
|
+
// Neither file contains code: only rule ids, file paths, fingerprints (one-way hashes) and people's reasons.
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
export const BASELINE_FILE = ".lintsure/baseline.json";
|
|
8
|
+
export const ACCEPTED_FILE = ".lintsure/accepted.yaml";
|
|
9
|
+
/** A short one-way hash of the rule, file and the flagged line with spacing normalised. Moving the line keeps it; editing it changes it. */
|
|
10
|
+
export function fingerprint(ruleId, file, lineText) {
|
|
11
|
+
return createHash("sha256").update(`${ruleId}\n${file}\n${lineText.trim().replace(/\s+/g, " ")}`).digest("hex").slice(0, 16);
|
|
12
|
+
}
|
|
13
|
+
/** The baseline to write for a report: every open finding, without code. Accepted findings are left out. */
|
|
14
|
+
export function toBaseline(r, created) {
|
|
15
|
+
return { version: 1, created, findings: r.findings.filter((f) => !f.accepted || f.accepted.expired).map(({ ruleId, file, fingerprint }) => ({ ruleId, file, fingerprint })) };
|
|
16
|
+
}
|
|
17
|
+
/** Reads the simple list form of accepted.yaml: "- key: value" items with indented "key: value" lines. */
|
|
18
|
+
export function parseAccepted(text) {
|
|
19
|
+
const out = [];
|
|
20
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
21
|
+
const line = raw.replace(/\s+#.*$/, "").replace(/^#.*$/, "");
|
|
22
|
+
const m = line.match(/^(\s*)(-\s+)?([a-z_]+)\s*:\s*(.*)$/);
|
|
23
|
+
if (!m)
|
|
24
|
+
continue;
|
|
25
|
+
if (m[2])
|
|
26
|
+
out.push({});
|
|
27
|
+
if (!out.length)
|
|
28
|
+
continue;
|
|
29
|
+
out[out.length - 1][m[3]] = m[4].trim().replace(/^["']|["']$/g, "");
|
|
30
|
+
}
|
|
31
|
+
return out.filter((e) => e.rule && e.fingerprint && e.reason && e.accepted_by);
|
|
32
|
+
}
|
|
33
|
+
async function readText(path) { try {
|
|
34
|
+
return await readFile(path, "utf8");
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return null;
|
|
38
|
+
} }
|
|
39
|
+
/** Adds acceptances, new/unchanged marks and the list of fixed findings, from the repo's .lintsure/ files. */
|
|
40
|
+
export async function applyReview(r, root, today) {
|
|
41
|
+
const acceptedText = await readText(join(root, ACCEPTED_FILE));
|
|
42
|
+
const accepted = acceptedText ? parseAccepted(acceptedText) : [];
|
|
43
|
+
for (const f of r.findings) {
|
|
44
|
+
const a = accepted.find((e) => e.rule === f.ruleId && e.fingerprint === f.fingerprint);
|
|
45
|
+
if (a)
|
|
46
|
+
f.accepted = { reason: a.reason, by: a.accepted_by, date: a.date, reviewBy: a.review_by, expired: !!a.review_by && a.review_by < today };
|
|
47
|
+
}
|
|
48
|
+
const baseText = await readText(join(root, BASELINE_FILE));
|
|
49
|
+
if (baseText) {
|
|
50
|
+
let base = null;
|
|
51
|
+
try {
|
|
52
|
+
base = JSON.parse(baseText);
|
|
53
|
+
}
|
|
54
|
+
catch { /* unreadable baseline: treat as none */ }
|
|
55
|
+
if (base?.findings) {
|
|
56
|
+
const known = new Set(base.findings.map((b) => b.fingerprint));
|
|
57
|
+
const now = new Set(r.findings.map((f) => f.fingerprint));
|
|
58
|
+
for (const f of r.findings)
|
|
59
|
+
f.change = known.has(f.fingerprint) ? "unchanged" : "new";
|
|
60
|
+
r.baseline = {
|
|
61
|
+
created: base.created,
|
|
62
|
+
newCount: r.findings.filter((f) => f.change === "new" && !(f.accepted && !f.accepted.expired)).length,
|
|
63
|
+
unchangedCount: r.findings.filter((f) => f.change === "unchanged").length,
|
|
64
|
+
fixed: base.findings.filter((b) => !now.has(b.fingerprint)),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return r;
|
|
69
|
+
}
|
|
70
|
+
/** Findings still needing a decision: not accepted, or accepted but past the review date. */
|
|
71
|
+
export const isOpen = (f) => !f.accepted || f.accepted.expired;
|
package/dist/src/rules/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { owaspForExisting, owaspRules } from "./owasp.js";
|
|
1
2
|
const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
|
|
2
3
|
// Beta: mapped by us, awaiting review by a qualified compliance professional.
|
|
3
4
|
const DRAFT = { mappedBy: "beta", reviewedAt: "pending" };
|
|
@@ -5,6 +6,23 @@ const LOG_CALL = /\b(console\.(log|info|warn|error|debug)|logger\.\w+|log\.(info
|
|
|
5
6
|
// Drops the text of string literals but keeps interpolations, so "email error" is ignored and `${user.email}` or f"{user.email}" is not.
|
|
6
7
|
const codeOnly = (l) => l.replace(/(["'`])(?:\\.|(?!\1).)*\1/g, (s) => (s.match(/\{[^}]*\}/g) ?? []).join(" "));
|
|
7
8
|
const PII = /\b(e-?mail|phone|ssn|social_?security|passport|date_?of_?birth|dob|password|passwd|credit_?card|card_?number|iban)\b/i;
|
|
9
|
+
// The arguments of the first log call on a line, up to its matching ")". Other code on the same line is ignored.
|
|
10
|
+
function logArgs(l) {
|
|
11
|
+
const m = LOG_CALL.exec(l);
|
|
12
|
+
if (!m)
|
|
13
|
+
return null;
|
|
14
|
+
let depth = 0, i = m.index + m[0].length - 1;
|
|
15
|
+
for (let j = i; j < l.length; j++) {
|
|
16
|
+
if (l[j] === "(")
|
|
17
|
+
depth++;
|
|
18
|
+
else if (l[j] === ")" && --depth === 0)
|
|
19
|
+
return l.slice(i + 1, j);
|
|
20
|
+
}
|
|
21
|
+
return l.slice(i + 1);
|
|
22
|
+
}
|
|
23
|
+
// Values that usually come from a request or the user. SQL built from them is a Gap; from other values, Partial.
|
|
24
|
+
const USER_INPUT = /\b(req|request|params|query|body|input|args|form|ctx|event|payload|searchParams|user_input)\b/;
|
|
25
|
+
const SQL_PARTS = /\$\{([^}]*)\}|\bf["'][^"']*\{([^}]*)\}|["']\s*\+\s*([\w.[\]]+)|\.format\(([^)]*)\)|%s["']\s*%\s*([^\n]+)/g;
|
|
8
26
|
export const rules = [
|
|
9
27
|
{
|
|
10
28
|
id: "pii.logged",
|
|
@@ -18,7 +36,7 @@ export const rules = [
|
|
|
18
36
|
fix: "Mask or remove the personal field before logging, for example mask(user.email).",
|
|
19
37
|
note: "Logs are copied to many places and kept for a long time. Personal data in them is hard to find and delete.",
|
|
20
38
|
extensions: CODE,
|
|
21
|
-
test: (l) =>
|
|
39
|
+
test: (l) => { const a = logArgs(l); return a !== null && PII.test(codeOnly(a)); },
|
|
22
40
|
...DRAFT,
|
|
23
41
|
},
|
|
24
42
|
{
|
|
@@ -121,10 +139,18 @@ export const rules = [
|
|
|
121
139
|
{ framework: "iso-27001", id: "A.8.28", title: "Secure coding" },
|
|
122
140
|
{ framework: "gdpr", id: "Art. 32", title: "Security of processing" },
|
|
123
141
|
],
|
|
124
|
-
fix: "Use parameterized queries or your ORM's query builder.",
|
|
125
|
-
note: "String-built SQL can let an attacker read or change your data (SQL injection).",
|
|
142
|
+
fix: "Use parameterized queries or your ORM's query builder. If the inserted value is fixed text from your own code, confirm it can never come from a user.",
|
|
143
|
+
note: "String-built SQL can let an attacker read or change your data (SQL injection). Marked Gap when the inserted value looks like user input, Partial when it may be fixed text from your code.",
|
|
126
144
|
extensions: CODE,
|
|
127
|
-
test: (l) =>
|
|
145
|
+
test: (l) => {
|
|
146
|
+
// SQL keywords are written in UPPER or lower case; "Select a plan from..." in a sentence is not SQL.
|
|
147
|
+
if (!/\b(SELECT|INSERT|UPDATE|DELETE|select|insert|update|delete)\b[^"'`]*\b(FROM|INTO|SET|WHERE|from|into|set|where)\b/.test(l))
|
|
148
|
+
return false;
|
|
149
|
+
const parts = [...l.matchAll(SQL_PARTS)].map((m) => m.slice(1).find(Boolean) ?? "");
|
|
150
|
+
if (!parts.length)
|
|
151
|
+
return false;
|
|
152
|
+
return parts.some((p) => USER_INPUT.test(p)) ? true : "partial";
|
|
153
|
+
},
|
|
128
154
|
...DRAFT,
|
|
129
155
|
},
|
|
130
156
|
{
|
|
@@ -238,3 +264,7 @@ rules.push({
|
|
|
238
264
|
test: (l) => /\b(detect|recogni[sz]e|analy[sz]e|infer|predict)\w*_?(emotion|sentiment_from_face|facial_expression)|\bemotion(s)?\s*[:=]\s*\w*\.(detect|analy)|\bDeepFace\.analyze\s*\(|\bdetect_faces?\b.*\bemotion|\b(face_recognition|FaceAttributes|DetectFaces)\b/i.test(l),
|
|
239
265
|
...DRAFT,
|
|
240
266
|
});
|
|
267
|
+
// OWASP Top 10:2025: map the rules above, then add the OWASP rules.
|
|
268
|
+
for (const r of rules)
|
|
269
|
+
r.controls.push(...(owaspForExisting[r.id] ?? []));
|
|
270
|
+
rules.push(...owaspRules);
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
|
|
2
|
+
const MARKUP = [...CODE, ".html", ".vue", ".svelte", ".astro", ".jinja", ".j2"];
|
|
3
|
+
const YAML = [".yml", ".yaml"];
|
|
4
|
+
const DRAFT = { mappedBy: "beta", reviewedAt: "pending" };
|
|
5
|
+
const A = (n, title) => ({ framework: "owasp-top10", id: `A${n}:2025`, title });
|
|
6
|
+
const A01 = A("01", "Broken Access Control"), A02 = A("02", "Security Misconfiguration"), A03 = A("03", "Software Supply Chain Failures"), A04 = A("04", "Cryptographic Failures"), A05 = A("05", "Injection"), A06 = A("06", "Insecure Design"), A07 = A("07", "Authentication Failures"), A08 = A("08", "Software or Data Integrity Failures"), A09 = A("09", "Security Logging and Alerting Failures"), A10 = A("10", "Mishandling of Exceptional Conditions");
|
|
7
|
+
// Request data on the same line. Without it a match is Partial: the value may be safe text from your own code.
|
|
8
|
+
const USER_INPUT = /\b(req\.(body|query|params|headers|cookies)|request\.(args|form|json|data|GET|POST|query_params|files)|ctx\.(query|request)|event\.(body|queryStringParameters)|searchParams\.get)\b/;
|
|
9
|
+
const byInput = (l) => (USER_INPUT.test(l) ? true : "partial");
|
|
10
|
+
const LOG_CALL = /\b(console\.(log|info|warn|error|debug)|logger\.\w+|log\.(info|warn|error|debug)|logging\.\w+)\s*\(/;
|
|
11
|
+
function logArgs(l) {
|
|
12
|
+
const m = LOG_CALL.exec(l);
|
|
13
|
+
if (!m)
|
|
14
|
+
return null;
|
|
15
|
+
let depth = 0;
|
|
16
|
+
const i = m.index + m[0].length - 1;
|
|
17
|
+
for (let j = i; j < l.length; j++) {
|
|
18
|
+
if (l[j] === "(")
|
|
19
|
+
depth++;
|
|
20
|
+
else if (l[j] === ")" && --depth === 0)
|
|
21
|
+
return l.slice(i + 1, j);
|
|
22
|
+
}
|
|
23
|
+
return l.slice(i + 1);
|
|
24
|
+
}
|
|
25
|
+
const stripStrings = (l) => l.replace(/(["'`])(?:\\.|(?!\1).)*\1/g, (s) => (s.match(/\{[^}]*\}/g) ?? []).join(" "));
|
|
26
|
+
const rule = (r) => ({ ...r, ...DRAFT });
|
|
27
|
+
export const owaspRules = [
|
|
28
|
+
// A01 Broken Access Control
|
|
29
|
+
rule({ id: "path.user-input", title: "File path built from request data", status: "gap", severity: "high", controls: [A01],
|
|
30
|
+
fix: "Don't pass request values into file paths. Map the request to a known file name, or use path.basename and check the result stays inside the allowed folder.",
|
|
31
|
+
note: "A path like ../../etc/passwd lets someone read or overwrite files outside the folder you meant (path traversal, CWE-22).", extensions: CODE,
|
|
32
|
+
test: (l) => /\b(fs\.(readFile|readFileSync|createReadStream|writeFile|writeFileSync|unlink|unlinkSync)|res\.(sendFile|download)|send_file|send_from_directory|open)\s*\(/.test(l) && USER_INPUT.test(l) }),
|
|
33
|
+
rule({ id: "redirect.open", title: "Redirect to a URL taken from the request", status: "gap", severity: "medium", controls: [A01],
|
|
34
|
+
fix: "Redirect only to paths on your own site, or check the target against a list of allowed hosts.",
|
|
35
|
+
note: "Attackers send people a link to your site that bounces them to a phishing page (open redirect, CWE-601).", extensions: CODE,
|
|
36
|
+
test: (l) => /\b(res\.redirect|redirect|HttpResponseRedirect|RedirectResponse)\s*\(\s*(req\.(query|body|params)|request\.(args|GET|query_params|form))/.test(l) }),
|
|
37
|
+
rule({ id: "ssrf.user-url", title: "Server fetches a URL taken from the request", status: "gap", severity: "high", controls: [A01],
|
|
38
|
+
fix: "Don't let users choose the full URL your server calls. Allow only known hosts, and block internal addresses such as 169.254.169.254 and localhost.",
|
|
39
|
+
note: "Your server can be made to call internal services or cloud metadata on an attacker's behalf (server-side request forgery, CWE-918).", extensions: CODE,
|
|
40
|
+
test: (l) => /\b(fetch|axios(\.(get|post|request))?|got|requests\.(get|post|request)|httpx\.(get|post)|urlopen)\s*\(\s*(req\.(body|query|params)|request\.(args|json|form|GET|data))/.test(l) }),
|
|
41
|
+
rule({ id: "csrf.disabled", title: "CSRF protection switched off", status: "partial", severity: "medium", controls: [A01],
|
|
42
|
+
fix: "Keep CSRF protection on for routes that use cookies. Turning it off is only safe for APIs that authenticate with a token header, not cookies.",
|
|
43
|
+
note: "Another site can make a logged-in user's browser submit forms to your app (cross-site request forgery, CWE-352).", extensions: CODE,
|
|
44
|
+
test: (l) => /@csrf_exempt\b|WTF_CSRF_ENABLED\s*=\s*False|\bcsrf\s*:\s*false\b|csrf_protect\s*=\s*False/.test(l) }),
|
|
45
|
+
rule({ id: "fs.world-writable", title: "File made readable and writable by everyone", status: "gap", severity: "medium", controls: [A01],
|
|
46
|
+
fix: "Use the narrowest permissions that work, for example 0o600 for secrets and 0o644 or 0o755 for public files.",
|
|
47
|
+
note: "Any user or process on the machine can change the file (incorrect permissions, CWE-732).", extensions: CODE,
|
|
48
|
+
test: (l) => /\bchmod(Sync)?\s*\([^)]*\b0o?777\b/.test(l) }),
|
|
49
|
+
// A02 Security Misconfiguration
|
|
50
|
+
rule({ id: "config.allowed-hosts-any", title: "Django accepts any host name", status: "gap", severity: "medium", controls: [A02],
|
|
51
|
+
fix: "List your real domains in ALLOWED_HOSTS, ideally from an environment variable per environment.",
|
|
52
|
+
note: "Any Host header is accepted, which enables host header attacks such as poisoned password reset links.", extensions: CODE,
|
|
53
|
+
test: (l) => /\bALLOWED_HOSTS\s*=\s*\[\s*["']\*["']/.test(l) }),
|
|
54
|
+
rule({ id: "config.default-secret-key", title: "Default or placeholder secret key", status: "gap", severity: "high", controls: [A02, A07],
|
|
55
|
+
fix: "Generate a long random secret per environment and load it from an environment variable or secret manager.",
|
|
56
|
+
note: "With a known secret key, attackers can forge sessions, cookies or signed tokens (CWE-1394).", extensions: [...CODE, ".env"],
|
|
57
|
+
test: (l) => /\b(SECRET_KEY|JWT_SECRET|SESSION_SECRET|secret)\s*[:=]\s*["']?(django-insecure-|changeme|change-me|secret\b|mysecret|keyboard cat|dev-secret|supersecret)/i.test(l) }),
|
|
58
|
+
rule({ id: "xml.external-entities", title: "XML parser may load external entities", status: "partial", severity: "high", controls: [A02],
|
|
59
|
+
fix: "Use defusedxml in Python, or turn off entity resolution and DTD loading in your parser.",
|
|
60
|
+
note: "A crafted XML file can read local files or call internal URLs (XML external entities, CWE-611).", extensions: CODE,
|
|
61
|
+
test: (l) => /resolve_entities\s*=\s*True|\bnoent\s*:\s*true|\bxml\.(etree\.ElementTree|dom\.minidom|sax)\b[^\n]*\b(parse|parseString|fromstring)\s*\(/.test(l) }),
|
|
62
|
+
// A03 Software Supply Chain Failures
|
|
63
|
+
rule({ id: "deps.unpinned-version", title: "Dependency with no version limit", status: "gap", severity: "medium", controls: [A03],
|
|
64
|
+
fix: "Pin a version or a range in package.json and commit the lockfile, so every install gets the code you tested.",
|
|
65
|
+
note: "\"*\" or \"latest\" installs whatever is published next, including a compromised release (CWE-1357).", extensions: [".json"],
|
|
66
|
+
test: (l) => /^\s*"(@?[\w.-]+\/)?[\w.-]+"\s*:\s*"(\*|latest|x)"\s*,?\s*$/.test(l) }),
|
|
67
|
+
rule({ id: "deps.install-script", title: "Install script downloads code", status: "partial", severity: "medium", controls: [A03],
|
|
68
|
+
fix: "Avoid downloading and running code in preinstall or postinstall. Vendor the file or document a manual step.",
|
|
69
|
+
note: "Code fetched at install time isn't pinned or reviewed and runs with the installer's permissions (CWE-829).", extensions: [".json"],
|
|
70
|
+
test: (l) => /"(pre|post)?install"\s*:\s*"[^"]*\b(curl|wget|Invoke-WebRequest)\b/.test(l) }),
|
|
71
|
+
rule({ id: "ci.action-unpinned", title: "Third-party GitHub Action not pinned to a commit", status: "partial", severity: "medium", controls: [A03],
|
|
72
|
+
fix: "Pin third-party actions to a full commit SHA, with the version as a comment, for example uses: owner/action@<40-character sha> # v2.",
|
|
73
|
+
note: "A tag like @v1 can be moved by the action's owner, or by whoever takes over their account (CWE-829).", extensions: YAML,
|
|
74
|
+
test: (l) => /^\s*-?\s*uses:\s*["']?(?!actions\/|github\/|\.\/|docker:\/\/)[\w.-]+\/[\w./-]+@(?![0-9a-f]{40}\b)[\w.-]+/.test(l) }),
|
|
75
|
+
rule({ id: "ci.prt-checkout-head", title: "pull_request_target workflow checks out untrusted code", status: "gap", severity: "high", controls: [A03, A08],
|
|
76
|
+
fix: "Use the pull_request trigger for workflows that build or run code from a pull request. If you need pull_request_target, never check out the pull request's code in it.",
|
|
77
|
+
note: "pull_request_target runs with your repository's secrets; checking out the contributor's code lets a pull request run with them (CWE-829).", extensions: YAML,
|
|
78
|
+
fileTest: (lines) => lines.some((l) => /\bpull_request_target\b/.test(l))
|
|
79
|
+
? lines.flatMap((l, i) => (/github\.event\.pull_request\.head\.(sha|ref)|refs\/pull\/.*\/(head|merge)/.test(l) ? [i + 1] : [])) : [] }),
|
|
80
|
+
// A04 Cryptographic Failures
|
|
81
|
+
rule({ id: "crypto.weak-random-token", title: "Predictable random numbers used for a secret", status: "gap", severity: "high", controls: [A04],
|
|
82
|
+
fix: "Use crypto.randomBytes or crypto.randomUUID in Node, or the secrets module in Python, for tokens, codes and IDs people shouldn't guess.",
|
|
83
|
+
note: "Math.random and Python's random module are predictable; tokens made with them can be guessed (CWE-338).", extensions: CODE,
|
|
84
|
+
test: (l) => /\bMath\.random\(\)|\brandom\.(random|randint|choice|choices|getrandbits)\(/.test(l) && /(token|secret|password|passwd|otp|nonce|session|api_?key|reset|invite|verification|code\b)/i.test(l) }),
|
|
85
|
+
rule({ id: "crypto.weak-cipher", title: "Weak or broken encryption", status: "gap", severity: "high", controls: [A04],
|
|
86
|
+
fix: "Use AES-256-GCM or ChaCha20-Poly1305 with a random nonce, through a maintained library. Replace createCipher with createCipheriv.",
|
|
87
|
+
note: "DES, RC4 and ECB mode can be broken or leak patterns in the data; createCipher derives a weak key and IV (CWE-327).", extensions: CODE,
|
|
88
|
+
test: (l) => /\bcreateCipher\s*\(|\bMODE_ECB\b|["'](des|des-ede3?|des-ede3-cbc|rc4|aes-\d{3}-ecb)["']|\b(DES3?|ARC4|Blowfish)\.new\s*\(/i.test(l) }),
|
|
89
|
+
rule({ id: "jwt.unverified", title: "JWT accepted without checking its signature", status: "gap", severity: "high", controls: [A04, A07],
|
|
90
|
+
fix: "Verify tokens with jwt.verify (Node) or jwt.decode with a key and an explicit algorithms list (Python). Never allow the 'none' algorithm.",
|
|
91
|
+
note: "Without signature checks anyone can write their own token and claim to be any user (CWE-347).", extensions: CODE,
|
|
92
|
+
test: (l) => {
|
|
93
|
+
if (/verify_signature["']?\s*:\s*False|\bverify\s*=\s*False|algorithms\s*[:=]\s*\[\s*["']none["']/i.test(l) && /jwt/i.test(l))
|
|
94
|
+
return true;
|
|
95
|
+
return /\bjwt\.decode\(\s*[\w.]+\s*\)/.test(l) ? "partial" : false; // Node jwt.decode reads a token without verifying it
|
|
96
|
+
} }),
|
|
97
|
+
// A05 Injection
|
|
98
|
+
rule({ id: "cmd.shell-built", title: "Shell command built from strings", status: "gap", severity: "high", controls: [A05],
|
|
99
|
+
fix: "Pass arguments as an array (execFile, spawn, subprocess.run([...])) instead of building a command string, and never use shell=True with outside input.",
|
|
100
|
+
note: "Characters like ; or $( ) in an inserted value run extra commands (OS command injection, CWE-78). Partial when the value may be fixed text from your own code.", extensions: CODE,
|
|
101
|
+
test: (l) => /\b(exec|execSync)\s*\(\s*(`[^`]*\$\{|["'][^"']*["']\s*\+)|\bsubprocess\.\w+\([^)]*shell\s*=\s*True|\bos\.(system|popen)\(\s*(f["']|["'][^"']*["']\s*[+%]|\w)/.test(l) ? byInput(l) : false }),
|
|
102
|
+
rule({ id: "code.eval", title: "Code run from a string", status: "gap", severity: "high", controls: [A05],
|
|
103
|
+
fix: "Avoid eval and new Function. Parse data with JSON.parse or a real parser, and map names to functions with a lookup table.",
|
|
104
|
+
note: "If any part of the string comes from outside, it runs as your code (code injection, CWE-94). Partial when the input isn't visible on the line.", extensions: CODE,
|
|
105
|
+
test: (l) => /(^|[^.\w])eval\s*\(|\bnew Function\s*\(/.test(l) ? byInput(l) : false }),
|
|
106
|
+
rule({ id: "xss.raw-html", title: "HTML inserted without escaping", status: "partial", severity: "high", controls: [A05],
|
|
107
|
+
fix: "Set text with textContent, let your framework escape values, or sanitise with DOMPurify before inserting HTML.",
|
|
108
|
+
note: "If the HTML contains user input, attackers can run scripts in your users' browsers (cross-site scripting, CWE-79). Partial because fixed HTML from your own code is safe.", extensions: MARKUP,
|
|
109
|
+
test: (l) => /\.(innerHTML|outerHTML)\s*[+]?=|\bdocument\.write(ln)?\(|\bdangerouslySetInnerHTML\b|\bv-html=|\{@html\b|\|\s*safe\b|\bmark_safe\(|\bMarkup\(/.test(l) }),
|
|
110
|
+
rule({ id: "template.user-string", title: "Template built from request data", status: "gap", severity: "high", controls: [A05],
|
|
111
|
+
fix: "Render a fixed template file and pass user values as variables, never as part of the template text.",
|
|
112
|
+
note: "Template syntax in user input runs on your server (server-side template injection, CWE-94).", extensions: CODE,
|
|
113
|
+
test: (l) => /\brender_template_string\(\s*(request\.|f["'])|\bTemplate\(\s*request\./.test(l) }),
|
|
114
|
+
rule({ id: "nosql.operator-input", title: "Database query object taken straight from the request", status: "partial", severity: "high", controls: [A05],
|
|
115
|
+
fix: "Build the query from the specific fields you expect, and convert them to the expected types, so operators like $ne or $gt can't be injected.",
|
|
116
|
+
note: "A body such as {\"password\": {\"$ne\": null}} can match any record (NoSQL injection, CWE-943).", extensions: CODE,
|
|
117
|
+
test: (l) => /\.(find|findOne|updateOne|updateMany|deleteOne|deleteMany|countDocuments)\(\s*req\.(body|query)\s*\)|\$where\b/.test(l) }),
|
|
118
|
+
// A06 Insecure Design
|
|
119
|
+
rule({ id: "upload.unrestricted", title: "File upload with no type or size limit", status: "partial", severity: "medium", controls: [A06],
|
|
120
|
+
fix: "Set limits.fileSize and a fileFilter that allows only the types you need, store uploads outside the web root, and give them new names.",
|
|
121
|
+
note: "Unlimited uploads let people fill your disk or upload files that later run or are served as pages (CWE-434).", extensions: CODE,
|
|
122
|
+
test: (l) => /\bmulter\(\s*(\{[^}]*\})?\s*\)/.test(l) && !/fileFilter|limits/.test(l) }),
|
|
123
|
+
rule({ id: "mass-assignment", title: "Whole request body saved to a model", status: "partial", severity: "medium", controls: [A06, A08],
|
|
124
|
+
fix: "Copy only the fields a user may change, for example with a schema (zod, pydantic) that lists them.",
|
|
125
|
+
note: "Users can set fields you didn't expect, such as role or isAdmin (mass assignment, CWE-915).", extensions: CODE,
|
|
126
|
+
test: (l) => /\.(create|update|insert|build|insertOne|updateOne)\(\s*req\.body\s*[),]|\bObject\.assign\(\s*\w+\s*,\s*req\.body\s*\)|\(\s*\*\*request\.(json|form|data)\b/.test(l) }),
|
|
127
|
+
// A07 Authentication Failures
|
|
128
|
+
rule({ id: "auth.hardcoded-password", title: "Password written in the code", status: "partial", severity: "high", controls: [A07],
|
|
129
|
+
fix: "Load passwords from environment variables or a secret manager, and rotate any that were committed.",
|
|
130
|
+
note: "Anyone with the code has the password, and it can't be changed without a release (CWE-259, CWE-798).", extensions: CODE,
|
|
131
|
+
test: (l) => /\b(password|passwd|pwd|db_pass)\s*[:=]\s*["'][^"'\s]{4,}["']/i.test(l) && !/(example|placeholder|changeme|your[_-]|xxx|\*\*\*|<|process\.env|os\.environ|getenv|type\s*[:=]|label|autocomplete)/i.test(l) }),
|
|
132
|
+
rule({ id: "jwt.no-expiry", title: "JWT signed without an expiry", status: "partial", severity: "medium", controls: [A07],
|
|
133
|
+
fix: "Add expiresIn (Node) or an exp claim (Python), and keep access tokens short-lived.",
|
|
134
|
+
note: "A stolen token without an expiry works forever (insufficient session expiration, CWE-613). Partial because the expiry may be set in a payload built elsewhere.", extensions: CODE,
|
|
135
|
+
test: (l) => /\bjwt\.(sign|encode)\(/.test(l) && !/expiresIn|\bexp\b/.test(l) }),
|
|
136
|
+
// A08 Software or Data Integrity Failures
|
|
137
|
+
rule({ id: "deserialize.unsafe", title: "Unsafe deserialisation", status: "gap", severity: "high", controls: [A08],
|
|
138
|
+
fix: "Use JSON for data from outside. In Python use yaml.safe_load, never pickle or marshal on untrusted data.",
|
|
139
|
+
note: "Deserialising untrusted data with these functions can run attacker code on your server (CWE-502).", extensions: CODE,
|
|
140
|
+
test: (l) => /\b(c?[Pp]ickle|dill)\.loads?\(|\byaml\.load\((?![^)]*Loader\s*=\s*(yaml\.)?C?SafeLoader)|\byaml\.unsafe_load\(|\bmarshal\.loads?\(|\bjsonpickle\.decode\(|\bshelve\.open\(|\bunserialize\(/.test(l) }),
|
|
141
|
+
rule({ id: "html.script-no-sri", title: "Third-party script loaded without an integrity check", status: "partial", severity: "medium", controls: [A08],
|
|
142
|
+
fix: "Add integrity and crossorigin attributes with the file's hash, or host the file yourself.",
|
|
143
|
+
note: "If the CDN or package is compromised, the changed script runs on your site (CWE-353, CWE-829).", extensions: MARKUP,
|
|
144
|
+
test: (l) => /<script\b[^>]*\bsrc=["']https?:\/\/(?!localhost|127\.0\.0\.1)[^"']+["'][^>]*>/i.test(l) && !/\bintegrity=/i.test(l) }),
|
|
145
|
+
rule({ id: "cookie.trusted-role", title: "Permissions read from a cookie", status: "partial", severity: "high", controls: [A08, A01],
|
|
146
|
+
fix: "Keep roles and permissions on the server, looked up from the authenticated user, not in a cookie the browser can change.",
|
|
147
|
+
note: "Users can edit their own cookies and give themselves admin rights (CWE-565).", extensions: CODE,
|
|
148
|
+
test: (l) => /\b(req\.cookies|request\.COOKIES|request\.cookies)(\.get\(\s*["']|\[\s*["']|\.)(role|isAdmin|is_admin|admin|permissions)\b/.test(l) }),
|
|
149
|
+
// A09 Security Logging and Alerting Failures
|
|
150
|
+
rule({ id: "log.secret", title: "Secret or token written to logs", status: "gap", severity: "high", controls: [A09],
|
|
151
|
+
fix: "Remove the value from the log call, or log only that it was present.",
|
|
152
|
+
note: "Logs are copied to many tools and people; a token in a log is a token anyone with log access can use (CWE-532).", extensions: CODE,
|
|
153
|
+
test: (l) => { const a = logArgs(l); return a !== null && /\b(token|secret|authorization|api_?key|apiKey|bearer|access_token|refresh_token|private_?key|client_secret)\b/i.test(stripStrings(a)); } }),
|
|
154
|
+
rule({ id: "log.injection", title: "Raw request data written to logs", status: "partial", severity: "low", controls: [A09],
|
|
155
|
+
fix: "Log specific, validated fields, and strip line breaks from user input before logging it.",
|
|
156
|
+
note: "Line breaks in user input can forge fake log entries and mislead an investigation (CWE-117).", extensions: CODE,
|
|
157
|
+
test: (l) => { const a = logArgs(l); return a !== null && /\b(req\.(body|query|params|headers)|request\.(args|form|json|data))\b(?!\.\w)/.test(a); } }),
|
|
158
|
+
// A10 Mishandling of Exceptional Conditions
|
|
159
|
+
rule({ id: "error.empty-catch", title: "Error caught and ignored", status: "gap", severity: "medium", controls: [A10],
|
|
160
|
+
fix: "Handle the error, log it, or let it propagate. If ignoring it is deliberate, say why in a comment and catch only the specific error.",
|
|
161
|
+
note: "Silent failures hide attacks and bugs, and can leave the app running in a broken or unsafe state (CWE-390).", extensions: CODE,
|
|
162
|
+
test: (l) => /\bcatch\s*(\(\s*\w*\s*\))?\s*\{\s*\}|^\s*except(\s+[\w.,() ]+)?\s*:\s*pass\b/.test(l) }),
|
|
163
|
+
rule({ id: "error.stack-to-client", title: "Error details sent to the user", status: "gap", severity: "medium", controls: [A10, A02],
|
|
164
|
+
fix: "Log the full error on the server and send users a short, generic message with a reference id.",
|
|
165
|
+
note: "Stack traces show file paths, library versions and sometimes data, which helps attackers (CWE-209).", extensions: CODE,
|
|
166
|
+
test: (l) => !LOG_CALL.test(l) && /\bres\.(status\(\d+\)\.)?(send|json|end)\(\s*(\{[^}]*)?\b(err|error|e)\.stack\b|\bres\.(status\(\d+\)\.)?send\(\s*(err|error)\s*\)|\btraceback\.format_exc\(\)/.test(l) }),
|
|
167
|
+
];
|
|
168
|
+
/** Existing rules that also relate to an OWASP Top 10:2025 category. Added to their controls at load time. */
|
|
169
|
+
export const owaspForExisting = {
|
|
170
|
+
"pii.logged": [A09],
|
|
171
|
+
"secret.in-source": [A04, A07],
|
|
172
|
+
"transport.plain-http": [A04],
|
|
173
|
+
"pii.in-url": [A06],
|
|
174
|
+
"crypto.weak-password-hash": [A04],
|
|
175
|
+
"transport.tls-verify-off": [A04, A07],
|
|
176
|
+
"sql.string-built": [A05],
|
|
177
|
+
"cors.any-origin": [A02, A01],
|
|
178
|
+
"session.cookie-insecure": [A02, A07],
|
|
179
|
+
"config.debug-on": [A02],
|
|
180
|
+
"ai.call-not-logged": [A09],
|
|
181
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Report } from "./types.js";
|
|
2
|
+
export declare function toSarif(r: Report, version: string): {
|
|
3
|
+
$schema: string;
|
|
4
|
+
version: string;
|
|
5
|
+
runs: {
|
|
6
|
+
tool: {
|
|
7
|
+
driver: {
|
|
8
|
+
name: string;
|
|
9
|
+
version: string;
|
|
10
|
+
informationUri: string;
|
|
11
|
+
rules: {
|
|
12
|
+
id: string;
|
|
13
|
+
name: string;
|
|
14
|
+
shortDescription: {
|
|
15
|
+
text: string;
|
|
16
|
+
};
|
|
17
|
+
help: {
|
|
18
|
+
text: string;
|
|
19
|
+
};
|
|
20
|
+
helpUri: string;
|
|
21
|
+
properties: {
|
|
22
|
+
tags: string[];
|
|
23
|
+
};
|
|
24
|
+
}[];
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
results: {
|
|
28
|
+
suppressions?: {
|
|
29
|
+
kind: string;
|
|
30
|
+
justification: string;
|
|
31
|
+
}[] | undefined;
|
|
32
|
+
baselineState?: "new" | "unchanged" | undefined;
|
|
33
|
+
ruleId: string;
|
|
34
|
+
level: string;
|
|
35
|
+
message: {
|
|
36
|
+
text: string;
|
|
37
|
+
};
|
|
38
|
+
locations: {
|
|
39
|
+
physicalLocation: {
|
|
40
|
+
artifactLocation: {
|
|
41
|
+
uri: string;
|
|
42
|
+
};
|
|
43
|
+
region: {
|
|
44
|
+
startLine: number;
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
}[];
|
|
48
|
+
partialFingerprints: {
|
|
49
|
+
"lintsure/v1": string;
|
|
50
|
+
};
|
|
51
|
+
}[];
|
|
52
|
+
}[];
|
|
53
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { rules } from "./rules/index.js";
|
|
2
|
+
export function toSarif(r, version) {
|
|
3
|
+
const used = [...new Set(r.findings.map((f) => f.ruleId))];
|
|
4
|
+
return {
|
|
5
|
+
$schema: "https://json.schemastore.org/sarif-2.1.0.json",
|
|
6
|
+
version: "2.1.0",
|
|
7
|
+
runs: [{
|
|
8
|
+
tool: { driver: {
|
|
9
|
+
name: "Lintsure", version, informationUri: "https://lintsure.com",
|
|
10
|
+
rules: used.map((id) => {
|
|
11
|
+
const rule = rules.find((x) => x.id === id);
|
|
12
|
+
return { id, name: id, shortDescription: { text: rule.title }, help: { text: `${rule.fix} ${rule.note}` },
|
|
13
|
+
helpUri: `https://lintsure.com/rules/${id.split(".").join("-")}`, properties: { tags: rule.controls.map((c) => `${c.framework} ${c.id}`) } };
|
|
14
|
+
}),
|
|
15
|
+
} },
|
|
16
|
+
results: r.findings.map((f) => ({
|
|
17
|
+
ruleId: f.ruleId,
|
|
18
|
+
level: f.status === "gap" ? "error" : "warning",
|
|
19
|
+
message: { text: `${f.title}. Proposed change (needs your approval): ${f.proposal.what} Why: ${f.proposal.why}` },
|
|
20
|
+
locations: [{ physicalLocation: { artifactLocation: { uri: f.file }, region: { startLine: f.line } } }],
|
|
21
|
+
partialFingerprints: { "lintsure/v1": f.fingerprint },
|
|
22
|
+
...(f.change ? { baselineState: f.change } : {}),
|
|
23
|
+
...(f.accepted && !f.accepted.expired ? { suppressions: [{ kind: "external", justification: `${f.accepted.reason} (accepted by ${f.accepted.by}, ${f.accepted.date})` }] } : {}),
|
|
24
|
+
})),
|
|
25
|
+
}],
|
|
26
|
+
};
|
|
27
|
+
}
|
package/dist/src/types.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export type Status = "met" | "partial" | "gap" | "outside";
|
|
2
2
|
export type Severity = "high" | "medium" | "low";
|
|
3
|
-
export type FrameworkId = "gdpr" | "soc2" | "iso-27001" | "eu-ai-act";
|
|
3
|
+
export type FrameworkId = "gdpr" | "soc2" | "iso-27001" | "eu-ai-act" | "owasp-top10";
|
|
4
4
|
export interface Control {
|
|
5
5
|
framework: FrameworkId;
|
|
6
6
|
id: string;
|
|
@@ -18,7 +18,7 @@ export interface Rule {
|
|
|
18
18
|
/** Files this rule reads, by extension. */
|
|
19
19
|
extensions: string[];
|
|
20
20
|
/** Line rule: true when the line breaks the rule. Must be pure: same line, same answer. */
|
|
21
|
-
test?(line: string): boolean;
|
|
21
|
+
test?(line: string): boolean | "partial";
|
|
22
22
|
/** File rule, for checks that need context (e.g. "an AI call with no logging in this file").
|
|
23
23
|
* Returns 1-based line numbers to flag. Must be pure. */
|
|
24
24
|
fileTest?(lines: string[]): number[];
|
|
@@ -39,6 +39,8 @@ export interface Proposal {
|
|
|
39
39
|
needsApproval: true;
|
|
40
40
|
}
|
|
41
41
|
export interface Finding {
|
|
42
|
+
/** Finding number within this run, for example F-003. */
|
|
43
|
+
id: string;
|
|
42
44
|
ruleId: string;
|
|
43
45
|
file: string;
|
|
44
46
|
line: number;
|
|
@@ -50,6 +52,31 @@ export interface Finding {
|
|
|
50
52
|
note: string;
|
|
51
53
|
/** The suggested change, laid out for a person to approve or decline. */
|
|
52
54
|
proposal: Proposal;
|
|
55
|
+
/** Stable id: rule, file and the flagged line's content (not its number). Contains no code. */
|
|
56
|
+
fingerprint: string;
|
|
57
|
+
/** Set when .lintsure/baseline.json exists: whether the finding is new since then. */
|
|
58
|
+
change?: "new" | "unchanged";
|
|
59
|
+
/** Set when a person accepted this finding in .lintsure/accepted.yaml. */
|
|
60
|
+
accepted?: Acceptance;
|
|
61
|
+
}
|
|
62
|
+
/** A person's decision to accept a finding, with their reason. Expired acceptances count as open again. */
|
|
63
|
+
export interface Acceptance {
|
|
64
|
+
reason: string;
|
|
65
|
+
by: string;
|
|
66
|
+
date: string;
|
|
67
|
+
reviewBy?: string;
|
|
68
|
+
expired: boolean;
|
|
69
|
+
}
|
|
70
|
+
/** What changed since the baseline: findings that were in the baseline and are now gone. */
|
|
71
|
+
export interface BaselineDiff {
|
|
72
|
+
created: string;
|
|
73
|
+
newCount: number;
|
|
74
|
+
unchangedCount: number;
|
|
75
|
+
fixed: {
|
|
76
|
+
ruleId: string;
|
|
77
|
+
file: string;
|
|
78
|
+
fingerprint: string;
|
|
79
|
+
}[];
|
|
53
80
|
}
|
|
54
81
|
export interface OutsideItem {
|
|
55
82
|
framework: FrameworkId;
|
|
@@ -73,4 +100,8 @@ export interface Report {
|
|
|
73
100
|
disclaimer: string;
|
|
74
101
|
/** Files the rules actually read (after skipping folders, large and binary files). */
|
|
75
102
|
filesChecked: number;
|
|
103
|
+
/** Present when the repo has a .lintsure/baseline.json. */
|
|
104
|
+
baseline?: BaselineDiff;
|
|
105
|
+
/** The dated record of this run: scope, what applies and why, check points, results by control, counts. */
|
|
106
|
+
record?: import("./record.js").CheckRecord;
|
|
76
107
|
}
|
package/package.json
CHANGED