Files
CatoandClaude 14a4ea80b9 fix(quality): refuse source links that redirect into the private network (#382)
* fix(quality): refuse source links that redirect into the private network

The data-quality cron (lib/quality/page-text.ts, lib/quality/network.ts)
fetched corpus source URLs with redirect:'follow' and no private-network
guard, so a cited link that 302s to localhost or the cloud metadata service
would have been fetched from the box.

Every quality fetch now goes through guardedFetch: redirect:'manual' and
@bitbaum/ai-kit/web's validateFetchTarget on the first URL and on every hop
(up to 5), per the package-first rule. A refused target is a ReadError
("refused: ..."): pageText reports the quote as unreadable, probeUrl as an
error, without retrying. A failed DNS lookup is rethrown in fetch's shape so
EAI_AGAIN still reads as unresolved (unscored) and ENOTFOUND as broken.

readPage is not used for the body: it refuses PDFs, sends its own user agent
and keeps only the article part of a page, which would change which quotes
are found. Public URLs answer as before (test/quality-network.test.ts).
package-plan.json binds the file under the ai block; README says so.

Claude-Session: https://claude.ai/code/session_019MDtmuvTGrpo3VChP3skH8

* docs(quality): say which network checks go through the SSRF guard

Every check that opens a corpus link uses guardedFetch; the SEC ticker
file and OpenFIGI calls go to fixed hosts. The README said every check.

Claude-Session: https://claude.ai/code/session_019MDtmuvTGrpo3VChP3skH8

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 08:50:40 +01:00

175 lines
5.8 KiB
TypeScript

/**
* The network half of the quality checks: does a source URL still resolve,
* and is a quoted sentence still on its page. No AI, no judgement — HTTP and
* string matching. Called by the scheduled run (lib/quality/run.ts) and the
* on-demand CLI (scripts/quality/run.ts), never by `verify`.
*
* Every request goes through `guardedFetch` (ai-kit's SSRF guard on each
* redirect hop), so a corpus link that redirects into the private network is
* refused and reported as an error, never fetched.
*/
import {
AGENTS,
guardedFetch,
pageText,
quoteOnPage,
ReadError,
type GuardedFetchDeps,
} from './page-text';
/**
* What a URL did, after up to three tries.
*
* `blocked` (401, 403, 429, a bot challenge) proves nothing about the page —
* a publisher refusing a robot is not a dead link — so it is reported apart
* and left out of the score. `gone` (404, 410) and the other 4xx are broken;
* `server` (5xx) and `timeout` persisted through every retry.
*/
export type LinkStatus =
'ok' | 'blocked' | 'unresolved' | 'gone' | 'client' | 'server' | 'timeout' | 'error';
export interface LinkResult {
url: string;
status: LinkStatus;
code: number | null;
detail: string;
}
export const BROKEN: ReadonlySet<LinkStatus> = new Set([
'gone',
'client',
'server',
'timeout',
'error',
]);
/**
* What a thrown fetch means. A resolver that answered "try again" (EAI_AGAIN)
* says nothing about the page — it is the checker's own network — so it is
* `unresolved` and not scored; a name that does not exist (ENOTFOUND), a
* refused connection or a TLS failure is the link's.
*/
function failureOf(error: unknown, timeoutMs: number): Omit<LinkResult, 'url'> {
const name = error instanceof Error ? error.name : '';
if (name === 'TimeoutError' || name === 'AbortError')
return { status: 'timeout', code: null, detail: `no answer in ${timeoutMs / 1000}s` };
if (error instanceof ReadError) return { status: 'error', code: null, detail: error.message };
const cause = (error as Error)?.cause as (Error & { code?: string }) | undefined;
const code = cause?.code ?? '';
const detail = [code, cause?.message].filter(Boolean).join(': ').slice(0, 100) || 'fetch failed';
if (code === 'EAI_AGAIN') return { status: 'unresolved', code: null, detail };
if (code === 'UND_ERR_CONNECT_TIMEOUT') return { status: 'timeout', code: null, detail };
return { status: 'error', code: null, detail };
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
function classify(code: number): LinkStatus {
if (code < 400) return 'ok';
if (code === 401 || code === 403 || code === 429 || code === 999) return 'blocked';
if (code === 404 || code === 410) return 'gone';
if (code < 500) return 'client';
return 'server';
}
async function once(
url: string,
method: 'HEAD' | 'GET',
agent: string,
timeoutMs: number,
signal?: AbortSignal,
deps?: GuardedFetchDeps,
) {
const timeout = AbortSignal.timeout(timeoutMs);
const combinedSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
const response = await guardedFetch(
url,
{ method, headers: { 'User-Agent': agent, Accept: '*/*' }, signal: combinedSignal },
deps,
);
// Drain without reading a whole PDF into memory.
await response.body?.cancel().catch(() => undefined);
return response.status;
}
/** HEAD first, GET when HEAD is refused; three tries with backoff on timeouts and 5xx only. */
export async function probeUrl(
url: string,
timeoutMs = 15_000,
signal?: AbortSignal,
deps?: GuardedFetchDeps,
): Promise<LinkResult> {
let last: LinkResult = { url, status: 'error', code: null, detail: '' };
for (let attempt = 0; attempt < 3; attempt++) {
if (signal?.aborted) break;
if (attempt > 0) await sleep(1000 * 2 ** attempt);
if (signal?.aborted) break;
try {
let code = await once(url, 'HEAD', AGENTS[0], timeoutMs, signal, deps);
if (code >= 400 && !signal?.aborted) {
code = await once(url, 'GET', AGENTS[attempt % 2], timeoutMs, signal, deps);
}
const status = classify(code);
last = { url, status, code, detail: `HTTP ${code}` };
if (status !== 'server') return last;
} catch (error) {
last = { url, ...failureOf(error, timeoutMs) };
// A refused target stays refused; asking again would only wait.
if (error instanceof ReadError) return last;
}
}
return last;
}
/** Run `work` over `items` with at most `limit` at once, stopping new starts at `deadline`. */
export async function pool<T, R>(
items: readonly T[],
limit: number,
deadline: number,
work: (item: T) => Promise<R>,
signal?: AbortSignal,
): Promise<R[]> {
const out: R[] = [];
let next = 0;
const lane = async () => {
while (next < items.length && Date.now() < deadline && !signal?.aborted) {
const idx = next++;
if (idx >= items.length) break;
const item = items[idx];
out.push(await work(item));
}
};
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, lane));
return out;
}
export interface QuoteResult {
key: string;
url: string;
verdict: 'found' | 'missing' | 'unreadable';
detail: string;
}
/** Every quote that cites one URL, answered from a single read of it per user agent. */
export async function quotesAt(
url: string,
quotes: readonly { key: string; quote: string }[],
signal?: AbortSignal,
timeoutMs = 40_000,
): Promise<QuoteResult[]> {
const pages = new Map<string, Promise<string>>();
const read = (u: string, agent: string) => {
if (!pages.has(agent)) pages.set(agent, pageText(u, agent, timeoutMs, signal));
return pages.get(agent)!;
};
const out: QuoteResult[] = [];
for (const q of quotes) {
if (signal?.aborted) break;
const { verdict, detail } = await quoteOnPage(url, q.quote, read, signal);
out.push({ key: q.key, url, verdict, detail });
}
return out;
}
export { ReadError };