AI ad writer: "Write my ad from my link" on the ad form (Marty 2026-11-17: "okay, let's do it.")

adwriter.js: the server reads the member's page (or follows their LinkSpin spin link, max 5 hops),
SSRF-safe (http/https, ports 80/443, every hop's DNS answer checked and the connection pinned to it,
no private/loopback/link-local/metadata address, 8 s, 1.5 MB, text/html only), extracts title, meta
and og description, h1-h3 and the first paragraphs (about 2,500 tokens), and asks OpenRouter
deepseek/deepseek-v4-flash (reasoning off; fallback anthropic/claude-haiku-5.5) for 3 options
{headline <= 60, line <= 90} written only from the page. Every option goes through the new
safety.checkAdCopy (no dashes, income promises, guarantees, links, shouting; every number must be
on the page) plus the length limits; failing ones are dropped, one retry when none survive. The
member picks one, it fills the form, nothing is posted.
Limits: AI_AD_DAILY (5) per member per Central day, AI_AD_GLOBAL_DAILY (500), 12 an hour per IP,
one at a time, a 24 h cache by page (a repeat is free). Off and hidden without AI_AD_KEY (a dedicated
OpenRouter key, $5 a month). Admin status: writes today, tokens, estimated spend.
safety.privateIp: IPv4-mapped IPv6 in hex form (::ffff:7f00:1) and all of fe80::/10 now count as private.
Chatbot fact added (KNOWLEDGE_DATE 2026-11-17). Server wiring + form markup landed in 828abce.
qa/adwriter.test.mjs 82/82, qa/e2e.mjs 63/63, qa/chatbot.test.mjs 108/108.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-17 07:12:12 -06:00
parent 828abce0fd
commit def20f8ffe
8 changed files with 574 additions and 5 deletions
+194
View File
@@ -0,0 +1,194 @@
// 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 = '<!doctype html><html><head><meta charset="utf-8"><title>Spin &amp; Win Links | LinkSpin</title>'
+ '<meta name="description" content="Rotate your links &mdash; free tracking for every click.">'
+ '<meta property="og:title" content="LinkSpin: one link, many pages"><meta property="og:description" content=\'Share one link that rotates your offers.\'>'
+ '<style>body{color:red} .secret{}</style><script>var SECRET_TOKEN="abc"; document.write("<p>injected paragraph text here</p>")</script></head>'
+ '<body><nav><p>Home About Pricing Contact Login Signup menu text</p></nav><h1>Rotate your links</h1><h2>Track every click</h2><h3>Free to start</h3><h4>skip h4</h4>'
+ '<p>LinkSpin lets you share one link that sends visitors to your pages in turn.</p><p>short</p><!-- <p>hidden comment paragraph text</p> -->'
+ '<ul><li>See which page brings sign-ups and which does not.</li></ul><noscript><p>Please turn on JavaScript to see this.</p></noscript>'
+ '<footer><p>Copyright 2026 all rights reserved footer text</p></footer></body></html>';
const x = aw.extract(html);
ok(x.title === 'Spin & Win Links | LinkSpin', 'title + entity', x.title);
ok(x.description === 'Rotate your links , free tracking for every click.' || /Rotate your links/.test(x.description), 'meta description', x.description);
ok(!/\u2014/.test(x.text), 'no em dash survives extraction');
ok(x.ogTitle === 'LinkSpin: one link, many pages' && x.ogDescription === 'Share one link that rotates your offers.', 'og tags', x);
ok(x.headings.join('|') === 'Rotate your links|Track every click|Free to start', 'h1 to h3 only', x.headings);
ok(x.paragraphs.length === 2 && /share one link/.test(x.paragraphs[0]) && /sign-ups/.test(x.paragraphs[1]), 'first paragraphs + list items, short ones skipped', x.paragraphs);
ok(!/SECRET_TOKEN|color:red|injected|hidden comment|JavaScript|footer text|menu text/.test(x.text), 'scripts, styles, comments, noscript, nav, footer stripped', x.text);
const big = '<title>Big</title>' + Array.from({ length: 400 }, (_, i) => '<p>Paragraph number ' + i + ' with plenty of words to fill the page up nicely for the cap test.</p>').join('');
const xb = aw.extract(big); ok(xb.text.length <= 10000, 'text capped near 2,500 tokens', xb.text.length);
ok(aw.extract('<html><body><img src=x></body></html>').words < 8, 'an empty page has no words');
}
// ---- URL rules + SSRF refusals (no test allowances yet)
aw._test({ allow: null, lookup: (h, o, cb) => {
const map = { 'evil.example.com': '10.1.2.3', 'meta.attacker.net': '169.254.169.254', 'v6loop.attacker.net': '::1', 'mixed.attacker.net': ['93.184.216.34', '192.168.1.5'], 'public.site.net': '93.184.216.34' };
const v = map[h]; if (!v) return cb(new Error('ENOTFOUND'));
const list = (Array.isArray(v) ? v : [v]).map(a => ({ address: a, family: a.includes(':') ? 6 : 4 }));
return o && o.all ? cb(null, list) : cb(null, list[0].address, list[0].family);
} });
for (const [u, code] of [
['http://127.0.0.1/', 'private'], ['http://127.1.2.3:80/x', 'private'], ['https://10.0.0.5/', 'private'], ['http://169.254.169.254/latest/meta-data/', 'private'],
['http://[::1]/', 'private'], ['http://[::ffff:127.0.0.1]/', 'private'], ['http://192.168.0.1/', 'private'], ['http://172.16.3.4/', 'private'], ['http://100.64.0.1/', 'private'],
['http://0.0.0.0/', 'private'], ['http://localhost/', 'private'], ['http://intranet.corp/', 'private'], ['http://evil.example.com/', 'private'],
['http://meta.attacker.net/', 'private'], ['http://v6loop.attacker.net/', 'private'], ['http://mixed.attacker.net/', 'private'],
['ftp://public.site.net/', 'bad_url'], ['file:///etc/passwd', 'bad_url'], ['https://user:pw@public.site.net/', 'bad_url'], ['https://public.site.net:8080/', 'bad_port'],
['not a url', 'bad_url'], ['http://nosuch.domain.zz/', 'dns']
]) { const r = await aw.fetchPage(u); ok(r.error === code, 'refused ' + u + ' (' + code + ')', r); }
ok(aw.checkUrl('https://public.site.net/page').ok, 'a public https address passes the URL rules');
// ---- local test pages (only this server's port may be read)
const big = Buffer.alloc(2 * 1024 * 1024, 'a');
const pages = http.createServer((q, r) => {
const u = q.url;
if (u === '/ok') { r.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); return r.end('<title>Garden Tools Shop</title><meta name="description" content="Hand tools for small gardens."><h1>Garden tools that last</h1><p>We sell hand tools for small gardens, shipped in 3 days.</p>'); }
if (u === '/gz') { r.writeHead(200, { 'Content-Type': 'text/html', 'Content-Encoding': 'gzip' }); return r.end(zlib.gzipSync('<title>Zipped page title</title><p>This page was sent compressed with gzip to the reader.</p>')); }
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('<title>Big page title here</title><p>' + 'word '.repeat(40) + '</p>'); r.write(big); return r.end(); }
if (u === '/slow') { r.writeHead(200, { 'Content-Type': 'text/html' }); r.write('<title>'); return; }
if (u === '/thin') { r.writeHead(200, { 'Content-Type': 'text/html' }); return r.end('<html><body></body></html>'); }
if (u === '/promo') { r.writeHead(200, { 'Content-Type': 'text/html' }); return r.end('<title>Promo page</title><p>A page about promotions and nothing in particular to say.</p>'); }
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);