// AI ad writer checks (2026-11-17): node qa/adwriter.test.mjs // No network: a stand-in OpenRouter and local test pages (the only loopback addresses the test lets the reader open). // Checks: page extraction, SSRF refusals (loopback, 10.x, the metadata address, IPv6 loopback, a DNS name answering a private // address, a redirect into any of them, odd ports, non-http), the 1.5 MB / text-html / redirect-count rules, the option filter // (lengths, dashes, promises, invented numbers), and the limits (per member per day, global, cache, one at a time), the fallback // model and the one retry. import http from 'node:http'; import zlib from 'node:zlib'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { createRequire } from 'node:module'; const require = createRequire(import.meta.url); const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'adw-')); process.env.AI_AD_KEY = 'test-key-not-real-123456'; process.env.AI_AD_DAILY = '5'; process.env.AI_AD_GLOBAL_DAILY = '500'; let pass = 0, fail = 0; const ok = (c, m, extra) => { if (c) { pass++; } else { fail++; console.log('FAIL', m, extra !== undefined ? JSON.stringify(extra).slice(0, 400) : ''); } }; const aw = require(path.join(ROOT, 'adwriter.js')); const safety = require(path.join(ROOT, 'safety.js')); // ---- extraction { const html = '
LinkSpin lets you share one link that sends visitors to your pages in turn.
short
' + 'Paragraph number ' + i + ' with plenty of words to fill the page up nicely for the cap test.
').join(''); const xb = aw.extract(big); ok(xb.text.length <= 10000, 'text capped near 2,500 tokens', xb.text.length); ok(aw.extract('We sell hand tools for small gardens, shipped in 3 days.
'); } if (u === '/gz') { r.writeHead(200, { 'Content-Type': 'text/html', 'Content-Encoding': 'gzip' }); return r.end(zlib.gzipSync('This page was sent compressed with gzip to the reader.
')); } if (u === '/to-meta') { r.writeHead(302, { Location: 'http://169.254.169.254/latest/meta-data/' }); return r.end(); } if (u === '/to-ten') { r.writeHead(301, { Location: 'http://10.0.0.1/' }); return r.end(); } if (u === '/to-evil') { r.writeHead(302, { Location: 'http://evil.example.com/x' }); return r.end(); } if (u === '/to-other-port') { r.writeHead(302, { Location: 'http://127.0.0.1:1/' }); return r.end(); } if (u === '/to-ok') { r.writeHead(302, { Location: '/ok' }); return r.end(); } const m = /^\/loop(\d+)$/.exec(u); if (m) { r.writeHead(302, { Location: '/loop' + (Number(m[1]) + 1) }); return r.end(); } if (u === '/pdf') { r.writeHead(200, { 'Content-Type': 'application/pdf' }); return r.end('%PDF'); } if (u === '/404') { r.writeHead(404, { 'Content-Type': 'text/html' }); return r.end('no'); } if (u === '/big') { r.writeHead(200, { 'Content-Type': 'text/html' }); r.write('' + 'word '.repeat(40) + '
'); r.write(big); return r.end(); } if (u === '/slow') { r.writeHead(200, { 'Content-Type': 'text/html' }); r.write('A page about promotions and nothing in particular to say.
'); } r.writeHead(404); r.end(); }); await new Promise(r => pages.listen(0, '127.0.0.1', r)); const PP = pages.address().port, PB = 'http://127.0.0.1:' + PP; aw._test({ allow: (ip, port) => ip === '127.0.0.1' && port === PP, timeout: 1500 }); { let r = await aw.fetchPage(PB + '/ok'); ok(r.ok && /Garden tools/.test(r.html), 'reads a page', r); r = await aw.fetchPage(PB + '/gz'); ok(r.ok && /Zipped page/.test(r.html), 'gzip page inflated', r); r = await aw.fetchPage(PB + '/to-ok'); ok(r.ok && r.url === PB + '/ok' && r.hops === 1, 'follows a redirect, reports where it landed', r); r = await aw.fetchPage(PB + '/to-meta'); ok(r.error === 'private', 'redirect to the metadata address refused', r); r = await aw.fetchPage(PB + '/to-ten'); ok(r.error === 'private', 'redirect to 10.x refused', r); r = await aw.fetchPage(PB + '/to-evil'); ok(r.error === 'private', 'redirect to a name answering a private address refused', r); r = await aw.fetchPage(PB + '/to-other-port'); ok(r.error === 'private', 'redirect to another loopback port refused', r); r = await aw.fetchPage(PB + '/loop0'); ok(r.error === 'hops', 'more than 5 redirects refused', r); r = await aw.fetchPage(PB + '/loop1'.replace('1', '1')); ok(r.error === 'hops', 'redirect loop refused', r); r = await aw.fetchPage(PB + '/pdf'); ok(r.error === 'not_html', 'non-html refused', r); r = await aw.fetchPage(PB + '/404'); ok(r.error === 'status', 'an error page refused', r); r = await aw.fetchPage(PB + '/big'); ok(r.ok && r.truncated && Buffer.byteLength(r.html) <= 1536 * 1024, 'read stops at 1.5 MB', { ok: r.ok, t: r.truncated, n: r.html && r.html.length }); const t0 = Date.now(); r = await aw.fetchPage(PB + '/slow'); ok(r.error === 'timeout' && Date.now() - t0 < 3000, 'a slow page times out', r); } // 5 hops are allowed, the 6th is not { const r5 = await aw.fetchPage(PB + '/loop0'); ok(r5.error === 'hops', 'loop'); } // ---- the option filter { const page = 'We sell hand tools for small gardens, shipped in 3 days. Prices from $12.'; const f = aw.filterOptions([ { headline: 'Garden tools that last', line: 'Hand tools for small gardens, shipped in 3 days.' }, { headline: 'Tools \u2014 for gardens', line: 'Hand tools for small gardens.' }, { headline: 'Garden tools -- shop now', line: 'Hand tools for small gardens.' }, { headline: 'x'.repeat(61), line: 'Hand tools for small gardens.' }, { headline: 'Small garden tools', line: 'y'.repeat(91) }, { headline: 'Tools from $12', line: 'Hand tools, ready in 3 days.' }, { headline: 'Tools from $9', line: 'Hand tools for small gardens.' }, { headline: 'Earn money gardening', line: 'Hand tools for small gardens.' }, { headline: 'Guaranteed results', line: 'Hand tools for small gardens.' }, { headline: 'Garden tools that last', line: 'A duplicate headline.' }, { headline: 'Visit our shop', line: 'See https://example.com today.' }, { headline: 'BEST TOOLS EVER MADE', line: 'Hand tools for small gardens.' }, { headline: '"Quiet garden hours"', line: 'Hand tools for small gardens!' } ], page); ok(f.options.length === 3, 'three options kept', f); ok(f.options[0].headline === 'Garden tools that last' && f.options[1].headline === 'Tools from $12' && f.options[2].headline === 'Quiet garden hours', 'the right three kept, outer quotes tidied', f.options); ok(f.dropped.includes('dash') && f.dropped.includes('number') && f.dropped.includes('promise') && f.dropped.includes('duplicate') && f.dropped.includes('link') && f.dropped.includes('shouting'), 'drop reasons', f.dropped); ok(f.dropped.filter(x => /length/.test(x)).length === 2, 'length limits 60 / 90', f.dropped); ok(safety.checkAdCopy('Make $500 a day from home', 'make 500').error === 'promise', 'income promise refused'); ok(safety.checkAdCopy('Passive income on autopilot').error === 'promise', 'passive income refused'); ok(safety.checkAdCopy('Track your earnings in one place').ok, 'plain mention of earnings allowed'); ok(safety.checkAdCopy('Join 1,200 members', 'over 1200 members').ok, 'a number on the page is allowed (1,200 = 1200)'); ok(safety.checkAdCopy('Join 1,500 members', 'over 1200 members').error === 'number', 'a number not on the page is refused'); ok(aw.parseOptions('```json\n{"options":[{"headline":"A b c","line":"D e f"}]}\n```').length === 1, 'parses fenced JSON'); ok(aw.parseOptions('Sure! [{"headline":"A b c","line":"D e f"}]').length === 1, 'parses a bare array'); ok(aw.parseOptions('nothing here').length === 0, 'unparseable -> none'); } // ---- stand-in OpenRouter + the limits let calls = [], mode = 'good'; const GOOD = JSON.stringify({ options: [ { headline: 'Garden tools that last', line: 'Hand tools for small gardens, shipped in 3 days.' }, { headline: 'Tools for small gardens', line: 'Pick the hand tools your garden needs.' }, { headline: 'Shop garden hand tools', line: 'Simple tools for small gardens.' }] }); const BAD = JSON.stringify({ options: [{ headline: 'Earn money \u2014 now', line: 'Guaranteed $999 a day.' }] }); const or = http.createServer((q, r) => { let b = ''; q.on('data', c => { b += c; }); q.on('end', () => { const j = JSON.parse(b); calls.push(j); r.setHeader('Content-Type', 'application/json'); if (mode === 'down' || (mode === 'fallback' && j.model === 'deepseek/deepseek-v4-flash')) { r.statusCode = 502; return r.end(JSON.stringify({ error: { message: 'upstream down' } })); } if (mode === 'empty' && j.model === 'deepseek/deepseek-v4-flash') return r.end(JSON.stringify({ choices: [{ message: { content: '' } }] })); const txt = mode === 'retry' && calls.length === 1 ? BAD : mode === 'allbad' ? BAD : GOOD; r.end('\n\n' + JSON.stringify({ model: j.model, choices: [{ message: { content: txt } }], usage: { prompt_tokens: 400, completion_tokens: 90, cost: 0.0002 } })); }); }); await new Promise(r => or.listen(0, '127.0.0.1', r)); process.env.AI_AD_URL = 'http://127.0.0.1:' + or.address().port + '/api/v1/chat/completions'; let day = '2026-11-17'; const S = {}; aw.init({ store: { state: () => S, ctDay: () => day, save: () => {} }, ad: { headline: 60, line: 90 } }); { const M = '0x' + 'a'.repeat(40), M2 = '0x' + 'b'.repeat(40); let r = await aw.write(M, PB + '/ok'); ok(r.ok && r.options.length === 3 && !r.cached && r.left === 4, 'first write: 3 options, 4 left', r); ok(calls.length === 1 && calls[0].reasoning && calls[0].reasoning.enabled === false && calls[0].model === 'deepseek/deepseek-v4-flash', 'deepseek with reasoning off', calls[0] && { m: calls[0].model, r: calls[0].reasoning }); ok(/hand tools for small gardens/i.test(calls[0].messages[1].content) && /never invent/i.test(calls[0].messages[0].content) && /em dash/i.test(calls[0].messages[0].content), 'prompt carries the page and the rules'); r = await aw.write(M, PB + '/ok'); ok(r.ok && r.cached && calls.length === 1 && r.left === 4, 'same page again: cached, free, no daily write used', r); r = await aw.write(M2, PB + '/to-ok'); ok(r.ok && r.cached && calls.length === 1, 'a link landing on a cached page is free too', r); aw._reset(); calls = []; for (let i = 0; i < 4; i++) { aw._reset(); r = await aw.write(M, PB + '/ok'); } ok(r.ok && r.left === 0, 'five writes used', r); aw._reset(); r = await aw.write(M, PB + '/ok'); ok(r.code === 'member_limit' && r.status === 429 && /midnight Central/.test(r.error), 'sixth write refused with a friendly message', r); r = await aw.write(M2, PB + '/ok'); ok(r.ok, 'another member still has writes (cache was cleared so it calls the model)', r); day = '2026-11-18'; aw._reset(); r = await aw.write(M, PB + '/ok'); ok(r.ok && r.left === 4, 'a new Central day resets the member', r); ok(Array.isArray(S.aiAdDays) && S.aiAdDays[0].day === '2026-11-17' && S.aiAdDays[0].n === 6, 'yesterday kept in the 30-day history', S.aiAdDays); process.env.AI_AD_GLOBAL_DAILY = '1'; aw._reset(); r = await aw.write(M2, PB + '/ok'); ok(r.code === 'global_limit', 'global daily cap', r); process.env.AI_AD_GLOBAL_DAILY = '500'; aw._reset(); mode = 'fallback'; calls = []; r = await aw.write(M2, PB + '/ok'); ok(r.ok && calls.length === 2 && calls[1].model === 'anthropic/claude-haiku-5.5', 'fallback model on an error', calls.map(c => c.model)); aw._reset(); mode = 'empty'; calls = []; r = await aw.write(M2, PB + '/ok'); ok(r.ok && calls[1].model === 'anthropic/claude-haiku-5.5', 'fallback on an empty answer'); aw._reset(); mode = 'retry'; calls = []; r = await aw.write(M2, PB + '/ok'); ok(r.ok && calls.length === 2 && /broke the rules/.test(calls[1].messages[1].content), 'none survive -> asked once more', calls.length); aw._reset(); mode = 'allbad'; calls = []; r = await aw.write(M2, PB + '/ok'); ok(r.code === 'none' && calls.length === 2, 'still none after the retry -> a clear message, no third call', r); aw._reset(); mode = 'down'; r = await aw.write(M2, PB + '/ok'); ok(r.code === 'ai' && /busy/.test(r.error), 'both models down -> friendly message', r); mode = 'good'; const M3 = '0x' + 'c'.repeat(40); aw._reset(); r = await aw.write(M3, PB + '/thin'); ok(r.code === 'empty' && /enough words/.test(r.error), 'a page with no words: clear message', r); r = await aw.write(M3, PB + '/pdf'); ok(r.code === 'not_html' && /not a web page/.test(r.error), 'a file: clear message', r); r = await aw.write(M3, 'http://169.254.169.254/'); ok(r.code === 'private' && r.status === 400, 'metadata address refused before anything else', r); ok(aw.usedBy(M3) === 0, 'failed page reads use no daily write'); // one at a time per member aw._reset(); const [a1, a2] = await Promise.all([aw.write(M3, PB + '/promo'), aw.write(M3, PB + '/promo')]); ok((a1.ok && a2.code === 'busy') || (a2.ok && a1.code === 'busy'), 'one write at a time per member', [a1.code, a2.code]); const v = aw.view(); ok(v.on && v.writes > 0 && v.costUsd > 0 && v.tokensIn > 0, 'admin view: writes, tokens, spend', v); delete process.env.AI_AD_KEY; ok(!aw.enabled(), 'no key -> off'); r = await aw.write(M3, PB + '/ok'); ok(r.code === 'off', 'off cleanly without a key', r); } pages.close(); or.close(); console.log(pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0);