diff --git a/.claude/worktrees/bit3884-metadata-editing b/.claude/worktrees/bit3884-metadata-editing deleted file mode 160000 index 67563bb..0000000 --- a/.claude/worktrees/bit3884-metadata-editing +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 67563bb6d0ad2b83012b8e666b52acee68df57b1 diff --git a/src/analytics/csv-export.test.js b/src/analytics/csv-export.test.js new file mode 100644 index 0000000..15d4c86 --- /dev/null +++ b/src/analytics/csv-export.test.js @@ -0,0 +1,107 @@ +'use strict'; + +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); +const { setCSVResponseHeaders, exportArticleEngagement, exportCategoryBenchmarks } = require('./csv-export'); + +function makeMockRes() { + const res = { + headers: {}, + statusCode: null, + body: null, + ended: false, + writeHead(code, headers) { + this.statusCode = code; + Object.assign(this.headers, headers); + }, + end(data) { + this.body = data ?? ''; + this.ended = true; + } + }; + return res; +} + +describe('setCSVResponseHeaders', () => { + it('sets Content-Type to text/csv', () => { + const res = makeMockRes(); + setCSVResponseHeaders(res, 'test.csv'); + assert.equal(res.statusCode, 200); + assert.ok(res.headers['Content-Type'].includes('text/csv')); + }); + + it('sets Content-Disposition with filename', () => { + const res = makeMockRes(); + setCSVResponseHeaders(res, 'my-report.csv'); + assert.ok(res.headers['Content-Disposition'].includes('my-report.csv')); + assert.ok(res.headers['Content-Disposition'].includes('attachment')); + }); + + it('sets Cache-Control to no-store', () => { + const res = makeMockRes(); + setCSVResponseHeaders(res, 'test.csv'); + assert.equal(res.headers['Cache-Control'], 'no-store'); + }); + + it('sanitizes dangerous characters in filename', () => { + const res = makeMockRes(); + setCSVResponseHeaders(res, 'file\r\n"injection.csv'); + const disp = res.headers['Content-Disposition']; + assert.ok(!disp.includes('\r')); + assert.ok(!disp.includes('\n')); + }); + + it('defaults to export.csv when no filename provided', () => { + const res = makeMockRes(); + setCSVResponseHeaders(res, null); + assert.ok(res.headers['Content-Disposition'].includes('export.csv')); + }); + + it('defaults to export.csv for empty string filename', () => { + const res = makeMockRes(); + setCSVResponseHeaders(res, ''); + assert.ok(res.headers['Content-Disposition'].includes('export.csv')); + }); +}); + +describe('exportArticleEngagement', () => { + it('sends a 200 response with CSV headers', async () => { + const res = makeMockRes(); + await exportArticleEngagement(null, res); + assert.equal(res.statusCode, 200); + assert.ok(res.headers['Content-Type'].includes('text/csv')); + }); + + it('ends the response', async () => { + const res = makeMockRes(); + await exportArticleEngagement(null, res); + assert.equal(res.ended, true); + }); + + it('uses article-engagement.csv as filename', async () => { + const res = makeMockRes(); + await exportArticleEngagement(null, res); + assert.ok(res.headers['Content-Disposition'].includes('article-engagement.csv')); + }); +}); + +describe('exportCategoryBenchmarks', () => { + it('sends a 200 response with CSV headers', async () => { + const res = makeMockRes(); + await exportCategoryBenchmarks(null, res); + assert.equal(res.statusCode, 200); + assert.ok(res.headers['Content-Type'].includes('text/csv')); + }); + + it('ends the response', async () => { + const res = makeMockRes(); + await exportCategoryBenchmarks(null, res); + assert.equal(res.ended, true); + }); + + it('uses category-benchmarks.csv as filename', async () => { + const res = makeMockRes(); + await exportCategoryBenchmarks(null, res); + assert.ok(res.headers['Content-Disposition'].includes('category-benchmarks.csv')); + }); +}); diff --git a/src/crawler/merge-sources.test.js b/src/crawler/merge-sources.test.js new file mode 100644 index 0000000..711fa23 --- /dev/null +++ b/src/crawler/merge-sources.test.js @@ -0,0 +1,132 @@ +'use strict'; + +const { describe, it, beforeEach, afterEach } = require('node:test'); +const assert = require('node:assert/strict'); +const Module = require('module'); + +// Stubs for dependencies +let stubRssArticles = []; +let stubXArticles = []; +let stubXError = null; + +const originalLoad = Module._load; + +function mockLoad(request, parent, isMain) { + const resolved = (() => { + try { + return Module._resolveFilename(request, parent); + } catch (_) { + return null; + } + })(); + + if (resolved && resolved.endsWith('/crawler/rss.js')) { + return { + fetchAllFeeds: async () => stubRssArticles, + filterByDomain: (articles, domains, mode) => { + if (mode === 'strict') { + return articles.filter(a => domains.some(d => (a.url || '').includes(d))); + } + return articles; + } + }; + } + if (resolved && resolved.endsWith('/crawler/x.js')) { + return { + fetchXAsArticles: async () => { + if (stubXError) throw stubXError; + return stubXArticles; + } + }; + } + if (resolved && resolved.endsWith('/config/loader.js')) { + return { + loadSocialConfig: () => ({}) + }; + } + return originalLoad(request, parent, isMain); +} + +describe('fetchMergedSourceArticles', () => { + let fetchMergedSourceArticles; + + beforeEach(() => { + stubRssArticles = []; + stubXArticles = []; + stubXError = null; + + Module._load = mockLoad; + + // Clear module cache + const key = Object.keys(require.cache).find(k => k.endsWith('/crawler/merge-sources.js')); + if (key) delete require.cache[key]; + ['rss.js', 'x.js', 'loader.js'].forEach(f => { + const k = Object.keys(require.cache).find(k => k.endsWith(`/crawler/${f}`) || k.endsWith(`/config/${f}`)); + if (k) delete require.cache[k]; + }); + + ({ fetchMergedSourceArticles } = require('./merge-sources')); + }); + + afterEach(() => { + Module._load = originalLoad; + const key = Object.keys(require.cache).find(k => k.endsWith('/crawler/merge-sources.js')); + if (key) delete require.cache[key]; + }); + + it('merges RSS and X articles and sorts newest first', async () => { + stubRssArticles = [ + { title: 'RSS Old', url: 'https://example.com/a', published_at: '2026-01-01T10:00:00Z' }, + { title: 'RSS New', url: 'https://example.com/b', published_at: '2026-01-03T10:00:00Z' } + ]; + stubXArticles = [ + { title: 'X Mid', url: 'https://twitter.com/c', published_at: '2026-01-02T10:00:00Z' } + ]; + + const result = await fetchMergedSourceArticles({ trusted_domains: [] }); + assert.equal(result.length, 3); + assert.equal(result[0].title, 'RSS New'); + assert.equal(result[1].title, 'X Mid'); + assert.equal(result[2].title, 'RSS Old'); + }); + + it('returns RSS only when X fetch fails', async () => { + stubRssArticles = [ + { title: 'RSS Only', url: 'https://example.com/a', published_at: '2026-01-01T10:00:00Z' } + ]; + stubXError = new Error('X API error'); + + const result = await fetchMergedSourceArticles({ trusted_domains: [] }); + assert.equal(result.length, 1); + assert.equal(result[0].title, 'RSS Only'); + }); + + it('applies domain filtering when trusted_domains are configured', async () => { + stubRssArticles = [ + { title: 'Trusted', url: 'https://trusted.com/article', published_at: '2026-01-01T10:00:00Z' }, + { title: 'Untrusted', url: 'https://unknown.com/article', published_at: '2026-01-01T09:00:00Z' } + ]; + + const result = await fetchMergedSourceArticles({ + trusted_domains: ['trusted.com'], + domain_filter_mode: 'strict' + }); + assert.equal(result.length, 1); + assert.equal(result[0].title, 'Trusted'); + }); + + it('skips domain filtering when trusted_domains is empty', async () => { + stubRssArticles = [ + { title: 'A', url: 'https://any.com', published_at: '2026-01-01T10:00:00Z' }, + { title: 'B', url: 'https://other.com', published_at: '2026-01-01T09:00:00Z' } + ]; + + const result = await fetchMergedSourceArticles({ trusted_domains: [] }); + assert.equal(result.length, 2); + }); + + it('returns empty array when no articles from any source', async () => { + const result = await fetchMergedSourceArticles({ trusted_domains: [] }); + assert.equal(result.length, 0); + }); +}); diff --git a/src/crawler/scraper.test.js b/src/crawler/scraper.test.js new file mode 100644 index 0000000..6ba39a2 --- /dev/null +++ b/src/crawler/scraper.test.js @@ -0,0 +1,126 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert'); + +// Mock dependencies before importing the module +// Create test helper to set environment variables +function setEnv(key, value) { + const original = process.env[key]; + process.env[key] = value; + return () => { + if (original === undefined) { + delete process.env[key]; + } else { + process.env[key] = original; + } + }; +} + +test('scrapeArticle extracts content from article selector', async () => { + // This test would require mocking axiosGetWithRetry and cheerio + // For now, we'll skip the full integration test and focus on + // testing the module can be imported and has the right exports + const { scrapeArticle } = require('./scraper'); + + assert.strictEqual(typeof scrapeArticle, 'function'); +}); + +test('scrapeArticle returns expected result structure', async () => { + const { scrapeArticle } = require('./scraper'); + + // Test that the function exists and has the right signature + assert.strictEqual(typeof scrapeArticle, 'function'); + + // We can't easily test the full behavior without mocking HTTP requests, + // but we can verify the module structure + const moduleExports = require('./scraper'); + assert.ok(moduleExports.scrapeArticle); + assert.strictEqual(typeof moduleExports.scrapeArticle, 'function'); +}); + +test('scraper module exports scrapeArticle function', () => { + const moduleExports = require('./scraper'); + + assert.ok(moduleExports.scrapeArticle); + assert.strictEqual(typeof moduleExports.scrapeArticle, 'function'); + assert.strictEqual(Object.keys(moduleExports).length, 1); +}); + +test('environment variables affect scraper configuration', () => { + // Test that environment variables are read correctly + // by setting them and checking the behavior + + const restoreTimeout = setEnv('SCRAPER_TIMEOUT_MS', '8000'); + const restoreAttempts = setEnv('SCRAPER_HTTP_MAX_ATTEMPTS', '2'); + const restoreBaseMs = setEnv('SCRAPER_RETRY_BASE_MS', '1000'); + + try { + // Re-import the module to pick up new env values + delete require.cache[require.resolve('./scraper')]; + const { scrapeArticle } = require('./scraper'); + + // Verify the module loaded successfully + assert.strictEqual(typeof scrapeArticle, 'function'); + } finally { + restoreTimeout(); + restoreAttempts(); + restoreBaseMs(); + + // Clear the cache to restore original values + delete require.cache[require.resolve('./scraper')]; + } +}); + +test('scraper handles invalid environment values gracefully', () => { + const restoreTimeout = setEnv('SCRAPER_TIMEOUT_MS', 'invalid'); + const restoreAttempts = setEnv('SCRAPER_HTTP_MAX_ATTEMPTS', 'not-a-number'); + const restoreBaseMs = setEnv('SCRAPER_RETRY_BASE_MS', 'also-invalid'); + + try { + delete require.cache[require.resolve('./scraper')]; + const { scrapeArticle } = require('./scraper'); + + // Module should still load with defaults + assert.strictEqual(typeof scrapeArticle, 'function'); + } finally { + restoreTimeout(); + restoreAttempts(); + restoreBaseMs(); + delete require.cache[require.resolve('./scraper')]; + } +}); + +test('scraper clamps environment values to safe bounds', () => { + // Test minimum bounds + const restoreMinTimeout = setEnv('SCRAPER_TIMEOUT_MS', '100'); + const restoreMinAttempts = setEnv('SCRAPER_HTTP_MAX_ATTEMPTS', '0'); + const restoreMinBaseMs = setEnv('SCRAPER_RETRY_BASE_MS', '50'); + + try { + delete require.cache[require.resolve('./scraper')]; + const { scrapeArticle } = require('./scraper'); + assert.strictEqual(typeof scrapeArticle, 'function'); + } finally { + restoreMinTimeout(); + restoreMinAttempts(); + restoreMinBaseMs(); + delete require.cache[require.resolve('./scraper')]; + } + + // Test maximum bounds + const restoreMaxTimeout = setEnv('SCRAPER_TIMEOUT_MS', '200000'); + const restoreMaxAttempts = setEnv('SCRAPER_HTTP_MAX_ATTEMPTS', '10'); + const restoreMaxBaseMs = setEnv('SCRAPER_RETRY_BASE_MS', '50000'); + + try { + delete require.cache[require.resolve('./scraper')]; + const { scrapeArticle } = require('./scraper'); + assert.strictEqual(typeof scrapeArticle, 'function'); + } finally { + restoreMaxTimeout(); + restoreMaxAttempts(); + restoreMaxBaseMs(); + delete require.cache[require.resolve('./scraper')]; + } +}); \ No newline at end of file diff --git a/src/http/ui-validators.test.js b/src/http/ui-validators.test.js new file mode 100644 index 0000000..3eb8c17 --- /dev/null +++ b/src/http/ui-validators.test.js @@ -0,0 +1,169 @@ +'use strict'; + +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); +const { validateSourcesPayload, validateSocialPayload, validateThemePayload } = require('./ui-validators'); + +describe('validateSourcesPayload', () => { + it('accepts a valid sources object', () => { + assert.doesNotThrow(() => + validateSourcesPayload({ + rss: [{ name: 'Feed', url: 'https://example.com/feed' }] + }) + ); + }); + + it('throws when root is not an object', () => { + assert.throws(() => validateSourcesPayload(null), /JSON inválido/); + assert.throws(() => validateSourcesPayload('string'), /JSON inválido/); + assert.throws(() => validateSourcesPayload(42), /JSON inválido/); + }); + + it('throws when rss is missing', () => { + assert.throws(() => validateSourcesPayload({}), /rss tem de ser um array/); + }); + + it('throws when rss is not an array', () => { + assert.throws(() => validateSourcesPayload({ rss: 'bad' }), /rss tem de ser um array/); + assert.throws(() => validateSourcesPayload({ rss: {} }), /rss tem de ser um array/); + }); + + it('throws on invalid rss entry (not object)', () => { + assert.throws(() => validateSourcesPayload({ rss: [null] }), /Entrada rss inválida/); + assert.throws(() => validateSourcesPayload({ rss: ['string'] }), /Entrada rss inválida/); + }); + + it('throws on rss entry missing name', () => { + assert.throws( + () => validateSourcesPayload({ rss: [{ name: '', url: 'https://example.com' }] }), + /Cada feed precisa de name/ + ); + assert.throws( + () => validateSourcesPayload({ rss: [{ url: 'https://example.com' }] }), + /Cada feed precisa de name/ + ); + }); + + it('throws on rss entry with invalid URL', () => { + assert.throws( + () => validateSourcesPayload({ rss: [{ name: 'Feed', url: 'not-a-url' }] }), + /URL inválida/ + ); + assert.throws( + () => validateSourcesPayload({ rss: [{ name: 'Feed', url: 'ftp://bad.com' }] }), + /URL inválida/ + ); + }); + + it('accepts http:// URLs (not just https)', () => { + assert.doesNotThrow(() => + validateSourcesPayload({ rss: [{ name: 'Feed', url: 'http://example.com/feed' }] }) + ); + }); + + it('throws when keywords is not an array (if provided)', () => { + assert.throws( + () => validateSourcesPayload({ rss: [], keywords: 'bad' }), + /keywords tem de ser um array/ + ); + }); + + it('accepts keywords as null or undefined', () => { + assert.doesNotThrow(() => validateSourcesPayload({ rss: [], keywords: null })); + assert.doesNotThrow(() => validateSourcesPayload({ rss: [] })); + }); + + it('accepts keywords as array', () => { + assert.doesNotThrow(() => validateSourcesPayload({ rss: [], keywords: ['tech', 'news'] })); + }); + + it('throws when trusted_domains is not an array (if provided)', () => { + assert.throws( + () => validateSourcesPayload({ rss: [], trusted_domains: 'bad' }), + /trusted_domains tem de ser um array/ + ); + }); + + it('accepts trusted_domains as null or undefined', () => { + assert.doesNotThrow(() => validateSourcesPayload({ rss: [], trusted_domains: null })); + assert.doesNotThrow(() => validateSourcesPayload({ rss: [] })); + }); + + it('accepts trusted_domains as array', () => { + assert.doesNotThrow(() => validateSourcesPayload({ rss: [], trusted_domains: ['example.com'] })); + }); +}); + +describe('validateSocialPayload', () => { + it('accepts valid social payload', () => { + assert.doesNotThrow(() => + validateSocialPayload({ x: { queries: ['bitcoin', 'crypto'] } }) + ); + }); + + it('throws when root is not an object', () => { + assert.throws(() => validateSocialPayload(null), /JSON inválido/); + assert.throws(() => validateSocialPayload(42), /JSON inválido/); + }); + + it('throws when x object is missing', () => { + assert.throws(() => validateSocialPayload({}), /Falta o objeto x/); + assert.throws(() => validateSocialPayload({ x: null }), /Falta o objeto x/); + }); + + it('throws when x.queries is not an array', () => { + assert.throws(() => validateSocialPayload({ x: { queries: 'bad' } }), /x\.queries tem de ser um array/); + assert.throws(() => validateSocialPayload({ x: {} }), /x\.queries tem de ser um array/); + }); + + it('throws when a query is not a string', () => { + assert.throws( + () => validateSocialPayload({ x: { queries: [42] } }), + /Cada query tem de ser texto/ + ); + }); + + it('accepts empty queries array', () => { + assert.doesNotThrow(() => validateSocialPayload({ x: { queries: [] } })); + }); +}); + +describe('validateThemePayload', () => { + it('accepts valid theme payload', () => { + assert.doesNotThrow(() => + validateThemePayload({ app_title: 'My App', accent_hex: '#FF5733' }) + ); + }); + + it('throws when root is not an object', () => { + assert.throws(() => validateThemePayload(null), /JSON inválido/); + assert.throws(() => validateThemePayload('bad'), /JSON inválido/); + }); + + it('throws when app_title is missing or empty', () => { + assert.throws(() => validateThemePayload({ accent_hex: '#FF5733' }), /app_title obrigatório/); + assert.throws(() => validateThemePayload({ app_title: '', accent_hex: '#FF5733' }), /app_title obrigatório/); + assert.throws(() => validateThemePayload({ app_title: ' ', accent_hex: '#FF5733' }), /app_title obrigatório/); + }); + + it('throws when accent_hex is invalid format', () => { + assert.throws( + () => validateThemePayload({ app_title: 'App', accent_hex: 'red' }), + /accent_hex tem de ser/ + ); + assert.throws( + () => validateThemePayload({ app_title: 'App', accent_hex: '#XYZ' }), + /accent_hex tem de ser/ + ); + assert.throws( + () => validateThemePayload({ app_title: 'App', accent_hex: '#FFF' }), + /accent_hex tem de ser/ + ); + }); + + it('accepts both uppercase and lowercase hex', () => { + assert.doesNotThrow(() => validateThemePayload({ app_title: 'App', accent_hex: '#ff5733' })); + assert.doesNotThrow(() => validateThemePayload({ app_title: 'App', accent_hex: '#FF5733' })); + assert.doesNotThrow(() => validateThemePayload({ app_title: 'App', accent_hex: '#aAbBcC' })); + }); +}); diff --git a/src/publisher/wp-publish-hours.test.js b/src/publisher/wp-publish-hours.test.js new file mode 100644 index 0000000..4f1e009 --- /dev/null +++ b/src/publisher/wp-publish-hours.test.js @@ -0,0 +1,137 @@ +'use strict'; + +const { describe, it, beforeEach, afterEach } = require('node:test'); +const assert = require('node:assert/strict'); +const { getLocalHourForPublishWindow, resolveWpStatus } = require('./wp-publish-hours'); + +describe('getLocalHourForPublishWindow', () => { + let prevTz; + + beforeEach(() => { + prevTz = process.env.CRON_TIMEZONE; + }); + + afterEach(() => { + if (prevTz !== undefined) { + process.env.CRON_TIMEZONE = prevTz; + } else { + delete process.env.CRON_TIMEZONE; + } + }); + + it('returns a number between 0 and 23', () => { + delete process.env.CRON_TIMEZONE; + const h = getLocalHourForPublishWindow(new Date()); + assert.ok(typeof h === 'number'); + assert.ok(h >= 0 && h <= 23); + }); + + it('returns correct hour for a specific time with UTC timezone', () => { + process.env.CRON_TIMEZONE = 'UTC'; + const date = new Date('2026-01-15T14:30:00Z'); + const h = getLocalHourForPublishWindow(date); + assert.equal(h, 14); + }); + + it('returns correct hour for Europe/Lisbon (UTC+0/UTC+1)', () => { + process.env.CRON_TIMEZONE = 'Europe/Lisbon'; + // January = UTC+0 for Lisbon + const date = new Date('2026-01-15T10:00:00Z'); + const h = getLocalHourForPublishWindow(date); + assert.ok(typeof h === 'number'); + assert.ok(h >= 0 && h <= 23); + }); + + it('falls back to host time when CRON_TIMEZONE is empty', () => { + process.env.CRON_TIMEZONE = ''; + const now = new Date(); + const h = getLocalHourForPublishWindow(now); + assert.ok(typeof h === 'number'); + assert.ok(h >= 0 && h <= 23); + }); + + it('falls back to host time when CRON_TIMEZONE is invalid', () => { + process.env.CRON_TIMEZONE = 'Not/A/Valid/Timezone'; + const now = new Date(); + const h = getLocalHourForPublishWindow(now); + assert.ok(typeof h === 'number'); + assert.ok(h >= 0 && h <= 23); + }); + + it('uses new Date() when no date argument is provided', () => { + delete process.env.CRON_TIMEZONE; + const h = getLocalHourForPublishWindow(); + assert.ok(typeof h === 'number'); + assert.ok(h >= 0 && h <= 23); + }); +}); + +describe('resolveWpStatus', () => { + let prevTz; + + beforeEach(() => { + prevTz = process.env.CRON_TIMEZONE; + process.env.CRON_TIMEZONE = 'UTC'; + }); + + afterEach(() => { + if (prevTz !== undefined) { + process.env.CRON_TIMEZONE = prevTz; + } else { + delete process.env.CRON_TIMEZONE; + } + }); + + it('returns base status when publishHours is null', () => { + const status = resolveWpStatus({ wp_status: 'draft' }, null); + assert.equal(status, 'draft'); + }); + + it('returns base status when publishHours is undefined', () => { + const status = resolveWpStatus({ wp_status: 'publish' }, undefined); + assert.equal(status, 'publish'); + }); + + it('falls back to status_default when wp_status is not set', () => { + const status = resolveWpStatus({ status_default: 'draft' }, null); + assert.equal(status, 'draft'); + }); + + it('falls back to "draft" when no status config is set', () => { + const status = resolveWpStatus({}, null); + assert.equal(status, 'draft'); + }); + + it('returns "publish" when current hour is inside publish window', () => { + // Use UTC noon (12:00) and window 9-17 + const date = new Date('2026-01-15T12:00:00Z'); + const status = resolveWpStatus({ wp_status: 'draft' }, { start: 9, end: 17 }, date); + assert.equal(status, 'publish'); + }); + + it('returns "draft" when current hour is before publish window', () => { + // Use UTC 06:00 and window 9-17 + const date = new Date('2026-01-15T06:00:00Z'); + const status = resolveWpStatus({ wp_status: 'draft' }, { start: 9, end: 17 }, date); + assert.equal(status, 'draft'); + }); + + it('returns "draft" when current hour is at or after window end (exclusive)', () => { + // Use UTC 17:00 (end is exclusive: [start, end)) + const date = new Date('2026-01-15T17:00:00Z'); + const status = resolveWpStatus({ wp_status: 'draft' }, { start: 9, end: 17 }, date); + assert.equal(status, 'draft'); + }); + + it('returns "publish" when hour equals window start (inclusive)', () => { + const date = new Date('2026-01-15T09:00:00Z'); + const status = resolveWpStatus({ wp_status: 'draft' }, { start: 9, end: 17 }, date); + assert.equal(status, 'publish'); + }); + + it('returns "draft" when outside window (evening)', () => { + const date = new Date('2026-01-15T22:00:00Z'); + const status = resolveWpStatus({ wp_status: 'draft' }, { start: 8, end: 20 }, date); + assert.equal(status, 'draft'); + }); +}); diff --git a/src/research/aggregator.js b/src/research/aggregator.js new file mode 100644 index 0000000..94a18bd --- /dev/null +++ b/src/research/aggregator.js @@ -0,0 +1,37 @@ +'use strict'; + +const WEIGHTS = { + google_factcheck: 0.5, + cross_reference: 0.35, + claimcheck: 0.15 +}; +const DEFAULT_WEIGHT = 0.25; + +function aggregateVerificationResults(results) { + const scored = (results || []).filter( + (r) => r.status === 'found' && r.confidence !== null && r.confidence !== undefined + ); + + if (scored.length === 0) { + return { overall_confidence: null, overall_status: 'skipped' }; + } + + let weightedSum = 0; + let weightSum = 0; + for (const r of scored) { + const w = WEIGHTS[r.source_name] !== null && WEIGHTS[r.source_name] !== undefined ? WEIGHTS[r.source_name] : DEFAULT_WEIGHT; + weightedSum += r.confidence * w; + weightSum += w; + } + + const overall_confidence = Math.round(weightedSum / weightSum); + + let overall_status; + if (overall_confidence >= 70) overall_status = 'verified'; + else if (overall_confidence >= 45) overall_status = 'unverified'; + else overall_status = 'disputed'; + + return { overall_confidence, overall_status }; +} + +module.exports = { aggregateVerificationResults }; diff --git a/src/research/aggregator.test.js b/src/research/aggregator.test.js new file mode 100644 index 0000000..4e77130 --- /dev/null +++ b/src/research/aggregator.test.js @@ -0,0 +1,98 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { aggregateVerificationResults } = require('./aggregator'); + +test('aggregateVerificationResults — all skipped returns null status', () => { + const results = [ + { source_name: 'google_factcheck', status: 'skipped', confidence: null }, + { source_name: 'cross_reference', status: 'skipped', confidence: null }, + { source_name: 'claimcheck', status: 'skipped', confidence: null } + ]; + const r = aggregateVerificationResults(results); + assert.equal(r.overall_confidence, null); + assert.equal(r.overall_status, 'skipped'); +}); + +test('aggregateVerificationResults — all error status excluded returns skipped', () => { + const results = [ + { source_name: 'google_factcheck', status: 'error', confidence: null }, + { source_name: 'cross_reference', status: 'error', confidence: null } + ]; + const r = aggregateVerificationResults(results); + assert.equal(r.overall_status, 'skipped'); +}); + +test('aggregateVerificationResults — single source high confidence returns verified', () => { + const results = [ + { source_name: 'google_factcheck', status: 'found', confidence: 80 } + ]; + const r = aggregateVerificationResults(results); + assert.equal(r.overall_confidence, 80); + assert.equal(r.overall_status, 'verified'); +}); + +test('aggregateVerificationResults — confidence exactly 70 is verified', () => { + const results = [ + { source_name: 'cross_reference', status: 'found', confidence: 70 } + ]; + const r = aggregateVerificationResults(results); + assert.equal(r.overall_status, 'verified'); +}); + +test('aggregateVerificationResults — confidence 45-69 is unverified', () => { + const results = [ + { source_name: 'cross_reference', status: 'found', confidence: 50 } + ]; + const r = aggregateVerificationResults(results); + assert.equal(r.overall_status, 'unverified'); +}); + +test('aggregateVerificationResults — confidence exactly 45 is unverified', () => { + const results = [ + { source_name: 'cross_reference', status: 'found', confidence: 45 } + ]; + const r = aggregateVerificationResults(results); + assert.equal(r.overall_status, 'unverified'); +}); + +test('aggregateVerificationResults — confidence below 45 is disputed', () => { + const results = [ + { source_name: 'google_factcheck', status: 'found', confidence: 20 } + ]; + const r = aggregateVerificationResults(results); + assert.equal(r.overall_status, 'disputed'); +}); + +test('aggregateVerificationResults — weighted average across all three sources', () => { + // google=0.50, cross_reference=0.35, claimcheck=0.15 + // (80*0.50 + 60*0.35 + 70*0.15) / 1.0 = (40+21+10.5) = 71.5 → rounds to 72 + const results = [ + { source_name: 'google_factcheck', status: 'found', confidence: 80 }, + { source_name: 'cross_reference', status: 'found', confidence: 60 }, + { source_name: 'claimcheck', status: 'found', confidence: 70 } + ]; + const r = aggregateVerificationResults(results); + assert.equal(r.overall_confidence, 72); + assert.equal(r.overall_status, 'verified'); +}); + +test('aggregateVerificationResults — unknown source uses default weight 0.25', () => { + const results = [ + { source_name: 'unknown_source', status: 'found', confidence: 60 } + ]; + const r = aggregateVerificationResults(results); + assert.equal(r.overall_confidence, 60); +}); + +test('aggregateVerificationResults — mixes scored and skipped', () => { + const results = [ + { source_name: 'google_factcheck', status: 'skipped', confidence: null }, + { source_name: 'cross_reference', status: 'found', confidence: 75 }, + { source_name: 'claimcheck', status: 'error', confidence: null } + ]; + const r = aggregateVerificationResults(results); + assert.equal(r.overall_confidence, 75); + assert.equal(r.overall_status, 'verified'); +}); diff --git a/src/research/claims.js b/src/research/claims.js new file mode 100644 index 0000000..69ad1db --- /dev/null +++ b/src/research/claims.js @@ -0,0 +1,41 @@ +'use strict'; + +const MIN_LEN = 20; +const MAX_LEN = 300; +const ABSOLUTE_MAX = 10; +const ABSOLUTE_MIN = 1; + +function stripHtml(text) { + return text.replace(/<[^>]+>/g, ''); +} + +function scoreSentence(s) { + let score = 0; + if (/\d/.test(s)) score += 2; + if (/%|million|billion/i.test(s)) score += 3; + return score; +} + +function extractClaims(article, maxClaims) { + const limit = Math.max(ABSOLUTE_MIN, Math.min(ABSOLUTE_MAX, maxClaims || 1)); + + const parts = [ + article.title || '', + article.subtitle || '', + article.body || '' + ].join(' '); + + const clean = stripHtml(parts); + + const sentences = clean + .split(/(?<=[.!?])\s+/) + .map((s) => s.trim()) + .filter((s) => s.length >= MIN_LEN && s.length <= MAX_LEN) + .filter((s) => !s.endsWith('?')); + + sentences.sort((a, b) => scoreSentence(b) - scoreSentence(a)); + + return sentences.slice(0, limit); +} + +module.exports = { extractClaims }; diff --git a/src/research/claims.test.js b/src/research/claims.test.js new file mode 100644 index 0000000..6c244ea --- /dev/null +++ b/src/research/claims.test.js @@ -0,0 +1,93 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { extractClaims } = require('./claims'); + +test('extractClaims returns array', () => { + const claims = extractClaims({}, 5); + assert.ok(Array.isArray(claims)); +}); + +test('extractClaims strips HTML tags', () => { + const article = { + body: '
The company earned $2 million in revenue for 2024.
' + }; + const claims = extractClaims(article, 5); + assert.ok(claims.every((c) => !/<[^>]+>/.test(c))); +}); + +test('extractClaims respects maxClaims limit', () => { + const body = Array(20) + .fill('The temperature rose by 1.5 degrees Celsius per decade.') + .join(' '); + const claims = extractClaims({ body }, 3); + assert.ok(claims.length <= 3); +}); + +test('extractClaims clamps maxClaims to 10', () => { + const body = Array(30) + .fill('GDP grew by 3.2% annually per government statistical data.') + .join(' '); + const claims = extractClaims({ body }, 50); + assert.ok(claims.length <= 10); +}); + +test('extractClaims clamps maxClaims minimum to 1', () => { + const article = { body: 'Revenue grew by 15% in fiscal year 2024.' }; + const claims = extractClaims(article, 0); + assert.ok(claims.length <= 1); +}); + +test('extractClaims prefers sentences with numbers', () => { + const article = { + body: 'Something happened in the world. Population reached 8 billion people worldwide. Another event occurred.' + }; + const claims = extractClaims(article, 1); + if (claims.length > 0) { + assert.ok(/\d/.test(claims[0])); + } +}); + +test('extractClaims excludes questions', () => { + const article = { + body: 'Is the economy growing? The economy grew by 2.5% in 2024 according to official data.' + }; + const claims = extractClaims(article, 5); + assert.ok(claims.every((c) => !c.endsWith('?'))); +}); + +test('extractClaims excludes very short sentences', () => { + const article = { + body: 'Yes. The economy grew by 2.5% in 2024. No.' + }; + const claims = extractClaims(article, 5); + assert.ok(claims.every((c) => c.length >= 20)); +}); + +test('extractClaims excludes very long sentences', () => { + const article = { + body: 'A'.repeat(310) + '. GDP rose 3%.' + }; + const claims = extractClaims(article, 5); + assert.ok(claims.every((c) => c.length <= 300)); +}); + +test('extractClaims combines title, subtitle, and body', () => { + const article = { + title: 'Study finds 40% increase in renewable energy adoption.', + subtitle: 'Researchers at MIT confirm significant progress in 2024.', + body: '' + }; + const claims = extractClaims(article, 5); + assert.ok(claims.length > 0); +}); + +test('extractClaims scores sentences with percent/million/billion higher', () => { + const article = { + body: 'The fund raised $500 million for infrastructure. Some general statement about things. Revenue hit 2 billion dollars.' + }; + const claims = extractClaims(article, 2); + const combined = claims.join(' '); + assert.ok(/million|billion|500|2/.test(combined)); +}); diff --git a/src/research/config.js b/src/research/config.js new file mode 100644 index 0000000..64d7995 --- /dev/null +++ b/src/research/config.js @@ -0,0 +1,17 @@ +'use strict'; + +function researchConfig() { + const enabled = + process.env.RESEARCH_ENABLED === 'true' || process.env.RESEARCH_ENABLED === '1'; + const timeoutMs = process.env.RESEARCH_TIMEOUT_MS + ? parseInt(process.env.RESEARCH_TIMEOUT_MS, 10) + : 10000; + const claimsMax = process.env.RESEARCH_CLAIMS_MAX + ? parseInt(process.env.RESEARCH_CLAIMS_MAX, 10) + : 5; + const googleApiKey = (process.env.GOOGLE_FACTCHECK_API_KEY || '').trim(); + const claimBusterApiKey = (process.env.CLAIMCHECK_API_KEY || '').trim(); + return { enabled, timeoutMs, claimsMax, googleApiKey, claimBusterApiKey }; +} + +module.exports = { researchConfig }; diff --git a/src/research/config.test.js b/src/research/config.test.js new file mode 100644 index 0000000..3327245 --- /dev/null +++ b/src/research/config.test.js @@ -0,0 +1,91 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +function withEnv(overrides, fn) { + const saved = {}; + const keys = Object.keys(overrides); + for (const k of keys) { + saved[k] = process.env[k]; + if (overrides[k] === undefined) { + delete process.env[k]; + } else { + process.env[k] = overrides[k]; + } + } + try { + fn(); + } finally { + for (const k of keys) { + if (saved[k] === undefined) delete process.env[k]; + else process.env[k] = saved[k]; + } + } +} + +test('researchConfig defaults when env vars are absent', () => { + withEnv( + { + RESEARCH_ENABLED: undefined, + RESEARCH_TIMEOUT_MS: undefined, + RESEARCH_CLAIMS_MAX: undefined, + GOOGLE_FACTCHECK_API_KEY: undefined, + CLAIMCHECK_API_KEY: undefined + }, + () => { + delete require.cache[require.resolve('./config')]; + const { researchConfig } = require('./config'); + const cfg = researchConfig(); + assert.equal(cfg.enabled, false); + assert.equal(cfg.timeoutMs, 10000); + assert.equal(cfg.claimsMax, 5); + assert.equal(cfg.googleApiKey, ''); + assert.equal(cfg.claimBusterApiKey, ''); + } + ); +}); + +test('researchConfig enabled via "true"', () => { + withEnv({ RESEARCH_ENABLED: 'true' }, () => { + delete require.cache[require.resolve('./config')]; + const { researchConfig } = require('./config'); + assert.equal(researchConfig().enabled, true); + }); +}); + +test('researchConfig enabled via "1"', () => { + withEnv({ RESEARCH_ENABLED: '1' }, () => { + delete require.cache[require.resolve('./config')]; + const { researchConfig } = require('./config'); + assert.equal(researchConfig().enabled, true); + }); +}); + +test('researchConfig disabled for any other value', () => { + withEnv({ RESEARCH_ENABLED: 'yes' }, () => { + delete require.cache[require.resolve('./config')]; + const { researchConfig } = require('./config'); + assert.equal(researchConfig().enabled, false); + }); +}); + +test('researchConfig reads timeout and claims max from env', () => { + withEnv({ RESEARCH_TIMEOUT_MS: '5000', RESEARCH_CLAIMS_MAX: '3' }, () => { + delete require.cache[require.resolve('./config')]; + const { researchConfig } = require('./config'); + const cfg = researchConfig(); + assert.equal(cfg.timeoutMs, 5000); + assert.equal(cfg.claimsMax, 3); + }); +}); + +test('researchConfig reads API keys from env', () => { + withEnv({ GOOGLE_FACTCHECK_API_KEY: 'gfck-123', CLAIMCHECK_API_KEY: ' cbk-456 ' }, () => { + delete require.cache[require.resolve('./config')]; + const { researchConfig } = require('./config'); + const cfg = researchConfig(); + assert.equal(cfg.googleApiKey, 'gfck-123'); + assert.equal(cfg.claimBusterApiKey, 'cbk-456'); + }); +}); diff --git a/src/research/sources/claimcheck.js b/src/research/sources/claimcheck.js new file mode 100644 index 0000000..4cfff4b --- /dev/null +++ b/src/research/sources/claimcheck.js @@ -0,0 +1,49 @@ +'use strict'; + +const { axiosGetWithRetry } = require('../../util/http-retry'); + +const MAX_CLAIMS = 3; +const CLAIMCHECK_API = 'https://idir.uta.edu/factcheck/api/v2/claims/search/'; + +function extractScore(data) { + if (data && data.score !== null && data.score !== undefined) return data.score; + if (data && Array.isArray(data.results) && data.results[0] && data.results[0].score !== null && data.results[0].score !== undefined) { + return data.results[0].score; + } + return null; +} + +async function queryClaimBuster(claims, apiKey, timeoutMs) { + if (!apiKey) { + return { source_name: 'claimcheck', status: 'skipped', confidence: null, reason: 'no_api_key', results: [] }; + } + if (!claims || claims.length === 0) { + return { source_name: 'claimcheck', status: 'skipped', confidence: null, reason: 'no_claims', results: [] }; + } + + const batch = claims.slice(0, MAX_CLAIMS); + const results = []; + + for (const claim of batch) { + try { + const url = `${CLAIMCHECK_API}?query=${encodeURIComponent(claim)}&api_key=${apiKey}`; + const resp = await axiosGetWithRetry(url, { timeout: timeoutMs }); + const score = extractScore(resp.data); + results.push({ claim, check_worthiness: score }); + } catch (err) { + results.push({ claim, error: err.message }); + } + } + + const scored = results.filter((r) => r.check_worthiness !== null && r.check_worthiness !== undefined); + if (scored.length === 0) { + return { source_name: 'claimcheck', status: 'error', confidence: null, error: 'all_requests_failed', results }; + } + + const avgScore = scored.reduce((s, r) => s + r.check_worthiness, 0) / scored.length; + const confidence = Math.round(40 + avgScore * 50); + + return { source_name: 'claimcheck', status: 'found', confidence, results }; +} + +module.exports = { queryClaimBuster }; diff --git a/src/research/sources/claimcheck.test.js b/src/research/sources/claimcheck.test.js new file mode 100644 index 0000000..43d10d3 --- /dev/null +++ b/src/research/sources/claimcheck.test.js @@ -0,0 +1,98 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +// Inject mock for axiosGetWithRetry before loading the module under test +const httpRetryMod = require('../../util/http-retry'); +const _origGet = httpRetryMod.axiosGetWithRetry; +let _mockGet = null; +httpRetryMod.axiosGetWithRetry = async (...args) => { + if (_mockGet) return _mockGet(...args); + throw new Error('axiosGetWithRetry mock not set'); +}; + +delete require.cache[require.resolve('./claimcheck')]; +const { queryClaimBuster } = require('./claimcheck'); + +httpRetryMod.axiosGetWithRetry = _origGet; + +test('queryClaimBuster — no API key returns skipped', async () => { + const result = await queryClaimBuster(['some claim'], '', 5000); + assert.equal(result.source_name, 'claimcheck'); + assert.equal(result.status, 'skipped'); + assert.equal(result.confidence, null); + assert.equal(result.reason, 'no_api_key'); +}); + +test('queryClaimBuster — empty claims array returns skipped', async () => { + const result = await queryClaimBuster([], 'api-key', 5000); + assert.equal(result.status, 'skipped'); + assert.equal(result.reason, 'no_claims'); +}); + +test('queryClaimBuster — null claims returns skipped', async () => { + const result = await queryClaimBuster(null, 'api-key', 5000); + assert.equal(result.status, 'skipped'); + assert.equal(result.reason, 'no_claims'); +}); + +test('queryClaimBuster — successful score returns found with confidence', async () => { + _mockGet = async () => ({ data: { score: 0.8 } }); + const result = await queryClaimBuster(['Revenue grew by 15% in 2024.'], 'api-key', 5000); + assert.equal(result.source_name, 'claimcheck'); + assert.equal(result.status, 'found'); + assert.ok(result.confidence >= 40 && result.confidence <= 90); + assert.ok(result.results.length > 0); + assert.equal(result.results[0].check_worthiness, 0.8); + _mockGet = null; +}); + +test('queryClaimBuster — processes up to 3 claims', async () => { + const scores = [0.9, 0.7, 0.5]; + let callCount = 0; + _mockGet = async () => ({ data: { score: scores[callCount++] } }); + const claims = ['c1', 'c2', 'c3', 'c4', 'c5']; + const result = await queryClaimBuster(claims, 'key', 5000); + assert.equal(callCount, 3); + assert.equal(result.results.length, 3); + _mockGet = null; +}); + +test('queryClaimBuster — all requests fail returns error', async () => { + _mockGet = async () => { throw new Error('timeout'); }; + const result = await queryClaimBuster(['some claim'], 'api-key', 5000); + assert.equal(result.status, 'error'); + assert.equal(result.confidence, null); + assert.equal(result.error, 'all_requests_failed'); + _mockGet = null; +}); + +test('queryClaimBuster — partial failure still returns found', async () => { + let callCount = 0; + _mockGet = async () => { + callCount++; + if (callCount === 1) throw new Error('fail'); + return { data: { score: 0.6 } }; + }; + const result = await queryClaimBuster(['c1', 'c2'], 'api-key', 5000); + assert.equal(result.status, 'found'); + assert.ok(result.results.some((r) => r.error)); + assert.ok(result.results.some((r) => r.check_worthiness !== undefined)); + _mockGet = null; +}); + +test('queryClaimBuster — handles nested score in results array', async () => { + _mockGet = async () => ({ data: { results: [{ score: 0.75 }] } }); + const result = await queryClaimBuster(['GDP grew by 3%.'], 'api-key', 5000); + assert.equal(result.status, 'found'); + assert.equal(result.results[0].check_worthiness, 0.75); + _mockGet = null; +}); + +test('queryClaimBuster — confidence formula: 40 + avgScore*50', async () => { + _mockGet = async () => ({ data: { score: 0.6 } }); + const result = await queryClaimBuster(['a claim'], 'api-key', 5000); + assert.equal(result.confidence, Math.round(40 + 0.6 * 50)); + _mockGet = null; +}); diff --git a/src/research/sources/cross-reference.js b/src/research/sources/cross-reference.js new file mode 100644 index 0000000..c9d21a4 --- /dev/null +++ b/src/research/sources/cross-reference.js @@ -0,0 +1,66 @@ +'use strict'; + +const { axiosGetWithRetry } = require('../../util/http-retry'); + +const TRUSTED_DOMAINS = [ + 'bbc.com', 'bbc.co.uk', 'reuters.com', 'apnews.com', 'theguardian.com', + 'nytimes.com', 'washingtonpost.com', 'bloomberg.com', 'ft.com', 'economist.com' +]; +const TRUSTED_PER_SOURCE = 10; +const MAX_TRUSTED_BONUS = 40; +const MAX_WEB_BONUS = 20; +const BASE_CONFIDENCE = 30; +const MAX_CONFIDENCE = 85; +const MIN_TITLE_LEN = 10; + +function countTrustedSources(sources) { + if (!Array.isArray(sources)) return 0; + let count = 0; + for (const s of sources) { + const url = (s && s.url) || ''; + if (TRUSTED_DOMAINS.some((d) => url.includes(d))) count++; + } + return count; +} + +function countWebHits(html) { + const matches = html.match(/class="result-link"/g); + return matches ? matches.length : 0; +} + +async function queryCrossReference(article, timeoutMs) { + const title = (article && article.title) || ''; + const sources = (article && article.sources) || []; + + const trustedCount = countTrustedSources(sources); + const trustedBonus = Math.min(MAX_TRUSTED_BONUS, trustedCount * TRUSTED_PER_SOURCE); + + let webBonus = 0; + if (title.length >= MIN_TITLE_LEN) { + try { + const query = encodeURIComponent(title); + const url = `https://html.duckduckgo.com/html/?q=${query}`; + const resp = await axiosGetWithRetry(url, { timeout: timeoutMs }); + const hits = countWebHits(resp.data || ''); + webBonus = Math.min(MAX_WEB_BONUS, hits * 4); + } catch (_) { + webBonus = 0; + } + } + + const rawConfidence = BASE_CONFIDENCE + trustedBonus + webBonus; + const confidence = Math.min(MAX_CONFIDENCE, rawConfidence); + const status = confidence > BASE_CONFIDENCE ? 'found' : 'not_found'; + + return { + source_name: 'cross_reference', + status, + confidence, + results: [ + { metric: 'trusted_source_overlap', value: trustedCount }, + { metric: 'web_news_hits', value: webBonus / 4 } + ] + }; +} + +module.exports = { queryCrossReference }; diff --git a/src/research/sources/cross-reference.test.js b/src/research/sources/cross-reference.test.js new file mode 100644 index 0000000..967a60e --- /dev/null +++ b/src/research/sources/cross-reference.test.js @@ -0,0 +1,104 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +// Inject mock for axiosGetWithRetry before loading the module under test +const httpRetryMod = require('../../util/http-retry'); +const _origGet = httpRetryMod.axiosGetWithRetry; +let _mockGet = null; +httpRetryMod.axiosGetWithRetry = async (...args) => { + if (_mockGet) return _mockGet(...args); + // Default: no web hits + return { data: '' }; +}; + +delete require.cache[require.resolve('./cross-reference')]; +const { queryCrossReference } = require('./cross-reference'); + +httpRetryMod.axiosGetWithRetry = _origGet; + +test('queryCrossReference — returns cross_reference source name', async () => { + const article = { title: 'Test article', sources: [] }; + const result = await queryCrossReference(article, 5000); + assert.equal(result.source_name, 'cross_reference'); + assert.ok(['found', 'not_found'].includes(result.status)); + assert.ok(typeof result.confidence === 'number'); +}); + +test('queryCrossReference — article with trusted source URLs increases confidence', async () => { + _mockGet = async () => ({ data: '' }); + const article = { + title: 'Football match results', + sources: [ + { url: 'https://www.bbc.com/sport/football/result' }, + { url: 'https://www.theguardian.com/sport' } + ] + }; + const withSources = await queryCrossReference(article, 5000); + assert.ok(typeof withSources.confidence === 'number'); + assert.ok(withSources.confidence >= 30); + _mockGet = null; +}); + +test('queryCrossReference — article with no sources has lower confidence', async () => { + _mockGet = async () => ({ data: '' }); + const articleNoSources = { title: 'Obscure local news article no sources', sources: [] }; + const result = await queryCrossReference(articleNoSources, 5000); + assert.equal(result.confidence, 30); + _mockGet = null; +}); + +test('queryCrossReference — web hits from DuckDuckGo add to confidence', async () => { + const fakeHtml = 'r1r2r3'; + _mockGet = async () => ({ data: fakeHtml }); + const article = { title: 'Tech news story coverage', sources: [] }; + const result = await queryCrossReference(article, 5000); + assert.ok(result.confidence > 30); + _mockGet = null; +}); + +test('queryCrossReference — DuckDuckGo failure does not crash', async () => { + _mockGet = async () => { throw new Error('network error'); }; + const article = { title: 'Some article', sources: [] }; + const result = await queryCrossReference(article, 5000); + assert.equal(result.source_name, 'cross_reference'); + assert.ok(typeof result.confidence === 'number'); + _mockGet = null; +}); + +test('queryCrossReference — title too short skips DDG search', async () => { + let callCount = 0; + _mockGet = async () => { callCount++; return { data: '' }; }; + const article = { title: 'Short', sources: [] }; + await queryCrossReference(article, 5000); + assert.equal(callCount, 0); + _mockGet = null; +}); + +test('queryCrossReference — confidence capped at 85', async () => { + // Maximum: 30 + 40 (trusted) + 20 (web) = 90, capped to 85 + const html = 'r'.repeat(10); + _mockGet = async () => ({ data: html }); + const article = { + title: 'Big news story with full coverage across all sources', + sources: [ + { url: 'https://trusted1.com/story' }, + { url: 'https://trusted2.com/story' }, + { url: 'https://trusted3.com/story' } + ] + }; + const result = await queryCrossReference(article, 5000); + assert.ok(result.confidence <= 85); + _mockGet = null; +}); + +test('queryCrossReference — results array contains expected metrics', async () => { + _mockGet = async () => ({ data: '' }); + const article = { title: 'A detailed analysis story here', sources: [] }; + const result = await queryCrossReference(article, 5000); + assert.ok(Array.isArray(result.results)); + assert.ok(result.results.some((r) => r.metric === 'trusted_source_overlap')); + assert.ok(result.results.some((r) => r.metric === 'web_news_hits')); + _mockGet = null; +}); diff --git a/src/research/sources/google-factcheck.js b/src/research/sources/google-factcheck.js new file mode 100644 index 0000000..3f68295 --- /dev/null +++ b/src/research/sources/google-factcheck.js @@ -0,0 +1,64 @@ +'use strict'; + +const { axiosGetWithRetry } = require('../../util/http-retry'); + +const FACTCHECK_API = 'https://factchecktools.googleapis.com/v1alpha1/claims:search'; +const MAX_CLAIMS = 3; +const POSITIVE_RATINGS = ['true', 'mostly true', 'correct', 'accurate']; +const NEGATIVE_RATINGS = ['false', 'mostly false', 'incorrect', 'inaccurate', 'misleading', 'pants on fire']; + +function rateRating(textualRating) { + const r = (textualRating || '').toLowerCase(); + if (POSITIVE_RATINGS.some((p) => r.includes(p))) return 1; + if (NEGATIVE_RATINGS.some((n) => r.includes(n))) return -1; + return 0; +} + +async function queryGoogleFactCheck(claims, apiKey, timeoutMs) { + if (!apiKey || !claims || claims.length === 0) { + return { source_name: 'google_factcheck', status: 'skipped', confidence: null, results: [] }; + } + + const query = claims.slice(0, MAX_CLAIMS).join(' ').slice(0, 200); + const url = `${FACTCHECK_API}?query=${encodeURIComponent(query)}&key=${apiKey}`; + + let data; + try { + const resp = await axiosGetWithRetry(url, { timeout: timeoutMs }); + data = resp.data; + } catch (err) { + return { source_name: 'google_factcheck', status: 'error', confidence: null, error: err.message, results: [] }; + } + + const claimList = (data && data.claims) || []; + if (claimList.length === 0) { + return { source_name: 'google_factcheck', status: 'not_found', confidence: 40, results: [] }; + } + + const mappedResults = []; + let scoreSum = 0; + let scoreCount = 0; + + for (const c of claimList) { + const reviews = c.claimReview || []; + for (const rev of reviews) { + const rating = rateRating(rev.textualRating); + scoreSum += rating; + scoreCount++; + mappedResults.push({ + claim: c.text, + publisher: rev.publisher && rev.publisher.name, + rating: rev.textualRating, + url: rev.url, + reviewDate: rev.reviewDate || null + }); + } + } + + const avgRating = scoreCount > 0 ? scoreSum / scoreCount : 0; + const confidence = Math.max(20, Math.min(90, Math.round(55 + avgRating * 35))); + + return { source_name: 'google_factcheck', status: 'found', confidence, results: mappedResults }; +} + +module.exports = { queryGoogleFactCheck }; diff --git a/src/research/sources/google-factcheck.test.js b/src/research/sources/google-factcheck.test.js new file mode 100644 index 0000000..92a7c85 --- /dev/null +++ b/src/research/sources/google-factcheck.test.js @@ -0,0 +1,124 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +// Inject mock for axiosGetWithRetry before loading the module under test +const httpRetryMod = require('../../util/http-retry'); +const _origGet = httpRetryMod.axiosGetWithRetry; +let _mockGet = null; +httpRetryMod.axiosGetWithRetry = async (...args) => { + if (_mockGet) return _mockGet(...args); + throw new Error('axiosGetWithRetry mock not set'); +}; + +delete require.cache[require.resolve('./google-factcheck')]; +const { queryGoogleFactCheck } = require('./google-factcheck'); + +// Restore http-retry for other modules +httpRetryMod.axiosGetWithRetry = _origGet; + +test('queryGoogleFactCheck — no API key returns skipped', async () => { + const result = await queryGoogleFactCheck(['some claim'], '', 5000); + assert.equal(result.source_name, 'google_factcheck'); + assert.equal(result.status, 'skipped'); + assert.equal(result.confidence, null); + assert.ok(Array.isArray(result.results)); +}); + +test('queryGoogleFactCheck — no claims list, empty string key skips', async () => { + const result = await queryGoogleFactCheck([], '', 5000); + assert.equal(result.status, 'skipped'); +}); + +test('queryGoogleFactCheck — not_found when API returns empty claims', async () => { + _mockGet = async () => ({ data: { claims: [] } }); + const result = await queryGoogleFactCheck(['test claim'], 'api-key-123', 5000); + assert.equal(result.source_name, 'google_factcheck'); + assert.equal(result.status, 'not_found'); + assert.equal(result.confidence, 40); + assert.deepEqual(result.results, []); + _mockGet = null; +}); + +test('queryGoogleFactCheck — found with claim reviews returns confidence', async () => { + _mockGet = async () => ({ + data: { + claims: [ + { + text: 'Vaccines cause autism', + claimReview: [ + { + publisher: { name: 'FactCheck.org' }, + textualRating: 'False', + url: 'https://example.com/review1', + reviewDate: '2024-01-01' + } + ] + }, + { + text: 'COVID vaccines are safe', + claimReview: [ + { + publisher: { name: 'Snopes' }, + textualRating: 'True', + url: 'https://example.com/review2', + reviewDate: '2024-02-01' + } + ] + } + ] + } + }); + const result = await queryGoogleFactCheck(['claim 1', 'claim 2'], 'api-key-123', 5000); + assert.equal(result.source_name, 'google_factcheck'); + assert.equal(result.status, 'found'); + assert.ok(result.confidence >= 20 && result.confidence <= 90); + assert.ok(result.results.length > 0); + assert.ok(result.results[0].claim); + assert.ok(result.results[0].publisher); + assert.ok(result.results[0].rating); + _mockGet = null; +}); + +test('queryGoogleFactCheck — multiple false ratings lower confidence', async () => { + const falseReview = (text) => ({ + text, + claimReview: [ + { publisher: { name: 'FC' }, textualRating: 'False', url: 'http://x', reviewDate: null } + ] + }); + _mockGet = async () => ({ + data: { + claims: [falseReview('c1'), falseReview('c2'), falseReview('c3')] + } + }); + const result = await queryGoogleFactCheck(['c1', 'c2', 'c3'], 'key', 5000); + assert.equal(result.status, 'found'); + assert.ok(result.confidence >= 20); + _mockGet = null; +}); + +test('queryGoogleFactCheck — HTTP error returns error status', async () => { + _mockGet = async () => { throw new Error('network error'); }; + const result = await queryGoogleFactCheck(['claim'], 'api-key', 5000); + assert.equal(result.source_name, 'google_factcheck'); + assert.equal(result.status, 'error'); + assert.equal(result.confidence, null); + assert.ok(result.error); + _mockGet = null; +}); + +test('queryGoogleFactCheck — only uses first 3 claims', async () => { + const capturedUrls = []; + _mockGet = async (url) => { + capturedUrls.push(url); + return { data: { claims: [] } }; + }; + const claims = ['c1', 'c2', 'c3', 'c4', 'c5']; + await queryGoogleFactCheck(claims, 'key', 5000); + // The query is built from first 3 claims joined and sliced + assert.ok(capturedUrls.length === 1); + assert.ok(capturedUrls[0].includes('query=')); + _mockGet = null; +}); diff --git a/src/runtime/process-diagnostics.test.js b/src/runtime/process-diagnostics.test.js new file mode 100644 index 0000000..62adb69 --- /dev/null +++ b/src/runtime/process-diagnostics.test.js @@ -0,0 +1,54 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +test('installProcessDiagnostics registers listeners', () => { + delete require.cache[require.resolve('./process-diagnostics')]; + const { installProcessDiagnostics } = require('./process-diagnostics'); + + const beforeUnhandled = process.listenerCount('unhandledRejection'); + const beforeUncaught = process.listenerCount('uncaughtException'); + + installProcessDiagnostics(); + + assert.equal(process.listenerCount('unhandledRejection'), beforeUnhandled + 1); + assert.equal(process.listenerCount('uncaughtException'), beforeUncaught + 1); +}); + +test('installProcessDiagnostics is idempotent — second call adds no listeners', () => { + delete require.cache[require.resolve('./process-diagnostics')]; + const { installProcessDiagnostics } = require('./process-diagnostics'); + + installProcessDiagnostics(); + const afterFirst = process.listenerCount('unhandledRejection'); + + installProcessDiagnostics(); + assert.equal(process.listenerCount('unhandledRejection'), afterFirst); +}); + +test('unhandledRejection listener handles Error objects without crashing', () => { + delete require.cache[require.resolve('./process-diagnostics')]; + const { installProcessDiagnostics } = require('./process-diagnostics'); + installProcessDiagnostics(); + + const listeners = process.rawListeners('unhandledRejection'); + const listener = listeners[listeners.length - 1]; + + assert.doesNotThrow(() => { + listener(new Error('test unhandled rejection')); + }); +}); + +test('unhandledRejection listener handles non-Error reasons', () => { + delete require.cache[require.resolve('./process-diagnostics')]; + const { installProcessDiagnostics } = require('./process-diagnostics'); + installProcessDiagnostics(); + + const listeners = process.rawListeners('unhandledRejection'); + const listener = listeners[listeners.length - 1]; + + assert.doesNotThrow(() => { + listener('string rejection reason'); + }); +});