rtl-analyzer 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +82 -2
- package/dist/bootstrap.js +27 -0
- package/dist/cli.js +76 -0
- package/dist/codemod.js +53 -0
- package/dist/coverage.js +36 -0
- package/dist/css.js +61 -0
- package/dist/dashboard-client.js +167 -0
- package/dist/dashboard-data.js +22 -0
- package/dist/dashboard-html.js +27 -0
- package/dist/discovery.js +71 -0
- package/dist/eligibility.js +19 -0
- package/dist/html.js +34 -0
- package/dist/model.js +9 -0
- package/dist/policy-audit.js +109 -0
- package/dist/policy-validation.js +137 -0
- package/dist/policy.js +32 -0
- package/dist/presentation-adapter.js +52 -0
- package/dist/preview-manifest.js +15 -0
- package/dist/report-publisher.js +110 -0
- package/dist/report.js +8 -0
- package/dist/review-session.js +153 -0
- package/dist/rules.js +215 -0
- package/dist/runtime-direction.js +334 -0
- package/dist/scan.js +59 -0
- package/dist/source-snippets.js +177 -0
- package/dist/standalone-cli.js +107 -0
- package/dist/structured-markdown.js +36 -0
- package/dist/tailwind.js +21 -0
- package/dist/typescript.js +191 -0
- package/package.json +30 -4
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { lstat, open } from 'node:fs/promises';
|
|
3
|
+
import { isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
|
|
4
|
+
export const SOURCE_SNIPPET_LIMITS = Object.freeze({ contextLines: 5, maxLines: 100, maxBytes: 16 * 1024, totalBytes: 2 * 1024 * 1024 });
|
|
5
|
+
const pathError = (path) => !path || isAbsolute(path) || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith('\\\\') || path.startsWith('//') || path.includes('\\') || /[\0\r\n]/.test(path) || path.split('/').some(part => part === '..');
|
|
6
|
+
const unavailable = (findingId, reason) => ({ findingId, available: false, reason });
|
|
7
|
+
async function validatePath(root, path) {
|
|
8
|
+
if (pathError(path))
|
|
9
|
+
return 'INVALID_PATH';
|
|
10
|
+
const rootAbsolute = resolve(root), portablePath = path.split('/').join(sep), normalized = normalize(portablePath), absolute = resolve(rootAbsolute, normalized), rel = relative(rootAbsolute, absolute);
|
|
11
|
+
if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel) || normalized !== portablePath)
|
|
12
|
+
return 'INVALID_PATH';
|
|
13
|
+
try {
|
|
14
|
+
const rootStat = await lstat(rootAbsolute);
|
|
15
|
+
if (rootStat.isSymbolicLink())
|
|
16
|
+
return 'SYMLINK';
|
|
17
|
+
const parts = path.split('/');
|
|
18
|
+
let current = rootAbsolute;
|
|
19
|
+
for (const part of parts) {
|
|
20
|
+
current = join(current, part);
|
|
21
|
+
const stat = await lstat(current);
|
|
22
|
+
if (stat.isSymbolicLink())
|
|
23
|
+
return 'SYMLINK';
|
|
24
|
+
}
|
|
25
|
+
const stat = await lstat(absolute);
|
|
26
|
+
if (!stat.isFile())
|
|
27
|
+
return 'NON_REGULAR_FILE';
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (error.code === 'ENOENT')
|
|
31
|
+
return 'MISSING_FILE';
|
|
32
|
+
return 'READ_FAILURE';
|
|
33
|
+
}
|
|
34
|
+
return { absolute };
|
|
35
|
+
}
|
|
36
|
+
async function readVerified(path, absolute) {
|
|
37
|
+
if (!constants.O_NOFOLLOW)
|
|
38
|
+
return 'UNSUPPORTED_NOFOLLOW';
|
|
39
|
+
let handle;
|
|
40
|
+
try {
|
|
41
|
+
handle = await open(absolute, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
42
|
+
const before = await handle.stat();
|
|
43
|
+
if (!before.isFile())
|
|
44
|
+
return 'NON_REGULAR_FILE';
|
|
45
|
+
const text = await handle.readFile({ encoding: 'utf8' });
|
|
46
|
+
const after = await handle.stat();
|
|
47
|
+
if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size)
|
|
48
|
+
return 'IDENTITY_CHANGED';
|
|
49
|
+
return { text, size: after.size };
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
const code = error.code;
|
|
53
|
+
if (code === 'ENOENT')
|
|
54
|
+
return 'MISSING_FILE';
|
|
55
|
+
if (code === 'ELOOP')
|
|
56
|
+
return 'SYMLINK';
|
|
57
|
+
return 'READ_FAILURE';
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
await handle?.close().catch(() => undefined);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function lineTable(text) {
|
|
64
|
+
const lines = [];
|
|
65
|
+
let start = 0;
|
|
66
|
+
for (let i = 0; i <= text.length;) {
|
|
67
|
+
const match = text.slice(i).match(/\r\n|\r|\n/);
|
|
68
|
+
if (!match) {
|
|
69
|
+
lines.push({ text: text.slice(start), start, end: text.length });
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
const end = i + match.index;
|
|
73
|
+
lines.push({ text: text.slice(start, end), start, end });
|
|
74
|
+
i = end + match[0].length;
|
|
75
|
+
start = i;
|
|
76
|
+
}
|
|
77
|
+
return lines.length ? lines : [{ text: '', start: 0, end: 0 }];
|
|
78
|
+
}
|
|
79
|
+
function lineAt(lines, offset) { const index = lines.findIndex(line => offset >= line.start && offset <= line.end); return index < 0 ? -1 : index; }
|
|
80
|
+
function scannerPoint(text, offset) {
|
|
81
|
+
const prefix = text.slice(0, offset), parts = prefix.split(/\r\n|\r|\n/);
|
|
82
|
+
return { offset, line: parts.length, column: parts.at(-1).length + 1 };
|
|
83
|
+
}
|
|
84
|
+
function samePoint(actual, expected) {
|
|
85
|
+
return actual.offset === expected.offset && actual.line === expected.line && actual.column === expected.column;
|
|
86
|
+
}
|
|
87
|
+
function makeWindow(path, finding, text, options) {
|
|
88
|
+
const lines = lineTable(text), start = finding.range.start.offset, end = finding.range.end.offset;
|
|
89
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end > text.length)
|
|
90
|
+
return 'INVALID_RANGE';
|
|
91
|
+
if (!samePoint(scannerPoint(text, start), finding.range.start) || !samePoint(scannerPoint(text, end), finding.range.end))
|
|
92
|
+
return 'POSITION_MISMATCH';
|
|
93
|
+
if (text.slice(start, end) !== finding.original)
|
|
94
|
+
return 'SOURCE_CHANGED';
|
|
95
|
+
const first = lineAt(lines, start), last = lineAt(lines, Math.max(start, end - 1));
|
|
96
|
+
if (first < 0 || last < 0)
|
|
97
|
+
return 'INVALID_RANGE';
|
|
98
|
+
if (last - first + 1 > options.maxLines || Buffer.byteLength(text.slice(start, end), 'utf8') > options.maxBytes)
|
|
99
|
+
return 'HIGHLIGHT_TOO_LARGE';
|
|
100
|
+
let from = Math.max(0, first - options.contextLines), to = Math.min(lines.length - 1, last + options.contextLines);
|
|
101
|
+
while (to - from + 1 > options.maxLines) {
|
|
102
|
+
if (from < first)
|
|
103
|
+
from++;
|
|
104
|
+
else if (to > last)
|
|
105
|
+
to--;
|
|
106
|
+
else
|
|
107
|
+
return 'SNIPPET_TOO_LARGE';
|
|
108
|
+
}
|
|
109
|
+
let bytes = Buffer.byteLength(text.slice(lines[from].start, lines[to].end), 'utf8');
|
|
110
|
+
while (bytes > options.maxBytes && (from < first || to > last)) {
|
|
111
|
+
if (from < first)
|
|
112
|
+
from++;
|
|
113
|
+
else
|
|
114
|
+
to--;
|
|
115
|
+
bytes = Buffer.byteLength(text.slice(lines[from].start, lines[to].end), 'utf8');
|
|
116
|
+
}
|
|
117
|
+
if (bytes > options.maxBytes)
|
|
118
|
+
return 'SNIPPET_TOO_LARGE';
|
|
119
|
+
const id = `${path}:${from + 1}-${to + 1}`;
|
|
120
|
+
return { id, path, startLine: from + 1, endLine: to + 1, bytes, lines: lines.slice(from, to + 1).map((line, i) => ({ number: from + i + 1, text: line.text, highlighted: from + i >= first && from + i <= last })) };
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Reads only finding-bearing files. Range matching verifies anchors, not full snapshot identity.
|
|
124
|
+
* O_NOFOLLOW protects the opened file, but the lstat/open sequence cannot eliminate an
|
|
125
|
+
* attacker replacing an ancestor directory concurrently; the approved scan root and its
|
|
126
|
+
* ancestors must therefore be trusted during generation. These are generation-time reads,
|
|
127
|
+
* not authoritative live or full-file snapshots.
|
|
128
|
+
*/
|
|
129
|
+
export async function extractSourceSnippets(root, findings, options = {}) {
|
|
130
|
+
const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
131
|
+
const limits = { ...SOURCE_SNIPPET_LIMITS, ...options }, ordered = findings.slice().sort((a, b) => compare(a.path, b.path) || a.range.start.offset - b.range.start.offset || compare(a.id, b.id));
|
|
132
|
+
const files = new Map(), windows = new Map(), output = [];
|
|
133
|
+
let embeddedBytes = 0;
|
|
134
|
+
for (const finding of ordered) {
|
|
135
|
+
let file = files.get(finding.path);
|
|
136
|
+
if (!file) {
|
|
137
|
+
const validated = await validatePath(root, finding.path);
|
|
138
|
+
file = {};
|
|
139
|
+
files.set(finding.path, file);
|
|
140
|
+
if (typeof validated === 'string')
|
|
141
|
+
file.result = validated;
|
|
142
|
+
else {
|
|
143
|
+
file.absolute = validated.absolute;
|
|
144
|
+
const read = await readVerified(finding.path, validated.absolute);
|
|
145
|
+
if (typeof read === 'string')
|
|
146
|
+
file.result = read;
|
|
147
|
+
else
|
|
148
|
+
file.text = read.text;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (file.text === undefined) {
|
|
152
|
+
output.push(unavailable(finding.id, file.result ?? 'READ_FAILURE'));
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
const window = makeWindow(finding.path, finding, file.text, limits);
|
|
156
|
+
if (typeof window === 'string') {
|
|
157
|
+
output.push(unavailable(finding.id, window));
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (embeddedBytes + (windows.has(window.id) ? 0 : window.bytes) > limits.totalBytes) {
|
|
161
|
+
output.push(unavailable(finding.id, 'TOTAL_LIMIT'));
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
const alreadyStored = windows.has(window.id);
|
|
165
|
+
windows.set(window.id, window);
|
|
166
|
+
if (!alreadyStored)
|
|
167
|
+
embeddedBytes += window.bytes;
|
|
168
|
+
output.push({ findingId: finding.id, sourceId: window.id, available: true, startLine: window.startLine, endLine: window.endLine });
|
|
169
|
+
}
|
|
170
|
+
const sourceTextByPath = {};
|
|
171
|
+
for (const [path, file] of files)
|
|
172
|
+
if (file.text !== undefined)
|
|
173
|
+
sourceTextByPath[path] = file.text;
|
|
174
|
+
const result = { sources: [...windows.values()].sort((a, b) => compare(a.id, b.id)), findings: output, embeddedBytes };
|
|
175
|
+
Object.defineProperty(result, 'sourceTextByPath', { value: sourceTextByPath, enumerable: false, writable: false });
|
|
176
|
+
return result;
|
|
177
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { lstat, mkdtemp, readFile, realpath } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { spawn } from 'node:child_process';
|
|
7
|
+
import { runCli } from './cli.js';
|
|
8
|
+
const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
9
|
+
const browserLaunchTimeoutMs = 5_000;
|
|
10
|
+
async function version() {
|
|
11
|
+
const packageJson = JSON.parse(await readFile(join(packageRoot, 'package.json'), 'utf8'));
|
|
12
|
+
return packageJson.version ?? '0.0.0';
|
|
13
|
+
}
|
|
14
|
+
function help() {
|
|
15
|
+
return `RTL Analyzer — conservative RTL risk scanning\n\nUsage:\n rtl-analyzer Scan the current directory and open a dashboard\n rtl-analyzer scan [path] [options]\n rtl-analyzer --help\n rtl-analyzer --version\n\nOptions:\n --root <path> Scan this project root\n --format <format> json, markdown, markdown-structured, or dashboard\n --output-dir <path> Write report artifacts to this directory\n --fail-on-findings Exit 1 when actionable findings exist\n --embed-source-snippets Embed bounded source snippets in dashboard output\n`;
|
|
16
|
+
}
|
|
17
|
+
const io = {
|
|
18
|
+
writeStdout: value => process.stdout.write(value),
|
|
19
|
+
writeStderr: value => process.stderr.write(`${value}\n`),
|
|
20
|
+
};
|
|
21
|
+
export function isDirectExecution(invokedPath, modulePath, platform = process.platform) {
|
|
22
|
+
if (!invokedPath || !modulePath)
|
|
23
|
+
return false;
|
|
24
|
+
return platform === 'win32' ? invokedPath.toLowerCase() === modulePath.toLowerCase() : invokedPath === modulePath;
|
|
25
|
+
}
|
|
26
|
+
export async function openDashboard(path, platform = process.platform, launcher = spawn, timeoutMs = browserLaunchTimeoutMs) {
|
|
27
|
+
const command = platform === 'darwin' ? 'open' : platform === 'win32' ? 'explorer.exe' : 'xdg-open';
|
|
28
|
+
return new Promise(resolve => {
|
|
29
|
+
let settled = false;
|
|
30
|
+
let timer;
|
|
31
|
+
let child;
|
|
32
|
+
const finish = (opened) => {
|
|
33
|
+
if (settled)
|
|
34
|
+
return;
|
|
35
|
+
settled = true;
|
|
36
|
+
if (timer)
|
|
37
|
+
clearTimeout(timer);
|
|
38
|
+
if (child) {
|
|
39
|
+
child.removeListener('error', onError);
|
|
40
|
+
child.removeListener('close', onClose);
|
|
41
|
+
}
|
|
42
|
+
resolve(opened);
|
|
43
|
+
};
|
|
44
|
+
const onError = () => finish(false);
|
|
45
|
+
const onClose = (code) => finish(code === 0);
|
|
46
|
+
try {
|
|
47
|
+
child = launcher(command, [path], { stdio: 'ignore', shell: false });
|
|
48
|
+
child.once('error', onError);
|
|
49
|
+
child.once('close', onClose);
|
|
50
|
+
timer = setTimeout(() => {
|
|
51
|
+
try {
|
|
52
|
+
child?.kill();
|
|
53
|
+
}
|
|
54
|
+
catch { /* browser process cleanup is best effort */ }
|
|
55
|
+
finish(false);
|
|
56
|
+
}, timeoutMs);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
finish(false);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
export async function runDefaultDashboard(options = {}) {
|
|
64
|
+
const outputDir = await mkdtemp(join(await realpath(options.tempRoot ?? tmpdir()), 'rtl-analyzer-dashboard-'));
|
|
65
|
+
const dashboardPath = join(outputDir, 'rtl-report-dashboard.html');
|
|
66
|
+
const output = options.io ?? io;
|
|
67
|
+
const code = await (options.run ?? runCli)(['--root', process.cwd(), '--format', 'dashboard', '--output-dir', outputDir], output);
|
|
68
|
+
let dashboardExists = false;
|
|
69
|
+
try {
|
|
70
|
+
dashboardExists = (await lstat(dashboardPath)).isFile();
|
|
71
|
+
}
|
|
72
|
+
catch { /* report the scan error below */ }
|
|
73
|
+
if (!dashboardExists) {
|
|
74
|
+
output.writeStderr(`Dashboard was not generated: ${dashboardPath}`);
|
|
75
|
+
return code === 0 ? 2 : code;
|
|
76
|
+
}
|
|
77
|
+
output.writeStderr(`Dashboard: ${dashboardPath}`);
|
|
78
|
+
if (!(await (options.open ?? openDashboard)(dashboardPath)))
|
|
79
|
+
output.writeStderr(`Could not open dashboard automatically. Open: ${dashboardPath}`);
|
|
80
|
+
return code;
|
|
81
|
+
}
|
|
82
|
+
export async function main(argv, output = io) {
|
|
83
|
+
if (argv.length === 0)
|
|
84
|
+
return runDefaultDashboard({ io: output });
|
|
85
|
+
if (argv[0] === '--help' || argv[0] === '-h') {
|
|
86
|
+
output.writeStdout(help());
|
|
87
|
+
return 0;
|
|
88
|
+
}
|
|
89
|
+
if (argv[0] === '--version' || argv[0] === '-v') {
|
|
90
|
+
output.writeStdout(`${await version()}\n`);
|
|
91
|
+
return 0;
|
|
92
|
+
}
|
|
93
|
+
if (argv[0] !== 'scan') {
|
|
94
|
+
output.writeStderr(`Unknown command: ${argv[0]}. Use --help for usage.`);
|
|
95
|
+
return 2;
|
|
96
|
+
}
|
|
97
|
+
const scanArgs = argv.slice(1);
|
|
98
|
+
const firstPath = scanArgs[0];
|
|
99
|
+
if (firstPath && !firstPath.startsWith('-')) {
|
|
100
|
+
scanArgs.splice(0, 1, '--root', firstPath);
|
|
101
|
+
}
|
|
102
|
+
return runCli(scanArgs, output);
|
|
103
|
+
}
|
|
104
|
+
const invokedPath = process.argv[1] ? await realpath(process.argv[1]).catch(() => null) : null;
|
|
105
|
+
const modulePath = await realpath(fileURLToPath(import.meta.url)).catch(() => null);
|
|
106
|
+
if (isDirectExecution(invokedPath, modulePath))
|
|
107
|
+
process.exitCode = await main(process.argv.slice(2));
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const sort = (a, b) => a.localeCompare(b);
|
|
2
|
+
// Escape backslashes before pipes as well as the pipe itself. Otherwise an
|
|
3
|
+
// input such as `\\|` can leave a pipe that CommonMark treats as a column.
|
|
4
|
+
const esc = (s) => s.replace(/[\u0000-\u001f\u007f]/g, '�').replace(/\\/g, '\\\\').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\|/g, '\\|').replace(/`/g, '\\`').replace(/\r?\n/g, ' ');
|
|
5
|
+
const block = (s) => { const runs = [...s.matchAll(/`+/g)].map(x => x[0].length); const fence = '`'.repeat(Math.max(3, (runs.length ? Math.max(...runs) : 2) + 1)); return fence + '\n' + s.replace(/[\u0000-\u001f\u007f]/g, '�') + '\n' + fence; };
|
|
6
|
+
const tally = (xs) => { const m = new Map(); xs.forEach(x => m.set(x, (m.get(x) || 0) + 1)); return [...m].sort((a, b) => sort(a[0], b[0])); };
|
|
7
|
+
export function structuredMarkdown(r) {
|
|
8
|
+
const groups = [
|
|
9
|
+
['Actionable findings', r.findings.filter(f => ['AUTO_CANDIDATE', 'MANUAL_REVIEW', 'RUNTIME_CONFIG'].includes(f.category))],
|
|
10
|
+
['Informational findings', r.findings.filter(f => f.category === 'INFORMATIONAL')],
|
|
11
|
+
['Intentional-LTR findings', r.findings.filter(f => f.category === 'INTENTIONAL_LTR')],
|
|
12
|
+
];
|
|
13
|
+
const table = (title, rows) => `## ${title}\n\n| Name | Count |\n| --- | ---: |\n${rows.map(x => `| ${esc(x[0])} | ${x[1]} |`).join('\n')}\n\n`;
|
|
14
|
+
let out = `# Structured RTL risk report\n\nStatic analysis and documented exceptions; not proof of visual failure.\n\n## Executive summary\n\n- Scan status: **${r.complete ? 'Complete' : 'Incomplete'}**\n- Schema: ${r.schemaVersion}\n- Files analyzed: ${r.files.length}\n- Skipped paths: ${r.skipped.length}\n- Findings: ${r.findings.length}\n- Diagnostics: ${r.diagnostics.length}\n- Blocking diagnostics: ${r.diagnostics.filter(d => d.blocking).length}\n\n${r.complete ? '' : '> This report is incomplete; absence of a finding is not evidence of safety.\n\n'}`;
|
|
15
|
+
out += `## Report metadata\n\n- Kind: ${esc(r.kind)}\n- Schema version: ${r.schemaVersion}\n- Input digest: ${esc(r.inputDigest)}\n- Policy digest: ${esc(r.policyDigest)}\n- Unique affected files: ${r.metrics.uniqueAffectedFiles}\n- Confidence metrics: ${Object.entries(r.metrics.byConfidence).sort(([a], [b]) => sort(a, b)).map(([k, v]) => `${esc(k)}=${v}`).join(', ') || 'none'}\n- Reference case IDs: ${r.metrics.referenceCaseIds.slice().sort(sort).map(esc).join(', ') || 'none'}\n\n`;
|
|
16
|
+
out += table('Findings overview', [['Actionable', groups[0][1].length], ['Informational', groups[1][1].length], ['Intentional LTR', groups[2][1].length]]);
|
|
17
|
+
out += table('Category breakdown', ['AUTO_CANDIDATE', 'MANUAL_REVIEW', 'RUNTIME_CONFIG', 'INFORMATIONAL', 'INTENTIONAL_LTR'].map(category => [category, r.findings.filter(f => f.category === category).length]));
|
|
18
|
+
out += table('Severity breakdown', tally(r.findings.map(f => f.severity)));
|
|
19
|
+
out += table('Rule breakdown', tally(r.findings.map(f => f.ruleId)));
|
|
20
|
+
out += table('Ownership', tally(r.findings.map(f => f.ownership)));
|
|
21
|
+
out += table('Application reachability', tally(r.findings.flatMap(f => f.applications.length ? f.applications : ['Shared or unresolved reachability'])));
|
|
22
|
+
out += '> Application attribution counts may overlap; they are not a unique finding total.\n\n';
|
|
23
|
+
for (const [title, list] of groups) {
|
|
24
|
+
out += `## ${title}\n\n`;
|
|
25
|
+
for (const f of list.slice().sort((a, b) => sort(a.path, b.path) || a.range.start.offset - b.range.start.offset || sort(a.id, b.id))) {
|
|
26
|
+
const ref = r.evidenceReferences.find(x => x.findingId === f.id);
|
|
27
|
+
const locations = f.relatedLocations.slice().sort((a, b) => sort(a.path, b.path) || a.range.start.offset - b.range.start.offset).map(x => `${esc(x.path)}:${x.range.start.line}:${x.range.start.column}`).join(', ') || 'none';
|
|
28
|
+
const exception = f.exceptionReason ? `\nException metadata: ${esc(f.exceptionReason)}; original category: ${esc(f.originalCategory ?? 'unknown')}.\n` : '';
|
|
29
|
+
const suggestion = f.suggestion ? `\nConditional suggestion (review required; not an automatic fix):\n\n- Property: ${esc(f.suggestion.property)}\n- Value:\n\n${block(f.suggestion.value)}\n` : '';
|
|
30
|
+
out += `### ${esc(f.id)}\n\n**${esc(f.title)}** — ${f.category}; ${f.severity}; ${f.confidence} confidence.\n\n- Source: ${esc(f.path)}:${f.range.start.line}:${f.range.start.column}\n- Owner: ${esc(f.ownership)}\n- Applications: ${f.applications.length ? f.applications.slice().sort(sort).map(esc).join(', ') : 'shared or unresolved reachability'}\n- Evidence IDs: ${ref?.evidenceIds.map(esc).join(', ') || 'none'}${ref?.missingEvidenceIds.length ? ` (missing: ${ref.missingEvidenceIds.map(esc).join(', ')})` : ''}${ref?.duplicateEvidenceIds.length ? ` (duplicate: ${ref.duplicateEvidenceIds.map(esc).join(', ')})` : ''}\n- Related locations: ${locations}\n\nOriginal declaration:\n\n${block(f.original)}\n\nRationale: ${esc(f.rationale)}\n\nTreatment: ${esc(f.treatment)}\n\nLimits: ${esc(f.limitation)}\n${exception}${suggestion}\n`;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const diagnostics = r.diagnostics.slice().sort((a, b) => sort(a.path, b.path) || a.range.start.offset - b.range.start.offset || sort(a.code, b.code)).map(d => `- ${esc(d.path)}:${d.range.start.line}:${d.range.start.column} — ${esc(d.code)}, impact=${esc(d.impact ?? 'none')}, blocking=${d.blocking}: ${esc(d.message)} ${esc(d.rationale ?? '')}`).join('\n') || '_None._';
|
|
34
|
+
const evidence = r.evidence.slice().sort((a, b) => sort(a.id, b.id)).map(e => `### ${esc(e.id)}\n\n- Source: ${esc(e.path)}:${e.range.start.line}:${e.range.start.column}\n- Mechanism: ${esc(e.mechanism)}\n- Property: ${esc(e.property)}\n- Value: ${block(e.value)}\n- Semantics: ${esc(e.semantics)}\n\n${block(e.original)}`).join('\n\n') || '_None._';
|
|
35
|
+
return out + `## Diagnostics and coverage warnings\n\n${diagnostics}\n\n## Evidence index\n\n${evidence}\n`;
|
|
36
|
+
}
|
package/dist/tailwind.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { fact } from './model.js';
|
|
2
|
+
const utilities = {
|
|
3
|
+
ml: 'margin-left', mr: 'margin-right', pl: 'padding-left', pr: 'padding-right',
|
|
4
|
+
left: 'left', right: 'right', 'text-left': 'text-align', 'text-right': 'text-align',
|
|
5
|
+
'border-l': 'border-left', 'border-r': 'border-right',
|
|
6
|
+
};
|
|
7
|
+
export function extractTailwind(path, text, value, valueStart, context) {
|
|
8
|
+
const evidence = [];
|
|
9
|
+
for (const match of value.matchAll(/\S+/g)) {
|
|
10
|
+
const token = match[0];
|
|
11
|
+
const parts = token.split(':');
|
|
12
|
+
const utility = parts.at(-1);
|
|
13
|
+
const key = /^(text-left|text-right)(?:-|$)/.test(utility) ? utility.startsWith('text-left') ? 'text-left' : 'text-right' : utility.match(/^(border-[lr]|(?:ml|mr|pl|pr|left|right))(?:-|$)/)?.[1];
|
|
14
|
+
if (!key || !utilities[key])
|
|
15
|
+
continue;
|
|
16
|
+
const start = valueStart + match.index;
|
|
17
|
+
const value = key === 'text-left' ? 'left' : key === 'text-right' ? 'right' : token;
|
|
18
|
+
evidence.push(fact(path, text, 'css', `${context}/.${token}`, utilities[key], value, start, start + token.length, 'tailwind-utility', [token]));
|
|
19
|
+
}
|
|
20
|
+
return evidence;
|
|
21
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { extractCss } from "./css.js";
|
|
3
|
+
import { fact, range } from "./model.js";
|
|
4
|
+
import { extractTailwind } from './tailwind.js';
|
|
5
|
+
import { extractBootstrap } from './bootstrap.js';
|
|
6
|
+
export function extractTypescript(path, text) {
|
|
7
|
+
const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, /\.(?:tsx|jsx)$/.test(path) ? ts.ScriptKind.TSX : /\.js$/.test(path) ? ts.ScriptKind.JSX : ts.ScriptKind.TS);
|
|
8
|
+
const evidence = [], diagnostics = [];
|
|
9
|
+
const imports = new Map();
|
|
10
|
+
const constants = new Map();
|
|
11
|
+
const ambiguousConstants = new Set();
|
|
12
|
+
function pre(n) {
|
|
13
|
+
if (ts.isImportDeclaration(n) && ts.isStringLiteral(n.moduleSpecifier)) {
|
|
14
|
+
const c = n.importClause;
|
|
15
|
+
if (c?.name)
|
|
16
|
+
imports.set(c.name.text, n.moduleSpecifier.text);
|
|
17
|
+
if (c?.namedBindings && ts.isNamedImports(c.namedBindings))
|
|
18
|
+
for (const e of c.namedBindings.elements)
|
|
19
|
+
imports.set(e.name.text, `${n.moduleSpecifier.text}:${e.propertyName?.text ?? e.name.text}`);
|
|
20
|
+
}
|
|
21
|
+
if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.initializer && ts.isVariableDeclarationList(n.parent) && (n.parent.flags & ts.NodeFlags.Const)) {
|
|
22
|
+
if (constants.has(n.name.text))
|
|
23
|
+
ambiguousConstants.add(n.name.text);
|
|
24
|
+
else
|
|
25
|
+
constants.set(n.name.text, n.initializer);
|
|
26
|
+
}
|
|
27
|
+
ts.forEachChild(n, pre);
|
|
28
|
+
}
|
|
29
|
+
pre(sf);
|
|
30
|
+
const diag = (n, code, message) => diagnostics.push({ path, code, message, range: range(text, n.getStart(sf), n.end) });
|
|
31
|
+
const context = (n) => { let p = n; while (p) {
|
|
32
|
+
if (ts.isFunctionDeclaration(p) && p.name)
|
|
33
|
+
return p.name.text;
|
|
34
|
+
if (ts.isVariableDeclaration(p) && ts.isIdentifier(p.name))
|
|
35
|
+
return p.name.text;
|
|
36
|
+
p = p.parent;
|
|
37
|
+
} return 'module'; };
|
|
38
|
+
const aliases = { ml: 'marginLeft', mr: 'marginRight', pl: 'paddingLeft', pr: 'paddingRight', mx: 'marginHorizontalAxis', my: 'marginVerticalAxis', px: 'paddingHorizontalAxis', py: 'paddingVerticalAxis', m: 'margin', p: 'padding' };
|
|
39
|
+
function object(n, mechanism, ctx, seen = new Set(), inheritedKey) {
|
|
40
|
+
if (ts.isParenthesizedExpression(n) || ts.isAsExpression(n) || ts.isSatisfiesExpression(n)) {
|
|
41
|
+
object(n.expression, mechanism, ctx, seen);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (ts.isIdentifier(n) && constants.has(n.text) && !ambiguousConstants.has(n.text) && !seen.has(n.text)) {
|
|
45
|
+
object(constants.get(n.text), mechanism, `${ctx}/reference:${n.text}`, new Set([...seen, n.text]));
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (ts.isArrayLiteralExpression(n)) {
|
|
49
|
+
n.elements.forEach((e, i) => object(e, mechanism, `${ctx}/array:${i}`, seen));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (ts.isArrowFunction(n) || ts.isFunctionExpression(n)) {
|
|
53
|
+
diag(n, 'STYLE_CALLBACK', 'Callback is inspected structurally, never invoked.');
|
|
54
|
+
if (ts.isBlock(n.body)) {
|
|
55
|
+
for (const stmt of n.body.statements)
|
|
56
|
+
if (ts.isReturnStatement(stmt) && stmt.expression)
|
|
57
|
+
object(stmt.expression, mechanism, ctx + '/callback', seen);
|
|
58
|
+
}
|
|
59
|
+
else
|
|
60
|
+
object(n.body, mechanism, ctx + '/callback', seen);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (!ts.isObjectLiteralExpression(n)) {
|
|
64
|
+
diag(n, 'UNRESOLVED_STYLE', 'Style expression is not a bounded object/literal; not evaluated.');
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
for (const p of n.properties) {
|
|
68
|
+
if (!ts.isPropertyAssignment(p) || ts.isComputedPropertyName(p.name)) {
|
|
69
|
+
diag(p, 'UNRESOLVED_PROPERTY', 'Spread, shorthand, method or computed style key not resolved.');
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
const key = ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) || ts.isNumericLiteral(p.name) ? p.name.text : p.name.getText(sf);
|
|
73
|
+
const v = p.initializer;
|
|
74
|
+
const resolvedKey = inheritedKey ?? (mechanism === 'mui-sx' ? aliases[key] ?? key : key);
|
|
75
|
+
if (ts.isArrayLiteralExpression(v) && mechanism === 'mui-sx' && key !== 'sx') {
|
|
76
|
+
v.elements.forEach((item, i) => { if (item.kind === ts.SyntaxKind.NullKeyword)
|
|
77
|
+
return; const literal = ts.isStringLiteral(item) || ts.isNumericLiteral(item) || (ts.isPrefixUnaryExpression(item) && ts.isNumericLiteral(item.operand)); if (!literal)
|
|
78
|
+
diag(item, 'DYNAMIC_VALUE', `Value for ${resolvedKey} is dynamic; original retained.`); evidence.push(fact(path, text, mechanism, `${ctx}/${key}/responsive:${i}`, resolvedKey, item.getText(sf), item.getStart(sf), item.end, /^(margin|padding|gap)/.test(resolvedKey) ? 'mui-theme-spacing' : 'mui-system')); });
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (ts.isObjectLiteralExpression(v) || ts.isArrayLiteralExpression(v)) {
|
|
82
|
+
const responsive = mechanism === 'mui-sx' && ts.isObjectLiteralExpression(v) && v.properties.length > 0 && v.properties.every(x => ts.isPropertyAssignment(x) && /^(xs|sm|md|lg|xl)$/.test(x.name.getText(sf)));
|
|
83
|
+
object(v, mechanism, `${ctx}/${key}`, seen, responsive ? resolvedKey : undefined);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const literal = ts.isStringLiteral(v) || ts.isNumericLiteral(v) || ts.isNoSubstitutionTemplateLiteral(v) || (ts.isPrefixUnaryExpression(v) && ts.isNumericLiteral(v.operand));
|
|
87
|
+
if (!literal) {
|
|
88
|
+
diag(v, 'DYNAMIC_VALUE', `Value for ${key} is dynamic; original retained.`);
|
|
89
|
+
}
|
|
90
|
+
const normalized = resolvedKey;
|
|
91
|
+
const spacing = /^(margin|padding|gap|rowGap|columnGap)/.test(normalized) || /(margin|padding|gap)(?:\/|$)/i.test(ctx);
|
|
92
|
+
evidence.push(fact(path, text, mechanism, ctx, normalized, v.getText(sf), p.getStart(sf), p.end, mechanism === 'react-inline' ? 'react-css' : mechanism === 'mui-theme' ? 'emotion-css' : spacing ? 'mui-theme-spacing' : 'mui-system'));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function visit(n) {
|
|
96
|
+
if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && n.expression.getText(sf) === 'React.createElement') {
|
|
97
|
+
const props = n.arguments[1];
|
|
98
|
+
if (props && ts.isObjectLiteralExpression(props))
|
|
99
|
+
for (const p of props.properties)
|
|
100
|
+
if (ts.isPropertyAssignment(p) && p.name.getText(sf) === 'style')
|
|
101
|
+
object(p.initializer, 'react-inline', 'React.createElement/style');
|
|
102
|
+
}
|
|
103
|
+
if (ts.isJsxAttribute(n) && n.initializer && ts.isJsxExpression(n.initializer) && n.initializer.expression) {
|
|
104
|
+
const key = n.name.getText(sf);
|
|
105
|
+
const opening = n.parent.parent;
|
|
106
|
+
const tag = ts.isJsxOpeningElement(opening) || ts.isJsxSelfClosingElement(opening) ? opening.tagName.getText(sf) : '';
|
|
107
|
+
const mui = imports.get(tag)?.startsWith('@mui/') || ['FormField', 'Button'].includes(tag) && imports.get(tag)?.startsWith('@atlas/design-system');
|
|
108
|
+
if (key === 'style')
|
|
109
|
+
object(n.initializer.expression, 'react-inline', `${context(n)}/${tag}`);
|
|
110
|
+
if (key === 'sx') {
|
|
111
|
+
if (mui)
|
|
112
|
+
object(n.initializer.expression, 'mui-sx', `${context(n)}/${tag}`);
|
|
113
|
+
else
|
|
114
|
+
diag(n, 'UNRESOLVED_SX_OWNER', 'sx owner not resolved to a known MUI import/wrapper.');
|
|
115
|
+
}
|
|
116
|
+
if (key === 'css' && ts.isObjectLiteralExpression(n.initializer.expression))
|
|
117
|
+
object(n.initializer.expression, 'react-inline', `${context(n)}/${tag}/css`);
|
|
118
|
+
if (key === 'className' && ts.isStringLiteral(n.initializer.expression)) {
|
|
119
|
+
const valueStart = n.initializer.expression.getStart(sf) + 1;
|
|
120
|
+
evidence.push(...extractTailwind(path, text, n.initializer.expression.text, valueStart, `${context(n)}/${tag}`));
|
|
121
|
+
evidence.push(...extractBootstrap(path, text, n.initializer.expression.text, valueStart, `${context(n)}/${tag}`));
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (ts.isJsxAttribute(n) && n.name.getText(sf) === 'className' && n.initializer && ts.isStringLiteral(n.initializer)) {
|
|
125
|
+
const opening = n.parent.parent;
|
|
126
|
+
const tag = ts.isJsxOpeningElement(opening) || ts.isJsxSelfClosingElement(opening) ? opening.tagName.getText(sf) : '';
|
|
127
|
+
evidence.push(...extractTailwind(path, text, n.initializer.text, n.initializer.getStart(sf) + 1, `${context(n)}/${tag}`));
|
|
128
|
+
evidence.push(...extractBootstrap(path, text, n.initializer.text, n.initializer.getStart(sf) + 1, `${context(n)}/${tag}`));
|
|
129
|
+
}
|
|
130
|
+
if (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && imports.get(n.expression.text)?.endsWith(':createTheme')) {
|
|
131
|
+
for (const a of n.arguments)
|
|
132
|
+
if (ts.isObjectLiteralExpression(a))
|
|
133
|
+
for (const p of a.properties)
|
|
134
|
+
if (ts.isPropertyAssignment(p) && p.name.getText(sf) === 'components' && ts.isObjectLiteralExpression(p.initializer)) {
|
|
135
|
+
function overrides(x) { if (ts.isPropertyAssignment(x) && x.name.getText(sf) === 'styleOverrides')
|
|
136
|
+
object(x.initializer, 'mui-theme', context(n) + '/styleOverrides');
|
|
137
|
+
else
|
|
138
|
+
ts.forEachChild(x, overrides); }
|
|
139
|
+
overrides(p.initializer);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (ts.isTaggedTemplateExpression(n)) {
|
|
143
|
+
let tag = n.tag;
|
|
144
|
+
while (ts.isPropertyAccessExpression(tag) || ts.isCallExpression(tag))
|
|
145
|
+
tag = tag.expression;
|
|
146
|
+
const imported = ts.isIdentifier(tag) ? imports.get(tag.text) : undefined;
|
|
147
|
+
const cssProp = ts.isIdentifier(tag) && imported === '@emotion/react:css' && ts.isJsxExpression(n.parent) && ts.isJsxAttribute(n.parent.parent) && n.parent.parent.name.getText(sf) === 'css';
|
|
148
|
+
const muiStyled = ts.isIdentifier(tag) && Boolean(imported && ((imported === '@mui/material/styles:styled') || imported === '@mui/material/styles'));
|
|
149
|
+
if (ts.isIdentifier(tag) && (imported === '@emotion/styled' || cssProp || muiStyled)) {
|
|
150
|
+
if (ts.isNoSubstitutionTemplateLiteral(n.template)) {
|
|
151
|
+
const start = n.template.getStart(sf) + 1;
|
|
152
|
+
const raw = text.slice(start, n.template.end - 1);
|
|
153
|
+
if (raw.includes('\\'))
|
|
154
|
+
diag(n.template, 'TEMPLATE_ESCAPE', 'Escaped template requires cooked/raw mapping; fragment skipped.');
|
|
155
|
+
else {
|
|
156
|
+
const r = extractCss(path, text, raw, start, 'emotion-template', context(n));
|
|
157
|
+
evidence.push(...r.evidence);
|
|
158
|
+
diagnostics.push(...r.diagnostics);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
diag(n.template, 'EMOTION_INTERPOLATION', 'Interpolated template not evaluated; independent declarations extracted conservatively.');
|
|
163
|
+
const chunks = [n.template.head, ...n.template.templateSpans.map(s => s.literal)];
|
|
164
|
+
for (const chunk of chunks) {
|
|
165
|
+
const start = chunk.getStart(sf) + 1;
|
|
166
|
+
const end = chunk.end - (chunk.kind === ts.SyntaxKind.TemplateTail ? 1 : 2);
|
|
167
|
+
const raw = text.slice(start, end);
|
|
168
|
+
if (raw.includes('\\')) {
|
|
169
|
+
diag(chunk, 'TEMPLATE_ESCAPE', 'Escaped interpolated fragment skipped.');
|
|
170
|
+
continue;
|
|
171
|
+
} // Only standalone semicolon-terminated declarations; no crossing holes.
|
|
172
|
+
const regex = /(?:^|[;\n])\s*([a-z-]+\s*:[^;{}$]+;)/g;
|
|
173
|
+
let m;
|
|
174
|
+
while ((m = regex.exec(raw))) {
|
|
175
|
+
const offset = start + m.index + m[0].indexOf(m[1]);
|
|
176
|
+
const r = extractCss(path, text, m[1], offset, 'emotion-template', context(n));
|
|
177
|
+
evidence.push(...r.evidence);
|
|
178
|
+
diagnostics.push(...r.diagnostics);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
ts.forEachChild(n, visit);
|
|
185
|
+
}
|
|
186
|
+
visit(sf);
|
|
187
|
+
const parsed = sf;
|
|
188
|
+
for (const d of parsed.parseDiagnostics)
|
|
189
|
+
diagnostics.push({ path, code: 'TS_PARSE', message: ts.flattenDiagnosticMessageText(d.messageText, ' '), range: range(text, d.start ?? 0, (d.start ?? 0) + (d.length ?? 0)) });
|
|
190
|
+
return { evidence, diagnostics };
|
|
191
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rtl-analyzer",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Conservative RTL risk scanning and report generation",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "https://github.com/FoushWare/rtl-analyzer.git"
|
|
8
|
+
},
|
|
9
|
+
"type": "module",
|
|
10
|
+
"bin": {
|
|
11
|
+
"rtl-analyzer": "dist/standalone-cli.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist/**",
|
|
15
|
+
"README.md",
|
|
16
|
+
"LICENSE"
|
|
17
|
+
],
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=22.12.0"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "tsc -p tsconfig.json",
|
|
23
|
+
"prepack": "npm run build"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"parse5": "7.3.0",
|
|
27
|
+
"postcss": "8.5.29",
|
|
28
|
+
"postcss-scss": "4.0.9",
|
|
29
|
+
"postcss-value-parser": "4.2.0",
|
|
30
|
+
"typescript": "~5.9.0"
|
|
31
|
+
}
|
|
32
|
+
}
|