Files
seo-agent/test/canonical.test.ts
Alan WizemannandClaude Fable 5 e42b103626 feat: og_image as the fifth override field — a chosen value on the manual lane (v1.23.0)
missing_og_image gets its fix path: an og_image override the injector serves
as BOTH og:image and twitter:image, rewrite-or-insert per tag with
independent presence flags. Unlike canonical there is no computable answer —
the value is CHOSEN (a host UI offers the site's own images) and rides
createProposal, never the drafting queue: fieldForRule stays null for the
rule, draftAndCreate refuses the field outright, and a model can never
invent an image URL.

invalidOgImageReason is the one gate (createProposal, applyOverride
fail-closed, and the injector belt) — the canonical validator's sibling
that deliberately allows query strings (CDN sizing params) and foreign
http(s) hosts. createProposal gains an optional findingId so a host-created
proposal carries the same remediation chip linkage as a drafted one.
verify.ts checks stored og_image against the crawl.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 21:08:09 -04:00

363 lines
17 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import worker from '../injector/src/index';
import { invalidCanonicalReason, storedOverrideValue, applyOverride, OVERRIDE_FIELDS } from '../src/overrides';
import { expectedCanonicalUrl } from '../src/rules';
import { fieldForRule, draftAndCreate, CANONICAL_RULES, currentValueFor } from '../src/propose';
import { createProposal } from '../src/actions';
import { verifyOverrides } from '../src/verify';
import { resolveSiteConfig } from '../src/config';
// The canonical lane, end to end at the unit level: the validator that gates
// every path to KV, the deterministic drafter (no model call, ever), the
// verify sense, and the injector's rewrite-or-insert behaviour.
const config = resolveSiteConfig({ SITE_URL: 'https://example.com', SITE_NAME: 'Acme' });
// ---------------------------------------------------------------------------
// invalidCanonicalReason — the one gate (storedOverrideValue and the drafter
// both run it, and the injector's serve-time belt enforces the same character
// rules).
// ---------------------------------------------------------------------------
describe('invalidCanonicalReason', () => {
it('accepts a clean absolute https URL, and a bare-origin homepage form', () => {
expect(invalidCanonicalReason('https://example.com/pricing')).toBeNull();
expect(invalidCanonicalReason('https://example.com')).toBeNull();
expect(invalidCanonicalReason('http://example.com/a')).toBeNull();
});
it('rejects the shapes that are not a page name', () => {
expect(invalidCanonicalReason('')).toMatch(/empty/);
expect(invalidCanonicalReason('/pricing')).toMatch(/absolute/);
expect(invalidCanonicalReason('javascript:alert(1)')).toMatch(/http/);
expect(invalidCanonicalReason('https://example.com/a?utm=1')).toMatch(/query/);
expect(invalidCanonicalReason('https://example.com/a#frag')).toMatch(/fragment/);
});
it('rejects every character that could escape an href attribute', () => {
for (const bad of ['https://example.com/a b', 'https://example.com/a"', "https://example.com/a'", 'https://example.com/<a', 'https://example.com/a\\b', 'https://example.com/ab']) {
expect(invalidCanonicalReason(bad), bad).not.toBeNull();
}
});
it('rejects a URL past the length bound', () => {
expect(invalidCanonicalReason(`https://example.com/${'a'.repeat(2100)}`)).toMatch(/too long/);
});
});
// ---------------------------------------------------------------------------
// expectedCanonicalUrl — shared by the rule and the drafter, so the fix can
// never disagree with the check that raised the finding.
// ---------------------------------------------------------------------------
describe('expectedCanonicalUrl', () => {
it('is origin + path, and the bare origin for the homepage', () => {
expect(expectedCanonicalUrl('https://example.com', '/pricing')).toBe('https://example.com/pricing');
expect(expectedCanonicalUrl('https://example.com', '/')).toBe('https://example.com');
});
it('percent-encodes attribute-hostile path characters, so the result always validates', () => {
expect(expectedCanonicalUrl('https://example.com', "/don't-panic")).toBe('https://example.com/don%27t-panic');
expect(invalidCanonicalReason(expectedCanonicalUrl('https://example.com', "/a b\"c'd"))).toBeNull();
});
});
// ---------------------------------------------------------------------------
// Field plumbing.
// ---------------------------------------------------------------------------
describe('canonical as an override field', () => {
it('both canonical rules map to the canonical field', () => {
expect(OVERRIDE_FIELDS.has('canonical')).toBe(true);
for (const rule of CANONICAL_RULES) expect(fieldForRule(rule)).toBe('canonical');
});
it('currentValueFor reads the snapshot canonical (null when the page has none)', () => {
expect(currentValueFor('canonical', { title: 't', description: 'd', canonical: 'https://example.com/x' })).toBe('https://example.com/x');
expect(currentValueFor('canonical', { title: 't', description: 'd' })).toBeNull();
});
it('storedOverrideValue stores a valid canonical verbatim — no title suffix — and throws on an invalid one', () => {
expect(storedOverrideValue('canonical', 'https://example.com/a', ' — Acme')).toBe('https://example.com/a');
expect(() => storedOverrideValue('canonical', 'not a url', undefined)).toThrow(/invalid canonical/);
});
});
// ---------------------------------------------------------------------------
// The deterministic drafter. Modeled on the jsonld draft tests' fakes, but the
// ai port THROWS on use: a canonical draft that reaches the model is the bug
// these tests exist to forbid.
// ---------------------------------------------------------------------------
type Row = Record<string, unknown>;
function drafterDeps() {
const proposals: Row[] = [];
const changes: Row[] = [];
const store = new Map<string, string>();
const db = {
prepare: (sql: string) => ({
bind: (...b: unknown[]) => ({
first: async () => {
if (/INSERT INTO proposals/.test(sql)) {
// The drafting lane binds 8 values (finding_id + model); the manual
// lane (createProposal) binds 6 with 'manual' inline.
const drafted = b.length === 8;
const row = drafted
? { id: proposals.length + 1, path: b[2], field: b[3], current_value: b[4], proposed_value: b[5], rationale: b[6], model: b[7], status: 'proposed' }
: { id: proposals.length + 1, path: b[2], field: b[3], current_value: b[4], proposed_value: b[5], rationale: b[6], model: 'manual', status: 'proposed' };
proposals.push(row);
return row;
}
if (/SELECT 1 FROM proposals/.test(sql)) {
return proposals.find((p) => p.path === b[0] && p.field === b[1] && p.status === 'proposed') ?? null;
}
if (/INSERT INTO changes/.test(sql)) {
const row = { id: changes.length + 1 };
changes.push(row);
return row;
}
if (/SELECT title, description\b.* FROM page_snapshots/.test(sql)) {
return { title: 'Pricing', description: 'd', canonical: 'https://old.example.com/pricing', og_image: null };
}
throw new Error(`unhandled: ${sql}`);
},
run: async () => ({}),
}),
}),
};
const overrides = {
get: async (k: string) => store.get(k) ?? null,
put: async (k: string, v: string) => void store.set(k, v),
delete: async (k: string) => void store.delete(k),
};
const ai = { run: () => { throw new Error('the canonical lane must never call the model'); } };
return { proposals, changes, store, deps: { db, overrides, ai, config } as any };
}
describe('draftAndCreate — canonical is deterministic only', () => {
const job = (over: Record<string, unknown> = {}) => ({
findingId: 7,
path: '/pricing',
rule: 'missing_canonical',
field: 'canonical' as const,
title: 'Pricing',
description: null,
current: null,
...over,
});
it('creates a proposal with the computed URL and model=deterministic, without touching the ai port', async () => {
const d = drafterDeps();
const result = await draftAndCreate(d.deps, job());
expect(result).toMatchObject({ created: true, field: 'canonical', value: 'https://example.com/pricing' });
expect(d.proposals[0]).toMatchObject({ proposed_value: 'https://example.com/pricing', model: 'deterministic' });
});
it('the homepage drafts the bare origin', async () => {
const d = drafterDeps();
const result = await draftAndCreate(d.deps, job({ path: '/' }));
expect(result).toMatchObject({ created: true, value: 'https://example.com' });
});
it('canonical_mismatch carries the delivered URL as current_value', async () => {
const d = drafterDeps();
await draftAndCreate(d.deps, job({ rule: 'canonical_mismatch', current: 'https://old.example.com/pricing' }));
expect(d.proposals[0]).toMatchObject({ current_value: 'https://old.example.com/pricing' });
});
it('a path with an attribute-hostile character drafts its percent-encoded spelling', async () => {
const d = drafterDeps();
const result = await draftAndCreate(d.deps, job({ path: '/a b' }));
expect(result).toMatchObject({ created: true, value: 'https://example.com/a%20b' });
});
it('drops the job when the computed URL cannot validate, instead of guessing', async () => {
const d = drafterDeps();
const result = await draftAndCreate(d.deps, job({ path: '/a\u0000b' }));
expect(result).toEqual({ created: false, field: 'canonical' });
expect(d.proposals).toHaveLength(0);
});
it('skips when a canonical proposal for the path is already live', async () => {
const d = drafterDeps();
await draftAndCreate(d.deps, job());
const again = await draftAndCreate(d.deps, job());
expect(again).toEqual({ created: false, field: 'canonical' });
expect(d.proposals).toHaveLength(1);
});
});
// ---------------------------------------------------------------------------
// createProposal — a hand-written canonical clears the SAME gate as the
// drafted one, not the title validator it used to fall through to.
// ---------------------------------------------------------------------------
describe('createProposal — canonical', () => {
it('accepts a valid canonical longer than a title could ever be, and records the delivered one as current', async () => {
const d = drafterDeps();
const long = `https://example.com/blog/2026/${'a'.repeat(70)}`;
expect(long.length).toBeGreaterThan(80); // past the title validator's cap
const r = await createProposal(d.deps, { path: '/pricing', field: 'canonical', value: long }, () => null);
expect(r.ok).toBe(true);
expect(d.proposals[0]).toMatchObject({ current_value: 'https://old.example.com/pricing' });
});
it('rejects an invalid canonical at creation with the canonical validator, not the title one', async () => {
await expect(
createProposal(drafterDeps().deps, { path: '/a', field: 'canonical', value: 'https://example.com/a?utm=1' }, () => null)
).rejects.toThrow(/invalid canonical: .*query/);
});
});
// ---------------------------------------------------------------------------
// applyOverride keeps its fail-closed edge for canonical.
// ---------------------------------------------------------------------------
describe('applyOverride — canonical', () => {
it('stores a valid canonical and journals the change', async () => {
const d = drafterDeps();
await applyOverride(d.deps, { path: '/a', field: 'canonical', value: 'https://example.com/a', oldValue: null, source: 'proposal' });
expect(JSON.parse(d.store.get('override:/a')!)).toEqual({ canonical: 'https://example.com/a' });
expect(d.changes).toHaveLength(1);
});
it('refuses an invalid canonical at the KV edge, whatever upstream believed', async () => {
const d = drafterDeps();
await expect(
applyOverride(d.deps, { path: '/a', field: 'canonical', value: 'https://example.com/a?utm=1', oldValue: null, source: 'proposal' })
).rejects.toThrow(/invalid canonical/);
expect(d.store.size).toBe(0);
});
});
// ---------------------------------------------------------------------------
// verify — a stored canonical the crawl can't see is an injection_regression.
// ---------------------------------------------------------------------------
describe('verifyOverrides — canonical', () => {
const snap = (canonical: string | null) =>
[{ path: '/a', status: 200, title: 't', description: 'd', canonical } as any];
it('silent when the delivered canonical matches the stored one', () => {
expect(verifyOverrides([{ path: '/a', canonical: 'https://example.com/a' }], snap('https://example.com/a'))).toEqual([]);
});
it('flags a mismatch, and a page delivering nothing', () => {
const out = verifyOverrides([{ path: '/a', canonical: 'https://example.com/a' }], snap(null));
expect(out).toHaveLength(1);
expect(out[0]).toMatchObject({ rule: 'injection_regression', severity: 'critical' });
expect(out[0].detail).toContain('canonical');
});
});
// ---------------------------------------------------------------------------
// The injector. Same model-of-the-platform stand-in as the jsonld tests, plus
// the two behaviours new to this lane: link[rel=canonical] attribute rewrite,
// and head onEndTag insertion when no such link exists.
// ---------------------------------------------------------------------------
function stubHtmlRewriter() {
class FakeRewriter {
private handlers: [string, any][] = [];
on(selector: string, handlers: any) {
this.handlers.push([selector, handlers]);
return this;
}
transform(res: Response): Response {
const self = this;
const rewritten = (async () => {
let html = await res.text();
const endTagCallbacks: Array<(end: { before(c: string, o: { html: boolean }) : void }) => void> = [];
for (const [selector, h] of self.handlers) {
if (!h.element) continue;
if (selector === 'head') {
h.element({
append: (content: string) => {
html = html.replace('</head>', `${content}</head>`);
},
onEndTag: (cb: (end: { before(c: string, o: { html: boolean }): void }) => void) => {
endTagCallbacks.push(cb);
},
});
} else if (selector === 'link[rel="canonical"]') {
const tagRe = /<link\b[^>]*rel="canonical"[^>]*>/g;
for (const tag of html.match(tagRe) ?? []) {
h.element({
setAttribute: (n: string, v: string) => {
html = html.replace(tag, tag.replace(new RegExp(`${n}="[^"]*"`), `${n}="${v}"`));
},
});
}
} else if (selector === 'head > title') {
h.element({
setInnerContent: (v: string) => {
html = html.replace(/(<title>)[\s\S]*?(<\/title>)/, `$1${v}$2`);
},
});
}
}
// Real HTMLRewriter fires head's end-tag callback after every child of
// head has streamed past — so after any link[rel=canonical] handler.
for (const cb of endTagCallbacks) {
cb({ before: (content: string) => { html = html.replace('</head>', `${content}</head>`); } });
}
return html;
})();
return new Response(
new ReadableStream({
async start(controller) {
controller.enqueue(new TextEncoder().encode(await rewritten));
controller.close();
},
}),
{ status: res.status, statusText: res.statusText, headers: res.headers }
);
}
}
vi.stubGlobal('HTMLRewriter', FakeRewriter);
}
const WITH_CANONICAL = '<html><head><title>Origin</title><link rel="canonical" href="https://old.example.com/x"></head><body></body></html>';
const WITHOUT_CANONICAL = '<html><head><title>Origin</title><meta name="description" content="d"></head><body></body></html>';
async function serveInjector(html: string, override: Record<string, string>) {
vi.stubGlobal('fetch', vi.fn(async () => new Response(html, { status: 200, headers: { 'content-type': 'text/html' } })));
stubHtmlRewriter();
const kv = { get: vi.fn(async (key: string) => (key === 'override:/x' ? JSON.stringify(override) : null)) };
const ctx = { waitUntil: vi.fn(), passThroughOnException: vi.fn() } as unknown as ExecutionContext;
const env = { ORIGIN_HOST: 'origin.example.com', SEO_OVERRIDES: kv } as unknown as Env;
const res = await worker.fetch(new Request('https://example.com/x'), env, ctx);
return await res.text();
}
describe('injector — canonical', () => {
beforeEach(() => stubHtmlRewriter());
afterEach(() => vi.unstubAllGlobals());
it('rewrites the href of an existing canonical link and does not add a second one', async () => {
const body = await serveInjector(WITH_CANONICAL, { canonical: 'https://example.com/x' });
expect(body).toContain('href="https://example.com/x"');
expect(body.match(/rel="canonical"/g)).toHaveLength(1);
});
it('inserts a canonical link into head when the page has none', async () => {
const body = await serveInjector(WITHOUT_CANONICAL, { canonical: 'https://example.com/x' });
expect(body).toContain('<link rel="canonical" href="https://example.com/x">');
const link = body.indexOf('rel="canonical"');
expect(link).toBeGreaterThan(body.indexOf('<head>'));
expect(link).toBeLessThan(body.indexOf('</head>'));
});
it('serves nothing rather than an attribute-breaking value (serve-time belt)', async () => {
const body = await serveInjector(WITHOUT_CANONICAL, { canonical: 'https://example.com/x" onload="x' });
expect(body).not.toContain('rel="canonical"');
});
it('the belt also refuses a non-http scheme and a query-carrying URL', async () => {
for (const hostile of ['javascript:alert(1)', 'https://example.com/x?utm=1', 'https://example.com/x#f']) {
const body = await serveInjector(WITHOUT_CANONICAL, { canonical: hostile });
expect(body, hostile).not.toContain('rel="canonical"');
}
});
});