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; <PageStats visitorCookie>, IAPL_VISITOR_COOKIE, verifyLimit.keyPrefix - test/legacyNames.test.ts: 24 tests for all of the above Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
0a4f001797
commit
425fac14fb
@@ -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'
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"]',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -17,7 +17,7 @@ export type ConsentCookieMap = Partial<Record<ConsentCategory, string[]>>
|
||||
* projects add theirs through <ConsentProvider cookieMap> (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'],
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<string, string> {
|
||||
const out = new Map<string, string>()
|
||||
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<string, string> {
|
||||
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)})` }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 <version>") is read too. */
|
||||
export const POINTER_BLOCK = /<!-- (?:iapl|ipal-kit):start -->[\s\S]*?## (?:IAPL|ipal-kit) ([\w.-]+) — agent guide[\s\S]*?<!-- (?:iapl|ipal-kit):end -->/
|
||||
|
||||
/** 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(/<!--[\s\S]*?-->/g, '')
|
||||
if (!/^\s*[-*] +\S/m.test(body)) {out.push({ file: 'AGENTS.md', message: '"## Project decisions" is empty', severity: 'warning' })}
|
||||
}
|
||||
const pointer = agents.match(/<!-- iapl:start -->[\s\S]*?## IAPL ([\w.-]+) — agent guide[\s\S]*?<!-- iapl:end -->/)
|
||||
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('<!-- iapl:start -->')) {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) && !/<!-- (?:iapl|ipal-kit):start -->/.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')
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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-<name>` before 1.17.0 (now `iapl-<name>`). `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<string, string> = {
|
||||
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<string, string> = {
|
||||
'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_<NAME>`, read as `IPAL_<NAME>` 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(`(?<![\\w@/.-])${name}(?![\\w/-])`).test(command)))
|
||||
if (commands.length) {info(`package.json scripts call ${commands.join(', ')}`, `optional: ${commands.map((name) => `${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 (/<!-- ipal-kit:start -->/.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 (!/<PageStats\b|<SiteProviders\s[^>]*\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 <PageStats> / <SiteProviders stats={{ … }}>"
|
||||
: "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',
|
||||
},
|
||||
]
|
||||
@@ -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
|
||||
|
||||
@@ -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": "<why>" — 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": "<why>" — 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<string, string>()
|
||||
for (const [key, reason] of ctx.auditSkips) {
|
||||
@@ -153,7 +156,7 @@ export async function runDoctor(options: RunDoctorOptions): Promise<DoctorReport
|
||||
const ctx = createDoctorContext({ config: options.config, envFile: options.envFile, live, offline: options.offline, packageRoot: options.packageRoot, root, today: options.today })
|
||||
|
||||
// Deep status: the probe (--deep), the endpoint (--url + IAPL_DOCTOR_TOKEN), or none.
|
||||
const token = process.env.IAPL_DOCTOR_TOKEN?.trim()
|
||||
const token = readEnv('IAPL_DOCTOR_TOKEN')?.trim()
|
||||
if (options.deepStatus !== undefined) {ctx.deep = options.deepStatus}
|
||||
else if (options.deep) {ctx.deep = runDeepProbe({ ...ctx, root })}
|
||||
else if (options.url && token && token.length >= 32) {ctx.deep = await fetchDeepStatus(options.url, token)}
|
||||
@@ -182,9 +185,9 @@ export async function runDoctor(options: RunDoctorOptions): Promise<DoctorReport
|
||||
|
||||
// First-seen dates (CSP report-only → warning after 4 weeks): stored outside CI when the file exists.
|
||||
const writeSeen = options.writeSeen ?? !process.env.CI
|
||||
if (writeSeen && findings.some((f) => 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])
|
||||
|
||||
@@ -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' })}
|
||||
|
||||
Vendored
+6
-1
@@ -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
|
||||
|
||||
|
||||
Vendored
+9
-3
@@ -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
|
||||
|
||||
Vendored
+2
-2
@@ -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'
|
||||
|
||||
@@ -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`: `<keyPrefix>:2fa-verify:<collection>:<id>`.
|
||||
* 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<unknown>; 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<Bucket | null> {
|
||||
@@ -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<null | Response> => {
|
||||
// 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))
|
||||
|
||||
@@ -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` +
|
||||
|
||||
@@ -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'
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* The plugin's own environment variables are spelled `IAPL_<NAME>` since 1.17.0. Before that
|
||||
* they were `IPAL_<NAME>`, 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<string, string | undefined>
|
||||
|
||||
/** `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
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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 <ConsentProvider>.
|
||||
*/
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Names of the visitor id cookie (set by <PageStats> 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 `<PageStats visitorCookie={IAPL_VISITOR_COOKIE} />`).
|
||||
* 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)
|
||||
@@ -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
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user