File size: 5,876 Bytes
bdd8da5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | #!/usr/bin/env node
/**
* Opt-in, network-dependent URL audit. This is intentionally separate from
* deterministic structural validation. Authentication, access-control and
* rate-limit responses are reported as indeterminate, never as missing.
*/
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, "..");
const dataDir = path.resolve(process.argv[2] || path.join(root, "data"));
const TIMEOUT_MS = 15_000;
const CONCURRENCY = 6;
function parseCsv(text, filename) {
const records = [];
let record = [];
let field = "";
let quoted = false;
for (let index = 0; index < text.length; index += 1) {
const char = text[index];
if (quoted) {
if (char === '"' && text[index + 1] === '"') { field += '"'; index += 1; }
else if (char === '"') quoted = false;
else field += char;
} else if (char === '"' && field === "") quoted = true;
else if (char === ",") { record.push(field); field = ""; }
else if (char === "\n") { record.push(field.replace(/\r$/, "")); records.push(record); record = []; field = ""; }
else field += char;
}
if (quoted) throw new Error(`${filename}: unclosed CSV quote`);
if (field || record.length) { record.push(field.replace(/\r$/, "")); records.push(record); }
const headers = records.shift() || [];
return records.filter((row) => row.some(Boolean)).map((values) =>
Object.fromEntries(headers.map((header, index) => [header, values[index] ?? ""]))
);
}
async function load(name) {
return parseCsv(await fs.readFile(path.join(dataDir, `${name}.csv`), "utf8"), name);
}
const sourceRows = await load("sources");
const officialRows = await load("official_data_sources");
const claimEvidenceRows = await load("claim_evidence");
const claimCodedSourceIds = new Set(claimEvidenceRows.map((row) => row.source_id).filter(Boolean));
const links = [
...sourceRows.map((row) => ({
table: "sources", row_id: row.source_id, url: row.url,
claim_coded_scope: claimCodedSourceIds.has(row.source_id)
})),
...officialRows.map((row) => ({
table: "official_data_sources", row_id: row.official_source_id,
url: row.landing_url || row.url, claim_coded_scope: false
}))
];
function classify(status) {
if (status === 404 || status === 410) return "confirmed_missing";
if ([401, 403, 407, 429].includes(status)) return "indeterminate_access_control";
if (status >= 200 && status < 400) return "reachable";
return "indeterminate_http";
}
async function request(link) {
let parsed;
try {
parsed = new URL(link.url);
if (!/^https?:$/.test(parsed.protocol)) throw new Error("unsupported protocol");
} catch (caught) {
return { ...link, status: null, classification: "malformed_url", detail: caught.message };
}
try {
const fetchOnce = async (range) => {
const response = await fetch(parsed, {
method: "GET",
redirect: "follow",
signal: AbortSignal.timeout(TIMEOUT_MS),
headers: {
...(range ? { Range: "bytes=0-0" } : { "Cache-Control": "no-cache" }),
"User-Agent": "agency-transfer-link-audit/0.4.0"
}
});
await response.body?.cancel();
return response;
};
const response = await fetchOnce(true);
if ([404, 410].includes(response.status)) {
try {
const confirmation = await fetchOnce(false);
if (![404, 410].includes(confirmation.status)) {
return {
...link, status: confirmation.status, classification: classify(confirmation.status),
final_url: confirmation.url, detail: `Initial ranged request returned ${response.status}; plain GET did not confirm it`
};
}
return {
...link, status: confirmation.status, classification: "confirmed_missing",
final_url: confirmation.url, confirmation: "two independent GET requests returned HTTP 404/410"
};
} catch (caught) {
return {
...link, status: response.status, classification: "indeterminate_unconfirmed_missing",
final_url: response.url, detail: `Initial ${response.status} could not be confirmed: ${String(caught.message || caught)}`
};
}
}
return {
...link,
status: response.status,
classification: classify(response.status),
final_url: response.url
};
} catch (caught) {
return { ...link, status: null, classification: "indeterminate_network", detail: String(caught.message || caught) };
}
}
const results = new Array(links.length);
let cursor = 0;
async function worker() {
while (cursor < links.length) {
const index = cursor;
cursor += 1;
results[index] = await request(links[index]);
}
}
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, links.length) }, worker));
results.sort((a, b) => a.table.localeCompare(b.table) || a.row_id.localeCompare(b.row_id));
const blocking = results.filter(
(item) => item.claim_coded_scope && ["malformed_url", "confirmed_missing"].includes(item.classification)
);
const counts = Object.fromEntries([...new Set(results.map((item) => item.classification))].sort().map((label) => [
label,
results.filter((item) => item.classification === label).length
]));
const report = {
auditor: "agency-transfer-election-cases-v0.4.0/audit-links",
checked_at: new Date().toISOString(),
status: blocking.length ? "fail" : "pass",
policy: "Only malformed URLs and twice-confirmed HTTP 404/410 responses in claim-coded evidence block; other corpus layers are advisory, and 401/403/407/429 or network failures are indeterminate.",
checked_url_count: results.length,
counts,
results
};
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
if (blocking.length) process.exitCode = 1;
|