From 425fac14fb3187b4fedc320a3c93346483d85ca5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Wed, 25 Nov 2026 17:31:13 +0100 Subject: [PATCH] IAPL rename: the old names keep working, and a second cookie name and counter key for new sites - exports: ipalKit, IpalOptions, ipalEnvRules, IpalEnvFeatures, ipalT, ipalVar, IPAL_TOKENS, IPAL_BREAKPOINTS, IpalTokenName, IpalGlobalSlug are aliases of the iapl names - env: IAPL_* is read first, IPAL_* as fallback (readEnv; EnvRule.aliases for assertEnv); the crawler service reads IPAL_CRAWLER_SITES too - doctor: reads ipal-doctor.json when it is the only one, the old pointer block, ipal-audit-skip and old skill folders; new rule legacy-names (info) and storage-names (warning) - iapl-skills: installs iapl-*, removes the 16 old folders by exact name, rewrites the old pointer block in place; a project's own ipal-* skill stays - storageNames: 'ipal' (default) | 'iapl': the cookie the scanner declares and the 2FA counter's kv prefix; , IAPL_VISITOR_COOKIE, verifyLimit.keyPrefix - test/legacyNames.test.ts: 24 tests for all of the above Co-Authored-By: Claude Fable 5.2 --- bin/iapl-skills.mjs | 23 +- bin/iapl.mjs | 4 +- services/cookie-crawler/Dockerfile | 2 +- services/cookie-crawler/README.md | 2 +- services/cookie-crawler/lib.mjs | 2 +- services/cookie-crawler/server.mjs | 4 +- src/exports/client.ts | 2 +- src/exports/env.ts | 4 +- src/exports/tokens.ts | 9 +- src/globals/overrides.ts | 3 + src/index.ts | 18 +- src/modules/admin-i18n/index.ts | 2 +- src/modules/admin-i18n/t.ts | 3 + src/modules/consent/scanner/crawl/config.ts | 5 +- src/modules/consent/scanner/integrations.ts | 5 +- src/modules/consent/scanner/types.ts | 5 +- src/modules/consent/useConsent.ts | 2 +- src/modules/doctor/probe.ts | 3 +- src/modules/doctor/project.ts | 19 +- src/modules/doctor/rules/agents.ts | 11 +- src/modules/doctor/rules/env.ts | 2 +- src/modules/doctor/rules/layout.ts | 2 +- src/modules/doctor/rules/legacy.ts | 133 +++++++++ src/modules/doctor/rules/security.ts | 2 +- src/modules/doctor/run.ts | 17 +- src/modules/doctor/status.ts | 3 +- src/modules/env/assertEnv.ts | 7 +- src/modules/env/iaplEnvRules.ts | 12 +- src/modules/env/index.ts | 4 +- src/modules/security/totp/verifyLimit.ts | 12 +- src/modules/seed/seeder.ts | 5 +- src/modules/seo/siteNoindex.ts | 6 +- src/modules/shared/envName.ts | 24 ++ src/modules/shared/rateLimit.ts | 4 +- src/modules/stats/PageStats.tsx | 25 +- src/modules/stats/client.ts | 2 +- src/modules/stats/visitorCookie.ts | 20 ++ src/modules/tokens/catalog.ts | 6 + src/modules/tokens/index.ts | 6 +- src/modules/tokens/names.ts | 6 + src/plugin.ts | 8 +- src/types.ts | 18 ++ test/legacyNames.test.ts | 313 ++++++++++++++++++++ 43 files changed, 683 insertions(+), 82 deletions(-) create mode 100644 src/modules/doctor/rules/legacy.ts create mode 100644 src/modules/shared/envName.ts create mode 100644 src/modules/stats/visitorCookie.ts create mode 100644 test/legacyNames.test.ts diff --git a/bin/iapl-skills.mjs b/bin/iapl-skills.mjs index 53a43f9..333e272 100755 --- a/bin/iapl-skills.mjs +++ b/bin/iapl-skills.mjs @@ -8,6 +8,9 @@ // pnpm exec iapl-skills --external ext-accessibility,ext-payload → only those // Only folders named iapl-* are touched; the project's own skills stay as they are. // iapl-* folders that no longer exist in the package are removed (renamed/retired skills). +// Before 1.17.0 the skills were named ipal-*: the 16 folders of that set are removed by their +// exact names (LEGACY_SKILLS) — any other ipal- folder is the project's own and stays. +// `ipal-skills` is the same command under its old name. // ext-* folders are touched only with --external, and only those carrying IAPL's SOURCE.md. // AGENTS.md (and CLAUDE.md) get a marked IAPL block pointing at the guide — only the // text between the markers is ever rewritten; the project's own content stays as it is. @@ -58,10 +61,19 @@ if (unknown.length) { process.exit(1) } -const isSkillDir = (base, name) => name.startsWith('ipal-') && statSync(join(base, name)).isDirectory() +// The same list as LEGACY_SKILL_NAMES in src/modules/doctor/rules/legacy.ts (test/legacyNames.test.ts compares them). +const LEGACY_SKILLS = [ + 'audit', 'block', 'collection', 'consent-check', 'debug', 'doctor', 'form', 'locale-add', + 'migrate-fields', 'nav', 'plugin-gap', 'reference', 'seo-check', 'setup', 'site', 'upgrade', +].map((name) => `ipal-${name}`) +const isDir = (base, name) => statSync(join(base, name)).isDirectory() +const isSkillDir = (base, name) => name.startsWith('iapl-') && isDir(base, name) const shipped = readdirSync(src).filter((n) => isSkillDir(src, n)) const existing = existsSync(dest) ? readdirSync(dest).filter((n) => isSkillDir(dest, n)) : [] -const retired = existing.filter((n) => !shipped.includes(n)) +const retired = [ + ...existing.filter((n) => !shipped.includes(n)), + ...(existsSync(dest) ? readdirSync(dest).filter((n) => LEGACY_SKILLS.includes(n) && isDir(dest, n)) : []), +] if (!dryRun) mkdirSync(dest, { recursive: true }) for (const name of shipped) { @@ -73,7 +85,7 @@ for (const name of shipped) { } } for (const name of retired) { - console.log(`remove ${name} (no longer in IAPL)`) + console.log(`remove ${name} (${LEGACY_SKILLS.includes(name) ? `now ${name.replace('ipal-', 'iapl-')}` : 'no longer in IAPL'})`) if (!dryRun) rmSync(join(dest, name), { recursive: true, force: true }) } console.log(`${dryRun ? '[dry-run] ' : ''}${shipped.length} skill(s) → ${dest}`) @@ -119,6 +131,8 @@ if (externalArg >= 0) { if (pointer) { const START = '' const END = '' + const OLD_START = '' + const OLD_END = '' const version = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')).version const skillsDir = relative(process.cwd(), dest).split('\\').join('/') const block = [ @@ -146,6 +160,9 @@ if (pointer) { next = create === 'import' ? '@AGENTS.md\n' : `# ${file.replace('.md', '')}\n\n${block}\n` } else if (text.includes(START) && text.includes(END)) { next = text.slice(0, text.indexOf(START)) + block + text.slice(text.indexOf(END) + END.length) + } else if (text.includes(OLD_START) && text.includes(OLD_END)) { + // the block written before 1.17.0: replaced where it stands, markers included + next = text.slice(0, text.indexOf(OLD_START)) + block + text.slice(text.indexOf(OLD_END) + OLD_END.length) } else { next = `${text.replace(/\s*$/, '')}\n\n${block}\n` } diff --git a/bin/iapl.mjs b/bin/iapl.mjs index aba36b5..73332ac 100755 --- a/bin/iapl.mjs +++ b/bin/iapl.mjs @@ -1,5 +1,5 @@ #!/usr/bin/env node -// IAPL — the plugin's command line. +// iapl — the IAPL command line (also installed as `ipal-kit`, its name before 1.17.0, which `pnpm dlx @intecion/ipal-kit` runs). // pnpm dlx @intecion/ipal-kit@ create intecion.com → a new client site (docs/project-starter.md) // pnpm exec iapl create intecion.com --dir ../intecioncom-web --answers answers.json // `pnpm dlx ` runs the bin named after the package, so every subcommand lives here. @@ -8,7 +8,7 @@ import { dirname, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' -const USAGE = `Usage: IAPL [options] +const USAGE = `Usage: iapl [options] create a new client site from the reference site (iapl create --help) Other tools: iapl-skills, iapl-blocks, iapl-tokens, iapl-doctor` diff --git a/services/cookie-crawler/Dockerfile b/services/cookie-crawler/Dockerfile index 8cf7f7a..7c65be8 100644 --- a/services/cookie-crawler/Dockerfile +++ b/services/cookie-crawler/Dockerfile @@ -1,4 +1,4 @@ -# ipal cookie crawler — one shared service for all sites (docs/cookie-scanner.md → Coolify). +# IAPL cookie crawler — one shared service for all sites (docs/cookie-scanner.md → Coolify). # The Playwright image ships Chromium and its system libraries; the npm package # version must match the image tag. FROM mcr.microsoft.com/playwright:v1.64.0-noble diff --git a/services/cookie-crawler/README.md b/services/cookie-crawler/README.md index 8ed6cce..533a5f7 100644 --- a/services/cookie-crawler/README.md +++ b/services/cookie-crawler/README.md @@ -1,4 +1,4 @@ -# ipal cookie crawler +# IAPL cookie crawler The browser half of IAPL's cookie scanner: one shared service that crawls a site twice (no consent / after "Accept all") and posts cookies, storage keys and third-party hosts back to the diff --git a/services/cookie-crawler/lib.mjs b/services/cookie-crawler/lib.mjs index 74d1fc0..4ac71e1 100644 --- a/services/cookie-crawler/lib.mjs +++ b/services/cookie-crawler/lib.mjs @@ -1,4 +1,4 @@ -// Pure helpers of the ipal cookie crawler (no browser, no network) — tested in +// Pure helpers of the IAPL cookie crawler (no browser, no network) — tested in // test/cookieCrawler.test.ts. Wire format: src/modules/consent/scanner/crawl/result.ts. import { createHash, timingSafeEqual } from 'node:crypto' diff --git a/services/cookie-crawler/server.mjs b/services/cookie-crawler/server.mjs index 3e56184..987ad98 100644 --- a/services/cookie-crawler/server.mjs +++ b/services/cookie-crawler/server.mjs @@ -1,4 +1,4 @@ -// ipal cookie crawler — HTTP service (deploy: docs/cookie-scanner.md → "Scanner service on Coolify"). +// IAPL cookie crawler — HTTP service (deploy: docs/cookie-scanner.md → "Scanner service on Coolify"). // // GET /health → { ok, running, queued } // POST /crawl → Authorization: Bearer @@ -139,7 +139,7 @@ export function createCrawlerServer({ // Run directly: `node server.mjs` if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { - const sites = parseSites(process.env.IAPL_CRAWLER_SITES) + const sites = parseSites(process.env.IAPL_CRAWLER_SITES?.trim() ? process.env.IAPL_CRAWLER_SITES : process.env.IPAL_CRAWLER_SITES) // IPAL_CRAWLER_SITES: the name before 1.17.0, still read if (!sites.length) { console.error('[crawler] IAPL_CRAWLER_SITES is empty — set "host=token" pairs (token ≥ 16 chars).') process.exit(1) diff --git a/src/exports/client.ts b/src/exports/client.ts index 3f0e0d8..86097ce 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -99,7 +99,7 @@ export { TableOfContents } from '../modules/richtext/TableOfContents.js' export type { TableOfContentsClassNames, TableOfContentsProps } from '../modules/richtext/TableOfContents.js' export { NoSnippet } from '../modules/seo/NoSnippet.js' export type { NoSnippetProps } from '../modules/seo/NoSnippet.js' -export { PageStats, VISITOR_COOKIE } from '../modules/stats/client.js' +export { IAPL_VISITOR_COOKIE, PageStats, VISITOR_COOKIE } from '../modules/stats/client.js' export type { PageStatsProps } from '../modules/stats/client.js' export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js' export { diff --git a/src/exports/env.ts b/src/exports/env.ts index 254f768..f817f90 100644 --- a/src/exports/env.ts +++ b/src/exports/env.ts @@ -13,5 +13,5 @@ * if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(iaplEnvRules({ storage: true })) * } */ -export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules } from '../modules/env/index.js' -export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures } from '../modules/env/index.js' +export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules, ipalEnvRules } from '../modules/env/index.js' +export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures, IpalEnvFeatures } from '../modules/env/index.js' diff --git a/src/exports/tokens.ts b/src/exports/tokens.ts index 1783ee6..957e77a 100644 --- a/src/exports/tokens.ts +++ b/src/exports/tokens.ts @@ -15,11 +15,14 @@ export { FLUID_SCALE, FLUID_TOKENS, fluidClamp, - INVERSE_SCOPE, - INVERSE_SELECTOR, IAPL_BREAKPOINTS, IAPL_TOKENS, iaplVar, + INVERSE_SCOPE, + INVERSE_SELECTOR, + IPAL_BREAKPOINTS, + IPAL_TOKENS, + ipalVar, LEGACY_DARK_ROLES, LIGHT_SELECTOR, parseColor, @@ -27,4 +30,4 @@ export { STATIC_DEFAULTS, tokensToCss, } from '../modules/tokens/index.js' -export type { ColorInput, ColorRole, ContrastRow, FluidRange, IaplTokenName, RemValue, TokensInput } from '../modules/tokens/index.js' +export type { ColorInput, ColorRole, ContrastRow, FluidRange, IaplTokenName, IpalTokenName, RemValue, TokensInput } from '../modules/tokens/index.js' diff --git a/src/globals/overrides.ts b/src/globals/overrides.ts index fe54bff..e45d6be 100644 --- a/src/globals/overrides.ts +++ b/src/globals/overrides.ts @@ -42,3 +42,6 @@ export function applyGlobalOverrides(globals: GlobalConfig[], overrides: GlobalO } }) } + +/** @deprecated The name before 1.17.0; the same type as `IaplGlobalSlug`. Removed in 2.0. */ +export type IpalGlobalSlug = IaplGlobalSlug diff --git a/src/index.ts b/src/index.ts index df2c574..b20c25f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ export { lightboxNotificationFields } from './globals/Notifications/fields.js' export { applyGlobalOverrides } from './globals/overrides.js' -export type { GlobalOverride, GlobalOverrides, IaplGlobalSlug } from './globals/overrides.js' +export type { GlobalOverride, GlobalOverrides, IaplGlobalSlug, IpalGlobalSlug } from './globals/overrides.js' export type { AccessOption, Role } from './modules/access/index.js' export { adminOnly, @@ -55,7 +55,7 @@ export type { AccountsOptions } from './modules/access/types.js' export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/state.js' export type { A11yState } from './modules/accessibility/state.js' export { applyAdminI18n } from './modules/admin-i18n/apply.js' -export { ADMIN_LANGUAGES, adminDocumentTitle, adminTexts, defineTexts, formatDateTime, formatNumber, iaplT } from './modules/admin-i18n/index.js' +export { ADMIN_LANGUAGES, adminDocumentTitle, adminTexts, defineTexts, formatDateTime, formatNumber, iaplT, ipalT } from './modules/admin-i18n/index.js' export type { AdminLanguage, AdminText, AdminTextKey } from './modules/admin-i18n/index.js' export { rowLabel } from './modules/admin-ui/index.js' export type { RowLabelProps } from './modules/admin-ui/index.js' @@ -216,8 +216,8 @@ export type { MailAdapterArgs } from './modules/email/mailAdapter.js' export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js' export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js' // Boot-time environment validation (fail fast on misconfigured deploys). -export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules } from './modules/env/index.js' -export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures } from './modules/env/index.js' +export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules, ipalEnvRules } from './modules/env/index.js' +export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures, IpalEnvFeatures } from './modules/env/index.js' export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions } from './modules/forms/attachments/config.js' export { buildFileBlock, fileBlock } from './modules/forms/attachments/fileBlock.js' export { FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS } from './modules/forms/attachments/fileTypes.js' @@ -452,6 +452,8 @@ export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit export { buildSlugField, toSlug } from './modules/slug/index.js' export { STATS_SLUG } from './modules/stats/index.js' export type { StatsOptions, StatsPage, StatsVisit } from './modules/stats/index.js' +export { IAPL_VISITOR_COOKIE, VISITOR_COOKIE, visitorCookieFor } from './modules/stats/visitorCookie.js' +export type { StorageNames } from './modules/stats/visitorCookie.js' export { buildImagesConfig } from './modules/storage/buildImagesConfig.js' export type { ImagesConfig } from './modules/storage/buildImagesConfig.js' export { buildR2Storage } from './modules/storage/index.js' @@ -459,9 +461,9 @@ export { isTheme, isThemeSetting, LEGACY_THEME_STORAGE_KEY, THEME_ATTRIBUTE, THE export type { Theme, ThemeConfig, ThemeSetting } from './modules/theme/index.js' // Imported from the file, not the turnstile barrel — that one re-exports verify, // which imports 'server-only'. -export { defineTokens, IAPL_BREAKPOINTS, IAPL_TOKENS, iaplVar } from './modules/tokens/index.js' -export type { IaplTokenName, TokensInput } from './modules/tokens/index.js' +export { defineTokens, IAPL_BREAKPOINTS, IAPL_TOKENS, iaplVar, IPAL_BREAKPOINTS, IPAL_TOKENS, ipalVar } from './modules/tokens/index.js' +export type { IaplTokenName, IpalTokenName, TokensInput } from './modules/tokens/index.js' export { getTurnstileConfig, TURNSTILE_SECRET_ENV, turnstileSecretFromEnv } from './modules/turnstile/config.js' export type { TurnstileConfig } from './modules/turnstile/config.js' -export { iapl } from './plugin.js' -export type { IaplOptions, ThemeOptions } from './types.js' +export { iapl, ipalKit } from './plugin.js' +export type { IaplOptions, IpalOptions, ThemeOptions } from './types.js' diff --git a/src/modules/admin-i18n/index.ts b/src/modules/admin-i18n/index.ts index 8188a31..72697da 100644 --- a/src/modules/admin-i18n/index.ts +++ b/src/modules/admin-i18n/index.ts @@ -1,6 +1,6 @@ // Client-safe: types, texts and helpers. The config transform (applyAdminI18n) lives in apply.ts. export type { AdminLanguage, AdminText } from './define.js' export { ADMIN_LANGUAGES, defineTexts } from './define.js' -export { adminDocumentTitle, formatDateTime, formatNumber, iaplT } from './t.js' +export { adminDocumentTitle, formatDateTime, formatNumber, iaplT, ipalT } from './t.js' export { adminTexts } from './texts/index.js' export type { AdminTextKey } from './texts/index.js' diff --git a/src/modules/admin-i18n/t.ts b/src/modules/admin-i18n/t.ts index 003b60e..f622471 100644 --- a/src/modules/admin-i18n/t.ts +++ b/src/modules/admin-i18n/t.ts @@ -20,3 +20,6 @@ export const formatDateTime = (iso: string, language: string, timeZone?: string) /** The tab title Payload builds for a view: its title plus `admin.meta.titleSuffix`. */ export const adminDocumentTitle = (title: string, titleSuffix?: null | string) => (titleSuffix ? `${title} ${titleSuffix}` : title) + +/** @deprecated The name before 1.17.0; the same function as `iaplT`. Removed in 2.0. */ +export const ipalT = iaplT diff --git a/src/modules/consent/scanner/crawl/config.ts b/src/modules/consent/scanner/crawl/config.ts index ae3b5cd..ffa14b9 100644 --- a/src/modules/consent/scanner/crawl/config.ts +++ b/src/modules/consent/scanner/crawl/config.ts @@ -2,6 +2,7 @@ import type { BasePayload } from 'payload' import type { CookieCrawlOptions } from '../types.js' +import { readEnv } from '../../../shared/envName.js' import { DEFAULT_TRACKER_HOSTS } from './violations.js' export const COOKIE_CRAWL_SLUG = 'cookie-crawl' @@ -27,8 +28,8 @@ const trimSlash = (v: string) => v.replace(/\/+$/, '') /** Options + env + Payload config, read at call time (env can change between deploys, not between requests). */ export function resolveCrawlConfig(options: CookieCrawlOptions, payload: BasePayload): ResolvedCrawlConfig { - const serviceUrl = options.serviceUrl ?? process.env[COOKIE_SCAN_URL_ENV]?.trim() - const token = options.token ?? process.env[COOKIE_SCAN_TOKEN_ENV]?.trim() + const serviceUrl = options.serviceUrl ?? readEnv(COOKIE_SCAN_URL_ENV)?.trim() + const token = options.token ?? readEnv(COOKIE_SCAN_TOKEN_ENV)?.trim() const siteUrl = options.siteUrl ?? (payload.config.serverURL || process.env.NEXT_PUBLIC_SERVER_URL?.trim()) return { acceptSelector: options.acceptSelector ?? '[data-ipal="accept"]', diff --git a/src/modules/consent/scanner/integrations.ts b/src/modules/consent/scanner/integrations.ts index 90f6632..0629ca2 100644 --- a/src/modules/consent/scanner/integrations.ts +++ b/src/modules/consent/scanner/integrations.ts @@ -4,6 +4,7 @@ import type { CookieDeclaration, CookieIntegration, CookieScanContext } from './ import { adminTexts } from '../../admin-i18n/texts/index.js' import { validAnalyticsId } from '../../analytics/idFormats.js' import { LOCALE_COOKIE_NAME } from '../../i18n/negotiateLocale.js' +import { VISITOR_COOKIE } from '../../stats/visitorCookie.js' import { THEME_STORAGE_KEY } from '../../theme/theme.js' import { getTurnstileConfig } from '../../turnstile/config.js' import { CONSENT_COOKIE } from '../storage.js' @@ -108,9 +109,9 @@ export const DEFAULT_COOKIE_INTEGRATIONS: CookieIntegration[] = [ label: A('cookieIntegrationLocale'), }, { - declarations: [ + declarations: (ctx) => [ { - name: 'ipal_vid', // VISITOR_COOKIE — that file is a client component + name: ctx.plugin.visitorCookie ?? VISITOR_COOKIE, // `iapl_vid` on a site with iapl({ storageNames: 'iapl' }) category: 'analytics', purpose: T( 'Built-in statistics: random visitor id that joins your visits across days. Set only with analytics consent.', diff --git a/src/modules/consent/scanner/types.ts b/src/modules/consent/scanner/types.ts index ce66135..2cf4e16 100644 --- a/src/modules/consent/scanner/types.ts +++ b/src/modules/consent/scanner/types.ts @@ -37,9 +37,8 @@ export type CookieScanContext = { /** Admin language of the request (`req.i18n.language`); names stored by a scan use it. Default `'en'`. */ language?: string payload: BasePayload - /** Plugin options that switch modules on. */ - /** Plugin options that switch modules on; `themeStorageKey` = `iapl({ theme: { storageKey } })`. */ - plugin: { localeCount: number; stats: boolean; themeStorageKey?: string } + /** Plugin options that switch modules on; `themeStorageKey` = `iapl({ theme: { storageKey } })`; `visitorCookie` = the statistics cookie of this site (`iapl({ storageNames })`, default `ipal_vid`). */ + plugin: { localeCount: number; stats: boolean; themeStorageKey?: string; visitorCookie?: string } } /** diff --git a/src/modules/consent/useConsent.ts b/src/modules/consent/useConsent.ts index f7915f9..4d41269 100644 --- a/src/modules/consent/useConsent.ts +++ b/src/modules/consent/useConsent.ts @@ -17,7 +17,7 @@ export type ConsentCookieMap = Partial> * projects add theirs through (merged, not replaced). */ export const DEFAULT_COOKIE_MAP: ConsentCookieMap = { - analytics: ['_ga', '_ga_*', '_gid', '_gat*', '_clck', '_clsk', 'CLID', '_hj*', 'ipal_vid'], + analytics: ['_ga', '_ga_*', '_gid', '_gat*', '_clck', '_clsk', 'CLID', '_hj*', 'ipal_vid', 'iapl_vid'], functional: [LOCALE_COOKIE_NAME], marketing: ['_fbp', '_fbc', '_gcl_*', '_ttp', 'li_fat_id', '_uetsid', '_uetvid'], } diff --git a/src/modules/doctor/probe.ts b/src/modules/doctor/probe.ts index f30a715..0613fb9 100644 --- a/src/modules/doctor/probe.ts +++ b/src/modules/doctor/probe.ts @@ -14,6 +14,7 @@ import { pathToFileURL } from 'node:url' import type { DoctorStatus } from './types.js' +import { readEnv } from '../shared/envName.js' import { collectDoctorStatus, pluginVersion } from './status.js' const root = process.cwd() @@ -47,7 +48,7 @@ async function main() { Object.assign(status, await collectDoctorStatus(payload)) // The doctor passes the committed import map it found (relative to the project root). - const committed = config.admin?.importMap?.importMapFile ?? (process.env.IAPL_DOCTOR_IMPORT_MAP ? join(root, process.env.IAPL_DOCTOR_IMPORT_MAP) : '') + const committed = config.admin?.importMap?.importMapFile ?? (readEnv('IAPL_DOCTOR_IMPORT_MAP') ? join(root, readEnv('IAPL_DOCTOR_IMPORT_MAP')!) : '') if (committed && existsSync(committed)) { const temp = join(dirname(committed), 'importMap.iapl-doctor.tmp.js') try { diff --git a/src/modules/doctor/project.ts b/src/modules/doctor/project.ts index fd3da58..87f65af 100644 --- a/src/modules/doctor/project.ts +++ b/src/modules/doctor/project.ts @@ -75,11 +75,11 @@ export function bareHost(value: string): string { const isLocalHost = (host: string) => /^(?:localhost|127\.0\.0\.1|\[?::1\]?|0\.0\.0\.0)$|^[^.]+$/.test(host) -/** Reads `iapl-audit-skip: a, b — reason` lines (AGENT.md §0b). */ +/** Reads `iapl-audit-skip: a, b — reason` lines (AGENT.md §0b); the spelling before 1.17.0, `ipal-audit-skip`, is read too. */ export function readAuditSkips(agents: string): Map { const out = new Map() for (const line of agents.split('\n')) { - const m = line.match(/^[-* ]*iapl-audit-skip:(.*)$/i) + const m = line.match(/^[-* ]*(?:iapl|ipal)-audit-skip:(.*)$/i) if (!m) {continue} const [keys = '', ...rest] = m[1].trim().split(/\s+—\s+|\s+-\s+/) const reason = rest.join(' — ').trim() @@ -88,15 +88,24 @@ export function readAuditSkips(agents: string): Map { return out } +/** The doctor's file in a project, and its name before 1.17.0. The first one that exists is read and written. */ +export const DOCTOR_CONFIG_FILES = ['iapl-doctor.json', 'ipal-doctor.json'] as const + +/** Name of the project's doctor file: `iapl-doctor.json`, or `ipal-doctor.json` when only that one exists. */ +export function doctorConfigFile(root: string): string { + return DOCTOR_CONFIG_FILES.find((name) => existsSync(join(root, name))) ?? DOCTOR_CONFIG_FILES[0] +} + export function loadDoctorConfig(root: string): { config: DoctorConfig; error: null | string } { - const file = join(root, 'iapl-doctor.json') + const name = doctorConfigFile(root) + const file = join(root, name) if (!existsSync(file)) {return { config: {}, error: null }} try { const parsed = JSON.parse(readFileSync(file, 'utf8')) as unknown - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {return { config: {}, error: 'iapl-doctor.json must hold an object' }} + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {return { config: {}, error: `${name} must hold an object` }} return { config: parsed as DoctorConfig, error: null } } catch (err) { - return { config: {}, error: `iapl-doctor.json is not valid JSON (${err instanceof Error ? err.message : String(err)})` } + return { config: {}, error: `${name} is not valid JSON (${err instanceof Error ? err.message : String(err)})` } } } diff --git a/src/modules/doctor/rules/agents.ts b/src/modules/doctor/rules/agents.ts index a4552f8..0dead2d 100644 --- a/src/modules/doctor/rules/agents.ts +++ b/src/modules/doctor/rules/agents.ts @@ -19,11 +19,14 @@ export function hashDir(dir: string): string { return hash.digest('hex') } +/** The pointer block `iapl-skills` keeps in AGENTS.md; the block written before 1.17.0 (`ipal-kit:start`, "## ipal-kit ") is read too. */ +export const POINTER_BLOCK = /[\s\S]*?## (?:IAPL|ipal-kit) ([\w.-]+) — agent guide[\s\S]*?/ + /** What `iapl-skills` would change in a skills folder: missing, stale (different content) and retired skills. */ export function planSkills({ dest, source }: { dest: string; source: string }): { missing: string[]; retired: string[]; stale: string[] } { const ls = (d: string) => { try { - return readdirSync(d).filter((n) => n.startsWith('ipal-') && statSync(join(d, n)).isDirectory()) + return readdirSync(d).filter((n) => /^(?:iapl|ipal)-/.test(n) && statSync(join(d, n)).isDirectory()) } catch { return [] } @@ -50,12 +53,12 @@ export const agentRules: DoctorRule[] = [ const body = parts[1].split(/^## /m)[0].replace(//g, '') if (!/^\s*[-*] +\S/m.test(body)) {out.push({ file: 'AGENTS.md', message: '"## Project decisions" is empty', severity: 'warning' })} } - const pointer = agents.match(/[\s\S]*?## IAPL ([\w.-]+) — agent guide[\s\S]*?/) + const pointer = agents.match(POINTER_BLOCK) if (!pointer) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec iapl-skills', message: 'no IAPL pointer block in AGENTS.md', severity: 'warning' })} else if (ctx.pluginVersion && pointer[1] !== ctx.pluginVersion) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec iapl-skills', message: `the pointer block names IAPL ${pointer[1]}, installed ${ctx.pluginVersion}`, severity: 'warning' })} const claude = ctx.read('CLAUDE.md') if (!claude) {out.push({ fix: 'pnpm exec iapl-skills (creates CLAUDE.md with @AGENTS.md)', message: 'no CLAUDE.md', severity: 'warning' })} - else if (!/^@AGENTS\.md\s*$/m.test(claude) && !claude.includes('')) {out.push({ file: 'CLAUDE.md', fix: 'add a line @AGENTS.md', message: 'CLAUDE.md neither imports AGENTS.md nor has the pointer block', severity: 'warning' })} + else if (!/^@AGENTS\.md\s*$/m.test(claude) && !//.test(claude)) {out.push({ file: 'CLAUDE.md', fix: 'add a line @AGENTS.md', message: 'CLAUDE.md neither imports AGENTS.md nor has the pointer block', severity: 'warning' })} return out }, docs: 'docs/agent/AGENT.md#13-agentsmd-template-for-a-project', @@ -65,7 +68,7 @@ export const agentRules: DoctorRule[] = [ { id: 'skills-current', check: (ctx) => { - const dest = ['.agents/skills', '.claude/skills'].find((d) => ctx.list(d).some((n) => n.startsWith('ipal-'))) + const dest = ['.agents/skills', '.claude/skills'].find((d) => ctx.list(d).some((n) => /^(?:iapl|ipal)-/.test(n))) if (!dest) {return [{ fix: 'pnpm exec iapl-skills', message: 'no iapl-* skills in .agents/skills or .claude/skills', severity: 'error' }]} // Compare with the skills the project's installed plugin ships (what `pnpm exec iapl-skills` copies). const installedSkills = join(ctx.root, 'node_modules/@intecion/ipal-kit/docs/agent/skills') diff --git a/src/modules/doctor/rules/env.ts b/src/modules/doctor/rules/env.ts index 06c467c..43a39e8 100644 --- a/src/modules/doctor/rules/env.ts +++ b/src/modules/doctor/rules/env.ts @@ -54,7 +54,7 @@ export const envRules: DoctorRule[] = [ return [{ file, fix: "register(): assertEnv(iaplEnvRules({ storage: true, ipHeader: true })) from '@intecion/ipal-kit/env'", message: 'instrumentation.ts does not call assertEnv(iaplEnvRules(…))', severity: 'error' }] } const out: RuleFinding[] = [] - if (!/iaplEnvRules\s*\(/.test(code)) {out.push({ file, message: 'assertEnv without iaplEnvRules — the plugin variables are not checked', severity: 'warning' })} + if (!/\b(?:iaplEnvRules|ipalEnvRules)\s*\(/.test(code)) {out.push({ file, message: 'assertEnv without iaplEnvRules — the plugin variables are not checked', severity: 'warning' })} if (/from\s+['"]@intecion\/ipal-kit['"]/.test(code)) {out.push({ file, fix: "import from '@intecion/ipal-kit/env'", message: 'instrumentation.ts imports the package root (Edge build breaks)', severity: 'error' })} const cfg = stripComments(ctx.read(configFile(ctx) ?? '')) const flag = (name: string) => new RegExp(`\\b${name}\\s*:`).test(code) diff --git a/src/modules/doctor/rules/layout.ts b/src/modules/doctor/rules/layout.ts index 9ab043e..8589c1e 100644 --- a/src/modules/doctor/rules/layout.ts +++ b/src/modules/doctor/rules/layout.ts @@ -243,7 +243,7 @@ export const layoutRules: DoctorRule[] = [ { id: 'tsconfig-skills', check: (ctx) => { - const dirs = ['.agents', '.claude'].filter((d) => ctx.list(`${d}/skills`).some((n) => n.startsWith('ipal-'))) + const dirs = ['.agents', '.claude'].filter((d) => ctx.list(`${d}/skills`).some((n) => /^(?:iapl|ipal)-/.test(n))) if (!dirs.length || !ctx.exists('tsconfig.json')) {return []} const exclude = ctx.read('tsconfig.json').replace(/\s/g, '').match(/"exclude":\[([^\]]*)\]/)?.[1] ?? '' const missing = dirs.filter((d) => !new RegExp(`"(?:\\./)?${d.replace('.', '\\.')}(?:/[^"]*)?"`).test(exclude)) diff --git a/src/modules/doctor/rules/legacy.ts b/src/modules/doctor/rules/legacy.ts new file mode 100644 index 0000000..e215c04 --- /dev/null +++ b/src/modules/doctor/rules/legacy.ts @@ -0,0 +1,133 @@ +import type { DoctorRule, RuleFinding } from '../types.js' + +import { legacyEnvName } from '../../shared/envName.js' +import { configFile, DOCTOR_CONFIG_FILES } from '../project.js' +import { stripComments } from '../util.js' + +/** The 16 skills shipped as `ipal-` before 1.17.0 (now `iapl-`). `iapl-skills` removes exactly these. */ +export const LEGACY_SKILL_NAMES = [ + 'audit', 'block', 'collection', 'consent-check', 'debug', 'doctor', 'form', 'locale-add', + 'migrate-fields', 'nav', 'plugin-gap', 'reference', 'seo-check', 'setup', 'site', 'upgrade', +].map((name) => `ipal-${name}`) + +/** Exported names before 1.17.0 → the names since. Both work through 1.x. */ +export const LEGACY_EXPORTS: Record = { + IPAL_BREAKPOINTS: 'IAPL_BREAKPOINTS', + IPAL_TOKENS: 'IAPL_TOKENS', + IpalEnvFeatures: 'IaplEnvFeatures', + ipalEnvRules: 'iaplEnvRules', + IpalGlobalSlug: 'IaplGlobalSlug', + ipalKit: 'iapl', + IpalOptions: 'IaplOptions', + ipalT: 'iaplT', + IpalTokenName: 'IaplTokenName', + ipalVar: 'iaplVar', +} + +/** Commands before 1.17.0 → the commands since. */ +export const LEGACY_COMMANDS: Record = { + 'ipal-blocks': 'iapl-blocks', + 'ipal-doctor': 'iapl-doctor', + 'ipal-kit': 'iapl', + 'ipal-skills': 'iapl-skills', + 'ipal-tokens': 'iapl-tokens', +} + +/** The plugin's runtime variables: `IAPL_`, read as `IPAL_` too. */ +export const PLUGIN_ENV_NAMES = [ + 'IAPL_COOKIE_SCAN_TOKEN', 'IAPL_COOKIE_SCAN_URL', 'IAPL_DOCTOR_IMPORT_MAP', 'IAPL_DOCTOR_TOKEN', + 'IAPL_IP_HEADER', 'IAPL_NOINDEX', 'IAPL_SEED_ALLOW_FULL', 'IAPL_SEED_ALLOW_PROD_UPDATE', +] + +/** + * `legacy-names`: names from before the rename to IAPL (1.17.0) that the project still uses. + * Every one of them keeps working through 1.x, so this is information, not a defect: the project + * moves when its owner asks (the iapl-upgrade skill, "→ 1.17.0"). The two cases that are more + * than information are a warning: both doctor files present, and one variable set under both + * spellings with different values (the new spelling is the one read). + */ +export const legacyRules: DoctorRule[] = [ + { + id: 'legacy-names', + check: (ctx) => { + const out: RuleFinding[] = [] + const info = (message: string, fix: string, file?: string) => out.push({ ...(file ? { file } : {}), fix, message, severity: 'info' }) + + if (DOCTOR_CONFIG_FILES.every((name) => ctx.exists(name))) { + out.push({ fix: 'merge ipal-doctor.json into iapl-doctor.json and delete it', message: 'both iapl-doctor.json and ipal-doctor.json exist — only iapl-doctor.json is read', severity: 'warning' }) + } else if (ctx.exists('ipal-doctor.json')) { + info('the doctor file has its name from before 1.17.0', 'optional: rename ipal-doctor.json to iapl-doctor.json', 'ipal-doctor.json') + } + + for (const file of [configFile(ctx), ctx.exists(`${ctx.src}instrumentation.ts`) ? `${ctx.src}instrumentation.ts` : 'instrumentation.ts']) { + const code = file ? stripComments(ctx.read(file)) : '' + const used = Object.keys(LEGACY_EXPORTS).filter((name) => new RegExp(`\\b${name}\\b`).test(code)) + if (used.length) {info(`uses ${used.join(', ')}`, `optional: ${used.map((name) => `${name} → ${LEGACY_EXPORTS[name]}`).join(', ')}`, file!)} + } + + const scripts = Object.entries((ctx.pkg.scripts ?? {})) + const commands = Object.keys(LEGACY_COMMANDS).filter((name) => scripts.some(([, command]) => new RegExp(`(? `${name} → ${LEGACY_COMMANDS[name]}`).join(', ')}`, 'package.json')} + + for (const [label, env] of [['.env.example', ctx.env.example], ['.env', ctx.env.local], ['--env-file', ctx.env.prod]] as const) { + if (!env) {continue} + const old = PLUGIN_ENV_NAMES.filter((name) => env[legacyEnvName(name)!] !== undefined) + const clash = old.filter((name) => env[name] !== undefined && env[name] !== env[legacyEnvName(name)!]) + if (clash.length) {out.push({ fix: `keep ${clash.join(', ')} and remove the IPAL_ spelling`, message: `${label}: ${clash.map((name) => `${name} and ${legacyEnvName(name)}`).join('; ')} are both set, with different values — the IAPL_ one is read`, severity: 'warning' })} + const only = old.filter((name) => !clash.includes(name) && env[name] === undefined) + if (only.length) {info(`${label} sets ${only.map((name) => legacyEnvName(name)).join(', ')}`, `optional: ${only.map((name) => `${legacyEnvName(name)} → ${name}`).join(', ')}`)} + } + + const agents = `${ctx.read('AGENTS.md')}\n${ctx.read('CLAUDE.md')}` + if (//.test(agents)) {info('the agent pointer block is the one from before 1.17.0', 'pnpm exec iapl-skills (rewrites the block in place)', 'AGENTS.md')} + if (/^[-* ]*ipal-audit-skip:/im.test(agents)) {info('ipal-audit-skip lines', 'optional: ipal-audit-skip → iapl-audit-skip', 'AGENTS.md')} + + for (const dir of ['.agents/skills', '.claude/skills']) { + const old = ctx.list(dir).filter((name) => LEGACY_SKILL_NAMES.includes(name)) + if (old.length) {info(`${old.length} skill folder(s) named ipal-* (from before 1.17.0)`, 'pnpm exec iapl-skills (installs iapl-*, removes these) and commit', dir)} + } + return out + }, + docs: 'docs/agent/AGENT.md#names-iapl-and-ipal-kit', + group: 'agents', + source: 'static', + }, + { + // The cookie the layout sets and the cookie the scanner declares must be the same one. + id: 'storage-names', + check: (ctx) => { + const cfg = stripComments(ctx.read(configFile(ctx) ?? '')) + const declared = /\bstorageNames\s*:\s*['"]iapl['"]/.test(cfg) ? 'iapl_vid' : 'ipal_vid' + const files: string[] = [] + const walk = (dir: string, depth: number) => { + for (const name of ctx.list(dir)) { + if (files.length >= 600 || name === 'node_modules' || name.startsWith('.')) {continue} + if (/\.tsx$/.test(name)) {files.push(`${dir}/${name}`)} + else if (!name.includes('.') || /^\(.*\)$|^\[.*\]$/.test(name)) {if (depth < 8) {walk(`${dir}/${name}`, depth + 1)}} + } + } + walk(`${ctx.src}app`, 0) + walk(`${ctx.src}components`, 0) + const out: RuleFinding[] = [] + for (const file of files) { + const code = stripComments(ctx.read(file)) + if (!/]*\bstats\b/.test(code)) {continue} + const set = /\bIAPL_VISITOR_COOKIE\b|['"]iapl_vid['"]/.test(code) ? 'iapl_vid' : /\bvisitorCookie\b/.test(code) ? null : 'ipal_vid' + if (set && set !== declared) { + out.push({ + file, + fix: declared === 'iapl_vid' + ? "pass visitorCookie={IAPL_VISITOR_COOKIE} (from '@intecion/ipal-kit/client') to / " + : "set iapl({ storageNames: 'iapl' }) in the config, or drop visitorCookie — one name per site (docs/stats.md)", + message: `the page sets the visitor cookie ${set}, the cookie scanner declares ${declared}`, + severity: 'warning', + }) + } + } + return out + }, + docs: 'docs/stats.md', + group: 'security', + source: 'static', + }, +] diff --git a/src/modules/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts index ad49f77..e6fb1c2 100644 --- a/src/modules/doctor/rules/security.ts +++ b/src/modules/doctor/rules/security.ts @@ -146,7 +146,7 @@ export const securityRules: DoctorRule[] = [ id: 'access-missing', check: (ctx) => { const code = cfg(ctx) - if (!/iapl\s*\(/.test(code)) {return []} + if (!/\b(?:iapl|ipalKit)\s*\(/.test(code)) {return []} // `access: { authCollection | defaultRole | … }`, an empty `access: {}`, or a variable whose name says so const set = /\baccess\s*:\s*\{\}/.test(code.replace(/\s+/g, '')) || /\baccess\s*:\s*\{[^{}]*\b(?:authCollection|defaultRole|authAccess|firstUserAdmin|staffCollections|panelRole|selfRegistration|password)\b/.test(code) || /\baccess\s*:\s*\w*[aA]ccess\w*\s*[,}]/.test(code) return set diff --git a/src/modules/doctor/run.ts b/src/modules/doctor/run.ts index 5f8c218..0bf7ac9 100644 --- a/src/modules/doctor/run.ts +++ b/src/modules/doctor/run.ts @@ -4,11 +4,13 @@ import { pathToFileURL } from 'node:url' import type { DoctorConfig, DoctorFinding, DoctorReport, DoctorRule, DoctorSeverity, DoctorStatus, RuleFinding } from './types.js' -import { createDoctorContext, type DoctorContext, loadDoctorConfig } from './project.js' +import { readEnv } from '../shared/envName.js' +import { createDoctorContext, doctorConfigFile, type DoctorContext, loadDoctorConfig } from './project.js' import { agentRules } from './rules/agents.js' import { blockRules } from './rules/blocks.js' import { envRules } from './rules/env.js' import { layoutRules } from './rules/layout.js' +import { legacyRules } from './rules/legacy.js' import { createLiveFetcher, liveRules } from './rules/live.js' import { securityRules } from './rules/security.js' import { seedRules } from './rules/seeds.js' @@ -32,6 +34,7 @@ export const doctorRules: DoctorRule[] = [ ...envRules, ...securityRules, ...agentRules, + ...legacyRules, ...seedRules, ...blockRules, ...toolingRules, @@ -111,9 +114,9 @@ export function applySettings(findings: DoctorFinding[], ctx: DoctorContext): Do const out: DoctorFinding[] = [] for (const [id, s] of Object.entries(settings)) { if (!s || typeof s !== 'object') {continue} - if (!s.reason?.trim()) {out.push({ fix: 'add "reason": "" — an entry without one is ignored', message: `iapl-doctor.json: rule "${id}" has no reason, so it is ignored`, rule: 'doctor-config', severity: 'error', source: 'static' })} - else if (s.severity && !SEVERITIES.includes(s.severity)) {out.push({ message: `iapl-doctor.json: rule "${id}" has an unknown severity "${s.severity}"`, rule: 'doctor-config', severity: 'error', source: 'static' })} - else if (s.until && ctx.today > s.until) {out.push({ fix: 'fix the finding, or extend "until" with a new reason', message: `iapl-doctor.json: the setting for "${id}" expired on ${s.until}`, rule: 'doctor-config', severity: 'warning', source: 'static' })} + if (!s.reason?.trim()) {out.push({ fix: 'add "reason": "" — an entry without one is ignored', message: `${doctorConfigFile(ctx.root)}: rule "${id}" has no reason, so it is ignored`, rule: 'doctor-config', severity: 'error', source: 'static' })} + else if (s.severity && !SEVERITIES.includes(s.severity)) {out.push({ message: `${doctorConfigFile(ctx.root)}: rule "${id}" has an unknown severity "${s.severity}"`, rule: 'doctor-config', severity: 'error', source: 'static' })} + else if (s.until && ctx.today > s.until) {out.push({ fix: 'fix the finding, or extend "until" with a new reason', message: `${doctorConfigFile(ctx.root)}: the setting for "${id}" expired on ${s.until}`, rule: 'doctor-config', severity: 'warning', source: 'static' })} } const skips = new Map() for (const [key, reason] of ctx.auditSkips) { @@ -153,7 +156,7 @@ export async function runDoctor(options: RunDoctorOptions): Promise= 32) {ctx.deep = await fetchDeepStatus(options.url, token)} @@ -182,9 +185,9 @@ export async function runDoctor(options: RunDoctorOptions): Promise f.rule === 'csp' && /report-only/.test(f.message)) && !ctx.config.seen?.['csp-report-only'] && existsSync(join(root, 'iapl-doctor.json'))) { + if (writeSeen && findings.some((f) => f.rule === 'csp' && /report-only/.test(f.message)) && !ctx.config.seen?.['csp-report-only'] && existsSync(join(root, doctorConfigFile(root)))) { const current = loadDoctorConfig(root).config - writeFileSync(join(root, 'iapl-doctor.json'), `${JSON.stringify({ ...current, seen: { ...current.seen, 'csp-report-only': ctx.today } }, null, 2)}\n`) + writeFileSync(join(root, doctorConfigFile(root)), `${JSON.stringify({ ...current, seen: { ...current.seen, 'csp-report-only': ctx.today } }, null, 2)}\n`) } const final = applySettings(findings, ctx).sort((a, b) => Number(!!a.silenced) - Number(!!b.silenced) || RANK[a.severity] - RANK[b.severity]) diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index 244d9c8..b0b5a64 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -10,6 +10,7 @@ import { countPendingCookies } from '../consent/scanner/approval.js' import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js' import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js' import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js' +import { readEnv } from '../shared/envName.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { turnstileSecretFromEnv } from '../turnstile/config.js' @@ -101,7 +102,7 @@ export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoi const tokenVar = options.tokenVar ?? 'IAPL_DOCTOR_TOKEN' return { handler: async (req: PayloadRequest) => { - const token = process.env[tokenVar]?.trim() ?? '' + const token = (options.tokenVar ? process.env[tokenVar] : readEnv(tokenVar))?.trim() ?? '' if (token.length < 32) {return Response.json({ error: 'Not found' }, { status: 404 })} const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'iapl-doctor', windowMs: 60_000 }) if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests' })} diff --git a/src/modules/env/assertEnv.ts b/src/modules/env/assertEnv.ts index b7eb2cb..f653fbb 100644 --- a/src/modules/env/assertEnv.ts +++ b/src/modules/env/assertEnv.ts @@ -10,6 +10,11 @@ export type EnvKind = 'boolean' | 'email' | 'number' | 'port' | 'string' | 'url' export type EnvRule = { + /** + * Older names of the same variable, read when `name` is missing or empty + * (e.g. `IPAL_IP_HEADER` for `IAPL_IP_HEADER`). Messages always use `name`. + */ + aliases?: readonly string[] /** Shown in the error to tell the deployer what the var is for. */ description?: string /** Shape check applied when a value is present. Default 'string' (non-empty). */ @@ -106,7 +111,7 @@ export function assertEnv(rules: EnvRule[], options: AssertEnvOptions = {}): voi const problems: string[] = [] for (const rule of rules) { - const raw = env[rule.name] + const raw = [rule.name, ...(rule.aliases ?? [])].map((key) => env[key]).find((v) => typeof v === 'string' && v.trim() !== '') const value = typeof raw === 'string' ? raw.trim() : '' const required = rule.required !== false diff --git a/src/modules/env/iaplEnvRules.ts b/src/modules/env/iaplEnvRules.ts index e52c2db..91297b9 100644 --- a/src/modules/env/iaplEnvRules.ts +++ b/src/modules/env/iaplEnvRules.ts @@ -148,7 +148,7 @@ export function iaplEnvRules(features: IaplEnvFeatures = {}): EnvRule[] { if (ipHeader) { rules.push({ - name: 'IAPL_IP_HEADER', + name: 'IAPL_IP_HEADER', aliases: ['IPAL_IP_HEADER'], description: 'Header holding the real client IP, e.g. cf-connecting-ip (Cloudflare) or x-forwarded-for', required: process.env.NODE_ENV === 'production', validate: (v) => (/^[a-z0-9-]+$/i.test(v) ? true : `IAPL_IP_HEADER must be a header name (got "${v}")`), @@ -158,9 +158,9 @@ export function iaplEnvRules(features: IaplEnvFeatures = {}): EnvRule[] { if (cookieCrawl) { const required = process.env.NODE_ENV === 'production' rules.push( - { name: 'IAPL_COOKIE_SCAN_URL', description: 'Cookie crawler service base URL, e.g. https://cookie-crawler.example.com', kind: 'url', required }, + { name: 'IAPL_COOKIE_SCAN_URL', aliases: ['IPAL_COOKIE_SCAN_URL'], description: 'Cookie crawler service base URL, e.g. https://cookie-crawler.example.com', kind: 'url', required }, { - name: 'IAPL_COOKIE_SCAN_TOKEN', + name: 'IAPL_COOKIE_SCAN_TOKEN', aliases: ['IPAL_COOKIE_SCAN_TOKEN'], description: 'Token shared with the cookie crawler (this site\'s entry in IAPL_CRAWLER_SITES)', required, validate: (v) => (v.length >= 16 ? true : 'IAPL_COOKIE_SCAN_TOKEN must be at least 16 characters'), @@ -199,3 +199,9 @@ export function iaplEnvRules(features: IaplEnvFeatures = {}): EnvRule[] { return rules } + +/** @deprecated The name before 1.17.0; the same function as `iaplEnvRules`. Removed in 2.0. */ +export const ipalEnvRules = iaplEnvRules + +/** @deprecated The name before 1.17.0; the same type as `IaplEnvFeatures`. Removed in 2.0. */ +export type IpalEnvFeatures = IaplEnvFeatures diff --git a/src/modules/env/index.ts b/src/modules/env/index.ts index cb87e3a..c62188a 100644 --- a/src/modules/env/index.ts +++ b/src/modules/env/index.ts @@ -1,5 +1,5 @@ export { assertEnv } from './assertEnv.js' export type { AssertEnvOptions, EnvKind, EnvRule } from './assertEnv.js' export { checkDatabaseName, databaseNameFromUri, databaseNamesFor } from './databaseName.js' -export { iaplEnvRules } from './iaplEnvRules.js' -export type { IaplEnvFeatures } from './iaplEnvRules.js' +export { iaplEnvRules, ipalEnvRules } from './iaplEnvRules.js' +export type { IaplEnvFeatures, IpalEnvFeatures } from './iaplEnvRules.js' diff --git a/src/modules/security/totp/verifyLimit.ts b/src/modules/security/totp/verifyLimit.ts index 4a336db..d4b8547 100644 --- a/src/modules/security/totp/verifyLimit.ts +++ b/src/modules/security/totp/verifyLimit.ts @@ -27,6 +27,13 @@ import { serverText } from '../../integrations/texts.js' * Requests a browser marks as coming from another origin never get here (sameOrigin.ts). */ export type VerifyLimitOptions = { + /** + * First part of the count's key in `payload.kv`: `:2fa-verify::`. + * Default `'ipal'`, the key every site made before 1.17.0 has; `iapl({ storageNames: 'iapl' })` + * (new sites) makes it `'iapl'`. One prefix per site: changing it on a live site starts the + * running counts from zero once. + */ + keyPrefix?: string /** Attempts per account in the window. Default 5. */ max?: number /** Where the count is kept besides the instance's memory. Default `'database'`; `'memory'` = this instance only. */ @@ -47,7 +54,7 @@ type KV = { get: (key: string) => Promise; set: (key: string, value: ob let warnedStore = false /** Key of an account's stored count in `payload.kv`. */ -export const verifyLimitKey = (collection: string, id: string) => `ipal:2fa-verify:${collection}:${id}` +export const verifyLimitKey = (collection: string, id: string, keyPrefix = 'ipal') => `${keyPrefix}:2fa-verify:${collection}:${id}` /** Counts one attempt in the database and returns the stored bucket; null when there is no store or it fails. */ async function hitStored(payload: { kv?: unknown; logger?: { warn: (m: string) => void } }, key: string, windowMs: number, now: number): Promise { @@ -72,6 +79,7 @@ export function buildVerifyLimit(collection: string, options: VerifyLimitOptions const max = Number.isFinite(options.max) && options.max! > 0 ? Math.floor(options.max!) : 5 const windowMs = (Number.isFinite(options.windowMinutes) && options.windowMinutes! > 0 ? options.windowMinutes! : 10) * 60_000 const stored = options.store !== 'memory' + const keyPrefix = typeof options.keyPrefix === 'string' && options.keyPrefix.trim() ? options.keyPrefix.trim() : 'ipal' return async (req: PayloadRequest): Promise => { // No session: the package refuses by itself, and there is no account to count against. @@ -94,7 +102,7 @@ export function buildVerifyLimit(collection: string, options: VerifyLimitOptions // This attempt's own number, taken now: the bucket is shared and keeps growing while we wait below. const mine: Bucket = { count: bucket.count, resetAt: bucket.resetAt } // …and in the database, so a restart or another instance does not start from zero. The higher count decides. - const kept = stored ? await hitStored(req.payload as never, verifyLimitKey(collection, id), windowMs, now) : null + const kept = stored ? await hitStored(req.payload as never, verifyLimitKey(collection, id, keyPrefix), windowMs, now) : null const worst = kept && kept.count > mine.count ? kept : mine if (worst.count <= max) {return null} const retryAfter = Math.max(1, Math.ceil((worst.resetAt - now) / 1000)) diff --git a/src/modules/seed/seeder.ts b/src/modules/seed/seeder.ts index dfec7c1..f71c7a7 100644 --- a/src/modules/seed/seeder.ts +++ b/src/modules/seed/seeder.ts @@ -2,6 +2,7 @@ import type { BasePayload } from 'payload' import type { SeedTarget } from './values.js' +import { readEnv } from '../shared/envName.js' import { activeSeedExitGuard } from './exitGuard.js' import { isLocalDatabase, seedDatabaseUrl } from './guard.js' import { @@ -211,8 +212,8 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}): if (guard) { const production = guard.production ?? env.NODE_ENV === 'production' const prodLike = production || !local - const allowProdUpdate = guard.allowProdUpdate ?? env.IAPL_SEED_ALLOW_PROD_UPDATE === '1' - const allowFull = guard.allowFull ?? env.IAPL_SEED_ALLOW_FULL === '1' + const allowProdUpdate = guard.allowProdUpdate ?? readEnv('IAPL_SEED_ALLOW_PROD_UPDATE', env) === '1' + const allowFull = guard.allowFull ?? readEnv('IAPL_SEED_ALLOW_FULL', env) === '1' if (!dryRun && !only?.length && prodLike && !allowFull) { throw new Error( `${label} full seed refused: ${production ? 'NODE_ENV=production' : 'the database is not local'} and no record list.\n` + diff --git a/src/modules/seo/siteNoindex.ts b/src/modules/seo/siteNoindex.ts index a857144..b81ee74 100644 --- a/src/modules/seo/siteNoindex.ts +++ b/src/modules/seo/siteNoindex.ts @@ -1,6 +1,8 @@ +import { readEnv } from '../shared/envName.js' + /** * Whole-site noindex for staging, previews and test copies: set IAPL_NOINDEX=1 - * in that environment's env. Then robots.txt disallows everything, every page + * in that environment's env (the old spelling IPAL_NOINDEX is still read). Then robots.txt disallows everything, every page * gets `robots: noindex, nofollow`, and buildSecurityHeaders adds * `X-Robots-Tag: noindex, nofollow` to every response (files and API too). * Production never sets it — a forgotten staging copy indexed by Google is a @@ -9,6 +11,6 @@ export const SITE_NOINDEX_ENV = 'IAPL_NOINDEX' export function isSiteNoindex(): boolean { - const v = process.env[SITE_NOINDEX_ENV]?.trim().toLowerCase() + const v = readEnv(SITE_NOINDEX_ENV)?.trim().toLowerCase() return v === '1' || v === 'true' || v === 'yes' } diff --git a/src/modules/shared/envName.ts b/src/modules/shared/envName.ts new file mode 100644 index 0000000..ba141e2 --- /dev/null +++ b/src/modules/shared/envName.ts @@ -0,0 +1,24 @@ +/** + * The plugin's own environment variables are spelled `IAPL_` since 1.17.0. Before that + * they were `IPAL_`, and a deploy that still sets the old spelling keeps working: the new + * name is read first, the old one when the new one is missing or empty. Both set → the new one wins + * (iapl-doctor reports the pair when they differ). + */ +export const ENV_PREFIX = 'IAPL_' +export const LEGACY_ENV_PREFIX = 'IPAL_' + +type Env = Record + +/** `IAPL_IP_HEADER` → `IPAL_IP_HEADER`; undefined for a name that is not the plugin's. */ +export function legacyEnvName(name: string): string | undefined { + return name.startsWith(ENV_PREFIX) ? `${LEGACY_ENV_PREFIX}${name.slice(ENV_PREFIX.length)}` : undefined +} + +/** Value of a plugin variable under its new name, else under its old one. Not trimmed. */ +export function readEnv(name: string, env: Env = process.env): string | undefined { + const value = env[name] + if (typeof value === 'string' && value.trim() !== '') {return value} + const legacy = legacyEnvName(name) + const old = legacy ? env[legacy] : undefined + return typeof old === 'string' && old.trim() !== '' ? old : value +} diff --git a/src/modules/shared/rateLimit.ts b/src/modules/shared/rateLimit.ts index 27967d7..46b0839 100644 --- a/src/modules/shared/rateLimit.ts +++ b/src/modules/shared/rateLimit.ts @@ -1,3 +1,5 @@ +import { readEnv } from './envName.js' + type Bucket = { count: number; resetAt: number } /** @@ -203,7 +205,7 @@ let warnedUnpinned = false export function clientIp(source: Headers | Request, options: ClientIpOptions = {}): string { const h = source instanceof Headers ? source : source.headers - const pinned = options.header ?? process.env.IAPL_IP_HEADER + const pinned = options.header ?? readEnv('IAPL_IP_HEADER') if (!pinned && !warnedUnpinned && process.env.NODE_ENV === 'production') { warnedUnpinned = true console.warn( diff --git a/src/modules/stats/PageStats.tsx b/src/modules/stats/PageStats.tsx index fead3f0..a738e42 100644 --- a/src/modules/stats/PageStats.tsx +++ b/src/modules/stats/PageStats.tsx @@ -6,9 +6,10 @@ import { usePathname } from 'next/navigation.js' import { useConsentContext } from '../consent/ConsentContext.js' import { CONSENT_COOKIE, CONSENT_MAX_AGE, parseConsent } from '../consent/storage.js' +import { VISITOR_COOKIE } from './visitorCookie.js' -/** Visitor id cookie — set ONLY with analytics consent, deleted on withdrawal (DEFAULT_COOKIE_MAP). */ -export const VISITOR_COOKIE = 'ipal_vid' +// Visitor id cookie — set ONLY with analytics consent, deleted on withdrawal (DEFAULT_COOKIE_MAP). +export { IAPL_VISITOR_COOKIE, VISITOR_COOKIE } from './visitorCookie.js' function readCookie(name: string): string | undefined { return document.cookie @@ -17,14 +18,14 @@ function readCookie(name: string): string | undefined { ?.split('=')[1] } -function ensureVisitorId(): string { - const existing = readCookie(VISITOR_COOKIE) +function ensureVisitorId(cookie: string): string { + const existing = readCookie(cookie) if (existing && /^[0-9a-f]{32}$/.test(existing)) {return existing} const bytes = new Uint8Array(16) globalThis.crypto.getRandomValues(bytes) const id = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('') const secure = location.protocol === 'https:' ? ';secure' : '' - document.cookie = `${VISITOR_COOKIE}=${id};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}` + document.cookie = `${cookie}=${id};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}` return id } @@ -33,6 +34,12 @@ export type PageStatsProps = { endpoint?: string /** Current locale code, stored with the visit. */ locale?: string + /** + * Name of the visitor id cookie. Default `ipal_vid` (VISITOR_COOKIE). A site made with + * `iapl({ storageNames: 'iapl' })` passes IAPL_VISITOR_COOKIE (`iapl_vid`), so the cookie set + * here is the one its cookie list declares. One name per site, for good: docs/stats.md. + */ + visitorCookie?: string } /** @@ -42,12 +49,12 @@ export type PageStatsProps = { * server joins page views into a visit with a daily-salted hash it can't * reverse, and keeps no IP. * - **With analytics consent** (the same category that turns on GA4) — sets the - * `ipal_vid` cookie with a random id, so the panel can show that visitor's + * `ipal_vid` cookie (`visitorCookie`; `iapl_vid` on sites made since 1.17.0) with a random id, so the panel can show that visitor's * history across days. Withdrawing consent deletes the cookie. * * Renders nothing. Mount once in the locale layout, INSIDE . */ -export function PageStats({ endpoint = '/api/ipal/hit', locale }: PageStatsProps) { +export function PageStats({ endpoint = '/api/ipal/hit', locale, visitorCookie = VISITOR_COOKIE }: PageStatsProps) { const pathname = usePathname() const { texts } = useConsentContext() const firstHit = useRef(true) @@ -61,7 +68,7 @@ export function PageStats({ endpoint = '/api/ipal/hit', locale }: PageStatsProps if (locale) {body.l = locale} // The cookie, not context state: on a full page load this effect runs before // useConsent has read the cookie, so state would still say "no consent". - if (parseConsent(readCookie(CONSENT_COOKIE), texts.version)?.analytics) {body.v = ensureVisitorId()} + if (parseConsent(readCookie(CONSENT_COOKIE), texts.version)?.analytics) {body.v = ensureVisitorId(visitorCookie)} const json = JSON.stringify(body) if (!navigator.sendBeacon?.(endpoint, new Blob([json], { type: 'application/json' }))) { @@ -69,7 +76,7 @@ export function PageStats({ endpoint = '/api/ipal/hit', locale }: PageStatsProps } // texts.version is read, not a trigger: a policy change isn't a page view // eslint-disable-next-line react-hooks/exhaustive-deps - }, [pathname, endpoint, locale]) + }, [pathname, endpoint, locale, visitorCookie]) return null } diff --git a/src/modules/stats/client.ts b/src/modules/stats/client.ts index 644787c..fa83a39 100644 --- a/src/modules/stats/client.ts +++ b/src/modules/stats/client.ts @@ -1,3 +1,3 @@ 'use client' -export { PageStats, VISITOR_COOKIE } from './PageStats.js' +export { IAPL_VISITOR_COOKIE, PageStats, VISITOR_COOKIE } from './PageStats.js' export type { PageStatsProps } from './PageStats.js' diff --git a/src/modules/stats/visitorCookie.ts b/src/modules/stats/visitorCookie.ts new file mode 100644 index 0000000..eba677f --- /dev/null +++ b/src/modules/stats/visitorCookie.ts @@ -0,0 +1,20 @@ +/** + * Names of the visitor id cookie (set by only with analytics consent). + * + * A site has ONE of them for its whole life: + * - `ipal_vid` — every site made before 1.17.0, and the default; + * - `iapl_vid` — sites made since (the starter sets `iapl({ storageNames: 'iapl' })` + * and ``). + * Changing the name on a live site starts every visitor's history again and changes the + * site's cookie list, so it needs the list approved again — docs/stats.md. + * + * A plain module (no 'use client'): the server (cookie scanner) and the browser read the same names. + */ +export const VISITOR_COOKIE = 'ipal_vid' +export const IAPL_VISITOR_COOKIE = 'iapl_vid' + +/** Which family of stored names a site uses: `iapl({ storageNames })`. Default `'ipal'`. */ +export type StorageNames = 'iapl' | 'ipal' + +/** The visitor cookie name of a site with these storage names. */ +export const visitorCookieFor = (names: StorageNames | undefined): string => (names === 'iapl' ? IAPL_VISITOR_COOKIE : VISITOR_COOKIE) diff --git a/src/modules/tokens/catalog.ts b/src/modules/tokens/catalog.ts index c015f4c..afa27f0 100644 --- a/src/modules/tokens/catalog.ts +++ b/src/modules/tokens/catalog.ts @@ -143,3 +143,9 @@ export type IaplTokenName = `${(typeof LEGACY_DARK_ROLES)[number]}-dark` | Color /** Standard breakpoints in rem (Tailwind 4 defaults). CSS variables can't be used in `@media`. */ export const IAPL_BREAKPOINTS = { '2xl': 96, lg: 64, md: 48, sm: 40, xl: 80 } as const + +/** @deprecated The name before 1.17.0; the same object as `IAPL_BREAKPOINTS`. Removed in 2.0. */ +export const IPAL_BREAKPOINTS = IAPL_BREAKPOINTS + +/** @deprecated The name before 1.17.0; the same type as `IaplTokenName`. Removed in 2.0. */ +export type IpalTokenName = IaplTokenName diff --git a/src/modules/tokens/index.ts b/src/modules/tokens/index.ts index e04b500..e13eb78 100644 --- a/src/modules/tokens/index.ts +++ b/src/modules/tokens/index.ts @@ -1,5 +1,5 @@ -export { COLOR_DEFAULTS, FLUID_TOKENS, INVERSE_SCOPE, IAPL_BREAKPOINTS, LEGACY_DARK_ROLES, STATIC_DEFAULTS } from './catalog.js' -export type { ColorRole, IaplTokenName } from './catalog.js' +export { COLOR_DEFAULTS, FLUID_TOKENS, IAPL_BREAKPOINTS, INVERSE_SCOPE, IPAL_BREAKPOINTS, LEGACY_DARK_ROLES, STATIC_DEFAULTS } from './catalog.js' +export type { ColorRole, IaplTokenName, IpalTokenName } from './catalog.js' export { contrastRatio, parseColor } from './color.js' export { contrastReport } from './contrast.js' export type { ContrastRow } from './contrast.js' @@ -8,4 +8,4 @@ export { defineTokens, resolveColors } from './define.js' export type { ColorInput, TokensInput } from './define.js' export { FLUID_RANGES, FLUID_SCALE, fluidClamp } from './fluid.js' export type { FluidRange, RemValue } from './fluid.js' -export { IAPL_TOKENS, iaplVar } from './names.js' +export { IAPL_TOKENS, iaplVar, IPAL_TOKENS, ipalVar } from './names.js' diff --git a/src/modules/tokens/names.ts b/src/modules/tokens/names.ts index a97fc57..c43165c 100644 --- a/src/modules/tokens/names.ts +++ b/src/modules/tokens/names.ts @@ -25,3 +25,9 @@ export const IAPL_TOKENS = Object.freeze( export function iaplVar(name: IaplTokenName, fallback?: string): string { return fallback === undefined ? `var(--ipal-${name})` : `var(--ipal-${name}, ${fallback})` } + +/** @deprecated The name before 1.17.0; the same object as `IAPL_TOKENS`. Removed in 2.0. */ +export const IPAL_TOKENS = IAPL_TOKENS + +/** @deprecated The name before 1.17.0; the same function as `iaplVar`. Removed in 2.0. */ +export const ipalVar = iaplVar diff --git a/src/plugin.ts b/src/plugin.ts index 7446260..ea6013a 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -61,6 +61,7 @@ import { searchSettingsFields } from './modules/seo/searchSettings.js' import { migrateTitleSeparator } from './modules/seo/titleSeparator.js' import { applyCollectionOverride } from './modules/shared/collectionOverride.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' +import { visitorCookieFor } from './modules/stats/visitorCookie.js' /** The admin provider @clocklimited/payload-2fa registers; IAPL swaps it (twoFactor.provider). */ const TOTP_PACKAGE_PROVIDER = '@clocklimited/payload-2fa/rsc#TOTPProvider' @@ -309,7 +310,7 @@ export const iapl = (options: IaplOptions): Plugin => { // `req.user` from ANY auth collection and act on the 2FA collection by id. // Only accounts of the 2FA collection may use them (guardTotpEndpoint) — // whatever the package registered, also paths a later version adds. - const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, tf.verifyLimit) + const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, { ...(options.storageNames === 'iapl' ? { keyPrefix: 'iapl' } : {}), ...tf.verifyLimit }) const extraOrigins = typeof tf.sameOrigin === 'object' ? (tf.sameOrigin.origins ?? []) : [] const guards = { ...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}), @@ -767,7 +768,7 @@ export const iapl = (options: IaplOptions): Plugin => { ...(config.collections ?? []), applyCollectionOverride(hideFromNav(withFillLocales('collection', buildCookieReviewCollection(scannerOptions), fillLocales['cookie-review'])), scannerOptions.collectionOverrides), ] - const scanPlugin = { localeCount: options.i18n.locales.length, stats: Boolean(options.stats), ...(options.theme?.storageKey ? { themeStorageKey: options.theme.storageKey } : {}) } + const scanPlugin = { localeCount: options.i18n.locales.length, stats: Boolean(options.stats), visitorCookie: visitorCookieFor(options.storageNames), ...(options.theme?.storageKey ? { themeStorageKey: options.theme.storageKey } : {}) } config.endpoints = [...(config.endpoints ?? []), ...buildCookieScanEndpoints(scannerOptions, scanPlugin)] // One approval for everything found (default on): the "Approve cookies" view and its endpoint. const approval = scannerOptions.approval === false ? null : (scannerOptions.approval ?? {}) @@ -1002,3 +1003,6 @@ export const iapl = (options: IaplOptions): Plugin => { return config } } + +/** @deprecated The name before 1.17.0; the same function as `iapl`. Removed in 2.0. */ +export const ipalKit = iapl diff --git a/src/types.ts b/src/types.ts index 35cbf5c..a59d740 100644 --- a/src/types.ts +++ b/src/types.ts @@ -28,6 +28,7 @@ import type { RequireSetupOptions } from './modules/security/totp/setupRequired. import type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js' import type { SeoOption } from './modules/seo/types.js' import type { StatsOptions } from './modules/stats/collection.js' +import type { StorageNames } from './modules/stats/visitorCookie.js' /** * Configuration options for the IAPL plugin. @@ -236,6 +237,20 @@ export type IaplOptions = { */ stats?: boolean | StatsOptions + /** + * Which spelling the two stored names of the plugin have on this site (docs/stats.md, + * docs/security.md): the visitor cookie (`ipal_vid` / `iapl_vid`) as the cookie scanner + * declares it, and the 2FA attempt counter's key in `payload.kv` + * (`ipal:2fa-verify:…` / `iapl:2fa-verify:…`). + * + * Default `'ipal'` — what every site made before 1.17.0 has, so an upgrade changes nothing. + * The starter sets `'iapl'` for a new site, together with + * `` in the layout. + * Decide once: on a live site a change starts visitors' histories and the running 2FA counts + * again, and the cookie list has to be approved again. + */ + storageNames?: StorageNames + /** * Light / dark theme. `storageKey`: the localStorage key of the visitor's * choice — default `theme` (the next-themes key and values, so a project using @@ -419,3 +434,6 @@ export type ThemeOptions = { /** localStorage key of the visitor's light / dark choice. Default `'theme'`. */ storageKey?: string } + +/** @deprecated The name before 1.17.0; the same type as `IaplOptions`. Removed in 2.0. */ +export type IpalOptions = IaplOptions diff --git a/test/legacyNames.test.ts b/test/legacyNames.test.ts new file mode 100644 index 0000000..b663100 --- /dev/null +++ b/test/legacyNames.test.ts @@ -0,0 +1,313 @@ +/** + * 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 }) + }) +})