Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. πŸ”₯

feat(api): URL-level threat protection checks, billed per scanned URL (#3967)

GergΕ‘ MΓ³riczf05d93f6b30c
diff --git a/apps/api/src/__tests__/snips/v2/threat-protection-billing.test.ts b/apps/api/src/__tests__/snips/v2/threat-protection-billing.test.ts
index 006b690e6..4209630c5 100644
--- a/apps/api/src/__tests__/snips/v2/threat-protection-billing.test.ts
+++ b/apps/api/src/__tests__/snips/v2/threat-protection-billing.test.ts
@@ -25,10 +25,12 @@ import {
// Threat protection billing (ENG-4985, ZDR rework ENG-5004)
//
// Billing rules under test:
-// - +2 credits per domain scanned in "normal" mode (Google Web Risk)
-// - a "scan" = a ThreatDecision with providerConsulted β€” +2 per consulted
-// verdict. There is no verdict cache anymore (ZDR): every request scans
-// afresh, and dedup only applies within one request/job.
+// - +2 credits per URL scanned in "normal" mode (Google Web Risk).
+// Checks are URL-level and so is billing: consulted decisions bill once
+// per unique canonical URL within one request/job
+// (calculateThreatScanCredits).
+// - There is no verdict cache (ZDR): every request scans afresh, and
+// dedup only applies within one request/job.
// - blocked requests still bill the scan fee (no base scrape cost, matching
// how other failed scrapes bill)
// - local-only decisions (whitelist/blacklist/blocked-tld) never bill
@@ -55,9 +57,9 @@ const CLEAN_URL = TEST_SUITE_WEBSITE;
// A stable cross-hostname redirect: google.com 301s to www.google.com. The
// mock flags only the redirect target, so the scrape consults the provider
-// twice (initial domain + redirect re-check) before being blocked.
-// NOTE the two hostnames are different domains for the request-scoped dedup,
-// so the redirect re-check is a second scan (two consulted decisions).
+// twice (initial URL + redirect re-check) before being blocked.
+// NOTE the redirect lands on a different URL, so the re-check is a second
+// billable scan (billing dedups per canonical URL, and these differ).
const REDIRECT_SOURCE_URL = "https://google.com/";
const REDIRECT_TARGET_DOMAIN = "www.google.com";
@@ -86,9 +88,9 @@ const webRiskHandler = createWebRiskMockHandler(webRiskDb, webRiskCounters);
let webRiskServer: http.Server | null = null;
-/** hashes:search confirmations whose prefix belongs to `domain`. */
-const webRiskHitsFor = (domain: string) =>
- webRiskCounters.hashesSearchRequestsForDomain(domain);
+/** hashes:search confirmations whose prefix belongs to a URL or domain. */
+const webRiskHitsFor = (urlOrDomain: string) =>
+ webRiskCounters.hashesSearchRequestsForTarget(urlOrDomain);
function startWebRiskMock(): Promise<void> {
const port = Number(new URL(webRiskMockUrl).port);
@@ -334,7 +336,7 @@ describeIf(TEST_PRODUCTION)("Threat protection billing", () => {
});
(HAS_WEB_RISK_MOCK ? it : it.skip)(
- "bills a scan fee per result domain on top of normal search billing",
+ "bills a scan fee per result URL on top of normal search billing",
async () => {
const limit = 20;
const res = await searchRaw(
@@ -353,22 +355,20 @@ describeIf(TEST_PRODUCTION)("Threat protection billing", () => {
const web: { url: string }[] = res.body.data.web ?? [];
expect(web.length).toBeGreaterThan(0);
- const uniqueDomains = new Set(
- web.map(x => new URL(x.url).hostname.toLowerCase()),
- );
+ const uniqueUrls = new Set(web.map(x => x.url));
const searchCredits = Math.ceil(web.length / 10) * 2;
if (web.length < limit) {
// Nothing was sliced off, so the returned set IS the scanned set:
- // exactly one +2 scan fee per unique result domain.
+ // exactly one +2 scan fee per unique result URL.
expect(res.body.creditsUsed).toBe(
- searchCredits + 2 * uniqueDomains.size,
+ searchCredits + 2 * uniqueUrls.size,
);
} else {
// The provider over-fetched (limit * 2 buffer) and results were
- // sliced; scanned domains βŠ‡ returned domains.
+ // sliced; scanned URLs βŠ‡ returned URLs.
expect(res.body.creditsUsed).toBeGreaterThanOrEqual(
- searchCredits + 2 * uniqueDomains.size,
+ searchCredits + 2 * uniqueUrls.size,
);
}
},
diff --git a/apps/api/src/__tests__/snips/v2/threat-protection-enforcement.test.ts b/apps/api/src/__tests__/snips/v2/threat-protection-enforcement.test.ts
index 796d5e613..c9fece440 100644
--- a/apps/api/src/__tests__/snips/v2/threat-protection-enforcement.test.ts
+++ b/apps/api/src/__tests__/snips/v2/threat-protection-enforcement.test.ts
@@ -55,6 +55,14 @@ const REDIRECT_TARGET_DOMAIN = "www.google.com";
// Domains the mock provider's threat lists flag as MALWARE (risk score 100).
const MOCK_RISKY_DOMAINS = [RISKY_DOMAIN, REDIRECT_TARGET_DOMAIN];
+// URL-level listing on the otherwise-clean test-suite domain: only this exact
+// page is flagged β€” the domain root and every other page stay clean. Blocked
+// scrapes never fetch, so the page does not need to exist.
+const RISKY_URL_ON_CLEAN_DOMAIN = new URL(
+ "/threat-fixture/flagged-page.html",
+ TEST_SUITE_WEBSITE,
+).href;
+
const mockProviderUrl = process.env.GOOGLE_WEB_RISK_API_URL ?? "";
const HAS_MOCK_PROVIDER =
/^http:\/\/(localhost|127\.0\.0\.1):\d+$/.test(mockProviderUrl) &&
@@ -67,14 +75,15 @@ const webRiskDb = new WebRiskMockDatabase();
for (const domain of MOCK_RISKY_DOMAINS) {
webRiskDb.addRiskyDomain(domain, "MALWARE");
}
+webRiskDb.addRiskyUrl(RISKY_URL_ON_CLEAN_DOMAIN, "MALWARE");
const webRiskCounters = createWebRiskMockCounters();
const webRiskHandler = createWebRiskMockHandler(webRiskDb, webRiskCounters);
let mockServer: http.Server | null = null;
-/** hashes:search confirmations whose prefix belongs to `domain`. */
-const providerHitsFor = (domain: string) =>
- webRiskCounters.hashesSearchRequestsForDomain(domain);
+/** hashes:search confirmations whose prefix belongs to a URL or domain. */
+const providerHitsFor = (urlOrDomain: string) =>
+ webRiskCounters.hashesSearchRequestsForTarget(urlOrDomain);
function startMockProvider(): Promise<void> {
const port = Number(new URL(mockProviderUrl).port);
@@ -451,6 +460,39 @@ describeIf(TEST_PRODUCTION)("Threat protection enforcement", () => {
scrapeTimeout,
);
+ (HAS_MOCK_PROVIDER ? it : it.skip)(
+ "scrape: flagged URL is blocked while the rest of its domain stays scrapeable",
+ async () => {
+ // Checks are URL-level: only the listed page's expression matches,
+ // so the block requires a hashes:search confirmation for the URL…
+ const blocked = await scrapeRaw(
+ {
+ url: RISKY_URL_ON_CLEAN_DOMAIN,
+ threatProtection: { mode: "normal", failurePolicy: "open" },
+ } as any,
+ identity,
+ );
+ expect(blocked.statusCode).toBe(403);
+ expect(blocked.body.success).toBe(false);
+ expect(blocked.body.code).toBe("unsafe_domain_blocked");
+ expect(blocked.body.error).toContain("/threat-fixture/flagged-page");
+ expect(
+ providerHitsFor(RISKY_URL_ON_CLEAN_DOMAIN),
+ ).toBeGreaterThanOrEqual(1);
+
+ // …while the same policy still scrapes the domain root fine.
+ const doc = await scrape(
+ {
+ url: CLEAN_URL,
+ threatProtection: { mode: "normal", failurePolicy: "open" },
+ } as any,
+ identity,
+ );
+ expect(doc.metadata.statusCode).toBe(200);
+ },
+ scrapeTimeout * 2,
+ );
+
(HAS_MOCK_PROVIDER ? it : it.skip)(
"scrape: clean domain redirecting to a blocked domain is blocked",
async () => {
diff --git a/apps/api/src/controllers/v1/batch-scrape.ts b/apps/api/src/controllers/v1/batch-scrape.ts
index a45b7efc1..599ca9f01 100644
--- a/apps/api/src/controllers/v1/batch-scrape.ts
+++ b/apps/api/src/controllers/v1/batch-scrape.ts
@@ -154,22 +154,21 @@ export async function batchScrapeController(
// Threat protection: reject/report blocked URLs at enqueue time so they
// never consume scrape slots (mirrors the isUrlBlocked handling above).
if (threatProtection.policy) {
- const { blocked } = await checkUrlsAgainstThreatPolicy(
+ const { blocked, decisionsByUrl } = await checkUrlsAgainstThreatPolicy(
urls,
threatProtection.policy,
{ teamId: req.auth.team_id },
);
if (blocked.length > 0) {
- // Blocked domains whose decision consulted the classifier (fresh or
- // cached verdict) bill the scan fee (+2 per scanned domain) even
- // though they will never be scraped β€” the scan already happened.
- // Allowed URLs are not billed here: their scrape jobs re-check the
- // cached verdict and bill there.
- const blockedDecisionsByDomain = new Map(
- blocked.map(x => [x.domain, x.decision]),
- );
+ // Consulted decisions bill the scan fee (+2 per unique scanned URL) β€”
+ // the scans already happened. With ignoreInvalidURLs the allowed URLs
+ // proceed to scrape jobs that bill their own scans, so only blocked
+ // ones bill here; when the whole request is rejected below, no scrape
+ // jobs will ever run, so every scanned URL bills here.
const threatScanCredits = calculateThreatScanCredits(
- blockedDecisionsByDomain.values(),
+ req.body.ignoreInvalidURLs
+ ? blocked.map(x => x.decision)
+ : decisionsByUrl.values(),
);
if (threatScanCredits > 0) {
billTeam(
@@ -200,10 +199,7 @@ export async function batchScrapeController(
unnormalizedURLs = keptUnnormalized;
} else {
const first = blocked[0];
- const error = new UnsafeDomainBlockedError(
- first.domain,
- first.decision,
- );
+ const error = new UnsafeDomainBlockedError(first.url, first.decision);
return res.status(403).json({
success: false,
code: error.code,
diff --git a/apps/api/src/controllers/v1/crawl.ts b/apps/api/src/controllers/v1/crawl.ts
index 9c2c8702d..d813648e9 100644
--- a/apps/api/src/controllers/v1/crawl.ts
+++ b/apps/api/src/controllers/v1/crawl.ts
@@ -30,9 +30,8 @@ import {
import { logRequest } from "../../services/logging/log_job";
import { getScrapeZDR } from "../../lib/zdr-helpers";
import { resolveThreatProtection } from "../../lib/threat-protection/request";
-import { checkDomain } from "../../lib/threat-protection";
+import { checkUrl } from "../../lib/threat-protection";
import { UnsafeDomainBlockedError } from "../../lib/threat-protection/error";
-import { normalizeDomain } from "../../lib/threat-protection/verdict";
import { calculateThreatScanCredits } from "../../lib/scrape-billing";
import { billTeam } from "../../services/billing/credit_billing";
@@ -70,8 +69,7 @@ export async function crawlController(
// Threat protection: check the seed URL before kicking off the crawl.
if (threatProtection.policy) {
- const seedDomain = normalizeDomain(req.body.url);
- const decision = await checkDomain(seedDomain, threatProtection.policy, {
+ const decision = await checkUrl(req.body.url, threatProtection.policy, {
teamId: req.auth.team_id,
});
if (!decision.allowed) {
@@ -92,7 +90,7 @@ export async function crawlController(
);
});
}
- const error = new UnsafeDomainBlockedError(seedDomain, decision);
+ const error = new UnsafeDomainBlockedError(req.body.url, decision);
return res.status(403).json({
success: false,
code: error.code,
diff --git a/apps/api/src/controllers/v1/extract.ts b/apps/api/src/controllers/v1/extract.ts
index 6662f67ba..b432706cc 100644
--- a/apps/api/src/controllers/v1/extract.ts
+++ b/apps/api/src/controllers/v1/extract.ts
@@ -157,16 +157,16 @@ export async function extractController(
});
}
if (threatProtection.policy && (req.body.urls?.length ?? 0) > 0) {
- const { blocked, decisionsByDomain } = await checkUrlsAgainstThreatPolicy(
+ const { blocked, decisionsByUrl } = await checkUrlsAgainstThreatPolicy(
req.body.urls ?? [],
threatProtection.policy,
{ teamId: req.auth.team_id },
);
- // Every consulted decision (fresh or cached provider verdict) is a
- // billable scan (+2 per scanned domain) β€” including when the request is
- // rejected below: the scans already happened.
+ // Consulted decisions bill the scan fee (+2 per unique scanned URL) β€”
+ // including when the request is rejected below: the scans already
+ // happened.
const threatScanCredits = calculateThreatScanCredits(
- decisionsByDomain.values(),
+ decisionsByUrl.values(),
);
if (threatScanCredits > 0) {
billTeam(
@@ -186,12 +186,10 @@ export async function extractController(
invalidURLs.push(...blocked.map(x => x.url));
} else {
const first = blocked[0];
- const error = new UnsafeDomainBlockedError(
- first.domain,
- first.decision,
- );
+ const error = new UnsafeDomainBlockedError(first.url, first.decision);
return res.status(403).json({
success: false,
+ code: error.code,
error: error.message,
});
}
diff --git a/apps/api/src/controllers/v1/map.ts b/apps/api/src/controllers/v1/map.ts
index 93aa6895e..35aefb53d 100644
--- a/apps/api/src/controllers/v1/map.ts
+++ b/apps/api/src/controllers/v1/map.ts
@@ -35,7 +35,6 @@ import {
checkUrlsAgainstThreatPolicy,
resolveThreatProtection,
} from "../../lib/threat-protection/request";
-import { normalizeDomain } from "../../lib/threat-protection/verdict";
import { calculateThreatScanCredits } from "../../lib/scrape-billing";
configDotenv();
@@ -485,19 +484,19 @@ export async function mapController(
}
}
- // Threat protection: remove links on blocked domains from the returned
- // URL list entirely. Every consulted decision (fresh or cached provider
- // verdict) is a billable scan (+2 per scanned domain).
+ // Threat protection: remove blocked links from the returned URL list
+ // entirely. Checks are URL-level; scan fees bill +2 per unique scanned
+ // URL (see calculateThreatScanCredits).
let threatScanCredits = 0;
if (threatProtection.policy && result.links.length > 0) {
- const { decisionsByDomain } = await checkUrlsAgainstThreatPolicy(
+ const { decisionsByUrl } = await checkUrlsAgainstThreatPolicy(
result.links,
threatProtection.policy,
{ teamId: req.auth.team_id },
);
- threatScanCredits = calculateThreatScanCredits(decisionsByDomain.values());
+ threatScanCredits = calculateThreatScanCredits(decisionsByUrl.values());
result.links = result.links.filter(x => {
- const decision = decisionsByDomain.get(normalizeDomain(x));
+ const decision = decisionsByUrl.get(x);
return decision === undefined || decision.allowed;
});
}
diff --git a/apps/api/src/controllers/v1/types.ts b/apps/api/src/controllers/v1/types.ts
index 7e0db4d88..5b0a925c5 100644
--- a/apps/api/src/controllers/v1/types.ts
+++ b/apps/api/src/controllers/v1/types.ts
@@ -1139,6 +1139,7 @@ export interface URLTrace {
export interface ExtractResponse {
success: boolean;
+ code?: ErrorCodes;
error?: string;
data?: any;
scrape_id?: string;
diff --git a/apps/api/src/controllers/v2/agent.ts b/apps/api/src/controllers/v2/agent.ts
index 24b2572f6..83f17c0a0 100644
--- a/apps/api/src/controllers/v2/agent.ts
+++ b/apps/api/src/controllers/v2/agent.ts
@@ -71,22 +71,18 @@ export async function agentController(
});
}
if (threatProtection.policy && (req.body.urls?.length ?? 0) > 0) {
- const { blocked } = await checkUrlsAgainstThreatPolicy(
+ const { blocked, decisionsByUrl } = await checkUrlsAgainstThreatPolicy(
req.body.urls ?? [],
threatProtection.policy,
{ teamId: req.auth.team_id },
);
if (blocked.length > 0) {
- // Blocked domains whose decision consulted the classifier (fresh or
- // cached verdict) bill the scan fee (+2 per scanned domain) even
- // though the request is rejected β€” the scan already happened. Allowed
- // start URLs are not billed here: the agent's API-driven scrapes
- // re-check the policy in the scrape pipeline and bill there.
- const blockedDecisionsByDomain = new Map(
- blocked.map(x => [x.domain, x.decision]),
- );
+ // The whole request is rejected below, so no agent job will ever run
+ // to bill the allowed start URLs' scans β€” every consulted decision
+ // (allowed and blocked) bills its scan fee here (+2 per unique
+ // scanned URL): the scans already happened.
const threatScanCredits = calculateThreatScanCredits(
- blockedDecisionsByDomain.values(),
+ decisionsByUrl.values(),
);
if (threatScanCredits > 0) {
billTeam(
@@ -102,9 +98,10 @@ export async function agentController(
});
}
const first = blocked[0];
- const error = new UnsafeDomainBlockedError(first.domain, first.decision);
+ const error = new UnsafeDomainBlockedError(first.url, first.decision);
return res.status(403).json({
success: false,
+ code: error.code,
error: error.message,
});
}
diff --git a/apps/api/src/controllers/v2/batch-scrape.ts b/apps/api/src/controllers/v2/batch-scrape.ts
index 5d74d8894..687b2ded2 100644
--- a/apps/api/src/controllers/v2/batch-scrape.ts
+++ b/apps/api/src/controllers/v2/batch-scrape.ts
@@ -179,22 +179,21 @@ export async function batchScrapeController(
// redirect) is still blocked in the scrape pipeline and its job document
// gets the unsafe_domain_blocked error.
if (threatProtection.policy) {
- const { blocked } = await checkUrlsAgainstThreatPolicy(
+ const { blocked, decisionsByUrl } = await checkUrlsAgainstThreatPolicy(
urls,
threatProtection.policy,
{ teamId: req.auth.team_id },
);
if (blocked.length > 0) {
- // Blocked domains whose decision consulted the classifier (fresh or
- // cached verdict) bill the scan fee (+2 per scanned domain) even
- // though they will never be scraped β€” the scan already happened.
- // Allowed URLs are not billed here: their scrape jobs re-check the
- // cached verdict and bill there.
- const blockedDecisionsByDomain = new Map(
- blocked.map(x => [x.domain, x.decision]),
- );
+ // Consulted decisions bill the scan fee (+2 per unique scanned URL) β€”
+ // the scans already happened. With ignoreInvalidURLs the allowed URLs
+ // proceed to scrape jobs that bill their own scans, so only blocked
+ // ones bill here; when the whole request is rejected below, no scrape
+ // jobs will ever run, so every scanned URL bills here.
const threatScanCredits = calculateThreatScanCredits(
- blockedDecisionsByDomain.values(),
+ req.body.ignoreInvalidURLs
+ ? blocked.map(x => x.decision)
+ : decisionsByUrl.values(),
);
if (
threatScanCredits > 0 &&
@@ -228,10 +227,7 @@ export async function batchScrapeController(
unnormalizedURLs = keptUnnormalized;
} else {
const first = blocked[0];
- const error = new UnsafeDomainBlockedError(
- first.domain,
- first.decision,
- );
+ const error = new UnsafeDomainBlockedError(first.url, first.decision);
return res.status(403).json({
success: false,
code: error.code,
diff --git a/apps/api/src/controllers/v2/crawl.ts b/apps/api/src/controllers/v2/crawl.ts
index cb07fb6ca..4dea44fc0 100644
--- a/apps/api/src/controllers/v2/crawl.ts
+++ b/apps/api/src/controllers/v2/crawl.ts
@@ -32,9 +32,8 @@ import {
import { logRequest } from "../../services/logging/log_job";
import { getScrapeZDR } from "../../lib/zdr-helpers";
import { resolveThreatProtection } from "../../lib/threat-protection/request";
-import { checkDomain } from "../../lib/threat-protection";
+import { checkUrl } from "../../lib/threat-protection";
import { UnsafeDomainBlockedError } from "../../lib/threat-protection/error";
-import { normalizeDomain } from "../../lib/threat-protection/verdict";
import { calculateThreatScanCredits } from "../../lib/scrape-billing";
import { billTeam } from "../../services/billing/credit_billing";
@@ -74,8 +73,7 @@ export async function crawlController(
// Blocked seed => request-level error. Discovered links are checked during
// link discovery in the workers (blocked ones are silently skipped).
if (threatProtection.policy) {
- const seedDomain = normalizeDomain(req.body.url);
- const decision = await checkDomain(seedDomain, threatProtection.policy, {
+ const decision = await checkUrl(req.body.url, threatProtection.policy, {
teamId: req.auth.team_id,
});
if (!decision.allowed) {
@@ -96,7 +94,7 @@ export async function crawlController(
);
});
}
- const error = new UnsafeDomainBlockedError(seedDomain, decision);
+ const error = new UnsafeDomainBlockedError(req.body.url, decision);
return res.status(403).json({
success: false,
code: error.code,
diff --git a/apps/api/src/controllers/v2/extract.ts b/apps/api/src/controllers/v2/extract.ts
index 6bdbf8090..b1d536adc 100644
--- a/apps/api/src/controllers/v2/extract.ts
+++ b/apps/api/src/controllers/v2/extract.ts
@@ -98,16 +98,16 @@ export async function extractController(
});
}
if (threatProtection.policy && (req.body.urls?.length ?? 0) > 0) {
- const { blocked, decisionsByDomain } = await checkUrlsAgainstThreatPolicy(
+ const { blocked, decisionsByUrl } = await checkUrlsAgainstThreatPolicy(
req.body.urls ?? [],
threatProtection.policy,
{ teamId: req.auth.team_id },
);
- // Every consulted decision (fresh or cached provider verdict) is a
- // billable scan (+2 per scanned domain) β€” including when the request is
- // rejected below: the scans already happened.
+ // Consulted decisions bill the scan fee (+2 per unique scanned URL) β€”
+ // including when the request is rejected below: the scans already
+ // happened.
const threatScanCredits = calculateThreatScanCredits(
- decisionsByDomain.values(),
+ decisionsByUrl.values(),
);
if (threatScanCredits > 0) {
billTeam(
@@ -127,12 +127,10 @@ export async function extractController(
invalidURLs.push(...blocked.map(x => x.url));
} else {
const first = blocked[0];
- const error = new UnsafeDomainBlockedError(
- first.domain,
- first.decision,
- );
+ const error = new UnsafeDomainBlockedError(first.url, first.decision);
return res.status(403).json({
success: false,
+ code: error.code,
error: error.message,
});
}
diff --git a/apps/api/src/controllers/v2/map.ts b/apps/api/src/controllers/v2/map.ts
index cc0203bfe..7cbbe1761 100644
--- a/apps/api/src/controllers/v2/map.ts
+++ b/apps/api/src/controllers/v2/map.ts
@@ -20,7 +20,6 @@ import {
checkUrlsAgainstThreatPolicy,
resolveThreatProtection,
} from "../../lib/threat-protection/request";
-import { normalizeDomain } from "../../lib/threat-protection/verdict";
import { calculateThreatScanCredits } from "../../lib/scrape-billing";
configDotenv();
@@ -210,19 +209,19 @@ export async function mapController(
}
}
- // Threat protection: remove links on blocked domains from the returned
- // URL list entirely. Every consulted decision (fresh or cached provider
- // verdict) is a billable scan (+2 per scanned domain).
+ // Threat protection: remove blocked links from the returned URL list
+ // entirely. Checks are URL-level; scan fees bill +2 per unique scanned
+ // URL (see calculateThreatScanCredits).
let threatScanCredits = 0;
if (threatProtection.policy && result.mapResults.length > 0) {
- const { decisionsByDomain } = await checkUrlsAgainstThreatPolicy(
+ const { decisionsByUrl } = await checkUrlsAgainstThreatPolicy(
result.mapResults.map(x => x.url),
threatProtection.policy,
{ teamId: req.auth.team_id },
);
- threatScanCredits = calculateThreatScanCredits(decisionsByDomain.values());
+ threatScanCredits = calculateThreatScanCredits(decisionsByUrl.values());
result.mapResults = result.mapResults.filter(x => {
- const decision = decisionsByDomain.get(normalizeDomain(x.url));
+ const decision = decisionsByUrl.get(x.url);
return decision === undefined || decision.allowed;
});
}
diff --git a/apps/api/src/controllers/v2/types.ts b/apps/api/src/controllers/v2/types.ts
index 37b95e62a..9fab09851 100644
--- a/apps/api/src/controllers/v2/types.ts
+++ b/apps/api/src/controllers/v2/types.ts
@@ -1385,6 +1385,7 @@ export interface URLTrace {
export interface ExtractResponse {
success: boolean;
+ code?: ErrorCodes;
error?: string;
data?: any;
scrape_id?: string;
diff --git a/apps/api/src/lib/crawl-redis.ts b/apps/api/src/lib/crawl-redis.ts
index 697fb774c..eb9d8cb7a 100644
--- a/apps/api/src/lib/crawl-redis.ts
+++ b/apps/api/src/lib/crawl-redis.ts
@@ -75,9 +75,14 @@ export async function recordRobotsBlocked(crawlId: string, url: string) {
/**
* Records a URL that was silently skipped during crawl link discovery because
- * its domain was blocked by the team's threat protection policy. The crawl
- * continues without it; the record (url -> full ThreatDecision JSON) is kept
- * for the security-logging layer to read.
+ * it was blocked by the team's threat protection policy. The crawl continues
+ * without it; the record (canonical url -> full ThreatDecision JSON) is
+ * crawl bookkeeping, and doubles as the crawl-scoped billing dedup for
+ * blocked discoveries: returns true only for the first record of a URL
+ * within this crawl (HSETNX), so a blocked link that many pages point at
+ * (e.g. in a site-wide nav) bills its scan fee once per crawl, not once per
+ * page that rediscovered it. Callers key by the decision's canonical URL so
+ * raw spelling variants dedupe together, matching billing.
*
* ZDR posture: this hash follows the same rules as the rest of the transient
* crawl bookkeeping in this file (crawl doc, visited sets, robots_blocked) β€”
@@ -89,10 +94,15 @@ export async function recordThreatBlocked(
crawlId: string,
url: string,
decision: unknown,
-) {
+): Promise<boolean> {
const key = "crawl:" + crawlId + ":threat_blocked";
- await redisEvictConnection.hset(key, url, JSON.stringify(decision));
+ const isNew = await redisEvictConnection.hsetnx(
+ key,
+ url,
+ JSON.stringify(decision),
+ );
await redisEvictConnection.expire(key, 24 * 60 * 60);
+ return isNew === 1;
}
export async function markCrawlActive(id: string) {
diff --git a/apps/api/src/lib/scrape-billing.test.ts b/apps/api/src/lib/scrape-billing.test.ts
index 68d80fb5d..5103995c6 100644
--- a/apps/api/src/lib/scrape-billing.test.ts
+++ b/apps/api/src/lib/scrape-billing.test.ts
@@ -124,9 +124,14 @@ describe("calculateCreditsToBeBilled", () => {
// Threat protection scan fees (ENG-4985)
// =========================================
-const consulted = (allowed = true): ThreatDecision => ({
+const consulted = (
+ allowed = true,
+ url = "http://scanned.example/",
+): ThreatDecision => ({
allowed,
rule: allowed ? "default-allow" : "risk-score",
+ url,
+ domain: new URL(url).hostname,
providerConsulted: true,
verdict: {
provider: "google-web-risk",
@@ -144,6 +149,8 @@ const localOnly = (
): ThreatDecision => ({
allowed,
rule,
+ url: "http://local.example/",
+ domain: "local.example",
providerConsulted: false,
verdict: null,
mode: "normal",
@@ -175,9 +182,42 @@ describe("calculateThreatScanCredits", () => {
expect(calculateThreatScanCredits([])).toBe(0);
});
- it("bills +2 per consulted decision", () => {
+ it("bills +2 per unique consulted URL", () => {
expect(calculateThreatScanCredits([consulted()])).toBe(2);
- expect(calculateThreatScanCredits([consulted(), consulted()])).toBe(4);
+ expect(
+ calculateThreatScanCredits([
+ consulted(true, "http://a.example/"),
+ consulted(true, "http://b.example/"),
+ ]),
+ ).toBe(4);
+ });
+
+ it("bills every distinct URL, including URLs sharing a domain", () => {
+ expect(
+ calculateThreatScanCredits([
+ consulted(true, "http://one.example/a"),
+ consulted(true, "http://one.example/b"),
+ consulted(false, "http://one.example/c"),
+ ]),
+ ).toBe(6);
+ });
+
+ it("bills a URL once no matter how many decisions repeat it", () => {
+ expect(
+ calculateThreatScanCredits([
+ consulted(true, "http://one.example/a"),
+ consulted(true, "http://one.example/a"),
+ ]),
+ ).toBe(2);
+ });
+
+ it("bills legacy decisions without a url individually (mid-rollout jobs)", () => {
+ const legacy = () => {
+ const decision = consulted();
+ delete (decision as Partial<ThreatDecision>).url;
+ return decision;
+ };
+ expect(calculateThreatScanCredits([legacy(), legacy()])).toBe(4);
});
it("bills consulted decisions regardless of the allow/block outcome", () => {
@@ -201,11 +241,11 @@ describe("calculateThreatScanCredits", () => {
).toBe(0);
});
- it("sums mixed decisions", () => {
+ it("sums mixed decisions across URLs", () => {
expect(
calculateThreatScanCredits([
- consulted(),
- consulted(false),
+ consulted(true, "http://a.example/"),
+ consulted(false, "http://b.example/"),
localOnly("blacklist", false),
]),
).toBe(4);
@@ -222,15 +262,30 @@ describe("calculateCreditsToBeBilled β€” threat protection scan fees", () => {
).toBe(3);
});
- it("bills each consulted decision on a redirect (two domains scanned)", async () => {
+ it("bills each scanned URL on a redirect β€” including same-domain", async () => {
expect(
await billWithDecisions({
document: successDocument,
- threatDecisions: [consulted(), consulted()],
+ threatDecisions: [
+ consulted(true, "http://one.example/"),
+ consulted(true, "http://one.example/landing"),
+ ],
}),
).toBe(5);
});
+ it("bills once when the redirect re-check resolves to the same URL", async () => {
+ expect(
+ await billWithDecisions({
+ document: successDocument,
+ threatDecisions: [
+ consulted(true, "http://one.example/"),
+ consulted(true, "http://one.example/"),
+ ],
+ }),
+ ).toBe(3);
+ });
+
it("adds nothing for local-only decisions on success", async () => {
expect(
await billWithDecisions({
@@ -262,8 +317,8 @@ describe("calculateCreditsToBeBilled β€” threat protection scan fees", () => {
});
it("does not double-bill when the error decision is also in the decisions array", async () => {
- const initial = consulted();
- const redirectBlock = consulted(false);
+ const initial = consulted(true, "http://a.example/");
+ const redirectBlock = consulted(false, "http://b.example/");
expect(
await billWithDecisions({
document: null,
diff --git a/apps/api/src/lib/scrape-billing.ts b/apps/api/src/lib/scrape-billing.ts
index bef1ebdc9..7350715ea 100644
--- a/apps/api/src/lib/scrape-billing.ts
+++ b/apps/api/src/lib/scrape-billing.ts
@@ -25,25 +25,36 @@ const redactPIICostBonus = 4;
// Each additional PDF page also gets redacted through fire-privacy, so
// the per-page surcharge mirrors the +4 base β€” same tier as lockdown.
const redactPIIPdfPageCostBonus = 4;
-// Threat protection domain scans: +2 per scanned domain in "normal" mode
-// (Google Web Risk). A "scan" is any ThreatDecision with providerConsulted
-// set β€” +2 per consulted verdict. Checks deduplicated within one request/job
-// (e.g. a scrape and its same-domain redirect re-check) share a single
-// decision and therefore bill once; verdicts are never reused across
-// requests (no verdict cache β€” ZDR). Local-only decisions (whitelist/
-// blacklist/blocked-tld, mode off, provider failure) never bill.
+// Threat protection scans: +2 per scanned URL in "normal" mode (Google Web
+// Risk). Checks are URL-level and so is the billable unit: consulted
+// decisions bill once per unique canonical `decision.url` within one billing
+// scope β€” a scrape and its same-URL re-check share one fee, while a crawl of
+// N pages bills N scans (each page job is its own scope). Verdicts are never
+// reused across requests (no verdict cache β€” ZDR). Local-only decisions
+// (whitelist/blacklist/blocked-tld, mode off, provider failure) never bill.
const threatScanCost = 2;
/**
* Sums the scan fees for a set of threat protection decisions. Only decisions
- * that consulted the provider bill; the fee is +2 per scanned domain.
+ * that consulted the provider bill; the fee is +2 per unique scanned
+ * canonical URL across the given decisions.
*/
export function calculateThreatScanCredits(
decisions: Iterable<ThreatDecision>,
): number {
+ const billedUrls = new Set<string>();
let credits = 0;
for (const decision of decisions) {
if (!decision.providerConsulted) continue;
+ // Decisions serialized by a pre-URL-level deploy have no `url`; bill
+ // them individually (the old per-decision behavior) rather than letting
+ // them all collapse onto one `undefined` key.
+ if (decision.url === undefined) {
+ credits += threatScanCost;
+ continue;
+ }
+ if (billedUrls.has(decision.url)) continue;
+ billedUrls.add(decision.url);
credits += threatScanCost;
}
return credits;
@@ -60,7 +71,7 @@ export async function calculateCreditsToBeBilled(
dataLayer?: DataLayerScrapeMetadata,
// Threat protection decisions for this scrape (initial + redirect checks,
// in order). Each decision with `providerConsulted` bills a scan fee (+2
- // per scanned domain) on top of the scrape's own cost β€” on both success
+ // per unique scanned URL) on top of the scrape's own cost β€” on both success
// and failure (a scrape blocked by threat protection still consulted the
// classifier). For scrapes blocked by threat protection, the
// UnsafeDomainBlockedError in `error` also carries its decision, which is
diff --git a/apps/api/src/lib/threat-protection/check-domain.test.ts b/apps/api/src/lib/threat-protection/check-url.test.ts
similarity index 62%
rename from apps/api/src/lib/threat-protection/check-domain.test.ts
rename to apps/api/src/lib/threat-protection/check-url.test.ts
index e0c0a2872..b699cf7ef 100644
--- a/apps/api/src/lib/threat-protection/check-domain.test.ts
+++ b/apps/api/src/lib/threat-protection/check-url.test.ts
@@ -1,7 +1,7 @@
import http from "http";
import { AddressInfo } from "net";
-// checkDomain is enforcement-only: it emits/exports no security events, so
+// checkUrl is enforcement-only: it emits/exports no security events, so
// there are no event sinks to stub here.
// The Web Risk threat-list store lives on the durable Redis connection β€”
// swap in an in-memory fake. (fake-redis.ts has no runtime imports, so the
@@ -16,7 +16,7 @@ vi.mock("../../services/queue-service", async () => {
import { config } from "../../config";
import {
- checkDomain,
+ checkUrl,
THREAT_PROTECTION_POLICY_DEFAULTS,
ThreatCheckDedup,
ThreatProtectionPolicy,
@@ -38,13 +38,16 @@ function policy(
};
}
-// The mock provider: a flagged fixture domain in the MALWARE list, served
-// through the Update API endpoints (computeDiff for the local list sync,
-// hashes:search for prefix-hit confirmation).
+// The mock provider: a flagged fixture domain plus a flagged single URL on an
+// otherwise-clean domain, both in the MALWARE list, served through the Update
+// API endpoints (computeDiff for the local list sync, hashes:search for
+// prefix-hit confirmation).
const RISKY_DOMAIN = "threat-risky.example";
+const RISKY_URL = "http://threat-mixed.example/downloads/malware-installer.exe";
const db = new WebRiskMockDatabase();
db.addRiskyDomain(RISKY_DOMAIN, "MALWARE");
+db.addRiskyUrl(RISKY_URL, "MALWARE");
const counters = createWebRiskMockCounters();
const webRiskHandler = createWebRiskMockHandler(db, counters);
@@ -96,18 +99,20 @@ beforeEach(() => {
failHashesSearches = 0;
});
-const riskyHits = () => counters.hashesSearchRequestsForDomain(RISKY_DOMAIN);
+const riskyHits = () => counters.hashesSearchRequestsForTarget(RISKY_DOMAIN);
-describe("checkDomain", () => {
+describe("checkUrl", () => {
it("allows immediately when mode is off, with no provider call", async () => {
const before = counters.hashesSearchRequests;
- const decision = await checkDomain("example.com", policy({ mode: "off" }), {
+ const decision = await checkUrl("example.com", policy({ mode: "off" }), {
teamId: "team-1",
});
expect(decision).toEqual({
allowed: true,
rule: "default-allow",
+ url: "http://example.com/",
+ domain: "example.com",
providerConsulted: false,
verdict: null,
mode: "off",
@@ -117,8 +122,8 @@ describe("checkDomain", () => {
it("skips the provider scan when a local rule is decisive", async () => {
const before = counters.hashesSearchRequests;
- const decision = await checkDomain(
- "cdn.blocked.com",
+ const decision = await checkUrl(
+ "https://cdn.blocked.com/some/page",
policy({ blacklist: ["blocked.com"] }),
{ teamId: "team-1" },
);
@@ -126,6 +131,7 @@ describe("checkDomain", () => {
expect(decision).toMatchObject({
allowed: false,
rule: "blacklist",
+ domain: "cdn.blocked.com",
providerConsulted: false,
verdict: null,
});
@@ -134,13 +140,14 @@ describe("checkDomain", () => {
it("consults the provider and blocks a flagged domain (fresh scan)", async () => {
const before = riskyHits();
- const decision = await checkDomain(RISKY_DOMAIN.toUpperCase(), policy(), {
+ const decision = await checkUrl(RISKY_DOMAIN.toUpperCase(), policy(), {
teamId: "team-1",
});
expect(decision).toMatchObject({
allowed: false,
rule: "risk-score",
+ domain: RISKY_DOMAIN,
providerConsulted: true,
mode: "normal",
});
@@ -156,13 +163,59 @@ describe("checkDomain", () => {
expect(riskyHits()).toBe(before + 1);
});
- it("resolves clean domains locally with zero Google calls", async () => {
+ it("blocks every URL on a flagged domain (host-suffix expressions)", async () => {
+ const decision = await checkUrl(
+ `https://${RISKY_DOMAIN}/any/path?query=1`,
+ policy(),
+ { teamId: "team-1" },
+ );
+
+ expect(decision).toMatchObject({
+ allowed: false,
+ rule: "risk-score",
+ domain: RISKY_DOMAIN,
+ providerConsulted: true,
+ });
+ });
+
+ it("blocks a flagged URL while keeping its domain's other URLs clean", async () => {
+ const flagged = await checkUrl(RISKY_URL, policy(), { teamId: "team-1" });
+ const sibling = await checkUrl(
+ "http://threat-mixed.example/downloads/press-kit.zip",
+ policy(),
+ { teamId: "team-1" },
+ );
+ const root = await checkUrl("http://threat-mixed.example/", policy(), {
+ teamId: "team-1",
+ });
+
+ expect(flagged).toMatchObject({
+ allowed: false,
+ rule: "risk-score",
+ domain: "threat-mixed.example",
+ providerConsulted: true,
+ });
+ expect(flagged.verdict).toMatchObject({ riskScore: 100 });
+ expect(sibling).toMatchObject({
+ allowed: true,
+ rule: "default-allow",
+ providerConsulted: true,
+ });
+ expect(root).toMatchObject({ allowed: true, rule: "default-allow" });
+ });
+
+ it("resolves clean URLs locally with zero Google calls", async () => {
const before = counters.hashesSearchRequests;
- const decision = await checkDomain("safe.example", policy(), {});
+ const decision = await checkUrl(
+ "https://safe.example/pricing",
+ policy(),
+ {},
+ );
expect(decision).toMatchObject({
allowed: true,
rule: "default-allow",
+ domain: "safe.example",
providerConsulted: true,
});
expect(decision.verdict?.fromCache).toBe(false);
@@ -172,8 +225,8 @@ describe("checkDomain", () => {
it("re-scans on a second lookup without a dedup handle (no verdict cache)", async () => {
const before = riskyHits();
- const first = await checkDomain(RISKY_DOMAIN, policy(), {});
- const second = await checkDomain(RISKY_DOMAIN, policy(), {});
+ const first = await checkUrl(RISKY_DOMAIN, policy(), {});
+ const second = await checkUrl(RISKY_DOMAIN, policy(), {});
expect(first).toMatchObject({ allowed: false, providerConsulted: true });
expect(second).toMatchObject({ allowed: false, providerConsulted: true });
@@ -186,35 +239,45 @@ describe("checkDomain", () => {
const before = riskyHits();
const dedup: ThreatCheckDedup = new Map();
- // Concurrent + sequential re-checks of the same domain in one request.
+ // Concurrent + sequential re-checks of the same URL in one request.
const [first, second] = await Promise.all([
- checkDomain(RISKY_DOMAIN, policy(), { dedup }),
- checkDomain(RISKY_DOMAIN, policy(), { dedup }),
+ checkUrl(RISKY_DOMAIN, policy(), { dedup }),
+ checkUrl(RISKY_DOMAIN, policy(), { dedup }),
]);
- const third = await checkDomain(`${RISKY_DOMAIN}.`, policy(), { dedup });
+ const third = await checkUrl(`http://${RISKY_DOMAIN}./`, policy(), {
+ dedup,
+ });
- // Same decision object β†’ a single scan β†’ a single billable decision.
+ // Same decision object β†’ a single scan β†’ a single consulted decision.
expect(second).toBe(first);
- expect(third).toBe(first); // normalization applies before dedup
+ expect(third).toBe(first); // URL canonicalization applies before dedup
expect(riskyHits()).toBe(before + 1);
});
- it("scans each distinct domain in a dedup scope separately", async () => {
+ it("scans distinct URLs in a dedup scope separately (same domain included)", async () => {
const dedup: ThreatCheckDedup = new Map();
const before = riskyHits();
- const clean = await checkDomain("safe.example", policy(), { dedup });
- const risky = await checkDomain(RISKY_DOMAIN, policy(), { dedup });
+ const clean = await checkUrl("safe.example", policy(), { dedup });
+ const risky = await checkUrl(RISKY_DOMAIN, policy(), { dedup });
+ const riskyPath = await checkUrl(`http://${RISKY_DOMAIN}/page`, policy(), {
+ dedup,
+ });
expect(clean.allowed).toBe(true);
expect(risky.allowed).toBe(false);
- expect(riskyHits()).toBe(before + 1);
+ expect(riskyPath.allowed).toBe(false);
+ expect(riskyPath).not.toBe(risky); // different canonical URLs
+ // Two independent scans of the same domain: each one confirms the
+ // domain's flagged root-expression prefix, and each is its own billable
+ // scan (billing dedups on decision.url β€” see calculateThreatScanCredits).
+ expect(riskyHits()).toBe(before + 2);
});
it("retries once and succeeds when the first confirmation attempt fails", async () => {
failHashesSearches = 1; // exactly the first hashes:search attempt 503s
- const decision = await checkDomain(RISKY_DOMAIN, policy(), {});
+ const decision = await checkUrl(RISKY_DOMAIN, policy(), {});
expect(decision).toMatchObject({
allowed: false,
@@ -227,7 +290,7 @@ describe("checkDomain", () => {
it("fails closed when confirmation is down and failurePolicy is closed", async () => {
failHashesSearches = Infinity;
- const decision = await checkDomain(
+ const decision = await checkUrl(
RISKY_DOMAIN,
policy({ failurePolicy: "closed" }),
{ teamId: "team-1" },
@@ -236,6 +299,8 @@ describe("checkDomain", () => {
expect(decision).toEqual({
allowed: false,
rule: "provider-failure",
+ url: `http://${RISKY_DOMAIN}/`,
+ domain: RISKY_DOMAIN,
providerConsulted: false,
verdict: null,
mode: "normal",
@@ -245,7 +310,7 @@ describe("checkDomain", () => {
it("fails open when confirmation is down and failurePolicy is open", async () => {
failHashesSearches = Infinity;
- const decision = await checkDomain(
+ const decision = await checkUrl(
RISKY_DOMAIN,
policy({ failurePolicy: "open" }),
{},
@@ -261,16 +326,20 @@ describe("checkDomain", () => {
});
describe("UnsafeDomainBlockedError", () => {
- it("carries the decision and the unsafe_domain_blocked code", async () => {
- const decision = await checkDomain(
- "bad.example",
+ it("carries the URL, domain and decision with the unsafe_domain_blocked code", async () => {
+ const decision = await checkUrl(
+ "https://bad.example/landing",
policy({ blacklist: ["bad.example"] }),
{},
);
- const error = new UnsafeDomainBlockedError("bad.example", decision);
+ const error = new UnsafeDomainBlockedError(
+ "https://bad.example/landing",
+ decision,
+ );
expect(error.code).toBe("unsafe_domain_blocked");
expect(error.name).toBe("UnsafeDomainBlockedError");
+ expect(error.url).toBe("https://bad.example/landing");
expect(error.domain).toBe("bad.example");
expect(error.decision).toBe(decision);
expect(error.message).toContain("threat protection policy");
diff --git a/apps/api/src/lib/threat-protection/error.ts b/apps/api/src/lib/threat-protection/error.ts
index bc12f70c6..2ef5a42ee 100644
--- a/apps/api/src/lib/threat-protection/error.ts
+++ b/apps/api/src/lib/threat-protection/error.ts
@@ -1,29 +1,36 @@
import { ErrorCodes, TransportableError } from "../error";
import type { ThreatDecision } from "./types";
-// Error surfaced when threat protection blocks a domain. Wired into the shared
+// Error surfaced when threat protection blocks a URL. Wired into the shared
// TransportableError machinery (src/lib/error.ts + src/lib/error-serde.ts) so
// blocked scrapes surface as a clean, documented API error β€” both on sync
-// responses (`code: "unsafe_domain_blocked"`) and on crawl/batch job document
-// errors. The full ThreatDecision rides along in serialize() so the billing
-// and security-logging layers can read it even across the job queue.
+// responses (`code: "unsafe_domain_blocked"`, name kept for API stability
+// even though checks are URL-level) and on crawl/batch job document errors.
+// The full ThreatDecision rides along in serialize() so the billing layer can
+// read it even across the job queue.
export class UnsafeDomainBlockedError extends TransportableError {
+ /** Canonicalized host of the blocked URL (from the decision). */
+ public readonly domain: string;
+
constructor(
- public readonly domain: string,
+ /** The blocked URL (or bare domain, e.g. for a blocked crawl seed). */
+ public readonly url: string,
public readonly decision: ThreatDecision,
) {
super(
"unsafe_domain_blocked",
- `This domain (${domain}) is blocked by your organization's threat protection policy (rule: ${decision.rule}). ` +
+ `This URL (${url}) is blocked by your organization's threat protection policy (rule: ${decision.rule}). ` +
`If you believe this is a mistake, contact your organization administrator to adjust the policy (e.g. whitelist the domain).`,
);
this.name = "UnsafeDomainBlockedError";
+ this.domain = decision.domain;
}
serialize() {
return {
...super.serialize(),
+ url: this.url,
domain: this.domain,
decision: this.decision,
};
@@ -33,7 +40,14 @@ export class UnsafeDomainBlockedError extends TransportableError {
_code: ErrorCodes,
data: ReturnType<typeof this.prototype.serialize>,
) {
- const x = new UnsafeDomainBlockedError(data.domain, data.decision);
+ const x = new UnsafeDomainBlockedError(data.url ?? data.domain, {
+ ...data.decision,
+ // Jobs serialized by a pre-URL-level deploy carry decisions without
+ // `url`/`domain`; backfill both so billing dedup and error surfaces
+ // keep working mid-rollout.
+ url: data.decision.url ?? data.url ?? data.domain,
+ domain: data.decision.domain ?? data.domain,
+ });
x.stack = data.stack;
return x;
}
diff --git a/apps/api/src/lib/threat-protection/index.ts b/apps/api/src/lib/threat-protection/index.ts
index b5f5e739a..f38a87ff2 100644
--- a/apps/api/src/lib/threat-protection/index.ts
+++ b/apps/api/src/lib/threat-protection/index.ts
@@ -1,5 +1,6 @@
import { logger } from "../logger";
import { fetchGoogleWebRiskVerdict } from "./providers/google-web-risk";
+import { canonicalizeUrl } from "./providers/web-risk/canonicalize";
import type {
RawVerdict,
ThreatCheckDedup,
@@ -10,7 +11,7 @@ import type {
import { evaluatePolicy, localOnlyDecision, normalizeDomain } from "./verdict";
/**
- * Request context threaded into {@link checkDomain}. Enforcement-only: the
+ * Request context threaded into {@link checkUrl}. Enforcement-only: the
* feature no longer emits or exports security events (both the ClickHouse
* security log and the SIEM push were removed), so this carries just the
* request/job-scoped dedup handle plus the team id used for server-side
@@ -21,7 +22,7 @@ export interface ThreatCheckContext {
teamId?: string;
/**
* Request/job-scoped dedup handle (see {@link ThreatCheckDedup}). When set,
- * checkDomain() reuses the in-flight decision for a domain already checked
+ * checkUrl() reuses the in-flight decision for a URL already checked
* within this request instead of re-scanning it. Strictly in-memory and
* request-scoped β€” never persisted, never shared across requests (ZDR).
*/
@@ -29,22 +30,26 @@ export interface ThreatCheckContext {
}
// Public entry point for the threat protection core library (enterprise
-// domain risk blocking). Flow per domain:
+// URL risk blocking). Flow per URL:
// 1. mode "off" β†’ allow, no provider, no billing
-// 2. request-scoped dedup (ctx.dedup) β†’ a domain already checked within
+// 2. request-scoped dedup (ctx.dedup) β†’ a URL already checked within
// this request/job reuses the same in-flight decision
-// 3. local-only rules (whitelist/blacklist/blocked-tld) β†’ decide without a
-// provider call (no billing)
+// 3. local-only rules (whitelist/blacklist/blocked-tld, evaluated against
+// the URL's host) β†’ decide without a provider call (no billing)
// 4. provider ("normal" = Google Web Risk local hash-prefix database),
-// with a per-attempt timeout and one retry
+// with a per-attempt timeout and one retry. Lookups are URL-level:
+// host-suffix Γ— path-prefix expressions per the Safe Browsing spec, so
+// a listing that flags only a specific page is caught even when its
+// domain is otherwise clean.
// 5. evaluate the policy against the verdict; provider failure β†’ the org's
// failurePolicy decides (fail-open allows, fail-closed blocks)
// Any decision backed by a verdict sets providerConsulted, which drives
-// billing (+2 credits per scanned domain) in the enforcement layer. This
-// module performs no billing or pipeline integration itself.
+// billing in the enforcement layer (+2 credits per unique scanned URL per
+// billing scope β€” see calculateThreatScanCredits). This module performs no
+// billing or pipeline integration itself.
//
// ZDR boundary: verdicts are NEVER persisted β€” there is no cross-request
-// verdict cache (scrape-target domains must not be stored at rest). The only
+// verdict cache (scrape-target URLs must not be stored at rest). The only
// reuse of a decision is via the caller-provided, request-scoped in-memory
// dedup map. The org-config cache in ./store.ts is unaffected: it caches the
// org's own settings, not scrape-derived data.
@@ -55,7 +60,7 @@ export interface ThreatCheckContext {
// Policy evaluation helpers (evaluatePolicy, localOnlyDecision) are exported
// from ./verdict, and the shared contract types from ./types β€” import those
-// directly; index.ts only re-exports what checkDomain callers need.
+// directly; index.ts only re-exports what checkUrl callers need.
export { UnsafeDomainBlockedError } from "./error";
export * from "./types";
@@ -64,13 +69,13 @@ const PROVIDER_ATTEMPTS = 2; // 1 initial + 1 retry
/**
* Single mode→provider dispatch point. Every provider is a separate module
- * under ./providers exporting `fetch<X>Verdict(domain) β†’ RawVerdict`; this
+ * under ./providers exporting `fetch<X>Verdict(url) β†’ RawVerdict`; this
* switch is the only place that knows which mode maps to which classifier.
* Deliberately kept as a dispatch even with one live branch β€” future partner
* classifiers add a mode + a case here and nothing else changes.
*/
async function fetchProviderVerdict(
- domain: string,
+ url: string,
mode: Exclude<ThreatProtectionMode, "off">,
): Promise<RawVerdict> {
let lastError: unknown;
@@ -79,13 +84,13 @@ async function fetchProviderVerdict(
const signal = AbortSignal.timeout(PROVIDER_TIMEOUT_MS);
switch (mode) {
case "normal":
- return await fetchGoogleWebRiskVerdict(domain, { signal });
+ return await fetchGoogleWebRiskVerdict(url, { signal });
}
} catch (error) {
lastError = error;
logger.warn("Threat protection provider lookup failed", {
canonicalLog: "threat-protection/provider",
- domain,
+ url,
mode,
attempt,
error,
@@ -95,14 +100,14 @@ async function fetchProviderVerdict(
throw lastError;
}
-async function checkDomainFresh(
- normalized: string,
+async function checkUrlFresh(
+ canonicalUrl: string,
policy: ThreatProtectionPolicy,
ctx: ThreatCheckContext,
): Promise<ThreatDecision> {
- // Local rules first: when whitelist/blacklist/blocked-tld are decisive we
- // skip the paid provider scan entirely.
- const local = localOnlyDecision(normalized, policy);
+ // Local rules first: when whitelist/blacklist/blocked-tld are decisive
+ // (they match on the URL's host) we skip the paid provider scan entirely.
+ const local = localOnlyDecision(canonicalUrl, policy);
if (local !== null) {
return local;
}
@@ -110,7 +115,7 @@ async function checkDomainFresh(
let verdict: RawVerdict | null = null;
try {
verdict = await fetchProviderVerdict(
- normalized,
+ canonicalUrl,
policy.mode as Exclude<ThreatProtectionMode, "off">,
);
} catch {
@@ -119,12 +124,13 @@ async function checkDomainFresh(
verdict = null;
}
- const decision = evaluatePolicy(normalized, verdict, policy);
+ const decision = evaluatePolicy(canonicalUrl, verdict, policy);
if (!decision.allowed || decision.rule === "provider-failure") {
logger.info("Threat protection decision", {
canonicalLog: "threat-protection/check",
teamId: ctx.teamId,
- domain: normalized,
+ url: canonicalUrl,
+ domain: decision.domain,
mode: policy.mode,
allowed: decision.allowed,
rule: decision.rule,
@@ -138,32 +144,36 @@ async function checkDomainFresh(
}
/**
- * Classify a domain against an org's threat protection policy. Never throws:
+ * Classify a URL against an org's threat protection policy. Accepts full URLs
+ * or bare domains (a bare domain is checked as its root URL). Never throws:
* provider failures resolve through the policy's failurePolicy
- * ("provider-failure" rule). Callers bill +2 credits per scanned domain when
- * the returned decision has `providerConsulted` set.
+ * ("provider-failure" rule). Callers bill scan fees for decisions with
+ * `providerConsulted` set β€” +2 per unique scanned canonical URL, see
+ * calculateThreatScanCredits.
*
* When `ctx.dedup` is provided (a request/job-scoped map created by the call
- * site), repeated checks of the same domain within that scope share one
- * in-flight decision: one scan, one billable consulted verdict. There is
- * deliberately no cross-request or persisted verdict reuse (ZDR:
- * scrape-target domains are never stored at rest).
+ * site), repeated checks of the same URL within that scope share one
+ * in-flight decision: one scan, one consulted verdict. There is deliberately
+ * no cross-request or persisted verdict reuse (ZDR: scrape-target URLs are
+ * never stored at rest).
*
* Enforcement-only: no security event is emitted or exported for a scan
* (neither to a ClickHouse log nor to a SIEM destination β€” both were
* removed). There is no built-in audit trail.
*/
-export async function checkDomain(
- domain: string,
+export async function checkUrl(
+ url: string,
policy: ThreatProtectionPolicy,
ctx: ThreatCheckContext,
): Promise<ThreatDecision> {
- const normalized = normalizeDomain(domain);
+ const canonicalUrl = canonicalizeUrl(url);
if (policy.mode === "off") {
return {
allowed: true,
rule: "default-allow",
+ url: canonicalUrl,
+ domain: normalizeDomain(canonicalUrl),
providerConsulted: false,
verdict: null,
mode: "off",
@@ -171,14 +181,14 @@ export async function checkDomain(
}
if (ctx.dedup) {
- const existing = ctx.dedup.get(normalized);
+ const existing = ctx.dedup.get(canonicalUrl);
if (existing !== undefined) {
return existing;
}
- const pending = checkDomainFresh(normalized, policy, ctx);
- ctx.dedup.set(normalized, pending);
+ const pending = checkUrlFresh(canonicalUrl, policy, ctx);
+ ctx.dedup.set(canonicalUrl, pending);
return pending;
}
- return checkDomainFresh(normalized, policy, ctx);
+ return checkUrlFresh(canonicalUrl, policy, ctx);
}
diff --git a/apps/api/src/lib/threat-protection/providers/google-web-risk.ts b/apps/api/src/lib/threat-protection/providers/google-web-risk.ts
index cd4867cfd..7d3244a6c 100644
--- a/apps/api/src/lib/threat-protection/providers/google-web-risk.ts
+++ b/apps/api/src/lib/threat-protection/providers/google-web-risk.ts
@@ -1,7 +1,7 @@
import { createHash } from "crypto";
import { config } from "../../../config";
import type { RawVerdict, ThreatProvider } from "../types";
-import { generateHostExpressions } from "./web-risk/canonicalize";
+import { generateUrlExpressions } from "./web-risk/canonicalize";
import {
getWebRiskListStore,
WEB_RISK_THREAT_TYPES,
@@ -16,11 +16,11 @@ import {
// Google Web Risk provider ("normal" threat protection mode), built on the
// Update API for ZDR compliance:
//
-// 1. The domain is canonicalized into host-suffix expressions per the Safe
-// Browsing spec, each expression is SHA-256 hashed, and the 4-byte hash
-// prefixes are checked against the locally synced threat lists
-// (./web-risk/store.ts + ./web-risk/sync.ts). No network I/O, and the
-// target domain is never transmitted anywhere.
+// 1. The URL is canonicalized into host-suffix Γ— path-prefix expressions per
+// the Safe Browsing spec, each expression is SHA-256 hashed, and the
+// 4-byte hash prefixes are checked against the locally synced threat
+// lists (./web-risk/store.ts + ./web-risk/sync.ts). No network I/O, and
+// the target URL is never transmitted anywhere.
// 2. Only when a local prefix matches (rare) is Google consulted:
// GET /v1/hashes:search with the matched (anonymized, non-reversible)
// hash prefix. The returned full hashes are compared locally β€” a full
@@ -80,12 +80,12 @@ async function searchHashPrefix(
}
/**
- * Look up a domain against Google Web Risk. Throws on any transport/API
+ * Look up a URL against Google Web Risk. Throws on any transport/API
* error, and when the local threat lists are unavailable or stale, so the
* caller can apply the org's failurePolicy.
*/
export async function fetchGoogleWebRiskVerdict(
- domain: string,
+ url: string,
options?: { signal?: AbortSignal },
): Promise<RawVerdict> {
if (!isGoogleWebRiskConfigured()) {
@@ -94,9 +94,9 @@ export async function fetchGoogleWebRiskVerdict(
ensureThreatListSyncLoop();
- const expressions = generateHostExpressions(domain);
+ const expressions = generateUrlExpressions(url);
if (expressions.length === 0) {
- throw new Error(`Cannot canonicalize domain for Web Risk lookup`);
+ throw new Error(`Cannot canonicalize URL for Web Risk lookup`);
}
const fullHashes = expressions.map(expression =>
createHash("sha256").update(expression).digest(),
@@ -115,7 +115,7 @@ export async function fetchGoogleWebRiskVerdict(
}
if (lookup.hits.length === 0) {
- // The overwhelmingly common case: clean domain, zero Google calls,
+ // The overwhelmingly common case: clean URL, zero Google calls,
// nothing transmitted anywhere.
return {
provider: PROVIDER,
diff --git a/apps/api/src/lib/threat-protection/providers/providers.test.ts b/apps/api/src/lib/threat-protection/providers/providers.test.ts
index a2d5ae811..cd9e82a16 100644
--- a/apps/api/src/lib/threat-protection/providers/providers.test.ts
+++ b/apps/api/src/lib/threat-protection/providers/providers.test.ts
@@ -12,7 +12,7 @@ vi.mock("../../../services/queue-service", async () => {
import { config } from "../../../config";
import { fetchGoogleWebRiskVerdict } from "./google-web-risk";
-import { domainExpressionHash, WebRiskMockDatabase } from "./web-risk/testing";
+import { urlExpressionHash, WebRiskMockDatabase } from "./web-risk/testing";
// Mocked-HTTP provider tests: a local http server stands in for the real
// provider API via the config URL override (same pattern as
@@ -30,15 +30,18 @@ let seenRequests: SeenRequest[] = [];
// once per process by the provider's boot sync).
const CONFIRMED_DOMAIN = "malware.example";
const COLLISION_DOMAIN = "collision.example";
+// URL-level listing: only this exact page is flagged, its domain is clean.
+const CONFIRMED_URL = "http://mostly-clean.example/landing/phishing-page.html";
const webRiskDb = new WebRiskMockDatabase();
webRiskDb.addRiskyDomain(CONFIRMED_DOMAIN, "MALWARE");
webRiskDb.addRiskyDomain(CONFIRMED_DOMAIN, "SOCIAL_ENGINEERING");
+webRiskDb.addRiskyUrl(CONFIRMED_URL, "SOCIAL_ENGINEERING");
// A list entry that shares the 4-byte prefix of COLLISION_DOMAIN's expression
// hash but is a different full hash β†’ local hit, unconfirmed by hashes:search.
webRiskDb.addCollidingFullHash(
Buffer.concat([
- domainExpressionHash(COLLISION_DOMAIN).subarray(0, 4),
+ urlExpressionHash(COLLISION_DOMAIN).subarray(0, 4),
Buffer.alloc(28, 0xab),
]),
"UNWANTED_SOFTWARE",
@@ -152,7 +155,7 @@ describe("fetchGoogleWebRiskVerdict", () => {
const url = new URL(baseUrl + confirmations[0].url);
expect(confirmations[0].method).toBe("GET");
expect(url.searchParams.get("hashPrefix")).toBe(
- domainExpressionHash(CONFIRMED_DOMAIN).subarray(0, 4).toString("base64"),
+ urlExpressionHash(CONFIRMED_DOMAIN).subarray(0, 4).toString("base64"),
);
expect(url.searchParams.getAll("threatTypes")).toEqual([
"MALWARE",
@@ -174,6 +177,35 @@ describe("fetchGoogleWebRiskVerdict", () => {
expect(verdict.categories).toContain("MALWARE");
});
+ it("flags every URL on a listed domain through host-suffix expressions", async () => {
+ const verdict = await fetchGoogleWebRiskVerdict(
+ `https://${CONFIRMED_DOMAIN}/some/deep/page.html?q=1`,
+ );
+
+ expect(verdict.riskScore).toBe(100);
+ expect(verdict.categories).toContain("MALWARE");
+ });
+
+ it("flags a listed URL whose domain is otherwise clean", async () => {
+ const verdict = await fetchGoogleWebRiskVerdict(CONFIRMED_URL);
+
+ expect(verdict.riskScore).toBe(100);
+ expect(verdict.categories).toEqual(["SOCIAL_ENGINEERING"]);
+ });
+
+ it("keeps other URLs on that domain clean (URL-level, not domain-level)", async () => {
+ const siblingPage = await fetchGoogleWebRiskVerdict(
+ "http://mostly-clean.example/landing/legit-page.html",
+ );
+ const root = await fetchGoogleWebRiskVerdict(
+ "http://mostly-clean.example/",
+ );
+
+ expect(siblingPage.riskScore).toBe(0);
+ expect(root.riskScore).toBe(0);
+ expect(hashesSearchRequests()).toHaveLength(0);
+ });
+
it("resolves clean domains locally with zero Google calls", async () => {
const verdict = await fetchGoogleWebRiskVerdict("safe.example");
diff --git a/apps/api/src/lib/threat-protection/providers/web-risk/canonicalize.test.ts b/apps/api/src/lib/threat-protection/providers/web-risk/canonicalize.test.ts
index 54234e5fe..cbe885e1d 100644
--- a/apps/api/src/lib/threat-protection/providers/web-risk/canonicalize.test.ts
+++ b/apps/api/src/lib/threat-protection/providers/web-risk/canonicalize.test.ts
@@ -1,7 +1,7 @@
import {
canonicalizeHost,
canonicalizeUrl,
- generateHostExpressions,
+ generateUrlExpressions,
} from "./canonicalize";
// Google's published canonicalization test vectors, verbatim:
@@ -62,6 +62,25 @@ describe("canonicalizeUrl", () => {
it.each(CANONICALIZATION_VECTORS)("canonicalizes %j", (input, expected) => {
expect(canonicalizeUrl(input)).toBe(expected);
});
+
+ // The published vectors never exercise %XX escapes inside the query, but
+ // the spec's "repeatedly unescape, then escape once" step applies to the
+ // whole URL β€” Google's reference implementations unescape the query too.
+ // Without it, a valid escape like %20 double-escapes to %2520, hashes to a
+ // different expression than the list entry, and silently never matches.
+ it.each([
+ // Already-canonical escape survives the unescape/escape round trip.
+ ["http://host.com/p?q=%20x", "http://host.com/p?q=%20x"],
+ // Double-escaped input converges instead of gaining another layer.
+ ["http://host.com/p?q=%2520x", "http://host.com/p?q=%20x"],
+ // Escapes of printable ASCII outside the escape class are dropped.
+ ["http://host.com/p?q=%61", "http://host.com/p?q=a"],
+ ] as [string, string][])(
+ "percent-unescapes the query: %j",
+ (input, expected) => {
+ expect(canonicalizeUrl(input)).toBe(expected);
+ },
+ );
});
describe("canonicalizeHost", () => {
@@ -82,38 +101,82 @@ describe("canonicalizeHost", () => {
});
});
-describe("generateHostExpressions", () => {
- // Spec example (host component of "http://a.b.c.d.e.f.g/1.html"): the
- // exact host plus the four suffixes built from the last five components.
- it("walks at most the last five host components", () => {
- expect(generateHostExpressions("a.b.c.d.e.f.g")).toEqual([
+describe("generateUrlExpressions", () => {
+ // Google's published suffix/prefix expression examples, verbatim:
+ // https://cloud.google.com/web-risk/docs/urls-hashing#suffixprefix_expressions
+ it("matches the spec example for a URL with path and query", () => {
+ expect(generateUrlExpressions("http://a.b.com/1/2.html?param=1")).toEqual([
+ "a.b.com/1/2.html?param=1",
+ "a.b.com/1/2.html",
+ "a.b.com/",
+ "a.b.com/1/",
+ "b.com/1/2.html?param=1",
+ "b.com/1/2.html",
+ "b.com/",
+ "b.com/1/",
+ ]);
+ });
+
+ it("matches the spec example for a long hostname (last five components)", () => {
+ expect(generateUrlExpressions("http://a.b.c.d.e.f.g/1.html")).toEqual([
+ "a.b.c.d.e.f.g/1.html",
"a.b.c.d.e.f.g/",
+ // (Note: skip "b.c.d.e.f.g", since we'll take only the last five
+ // hostname components, and the full hostname.)
+ "c.d.e.f.g/1.html",
"c.d.e.f.g/",
+ "d.e.f.g/1.html",
"d.e.f.g/",
+ "e.f.g/1.html",
"e.f.g/",
+ "f.g/1.html",
"f.g/",
]);
});
- it("generates exact host + registrable suffixes for short hosts", () => {
- expect(generateHostExpressions("a.b.c")).toEqual(["a.b.c/", "b.c/"]);
- expect(generateHostExpressions("example.com")).toEqual(["example.com/"]);
- expect(generateHostExpressions("www.phishing.example.com")).toEqual([
+ it("matches the spec example for an IP host (no suffix walk)", () => {
+ expect(generateUrlExpressions("http://1.2.3.4/1/")).toEqual([
+ "1.2.3.4/1/",
+ "1.2.3.4/",
+ ]);
+ });
+
+ it("caps path prefixes at the root plus the first three components", () => {
+ expect(generateUrlExpressions("http://example.com/a/b/c/d/e.html")).toEqual(
+ [
+ "example.com/a/b/c/d/e.html",
+ "example.com/",
+ "example.com/a/",
+ "example.com/a/b/",
+ "example.com/a/b/c/",
+ ],
+ );
+ });
+
+ it("expands a bare domain to its root expression (crawl seeds etc.)", () => {
+ expect(generateUrlExpressions("example.com")).toEqual(["example.com/"]);
+ expect(generateUrlExpressions("www.phishing.example.com")).toEqual([
"www.phishing.example.com/",
"phishing.example.com/",
"example.com/",
]);
});
- it("generates a single expression for IP hosts (no suffix walk)", () => {
- expect(generateHostExpressions("195.127.0.11")).toEqual(["195.127.0.11/"]);
- expect(generateHostExpressions("3279880203")).toEqual(["195.127.0.11/"]);
- });
-
- it("canonicalizes the host before expanding", () => {
- expect(generateHostExpressions("WWW.Example.COM.")).toEqual([
+ it("canonicalizes host and IP forms before expanding", () => {
+ expect(generateUrlExpressions("WWW.Example.COM.")).toEqual([
"www.example.com/",
"example.com/",
]);
+ expect(generateUrlExpressions("http://3279880203/blah")).toEqual([
+ "195.127.0.11/blah",
+ "195.127.0.11/",
+ ]);
+ });
+
+ it("puts the exact host + path + query expression first", () => {
+ const expressions = generateUrlExpressions(
+ "https://sub.example.com/page?x=1",
+ );
+ expect(expressions[0]).toBe("sub.example.com/page?x=1");
});
});
diff --git a/apps/api/src/lib/threat-protection/providers/web-risk/canonicalize.ts b/apps/api/src/lib/threat-protection/providers/web-risk/canonicalize.ts
index f150a68a2..b07ebe740 100644
--- a/apps/api/src/lib/threat-protection/providers/web-risk/canonicalize.ts
+++ b/apps/api/src/lib/threat-protection/providers/web-risk/canonicalize.ts
@@ -185,9 +185,12 @@ interface ParsedUrl {
/**
* Lenient URL splitter (real URL parsers reject hosts the spec requires us to
- * handle, e.g. embedded spaces or raw control bytes).
+ * handle, e.g. embedded spaces or raw control bytes). Exported so host
+ * extraction elsewhere (normalizeDomain) can fall back to the same splitting
+ * when WHATWG URL parsing rejects the input β€” otherwise local rule matching
+ * and the classifier could disagree about a URL's host.
*/
-function splitUrl(input: string): ParsedUrl {
+export function splitUrl(input: string): ParsedUrl {
let rest = input;
let scheme = "http";
const schemeMatch = rest.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):\/\//);
@@ -241,7 +244,12 @@ export function canonicalizeUrl(input: string): string {
const canonicalHost = canonicalizeHost(host);
const canonicalPath = escapeBytes(canonicalizePath(fullyUnescape(path)));
- const canonicalQuery = query === null ? null : escapeBytes(query);
+ // The query is percent-unescaped like every other component (the spec's
+ // "repeatedly unescape" step applies to the whole URL) and then re-escaped
+ // once β€” otherwise `?q=%20x` would double-escape to `?q=%2520x`, hash to a
+ // different expression than Google's list entry, and silently never match.
+ const canonicalQuery =
+ query === null ? null : escapeBytes(fullyUnescape(query));
return (
`${scheme}://${canonicalHost}${canonicalPath}` +
@@ -255,27 +263,66 @@ function isIpHost(host: string): boolean {
}
/**
- * Host-suffix lookup expressions for a domain-level check, per the spec: the
- * exact hostname plus up to four suffixes formed from the last five host
- * components, successively dropping the leading component (never the bare
- * TLD), each with the "/" root path. IP hosts get a single expression.
- *
- * Firecrawl's threat protection is domain-level (we classify the target
- * domain, not individual URLs), so path variants are intentionally not
- * generated β€” this matches the previous uris:search behavior of looking up
- * `http://<domain>/`.
+ * Host-suffix candidates per the spec: the exact (canonicalized) host plus up
+ * to four suffixes formed from the last five host components, successively
+ * dropping the leading component (never the bare TLD). IP hosts get a single
+ * candidate (no suffix walk).
*/
-export function generateHostExpressions(domain: string): string[] {
- const host = canonicalizeHost(domain.trim());
- if (host.length === 0) return [];
- if (isIpHost(host)) return [host + "/"];
+function hostSuffixes(host: string): string[] {
+ if (isIpHost(host)) return [host];
- const expressions = [host + "/"];
+ const suffixes = [host];
const parts = host.split(".");
const maxSuffix = Math.min(5, parts.length - 1);
for (let suffixLen = maxSuffix; suffixLen >= 2; suffixLen--) {
const suffix = parts.slice(parts.length - suffixLen).join(".");
- if (suffix !== host) expressions.push(suffix + "/");
+ if (suffix !== host) suffixes.push(suffix);
+ }
+ return suffixes;
+}
+
+/**
+ * Path-prefix candidates per the spec: the exact path with query parameters
+ * (if any), the exact path without them, and up to four prefix paths formed
+ * by starting at the root and successively appending path components with a
+ * trailing slash. The walk builds directory prefixes only β€” the leaf
+ * component never re-appears with a trailing slash (the spec's example for
+ * "/1/2.html" yields "/" and "/1/", not "/1/2.html/"). Duplicates are
+ * collapsed, most-specific first.
+ */
+function pathPrefixes(path: string, query: string | null): string[] {
+ const variants: string[] = [];
+ if (query !== null) variants.push(`${path}?${query}`);
+ variants.push(path);
+
+ const components = path.split("/").filter(component => component.length > 0);
+ const maxWalk = Math.min(3, Math.max(0, components.length - 1));
+ let prefix = "/";
+ variants.push(prefix);
+ for (const component of components.slice(0, maxWalk)) {
+ prefix += component + "/";
+ variants.push(prefix);
+ }
+ return [...new Set(variants)];
+}
+
+/**
+ * URL lookup expressions per the spec: every combination of host suffix and
+ * path prefix (up to 5 Γ— 6 = 30), most-specific first β€” index 0 is always the
+ * exact canonicalized host + path (+ query). Threat protection is URL-level:
+ * a listing that flags only a specific page (a path expression) is caught
+ * even when its domain is otherwise clean.
+ */
+export function generateUrlExpressions(url: string): string[] {
+ const canonical = canonicalizeUrl(url);
+ const { host, path, query } = splitUrl(canonical);
+ if (host.length === 0) return [];
+
+ const expressions: string[] = [];
+ for (const hostSuffix of hostSuffixes(host)) {
+ for (const pathPrefix of pathPrefixes(path, query)) {
+ expressions.push(hostSuffix + pathPrefix);
+ }
}
- return expressions;
+ return [...new Set(expressions)];
}
diff --git a/apps/api/src/lib/threat-protection/providers/web-risk/testing.ts b/apps/api/src/lib/threat-protection/providers/web-risk/testing.ts
index acc8d42b3..8c5cbf230 100644
--- a/apps/api/src/lib/threat-protection/providers/web-risk/testing.ts
+++ b/apps/api/src/lib/threat-protection/providers/web-risk/testing.ts
@@ -1,6 +1,6 @@
import { createHash } from "crypto";
import type http from "http";
-import { generateHostExpressions } from "./canonicalize";
+import { generateUrlExpressions } from "./canonicalize";
import { WEB_RISK_THREAT_TYPES, type WebRiskThreatType } from "./store";
// Test helpers for the Web Risk Update API provider β€” shared by the unit
@@ -15,9 +15,13 @@ export function sha256(data: string | Buffer): Buffer {
return createHash("sha256").update(data).digest();
}
-/** SHA-256 of the primary (exact-host) lookup expression for a domain. */
-export function domainExpressionHash(domain: string): Buffer {
- return sha256(generateHostExpressions(domain)[0]);
+/**
+ * SHA-256 of the exact (most-specific) lookup expression for a URL or bare
+ * domain β€” index 0 of the expression list is always exact host + exact path
+ * (+ query); for a bare domain that is `host/`.
+ */
+export function urlExpressionHash(url: string): Buffer {
+ return sha256(generateUrlExpressions(url)[0]);
}
/**
@@ -30,12 +34,24 @@ export class WebRiskMockDatabase {
/** Entries in the list with no confirmable full hash (collision cases). */
private prefixOnlyByType = new Map<WebRiskThreatType, Buffer[]>();
- /** Flags a domain: its exact-host expression hash joins the list. */
+ /**
+ * Flags a whole domain: its exact-host expression hash (`host/`) joins the
+ * list, so every URL on the domain matches via the host-suffix expressions.
+ */
addRiskyDomain(
domain: string,
threatType: WebRiskThreatType = "MALWARE",
): void {
- this.addFullHash(domainExpressionHash(domain), threatType);
+ this.addFullHash(urlExpressionHash(domain), threatType);
+ }
+
+ /**
+ * Flags a single URL: only its exact expression (host + path + query) joins
+ * the list β€” other URLs on the same domain stay clean, which is what makes
+ * checks URL-level rather than domain-level.
+ */
+ addRiskyUrl(url: string, threatType: WebRiskThreatType = "MALWARE"): void {
+ this.addFullHash(urlExpressionHash(url), threatType);
}
addFullHash(fullHash: Buffer, threatType: WebRiskThreatType): void {
@@ -125,7 +141,8 @@ interface WebRiskMockCounters {
hashesSearchRequests: number;
/** hashes:search requests per 4-byte prefix (hex). */
hashesSearchByPrefixHex: Map<string, number>;
- hashesSearchRequestsForDomain(domain: string): number;
+ /** hashes:search confirmations for a URL's/domain's exact expression. */
+ hashesSearchRequestsForTarget(urlOrDomain: string): number;
}
/**
@@ -169,8 +186,8 @@ export function createWebRiskMockCounters(): WebRiskMockCounters {
computeDiffRequests: 0,
hashesSearchRequests: 0,
hashesSearchByPrefixHex: new Map(),
- hashesSearchRequestsForDomain(domain: string): number {
- const prefixHex = domainExpressionHash(domain)
+ hashesSearchRequestsForTarget(urlOrDomain: string): number {
+ const prefixHex = urlExpressionHash(urlOrDomain)
.subarray(0, 4)
.toString("hex");
return counters.hashesSearchByPrefixHex.get(prefixHex) ?? 0;
diff --git a/apps/api/src/lib/threat-protection/request.ts b/apps/api/src/lib/threat-protection/request.ts
index f71e5014c..efb0abadd 100644
--- a/apps/api/src/lib/threat-protection/request.ts
+++ b/apps/api/src/lib/threat-protection/request.ts
@@ -1,6 +1,6 @@
import type { TeamFlags } from "../../controllers/v2/types";
import { getThreatProtection } from "../zdr-helpers";
-import { checkDomain, type ThreatCheckContext } from "./index";
+import { checkUrl, type ThreatCheckContext } from "./index";
import {
getOrgIdForTeam,
getOrgThreatProtectionConfig,
@@ -8,7 +8,6 @@ import {
type OrgThreatProtectionConfig,
} from "./store";
import type { ThreatDecision, ThreatProtectionPolicy } from "./types";
-import { normalizeDomain } from "./verdict";
// Controller-layer glue for threat protection enforcement. One helper
// (resolveThreatProtection) is shared by every endpoint: it turns
@@ -102,56 +101,55 @@ interface BlockedUrl {
interface UrlPolicyCheckResult {
allowedUrls: string[];
blocked: BlockedUrl[];
- /** All decisions, keyed by normalized domain β€” for logging/bookkeeping. */
- decisionsByDomain: Map<string, ThreatDecision>;
+ /** One decision per input URL, keyed by the URL as given by the caller. */
+ decisionsByUrl: Map<string, ThreatDecision>;
}
-// Crawls/searches fan out to many URLs on few domains: dedupe by domain and
-// check domains concurrently (bounded). Deduplication is strictly scoped to
-// this one batch (an in-memory map) β€” there is no cross-request or persisted
-// verdict reuse (ZDR).
-const DOMAIN_CHECK_CONCURRENCY = 16;
+// Checks are URL-level and run concurrently (bounded). Repeats of the same
+// canonical URL share one in-flight decision via the dedup handle, which is
+// strictly scoped to this one batch (an in-memory map) unless the caller
+// widens it β€” there is no cross-request or persisted verdict reuse (ZDR).
+// Clean URLs resolve against the local hash-prefix lists (no network I/O),
+// so many URLs stay cheap on the check side; billing is +2 per unique
+// scanned canonical URL (see calculateThreatScanCredits).
+const URL_CHECK_CONCURRENCY = 16;
/**
- * Checks a list of URLs against a policy, deduplicated by domain. Never
- * throws β€” `checkDomain` resolves provider failures via the policy's
- * failurePolicy. Each call scans a given domain at most once (per-batch
- * in-memory dedup; callers may pass their own `ctx.dedup` to widen the scope
- * to a whole request/job).
+ * Checks a list of URLs against a policy. Never throws β€” `checkUrl` resolves
+ * provider failures via the policy's failurePolicy. Each call scans a given
+ * canonical URL at most once (per-batch in-memory dedup; callers may pass
+ * their own `ctx.dedup` to widen the scope to a whole request/job).
*/
export async function checkUrlsAgainstThreatPolicy(
urls: string[],
policy: ThreatProtectionPolicy,
ctx: ThreatCheckContext,
): Promise<UrlPolicyCheckResult> {
- const domains = [...new Set(urls.map(url => normalizeDomain(url)))];
+ const uniqueUrls = [...new Set(urls)];
const dedupCtx: ThreatCheckContext = {
...ctx,
dedup: ctx.dedup ?? new Map(),
};
- const decisionsByDomain = new Map<string, ThreatDecision>();
- for (let i = 0; i < domains.length; i += DOMAIN_CHECK_CONCURRENCY) {
- const batch = domains.slice(i, i + DOMAIN_CHECK_CONCURRENCY);
+ const decisionsByUrl = new Map<string, ThreatDecision>();
+ for (let i = 0; i < uniqueUrls.length; i += URL_CHECK_CONCURRENCY) {
+ const batch = uniqueUrls.slice(i, i + URL_CHECK_CONCURRENCY);
const decisions = await Promise.all(
- batch.map(domain => checkDomain(domain, policy, dedupCtx)),
- );
- batch.forEach((domain, index) =>
- decisionsByDomain.set(domain, decisions[index]),
+ batch.map(url => checkUrl(url, policy, dedupCtx)),
);
+ batch.forEach((url, index) => decisionsByUrl.set(url, decisions[index]));
}
const allowedUrls: string[] = [];
const blocked: BlockedUrl[] = [];
for (const url of urls) {
- const domain = normalizeDomain(url);
- const decision = decisionsByDomain.get(domain);
+ const decision = decisionsByUrl.get(url);
if (decision && !decision.allowed) {
- blocked.push({ url, domain, decision });
+ blocked.push({ url, domain: decision.domain, decision });
} else {
allowedUrls.push(url);
}
}
- return { allowedUrls, blocked, decisionsByDomain };
+ return { allowedUrls, blocked, decisionsByUrl };
}
diff --git a/apps/api/src/lib/threat-protection/types.ts b/apps/api/src/lib/threat-protection/types.ts
index b21282820..a15e7c9a5 100644
--- a/apps/api/src/lib/threat-protection/types.ts
+++ b/apps/api/src/lib/threat-protection/types.ts
@@ -51,13 +51,13 @@ export interface RawVerdict {
}
/**
- * Request/job-scoped dedup handle for {@link import("./index").checkDomain}.
+ * Request/job-scoped dedup handle for {@link import("./index").checkUrl}.
* Call sites create one per request or job (never shared across requests, and
- * never persisted) so that repeated checks of the same domain within that
+ * never persisted) so that repeated checks of the same URL within that
* scope β€” e.g. a scrape plus its redirect re-check, or one crawl-discovery
* batch β€” share a single in-flight decision instead of re-scanning. Keyed by
- * normalized domain only: within one request the effective policy is
- * constant, so the domain fully identifies the decision.
+ * the canonicalized URL only: within one request the effective policy is
+ * constant, so the URL fully identifies the decision.
*/
export type ThreatCheckDedup = Map<string, Promise<ThreatDecision>>;
@@ -72,7 +72,16 @@ export type ThreatDecisionRule =
export interface ThreatDecision {
allowed: boolean;
rule: ThreatDecisionRule;
- /** True if a provider verdict (fresh OR cached) was consulted β€” this drives billing (+2 per scanned domain). */
+ /**
+ * The canonicalized URL this decision is about β€” also the billing dedup
+ * key: consulted decisions bill +2 once per unique canonical URL within
+ * one billing scope (see calculateThreatScanCredits), so raw-string
+ * variants of the same URL never double-bill a single scan.
+ */
+ url: string;
+ /** Canonicalized host of the checked URL (for logs and error surfaces). */
+ domain: string;
+ /** True if a provider verdict (fresh OR cached) was consulted β€” this drives billing (+2 per scanned URL). */
providerConsulted: boolean;
verdict: RawVerdict | null;
mode: ThreatProtectionMode;
diff --git a/apps/api/src/lib/threat-protection/verdict.test.ts b/apps/api/src/lib/threat-protection/verdict.test.ts
index e089f3f2d..95d7497b2 100644
--- a/apps/api/src/lib/threat-protection/verdict.test.ts
+++ b/apps/api/src/lib/threat-protection/verdict.test.ts
@@ -304,6 +304,8 @@ describe("localOnlyDecision", () => {
expect(decision).toEqual({
allowed: true,
rule: "whitelist",
+ url: "example.com",
+ domain: "example.com",
providerConsulted: false,
verdict: null,
mode: "normal",
@@ -373,6 +375,13 @@ describe("normalizeDomain", () => {
[" example.com ", "example.com"],
["example.com.", "example.com"],
["https://sub.example.com/path?q=1", "sub.example.com"],
+ // Hosts WHATWG URL rejects (escaped bytes) still resolve via the lenient
+ // splitter instead of degenerating to "http" (which would let such URLs
+ // slip past every local rule).
+ ["http://%20leadingspace.com/path", "%20leadingspace.com"],
+ // …including when a fragment directly follows the host (no path) β€” it
+ // must not ride along into the extracted host.
+ ["http://%20leadingspace.com#frag", "%20leadingspace.com"],
["example.com:8080", "example.com"],
["example.com/path", "example.com"],
// inet_aton-style IP forms canonicalize to dotted-quad, matching the Web
diff --git a/apps/api/src/lib/threat-protection/verdict.ts b/apps/api/src/lib/threat-protection/verdict.ts
index 2e96247fa..d65022305 100644
--- a/apps/api/src/lib/threat-protection/verdict.ts
+++ b/apps/api/src/lib/threat-protection/verdict.ts
@@ -8,7 +8,7 @@ import type {
// way; local blacklist/whitelist rules MUST use the exact same function so
// the two paths can never disagree on what host they're evaluating β€” e.g. so
// a blacklist entry for "195.127.0.11" is not bypassed by "http://3279880203/".
-import { canonicalizeHost } from "./providers/web-risk/canonicalize";
+import { canonicalizeHost, splitUrl } from "./providers/web-risk/canonicalize";
// Pure policy evaluation for threat protection. No I/O in this file β€” the
// provider/cache orchestration lives in ./index.ts. Rule precedence (fixed):
@@ -80,7 +80,17 @@ export function normalizeDomain(input: string): string {
try {
domain = new URL(domain).hostname;
} catch {
- // Not a parseable URL β€” fall through with the raw string.
+ // WHATWG URL rejects hosts the Safe Browsing spec still handles (e.g.
+ // percent-escaped spaces or control bytes). Fall back to the same
+ // lenient splitter the canonicalizer uses β€” the naive string handling
+ // below would otherwise extract "http:" as the "host" and local rules
+ // would silently never match. Mirror canonicalizeUrl's pre-split
+ // cleanup (embedded tab/CR/LF, fragment) so a fragment directly after
+ // the host can't ride along into it.
+ let cleaned = domain.replace(/[\t\r\n]/g, "");
+ const hash = cleaned.indexOf("#");
+ if (hash !== -1) cleaned = cleaned.slice(0, hash);
+ domain = splitUrl(cleaned).host;
}
}
// Strip a path fragment, then the port β€” carefully, because IPv6 literals
@@ -100,15 +110,19 @@ export function normalizeDomain(input: string): string {
/**
* Resolve a decision using ONLY local policy rules (whitelist β†’ blacklist β†’
- * blocked-tld), or null if a provider verdict is needed. Local decisions never
- * consult a provider, so they never set `providerConsulted` (no billing).
+ * blocked-tld), or null if a provider verdict is needed. Local rules are
+ * domain-level (the lists hold domains/globs), so `target` may be a full URL β€”
+ * only its canonicalized host is evaluated. Local decisions never consult a
+ * provider, so they never set `providerConsulted` (no billing).
*/
export function localOnlyDecision(
- domain: string,
+ target: string,
policy: ThreatProtectionPolicy,
): ThreatDecision | null {
- const normalized = normalizeDomain(domain);
+ const normalized = normalizeDomain(target);
const base = {
+ url: target,
+ domain: normalized,
providerConsulted: false,
verdict: null,
mode: policy.mode,
@@ -133,17 +147,19 @@ export function localOnlyDecision(
* was used, which drives billing.
*/
export function evaluatePolicy(
- domain: string,
+ target: string,
verdict: RawVerdict | null,
policy: ThreatProtectionPolicy,
): ThreatDecision {
const base = {
+ url: target,
+ domain: normalizeDomain(target),
providerConsulted: verdict !== null,
verdict,
mode: policy.mode,
};
- const local = localOnlyDecision(domain, policy);
+ const local = localOnlyDecision(target, policy);
if (local !== null) {
// Preserve the local rule but reflect any verdict we were given (billing
// still applies if a provider was consulted before evaluation).
@@ -162,7 +178,7 @@ export function evaluatePolicy(
}
// No verdict: the provider failed or was unavailable (mode "off" never
- // reaches here via checkDomain). Fail open or closed per the org policy.
+ // reaches here via checkUrl). Fail open or closed per the org policy.
if (policy.mode === "off") {
return { allowed: true, rule: "default-allow", ...base };
}
diff --git a/apps/api/src/scraper/scrapeURL/index.ts b/apps/api/src/scraper/scrapeURL/index.ts
index 6e235fe09..1c86edf65 100644
--- a/apps/api/src/scraper/scrapeURL/index.ts
+++ b/apps/api/src/scraper/scrapeURL/index.ts
@@ -89,13 +89,13 @@ import { tmpdir } from "node:os";
import { randomUUID } from "node:crypto";
import type { DataLayerScrapeMetadata } from "../../lib/data-layer";
import {
- checkDomain,
+ checkUrl,
type ThreatCheckDedup,
type ThreatDecision,
type ThreatProtectionPolicy,
} from "../../lib/threat-protection";
import { UnsafeDomainBlockedError } from "../../lib/threat-protection/error";
-import { normalizeDomain } from "../../lib/threat-protection/verdict";
+import { canonicalizeUrl } from "../../lib/threat-protection/providers/web-risk/canonicalize";
export type ScrapeUrlResponse =
| {
@@ -1111,24 +1111,26 @@ export async function scrapeURL(
meta.logger.info("scrapeURL entered");
- // Threat protection: check the target domain BEFORE any engine selection
+ // Threat protection: check the target URL BEFORE any engine selection
// or outbound fetch. The policy is resolved at the controller layer and
// threaded through internalOptions; absent policy = zero overhead.
// The dedup map is scoped to this one scrape: the initial check and any
- // redirect re-check on the same domain share a single scan (one billable
- // consulted decision); a cross-domain redirect is a second scan.
+ // redirect re-check on the same URL share a single scan (one fee); a
+ // redirect to a different URL is a second scan and bills a second fee
+ // (see calculateThreatScanCredits).
const threatPolicy = internalOptions.threatProtection;
const threatDedup: ThreatCheckDedup = new Map();
if (threatPolicy && threatPolicy.mode !== "off") {
- const initialDomain = normalizeDomain(meta.rewrittenUrl ?? meta.url);
- const decision = await checkDomain(initialDomain, threatPolicy, {
+ const initialUrl = meta.rewrittenUrl ?? meta.url;
+ const decision = await checkUrl(initialUrl, threatPolicy, {
teamId: internalOptions.teamId,
dedup: threatDedup,
});
meta.threatDecisions.push(decision);
if (!decision.allowed) {
- meta.logger.info("Domain blocked by threat protection policy", {
- domain: initialDomain,
+ meta.logger.info("URL blocked by threat protection policy", {
+ url: initialUrl,
+ domain: decision.domain,
rule: decision.rule,
});
setSpanAttributes(span, {
@@ -1136,7 +1138,7 @@ export async function scrapeURL(
});
return {
success: false,
- error: new UnsafeDomainBlockedError(initialDomain, decision),
+ error: new UnsafeDomainBlockedError(initialUrl, decision),
threatDecisions: meta.threatDecisions,
};
}
@@ -1327,15 +1329,18 @@ export async function scrapeURL(
}
}
- // Threat protection: if the scrape ended up on a different domain than
- // requested (redirect), re-check the destination domain. This closes
- // the "clean domain redirects to a blocked domain" bypass vector.
+ // Threat protection: if the scrape ended up on a different URL than
+ // requested (redirect), re-check the destination URL. This closes the
+ // "clean URL redirects to a blocked URL" bypass vector β€” including
+ // same-domain redirects onto a flagged path.
if (threatPolicy && threatPolicy.mode !== "off" && result.success) {
+ const initialUrl = meta.rewrittenUrl ?? meta.url;
const finalUrl = result.document.metadata.url;
- const initialDomain = normalizeDomain(meta.rewrittenUrl ?? meta.url);
- const finalDomain = finalUrl ? normalizeDomain(finalUrl) : null;
- if (finalDomain !== null && finalDomain !== initialDomain) {
- const decision = await checkDomain(finalDomain, threatPolicy, {
+ if (
+ finalUrl &&
+ canonicalizeUrl(finalUrl) !== canonicalizeUrl(initialUrl)
+ ) {
+ const decision = await checkUrl(finalUrl, threatPolicy, {
teamId: internalOptions.teamId,
dedup: threatDedup,
});
@@ -1344,15 +1349,16 @@ export async function scrapeURL(
meta.logger.info(
"Redirect destination blocked by threat protection policy",
{
- domain: finalDomain,
- initialDomain,
+ url: finalUrl,
+ domain: decision.domain,
+ initialUrl,
rule: decision.rule,
},
);
setSpanAttributes(span, {
"scrape.blocked_by_threat_protection": true,
});
- throw new UnsafeDomainBlockedError(finalDomain, decision);
+ throw new UnsafeDomainBlockedError(finalUrl, decision);
}
}
}
diff --git a/apps/api/src/search/execute.ts b/apps/api/src/search/execute.ts
index 2c80a200c..caabca548 100644
--- a/apps/api/src/search/execute.ts
+++ b/apps/api/src/search/execute.ts
@@ -18,7 +18,6 @@ import { trackSearchResults, trackSearchRequest } from "../lib/tracking";
import type { BillingMetadata } from "../services/billing/types";
import type { ThreatProtectionPolicy } from "../lib/threat-protection/types";
import { checkUrlsAgainstThreatPolicy } from "../lib/threat-protection/request";
-import { normalizeDomain } from "../lib/threat-protection/verdict";
import { calculateThreatScanCredits } from "../lib/scrape-billing";
interface SearchOptions {
@@ -110,11 +109,11 @@ export async function executeSearch(
enterprise: options.enterprise,
})) as SearchV2Response;
- // Threat protection: remove results on blocked domains entirely β€” before
- // slicing/counting, before scraping, and before returning. Domain checks
- // are deduped and Redis-cached. Every consulted decision (fresh or cached
- // provider verdict) is a billable scan (+2 per scanned domain), charged
- // as part of the search credits below.
+ // Threat protection: remove blocked results entirely β€” before
+ // slicing/counting, before scraping, and before returning. Checks are
+ // URL-level and deduped within this request; scan fees bill +2 per unique
+ // scanned URL (see calculateThreatScanCredits), charged as part of the
+ // search credits below.
let threatScanCredits = 0;
const threatPolicy = context.threatProtectionPolicy;
if (threatPolicy && threatPolicy.mode !== "off") {
@@ -125,17 +124,15 @@ export async function executeSearch(
].filter((x): x is string => !!x);
if (urlsToCheck.length > 0) {
- const { decisionsByDomain } = await checkUrlsAgainstThreatPolicy(
+ const { decisionsByUrl } = await checkUrlsAgainstThreatPolicy(
urlsToCheck,
threatPolicy,
{ teamId },
);
- threatScanCredits = calculateThreatScanCredits(
- decisionsByDomain.values(),
- );
+ threatScanCredits = calculateThreatScanCredits(decisionsByUrl.values());
const isAllowed = (url: string | undefined | null): boolean => {
if (!url) return true;
- const decision = decisionsByDomain.get(normalizeDomain(url));
+ const decision = decisionsByUrl.get(url);
return decision === undefined || decision.allowed;
};
if (searchResponse.web) {
diff --git a/apps/api/src/services/worker/scrape-worker.ts b/apps/api/src/services/worker/scrape-worker.ts
index a9441b613..a4d4bebc6 100644
--- a/apps/api/src/services/worker/scrape-worker.ts
+++ b/apps/api/src/services/worker/scrape-worker.ts
@@ -229,10 +229,11 @@ async function billScrapeJob(
* Bills threat protection scan fees for crawl-discovered URLs that were
* blocked by the policy and therefore never become scrape jobs. Only blocked
* decisions bill here: allowed discoveries are billed by their own scrape
- * job, which re-checks the (cached) verdict. Deduplicates by domain, and only
- * decisions that consulted the classifier (fresh or cached provider verdict)
- * carry a fee (+2 per scanned domain) β€” local-only blocks (e.g. blacklist)
- * are free.
+ * job, which performs its own scan. Only decisions that consulted the
+ * classifier carry a fee (+2 per unique scanned URL) β€” local-only blocks
+ * (e.g. blacklist) are free. Callers pass only FIRST-TIME blocks for this
+ * crawl (recordThreatBlocked's HSETNX return), so a blocked URL rediscovered
+ * by many page jobs bills once per crawl.
*/
function billThreatBlockedDiscoveries(
args: {
@@ -245,11 +246,8 @@ function billThreatBlockedDiscoveries(
logger: Logger,
) {
if (args.bypassBilling) return;
- const blockedDecisionsByDomain = new Map(
- blocked.map(x => [x.domain, x.decision]),
- );
const threatScanCredits = calculateThreatScanCredits(
- blockedDecisionsByDomain.values(),
+ blocked.map(x => x.decision),
);
if (threatScanCredits <= 0) return;
billTeam(
@@ -512,11 +510,12 @@ async function processJob(job: NuQJob<ScrapeJobSingleUrls>) {
}
}
- // Threat protection: silently skip discovered links on blocked
- // domains (cross-domain links included) β€” the crawl continues.
- // Skipped URLs + decisions are recorded for the security-logging
- // layer. Domain checks are deduped and rely on the Redis verdict
- // cache, so many links on few domains stay cheap.
+ // Threat protection: silently skip blocked discovered links
+ // (cross-domain links included) β€” the crawl continues. Skipped
+ // URLs + decisions are recorded for crawl bookkeeping. Checks
+ // are URL-level against the local hash-prefix lists (deduped
+ // in-batch), so many links stay cheap on the check side; blocked
+ // discoveries bill +2 per unique scanned URL.
let discoveredLinks = links.links;
const threatPolicy = job.data.internalOptions?.threatProtection;
if (
@@ -531,12 +530,19 @@ async function processJob(job: NuQJob<ScrapeJobSingleUrls>) {
{ teamId: job.data.team_id },
);
discoveredLinks = allowedUrls;
+ const newlyBlocked: typeof blocked = [];
for (const blockedUrl of blocked) {
- await recordThreatBlocked(
- job.data.crawl_id,
- blockedUrl.url,
- blockedUrl.decision,
- );
+ if (
+ await recordThreatBlocked(
+ job.data.crawl_id,
+ // Key on the canonical URL so raw spelling variants of
+ // one URL dedupe to a single fee, matching billing.
+ blockedUrl.decision.url ?? blockedUrl.url,
+ blockedUrl.decision,
+ )
+ ) {
+ newlyBlocked.push(blockedUrl);
+ }
}
if (blocked.length > 0) {
billThreatBlockedDiscoveries(
@@ -551,7 +557,7 @@ async function processJob(job: NuQJob<ScrapeJobSingleUrls>) {
bypassBilling:
job.data.internalOptions?.bypassBilling ?? false,
},
- blocked,
+ newlyBlocked,
logger,
);
logger.info(
@@ -1202,7 +1208,8 @@ async function processKickoffJob(job: NuQJob<ScrapeJobKickoff>) {
let indexLinks = await kickoffGetIndexLinks(sc, crawler, job.data.url);
- // Threat protection: skip index-sourced discoveries on blocked domains.
+ // Threat protection: skip blocked index-sourced discoveries (URL-level
+ // checks; first-time blocks are recorded and billed, see below).
const kickoffThreatPolicy = sc.internalOptions?.threatProtection;
if (
kickoffThreatPolicy &&
@@ -1215,12 +1222,19 @@ async function processKickoffJob(job: NuQJob<ScrapeJobKickoff>) {
{ teamId: job.data.team_id },
);
indexLinks = allowedUrls;
+ const newlyBlocked: typeof blocked = [];
for (const blockedUrl of blocked) {
- await recordThreatBlocked(
- job.data.crawl_id,
- blockedUrl.url,
- blockedUrl.decision,
- );
+ if (
+ await recordThreatBlocked(
+ job.data.crawl_id,
+ // Key on the canonical URL so raw spelling variants of one URL
+ // dedupe to a single fee, matching billing.
+ blockedUrl.decision.url ?? blockedUrl.url,
+ blockedUrl.decision,
+ )
+ ) {
+ newlyBlocked.push(blockedUrl);
+ }
}
if (blocked.length > 0) {
billThreatBlockedDiscoveries(
@@ -1234,7 +1248,7 @@ async function processKickoffJob(job: NuQJob<ScrapeJobKickoff>) {
}),
bypassBilling: sc.internalOptions?.bypassBilling ?? false,
},
- blocked,
+ newlyBlocked,
logger,
);
}
@@ -1360,8 +1374,9 @@ async function processKickoffSitemapJob(job: NuQJob<ScrapeJobKickoffSitemap>) {
)
).links;
- // Threat protection: skip sitemap entries on blocked domains β€” the crawl
- // continues; skipped URLs + decisions are recorded for security logging.
+ // Threat protection: skip blocked sitemap entries β€” the crawl continues;
+ // skipped URLs + decisions are recorded as crawl bookkeeping (which also
+ // dedups the scan fee per crawl).
const sitemapThreatPolicy = sc.internalOptions?.threatProtection;
if (
sitemapThreatPolicy &&
@@ -1374,12 +1389,19 @@ async function processKickoffSitemapJob(job: NuQJob<ScrapeJobKickoffSitemap>) {
{ teamId: job.data.team_id },
);
passingURLs = allowedUrls;
+ const newlyBlocked: typeof blocked = [];
for (const blockedUrl of blocked) {
- await recordThreatBlocked(
- job.data.crawl_id,
- blockedUrl.url,
- blockedUrl.decision,
- );
+ if (
+ await recordThreatBlocked(
+ job.data.crawl_id,
+ // Key on the canonical URL so raw spelling variants of one URL
+ // dedupe to a single fee, matching billing.
+ blockedUrl.decision.url ?? blockedUrl.url,
+ blockedUrl.decision,
+ )
+ ) {
+ newlyBlocked.push(blockedUrl);
+ }
}
if (blocked.length > 0) {
billThreatBlockedDiscoveries(
@@ -1393,7 +1415,7 @@ async function processKickoffSitemapJob(job: NuQJob<ScrapeJobKickoffSitemap>) {
}),
bypassBilling: sc.internalOptions?.bypassBilling ?? false,
},
- blocked,
+ newlyBlocked,
logger,
);
}