fix(scraper): harden Bloomberg login state (#40)

This commit is contained in:
2026-11-24 19:49:06 +01:00
parent a55dc2e189
commit a3c70670f6
6 changed files with 248 additions and 69 deletions

View File

@ -6,17 +6,22 @@ const vm = require('node:vm')
const { createRequire } = require('node:module')
const html = '<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z"><article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic editorial paragraph.</p></div></article>'
async function request (byparr, failOne = false, poolSize = 2, authTimeout = false, httpDenied = false) {
async function request (byparr, failOne = false, poolSize = 2, authTimeout = false, httpDenied = false, loginOutcome = 'authenticated') {
const routes = {}; const loads = []; const logs = []; const timers = []; let pages = 0; let closed = false; let active = 0; let peak = 0; let byparrCalls = 0; const typed = []
const app = { use () {}, get () {}, post (url, handler) { routes[url] = handler }, listen () {} }
const express = () => app; express.json = () => () => {}
function page (auth) {
let url = ''; let evals = 0
let url = ''; let evals = 0; let submits = 0
return {
async setViewport () {}, async evaluateOnNewDocument () {}, async waitForSelector () {}, async type (selector,value) {typed.push(value)}, async waitForFunction () {},
async waitForNavigation () { url = 'https://www.bloomberg.com/markets' }, async evaluate () { return evals++ === 0 ? [] : true },
async waitForNavigation () { url = 'https://www.bloomberg.com/markets' }, async evaluate (fn) {
if (fn.name === 'clearLoginInput') return true
if (fn.name === 'submitInputForm') {if (++submits === 2) url='https://www.bloomberg.com/markets';return true}
if (fn.name === 'inspectLoginState') return {authenticated:loginOutcome==='authenticated',challenge:loginOutcome==='challenge',twoFactor:loginOutcome==='two_factor_required',rejected:loginOutcome==='auth_rejected',loginForm:false}
return evals++ === 0 ? [] : true
},
async $ () { return null }, keyboard: { async press () {} },
async goto (value) { url = value; if (auth && authTimeout) return new Promise(() => {}); if (!auth) { loads.push(value); active++; peak = Math.max(peak, active); await new Promise(resolve => setTimeout(resolve, 1)); active--; if (failOne && value.endsWith('/b')) throw new Error('PRIVATE loader failed') }; return { status () { return !auth && httpDenied ? 403 : 200 } } }, url () { return url },
async goto (value) { url = auth && loginOutcome === 'login_origin_unavailable' ? 'https://outside.invalid/login' : value; if (auth && authTimeout) return new Promise(() => {}); if (!auth) { loads.push(value); active++; peak = Math.max(peak, active); await new Promise(resolve => setTimeout(resolve, 1)); active--; if (failOne && value.endsWith('/b')) throw new Error('PRIVATE loader failed') }; return { status () { return auth && loginOutcome === 'access_denied' ? 403 : auth && loginOutcome === 'login_http_unavailable' ? 503 : !auth && httpDenied ? 403 : 200 } } }, url () { return url },
async content () { return `<link rel="canonical" href="${url}">` + html }, async close () {}
}
}
@ -44,12 +49,12 @@ async function request (byparr, failOne = false, poolSize = 2, authTimeout = fal
let result
await routes['/bloomberg/enrich']({ body: { username: 'PRIVATE_USER', password: 'PRIVATE_SECRET', urls } }, { json (value) { result = value }, status () { return this } })
assert.deepEqual(result.articles.map(a => a.url), urls)
assert.equal(loads.length, authTimeout ? 0 : poolSize)
assert.ok(logs.every(line => !line.includes('PRIVATE') && !line.includes('http') && !line.includes('Synthetic editorial')))
return { result, pages, peak, closed, timers, byparrCalls, typed }
assert.equal(loads.length, authTimeout || loginOutcome !== 'authenticated' ? 0 : poolSize)
assert.ok(logs.every(line => !line.includes('PRIVATE') && !/https?:\/\//i.test(line) && !line.includes('Synthetic editorial')))
return { result, pages, peak, closed, timers, byparrCalls, typed, logs }
}
test('enrichment always uses authenticated Puppeteer even when Byparr is configured', async () => {
const { result, peak, pages, closed, byparrCalls, typed } = await request(true)
const { result, peak, pages, closed, byparrCalls, typed, logs } = await request(true)
assert.equal(byparrCalls, 0)
assert.equal(pages, 3); assert.equal(closed,true)
assert.ok(typed.includes('PRIVATE_USER') && typed.includes('PRIVATE_SECRET'))
@ -94,3 +99,26 @@ test('HTTP denied article responses cannot be complete even with a plausible edi
assert.equal(byparrCalls,0)
assert.ok(result.articles.every(a => a.content_state === 'unavailable' && a.content === ''))
})
for (const outcome of ['challenge', 'two_factor_required', 'auth_rejected', 'authentication_unconfirmed']) {
test(`login with ${outcome} cannot launch article requests despite leaving sign-in`, async () => {
const {result,byparrCalls,closed} = await request(true,false,2,false,false,outcome)
assert.equal(byparrCalls,0);assert.equal(closed,true)
assert.ok(result.articles.every(a => a.content_state==='unavailable' && a.content===''))
})
}
for (const outcome of ['access_denied','login_http_unavailable']) {
test(`login HTTP ${outcome} stops before any credential entry`, async () => {
const {result,typed,logs,byparrCalls} = await request(true,false,2,false,false,outcome)
assert.equal(typed.length,0);assert.equal(byparrCalls,0)
assert.ok(logs.some(line => line.endsWith(outcome)))
assert.ok(result.articles.every(a => a.content_state==='unavailable' && a.content===''))
})
}
test('unexpected login origin stops before credential entry', async () => {
const {result,typed,byparrCalls} = await request(true,false,2,false,false,'login_origin_unavailable')
assert.equal(typed.length,0);assert.equal(byparrCalls,0)
assert.ok(result.articles.every(a => a.content_state==='unavailable' && a.content===''))
})

View File

@ -0,0 +1,52 @@
const { test } = require('node:test')
const assert = require('node:assert/strict')
const vm = require('node:vm')
const cheerio = require('cheerio')
const { inspectLoginState, classifyLoginState, authenticatedDestination, clearLoginInput, typeVisibleInput, submitInputForm } = require('../bloomberg-login')
// Synthetic DOM fixtures only; no browser navigation, input capture or publisher HTML.
function fixture (html) {
const $ = cheerio.load(html); const clicked = []; const values = new Map()
const wrap = node => ({
hidden: $(node).is('[hidden]'), disabled: $(node).is('[disabled]'),
getAttribute: name => $(node).attr(name) ?? null,
getClientRects: () => $(node).parents().addBack().is('[hidden], [aria-hidden="true"], [style="display:none"]') ? [] : [{}],
get form () { const form = $(node).closest('form')[0];return form ? wrap(form) : null },
querySelectorAll: selector => $(node).find(selector).toArray().map(wrap),
click () { clicked.push($(node).attr('id')) },
get value () { return values.has(node) ? values.get(node) : $(node).attr('value') },
set value (value) { values.set(node,value) }, dispatchEvent () {}
})
const document = {querySelectorAll: selector => $(selector).toArray().map(wrap), querySelector: selector => {const n=$(selector)[0];return n ? wrap(n) : null}}
const run = (fn,arg) => vm.runInNewContext(`(${fn.toString()})(${arg === undefined ? '' : JSON.stringify(arg)})`, {document, Event:class {}})
return {document,run,clicked}
}
test('only explicit visible session evidence without login form confirms authentication', () => {
for (const [html,want] of [
['<main>Public page</main>','authentication_unconfirmed'],
['<a href="/account/logout">Account control</a>','authenticated'],
['<a hidden href="/account/logout">Hidden</a>','authentication_unconfirmed'],
['<a href="/account/logout">Account control</a><input type="password">','authentication_unconfirmed'],
['<a href="/account/logout">Account control</a><input type="email" name="newsletter">','authenticated'],
['<div id="px-captcha"></div>','challenge'],
['<input autocomplete="one-time-code">','two_factor_required'],
['<div data-testid="login-error"></div>','auth_rejected']
]) {const f=fixture(html);assert.equal(classifyLoginState(f.run(inspectLoginState)),want)}
assert.equal(authenticatedDestination('https://www.bloomberg.com/account/signin'),false)
assert.equal(authenticatedDestination('https://other.invalid/'),false)
assert.equal(authenticatedDestination('https://www.bloomberg.com/markets'),true)
})
test('submission targets the entered field form rather than another page form', () => {
const f=fixture('<form><button type="submit" id="unrelated">Other form</button></form><form><input id="entered"><button type="submit" id="correct">Submit</button></form>')
assert.equal(f.run(submitInputForm,'#entered'),true)
assert.deepEqual(f.clicked,['correct'])
assert.equal(f.run(submitInputForm,'#missing'),false)
})
test('visible input is cleared before typing and hidden fields cannot receive credentials', async () => {
const f=fixture('<form><input hidden id="hidden"><input id="entered" value="synthetic-prefill"></form>')
assert.equal(f.run(clearLoginInput,'#hidden'),false)
const typed=[]
const page={async waitForSelector(selector,options){assert.equal(options.visible,true)},async evaluate(fn,selector){return f.run(fn,selector)},async type(selector){assert.equal(f.document.querySelector(selector).value,'');typed.push(selector)}}
assert.equal(await typeVisibleInput(page,['#hidden','#entered'],'synthetic-test-input'),'#entered')
assert.deepEqual(typed,['#entered'])
})

View File

@ -27,8 +27,8 @@ async function runFixture ({ byparr = true, httpError = false, launchError = fal
const localRequire = createRequire(index)
const page = {
async setViewport () {}, async evaluateOnNewDocument () {},
async goto (url) { navigations.push(url) },
async evaluate () { return true }, async waitForSelector () {}, async type () {},
async goto (url) { navigations.push(url); return {status () {return 200}} },
async evaluate (fn) { return fn.name === 'inspectLoginState' ? {authenticated:true, loginForm:false} : true }, async waitForSelector () {}, async type () {},
async waitForFunction () {}, async waitForNavigation () {}, async $ () { return null },
keyboard: { async press () {} },
url () { return 'https://www.bloomberg.com/markets' },