/** * The rename to IAPL (1.17.0, docs/dev/rename-iapl-plan.md): every name a site used before it keeps * working. One place proves it — the other tests use the new names. * * 1. the ten exported names are the same values under both spellings; * 2. the plugin's env variables are read as IAPL_* and as IPAL_*; * 3. the doctor reads ipal-doctor.json, the old pointer block and ipal-audit-skip, and lists what is old * (legacy-names) without calling it a defect; * 4. the skills installer replaces the 16 old folders by name and leaves a project's own ipal-* skill; * 5. the old commands are still installed; * 6. the two stored names (visitor cookie, 2FA counter key) stay as they were unless a site says `storageNames: 'iapl'`. */ import { spawnSync } from 'node:child_process' import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import path from 'node:path' import { afterEach, describe, expect, test } from 'vitest' import type { CookieScanContext } from '../src/modules/consent/scanner/types.js' import * as envEntry from '../src/exports/env.js' import * as tokensEntry from '../src/exports/tokens.js' import * as root from '../src/index.js' import { declarationsOf, DEFAULT_COOKIE_INTEGRATIONS } from '../src/modules/consent/scanner/integrations.js' import { DEFAULT_COOKIE_MAP } from '../src/modules/consent/useConsent.js' import { readAuditSkips } from '../src/modules/doctor/project.js' import { POINTER_BLOCK } from '../src/modules/doctor/rules/agents.js' import { LEGACY_COMMANDS, LEGACY_EXPORTS, LEGACY_SKILL_NAMES, PLUGIN_ENV_NAMES } from '../src/modules/doctor/rules/legacy.js' import { runDoctor } from '../src/modules/doctor/run.js' import { assertEnv } from '../src/modules/env/assertEnv.js' import { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from '../src/modules/security/totp/verifyLimit.js' import { isSiteNoindex } from '../src/modules/seo/siteNoindex.js' import { legacyEnvName, readEnv } from '../src/modules/shared/envName.js' import { IAPL_VISITOR_COOKIE, VISITOR_COOKIE, visitorCookieFor } from '../src/modules/stats/visitorCookie.js' const packageRoot = path.resolve(import.meta.dirname, '..') const pkg = JSON.parse(readFileSync(path.join(packageRoot, 'package.json'), 'utf8')) as { bin: Record; name: string } let dirs: string[] = [] const saved = { ...process.env } function project(files: Record): string { const dir = mkdtempSync(path.join(tmpdir(), 'iapl-legacy-')) dirs.push(dir) for (const [rel, content] of Object.entries(files)) { const file = path.join(dir, rel) mkdirSync(path.dirname(file), { recursive: true }) writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content, null, 2)) } return dir } afterEach(() => { for (const d of dirs) {rmSync(d, { force: true, recursive: true })} dirs = [] for (const key of Object.keys(process.env)) {if (!(key in saved)) {delete process.env[key]}} Object.assign(process.env, saved) clearVerifyLimits() }) describe('exported names', () => { test('every old name is the same value as the new one', () => { const values = root as unknown as Record // types have no runtime value: only the names that exist at runtime are compared here const runtime = Object.entries(LEGACY_EXPORTS).filter(([, name]) => name in values) expect(runtime.map(([old]) => old).sort()).toEqual(['IPAL_BREAKPOINTS', 'IPAL_TOKENS', 'ipalEnvRules', 'ipalKit', 'ipalT', 'ipalVar']) for (const [old, name] of runtime) {expect(values[old], `${old} → ${name}`).toBe(values[name])} }) test('the env and tokens entries carry both spellings too', () => { expect(envEntry.ipalEnvRules).toBe(envEntry.iaplEnvRules) expect(tokensEntry.IPAL_TOKENS).toBe(tokensEntry.IAPL_TOKENS) expect(tokensEntry.IPAL_BREAKPOINTS).toBe(tokensEntry.IAPL_BREAKPOINTS) expect(tokensEntry.ipalVar).toBe(tokensEntry.iaplVar) }) test('the old type names still compile', () => { const options: root.IpalOptions = {} as root.IaplOptions const slug: root.IpalGlobalSlug = 'site-settings' const token: root.IpalTokenName = 'primary' const features: root.IpalEnvFeatures = { storage: true } expect([typeof options, slug, token, features.storage]).toEqual(['object', 'site-settings', 'primary', true]) }) test('the package name, the token prefix and the routes did not change', () => { expect(pkg.name).toBe('@intecion/ipal-kit') expect(root.iaplVar('primary')).toBe('var(--ipal-primary)') }) }) describe('env variables', () => { test('the new spelling is read first, the old one when the new one is missing or empty', () => { expect(legacyEnvName('IAPL_IP_HEADER')).toBe('IPAL_IP_HEADER') expect(legacyEnvName('DATABASE_URI')).toBeUndefined() expect(readEnv('IAPL_IP_HEADER', { IPAL_IP_HEADER: 'x-real-ip' })).toBe('x-real-ip') expect(readEnv('IAPL_IP_HEADER', { IAPL_IP_HEADER: 'cf-connecting-ip', IPAL_IP_HEADER: 'x-real-ip' })).toBe('cf-connecting-ip') expect(readEnv('IAPL_IP_HEADER', { IAPL_IP_HEADER: ' ', IPAL_IP_HEADER: 'x-real-ip' })).toBe('x-real-ip') expect(readEnv('IAPL_IP_HEADER', {})).toBeUndefined() // a variable that is not the plugin's has no second spelling expect(readEnv('DATABASE_URI', { IPAL_DATABASE_URI: 'x' })).toBeUndefined() }) test('IPAL_NOINDEX still makes the site noindex', () => { delete process.env.IAPL_NOINDEX process.env.IPAL_NOINDEX = '1' expect(isSiteNoindex()).toBe(true) process.env.IAPL_NOINDEX = '0' expect(isSiteNoindex()).toBe(false) // both set: the new one decides }) test('assertEnv(iaplEnvRules()) is satisfied by the old names, and checks their values', () => { const rules = envEntry.iaplEnvRules({ cookieCrawl: true, ipHeader: true }).filter((r) => r.name.startsWith('IAPL_')) expect(rules.map((r) => r.name).sort()).toEqual(['IAPL_COOKIE_SCAN_TOKEN', 'IAPL_COOKIE_SCAN_URL', 'IAPL_IP_HEADER']) const required = rules.map((r) => ({ ...r, required: true })) const old = { IPAL_COOKIE_SCAN_TOKEN: '0123456789abcdef', IPAL_COOKIE_SCAN_URL: 'https://crawler.example.com', IPAL_IP_HEADER: 'cf-connecting-ip' } expect(() => assertEnv(required, { env: old })).not.toThrow() expect(() => assertEnv(required, { env: {} })).toThrow(/IAPL_IP_HEADER is required/) expect(() => assertEnv(required, { env: { ...old, IPAL_COOKIE_SCAN_TOKEN: 'short' } })).toThrow(/IAPL_COOKIE_SCAN_TOKEN must be at least 16/) }) test('every runtime variable the doctor knows has an IPAL_ twin', () => { for (const name of PLUGIN_ENV_NAMES) {expect(legacyEnvName(name)).toBe(name.replace('IAPL_', 'IPAL_'))} }) }) describe('the doctor on a project that was not touched', () => { const OLD_POINTER = '\n## ipal-kit 1.16.7 — agent guide\n\ntext\n' const NEW_POINTER = '\n## IAPL 1.17.0 — agent guide\n\ntext\n' const site = (extra: Record = {}) => project({ 'node_modules/@intecion/ipal-kit/package.json': { name: '@intecion/ipal-kit', version: '1.16.7' }, 'package.json': { name: 'examplepl-web', dependencies: { '@intecion/ipal-kit': '1.16.7' }, scripts: { 'ipal:skills': 'ipal-skills', tokens: 'ipal-tokens' } }, ...extra, }) const run = (dir: string, only: string[]) => runDoctor({ offline: true, only, packageRoot, root: dir, today: '2026-11-25', writeSeen: false }) test('both pointer blocks are recognised, with their version', () => { expect(OLD_POINTER.match(POINTER_BLOCK)?.[1]).toBe('1.16.7') expect(NEW_POINTER.match(POINTER_BLOCK)?.[1]).toBe('1.17.0') }) test('ipal-audit-skip and iapl-audit-skip lines are both read', () => { const skips = readAuditSkips('- ipal-audit-skip: a11y — old reason\n- iapl-audit-skip: tokens — new reason\n') expect([...skips]).toEqual([['a11y', 'old reason'], ['tokens', 'new reason']]) }) test('ipal-doctor.json is read when it is the only one; a setting in it silences a rule', async () => { const dir = site({ 'ipal-doctor.json': { rules: { 'legacy-names': { off: true, reason: 'we move with 2.0' } } } }) const report = await run(dir, ['legacy-names']) expect(report.findings.filter((f) => f.rule === 'legacy-names' && !f.silenced)).toEqual([]) expect(report.findings.some((f) => f.rule === 'legacy-names' && f.silenced)).toBe(true) }) test('a broken ipal-doctor.json is reported under its own name', async () => { const dir = site({ 'ipal-doctor.json': '{ not json' }) const report = await run(dir, ['legacy-names']) expect(report.findings.find((f) => f.rule === 'doctor-config')?.message).toMatch(/^ipal-doctor\.json is not valid JSON/) }) test('legacy-names lists the old names as information, never as an error', async () => { const dir = site({ '.agents/skills/ipal-setup/SKILL.md': '# setup', '.agents/skills/ipal-upgrade/SKILL.md': '# upgrade', '.env.example': 'IPAL_IP_HEADER=cf-connecting-ip\nIPAL_NOINDEX=\n', 'AGENTS.md': `# AGENTS\n\n- ipal-audit-skip: a11y — reason\n\n${OLD_POINTER}\n`, 'ipal-doctor.json': { domain: 'example.pl' }, 'src/instrumentation.ts': "import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env'\nexport function register() { assertEnv(ipalEnvRules({ ipHeader: true })) }\n", 'src/payload.config.ts': "import { ipalKit } from '@intecion/ipal-kit'\nexport default { plugins: [ipalKit({})] }\n", }) const found = (await run(dir, ['legacy-names'])).findings.filter((f) => f.rule === 'legacy-names') expect(found.every((f) => f.severity === 'info')).toBe(true) const text = found.map((f) => `${f.message} | ${f.fix}`).join('\n') for (const part of ['ipal-doctor.json', 'ipalKit → iapl', 'ipalEnvRules → iaplEnvRules', 'ipal-skills → iapl-skills', 'ipal-tokens → iapl-tokens', 'IPAL_IP_HEADER → IAPL_IP_HEADER', 'pointer block', 'iapl-audit-skip', '2 skill folder(s)']) { expect(text, part).toContain(part) } }) test('a project on the new names has no legacy-names finding', async () => { const dir = project({ '.agents/skills/iapl-setup/SKILL.md': '# setup', '.env.example': 'IAPL_IP_HEADER=cf-connecting-ip\n', 'AGENTS.md': `# AGENTS\n\n${NEW_POINTER}\n`, 'iapl-doctor.json': { domain: 'example.pl' }, 'package.json': { name: 'examplepl-web', scripts: { 'iapl:skills': 'iapl-skills', tokens: 'iapl-tokens' } }, 'src/payload.config.ts': "import { iapl } from '@intecion/ipal-kit'\nexport default { plugins: [iapl({})] }\n", }) expect((await run(dir, ['legacy-names'])).findings.filter((f) => f.rule === 'legacy-names')).toEqual([]) }) test('two doctor files, or one variable under both spellings with different values, is a warning', async () => { const dir = site({ '.env.example': 'IAPL_IP_HEADER=cf-connecting-ip\nIPAL_IP_HEADER=x-real-ip\n', 'iapl-doctor.json': {}, 'ipal-doctor.json': {} }) const warnings = (await run(dir, ['legacy-names'])).findings.filter((f) => f.rule === 'legacy-names' && f.severity === 'warning').map((f) => f.message) expect(warnings).toHaveLength(2) expect(warnings.join('\n')).toMatch(/both iapl-doctor\.json and ipal-doctor\.json exist/) expect(warnings.join('\n')).toMatch(/IAPL_IP_HEADER and IPAL_IP_HEADER are both set/) }) test('the same value under both spellings is not a warning', async () => { const dir = site({ '.env.example': 'IAPL_IP_HEADER=cf-connecting-ip\nIPAL_IP_HEADER=cf-connecting-ip\n' }) expect((await run(dir, ['legacy-names'])).findings.filter((f) => f.severity === 'warning')).toEqual([]) }) test('storage-names: the cookie the page sets must be the one the scanner declares', async () => { const layout = (props: string) => `import { PageStats } from '@intecion/ipal-kit/client'\nexport default function L() { return }\n` const config = (names: string) => `import { iapl } from '@intecion/ipal-kit'\nexport default { plugins: [iapl({ ${names} })] }\n` const check = async (names: string, props: string) => (await run(project({ 'package.json': { name: 'x' }, 'src/app/(frontend)/[locale]/layout.tsx': layout(props), 'src/payload.config.ts': config(names) }), ['storage-names'])).findings .filter((f) => f.rule === 'storage-names') .map((f) => f.message) expect(await check('', 'locale="pl"')).toEqual([]) expect(await check("storageNames: 'iapl'", 'visitorCookie={IAPL_VISITOR_COOKIE}')).toEqual([]) expect(await check("storageNames: 'iapl'", 'locale="pl"')).toEqual(['the page sets the visitor cookie ipal_vid, the cookie scanner declares iapl_vid']) expect(await check('', 'visitorCookie="iapl_vid"')).toEqual(['the page sets the visitor cookie iapl_vid, the cookie scanner declares ipal_vid']) // a name the doctor cannot read (a variable) is not judged expect(await check('', 'visitorCookie={name}')).toEqual([]) }) }) describe('commands and skills', () => { test('the five old commands are installed beside the five new ones, on the same files', () => { for (const [old, name] of Object.entries(LEGACY_COMMANDS)) { expect(pkg.bin[old], old).toBe(pkg.bin[name]) expect(existsSync(path.join(packageRoot, pkg.bin[name])), pkg.bin[name]).toBe(true) } expect(Object.keys(pkg.bin)).toHaveLength(10) // `pnpm dlx @intecion/ipal-kit create` runs the bin named after the package expect(pkg.bin['ipal-kit']).toBe('bin/iapl.mjs') }) test('the package ships the 16 skills as iapl-*, and none under the old names', () => { const shipped = readdirSync(path.join(packageRoot, 'docs/agent/skills')) expect(shipped.filter((n) => n.startsWith('ipal-'))).toEqual([]) expect(shipped.filter((n) => n.startsWith('iapl-')).sort()).toEqual(LEGACY_SKILL_NAMES.map((n) => n.replace('ipal-', 'iapl-')).sort()) }) test('the installer and the doctor remove the same fixed list of old names', () => { const source = readFileSync(path.join(packageRoot, 'bin/iapl-skills.mjs'), 'utf8') const list = source.match(/const LEGACY_SKILLS = \[([\s\S]*?)\]/)?.[1] ?? '' expect([...list.matchAll(/'([a-z-]+)'/g)].map((m) => `ipal-${m[1]}`)).toEqual(LEGACY_SKILL_NAMES) }) test('iapl-skills on a 1.16 project: old folders replaced, own ipal-* skill kept, pointer rewritten once', () => { const own = '# our own skill\n' const dir = project({ '.agents/skills/ipal-custom/SKILL.md': own, '.agents/skills/ipal-setup/SKILL.md': '# old setup', '.agents/skills/ipal-upgrade/SKILL.md': '# old upgrade', '.agents/skills/our-skill/SKILL.md': own, 'AGENTS.md': '# AGENTS\n\nintro\n\n\n## ipal-kit 1.16.7 — agent guide\n\nold text\n\n\n## Project decisions\n\n- one\n', 'CLAUDE.md': '@AGENTS.md\n', 'tsconfig.json': { exclude: ['node_modules', '.agents'] }, }) const run = (bin: string) => spawnSync(process.execPath, [path.join(packageRoot, 'bin', bin)], { cwd: dir, encoding: 'utf8' }) const first = run('iapl-skills.mjs') expect(first.status, first.stderr).toBe(0) const skills = readdirSync(path.join(dir, '.agents/skills')).sort() expect(skills.filter((n) => n.startsWith('iapl-'))).toHaveLength(16) expect(skills.filter((n) => n.startsWith('ipal-'))).toEqual(['ipal-custom']) expect(readFileSync(path.join(dir, '.agents/skills/ipal-custom/SKILL.md'), 'utf8')).toBe(own) expect(skills).toContain('our-skill') expect(first.stdout).toContain('remove ipal-setup (now iapl-setup)') const agents = readFileSync(path.join(dir, 'AGENTS.md'), 'utf8') expect(agents).not.toContain('ipal-kit:start') expect(agents.match(//g)).toHaveLength(1) expect(agents.startsWith('# AGENTS\n\nintro\n\n')).toBe(true) expect(agents.endsWith('\n\n## Project decisions\n\n- one\n')).toBe(true) expect(readFileSync(path.join(dir, 'CLAUDE.md'), 'utf8')).toBe('@AGENTS.md\n') // a second run changes nothing const second = run('iapl-skills.mjs') expect(second.status).toBe(0) expect(second.stdout).not.toMatch(/^(?:add|remove|create)\b/m) expect(second.stdout).toContain('ok AGENTS.md') expect(readFileSync(path.join(dir, 'AGENTS.md'), 'utf8')).toBe(agents) }) }) describe('stored names', () => { const ctx = (plugin: Partial) => ({ integrations: {}, payload: {}, plugin: { localeCount: 1, stats: true, ...plugin } }) as unknown as CookieScanContext const statsCookie = (plugin: Partial) => declarationsOf(DEFAULT_COOKIE_INTEGRATIONS.find((i) => i.key === 'stats')!, ctx(plugin)).map((d) => d.name) test('the visitor cookie is ipal_vid unless the site says storageNames: iapl', () => { expect([VISITOR_COOKIE, IAPL_VISITOR_COOKIE]).toEqual(['ipal_vid', 'iapl_vid']) expect([visitorCookieFor(undefined), visitorCookieFor('ipal'), visitorCookieFor('iapl')]).toEqual(['ipal_vid', 'ipal_vid', 'iapl_vid']) expect(statsCookie({})).toEqual(['ipal_vid']) expect(statsCookie({ visitorCookie: visitorCookieFor('iapl') })).toEqual(['iapl_vid']) }) test('withdrawing analytics consent deletes the cookie under either name', () => { expect(DEFAULT_COOKIE_MAP.analytics).toEqual(expect.arrayContaining(['ipal_vid', 'iapl_vid'])) }) test('the 2FA counter key keeps its prefix by default; one key per site, never two', async () => { expect(verifyLimitKey('users', '1')).toBe('ipal:2fa-verify:users:1') expect(verifyLimitKey('users', '1', 'iapl')).toBe('iapl:2fa-verify:users:1') const data = new Map() const kv = { get: async (key: string) => data.get(key) ?? null, set: async (key: string, value: object) => void data.set(key, value) } const req = () => ({ payload: { kv, logger: { warn: () => {} } }, user: { id: 1 } }) as never await buildVerifyLimit('users')(req()) expect([...data.keys()]).toEqual(['ipal:2fa-verify:users:1']) data.clear() clearVerifyLimits() const limit = buildVerifyLimit('users', { keyPrefix: 'iapl', max: 2 }) expect(await limit(req())).toBeNull() expect(await limit(req())).toBeNull() expect((await limit(req()))?.status).toBe(429) expect([...data.keys()]).toEqual(['iapl:2fa-verify:users:1']) expect(data.get('iapl:2fa-verify:users:1')).toMatchObject({ count: 3 }) }) })