diff --git a/cmd/edgefetch-wasm/reactor.go b/cmd/edgefetch-wasm/reactor.go index 02f2b6b..d6e536a 100644 --- a/cmd/edgefetch-wasm/reactor.go +++ b/cmd/edgefetch-wasm/reactor.go @@ -2071,6 +2071,39 @@ func dispatchWasmRPC(rawReq []byte) (any, error) { } return map[string]any{"blocked": true, "message": msg}, nil + case "nostr_prepare_nip01": + var p struct { + URL string `json:"url"` + SelfHost string `json:"selfHost"` + SubID string `json:"subId"` + MaxEvents int `json:"maxEvents"` + } + if err := json.Unmarshal(env.Payload, &p); err != nil { + return nil, err + } + return extract.PrepareNostrNIP01(p.URL, p.SelfHost, p.SubID, p.MaxEvents), nil + + case "nostr_format_nip01": + var p struct { + OrigURL string `json:"origUrl"` + RelayURL string `json:"relayUrl"` + SubID string `json:"subId"` + NIP11Raw string `json:"nip11Raw"` + Frames []string `json:"frames"` + MaxEvents int `json:"maxEvents"` + } + if err := json.Unmarshal(env.Payload, &p); err != nil { + return nil, err + } + if p.Frames != nil && len(p.NIP11Raw) == 0 && p.RelayURL == "" { + return map[string]any{"events": extract.ParseNostrNIP01Frames(p.SubID, p.Frames, p.MaxEvents)}, nil + } + doc, ok := extract.FormatNostrNIP01Frames(p.OrigURL, p.RelayURL, p.SubID, p.NIP11Raw, p.Frames, p.MaxEvents) + if !ok || doc == nil { + return map[string]any{"ok": false}, nil + } + return map[string]any{"ok": true, "doc": doc}, nil + case "refine_blocked_map": var p classify.RefineBlockedMapInput if err := json.Unmarshal(env.Payload, &p); err != nil { diff --git a/hub/scripts/compile-manifests.mjs b/hub/scripts/compile-manifests.mjs index b7051c4..3035da1 100644 --- a/hub/scripts/compile-manifests.mjs +++ b/hub/scripts/compile-manifests.mjs @@ -414,6 +414,40 @@ export const VALID_HTML_MODES = new Set([ 'local_classifieds_html', 'creator_digital_stores_html', 'chairish_1stdibs_html', + // Wave 3 B6 Category Q (Product Identity & GTIN #368-#374 + fcc-id enrichment) + 'gs1_us_html', + 'open_icecat_html', + 'upcitemdb_barcodelookup_html', + 'open_product_wikidata_html', + 'energy_star_html', + 'fcc_test_report_html', + 'fcc_id_html', + 'prop65_warnings_html', + // Wave 3 B6 Category R (Media, Entertainment & Lyrics #375-#386) + 'tmdb_html', + 'imdb_datasets_html', + 'tvmaze_html', + 'musicbrainz_html', + 'discogs_html', + 'podcast_index_html', + 'spotify_html', + 'setlist_lastfm_html', + 'steam_store_html', + 'igdb_html', + 'bandcamp_html', + 'genius_lyrics_html', + // Wave 3 B6 Category S (Finance & Market Data #387-#392) + 'fed_h15_html', + 'msrb_emma_html', + 'ffiec_cdr_html', + // Wave 3 B6 Category T (Open Social & Creator #393-#400) + 'threads_html', + 'tumblr_html', + 'farcaster_html', + 'nostr_njump_html', + 'product_hunt_html', + 'substack_notes_html', + 'patreon_public_html', ]); const pslDatPath = join(manifestsDir, 'public_suffix_list.dat'); @@ -621,6 +655,8 @@ const APPROVED_WILDCARD_DOMAIN_PATTERNS = new Set([ '*.craigslist.org', '*.gumroad.com', '*.lemonsqueezy.com', + // Wave 3 B6 Category R + '*.bandcamp.com', ]); const RESERVED_CORE_ATS_DOMAINS = new Set([ diff --git a/hub/scripts/run-tests.mjs b/hub/scripts/run-tests.mjs index 67851ae..95863c2 100644 --- a/hub/scripts/run-tests.mjs +++ b/hub/scripts/run-tests.mjs @@ -107,6 +107,7 @@ const suiteSpecs = [ ['test/wave3-b3-trade-regulators.test.ts', 'wave3-b3-trade-regulators.test.mjs'], ['test/wave3-b4-research-security-dev.test.ts', 'wave3-b4-research-security-dev.test.mjs'], ['test/wave3-b5-cycling-resale.test.ts', 'wave3-b5-cycling-resale.test.mjs'], + ['test/wave3-b6-gtin-media-finance-social.test.ts', 'wave3-b6-gtin-media-finance-social.test.mjs'], ['test/mcp-part2-wave2e.test.ts', 'mcp-part2-wave2e.test.mjs'], ['test/wave2-security-fixes.test.ts', 'wave2-security-fixes.test.mjs'], ['test/hub-secrets-policy.test.ts', 'hub-secrets-policy.test.mjs'], diff --git a/hub/src/adapter-policy.ts b/hub/src/adapter-policy.ts index 8133c1c..05afbf8 100644 --- a/hub/src/adapter-policy.ts +++ b/hub/src/adapter-policy.ts @@ -16,6 +16,7 @@ export const USER_AGENT_PROFILES: Readonly> = { openstreetmap: 'EdgeFetch/2.7 (bot@edgefetch.dev; osm-polite-client)', 'sec-edgar': 'EdgeFetch/2.7 (bot@edgefetch.dev; sec-edgar-client)', usajobs: 'EdgeFetch/2.7 (bot@edgefetch.dev; usajobs-client)', + musicbrainz: 'EdgeFetch/2.7 (bot@edgefetch.dev; musicbrainz-client)', }; export interface AdapterPolicy { diff --git a/hub/src/extractors/declarative.ts b/hub/src/extractors/declarative.ts index d25d31c..5776bb3 100644 --- a/hub/src/extractors/declarative.ts +++ b/hub/src/extractors/declarative.ts @@ -659,7 +659,37 @@ export type DeclarativeJsonMode = | 'ifixit_json' | 'cpsc_ebike_incidents_json' | 'reverb_listing_json' - | 'reverb_search_json'; + | 'reverb_search_json' + | 'gs1_us_json' + | 'open_icecat_json' + | 'upcitemdb_json' + | 'barcodelookup_json' + | 'wikidata_gtin_sparql_json' + | 'energy_star_json' + | 'fcc_test_report_json' + | 'tmdb_json' + | 'tvmaze_json' + | 'musicbrainz_json' + | 'coverart_archive_json' + | 'discogs_json' + | 'podcast_index_json' + | 'spotify_api_json' + | 'spotify_oembed_json' + | 'setlist_fm_json' + | 'lastfm_json' + | 'steam_store_json' + | 'igdb_json' + | 'nasdaq_data_link_json' + | 'market_quotes_json' + | 'sec_xbrl_frames_json' + | 'ffiec_cdr_json' + | 'youtube_data_api_json' + | 'threads_api_json' + | 'tumblr_api_json' + | 'farcaster_hub_json' + | 'nostr_relay_json' + | 'product_hunt_json' + | 'beehiiv_api_json'; export interface DeclarativeExtractSpec { commerceMode?: DeclarativeCommerceMode; @@ -708,7 +738,10 @@ export interface DeclarativeExtractSpec { | 'exploit_db_csv' | 'exploit_db_rss' | 'gerrit_json' - | 'apis_guru_list_bounded'; + | 'apis_guru_list_bounded' + | 'opengtindb_text' + | 'imdb_datasets_tsv' + | 'fed_h15_csv'; pathParam?: string; codeByPath?: DeclarativeCodeByPathSpec; xml?: DeclarativeXmlSpec; @@ -1134,7 +1167,37 @@ export type DeclarativeHtmlMode = | 'peer_resale_fashion_html' | 'local_classifieds_html' | 'creator_digital_stores_html' - | 'chairish_1stdibs_html'; + | 'chairish_1stdibs_html' + | 'gs1_us_html' + | 'open_icecat_html' + | 'upcitemdb_barcodelookup_html' + | 'open_product_wikidata_html' + | 'energy_star_html' + | 'fcc_test_report_html' + | 'fcc_id_html' + | 'prop65_warnings_html' + | 'tmdb_html' + | 'imdb_datasets_html' + | 'tvmaze_html' + | 'musicbrainz_html' + | 'discogs_html' + | 'podcast_index_html' + | 'spotify_html' + | 'setlist_lastfm_html' + | 'steam_store_html' + | 'igdb_html' + | 'bandcamp_html' + | 'genius_lyrics_html' + | 'fed_h15_html' + | 'msrb_emma_html' + | 'ffiec_cdr_html' + | 'threads_html' + | 'tumblr_html' + | 'farcaster_html' + | 'nostr_njump_html' + | 'product_hunt_html' + | 'substack_notes_html' + | 'patreon_public_html'; export interface DeclarativeHtmlRouteSpec { id?: string; diff --git a/hub/src/scrape.ts b/hub/src/scrape.ts index 8d670c5..3a4b168 100644 --- a/hub/src/scrape.ts +++ b/hub/src/scrape.ts @@ -30,8 +30,10 @@ import { decodeWireItemBodyText, evaluateTwinResponseRedirect, executeKeyedTwinOfficialFetch, + fetchNostrRelayNip01Events, isTrustedTwinRedirectUrl, isTwinRedirectedToErrorPage, + runNostrNip11AndNip01AfterHubFetch, selectRawBodyForContentState, sliceToPolicyMaxFetchBytes, } from './twin-transport'; @@ -243,6 +245,7 @@ export { isSameApiEndpointOriginAndPath } from './api-keys'; export { decodeBase64ArchiveMagicPrefix, decodeBoundedGzipTsvFromBase64, + fetchNostrRelayNip01Events, isTrustedTwinRedirectUrl, isTwinRedirectedToErrorPage, }; @@ -3400,6 +3403,7 @@ export async function executeScrapeCall(params: { tracer?: RequestTracer | TraceContext; apiKeyVaultStore?: ApiKeyVaultStore; mcpVaultStore?: McpVaultStore; + webSocketFactory?: (wssUrl: string) => WebSocket; }): Promise<{ status: number; body: Record; via: string; retryAfter?: string }> { const activeTracer = getActiveRequestTracer(params.tracer); const runScrape = async (): Promise<{ status: number; body: Record; via: string; retryAfter?: string }> => { @@ -5197,6 +5201,60 @@ export async function executeScrapeCall(params: { formatted = registryTwin.formatTwin(twinBody, normalizedUrl, htmlFragToMd); } } + } else if ( + registryTwin.id === 'nostr-relays' && + callCoreWasm<{ enabled?: boolean }>('nostr_prepare_nip01', { url: normalizedUrl, ...(selfHost ? { selfHost } : {}) }).enabled + ) { + const nip11Url = `${parsedUrl.origin}/`; + activeFetchUrl = nip11Url; + const twinPolicy = resolveAdapterPolicyForUrl(nip11Url); + const twinMinIntervalMs = Math.max(registryTwin.minIntervalMs ?? 0, twinPolicy.minIntervalMs ?? 0); + const twinRes = await executeHubFetch( + target, + JSON.stringify({ + maxSeconds: 30, + options: { + includeBody: true, + respectRobots: true, + maxBytes: registryTwin.maxBytes ?? MAX_WASM_INPUT_BYTES, + maxInlineBodyBytes: MAX_WASM_INPUT_BYTES, + }, + requests: [ + buildTwinHubRequestSpec({ + requestId: `twin-${registryTwin.id}`, + twin: { ...registryTwin, fetchUrl: nip11Url }, + fallbackUaProfile: hostAdapterPolicy.userAgentProfile, + }), + ], + }), + site, + `${source}:extractor:${registryTwin.id}`, + retentionMode, + true, + collectionId, + ); + twinVia = twinRes.via; + twinDispatchStatus = twinRes.status; + if (twinRes.status === 200) { + const twinParsed = JSON.parse(twinRes.bodyText) as { results?: Array> }; + twinItem = twinParsed.results?.[0]; + const nostrOut = await runNostrNip11AndNip01AfterHubFetch({ + normalizedUrl, + nip11Url, + nostrHost: parsedUrl.hostname.toLowerCase().replace(/\.+$/, ''), + twinId: registryTwin.id, + twinItem, + twinMinIntervalMs, + selfHost, + sleepFn, + webSocketFactory: params.webSocketFactory, + }); + if (nostrOut.trusted) { + formatted = nostrOut.formatted; + } else if (twinItem && twinItem.outcome !== 'ok') { + reusedTwinFetchRes = twinRes; + } + } } else { const twinRes = await executeHubFetch( target, diff --git a/hub/src/twin-transport.ts b/hub/src/twin-transport.ts index f612dcd..54393a3 100644 --- a/hub/src/twin-transport.ts +++ b/hub/src/twin-transport.ts @@ -15,8 +15,14 @@ import { resolveOfficialApiProviderSpecForUrl, scrubSecretFromText, } from './api-keys'; -import { findRegisteredAdapterById, type SiteExtractorTwin } from './extractors/registry'; -import { decodeBase64TextWireBody, validatePublicHttpsTargetUrl } from './overflow'; +import { findRegisteredAdapterById, type SiteExtractorTwin, type TwinFormattedDoc } from './extractors/registry'; +import { isSafePublicHttpsUrl } from './mcp-registry'; +import { + decodeBase64TextWireBody, + getProcessHostLastFetchAt, + recordProcessHostFetch, + validatePublicHttpsTargetUrl, +} from './overflow'; import { classifyWafAndChallenge, type WafClassification } from './waf'; import { callCoreWasm, MAX_WASM_INPUT_BYTES } from './wasm-bridge'; @@ -464,3 +470,213 @@ export function sliceToPolicyMaxFetchBytes(raw: string, maxFetchBytes?: number): if (last >= 0xd800 && last <= 0xdbff) end--; return raw.slice(0, end); } + +export async function fetchNostrRelayNip01Events(params: { + url: string; + selfHost?: string; + timeoutMs?: number; + maxBytes?: number; + maxEvents?: number; + webSocketFactory?: (wssUrl: string) => WebSocket; +}): Promise< + | { ok: true; wssUrl: string; subId: string; frames: string[]; events: unknown[] } + | { ok: false; reason: string; events: [] } +> { + const safe = isSafePublicHttpsUrl(params.url, params.selfHost); + if (!safe.ok) { + return { ok: false, reason: safe.reason, events: [] }; + } + const timeoutMs = Math.min(5_000, Math.max(100, Math.floor(params.timeoutMs ?? 5_000))); + const maxBytes = Math.min(512 * 1024, Math.max(1024, Math.floor(params.maxBytes ?? 512 * 1024))); + const maxEvents = Math.min(20, Math.max(1, Math.floor(params.maxEvents ?? 20))); + const subId = `ef-${crypto.randomUUID().slice(0, 12)}`; + const plan = callCoreWasm<{ + ok: boolean; + reason?: string; + wssUrl?: string; + reqFrame?: string; + closeFrame?: string; + }>('nostr_prepare_nip01', { + url: params.url, + ...(params.selfHost ? { selfHost: params.selfHost } : {}), + subId, + maxEvents, + }); + if (!plan.ok || !plan.wssUrl || !plan.reqFrame || !plan.closeFrame) { + return { ok: false, reason: plan.reason || 'invalid_nostr_url', events: [] }; + } + + let ws: WebSocket | null = null; + try { + ws = params.webSocketFactory + ? params.webSocketFactory(plan.wssUrl) + : typeof globalThis.WebSocket === 'function' + ? new globalThis.WebSocket(plan.wssUrl) + : null; + } catch { + ws = null; + } + if (!ws) { + return { ok: false, reason: 'websocket_unavailable', events: [] }; + } + + const encoder = new TextEncoder(); + const frames: string[] = []; + let eventFramesSeen = 0; + let totalBytes = 0; + const eosePrefix = `["EOSE","${subId}"`; + const closedPrefix = `["CLOSED","${subId}"`; + const eventPrefix = `["EVENT","${subId}"`; + + await new Promise((resolve) => { + let settled = false; + let sentClose = false; + const finish = () => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (!sentClose && ws && ws.readyState === 1) { + sentClose = true; + try { + ws.send(plan.closeFrame!); + } catch { + // ignore + } + } + if (ws && (ws.readyState === 0 || ws.readyState === 1)) { + try { + ws.close(1000); + } catch { + // ignore + } + } + resolve(); + }; + const timer = setTimeout(finish, timeoutMs); + + const onOpen = () => { + if (settled || !ws) return; + try { + ws.send(plan.reqFrame!); + } catch { + finish(); + } + }; + const onMessage = (ev: { data?: unknown }) => { + if (settled) return; + const data = ev?.data; + let msgBytes = 0; + let text = ''; + if (typeof data === 'string') { + msgBytes = encoder.encode(data).byteLength; + text = data; + } else if (data instanceof ArrayBuffer) { + msgBytes = data.byteLength; + text = new TextDecoder().decode(data); + } else if (ArrayBuffer.isView(data)) { + msgBytes = data.byteLength; + text = new TextDecoder().decode(data); + } + totalBytes += msgBytes; + if (totalBytes > maxBytes) { + finish(); + return; + } + if (!text) return; + const compact = text.replace(/\s+/g, ''); + if (compact.startsWith(eosePrefix)) { + finish(); + return; + } + if (compact.startsWith(closedPrefix)) { + sentClose = true; + finish(); + return; + } + if (frames.length < maxEvents * 2 + 8) { + frames.push(text); + if (compact.startsWith(eventPrefix)) { + eventFramesSeen++; + if (eventFramesSeen >= maxEvents) { + finish(); + } + } + } else { + finish(); + } + }; + + if (typeof ws.addEventListener === 'function') { + ws.addEventListener('open', onOpen); + ws.addEventListener('message', onMessage as EventListener); + ws.addEventListener('error', finish); + ws.addEventListener('close', finish); + } else { + ws.onopen = onOpen; + ws.onmessage = onMessage as (ev: MessageEvent) => void; + ws.onerror = finish; + ws.onclose = finish; + } + if (ws.readyState === 1) { + onOpen(); + } + }); + + const parsedEvents = + frames.length > 0 + ? (callCoreWasm<{ events?: unknown[] }>('nostr_format_nip01', { subId, frames, maxEvents }).events ?? []) + : []; + return { ok: true, wssUrl: plan.wssUrl, subId, frames, events: parsedEvents }; +} + +export async function runNostrNip11AndNip01AfterHubFetch(params: { + normalizedUrl: string; + nip11Url: string; + nostrHost: string; + twinId: string; + twinItem: Record | undefined; + twinMinIntervalMs: number; + selfHost?: string; + sleepFn: (ms: number) => Promise; + webSocketFactory?: (wssUrl: string) => WebSocket; +}): Promise<{ trusted: boolean; formatted: TwinFormattedDoc | null }> { + const { normalizedUrl, nip11Url, nostrHost, twinId, twinItem, twinMinIntervalMs, selfHost, sleepFn, webSocketFactory } = params; + const nip11Raw = + typeof twinItem?.body === 'string' && twinItem.bodyEncoding !== 'base64' ? twinItem.body : ''; + const trusted = + Boolean(twinItem && twinItem.outcome === 'ok') && + isTrustedTwinRedirectUrl(twinId, nip11Url, twinItem!, selfHost) && + !isTwinRedirectedToErrorPage(nip11Url, twinItem); + if (!twinItem || twinItem.outcome !== 'ok' || !trusted) { + return { trusted, formatted: null }; + } + if (twinMinIntervalMs > 0) { + const prevDone = getProcessHostLastFetchAt(nostrHost); + if (prevDone !== undefined) { + const wait = prevDone + twinMinIntervalMs - Date.now(); + if (wait > 0) { + await sleepFn(wait); + } + } + } + const wsRes = await fetchNostrRelayNip01Events({ + url: normalizedUrl, + selfHost, + timeoutMs: 5_000, + maxBytes: 512 * 1024, + maxEvents: 20, + webSocketFactory, + }); + if (twinMinIntervalMs > 0 && getProcessHostLastFetchAt(nostrHost) !== undefined) { + recordProcessHostFetch(nostrHost, Date.now()); + } + const fmtRes = callCoreWasm<{ ok: boolean; doc?: TwinFormattedDoc }>('nostr_format_nip01', { + origUrl: normalizedUrl, + relayUrl: nip11Url, + subId: wsRes.ok ? wsRes.subId : '', + nip11Raw, + frames: wsRes.ok ? wsRes.frames : [], + maxEvents: 20, + }); + return { trusted: true, formatted: fmtRes.ok && fmtRes.doc ? fmtRes.doc : null }; +} diff --git a/hub/test/fixtures/adapters/bandcamp.json b/hub/test/fixtures/adapters/bandcamp.json new file mode 100644 index 0000000..121c6d1 --- /dev/null +++ b/hub/test/fixtures/adapters/bandcamp.json @@ -0,0 +1,36 @@ +{ + "adapterId": "bandcamp", + "mode": "html", + "inputUrl": "https://c418.bandcamp.com/album/minecraft-volume-alpha", + "mockPayload": "Minecraft - Volume Alpha | C418

Minecraft - Volume Alpha

", + "expectTitleIncludes": "Minecraft - Volume Alpha", + "expectMarkdownIncludes": [ + "C418", + "7.00 USD", + "Sweden", + "ambient, electronic, soundtrack" + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "Bandcamp

Sorry, that something isn't here.

" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://bandcamp.com/error", + "payload": "404 Not Found

Not Found

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "payload": "Bandcamp
" + } + ] +} diff --git a/hub/test/fixtures/adapters/discogs.json b/hub/test/fixtures/adapters/discogs.json new file mode 100644 index 0000000..3962800 --- /dev/null +++ b/hub/test/fixtures/adapters/discogs.json @@ -0,0 +1,45 @@ +{ + "adapterId": "discogs", + "mode": "twin", + "inputUrl": "https://api.discogs.com/releases/249504", + "expectedFetchUrl": "https://api.discogs.com/releases/249504", + "mockPayload": "{\"id\":249504,\"title\":\"Never Gonna Give You Up\",\"artists_sort\":\"Rick Astley\",\"year\":1987,\"released\":\"1987-07-27\",\"country\":\"UK\",\"genres\":[\"Electronic\",\"Pop\"],\"styles\":[\"Synth-pop\"],\"labels\":[{\"name\":\"RCA\",\"catno\":\"PB 41447\"}],\"lowest_price\":1.99,\"num_for_sale\":42,\"uri\":\"https://www.discogs.com/release/249504-Rick-Astley-Never-Gonna-Give-You-Up\",\"tracklist\":[{\"position\":\"A\",\"title\":\"Never Gonna Give You Up\",\"duration\":\"3:32\"},{\"position\":\"B\",\"title\":\"Never Gonna Give You Up (Instrumental)\",\"duration\":\"3:30\"}]}", + "expectTitleIncludes": "Never Gonna Give You Up", + "expectMarkdownIncludes": [ + "249504", + "Rick Astley", + "1987", + "Synth-pop", + "RCA (PB 41447)" + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "{\"message\":\"Release not found.\"}" + }, + { + "name": "cloudflare-challenge-html", + "status": 403, + "inputUrl": "https://www.discogs.com/release/249504-Rick-Astley-Never-Gonna-Give-You-Up", + "payload": "Just a moment...
cf-mitigated challenge
" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.discogs.com/error", + "payload": "404 Not Found

Not Found

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "inputUrl": "https://www.discogs.com/release/missing", + "payload": "Discogs
" + } + ] +} diff --git a/hub/test/fixtures/adapters/energy-star.json b/hub/test/fixtures/adapters/energy-star.json new file mode 100644 index 0000000..3f89a0e --- /dev/null +++ b/hub/test/fixtures/adapters/energy-star.json @@ -0,0 +1,38 @@ +{ + "adapterId": "energy-star", + "mode": "twin", + "inputUrl": "https://data.energystar.gov/resource/7p2p-wkbf.json?$limit=2", + "expectedFetchUrl": "https://data.energystar.gov/resource/7p2p-wkbf.json?$limit=2", + "mockPayload": "[{\"pd_id\":\"2406498\",\"energy_star_partner\":\"LG Electronics, Inc.\",\"brand_name\":\"LG\",\"model_name\":\"LRYXC2606S\",\"model_number\":\"LRYXC2606S\",\"annual_energy_use_kwh_yr\":\"589\",\"date_certified\":\"2024-02-15\"}]", + "expectTitleIncludes": "ENERGY STAR: LG LRYXC2606S", + "expectMarkdownIncludes": [ + "2406498", + "LG Electronics, Inc.", + "LRYXC2606S", + "2024-02-15" + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "{\"code\":\"not_found\",\"error\":true,\"message\":\"Dataset not found\"}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.energystar.gov/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "unhydrated-productfinder-spa-shell", + "status": 200, + "inputUrl": "https://www.energystar.gov/productfinder/product/certified-residential-refrigerators/details/2406498", + "payload": "ENERGY STAR
" + } + ] +} diff --git a/hub/test/fixtures/adapters/farcaster-hub.json b/hub/test/fixtures/adapters/farcaster-hub.json new file mode 100644 index 0000000..84c1ad7 --- /dev/null +++ b/hub/test/fixtures/adapters/farcaster-hub.json @@ -0,0 +1,43 @@ +{ + "adapterId": "farcaster-hub", + "mode": "twin", + "inputUrl": "https://fnames.farcaster.xyz/transfers?fid=3", + "expectedFetchUrl": "https://fnames.farcaster.xyz/transfers?fid=3", + "mockPayload": "{\"transfers\":[{\"id\":3,\"timestamp\":1675209600,\"username\":\"dwr\",\"owner\":\"0x8773442740c17c9d0f0b87022c722f9a136206ed\",\"from\":0,\"to\":3}]}", + "expectTitleIncludes": "Farcaster Name Transfers", + "expectMarkdownIncludes": [ + "dwr", + "0x8773442740c17c9d0f0b87022c722f9a136206ed", + "2023-02-01" + ], + "negativeCases": [ + { + "name": "http-402-neynar-key-required", + "status": 402, + "inputUrl": "https://hub-api.neynar.com/v1/castsByFid?fid=3&pageSize=5", + "payload": "{\"code\":\"PaymentRequired\",\"message\":\"X-PAYMENT header or API key required\"}" + }, + { + "name": "empty-transfers-404", + "status": 404, + "payload": "{\"transfers\":[]}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://farcaster.xyz/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell-html", + "status": 200, + "inputUrl": "https://farcaster.xyz/dwr", + "payload": "Farcaster
" + } + ] +} diff --git a/hub/test/fixtures/adapters/fcc-test-report.json b/hub/test/fixtures/adapters/fcc-test-report.json new file mode 100644 index 0000000..77f8450 --- /dev/null +++ b/hub/test/fixtures/adapters/fcc-test-report.json @@ -0,0 +1,42 @@ +{ + "adapterId": "fcc-test-report", + "mode": "html", + "inputUrl": "https://apps.fcc.gov/oetcf/eas/reports/ViewExhibitReport.cfm?mode=Exhibits&RequestTimeout=500&calledFromFrame=N&application_id=123456&fcc_id=BCG-E3542A", + "mockPayload": "FCC OET Equipment Authorization - FCC ID BCG-E3542A

FCC OET Equipment Authorization: FCC ID BCG-E3542A

ApplicantApple Inc.
Equipment ClassDTS - Digital Transmission System
Frequency Range2402 - 2480 MHz
Grant Date2024-09-10

Exhibits

Test Report PDFRF Exposure Info
", + "expectTitleIncludes": "FCC ID BCG-E3542A", + "expectMarkdownIncludes": [ + "`BCG-E3542A`", + "Apple Inc.", + "2402 - 2480 MHz", + "Test Report PDF" + ], + "negativeCases": [ + { + "name": "akamai-access-denied-403", + "status": 403, + "payload": "Access Denied

Access Denied

You don't have permission to access \"http://apps.fcc.gov/oetcf/eas/reports/GenericSearch.cfm\" on this server.

Reference #18.1234abcd

" + }, + { + "name": "http-404", + "status": 404, + "payload": "404 Not Found

Not Found

" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://apps.fcc.gov/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-search-form-shell", + "status": 200, + "inputUrl": "https://apps.fcc.gov/oetcf/eas/reports/GenericSearch.cfm", + "payload": "OET Equipment Authorization Search

Generic Search

" + } + ] +} diff --git a/hub/test/fixtures/adapters/fed-h15-datadownload.json b/hub/test/fixtures/adapters/fed-h15-datadownload.json new file mode 100644 index 0000000..14c545a --- /dev/null +++ b/hub/test/fixtures/adapters/fed-h15-datadownload.json @@ -0,0 +1,39 @@ +{ + "adapterId": "fed-h15-datadownload", + "mode": "twin", + "inputUrl": "https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15&series=bf17364827e38702b42a58cf8eaa3f78&lastobs=5&from=&to=&filetype=csv&label=include&layout=seriescolumn", + "expectedFetchUrl": "https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15&series=bf17364827e38702b42a58cf8eaa3f78&lastobs=5&from=&to=&filetype=csv&label=include&layout=seriescolumn", + "mockPayload": "\"Series Description\",\"Market yield on U.S. Treasury securities at 10-year constant maturity, quoted on investment basis\"\n\"Unit:\",\"Percent:_Per_Year\"\n\"Multiplier:\",\"1\"\n\"Currency:\",\"NA\"\n\"Unique Identifier:\",\"H15/H15/RIFLGFCY10_N.B\"\n\"Time Period\",\"RIFLGFCY10_N.B\"\n2026-11-23,4.25\n2026-11-24,4.28\n2026-11-25,4.22\n", + "expectTitleIncludes": "Federal Reserve H.15", + "expectMarkdownIncludes": [ + "H15/H15/RIFLGFCY10_N.B", + "Percent:_Per_Year", + "2026-11-23", + "4.25", + "2026-11-25", + "4.22" + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "404 Page Not Found - Federal Reserve

Page Not Found

" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.federalreserve.gov/error", + "payload": "Error

Request Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "unsupported-html-response", + "status": 200, + "payload": "Data Download Program
" + } + ] +} diff --git a/hub/test/fixtures/adapters/ffiec-cdr.json b/hub/test/fixtures/adapters/ffiec-cdr.json new file mode 100644 index 0000000..8223beb --- /dev/null +++ b/hub/test/fixtures/adapters/ffiec-cdr.json @@ -0,0 +1,37 @@ +{ + "adapterId": "ffiec-cdr", + "mode": "html", + "inputUrl": "https://cdr.ffiec.gov/public/ManageFacsimiles.aspx", + "mockPayload": "FFIEC Central Data Repository - View or Download Data

FFIEC Central Data Repository: View or Download Data

RSSD IDInstitution NameCityState
480228JPMorgan Chase Bank, National AssociationColumbusOH
Download Bulk Data
", + "expectTitleIncludes": "FFIEC Central Data Repository", + "expectMarkdownIncludes": [ + "Call Reports -- Single Period", + "2026-09-30", + "480228", + "JPMorgan Chase Bank", + "DownloadBulkData.aspx" + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "404 Not Found

Resource Not Found

" + }, + { + "name": "redirect-to-error-aspx", + "status": 200, + "finalUrl": "https://cdr.ffiec.gov/public/Error.aspx", + "payload": "Runtime Error

Server Error in '/' Application

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Site Under Maintenance

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "payload": "FFIEC CDR
" + } + ] +} diff --git a/hub/test/fixtures/adapters/genius-lyrics.json b/hub/test/fixtures/adapters/genius-lyrics.json new file mode 100644 index 0000000..401c82f --- /dev/null +++ b/hub/test/fixtures/adapters/genius-lyrics.json @@ -0,0 +1,48 @@ +{ + "adapterId": "genius-lyrics", + "mode": "html", + "inputUrl": "https://genius.com/Rick-astley-never-gonna-give-you-up-lyrics", + "mockPayload": "Rick Astley - Never Gonna Give You Up Lyrics | Genius Lyrics

Never Gonna Give You Up

[Verse 1]
We're no strangers to love
You know the rules and so do I
[Chorus]
Never gonna give you up
Never gonna let you down
", + "expectTitleIncludes": "Rick Astley - Never Gonna Give You Up", + "expectMarkdownIncludes": [ + "Rick Astley", + "Whenever You Need Somebody", + "We're no strangers to love", + "Never gonna give you up", + "Opening line introducing" + ], + "negativeCases": [ + { + "name": "cloudflare-genius-shell", + "status": 403, + "payload": "Genius
cf-mitigated
" + }, + { + "name": "genius-title-without-lyrics-container", + "status": 200, + "payload": "Genius
" + }, + { + "name": "http-404", + "status": 404, + "payload": "404 Not Found | Genius

We couldn't find that

" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://genius.com/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "inputUrl": "https://www.musixmatch.com/lyrics/Rick-Astley/Missing", + "payload": "Musixmatch
" + } + ] +} diff --git a/hub/test/fixtures/adapters/gs1-us-datahub.json b/hub/test/fixtures/adapters/gs1-us-datahub.json new file mode 100644 index 0000000..4cc7ce7 --- /dev/null +++ b/hub/test/fixtures/adapters/gs1-us-datahub.json @@ -0,0 +1,44 @@ +{ + "adapterId": "gs1-us-datahub", + "mode": "twin", + "inputUrl": "https://api.gs1us.org/gtins/0012000161155", + "expectedFetchUrl": "https://api.gs1us.org/gtins/0012000161155", + "mockPayload": "{\"gtin\":\"0012000161155\",\"companyName\":\"PepsiCo, Inc.\",\"brandName\":\"LIFEWTR\",\"gln\":\"0012000000008\",\"gs1CompanyPrefix\":\"0012000\",\"gtinStatus\":\"ACTIVE\",\"productDescription\":\"LIFEWTR Purified Water 700mL Bottle\",\"gpcCategoryName\":\"Bottled Water\",\"targetMarket\":\"US\"}", + "expectTitleIncludes": "0012000161155", + "expectMarkdownIncludes": [ + "0012000161155", + "PepsiCo, Inc.", + "LIFEWTR", + "0012000", + "ACTIVE" + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "{\"statusCode\":404,\"message\":\"Resource not found\"}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.gs1us.org/error", + "payload": "Error

Something went wrong

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Service Unavailable

" + }, + { + "name": "unauthorized-401", + "status": 401, + "payload": "{\"statusCode\":401,\"message\":\"Unauthorized: invalid API key\"}" + }, + { + "name": "empty-spa-shell", + "status": 200, + "inputUrl": "https://www.gs1us.org/tools/gs1-company-database-gepir", + "payload": "GS1 US
" + } + ] +} diff --git a/hub/test/fixtures/adapters/igdb.json b/hub/test/fixtures/adapters/igdb.json new file mode 100644 index 0000000..c718b04 --- /dev/null +++ b/hub/test/fixtures/adapters/igdb.json @@ -0,0 +1,43 @@ +{ + "adapterId": "igdb", + "mode": "twin", + "inputUrl": "https://www.igdb.com/games/portal-2", + "expectedFetchUrl": "https://api.igdb.com/v4/games", + "mockPayload": "[{\"id\":72,\"name\":\"Portal 2\",\"slug\":\"portal-2\",\"rating\":91.8,\"rating_count\":3400,\"summary\":\"Sequel to the acclaimed Portal (2007), featuring a co-op campaign and physics-based puzzle chambers.\",\"genres\":[{\"id\":9,\"name\":\"Puzzle\"},{\"id\":5,\"name\":\"Shooter\"}],\"platforms\":[{\"id\":6,\"name\":\"PC (Microsoft Windows)\"},{\"id\":14,\"name\":\"Mac\"}],\"url\":\"https://www.igdb.com/games/portal-2\"}]", + "expectTitleIncludes": "Portal 2", + "expectMarkdownIncludes": [ + "72", + "91.8", + "Puzzle, Shooter", + "PC (Microsoft Windows)" + ], + "negativeCases": [ + { + "name": "empty-results-array", + "status": 200, + "payload": "[]" + }, + { + "name": "unauthorized-401", + "status": 401, + "payload": "{\"message\":\"Authorization Failure\"}" + }, + { + "name": "cloudflare-challenge-html", + "status": 403, + "inputUrl": "https://www.igdb.com/games/missing", + "payload": "Just a moment...
cf-mitigated challenge
" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.igdb.com/error", + "payload": "404 Not Found

Not Found

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + } + ] +} diff --git a/hub/test/fixtures/adapters/imdb-datasets.json b/hub/test/fixtures/adapters/imdb-datasets.json new file mode 100644 index 0000000..fa1fc48 --- /dev/null +++ b/hub/test/fixtures/adapters/imdb-datasets.json @@ -0,0 +1,44 @@ +{ + "adapterId": "imdb-datasets", + "mode": "twin", + "inputUrl": "https://datasets.imdbws.com/title.ratings.tsv.gz", + "expectedFetchUrl": "https://datasets.imdbws.com/title.ratings.tsv.gz", + "mockPayload": "tconst\taverageRating\tnumVotes\ntt0000001\t5.7\t2244\ntt0000002\t5.5\t308\ntt0000003\t6.5\t2286\n", + "expectTitleIncludes": "title.ratings.tsv.gz", + "expectMarkdownIncludes": [ + "IMDb Non-Commercial Datasets", + "nonCommercialLicense: true", + "tt0000001", + "5.7", + "2244" + ], + "negativeCases": [ + { + "name": "http-404-nosuchkey", + "status": 404, + "payload": "NoSuchKeyThe specified key does not exist." + }, + { + "name": "access-denied-403", + "status": 403, + "payload": "AccessDeniedAccess Denied" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://data.imdb.com/error", + "payload": "404 Not Found

Not Found

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-tsv", + "status": 200, + "inputUrl": "https://data.imdb.com/non-commercial-datasets/", + "payload": "IMDb Datasets
" + } + ] +} diff --git a/hub/test/fixtures/adapters/market-quotes-pack.json b/hub/test/fixtures/adapters/market-quotes-pack.json new file mode 100644 index 0000000..c88fdff --- /dev/null +++ b/hub/test/fixtures/adapters/market-quotes-pack.json @@ -0,0 +1,42 @@ +{ + "adapterId": "market-quotes-pack", + "mode": "twin", + "inputUrl": "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=IBM", + "expectedFetchUrl": "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=IBM", + "mockPayload": "{\"Global Quote\":{\"01. symbol\":\"IBM\",\"02. open\":\"221.5000\",\"03. high\":\"224.1000\",\"04. low\":\"220.8000\",\"05. price\":\"223.4500\",\"06. volume\":\"3412500\",\"07. latest trading day\":\"2026-11-27\",\"08. previous close\":\"221.1000\",\"09. change\":\"2.3500\",\"10. change percent\":\"1.0629%\"}}", + "expectTitleIncludes": "IBM Global Quote", + "expectMarkdownIncludes": [ + "`IBM`", + "223.4500", + "2026-11-27", + "1.0629%" + ], + "negativeCases": [ + { + "name": "alphavantage-rate-limit-note", + "status": 200, + "payload": "{\"Information\":\"Thank you for using Alpha Vantage! Our standard API rate limit is 25 requests per day.\"}" + }, + { + "name": "http-404-error-message", + "status": 404, + "payload": "{\"Error Message\":\"Invalid API call. Please retry or visit the documentation.\"}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.alphavantage.co/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Service Unavailable

" + }, + { + "name": "empty-json", + "status": 200, + "payload": "{}" + } + ] +} diff --git a/hub/test/fixtures/adapters/msrb-emma.json b/hub/test/fixtures/adapters/msrb-emma.json new file mode 100644 index 0000000..d0346f0 --- /dev/null +++ b/hub/test/fixtures/adapters/msrb-emma.json @@ -0,0 +1,42 @@ +{ + "adapterId": "msrb-emma", + "mode": "html", + "inputUrl": "https://emma.msrb.org/Security/Details/A1B2C3D4E5", + "mockPayload": "State of California General Obligation Bond - MSRB EMMA

State of California General Obligation Bond, Series 2025A

CUSIP
13063D2M4
Issuer
State of California
Coupon Rate
5.00%
Maturity Date
2035-10-01
Par Amount
$150,000,000
Trade DatePriceYieldAmount
2026-11-24106.454.12%$250,000
Official Statement PDF
", + "expectTitleIncludes": "State of California General Obligation Bond", + "expectMarkdownIncludes": [ + "`13063D2M4`", + "5.00%", + "2035-10-01", + "$150,000,000", + "106.45" + ], + "negativeCases": [ + { + "name": "awselb-403-waf", + "status": 403, + "payload": "403 Forbidden

403 Forbidden


awselb/2.0
" + }, + { + "name": "http-404", + "status": 404, + "payload": "404 Page Not Found

Security Not Found

" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://emma.msrb.org/error", + "payload": "Error

Application Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "payload": "MSRB EMMA
" + } + ] +} diff --git a/hub/test/fixtures/adapters/musicbrainz-coverart.json b/hub/test/fixtures/adapters/musicbrainz-coverart.json new file mode 100644 index 0000000..cc93da7 --- /dev/null +++ b/hub/test/fixtures/adapters/musicbrainz-coverart.json @@ -0,0 +1,43 @@ +{ + "adapterId": "musicbrainz-coverart", + "mode": "twin", + "inputUrl": "https://coverartarchive.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd", + "expectedFetchUrl": "https://coverartarchive.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd", + "mockPayload": "{\"images\":[{\"approved\":true,\"back\":false,\"comment\":\"Front cover\",\"edit\":10234567,\"front\":true,\"id\":1234567890,\"image\":\"https://coverartarchive.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd/1234567890.jpg\",\"types\":[\"Front\"]}],\"release\":\"https://musicbrainz.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd\"}", + "expectTitleIncludes": "Cover Art Archive", + "expectMarkdownIncludes": [ + "76df3287-6cda-33eb-8e9a-044b5e15ffdd", + "Front", + "1234567890" + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "{\"error\":\"Not Found\"}" + }, + { + "name": "pow-meb-verify-challenge", + "status": 200, + "inputUrl": "https://musicbrainz.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd", + "payload": "Verifying your browser
" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://coverartarchive.org/error", + "payload": "404 Not Found

Not Found

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "inputUrl": "https://musicbrainz.org/release/missing", + "payload": "MusicBrainz
" + } + ] +} diff --git a/hub/test/fixtures/adapters/nasdaq-data-link.json b/hub/test/fixtures/adapters/nasdaq-data-link.json new file mode 100644 index 0000000..da53ca1 --- /dev/null +++ b/hub/test/fixtures/adapters/nasdaq-data-link.json @@ -0,0 +1,42 @@ +{ + "adapterId": "nasdaq-data-link", + "mode": "twin", + "inputUrl": "https://data.nasdaq.com/api/v3/datasets/FRED/GDP.json?rows=5", + "expectedFetchUrl": "https://data.nasdaq.com/api/v3/datasets/FRED/GDP.json?rows=5", + "mockPayload": "{\"dataset\":{\"id\":120140,\"dataset_code\":\"GDP\",\"database_code\":\"FRED\",\"name\":\"Gross Domestic Product\",\"description\":\"Gross Domestic Product, Billions of Dollars, Quarterly\",\"frequency\":\"quarterly\",\"type\":\"Time Series\",\"oldest_available_date\":\"1947-01-01\",\"newest_available_date\":\"2026-07-01\",\"column_names\":[\"Date\",\"Value\"],\"data\":[[\"2026-07-01\",29354.321],[\"2026-04-01\",29016.714]]}}", + "expectTitleIncludes": "Gross Domestic Product", + "expectMarkdownIncludes": [ + "FRED/GDP", + "quarterly", + "2026-07-01", + "29354.321" + ], + "negativeCases": [ + { + "name": "http-404-quandl-error", + "status": 404, + "payload": "{\"quandl_error\":{\"code\":\"QECx02\",\"message\":\"You have submitted an incorrect Quandl code.\"}}" + }, + { + "name": "incapsula-waf-403", + "status": 403, + "payload": "Request Rejected" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://data.nasdaq.com/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-json", + "status": 200, + "payload": "{}" + } + ] +} diff --git a/hub/test/fixtures/adapters/nostr-relays.json b/hub/test/fixtures/adapters/nostr-relays.json new file mode 100644 index 0000000..a4a1cf6 --- /dev/null +++ b/hub/test/fixtures/adapters/nostr-relays.json @@ -0,0 +1,50 @@ +{ + "adapterId": "nostr-relays", + "mode": "twin", + "inputUrl": "https://nos.lol/", + "expectedFetchUrl": "https://nos.lol/", + "mockPayload": "{\"relay\":\"https://nos.lol/\",\"nip11\":{\"name\":\"nos.lol\",\"description\":\"A public Nostr relay running strfry.\",\"pubkey\":\"f86e7c5a1f0b1234567890abcdef1234567890abcdef1234567890abcdef1234\",\"contact\":\"mailto:admin@nos.lol\",\"supported_nips\":[1,2,4,9,11,12,15,16,20,22,28,33,40],\"software\":\"https://github.com/hoytech/strfry\",\"version\":\"1.0.0\",\"limitation\":{\"max_message_length\":65536,\"max_subscriptions\":20,\"auth_required\":false,\"payment_required\":false}},\"events\":[{\"id\":\"aaaa1111bbbb2222cccc3333dddd4444eeee5555ffff66667777888899990000\",\"pubkey\":\"1111222233334444555566667777888899990000aaaabbbbccccddddeeeeffff\",\"created_at\":1732838400,\"kind\":1,\"tags\":[[\"t\",\"nostr\"],[\"r\",\"https://nos.lol/\"]],\"content\":\"Hello Nostr! Testing bounded NIP-01 REQ extraction.\",\"sig\":\"deadbeef\"}]}", + "expectTitleIncludes": "nos.lol", + "expectMarkdownIncludes": [ + "strfry", + "1, 2, 4, 9, 11", + "Recent Nostr Events", + "Hello Nostr!", + "Testing bounded NIP-01 REQ extraction." + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "{\"error\":\"Not found\"}" + }, + { + "name": "empty-nip11-object", + "status": 404, + "payload": "{}" + }, + { + "name": "empty-spa-shell-njump", + "status": 200, + "inputUrl": "https://njump.me/nevent1qqsmissing000", + "payload": "njump
" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://njump.me/error", + "payload": "Error

Event not found

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Service Unavailable

" + }, + { + "name": "njump-not-found-404", + "status": 404, + "inputUrl": "https://njump.me/nevent1qqsmissing000", + "payload": "Event not found | njump

Event not found

" + } + ] +} diff --git a/hub/test/fixtures/adapters/open-icecat.json b/hub/test/fixtures/adapters/open-icecat.json new file mode 100644 index 0000000..844dfe1 --- /dev/null +++ b/hub/test/fixtures/adapters/open-icecat.json @@ -0,0 +1,44 @@ +{ + "adapterId": "open-icecat", + "mode": "twin", + "inputUrl": "https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=8710103792772", + "expectedFetchUrl": "https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=8710103792772", + "mockPayload": "{\"msg\":\"OK\",\"data\":{\"GeneralInfo\":{\"IcecatId\":32928991,\"Title\":\"Saeco CA6705/60 milk circuit cleaner\",\"Brand\":\"Saeco\",\"BrandInfo\":{\"BrandName\":\"Saeco\"},\"BrandPartCode\":\"CA6705/60\",\"GTIN\":[\"8710103792772\"],\"Category\":{\"Name\":{\"Value\":\"Coffee Maker Accessories\"}},\"ReleaseDate\":\"2016-05-10\",\"SummaryDescription\":{\"ShortSummaryDescription\":\"Saeco CA6705/60 milk circuit cleaner protects milk circuits against clogging.\"},\"ProductPicture\":{\"HighPic\":\"https://images.icecat.biz/img/norm/high/32928991-4510.jpg\"}},\"FeaturesGroups\":[{\"FeatureGroup\":{\"Name\":{\"Value\":\"Technical details\"}},\"Features\":[{\"Feature\":{\"Name\":{\"Value\":\"Quantity per pack\"}},\"PresentationValue\":\"6 pc(s)\"}]}]}}", + "expectTitleIncludes": "Saeco CA6705/60", + "expectMarkdownIncludes": [ + "32928991", + "8710103792772", + "Saeco", + "CA6705/60", + "6 pc(s)" + ], + "negativeCases": [ + { + "name": "brand-restricted-404", + "status": 404, + "payload": "{\"StatusCode\":14,\"Code\":404,\"Error\":\"Brand is restricted for openicecat-live\"}" + }, + { + "name": "gtin-not-found-400", + "status": 400, + "payload": "{\"StatusCode\":16,\"Code\":400,\"Message\":\"GTIN not found\"}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://icecat.biz/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "nextjs-error-html", + "status": 404, + "inputUrl": "https://icecat.biz/en/p/missing/item.html", + "payload": "Icecat
__next_error__
" + } + ] +} diff --git a/hub/test/fixtures/adapters/open-product-wikidata-gtin.json b/hub/test/fixtures/adapters/open-product-wikidata-gtin.json new file mode 100644 index 0000000..5748a5f --- /dev/null +++ b/hub/test/fixtures/adapters/open-product-wikidata-gtin.json @@ -0,0 +1,43 @@ +{ + "adapterId": "open-product-wikidata-gtin", + "mode": "twin", + "inputUrl": "https://opengtindb.org/?ean=4006381333931&cmd=query&queryid=400000000", + "expectedFetchUrl": "https://opengtindb.org/?ean=4006381333931&cmd=query&queryid=400000000", + "mockPayload": "error=0\n---\nasin=\nname=Fineliner\ndetailname=Stabilo point 88 Fineliner 0.4mm\nvendor=Schwan-STABILO\nmaincat=Bürobedarf\nsubcat=Schreibgeräte\norigin=Deutschland\ndescr=Classic hexagonal fineliner pen.\n---", + "expectTitleIncludes": "Stabilo point 88", + "expectMarkdownIncludes": [ + "4006381333931", + "Schwan-STABILO", + "Deutschland", + "fineliner" + ], + "negativeCases": [ + { + "name": "opengtindb-error-1", + "status": 200, + "payload": "error=1\n---\n" + }, + { + "name": "http-404", + "status": 404, + "payload": "404 Not Found

Not Found

" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://opengtindb.org/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Service Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "inputUrl": "https://opengtindb.org/", + "payload": "OpenGTINdb
" + } + ] +} diff --git a/hub/test/fixtures/adapters/patreon-public.json b/hub/test/fixtures/adapters/patreon-public.json new file mode 100644 index 0000000..bdfe6d9 --- /dev/null +++ b/hub/test/fixtures/adapters/patreon-public.json @@ -0,0 +1,41 @@ +{ + "adapterId": "patreon-public", + "mode": "html", + "inputUrl": "https://www.patreon.com/cw/Kurzgesagt", + "mockPayload": "Kurzgesagt | Patreon

Kurzgesagt

", + "expectTitleIncludes": "Kurzgesagt", + "expectMarkdownIncludes": [ + "Creating animated science explainers and educational videos.", + "24500", + "animated science videos", + "Behind the Scenes: Black Holes" + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "Page not found | Patreon

404 Page Not Found

" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.patreon.com/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "login-gate", + "status": 200, + "payload": "Log in | Patreon

Log in to Patreon

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "payload": "Patreon
" + } + ] +} diff --git a/hub/test/fixtures/adapters/podcast-index.json b/hub/test/fixtures/adapters/podcast-index.json new file mode 100644 index 0000000..1bf5bd9 --- /dev/null +++ b/hub/test/fixtures/adapters/podcast-index.json @@ -0,0 +1,43 @@ +{ + "adapterId": "podcast-index", + "mode": "twin", + "inputUrl": "https://api.podcastindex.org/api/1.0/podcasts/byfeedid?id=920666", + "expectedFetchUrl": "https://api.podcastindex.org/api/1.0/podcasts/byfeedid?id=920666", + "mockPayload": "{\"status\":\"true\",\"feed\":{\"id\":920666,\"title\":\"Podcasting 2.0\",\"url\":\"https://mp3s.nashownotes.com/pc20rss.xml\",\"link\":\"https://podcastindex.org/\",\"author\":\"Adam Curry & Dave Jones\",\"ownerName\":\"Podcast Index LLC\",\"description\":\"Keeping podcasting open and independent.\",\"language\":\"en\",\"episodeCount\":195,\"itunesId\":1533880442,\"categories\":{\"55\":\"News\",\"102\":\"Technology\"}},\"description\":\"Found matching feed.\"}", + "expectTitleIncludes": "Podcasting 2.0", + "expectMarkdownIncludes": [ + "920666", + "Adam Curry", + "195", + "https://mp3s.nashownotes.com/pc20rss.xml" + ], + "negativeCases": [ + { + "name": "missing-auth-401", + "status": 401, + "payload": "{\"status\":\"false\",\"description\":\"Authorization header value either not set or blank.\"}" + }, + { + "name": "http-404", + "status": 404, + "payload": "{\"status\":\"false\",\"description\":\"Feed not found.\"}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://podcastindex.org/error", + "payload": "404 Not Found

Not Found

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "inputUrl": "https://podcastindex.org/", + "payload": "Podcast Index
" + } + ] +} diff --git a/hub/test/fixtures/adapters/product-hunt.json b/hub/test/fixtures/adapters/product-hunt.json new file mode 100644 index 0000000..ff87a38 --- /dev/null +++ b/hub/test/fixtures/adapters/product-hunt.json @@ -0,0 +1,49 @@ +{ + "adapterId": "product-hunt", + "mode": "twin", + "inputUrl": "https://api.producthunt.com/v2/api/graphql", + "expectedFetchUrl": "https://api.producthunt.com/v2/api/graphql", + "mockPayload": "{\"data\":{\"posts\":{\"edges\":[{\"node\":{\"id\":\"482910\",\"name\":\"EdgeFetch CLI\",\"tagline\":\"Fast web extraction for AI agents\",\"description\":\"Convert public pages and APIs into clean Markdown and structured records.\",\"votesCount\":642,\"commentsCount\":48,\"url\":\"https://www.producthunt.com/posts/edgefetch-cli\",\"website\":\"https://edgefetch.dev\",\"createdAt\":\"2026-11-28T08:00:00Z\",\"topics\":{\"edges\":[{\"node\":{\"name\":\"Developer Tools\"}}]},\"makers\":[{\"name\":\"Alex Rivera\",\"username\":\"arivera\"}]}}]}}}", + "expectTitleIncludes": "EdgeFetch CLI", + "expectMarkdownIncludes": [ + "Fast web extraction for AI agents", + "642", + "Developer Tools", + "Alex Rivera" + ], + "negativeCases": [ + { + "name": "http-401-invalid-token", + "status": 401, + "payload": "{\"errors\":[{\"error\":\"invalid_oauth_token\",\"error_description\":\"The access token is invalid\"}]}" + }, + { + "name": "empty-posts-edges", + "status": 404, + "payload": "{\"data\":{\"posts\":{\"edges\":[]}}}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.producthunt.com/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "cloudflare-challenge-html", + "status": 403, + "inputUrl": "https://www.producthunt.com/posts/claude-3-5-sonnet", + "payload": "Just a moment...
cf-mitigated challenge
" + }, + { + "name": "empty-spa-shell", + "status": 200, + "inputUrl": "https://www.producthunt.com/posts/claude-3-5-sonnet", + "payload": "Product Hunt
" + } + ] +} diff --git a/hub/test/fixtures/adapters/prop65-warnings.json b/hub/test/fixtures/adapters/prop65-warnings.json new file mode 100644 index 0000000..51b6900 --- /dev/null +++ b/hub/test/fixtures/adapters/prop65-warnings.json @@ -0,0 +1,41 @@ +{ + "adapterId": "prop65-warnings", + "mode": "html", + "inputUrl": "https://www.p65warnings.ca.gov/fact-sheets/acrylamide", + "mockPayload": "Acrylamide - Proposition 65 Warnings

Acrylamide

CAS Number
79-06-1
Type of Toxicity
Cancer, Male Reproductive, Developmental
Date Listed
1990-01-01

Acrylamide is listed under California Proposition 65 as known to the State to cause cancer and reproductive harm. It can form in starchy foods cooked at high temperatures.

", + "expectTitleIncludes": "Acrylamide", + "expectMarkdownIncludes": [ + "79-06-1", + "Cancer, Male Reproductive, Developmental", + "1990-01-01", + "Proposition 65" + ], + "negativeCases": [ + { + "name": "incapsula-waf-shell", + "status": 200, + "payload": " " + }, + { + "name": "http-404", + "status": 404, + "payload": "404 Page Not Found

Chemical not found

" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.p65warnings.ca.gov/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "payload": "Prop 65
" + } + ] +} diff --git a/hub/test/fixtures/adapters/sec-xbrl-frames.json b/hub/test/fixtures/adapters/sec-xbrl-frames.json new file mode 100644 index 0000000..4629be4 --- /dev/null +++ b/hub/test/fixtures/adapters/sec-xbrl-frames.json @@ -0,0 +1,43 @@ +{ + "adapterId": "sec-xbrl-frames", + "mode": "twin", + "inputUrl": "https://data.sec.gov/api/xbrl/frames/us-gaap/AccountsPayableCurrent/USD/CY2023Q4I.json", + "expectedFetchUrl": "https://data.sec.gov/api/xbrl/frames/us-gaap/AccountsPayableCurrent/USD/CY2023Q4I.json", + "mockPayload": "{\"taxonomy\":\"us-gaap\",\"tag\":\"AccountsPayableCurrent\",\"ccp\":\"CY2023Q4I\",\"uom\":\"USD\",\"label\":\"Accounts Payable, Current\",\"description\":\"Carrying value as of the balance sheet date of liabilities incurred.\",\"pts\":3909,\"data\":[{\"accn\":\"0000320193-24-000006\",\"cik\":320193,\"entityName\":\"Apple Inc.\",\"loc\":\"US-CA\",\"end\":\"2023-12-30\",\"val\":58146000000},{\"accn\":\"0000789019-24-000008\",\"cik\":789019,\"entityName\":\"MICROSOFT CORP\",\"loc\":\"US-WA\",\"end\":\"2023-12-31\",\"val\":17697000000}]}", + "expectTitleIncludes": "Accounts Payable, Current", + "expectMarkdownIncludes": [ + "us-gaap", + "AccountsPayableCurrent", + "CY2023Q4I", + "Apple Inc.", + "58146000000" + ], + "negativeCases": [ + { + "name": "http-404-s3-nosuchkey", + "status": 404, + "payload": "NoSuchKeyThe specified key does not exist." + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://data.sec.gov/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-json", + "status": 200, + "payload": "{}" + }, + { + "name": "empty-spa-shell", + "status": 200, + "payload": "SEC
" + } + ] +} diff --git a/hub/test/fixtures/adapters/setlist-lastfm.json b/hub/test/fixtures/adapters/setlist-lastfm.json new file mode 100644 index 0000000..108f033 --- /dev/null +++ b/hub/test/fixtures/adapters/setlist-lastfm.json @@ -0,0 +1,42 @@ +{ + "adapterId": "setlist-lastfm", + "mode": "html", + "inputUrl": "https://www.setlist.fm/setlist/motionless-in-white/2023/mobile-civic-center-mobile-al-3ba45068.html", + "mockPayload": "Motionless in White Setlist at Mobile Civic Center, Mobile | setlist.fm

Motionless in White at Mobile Civic Center, Mobile, AL, USA

Sep 23 2023
", + "expectTitleIncludes": "Motionless in White", + "expectMarkdownIncludes": [ + "Meltdown", + "Sign of Life", + "Eternally Yours", + "Sep 23 2023" + ], + "negativeCases": [ + { + "name": "fastly-challenge-lastfm", + "status": 200, + "inputUrl": "https://www.last.fm/music/Nirvana", + "payload": "Client Challenge
" + }, + { + "name": "http-404", + "status": 404, + "payload": "404 Page Not Found | setlist.fm

Not Found

" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.setlist.fm/error", + "payload": "Whitelabel Error Page

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "payload": "setlist.fm
" + } + ] +} diff --git a/hub/test/fixtures/adapters/spotify-web-api.json b/hub/test/fixtures/adapters/spotify-web-api.json new file mode 100644 index 0000000..8f724ed --- /dev/null +++ b/hub/test/fixtures/adapters/spotify-web-api.json @@ -0,0 +1,42 @@ +{ + "adapterId": "spotify-web-api", + "mode": "twin", + "inputUrl": "https://open.spotify.com/oembed?url=https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk", + "expectedFetchUrl": "https://open.spotify.com/oembed?url=https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk", + "mockPayload": "{\"html\":\"\",\"iframe_url\":\"https://open.spotify.com/embed/show/4rOoJ6Egrf8K2IrywzwOMk\",\"width\":456,\"height\":152,\"version\":\"1.0\",\"provider_name\":\"Spotify\",\"provider_url\":\"https://spotify.com\",\"type\":\"rich\",\"title\":\"The Joe Rogan Experience\",\"thumbnail_url\":\"https://i.scdn.co/image/ab6765630000ba8a1234567890abcdef\"}", + "expectTitleIncludes": "The Joe Rogan Experience", + "expectMarkdownIncludes": [ + "Spotify", + "https://open.spotify.com/embed/show/4rOoJ6Egrf8K2IrywzwOMk" + ], + "negativeCases": [ + { + "name": "unauthorized-401-api", + "status": 401, + "inputUrl": "https://api.spotify.com/v1/shows/4rOoJ6Egrf8K2IrywzwOMk", + "payload": "{\"error\":{\"status\":401,\"message\":\"Invalid access token\"}}" + }, + { + "name": "http-404", + "status": 404, + "payload": "{\"error\":{\"status\":404,\"message\":\"Non existing id\"}}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://open.spotify.com/error", + "payload": "Page not found

Page not found

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-encore-shell", + "status": 200, + "inputUrl": "https://open.spotify.com/track/missing", + "payload": "Spotify
" + } + ] +} diff --git a/hub/test/fixtures/adapters/steam-store.json b/hub/test/fixtures/adapters/steam-store.json new file mode 100644 index 0000000..b8b7219 --- /dev/null +++ b/hub/test/fixtures/adapters/steam-store.json @@ -0,0 +1,45 @@ +{ + "adapterId": "steam-store", + "mode": "twin", + "inputUrl": "https://store.steampowered.com/app/620/Portal_2/", + "expectedFetchUrl": "https://store.steampowered.com/api/appdetails?appids=620", + "mockPayload": "{\"620\":{\"success\":true,\"data\":{\"type\":\"game\",\"name\":\"Portal 2\",\"steam_appid\":620,\"is_free\":false,\"short_description\":\"The Perpetual Testing Initiative has been expanded to allow you to design co-op puzzles for you and your friends!\",\"developers\":[\"Valve\"],\"publishers\":[\"Valve\"],\"price_overview\":{\"currency\":\"USD\",\"initial\":999,\"final\":999,\"discount_percent\":0,\"final_formatted\":\"$9.99\"},\"genres\":[{\"id\":\"1\",\"description\":\"Action\"},{\"id\":\"25\",\"description\":\"Adventure\"}],\"release_date\":{\"coming_soon\":false,\"date\":\"Apr 18, 2011\"},\"metacritic\":{\"score\":95}}}}", + "expectTitleIncludes": "Portal 2", + "expectMarkdownIncludes": [ + "620", + "Valve", + "$9.99", + "Action, Adventure", + "95" + ], + "negativeCases": [ + { + "name": "http-404-appdetails-false", + "status": 404, + "payload": "{\"99999999\":{\"success\":false}}" + }, + { + "name": "appreviews-html-homepage-redirect", + "status": 200, + "inputUrl": "https://store.steampowered.com/appreviews/620?json=1", + "payload": "Welcome to Steam
" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://store.steampowered.com/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "inputUrl": "https://store.steampowered.com/app/620/agecheck", + "payload": "Steam Store
" + } + ] +} diff --git a/hub/test/fixtures/adapters/substack-notes-beehiiv.json b/hub/test/fixtures/adapters/substack-notes-beehiiv.json new file mode 100644 index 0000000..e95720a --- /dev/null +++ b/hub/test/fixtures/adapters/substack-notes-beehiiv.json @@ -0,0 +1,41 @@ +{ + "adapterId": "substack-notes-beehiiv", + "mode": "html", + "inputUrl": "https://substack.com/@hamish", + "mockPayload": "Hamish McKenzie | Substack

Hamish McKenzie

", + "expectTitleIncludes": "Hamish McKenzie", + "expectMarkdownIncludes": [ + "@hamish", + "12K subscribers", + "Independent writers thrive when they own the direct relationship with readers." + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "Page not found | Substack

404 Not Found

" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://substack.com/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "payload": "Substack
" + }, + { + "name": "beehiiv-api-401", + "status": 401, + "inputUrl": "https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/posts", + "payload": "{\"status\":401,\"statusText\":\"Unauthorized\",\"errors\":[{\"message\":\"INVALID_API_KEY\"}]}" + } + ] +} diff --git a/hub/test/fixtures/adapters/threads-api.json b/hub/test/fixtures/adapters/threads-api.json new file mode 100644 index 0000000..f5b117f --- /dev/null +++ b/hub/test/fixtures/adapters/threads-api.json @@ -0,0 +1,42 @@ +{ + "adapterId": "threads-api", + "mode": "twin", + "inputUrl": "https://graph.threads.net/v1.0/me?fields=id,username,name,threads_biography", + "expectedFetchUrl": "https://graph.threads.net/v1.0/me?fields=id,username,name,threads_biography", + "mockPayload": "{\"id\":\"17841400000000001\",\"username\":\"edgefetch_dev\",\"name\":\"EdgeFetch Developer\",\"threads_biography\":\"Open web extraction, structured records, and protocol adapters.\"}", + "expectTitleIncludes": "EdgeFetch Developer", + "expectMarkdownIncludes": [ + "17841400000000001", + "@edgefetch_dev", + "Open web extraction, structured records, and protocol adapters." + ], + "negativeCases": [ + { + "name": "http-401-invalid-token", + "status": 401, + "payload": "{\"error\":{\"message\":\"Invalid OAuth access token\",\"type\":\"OAuthException\",\"code\":190}}" + }, + { + "name": "http-404", + "status": 404, + "payload": "{\"error\":{\"message\":\"Unsupported get request.\",\"code\":100}}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.threads.net/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell-threads-html", + "status": 200, + "inputUrl": "https://www.threads.net/@threads", + "payload": "Threads
" + } + ] +} diff --git a/hub/test/fixtures/adapters/tmdb.json b/hub/test/fixtures/adapters/tmdb.json new file mode 100644 index 0000000..c6df841 --- /dev/null +++ b/hub/test/fixtures/adapters/tmdb.json @@ -0,0 +1,44 @@ +{ + "adapterId": "tmdb", + "mode": "twin", + "inputUrl": "https://www.themoviedb.org/movie/550", + "expectedFetchUrl": "https://api.themoviedb.org/3/movie/550", + "mockPayload": "{\"id\":550,\"title\":\"Fight Club\",\"original_title\":\"Fight Club\",\"tagline\":\"Mischief. Mayhem. Soap.\",\"release_date\":\"1999-10-15\",\"runtime\":139,\"status\":\"Released\",\"vote_average\":8.438,\"vote_count\":29120,\"imdb_id\":\"tt0137523\",\"genres\":[{\"id\":18,\"name\":\"Drama\"},{\"id\":53,\"name\":\"Thriller\"}],\"overview\":\"A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy.\",\"homepage\":\"https://www.foxmovies.com/movies/fight-club\"}", + "expectTitleIncludes": "Fight Club", + "expectMarkdownIncludes": [ + "550", + "1999-10-15", + "139 min", + "Drama, Thriller", + "tt0137523" + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "{\"success\":false,\"status_code\":34,\"status_message\":\"The resource you requested could not be found.\"}" + }, + { + "name": "invalid-api-key-401", + "status": 401, + "payload": "{\"status_code\":7,\"status_message\":\"Invalid API key: You must be granted a valid key.\",\"success\":false}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.themoviedb.org/error", + "payload": "Oops! We can't find the page you're looking for — TMDB

Oops! We can't find the page

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "inputUrl": "https://www.themoviedb.org/movie", + "payload": "The Movie Database (TMDB)
" + } + ] +} diff --git a/hub/test/fixtures/adapters/tumblr.json b/hub/test/fixtures/adapters/tumblr.json new file mode 100644 index 0000000..96a7668 --- /dev/null +++ b/hub/test/fixtures/adapters/tumblr.json @@ -0,0 +1,46 @@ +{ + "adapterId": "tumblr", + "mode": "html", + "inputUrl": "https://www.tumblr.com/staff", + "mockPayload": "Tumblr Staff | Tumblr

Tumblr Staff

", + "expectTitleIncludes": "Tumblr Staff", + "expectMarkdownIncludes": [ + "staff", + "Official announcements and product updates from Tumblr.", + "Premium features update for creators" + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "Not Found | Tumblr

There's nothing here.

" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.tumblr.com/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "pow-hashcash-challenge", + "status": 403, + "payload": "Tumblr" + }, + { + "name": "empty-spa-shell", + "status": 200, + "payload": "Tumblr
" + }, + { + "name": "api-unauthorized-401", + "status": 401, + "inputUrl": "https://api.tumblr.com/v2/blog/staff.tumblr.com/posts", + "payload": "{\"meta\":{\"status\":401,\"msg\":\"Unauthorized\"},\"response\":[],\"errors\":[{\"title\":\"Unauthorized\",\"code\":0}]}" + } + ] +} diff --git a/hub/test/fixtures/adapters/tvmaze.json b/hub/test/fixtures/adapters/tvmaze.json new file mode 100644 index 0000000..f7de987 --- /dev/null +++ b/hub/test/fixtures/adapters/tvmaze.json @@ -0,0 +1,39 @@ +{ + "adapterId": "tvmaze", + "mode": "twin", + "inputUrl": "https://www.tvmaze.com/shows/1/under-the-dome", + "expectedFetchUrl": "https://api.tvmaze.com/shows/1?embed=episodes", + "mockPayload": "{\"id\":1,\"url\":\"https://www.tvmaze.com/shows/1/under-the-dome\",\"name\":\"Under the Dome\",\"type\":\"Scripted\",\"language\":\"English\",\"genres\":[\"Drama\",\"Science-Fiction\",\"Thriller\"],\"status\":\"Ended\",\"runtime\":60,\"premiered\":\"2013-06-24\",\"ended\":\"2015-09-10\",\"rating\":{\"average\":6.5},\"network\":{\"id\":2,\"name\":\"CBS\"},\"externals\":{\"imdb\":\"tt1553656\"},\"summary\":\"

Under the Dome is the story of a small town that is suddenly and inexplicably sealed off from the rest of the world by an enormous transparent dome.

\",\"_embedded\":{\"episodes\":[{\"id\":1,\"name\":\"Pilot\",\"season\":1,\"number\":1,\"airdate\":\"2013-06-24\"},{\"id\":2,\"name\":\"The Fire\",\"season\":1,\"number\":2,\"airdate\":\"2013-07-01\"}]}}", + "expectTitleIncludes": "Under the Dome", + "expectMarkdownIncludes": [ + "2013-06-24", + "CBS", + "tt1553656", + "S1E1", + "Pilot" + ], + "negativeCases": [ + { + "name": "http-404", + "status": 404, + "payload": "{\"name\":\"Not Found\",\"message\":\"Page not found.\",\"code\":0,\"status\":404}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.tvmaze.com/error", + "payload": "Page Not Found | TVmaze

Page Not Found

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "inputUrl": "https://www.tvmaze.com/shows", + "payload": "TVmaze
" + } + ] +} diff --git a/hub/test/fixtures/adapters/upcitemdb-barcodelookup.json b/hub/test/fixtures/adapters/upcitemdb-barcodelookup.json new file mode 100644 index 0000000..8762f73 --- /dev/null +++ b/hub/test/fixtures/adapters/upcitemdb-barcodelookup.json @@ -0,0 +1,43 @@ +{ + "adapterId": "upcitemdb-barcodelookup", + "mode": "twin", + "inputUrl": "https://api.upcitemdb.com/prod/trial/lookup?upc=012000161155", + "expectedFetchUrl": "https://api.upcitemdb.com/prod/trial/lookup?upc=012000161155", + "mockPayload": "{\"code\":\"OK\",\"total\":1,\"offset\":0,\"items\":[{\"ean\":\"0012000161155\",\"title\":\"LIFEWTR Purified Water, pH Balanced with Electrolytes For Taste, 23.7 Fl Oz\",\"description\":\"LIFEWTR is a purified water, pH balanced with electrolytes added for taste.\",\"upc\":\"012000161155\",\"brand\":\"LIFEWTR\",\"model\":\"700mL\",\"category\":\"Food, Beverages & Tobacco > Beverages > Water\",\"lowest_recorded_price\":1.29,\"highest_recorded_price\":4.99,\"offers\":[{\"merchant\":\"Example Mart\",\"price\":1.99,\"currency\":\"USD\",\"condition\":\"New\",\"link\":\"https://www.upcitemdb.com/upc/012000161155\"}]}]}", + "expectTitleIncludes": "LIFEWTR Purified Water", + "expectMarkdownIncludes": [ + "0012000161155", + "LIFEWTR", + "700mL", + "1.99 USD" + ], + "negativeCases": [ + { + "name": "invalid-upc-400", + "status": 400, + "payload": "{\"code\":\"INVALID_UPC\",\"message\":\"Not a valid UPC code\"}" + }, + { + "name": "empty-items-404", + "status": 404, + "payload": "{\"code\":\"OK\",\"total\":0,\"items\":[]}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.upcitemdb.com/error", + "payload": "Error

Error

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "barcodelookup-cf-challenge", + "status": 403, + "inputUrl": "https://www.barcodelookup.com/012000161155", + "payload": "Barcode Lookup Security Verification
Enable JavaScript and cookies to continue
" + } + ] +} diff --git a/hub/test/fixtures/adapters/youtube-data-api.json b/hub/test/fixtures/adapters/youtube-data-api.json new file mode 100644 index 0000000..502b952 --- /dev/null +++ b/hub/test/fixtures/adapters/youtube-data-api.json @@ -0,0 +1,43 @@ +{ + "adapterId": "youtube-data-api", + "mode": "twin", + "inputUrl": "https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics,contentDetails&id=dQw4w9WgXcQ", + "expectedFetchUrl": "https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics,contentDetails&id=dQw4w9WgXcQ", + "mockPayload": "{\"kind\":\"youtube#videoListResponse\",\"items\":[{\"kind\":\"youtube#video\",\"id\":\"dQw4w9WgXcQ\",\"snippet\":{\"publishedAt\":\"2009-10-25T06:57:33Z\",\"channelId\":\"UCuAXFkgsw1L7xaCfnd5JJOw\",\"title\":\"Rick Astley - Never Gonna Give You Up (Official Music Video)\",\"description\":\"The official video for Never Gonna Give You Up by Rick Astley.\",\"channelTitle\":\"Rick Astley\",\"tags\":[\"rick astley\",\"never gonna give you up\",\"official\"]},\"contentDetails\":{\"duration\":\"PT3M33S\"},\"statistics\":{\"viewCount\":\"1600000000\",\"likeCount\":\"18000000\",\"commentCount\":\"2350000\"}}],\"pageInfo\":{\"totalResults\":1,\"resultsPerPage\":1}}", + "expectTitleIncludes": "Rick Astley - Never Gonna Give You Up", + "expectMarkdownIncludes": [ + "dQw4w9WgXcQ", + "Rick Astley", + "3:33 (PT3M33S)", + "1600000000", + "https://www.youtube.com/watch?v=dQw4w9WgXcQ" + ], + "negativeCases": [ + { + "name": "http-403-permission-denied", + "status": 403, + "payload": "{\"error\":{\"code\":403,\"message\":\"Method doesn't allow unregistered callers (callers without established identity).\",\"status\":\"PERMISSION_DENIED\"}}" + }, + { + "name": "empty-items-404", + "status": 404, + "payload": "{\"kind\":\"youtube#videoListResponse\",\"items\":[],\"pageInfo\":{\"totalResults\":0,\"resultsPerPage\":0}}" + }, + { + "name": "redirect-to-error", + "status": 200, + "finalUrl": "https://www.googleapis.com/error", + "payload": "404 Not Found

Not Found

" + }, + { + "name": "maintenance", + "status": 503, + "payload": "Scheduled Maintenance

Temporarily Unavailable

" + }, + { + "name": "empty-spa-shell", + "status": 200, + "payload": "YouTube
" + } + ] +} diff --git a/hub/test/wave3-b6-gtin-media-finance-social.test.ts b/hub/test/wave3-b6-gtin-media-finance-social.test.ts new file mode 100644 index 0000000..2caf8b3 --- /dev/null +++ b/hub/test/wave3-b6-gtin-media-finance-social.test.ts @@ -0,0 +1,1040 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import test from 'node:test'; +import { gzipSync } from 'node:zlib'; +import { resolveAdapterPolicyForUrl, resolveUserAgentProfile } from '../src/adapter-policy'; +import { + fetchWithOfficialApiKey, + redactSecretsInBody, + resolveOfficialApiExtraHeaders, + resolveOfficialApiExtraHeadersAsync, + resolveOfficialApiExtraSecrets, + resolveOfficialApiProviderSpec, + resolveOfficialApiProviderSpecForUrl, + scrubSecretFromText, + sealUserApiKey, +} from '../src/api-keys'; +import { KNOWN_TELEMETRY_ADAPTER_IDS } from '../src/dev-telemetry'; +import { validateSingleErrorEvent } from '../../telemetry/src/index'; +import { DECLARATIVE_SITE_ADAPTERS } from '../src/extractors/declarative'; +import { resolveSiteExtractorTwin } from '../src/extractors/registry'; +import { postExtractHtml } from './post-fetch-wasm'; +import { RequestTracer } from '../src/otel'; +import { resetOverflowRobotsCacheForTests } from '../src/overflow'; +import { + decodeBoundedGzipTsvFromBase64, + executeScrapeCall, + fetchNostrRelayNip01Events, + isTrustedTwinRedirectUrl, + isTwinRedirectedToErrorPage, +} from '../src/scrape'; +import { executeExtractCall } from '../src/search-index'; +import { callCoreWasm, resetIsolateBudgetForTests } from '../src/wasm-bridge'; +import { assertFastAsync, assertFastUnscaledSync } from './perf-budget'; + +const WAVE3_B6_CAT_Q_IDS = [ + 'gs1-us-datahub', + 'open-icecat', + 'upcitemdb-barcodelookup', + 'open-product-wikidata-gtin', + 'energy-star', + 'fcc-test-report', + 'prop65-warnings', +] as const; + +const WAVE3_B6_CAT_R_IDS = [ + 'tmdb', + 'imdb-datasets', + 'tvmaze', + 'musicbrainz-coverart', + 'discogs', + 'podcast-index', + 'spotify-web-api', + 'setlist-lastfm', + 'steam-store', + 'igdb', + 'bandcamp', + 'genius-lyrics', +] as const; + +const WAVE3_B6_CAT_S_IDS = [ + 'fed-h15-datadownload', + 'nasdaq-data-link', + 'market-quotes-pack', + 'sec-xbrl-frames', + 'msrb-emma', + 'ffiec-cdr', +] as const; + +const WAVE3_B6_CAT_T_IDS = [ + 'youtube-data-api', + 'threads-api', + 'tumblr', + 'farcaster-hub', + 'nostr-relays', + 'product-hunt', + 'substack-notes-beehiiv', + 'patreon-public', +] as const; + +const ALL_B6_IDS = [ + ...WAVE3_B6_CAT_Q_IDS, + ...WAVE3_B6_CAT_R_IDS, + ...WAVE3_B6_CAT_S_IDS, + ...WAVE3_B6_CAT_T_IDS, +] as const; + +interface B6Fixture { + adapterId: string; + mode: 'twin' | 'html'; + inputUrl: string; + expectedFetchUrl?: string; + mockPayload: string; + expectTitleIncludes?: string; + expectMarkdownIncludes: string[]; + negativeCases: Array<{ + name: string; + status?: number; + inputUrl?: string; + finalUrl?: string; + payload: string; + }>; +} + +const noopHtmlToMd = () => ({ markdown: '', links: [] as string[] }); + +const EXPECTED_CATEGORY_BY_ID: Record<(typeof ALL_B6_IDS)[number], string> = { + 'gs1-us-datahub': 'commerce-social', + 'open-icecat': 'commerce-social', + 'upcitemdb-barcodelookup': 'commerce-social', + 'open-product-wikidata-gtin': 'commerce-social', + 'energy-star': 'public-records', + 'fcc-test-report': 'public-records', + 'prop65-warnings': 'public-records', + tmdb: 'commerce-social', + 'imdb-datasets': 'commerce-social', + tvmaze: 'commerce-social', + 'musicbrainz-coverart': 'commerce-social', + discogs: 'commerce-social', + 'podcast-index': 'commerce-social', + 'spotify-web-api': 'commerce-social', + 'setlist-lastfm': 'commerce-social', + 'steam-store': 'commerce-social', + igdb: 'commerce-social', + bandcamp: 'commerce-social', + 'genius-lyrics': 'commerce-social', + 'fed-h15-datadownload': 'finance', + 'nasdaq-data-link': 'finance', + 'market-quotes-pack': 'finance', + 'sec-xbrl-frames': 'finance', + 'msrb-emma': 'finance', + 'ffiec-cdr': 'finance', + 'youtube-data-api': 'commerce-social', + 'threads-api': 'commerce-social', + tumblr: 'commerce-social', + 'farcaster-hub': 'commerce-social', + 'nostr-relays': 'commerce-social', + 'product-hunt': 'commerce-social', + 'substack-notes-beehiiv': 'commerce-social', + 'patreon-public': 'commerce-social', +}; + +function makeOverflowMock(statusCode: number, bodyStr: string, ct: string, finalUrl?: string) { + return async (_t: unknown, body: string) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string; url: string }> }).requests[0]!; + const outcome = + statusCode >= 200 && statusCode < 300 + ? 'ok' + : statusCode === 404 + ? 'not_found' + : statusCode === 410 + ? 'gone' + : statusCode === 403 + ? 'blocked' + : 'error'; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [ + { + id: req.id, + url: req.url, + ...(finalUrl ? { finalUrl } : {}), + outcome, + status: statusCode, + contentType: ct, + body: bodyStr, + }, + ], + }), + }; + }; +} + +function makeKeyFetchEnv(statusCode: number, bodyStr: string, ct: string) { + return { + SAFE_PUBLIC_FETCH: (async (input: RequestInfo | URL) => { + const u = new URL(typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url); + if (u.pathname === '/robots.txt') { + return new Response('User-agent: *\nAllow: /\n', { status: 200, headers: { 'content-type': 'text/plain' } }); + } + return new Response(bodyStr, { status: statusCode, headers: { 'content-type': ct } }); + }) as typeof fetch, + }; +} + +function reqUrl(input: RequestInfo | URL): URL { + return new URL(typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url); +} + +class MockNostrWebSocket { + static instances: MockNostrWebSocket[] = []; + readonly url: string; + readonly sentMessages: string[] = []; + closedWith?: { code?: number; reason?: string }; + readyState = 0; + private listeners = new Map void>>(); + + constructor(url: string) { + this.url = url; + MockNostrWebSocket.instances.push(this); + } + + addEventListener(type: string, fn: (ev: unknown) => void): void { + const arr = this.listeners.get(type) ?? []; + arr.push(fn); + this.listeners.set(type, arr); + } + + emit(type: string, ev: unknown): void { + for (const fn of this.listeners.get(type) ?? []) { + fn(ev); + } + } + + send(data: string): void { + this.sentMessages.push(data); + } + + close(code?: number, reason?: string): void { + this.closedWith = { code, reason }; + this.readyState = 3; + this.emit('close', {}); + } +} + +test('Wave 3 B6 Integration: All 33 adapter IDs registered, telemetry aligned, zero Rule 7 additions & Rule 9 clean', () => { + assert.equal(ALL_B6_IDS.length, 33, 'Batch B6 must cover all 33 adapters (#368-#400)'); + const registered = new Map(DECLARATIVE_SITE_ADAPTERS.map((a) => [a.id, a])); + + for (const id of ALL_B6_IDS) { + const adapter = registered.get(id); + assert.ok(adapter, `Missing DECLARATIVE_SITE_ADAPTERS entry: ${id}`); + assert.notEqual(adapter.authMode, 'detect-only', `${id} must never be detect-only`); + assert.equal(adapter.category, EXPECTED_CATEGORY_BY_ID[id], `${id} category mismatch`); + assert.ok(KNOWN_TELEMETRY_ADAPTER_IDS.has(id), `Missing KNOWN_TELEMETRY_ADAPTER_IDS entry: ${id}`); + assert.equal( + validateSingleErrorEvent({ + schemaVersion: 1, + version: '2.8.32', + runtime: 'workers', + os: 'cloudflare', + arch: 'v8', + mode: 'hub', + spanName: 'edgefetch.scrape', + adapterId: id, + wafVendor: '', + httpStatus: 500, + errorClass: 'timeout', + }).ok, + true, + `Missing telemetry/src/index.ts VALID_ADAPTER_IDS entry: ${id}`, + ); + assert.ok(adapter.exampleUrls.length >= 1, `${id} missing exampleUrls`); + } + + // Rule 7: Zero additions to APPROVED_CROSS_DOMAIN_TWIN_HOSTS (TS or Go) + const compileSrc = readFileSync(resolve('scripts', 'compile-manifests.mjs'), 'utf8'); + const crossBlock = compileSrc.slice( + compileSrc.indexOf('APPROVED_CROSS_DOMAIN_TWIN_HOSTS'), + compileSrc.indexOf('APPROVED_WILDCARD_DOMAIN_PATTERNS'), + ); + for (const id of ALL_B6_IDS) { + assert.equal(crossBlock.includes(`'${id}'`), false, `Rule 7 violation: ${id} in APPROVED_CROSS_DOMAIN_TWIN_HOSTS`); + } + for (const forbiddenHost of ['coverartarchive.org', 'api.barcodelookup.com', 'api.igdb.com']) { + assert.equal(crossBlock.includes(forbiddenHost), false, `Rule 7 violation: ${forbiddenHost} in APPROVED_CROSS_DOMAIN_TWIN_HOSTS`); + } + + const declGoSrc = readFileSync(resolve('..', 'internal', 'extract', 'declarative.go'), 'utf8'); + const goCrossMatch = /var approvedCrossDomainTwinHostsGo = map\[string\]map\[string\]bool\{([\s\S]*?)\n\}/.exec(declGoSrc); + assert.ok(goCrossMatch); + for (const id of ALL_B6_IDS) { + assert.equal(goCrossMatch[1]!.includes(`"${id}"`), false, `Rule 7 Go violation: ${id} in approvedCrossDomainTwinHostsGo`); + } + + // Rule 9: Zero private / internal names across all 33 B6 manifests, fixtures, and Go sources/tests + const privateBrandRe = new RegExp(Buffer.from('c2hlcGhlcmR8c2hvcGRhd2d8anVpY2VkLj93aGVlbHM=', 'base64').toString('utf8'), 'i'); + for (const id of ALL_B6_IDS) { + const yamlText = readFileSync(resolve('..', 'internal', 'extract', 'manifests', `${id}.yaml`), 'utf8'); + assert.equal(privateBrandRe.test(yamlText), false, `Rule 9 violation in ${id}.yaml`); + const fxText = readFileSync(resolve('test', 'fixtures', 'adapters', `${id}.json`), 'utf8'); + assert.equal(privateBrandRe.test(fxText), false, `Rule 9 violation in ${id}.json`); + } + for (const goRel of [ + 'wave3_gtin_identity.go', + 'wave3_gtin_identity_test.go', + 'wave3_media_lyrics.go', + 'wave3_media_lyrics_test.go', + 'wave3_finance.go', + 'wave3_finance_test.go', + 'wave3_social_creator.go', + 'wave3_social_creator_test.go', + ]) { + const goText = readFileSync(resolve('..', 'internal', 'extract', goRel), 'utf8'); + assert.equal(privateBrandRe.test(goText), false, `Rule 9 violation in ${goRel}`); + } +}); + +test('Wave 3 B6 Fixtures: All 33 golden + >=4 negative cases pass via formatTwin/HTML, executeScrapeCall, executeExtractCall & RequestTracer', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + const b6ApiKeys = { + 'gs1-us-datahub': 'gs1-us-test-key-0123456789abcdef', + 'upcitemdb-barcodelookup': 'upc-barcodelookup-key-0123456789abcdef', + tmdb: 'tmdb-test-api-key-0123456789abcdef', + 'podcast-index': 'podcast-index-key-0123456789abcdef', + PODCASTINDEX_API_SECRET: 'podcast-index-secret-0123456789abcdef', + 'spotify-web-api': 'spotify-access-token-0123456789abcdef', + 'setlist-lastfm': 'setlist-lastfm-key-0123456789abcdef', + igdb: 'igdb-twitch-token-0123456789abcdef', + TWITCH_CLIENT_ID: 'twitch-client-id-0123456789abcdef', + 'nasdaq-data-link': 'nasdaq-data-link-key-0123456789abcdef', + 'market-quotes-pack': 'market-quotes-key-0123456789abcdef', + 'ffiec-cdr': 'ffiec-cdr-token-0123456789abcdef', + 'youtube-data-api': 'youtube-data-api-key-0123456789abcdef', + 'threads-api': 'threads-access-token-0123456789abcdef', + tumblr: 'tumblr-api-key-0123456789abcdef', + 'farcaster-hub': 'neynar-api-key-0123456789abcdef', + 'product-hunt': 'producthunt-token-0123456789abcdef', + 'substack-notes-beehiiv': 'beehiiv-api-key-0123456789abcdef', + }; + + for (const slug of ALL_B6_IDS) { + const fx = JSON.parse(readFileSync(resolve('test', 'fixtures', 'adapters', `${slug}.json`), 'utf8')) as B6Fixture; + assert.equal(fx.adapterId, slug); + assert.ok(fx.negativeCases.length >= 4, `${slug} must have >= 4 negativeCases`); + + const resolvedTwin = fx.mode === 'twin' ? resolveSiteExtractorTwin(fx.inputUrl) : null; + const isKeyTwin = Boolean(resolvedTwin && resolvedTwin.authMode === 'key'); + const fetchUrl = fx.expectedFetchUrl || fx.inputUrl; + const trimmedMock = fx.mockPayload.trimStart(); + const contentType = + fx.mode === 'html' + ? 'text/html' + : trimmedMock.startsWith('{') || trimmedMock.startsWith('[') + ? 'application/json' + : 'text/plain'; + + if (fx.mode === 'twin') { + assert.ok(resolvedTwin && resolvedTwin.id === slug, `${slug}: expected twin for ${fx.inputUrl}`); + if (fx.expectedFetchUrl) { + assert.equal(resolvedTwin.fetchUrl, fx.expectedFetchUrl, `${slug}: unexpected fetchUrl`); + } + const out = resolvedTwin.formatTwin(fx.mockPayload, fx.inputUrl, noopHtmlToMd); + assert.ok(out && out.markdown.trim().length > 0, `${slug}: formatTwin returned null/empty`); + if (fx.expectTitleIncludes) { + assert.ok(out.title.includes(fx.expectTitleIncludes), `${slug}: title "${out.title}" missing "${fx.expectTitleIncludes}"`); + } + for (const needle of fx.expectMarkdownIncludes) { + assert.ok(out.markdown.includes(needle), `${slug}: markdown missing "${needle}"`); + } + if (out.records) { + assert.ok(out.records.length <= 25, `${slug}: records[] exceeds 25`); + } + } else { + const postOut = postExtractHtml(fx.mockPayload, fx.inputUrl, ''); + assert.ok(postOut && postOut.extractorId === slug && postOut.markdown.trim().length > 0, `${slug}: HTML extraction failed`); + if (fx.expectTitleIncludes && postOut.title) { + assert.ok(postOut.title.includes(fx.expectTitleIncludes), `${slug}: title "${postOut.title}" missing "${fx.expectTitleIncludes}"`); + } + for (const needle of fx.expectMarkdownIncludes) { + assert.ok(postOut.markdown.includes(needle), `${slug}: markdown missing "${needle}"`); + } + if (postOut.records) { + assert.ok(postOut.records.length <= 25, `${slug}: records[] exceeds 25`); + } + } + + // Golden scrape + RequestTracer + const scTracer = RequestTracer.fromRequest(new Request('https://hub.example.com/v1/scrape')); + let scRes!: Awaited>; + await scTracer.withSpan('edgefetch.scrape', async () => { + scRes = await executeScrapeCall({ + payload: { + url: fx.inputUrl, + formats: ['markdown', 'records'], + discoverLlmsTxt: false, + noCache: true, + ...(isKeyTwin ? { apiKeys: b6ApiKeys } : {}), + }, + env: (isKeyTwin ? makeKeyFetchEnv(200, fx.mockPayload, contentType) : {}) as never, + tracer: scTracer, + executeHubFetch: isKeyTwin + ? async () => { + throw new Error(`${slug}: keyed twin must use fetchWithOfficialApiKey`); + } + : makeOverflowMock(200, fx.mockPayload, contentType, fx.mode === 'twin' ? fetchUrl : undefined), + }); + }); + assert.equal(scRes.status, 200, `${slug} scrape failed: ${JSON.stringify(scRes.body)}`); + assert.equal(scRes.body.extractorId, slug, `${slug} scrape extractorId mismatch`); + assert.equal(scRes.body.contentState, 'active', `${slug} scrape contentState must be active`); + assert.equal( + scTracer.getRecordedSpans().find((s) => s.name === 'edgefetch.scrape')?.attributes?.['edgefetch.adapter_id'], + slug, + `${slug} scrape span missing edgefetch.adapter_id`, + ); + + // Golden extract + RequestTracer + const exTracer = RequestTracer.fromRequest(new Request('https://hub.example.com/v1/extract')); + let exRes!: Awaited>; + await exTracer.withSpan('edgefetch.extract', async () => { + exRes = await executeExtractCall({ + payload: { + urls: [fx.inputUrl], + noCache: true, + ...(isKeyTwin ? { apiKeys: b6ApiKeys } : {}), + }, + env: (isKeyTwin ? makeKeyFetchEnv(200, fx.mockPayload, contentType) : {}) as never, + tracer: exTracer, + executeHubFetch: isKeyTwin + ? async () => { + throw new Error(`${slug}: keyed extract must use fetchWithOfficialApiKey`); + } + : makeOverflowMock(200, fx.mockPayload, contentType, fx.mode === 'twin' ? fetchUrl : undefined), + }); + }); + assert.equal(exRes.status, 200, `${slug} extract failed`); + assert.equal( + exTracer.getRecordedSpans().find((s) => s.name === 'edgefetch.extract')?.attributes?.['edgefetch.adapter_id'], + slug, + `${slug} extract span missing edgefetch.adapter_id`, + ); + + // >= 4 negative cases + for (const nc of fx.negativeCases) { + const ncUrl = nc.inputUrl || fx.inputUrl; + const ncStatus = nc.status ?? 200; + const ncTrim = nc.payload.trimStart(); + const ncCt = ncTrim.startsWith('<') ? 'text/html' : ncTrim.startsWith('{') || ncTrim.startsWith('[') ? 'application/json' : 'text/plain'; + const ncTwin = resolveSiteExtractorTwin(ncUrl); + + if (nc.finalUrl && nc.finalUrl !== ncUrl) { + if (fx.mode === 'twin' && ncTwin && ncTwin.id === slug) { + assert.equal( + isTrustedTwinRedirectUrl(slug, fetchUrl, { finalUrl: nc.finalUrl }), + false, + `${slug}:${nc.name} redirect to ${nc.finalUrl} must be rejected`, + ); + } else { + const isErrRedir = isTwinRedirectedToErrorPage(ncUrl, { finalUrl: nc.finalUrl }); + const negHtml = postExtractHtml(nc.payload, nc.finalUrl, ''); + assert.ok(isErrRedir || negHtml === null, `${slug}:${nc.name} error redirect must not extract`); + } + } else if (ncTwin && ncTwin.id === slug) { + const negTwin = ncTwin.formatTwin(nc.payload, ncUrl, noopHtmlToMd); + assert.equal(Boolean(negTwin && negTwin.markdown.trim()), false, `${slug}:${nc.name} formatTwin must return null/empty`); + } else { + const negHtml = postExtractHtml(nc.payload, ncUrl, ''); + assert.equal(negHtml, null, `${slug}:${nc.name} HTML extractor must return null`); + } + + const useKeyFetch = Boolean(ncTwin && ncTwin.id === slug && ncTwin.authMode === 'key' && !nc.finalUrl); + const scNeg = await executeScrapeCall({ + payload: { + url: ncUrl, + discoverLlmsTxt: false, + noCache: true, + ...(useKeyFetch ? { apiKeys: b6ApiKeys } : {}), + }, + env: (useKeyFetch ? makeKeyFetchEnv(ncStatus, nc.payload, ncCt) : {}) as never, + executeHubFetch: makeOverflowMock(ncStatus, nc.payload, ncCt, nc.finalUrl), + }); + assert.notEqual( + (scNeg.body as { contentState?: string }).contentState, + 'active', + `scrape ${slug}:${nc.name} must NEVER return contentState=active`, + ); + + const exNeg = await executeExtractCall({ + payload: { + urls: [ncUrl], + noCache: true, + ...(useKeyFetch ? { apiKeys: b6ApiKeys } : {}), + }, + env: (useKeyFetch ? makeKeyFetchEnv(ncStatus, nc.payload, ncCt) : {}) as never, + executeHubFetch: makeOverflowMock(ncStatus, nc.payload, ncCt, nc.finalUrl), + }); + const exFirst = ((exNeg.body as { results?: Array<{ contentState?: string }> }).results ?? [])[0]; + assert.notEqual( + exFirst?.contentState, + 'active', + `extract ${slug}:${nc.name} must NEVER return contentState=active`, + ); + } + } +}); + +test('Wave 3 B6 Cat Q: Strict 8/12/13/14-digit GTIN validation (#368-#371), fcc-id exhibit mode & Incapsula/SPA rejections', () => { + resetIsolateBudgetForTests(); + + // Valid 8, 12, 13, 14-digit GTINs resolve on #369 & #370 + for (const goodUrl of [ + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=12345670', + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=012000161155', + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=8710103792772', + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=00871010379277', + 'https://api.upcitemdb.com/prod/trial/lookup?upc=012000161155', + 'https://api.barcodelookup.com/v3/products?barcode=0012000161155', + ]) { + assert.ok(resolveSiteExtractorTwin(goodUrl), `Expected valid GTIN route to match: ${goodUrl}`); + } + + // Invalid 9/10/11-digit codes, ASINs, SKUs, hex strings MUST be rejected by route matchers + for (const badUrl of [ + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=B08N5WRWNW', + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=1234567890', + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=12345678901', + 'https://api.upcitemdb.com/prod/trial/lookup?upc=SKU-12345', + 'https://api.upcitemdb.com/prod/trial/lookup?upc=123456789', + 'https://api.barcodelookup.com/v3/products?barcode=deadbeef1234', + ]) { + assert.equal(resolveSiteExtractorTwin(badUrl), null, `Expected invalid GTIN route to be rejected: ${badUrl}`); + } + + // OpenGTINdb invalid EAN (10-digit) rejected at route match time; invalid GTIN codes in payload omitted from records[] + assert.equal(resolveSiteExtractorTwin('https://opengtindb.org/?ean=1234567890&cmd=query&queryid=400000000'), null); + const openGtinTwin = resolveSiteExtractorTwin('https://opengtindb.org/?ean=4006381333931&cmd=query&queryid=400000000'); + assert.ok(openGtinTwin && openGtinTwin.id === 'open-product-wikidata-gtin'); + const icecatTwin = resolveSiteExtractorTwin('https://live.icecat.biz/api?shopname=openicecat-live&lang=en&icecat_id=32928991'); + assert.ok(icecatTwin && icecatTwin.id === 'open-icecat'); + const icecatBadGtinOut = icecatTwin.formatTwin( + JSON.stringify({ + msg: 'OK', + data: { + GeneralInfo: { + IcecatId: 32928991, + Title: 'Widget', + Brand: 'Acme', + GTIN: ['1234567890', 'B08N5WRWNW'], + }, + }, + }), + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en&icecat_id=32928991', + noopHtmlToMd, + ); + assert.ok(icecatBadGtinOut); + assert.equal(icecatBadGtinOut.records?.[0]?.gtin, undefined, 'Invalid 10-digit/ASIN codes must NOT appear as GTIN'); + + // Upgraded fcc-id exhibit link extraction on fccid.io/ + const fccIdHtml = `FCC ID BCG-E3542A by Apple Inc.
+

FCC ID BCG-E3542A

+

Grantee: Apple Inc. Equipment Class: DTS Digital Transmission System.

+ Test Report PDF + RF Exposure Info +
`; + const fccIdOut = postExtractHtml(fccIdHtml, 'https://fccid.io/BCG-E3542A', ''); + assert.equal(fccIdOut?.extractorId, 'fcc-id'); + assert.ok(fccIdOut?.markdown.includes('Test Report')); +}); + +test('Wave 3 B6 Cat R: #376 IMDb bounded gzip + nonCommercialLicense, #378 MusicBrainz UA/rate & PoW, #386 multi-site lyrics', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + // 1. #376 imdb-datasets: full gzip AND mid-stream truncated gzip base64 -> TSV + nonCommercialLicense: true + const tsvText = [ + 'tconst\taverageRating\tnumVotes', + 'tt0000001\t5.7\t2244', + 'tt0000002\t5.5\t308', + 'tt0000003\t6.5\t2286', + ].join('\n'); + const fullGzB64 = gzipSync(Buffer.from(tsvText, 'utf8')).toString('base64'); + const decodedFull = await decodeBoundedGzipTsvFromBase64(fullGzB64); + assert.ok(decodedFull && decodedFull.includes('tt0000001\t5.7\t2244')); + + // Large multi-row gzipped TSV sliced before trailer (simulating HTTP 206 Range chunk) + const manyRows = ['tconst\taverageRating\tnumVotes']; + for (let i = 1; i <= 500; i++) { + manyRows.push(`tt${String(i).padStart(7, '0')}\t${((i % 9) + 1).toFixed(1)}\t${100 + i}`); + } + const fullManyGz = gzipSync(Buffer.from(`${manyRows.join('\n')}\n`, 'utf8')); + const truncatedGzB64 = fullManyGz.subarray(0, Math.max(40, fullManyGz.byteLength - 16)).toString('base64'); + const decodedTrunc = await decodeBoundedGzipTsvFromBase64(truncatedGzB64); + assert.ok(decodedTrunc && decodedTrunc.includes('tconst\taverageRating\tnumVotes'), 'Truncated gzip stream must yield decoded prefix rows'); + + // Bounded <= 2 MiB decompression cap check + const bigRow = 'tt0000001\t8.8\t123456\t' + 'abcdefghij'.repeat(20) + '\n'; + const over2MiBText = 'tconst\taverageRating\tnumVotes\textra\n' + bigRow.repeat(12_000); + const over2MiBGzB64 = gzipSync(Buffer.from(over2MiBText, 'utf8')).toString('base64'); + const boundedDecoded = await decodeBoundedGzipTsvFromBase64(over2MiBGzB64); + assert.ok(boundedDecoded); + assert.ok(Buffer.byteLength(boundedDecoded, 'utf8') <= 2 * 1024 * 1024 + 512, 'Decompressed TSV must stay bounded to <= 2 MiB'); + + const imdbScrape = await executeScrapeCall({ + payload: { + url: 'https://datasets.imdbws.com/title.ratings.tsv.gz', + formats: ['markdown', 'records'], + discoverLlmsTxt: false, + noCache: true, + }, + env: {}, + executeHubFetch: async (_t, body) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string; url: string; headers?: Record }> }).requests[0]!; + assert.equal(req.headers?.Range, 'bytes=0-262143'); + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [ + { + id: req.id, + url: req.url, + outcome: 'ok', + status: 206, + contentType: 'binary/octet-stream', + bodyEncoding: 'base64', + body: fullGzB64, + }, + ], + }), + }; + }, + }); + assert.equal(imdbScrape.status, 200); + assert.equal(imdbScrape.body.extractorId, 'imdb-datasets'); + assert.equal(imdbScrape.body.contentState, 'active'); + assert.ok(String(imdbScrape.body.markdown).includes('IMDb Non-Commercial Datasets')); + assert.ok(String(imdbScrape.body.markdown).includes('nonCommercialLicense: true')); + const imdbRecs = imdbScrape.body.records as Array>; + assert.ok(Array.isArray(imdbRecs) && imdbRecs.length >= 3); + assert.equal(imdbRecs[0]?.nonCommercialLicense, true); + + // Also verify executeExtractCall decodes base64 gzip for #376 + const imdbExtract = await executeExtractCall({ + payload: { urls: ['https://datasets.imdbws.com/title.ratings.tsv.gz'], includeRawContent: true, noCache: true }, + env: {}, + executeHubFetch: async (_t, body) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string; url: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [ + { + id: req.id, + url: req.url, + outcome: 'ok', + status: 206, + contentType: 'binary/octet-stream', + bodyEncoding: 'base64', + body: fullGzB64, + }, + ], + }), + }; + }, + }); + assert.equal(imdbExtract.status, 200); + const imdbExRes = (imdbExtract.body as { results: Array<{ contentState?: string; rawContent?: string; chunks: Array<{ text: string }> }> }).results[0]!; + assert.equal(imdbExRes.contentState, 'active'); + const imdbExText = imdbExRes.rawContent || imdbExRes.chunks.map((c) => c.text).join('\n'); + assert.ok(imdbExText.includes('tt0000001')); + + // 2. #378 MusicBrainz UA profile, rate limit policy, and /__meb_verify PoW prose shell rejection + const mbPol = resolveAdapterPolicyForUrl('https://musicbrainz.org/ws/2/artist/5b11f4ce-a62d-471e-81fc-a69a8278c7da?fmt=json'); + assert.equal(mbPol.adapterId, 'musicbrainz-coverart'); + assert.equal(mbPol.userAgentProfile, 'musicbrainz'); + assert.equal(mbPol.maxConcurrent, 1); + assert.ok((mbPol.minIntervalMs ?? 0) >= 1000); + assert.equal(resolveUserAgentProfile('musicbrainz'), 'EdgeFetch/2.7 (bot@edgefetch.dev; musicbrainz-client)'); + + const mebProseHtml = + 'Verifying your browser

Please wait while we verify your browser request.

'; + const mebScrape = await executeScrapeCall({ + payload: { url: 'https://musicbrainz.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd', discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeOverflowMock(200, mebProseHtml, 'text/html'), + }); + assert.notEqual(mebScrape.body.contentState, 'active', 'MusicBrainz /__meb_verify PoW prose shell must never be active'); + + // 3. #386 Real multi-site lyrics extraction across Genius, AZLyrics, Musixmatch, and SongMeanings (zero copyright refusal) + const azHtml = `Rick Astley - Never Gonna Give You Up Lyrics | AZLyrics.com
"Never Gonna Give You Up"
We're no strangers to love
You know the rules and so do I
`; + const azOut = postExtractHtml(azHtml, 'https://www.azlyrics.com/lyrics/rickastley/nevergonnagiveyouup.html', ''); + assert.equal(azOut?.extractorId, 'genius-lyrics'); + assert.ok(azOut?.markdown.includes("We're no strangers to love\nYou know the rules and so do I")); + + const mxmHtml = `Never Gonna Give You Up Lyrics - Musixmatch
We're no strangers to love
`; + const mxmOut = postExtractHtml(mxmHtml, 'https://www.musixmatch.com/lyrics/Rick-Astley/Never-Gonna-Give-You-Up', ''); + assert.equal(mxmOut?.extractorId, 'genius-lyrics'); + assert.ok(mxmOut?.markdown.includes("We're no strangers to love")); + + const smHtml = `Rick Astley - Never Gonna Give You Up Lyrics | SongMeanings

Never Gonna Give You Up

Classic 1987 pop commitment anthem.
`; + const smOut = postExtractHtml(smHtml, 'https://songmeanings.com/songs/view/3530822107858506064/', ''); + assert.equal(smOut?.extractorId, 'genius-lyrics'); + assert.ok(smOut?.markdown.includes("We're no strangers to love")); + assert.ok(smOut?.markdown.includes('Classic 1987 pop commitment anthem.')); +}); + +test('Wave 3 B6 Cat T: #397 Nostr NIP-11 + bounded read-only WS NIP-01 REQ + SSRF guards + njump.me', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + MockNostrWebSocket.instances = []; + + assert.equal(callCoreWasm<{ enabled: boolean }>('nostr_prepare_nip01', { url: 'https://nos.lol/' }).enabled, false); + assert.equal(callCoreWasm<{ enabled: boolean }>('nostr_prepare_nip01', { url: 'https://nos.lol/?nip01=1&kinds=1&limit=5' }).enabled, true); + assert.equal(callCoreWasm<{ enabled: boolean }>('nostr_prepare_nip01', { url: 'https://nos.lol/?kinds=1,30023' }).enabled, true); + + // SSRF / port / credential / private-IP guards fail closed BEFORE opening WS + let factoryCalled = false; + for (const badUrl of [ + 'http://nos.lol/?nip01=1', + 'https://nos.lol:8443/?nip01=1', + 'https://user:pass@nos.lol/?nip01=1', + 'https://127.0.0.1/?nip01=1', + 'https://169.254.169.254/?nip01=1', + 'https://hub.example.com/?nip01=1', + ]) { + const res = await fetchNostrRelayNip01Events({ + url: badUrl, + selfHost: 'hub.example.com', + webSocketFactory: () => { + factoryCalled = true; + return new MockNostrWebSocket('wss://bad/') as unknown as WebSocket; + }, + }); + assert.equal(res.ok, false, `Expected Nostr WS SSRF rejection for ${badUrl}`); + } + assert.equal(factoryCalled, false, 'WebSocket factory must NEVER be called for unsafe Nostr URLs'); + + // robots_disallowed on NIP-11 precheck also blocks WS + const robotsBlocked = await executeScrapeCall({ + payload: { url: 'https://nos.lol/?nip01=1&kinds=1', discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: async (_t, body) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string; url: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [{ id: req.id, url: req.url, outcome: 'robots_disallowed', status: 422, problem: 'Disallowed by robots.txt' }], + }), + }; + }, + webSocketFactory: () => { + factoryCalled = true; + return new MockNostrWebSocket('wss://nos.lol/') as unknown as WebSocket; + }, + }); + assert.equal(factoryCalled, false, 'WebSocket must NOT open when robots.txt disallows NIP-11 origin'); + assert.notEqual(robotsBlocked.body.contentState, 'active'); + + // Mocked bounded read-only WS NIP-01 REQ -> sends ONLY REQ & CLOSE (ZERO EVENT/AUTH/COUNT), collects events & stops on EOSE + const nip11Json = JSON.stringify({ + name: 'nos.lol', + description: 'Public Nostr relay', + supported_nips: [1, 11], + software: 'https://github.com/hoytech/strfry', + version: '1.0.0', + }); + const wsScrape = await executeScrapeCall({ + payload: { + url: 'https://nos.lol/?nip01=1&kinds=1&limit=99', + formats: ['markdown', 'records'], + discoverLlmsTxt: false, + noCache: true, + }, + env: {}, + executeHubFetch: makeOverflowMock(200, nip11Json, 'application/nostr+json', 'https://nos.lol/'), + webSocketFactory: (wssUrl: string) => { + assert.equal(wssUrl, 'wss://nos.lol/'); + const sock = new MockNostrWebSocket(wssUrl); + queueMicrotask(() => { + sock.readyState = 1; + sock.emit('open', {}); + const reqFrame = JSON.parse(sock.sentMessages[0]!) as [string, string, { kinds: number[]; limit: number }]; + assert.equal(reqFrame[0], 'REQ'); + assert.deepEqual(reqFrame[2].kinds, [1]); + assert.equal(reqFrame[2].limit, 20, 'limit=99 must clamp to <= 20'); + const subId = reqFrame[1]; + sock.emit('message', { + data: JSON.stringify([ + 'EVENT', + subId, + { + id: 'a'.repeat(64), + pubkey: 'b'.repeat(64), + created_at: 1732838400, + kind: 1, + tags: [['t', 'nostr']], + content: 'Live WS note clean text.', + sig: 'c'.repeat(128), + }, + ]), + }); + sock.emit('message', { data: JSON.stringify(['EOSE', subId]) }); + }); + return sock as unknown as WebSocket; + }, + }); + assert.equal(wsScrape.status, 200); + assert.equal(wsScrape.body.extractorId, 'nostr-relays'); + assert.equal(wsScrape.body.contentState, 'active'); + assert.ok(String(wsScrape.body.markdown).includes('Live WS note')); + assert.equal(String(wsScrape.body.markdown).includes('

Verifying your browser before redirecting...

`, + markdown: "Verifying your browser before redirecting...", + }, + { + name: "genius-hashcash-challenge-js-200", + status: 200, + url: "https://genius.com/Example-lyrics", + title: "Genius", + rawHTML: `Genius

Please wait while we verify your session.

`, + markdown: "Please wait while we verify your session.", + }, + { + name: "nos-lol-hashcash-403-45w", + status: 403, + url: "https://nos.lol/", + title: "Verification", + rawHTML: `Verification

` + strings.Repeat("Browser proof of work verification step required. ", 7) + `

`, + markdown: strings.Repeat("Browser proof of work verification step required. ", 7), + }, + { + name: "hashcash-429-45w", + status: 429, + url: "https://example.org/protected", + title: "Rate Limit Challenge", + rawHTML: `Rate Limit Challenge

` + strings.Repeat("Please wait while proof of work completes. ", 7) + `

`, + markdown: strings.Repeat("Please wait while proof of work completes. ", 7), + }, + } + + for _, tc := range powCases { + waf := ClassifyWAFAndChallengeFull(WAFChallengeInput{ + Status: tc.status, + URL: tc.url, + Title: tc.title, + RawHTML: tc.rawHTML, + Markdown: tc.markdown, + }) + if waf == nil || waf.Category != "challenge" || waf.Vendor != "generic" { + t.Fatalf("%s: ClassifyWAFAndChallengeFull got %+v, want vendor=generic category=challenge", tc.name, waf) + } + cs := ClassifyContentStateFull(ContentStateInput{ + Status: tc.status, + URL: tc.url, + FinalURL: tc.url, + Title: tc.title, + RawHTML: tc.rawHTML, + Markdown: tc.markdown, + }) + if cs.State != "temporarily_unavailable" { + t.Fatalf("%s: ClassifyContentStateFull got %q (%s), want temporarily_unavailable", tc.name, cs.State, cs.Reason) + } + } + + // 2. Negative anti-FP controls for HASHCASH_CONFIG: short prose mention (no JS assignment) and >=120-word blog with

+	shortProseHTML := `PoW Note

Tumblr uses HASHCASH_CONFIG for rate limiting.

` + shortProseMD := "Tumblr uses HASHCASH_CONFIG for rate limiting." + if got := ClassifyWAFAndChallengeFull(WAFChallengeInput{ + Status: 200, + URL: "https://blog.example.com/pow-note", + Title: "PoW Note", + RawHTML: shortProseHTML, + Markdown: shortProseMD, + }); got != nil { + t.Fatalf("short prose HASHCASH_CONFIG mention must NOT false-positive in ClassifyWAFAndChallengeFull, got %+v", got) + } + if cs := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://blog.example.com/pow-note", + FinalURL: "https://blog.example.com/pow-note", + Title: "PoW Note", + RawHTML: shortProseHTML, + Markdown: shortProseMD, + }); cs.State != "active" { + t.Fatalf("short prose HASHCASH_CONFIG mention got state=%q (%s), want active", cs.State, cs.Reason) + } + + longBlogBody := strings.Repeat("Hashcash proof-of-work challenges protect public web endpoints from automated abuse without relying on invasive third-party tracking cookies or visual puzzles. ", 16) + longBlogHTML := `Hashcash Proof of Work Guide

Hashcash Proof of Work Guide

` + longBlogBody + `

window.HASHCASH_CONFIG = { difficulty: 4 };
` + longBlogMD := "# Hashcash Proof of Work Guide\n\n" + longBlogBody + "\n\n```\nwindow.HASHCASH_CONFIG = { difficulty: 4 };\n```\n" + if got := ClassifyWAFAndChallengeFull(WAFChallengeInput{ + Status: 200, + URL: "https://docs.example.com/hashcash", + Title: "Hashcash Proof of Work Guide", + RawHTML: longBlogHTML, + Markdown: longBlogMD, + }); got != nil { + t.Fatalf(">=120-word blog with
 HASHCASH_CONFIG must NOT false-positive in ClassifyWAFAndChallengeFull, got %+v", got)
+	}
+	if cs := ClassifyContentStateFull(ContentStateInput{
+		Status:   200,
+		URL:      "https://docs.example.com/hashcash",
+		FinalURL: "https://docs.example.com/hashcash",
+		Title:    "Hashcash Proof of Work Guide",
+		RawHTML:  longBlogHTML,
+		Markdown: longBlogMD,
+	}); cs.State != "active" {
+		t.Fatalf(">=120-word blog with 
 HASHCASH_CONFIG got state=%q (%s), want active", cs.State, cs.Reason)
+	}
+
+	// 3. energystar #main[data-basepath] empty shell WITH >= 15 words in