Files
ipal-kit/test/legacyNames.test.ts
Radosław SmolińskiandClaude Opus 5.5 91770ec17f 2FA verify limit: a right code gives its place back; exempt by an admin-only field, not e-mail (docs)
The verify limit took a place for every attempt and kept it, so the sixth
correct login of one account within 10 minutes was refused (IAWL idea 27).
Now an attempt takes its place before the compare (a parallel burst still
cannot slip under the limit), a right code gives it back, an attempt refused
without a compare gives it back at once, and a new attempt held out only by
attempts still being checked gets 429 + Retry-After: 2 "try again in a
moment". buildVerifyLimit returns limit.settle(req, correct); the plugin's
guard calls it with the package's answer. No schema change: payload-kv keeps
{ count, resetAt }.

Docs: the exempt example keyed on e-mail, which every account may change
itself (shown over REST and GraphQL): now an admin-only checkbox, with a test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:15:51 +01:00

404 lines
25 KiB
TypeScript

/**
* 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, SITE_NOINDEX_ENV } 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<string, string>; name: string }
let dirs: string[] = []
const saved = { ...process.env }
function project(files: Record<string, object | string>): 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<string, unknown>
// 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'])
// ipalEnvRules is the one exception: the same rules under the names a project wrote before (next test block)
for (const [old, name] of runtime.filter(([o]) => o !== 'ipalEnvRules')) {expect(values[old], `${old} → ${name}`).toBe(values[name])}
})
test('the env and tokens entries carry both spellings too', () => {
expect(envEntry.ipalEnvRules).toBe(root.ipalEnvRules)
expect(envEntry.iaplEnvRules).toBe(root.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('ipalEnvRules() keeps the old rule names, so code that adapts the rules by name still starts', () => {
const features = { cookieCrawl: true, ipHeader: true }
const names = (rules: { name: string }[]) => rules.map((r) => r.name)
const old = envEntry.ipalEnvRules(features)
const fresh = envEntry.iaplEnvRules(features)
expect(names(old)).toEqual(names(fresh).map((n) => n.replace(/^IAPL_/, 'IPAL_')))
expect(old.find((r) => r.name === 'IPAL_IP_HEADER')?.aliases).toEqual(['IAPL_IP_HEADER'])
expect(fresh.find((r) => r.name === 'IAPL_IP_HEADER')?.aliases).toEqual(['IPAL_IP_HEADER'])
// the two measured cases of the review: production, only the old env names, the project's code unchanged
const env = { DATABASE_URI: 'mongodb://127.0.0.1/x_prod', IPAL_IP_HEADER: 'cf-connecting-ip', NEXT_PUBLIC_SERVER_URL: 'https://example.pl', NODE_ENV: 'production', PAYLOAD_SECRET: 's'.repeat(40) }
const before = process.env.NODE_ENV
;(process.env as Record<string, string | undefined>).NODE_ENV = 'production'
try {
const rules = envEntry.ipalEnvRules(features)
expect(() => assertEnv(rules, { env })).toThrow(/IPAL_COOKIE_SCAN_URL is required/)
expect(() => assertEnv(rules.map((r) => (/^IPAL_COOKIE_SCAN/.test(r.name) ? { ...r, required: false } : r)), { env })).not.toThrow()
expect(() => assertEnv(rules.filter((r) => !r.name.startsWith('IPAL_COOKIE_SCAN')), { env })).not.toThrow()
// untouched rules: the old env alone, the new env alone, and a too-short token under the old rule's own name
const scan = { COOKIE_SCAN_TOKEN: '0123456789abcdef', COOKIE_SCAN_URL: 'https://crawler.example.com' }
const withPrefix = (prefix: string) => Object.fromEntries(Object.entries(scan).map(([k, v]) => [`${prefix}_${k}`, v]))
expect(() => assertEnv(rules, { env: { ...env, ...withPrefix('IPAL') } })).not.toThrow()
expect(() => assertEnv(rules, { env: { ...env, IAPL_IP_HEADER: 'cf-connecting-ip', IPAL_IP_HEADER: undefined, ...withPrefix('IAPL') } })).not.toThrow()
expect(() => assertEnv(envEntry.iaplEnvRules(features), { env: { ...env, ...withPrefix('IPAL') } })).not.toThrow()
expect(() => assertEnv(rules, { env: { ...env, ...withPrefix('IPAL'), IPAL_COOKIE_SCAN_TOKEN: 'short' } })).toThrow(/IPAL_COOKIE_SCAN_TOKEN must be at least 16/)
// both spellings set: the IAPL_ value is the one checked, whichever the rule is named after
expect(() => assertEnv(rules, { env: { ...env, ...withPrefix('IPAL'), IAPL_COOKIE_SCAN_TOKEN: 'short' } })).toThrow(/must be at least 16/)
} finally {
;(process.env as Record<string, string | undefined>).NODE_ENV = before
}
})
test('the exported name constants kept their values; the new names have constants of their own', () => {
expect([root.COOKIE_SCAN_URL_ENV, root.COOKIE_SCAN_TOKEN_ENV]).toEqual(['IPAL_COOKIE_SCAN_URL', 'IPAL_COOKIE_SCAN_TOKEN'])
expect([root.IAPL_COOKIE_SCAN_URL_ENV, root.IAPL_COOKIE_SCAN_TOKEN_ENV]).toEqual(['IAPL_COOKIE_SCAN_URL', 'IAPL_COOKIE_SCAN_TOKEN'])
expect(SITE_NOINDEX_ENV).toBe('IPAL_NOINDEX')
// an empty new variable does not switch the old one off (docs/env.md)
process.env.IAPL_NOINDEX = ''
process.env.IPAL_NOINDEX = '1'
expect(isSiteNoindex()).toBe(true)
})
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 = '<!-- ipal-kit:start -->\n## ipal-kit 1.16.7 — agent guide\n\ntext\n<!-- ipal-kit:end -->'
const NEW_POINTER = '<!-- iapl:start -->\n## IAPL 1.17.0 — agent guide\n\ntext\n<!-- iapl:end -->'
const site = (extra: Record<string, object | string> = {}) =>
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('IPAL_* names in .env.example satisfy env-example; IPAL_SEED_ALLOW_FULL=1 is still caught', async () => {
const example = 'DATABASE_URI=\nPAYLOAD_SECRET=\nNEXT_PUBLIC_SERVER_URL=\nIPAL_IP_HEADER=\nIPAL_COOKIE_SCAN_URL=\nIPAL_COOKIE_SCAN_TOKEN=\n'
const config = "export default { plugins: [ipalKit({ cookieScanner: { crawl: true } })] }\n"
const ok = site({ '.env.example': example, 'src/payload.config.ts': config })
expect((await run(ok, ['env-example'])).findings.filter((f) => f.rule === 'env-example')).toEqual([])
const bad = site({
'.env.example': `${example}IPAL_SEED_ALLOW_FULL=1\nIPAL_DOCTOR_TOKEN=0123456789abcdef0123456789abcdef\n`,
'package.json': { name: 'x', scripts: { 'seed:all': 'IPAL_SEED_ALLOW_FULL=1 payload run src/seed/index.ts' } },
'src/payload.config.ts': config,
})
const messages = (await run(bad, ['env-example', 'seed-named'])).findings.map((f) => f.message).join('\n')
expect(messages).toMatch(/IPAL_DOCTOR_TOKEN in \.env\.example has a value/)
expect(messages).toMatch(/\.env\.example sets IAPL_SEED_ALLOW_FULL=1/)
expect(messages).toMatch(/script "seed:all" switc/)
})
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 <PageStats ${props} /> }\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'])
// the reference layout's shape: <SiteProviders> with a JSX prop before `stats` (the first `>` is inside it)
const providers = (stats: string) => `import { SiteProviders } from '@intecion/ipal-kit/rsc'\nexport default function L() {\n return (\n <SiteProviders\n banner={<CookieBanner controls="switch" equalChoice settings="detailed" />}\n lightbox\n ${stats}\n shell={shell}\n >\n <main />\n </SiteProviders>\n )\n}\n`
const withProviders = async (names: string, stats: string) =>
(await run(project({ 'package.json': { name: 'x' }, 'src/app/(frontend)/[locale]/layout.tsx': providers(stats), 'src/payload.config.ts': config(names) }), ['storage-names'])).findings.filter((f) => f.rule === 'storage-names').length
expect(await withProviders("storageNames: 'iapl'", 'stats={{ locale }}')).toBe(1)
expect(await withProviders("storageNames: 'iapl'", 'stats')).toBe(1)
expect(await withProviders("storageNames: 'iapl'", 'stats={{ locale, visitorCookie: IAPL_VISITOR_COOKIE }}')).toBe(0)
expect(await withProviders('', 'stats={{ locale }}')).toBe(0)
expect(await withProviders("storageNames: 'iapl'", 'theme')).toBe(0) // no statistics mounted: nothing to compare
// 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)
// …and the old FILES are still there: 1.16's own audit skill and CI scripts call them by path
for (const [old, name] of Object.entries(LEGACY_COMMANDS)) {
const file = path.join(packageRoot, 'bin', `${old}.mjs`)
expect(existsSync(file), `bin/${old}.mjs`).toBe(true)
expect(readFileSync(file, 'utf8')).toContain(`import './${pkg.bin[name].replace('bin/', '')}'`)
}
const byPath = spawnSync(process.execPath, [path.join(packageRoot, 'bin/ipal-skills.mjs'), '--help'], { encoding: 'utf8' })
expect(byPath.status).toBe(0)
expect(byPath.stdout).toContain('Usage: iapl-skills')
// `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<!-- ipal-kit:start -->\n## ipal-kit 1.16.7 — agent guide\n\nold text\n<!-- ipal-kit:end -->\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(/<!-- iapl:start -->/g)).toHaveLength(1)
expect(agents.startsWith('# AGENTS\n\nintro\n\n<!-- iapl:start -->')).toBe(true)
expect(agents.endsWith('<!-- iapl:end -->\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)
// a rollback to 1.16 whose installer appended its block again, then the upgrade: one block, the new one
writeFileSync(path.join(dir, 'AGENTS.md'), `${agents}\n<!-- ipal-kit:start -->\n## ipal-kit 1.16.7 — agent guide\n\nold text\n<!-- ipal-kit:end -->\n`)
expect(run('iapl-skills.mjs').status).toBe(0)
expect(readFileSync(path.join(dir, 'AGENTS.md'), 'utf8')).toBe(agents)
})
})
describe('stored names', () => {
const ctx = (plugin: Partial<CookieScanContext['plugin']>) => ({ integrations: {}, payload: {}, plugin: { localeCount: 1, stats: true, ...plugin } }) as unknown as CookieScanContext
const statsCookie = (plugin: Partial<CookieScanContext['plugin']>) =>
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<string, object>()
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: 2 }) // the refused third gave its place back (1.17.1)
// an empty or undefined prefix is "not given", never a third key
for (const keyPrefix of [undefined, '', ' ']) {
data.clear()
clearVerifyLimits()
await buildVerifyLimit('users', { keyPrefix })(req())
expect([...data.keys()]).toEqual(['ipal:2fa-verify:users:1'])
}
})
})