Compare commits

..
202 Commits
Author SHA1 Message Date
Radosław SmolińskiandClaude Opus 5.5 fc70a34f3e 1.17.1 notes: the sending method (PROGRAMISTA 82, the upgrade skill's item number, one stray bold mark)
CI / check (push) Failing after 6m56s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 23:27:59 +01:00
Radosław SmolińskiandClaude Opus 5.5 344b84f9fc Merge claude/mail-transport-choice: "Sending method" is an explicit choice in the panel (IWSN, own SMTP, Graph); nothing changes until another option is picked
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 23:27:36 +01:00
Radosław SmolińskiandClaude Fable 5.2 dc3e594d38 Sending method, the owner's answers: nothing changes until another option is picked; the panel warns before the save
- a save that sends the method already shown, while nothing is stored, stores nothing: the site keeps sending
  exactly as before and keeps following what is filled in, until somebody picks ANOTHER option
- the state block reads the form as it is edited and warns at once when "Own SMTP server" is picked with server,
  user name or password empty, or "Microsoft Graph" on a server without GRAPH_* (graphReady in the panel state);
  it reloads after every save
- texts, doctor's info finding, docs, skills, changelog; reference e2e checks the warning

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 23:15:42 +01:00
Radosław SmolińskiandClaude Fable 5.2 8c19391590 Sending method, review M-1 and M-2: the plugin's own status write never stores a choice; a non-method is refused
- M-1: the save rule of `emailMethod` ran after the early return for the plugin's status writes, so the first
  failed (or recovered) send stored the method the read showed as if an admin had chosen it. The rule is now a
  hook of its own that runs on every write: a write that does not name the method leaves what is stored, empty
  included.
- M-2: a sent value that is not null or one of the three methods (a number, a list, another word) is refused
  with a ValidationError (400) before it reaches the database.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 23:08:34 +01:00
Radosław SmolińskiandClaude Fable 5.2 f2da28e7cb Reference site: generated types with the field emailMethod
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 22:48:42 +01:00
Radosław SmolińskiandClaude Fable 5.2 ee8ea42956 E-mail: "Sending method" is an explicit choice - IWSN (built-in), Own SMTP server, Microsoft Graph (deprecated)
What is chosen is what is used. The choice is the stored field `emailMethod` of Site integrations (empty until
somebody chooses); `emailTransport` of 1.6 - 1.17.0 stays, hidden.

- no silent switch: a chosen method that cannot be used (SMTP incomplete, Graph without GRAPH_*) fails loudly
  - status smtp-incomplete / graph-not-set-up, state block, doctor mail-method - and nothing is sent another way
- upgrade writes nothing and loses no mail: until somebody chooses, the order of 1.17.0 applies and the field
  shows its result as selected; the first save of the panel's form stores the choice
- only the chosen method's fields are shown; the test e-mail names the method (Graph too)
- mail: { relay: false } does not offer "IWSN" (the stored values stay three: one SQL enum for every project)
- Postgres / SQLite: one migration (a column). Before it runs the plugin's readers read the global without the
  field, mail goes the old way, one loud log line and the doctor say what to do
- getMailMethod, setMailMethod, resolveMailMethod, readMailSettings, mailMethodColumnMissing exported
- tests on SQLite, Postgres and MongoDB, with and without the migration; docs, AGENT.md, skills, changelog

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 22:39:03 +01:00
Radosław SmolińskiandClaude Fable 5.2 c6841a1674 WIP: sending method as an explicit choice, kept in payload-kv (superseded: the choice moves to a stored field)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 22:30:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 726f028e9f 1.17.1 notes: the sign-in logo as 1.17.0 shows it (an SVG too, no plate)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 22:27:17 +01:00
Radosław SmolińskiandClaude Opus 5.5 1f65e1c97f Merge claude/login-page-whitelabel-616f3d: the sign-in logo as 1.17.0's login screen shows it (SVG as an image, no plate)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 22:26:57 +01:00
Radosław SmolińskiandClaude Fable 5.2 24ccc5dc8b Sign-in look: the logo is handled as the white label handled it in 1.17.0 (owner, 2026-11-26)
A logo that showed on a site's login screen shows on the new screens: any picture Site settings holds,
an SVG included, as <img>; svgLogo: false refuses SVG (off by default); the list of allowed types is
gone. The look at the file only avoids a broken picture: a file that is gone (404 / 410) or is no picture
gives the name; anything else (no answer, a redirect, another status, over 512 KB) believes the upload.
Redirects are still never followed by the server, and the body is read with the 512 KB cap. A test
checks twelve kinds of logo that 1.17.0 shows. No plate stays the default. Docs, skills, changelog draft.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 22:14:50 +01:00
Radosław SmolińskiandClaude Opus 5.5 68a2555277 1.17.1 upgrade notes
PROGRAMISTA §6 rows 79 (security: strict switches, write-only secrets out of queries), 80 (the sign-in look),
81 (the proxy matcher); iapl-upgrade "→ 1.17.1, security" and item numbers; reference skills, AGENTS.md and the
reference index on 1.17.1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 22:05:42 +01:00
Radosław SmolińskiandClaude Opus 5.5 38f1c012c4 1.17.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 22:05:42 +01:00
Radosław SmolińskiandClaude Opus 5.5 99073e24e9 routes.snapshot.json: admin-language in sorted place
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 22:04:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 7159ec25de Merge claude/login-page-whitelabel-616f3d: the panel's sign-in look (whiteLabel.signIn), the client's logo, hardened brand image fetch
Conflicts kept both sides: the 2FA texts (twoFactorBusy from A, twoFactorCodeDigit here), the reference index rows,
and the e2e:built line (closed doors from C and the sign-in look here). routes.snapshot.json judges the new public
GET /api/ipal/admin-language.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 22:04:30 +01:00
Radosław SmolińskiandClaude Fable 5.2 aef1efac73 Public brand image fetch: the site's configured origin only, no redirect followed, a time and a byte limit
/api/ipal/admin-og resolved a relative logo address against the request's own host and fetched it with
Node's defaults (redirects followed, no timeout, no size cap); /api/ipal/admin-icon resolved the same way.
Both now resolve against serverURL / NEXT_PUBLIC_SERVER_URL (never the request) and fetch through
fetchPublicImage, which asks one address with redirect: 'manual' (a 3xx is no image), within
PUBLIC_IMAGE_TIMEOUT_MS, reading at most 512 KB. The renderer still draws PNG, JPEG, GIF (by their bytes)
and SVG (by its type, as before). Tests against local servers: hostile Host / X-Forwarded-Host, a 302 to an
internal host, an endless body, a hanging server, the normal logo. Docs say 1.17.1 instead of 1.18.0.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 22:03:52 +01:00
Radosław SmolińskiandClaude Fable 5.2 562bf5388d Sign-in look: the logo check never follows a redirect; the review pictures stay out of the package
checkLogoFile asks only the address the upload has (redirect: 'manual'); a redirecting logo counts as
unknown, so the server fetches nothing at an internal address. docs/dev/login-page/*.png is excluded
in package.json files (npm pack --dry-run: none of them packed).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 21:44:39 +01:00
Radosław SmolińskiandClaude Opus 5.5 7026254c25 Reference skills: copies synced after the security B merge
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 21:43:05 +01:00
Radosław SmolińskiandClaude Opus 5.5 df9f2f3de3 Merge claude/security-b-content-state-cc308e: sizes before work, one link rule, no stand-in locale, strict switches, write-only secrets cannot be queried
AGENT.md conflict: the 2FA rows from A, the stored-secrets row from B (its check answers 400 QueryError, not 403).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 21:43:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 12bb6be76e Reference skills: copies synced after the security A and C merges
Branch A changed docs/agent/skills without its reference copies; iapl-doctor's skills-current warned on the reference
site.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 21:20:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 eb2ad27787 Write-only secrets cannot be queried (review B-R1)
A where or sort on a write-only field answered by the stored value: as an admin,
where[version.smtpPassword][like]=Zq on Site integrations' versions gave a count, so the
secret could be read back one character at a time. writeOnlySecret now gives the field a
read rule, secretReadAccess (exported), that denies when Payload checks a query's fields
(no document) and allows a document read (masked as before). The panel's edit and create
views pass the document, so the field stays visible and editable there.

Covered: the global, its versions, a collection with and without versions, REST and
GraphQL, like / equals / exists / or / sort / count; reads still masked; panel
permissions; a save still stores the new value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 21:10:45 +01:00
Radosław SmolińskiandClaude Opus 5.5 dd8cc5ecbd Merge claude/security-c-files-jobs-tests-cfba70: resolved paths in the bins and starter, proxy matcher ends at /, closed doors on the built site, every public route judged
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:57:50 +01:00
Radosław SmolińskiandClaude Opus 5.5 675d0c1997 Merge claude/security-a-signin-limits-80f95e: 2FA verify limit counts wrong codes only, exempt by an admin-only field, 2FA reset only from the site's own origin
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:57:45 +01:00
Radosław SmolińskiandClaude Fable 5.2 939ab679c7 Sign-in look: the logo follows IAWL's rules; no plate by default; the brand fields are admin-only
Bitmaps only (JPEG, PNG, WebP, AVIF, GIF; SVG with svgLogo: true), the file fetched and checked by its
bytes before it is printed (checkLogo; 512 KB; ten-minute memory; an unreachable address is believed),
served from a generated size at least twice the shown width. logoPlate replaces logoMadeFor: no plate
unless asked. With the look on, the name, logo and icon of Site settings are changed by admins only
(brandAccess: 'editor' gives them back). Docs, skills, changelog draft, tests and pictures follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 20:52:41 +01:00
Radosław SmolińskiandClaude Fable 5.2 3ceeab8469 Sign-in look: screenshots (before, after, an unedited 1.16.7 site, IAWL for comparison) and the capture script
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 20:39:27 +01:00
Radosław SmolińskiandClaude Fable 5.2 b6c91a3a11 Sign-in look: the client's logo or the site's name on a dark panel beside the form (whiteLabel.signIn)
On by default with whiteLabel. The login screen and the 2FA screens get the look through AdminLogo and
SafeTotpView, which every site already has in its import map: an upgrade needs no edit. allScreens adds one
provider (SignInLook) for forgot / reset password, first user and logout; a production start leaves it out
when the import map on disk lacks it. Logo and name come from Site settings: no new field, no migration.
Language links through GET /api/ipal/admin-language (Payload's own cookie, back to an admin path only).
Options: accent, logoMadeFor, languages, svgLogo; whiteLabel.brandAccess 'admin'. The 2FA code boxes get
names for screen readers. Reference site and starter: allScreens on. Docs, agent guide, skills, tests.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 20:35:33 +01:00
Radosław SmolińskiandClaude Opus 5.5 8f443c9214 Lint: the new route inventory, its tests and the touched tests
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:33:04 +01:00
Radosław SmolińskiandClaude Opus 5.5 d4fe3bf4ba Agent reference: the route-check exports; reference index: the closed-doors and route-check files
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:29:47 +01:00
Radosław SmolińskiandClaude Opus 5.5 2468390538 Outside-in tests (IAWL ideas 33, 34): closed doors on the built site as anonymous, customer and editor; every public route judged
- reference/e2e/closed-doors.ts + closed-doors.spec.ts: one table of doors, asked by pnpm e2e:built in both bundlers;
  doors still open while the owner decides are asserted open (test.fail) with their question
- listPublicRoutes / listNextRouteFiles / compareRouteSnapshot / updateRouteSnapshot (main entry), runRouteCheck (/doctor)
- reference/e2e/routes.ts + routes.snapshot.json (395 routes, one reason each); pnpm routes:check [--update], first step of e2e:built
- create-test-admin.ts makes an editor test account
- docs: security.md sections, AGENT.md 8a, iapl-audit templates, iapl-upgrade 1.17.1, changelog draft

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:26:30 +01:00
Radosław SmolińskiandClaude Opus 5.5 ecf03c8dc0 IAWL ideas, group B: sizes before work, one link rule, no stand-in locale, strict switches
- Request bodies from strangers are read only up to a cap, declared length or not:
  mail-service confirm, CSP reports, page views, MCP (maxBytes, 413). readCappedBody moves
  to shared/ (the consent log keeps exporting it).
- searchContent / createSearchRoute / MCP search: queryLimit (default 200 characters,
  10 words) before the database; an unknown ?locale is the default locale throughout.
- Rich text: autolinks and links marked internal pass safeHref too; lexicalToMarkdown
  drops unsafe link targets.
- truncate() never returns more than its limit (summary / meta autofill after validation).
- resolveRoute answers null for a locale the site does not have (xx, all, *): no
  default-locale page under another code (page route past the proxy, /md/xx, MCP).
- A 404 page that is a draft is not shown (resolveNotFoundPage, getNotFoundPage).
- readPublished() access rule (exported); Site integrations readVersions: admin.
- Plugin switches, buildCsp, buildSecurityHeaders and the seed guard refuse nonsense
  values at start; an unknown role name is met by nobody, requireRole throws on one.
- Docs, AGENT.md, iapl-collection and iapl-audit skills.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:25:26 +01:00
Radosław SmolińskiandClaude Opus 5.5 b2fed3bf90 Turnstile docs: limit before asking Cloudflare; test and lint fixes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:22:21 +01:00
Radosław SmolińskiandClaude Opus 5.5 6ca0730c08 2FA reset endpoint: only from the site's own origin (twoFactor.sameOrigin)
POST /api/ipal/two-factor/reset reads a text/plain body, which another
origin can send without a CORS preflight; a sibling subdomain is same-site,
so the browser sends the admin's SameSite=Lax cookie, and Payload's csrf
list is empty without serverURL. Such a page could reset any account's
TOTP and end its sessions (reproduced on SQLite, Postgres, MongoDB). Now the
endpoint takes the same origin rule as verify and setup, before it reads
or changes anything; twoFactor.sameOrigin: false leaves it out, and
buildTwoFactorResetEndpoint takes ownOrigin for own wiring.

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:15:51 +01:00
Radosław SmolińskiandClaude Opus 5.5 498b3dbf38 Files and paths (IAWL ideas 12, 13, 36): resolved --dest, starter refuses links and escaping paths, Office ZIP entries with trailing dots, proxy matcher ends api/admin/_next at /
- iapl-skills: --dest is compared with the project root after resolving links; a folder that is the root or holds it (.., /) is refused
- starter: collectBundle refuses symbolic links (their target would ship in the published bundle); writeFiles refuses absolute or escaping paths
- form files: a program inside a DOCX/XLSX is found with trailing dots or spaces (Windows drops them)
- proxy matcher: (?!(?:api|admin|_next)(?:/|$)|...) so /administracja, /apis get the proxy; doctor rule proxy-matcher reports the old literal
- pnpm: @swc/core in ignoredBuiltDependencies (its postinstall only checks the native binary, already installed)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:14:59 +01:00
Radosław SmolińskiandClaude Opus 5.5 e821d52d19 CLAUDE.md: the plugin is called IAPL (iapl-* skills, iapl-skills)
CI / check (push) Failing after 7m26s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Both rules keep their meaning word for word; only the names change. Not part of the npm package.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:45:26 +01:00
Radosław SmolińskiandClaude Opus 5.5 d97d571de7 1.17.0 release notes: consent
The box says "a doctor warning" for consent-log-migration (decided after the review); the reference copies of the
iapl-upgrade and iapl-reference skills re-synced from docs/agent/skills.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:19:50 +01:00
Radosław SmolińskiandClaude Opus 5.5 9fa886ce62 Merge claude/consent-compliance-build: Global Privacy Control honoured, equal choice by default, withdrawal that stops running tools, consent log on by default
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:19:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 963464d6cb Consent log endpoint: body capped at 4 KiB (413), version bounded by the policy version; consent-log-migration a warning
Review C-1: the endpoint, on on every site, parsed a 20 MB body. It now refuses a content-length over
CONSENT_LOG_MAX_BYTES (4096) before reading and reads the stream only up to the cap (readCappedBody), so a missing or
false length cannot make it hold more. A version above Cookie settings' policy version is 400 (the cached version is
read again once, for an editor's fresh raise); versions from 1 up are accepted (pages rendered before a raise).
Review C-2: consent-log-migration is a warning, like every consent check of 1.17.0 (the owner's decision).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:10:44 +01:00
Radosław SmolińskiandClaude Opus 5.5 9a448ba5df Consent log upgrade test: key order (lint)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:00:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 c6a276823c Consent log: missing-table line once per Payload instance; SQL upgrade proof on Postgres and SQLite
test/consentLogUpgrade.test.ts: a site without the log (migrations applied) upgraded to 1.17.0 — without a migration
the site works and a consent write answers 503 with one log line; migrate:create adds only consent_records (and the
lock-relation column) and writes succeed. SQLite always; Postgres with IAPL_TEST_PG_URL. Docs say exactly what the
migration creates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 13:51:52 +01:00
Radosław SmolińskiandClaude Opus 5.5 f5c53e4523 Consent compliance: docs, agent guide, skills, changelog, shared behaviour spec, browser check, reference e2e
- docs/consent.md: compliance defaults, Global Privacy Control, withdrawal, consent log on by default and the SQL
  migration; no more "UODO requirement" or "GPC not needed". docs/analytics.md: what Consent Mode advanced sends.
- docs/consent-behaviour-spec.md: the behaviour IAPL and IAWL share, with the 13-item test list.
- CHANGELOG 1.17.0: the SQL migration first, a before → after table for an existing site.
- AGENT.md, iapl-setup / iapl-upgrade / iapl-reference / iapl-consent-check, PROGRAMISTA item 78; reference skills copy.
- iapl-consent-check: Global Privacy Control, equal prominence and withdrawal runs; Google asset warnings.
- Reference site uses the new defaults; e2e for GPC, a stale grant, equal prominence, withdrawal; e2e:built runs every
  consent test in both bundlers. YouTubeEmbed warns in development without a poster.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 13:48:19 +01:00
Radosław SmolińskiandClaude Opus 5.5 99036eb70c Consent compliance: Global Privacy Control honoured, equal choice by default, withdrawal that stops running tools, consent log on by default
- GPC (gpc.ts): read in the browser before the first paint (consentBannerScript) and in the consent store; pages stay
  static. 'honour' (default): no banner, analytics and marketing off, no request to Google or a pixel; an explicit
  choice on the site wins; a grant made without the signal gives way when it appears. 'ask' and false as opt-outs.
- equalChoice defaults to true; a development warning when the banner has no 'reject'.
- Withdrawal: Meta / TikTok / Clarity told at once, listed localStorage / sessionStorage keys removed.
- Clarity gets consentv2 when it loads; ads_data_redaction with the Consent Mode default.
- consentLog on by default (consentLog: false turns it off); SiteProviders posts to it by itself; a missing SQL table
  answers 503 with one log line.
- Default banner text: one sentence on changing the choice and browser settings; the GPC line (PL / EN).
- Doctor: consent-log-migration, consent-banner rules.
- Stats: Sec-GPC over a choice made without it keeps the visitor id out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 13:38:39 +01:00
Radosław SmolińskiandClaude Fable 5.2 41771fd51a Consent compliance proposal: the banner against the rules, Global Privacy Control, defaults the plugin enforces, the spec shared with IAWL
Design only, no code. First cut for 1.17.0 needs no schema change; eight yes-or-no decisions for the owner.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 13:25:34 +01:00
Radosław SmolińskiandClaude Opus 5.5 9520e61b15 1.17.0 release notes: the speed of public pages
The "Read before upgrading" box names the two changes merged after 2f6a81a: the cookie banner painted with the
page (nothing to do) and Payload's colour-scheme client hints for the admin only (one line in next.config.ts).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 12:56:42 +01:00
Radosław SmolińskiandClaude Opus 5.5 80e202111c Merge claude/consent-banner-first-paint-154f9f: the cookie banner is part of the first render
Conflicts in the docs only, both sides kept: changelog lines, AGENT.md checklist rows 12 (banner) and 13 (wrapper order),
the two iapl-upgrade blocks, PROGRAMISTA rows 76 (client hints) and 77 (banner, renumbered from 76).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 12:56:20 +01:00
Radosław SmolińskiandClaude Opus 5.5 6dd552f721 Merge claude/admin-only-theme-headers-f19f9f: Payload's colour-scheme client hints go to the admin only
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 12:45:22 +01:00
Radosław SmolińskiandClaude Fable 5.2 177620da57 Cookie banner is part of the first render: in the server HTML, decided before the first paint; pages stay static
Until now CookieBanner rendered nothing until the page had hydrated and an effect had read the cookie, so on a first
visit it appeared late and became the LCP element on text pages (request from a client project, 2026-11-26).

- The banner is rendered on the server with `hidden`, followed by one inline script (consentBannerScript) that,
  before the browser paints, shows it (no current decision) or keeps it hidden (current decision). It decides as
  readConsentRecord does. A click on a banner button before hydration is kept and carried out once the page is live.
- The decision is read through a store (useSyncExternalStore): no hydration mismatch, the browser's value before
  the next paint. One decision per document.
- Optional server read (ConsentProvider cookieValue, SiteProviders consentCookie): exact HTML, dynamic pages.
- CookieBanner firstPaint={false} keeps the old behaviour; nonce from SiteProviders / ConsentProvider / the prop.
- Nothing about consent changes: no tag earlier, Consent Mode default first, cookie, consent log, withdrawal.

Tests: test/consentFirstPaint.test.ts (server render, script against readConsentRecord, hydration with no warning,
decisions, tags), reference e2e (static HTML, painted before hydration, returning visitor, early click).
Docs: consent.md "First paint", frontend.md, security.md, AGENT.md, skills, changelog draft under 1.17.0.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 12:08:59 +01:00
Radosław SmolińskiandClaude Fable 5.2 9143c132a3 Payload's colour-scheme client hints go to the admin only: withSecurityConfig outside withPayload
withPayload adds Accept-CH, Critical-CH and Vary: Sec-CH-Prefers-Color-Scheme for /:path*; Critical-CH makes
Chrome repeat the first document request of a visit to a public page. As the outer wrapper, withSecurityConfig
moves the three headers to /admin/:path* (adminClientHints: { route, sources } | false). Inside withPayload
nothing changes, so an unedited site behaves as before. Exports scopeColorSchemeClientHints,
adminClientHintSources, COLOR_SCHEME_CLIENT_HINT; doctor rule client-hints (info); reference site and starter
use the new order; e2e:built and the starter gate check it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 11:55:26 +01:00
Radosław SmolińskiandClaude Opus 5.5 2f6a81acbf 1.17.0 upgrade notes
Changelog: one 1.17.0 entry, the security follow-ups prepared as 1.16.8 first, then e-mail, the name, Postgres;
the mail service is live with enrolment "pending". PROGRAMISTA §6 rows 71 (renamed), 74 and 75; iapl-upgrade
"→ 1.17.0, security"; iapl-setup, iapl-debug, email.md, deployment.md: a new site waits for approval while the
service runs with "pending". Reference skills, AGENTS.md and the reference index on 1.17.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 11:09:53 +01:00
Radosław SmolińskiandClaude Opus 5.5 3bfe377f1b 1.17.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 11:09:00 +01:00
Radosław SmolińskiandClaude Opus 5.5 536e219f57 Merge claude/mail-relay-dev-hosts: development hosts by pattern with no env, built in *.dev.netscale.pl
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 11:08:15 +01:00
Radosław SmolińskiandClaude Fable 5.2 6c4e244094 Development hosts, review V-1 to V-3: a malformed list stops the start, a trailing dot and Unicode patterns match, every send reads the store
- V-1: assertDevelopmentHosts - iapl({ developmentHosts }), mail.relay.developmentHosts and
  mailAdapter({ relay }) refuse anything but an array of non-empty host patterns, and a pattern of `*` alone
  (it would make the public site a development address). Nothing is ignored silently any more.
- V-2: one trailing dot of the host is stripped before matching; patterns are punycoded, so one written in
  Unicode matches; a `*` inside a non-ASCII label is refused.
- V-3: the 30-second memory of other hosts is gone. A dump restored into a running development site stops
  its very next e-mail.
- docs, AGENT.md, changelog draft, skills

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 10:57:32 +01:00
Radosław SmolińskiandClaude Fable 5.2 99c73ed0ff Development hosts are about mail only: one sentence on robots; the reference index after the fixture
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 10:40:33 +01:00
Radosław Smoliński 5df5358768 Revert "A development host is kept out of search engines without IAPL_NOINDEX (developmentNoindex, default on)"
This reverts commit bc3aac249f.
2026-11-26 10:38:29 +01:00
Radosław SmolińskiandClaude Fable 5.2 463b966365 Reference site: a test fixture for development hosts (E2E_DEVELOPMENT_HOSTS), for the built-site run of the launch cases
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 10:36:59 +01:00
Radosław SmolińskiandClaude Fable 5.2 bc3aac249f A development host is kept out of search engines without IAPL_NOINDEX (developmentNoindex, default on)
Separate from the mail rule so that it can be taken or left. A site whose address matches
iapl({ developmentHosts }) - built in: *.dev.netscale.pl - is noindex with no env: robots.txt disallows
everything, pages carry noindex, IndexNow sends nothing, buildSecurityHeaders() adds X-Robots-Tag. Nothing
kept a development copy out of search engines until now unless somebody set the variable.

- iapl({ developmentNoindex: false }) switches it off for the project, IAPL_NOINDEX=0 for one environment
- buildSecurityHeaders({ developmentHosts, serverUrl }): next.config runs before the plugin
- the mail rule keeps its own two signals: the development pattern, and the variable itself
- changelog "what changes on upgrade", deployment.md, security.md, AGENT.md, skills

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 10:31:03 +01:00
Radosław SmolińskiandClaude Fable 5.2 14abf369da Mail relay: development hosts are known by pattern, with no env - built in: *.dev.netscale.pl
The launch rule called a site non-public only when IAPL_NOINDEX was set (or the project named its hosts).
The owner's development sites set nothing, so production's database copied onto a development address
counted as a launch and would have mailed real people.

- iapl({ developmentHosts }): host patterns of development addresses. Default DEFAULT_DEVELOPMENT_HOSTS =
  ['*.dev.netscale.pl'], Intecion's own development domain; a project replaces the list or empties it.
  mail.relay.developmentHosts overrides it for the mail service.
- a site whose host matches is non-public exactly as with IAPL_NOINDEX=1; either signal is enough
- siteNonPublicSignal, matchDevelopmentHost, isDevelopmentHost, pluginDevelopmentHosts exported
- panel state: nonPublicBy, nonPublicPattern; doctor: mail-non-public (info) names the signal
- every case of the launch table runs with no env on the built-in pattern
- docs, AGENT.md, skills, changelog draft

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 10:26:12 +01:00
Radosław SmolińskiandClaude Opus 5.5 634908eb57 Merge claude/postgres-mail-deadlock: Postgres keeps connections free of transactions; form and account mail go out after the commit
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 01:38:31 +01:00
Radosław SmolińskiandClaude Opus 5.5 074353bf5f Merge claude/mail-relay-launch: launch and a domain move need no click; a non-public copy neither enrols nor sends by itself
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 01:38:26 +01:00
Radosław SmolińskiandClaude Opus 5.5 919953e65e Account mail after commit: matched by its token, not by the address (P-4)
holdAccountMailFor bound the next message to an address to whichever
request held it: two resets for one account at once could lose the first
one's mail on the second's rollback, and a form's mail to that address was
deferred to the reset's transaction.

Payload calls generateEmailSubject({ req, token, user }) right before it
sends the reset or verify mail, and the mail carries that token. The plugin
now wraps that function on every auth collection (a project's own one is
kept, Payload's subject otherwise) and holds the token for the request's
transaction; mailAdapter defers only a message to that account alone whose
body contains a held token. An AsyncLocalStorage mark set in a
beforeOperation hook was not used: Payload awaits the hook, and a mark set
inside it does not reach the send (relay/kinds.ts says the same).

Building blocks renamed with it: holdAccountMail(token, address, req),
releaseAccountMail(token). Both review rows are tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 01:36:17 +01:00
Radosław SmolińskiandClaude Opus 5.5 4efadb21d5 Postgres pool, review round 1: nested transactions, account mail after commit
P-1: a transaction begun inside another one (a hook calling the Local API
without req) no longer queues behind its caller. An AsyncLocalStorage mark set
when a transaction begins lets the inner one through at once, without a
place, but never into the last connection (a second level may take that
one). If the mark is lost, a queue that has not moved for a second admits
its newest waiter. connectionReserve: false now admits everything, as
before. Measured on Postgres 17: 9, 12 and 30 such submissions finish
(before: stuck from 9).

P-2: Payload's "forgot password" and "verify your e-mail" through
mailAdapter() go out right after their transaction commits
(mail.accountMailAfterCommit, default on). With the relay hanging,
30 resets + 30 submissions finish in about 11 s instead of 43.5 s.

P-3: Postgres tests for the "not confirmed" file result after commit, a
caller's outer transaction rolled back or committed, the relay hanging,
and the nested rows; deployment.md has the measured table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 01:19:27 +01:00
Radosław SmolińskiandClaude Fable 5.2 49927205bb Mail relay: launch and a domain move need no click; a non-public copy neither enrols nor sends by itself
The copy rule now goes by direction. A public site that finds another host's connection in its database
(its development address after launch, its old domain after a move) enrols by itself. A site that says it
is not public - IAPL_NOINDEX=1, or a host in the new mail.relay.developmentHosts - and holds another host's
connection is a copy of that site's data: it neither enrols nor sends until "Connect again", also when it
has a token of its own (production's database copied back onto the development address). The consent is
stored with the copy (acceptedHosts), so the next fresh copy waits again.

- mail.relay.otherHosts: 'auto' (default) | 'wait' | 'enrol' | list of the site's own hosts
- mail.relay.developmentHosts, siteIsNonPublic() exported
- the copy refusal ends when its reason does (no cool-down; the panel recomputes it on every read)
- doctor: info for a public site whose database knows another host (the launched site, or a copy that
  forgot IAPL_NOINDEX)
- contract copy 1.7.1 (wording only)
- docs, AGENT.md, skills, changelog draft

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 00:46:16 +01:00
Radosław SmolińskiandClaude Opus 5.5 32bb542e8e Postgres: many requests at once no longer stop the site
Each Payload transaction holds a pool connection; code inside it that runs
without its req needs a second one (Payload's own forgotPassword, the mail
adapter's settings read and status write, payload.kv). With the default pool
of 10, ten form submissions or ten "forgot password" requests at once held
every connection and waited for good.

- connectionReserve (default on): at most pool size − reserve transactions
  open at once; a waiter older than a second may use all but the last
  connection. Building blocks in modules/database/transactions.ts.
- Form e-mails go out right after the submission's transaction commits, in
  the same request (forms.emailsInTransaction: true = the old way).
- recordIntegrationStatus merges identical writes and does not hold its
  caller while the pool is busy.
- SMTP time-outs: 10 s connect, 30 s greeting, 60 s silence (smtp.timeouts).

Tests on Postgres 17: 30 submissions, 30 forgot-password, and both against
an SMTP server that never answers, finish while a page answers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 00:33:07 +01:00
Radosław SmolińskiandClaude Opus 5.5 acfcf72c03 Merge claude/mail-relay-adapter: mail through IWSN by default, SMTP on request, Graph deprecated
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 23:59:55 +01:00
Radosław SmolińskiandClaude Fable 5.2 85ed92bb89 Mail relay: review round 2 — the store is keyed by host, a copied database does not enrol by itself
- Q-1 one entry per host (iapl:mail-relay:site:<host>); a read never deletes or writes; another host's
  entry is neither used nor touched (a developer's process on the live database, www and apex, a copy)
- a database that holds another host's connection and none of this site's does not enrol by itself:
  "Connect again" does, once; mail.relay.otherHosts ('wait' | 'enrol' | the site's own other hosts);
  panel text and doctor finding; a site with an empty store enrols by itself as before
- Q-2 the file limit answers from what is stored and never asks the service
- Q-3 a file whose mail was not confirmed is not reported as a wrong file, and no notice mail follows
- Q-4 its own text when the access-key field is off
- D-1 docs for open enrolment; staging, copies and several hosts

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 23:14:11 +01:00
Radosław SmolińskiandClaude Fable 5.2 edee3a321f Mail relay: the access-key field is off by default (mail.relay.accessKeyField)
A token issued by hand is set by a developer: setRelayToken() from a script, or mail.relay.token.
The panel field and its route take a token only when the project switches the field on. Docs and
AGENT.md say when such a token is needed and how to set it; a token of another host is refused on
every way in.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 22:25:34 +01:00
Radosław SmolińskiandClaude Fable 5.2 1a11cefffa Mail relay: the 1.7.0 test allows the status read that follows a new enrolment
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 22:14:09 +01:00
Radosław SmolińskiandClaude Fable 5.2 fef2c51bae Mail relay: contract 1.7.0 — X-Intecion-Site on every request with a token, host-mismatch
contracts/mail-relay refreshed from IWDL 6cd99f7 (64 files). A token the service knows as another
site's is forgotten without revoking and the site enrols as itself; a hand-issued one is refused.
The fake requires the header and answers host-mismatch.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 22:13:58 +01:00
Radosław SmolińskiandClaude Fable 5.2 a2b07b1dc1 Mail relay: review of 7d766b6 — R-1 to R-12, four mutations, two sentences
- R-1 a delivered token becomes the one in use only on 200 or a refusal given after authentication
- R-2 a token of another site is refused by what /v1/status says (access-key field, scripts); docs for staging
- R-3 the confirm route looks the nonce up first and counts only refused calls
- R-4 one budget of time per message (10 s, 30 s with files), enrolment and retries included
- R-5 'Disconnect' without the service's answer is not confirmed and keeps the token to try again
- R-6 no enrolment without the confirm route in the config
- R-7 half an SMTP set-up: one log line and a hint in the panel
- R-8 to R-10, R-12 docs; R-11 the last failure stays in the state block
- tests for redirect: manual, the candidate's nonce, the expectation taken back, one recipient only

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 22:07:10 +01:00
Radosław SmolińskiandClaude Fable 5.2 0ee74ab2a4 Mail relay: contract 1.6.0, the token tied to its host, IWSN in the panel
- contracts/mail-relay refreshed from IWDL 83af8c6 (1.6.0)
- an answer that is not the service's JSON is 'not confirmed' unless its status is 400 to 499
- a site with a token issued by hand does not enrol to heal: it stops and says what to ask Intecion for
- a store made on another host (a database copied to staging) is not used: the copy enrols as itself, nothing is revoked
- the panel calls the service IWSN (RELAY_SHORT_NAME); docs, logs and the doctor keep the full name

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 21:51:47 +01:00
Radosław SmolińskiandClaude Fable 5.2 7d766b6d58 Mail relay: the reference site's generated types without the e2e fixture's collections; doctor command in the guide
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 21:24:24 +01:00
Radosław SmolińskiandClaude Fable 5.2 ebfedb03d9 Mail relay: tests count the account rules' own hooks, reference index, doctor fixture
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 21:18:09 +01:00
Radosław SmolińskiandClaude Fable 5.2 2cceceffd0 Mail relay: state block without an import-map entry, e2e on the reference site, sharper failure reports
- the state block is rendered by IntegrationStatusBanner (no new admin component: generate:importmap gives no diff)
- reference site: e2e/mail-relay.spec.ts with a fixture and setup script; e2e:built runs it with both bundlers
- a failed enrolment is reported as what it was; the service's own refusal after a fresh enrolment
- a message keeps its key after any failure that is not final
- a local site is shown as refused in the panel before any e-mail

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 21:14:47 +01:00
Radosław SmolińskiandClaude Fable 5.2 dd3792cbc7 Mail relay: docs, agent guide, skills, changelog draft; test against the real service code; starter offers the mail service
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 20:53:38 +01:00
Radosław SmolińskiandClaude Fable 5.2 533f571d4d Mail relay: HTTP tests on a running Payload, account mail marked by recipient, panel wording, doctor rules tested
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 20:40:17 +01:00
Radosław SmolińskiandClaude Fable 5.2 ea9703f8e3 Mail relay: the built-in client for the Intecion Notifications Webservice
Transport, enrolment with the confirm route, token and state in payload-kv, rotation,
the panel's state block, doctor rules, the fake service and the copied contract 1.5.0.
Tests against the contract's runner and the fake. Docs and HTTP tests follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 20:29:46 +01:00
Radosław SmolińskiandClaude Opus 5.5 9efd86a06f Merge claude/iapl-rename-1170: the plugin is called IAPL, every name from before keeps working
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 19:26:36 +01:00
Radosław SmolińskiandClaude Fable 5.2 38b903fcfa IAPL rename, review fixes I-1 to I-11
I-1  ipalEnvRules() keeps the IPAL_ rule names (IAPL_ as aliases); iaplEnvRules() the other way round; the IAPL_ value
     is the one checked when both are set
I-2  COOKIE_SCAN_URL_ENV / COOKIE_SCAN_TOKEN_ENV (and the internal SITE_NOINDEX_ENV) keep their old values;
     IAPL_COOKIE_SCAN_URL_ENV / IAPL_COOKIE_SCAN_TOKEN_ENV added
I-3  bin/ipal-*.mjs: five files that run the new ones (1.16's audit skill and CI call them by path); legacy:site checks it
I-4  storage-names sees <SiteProviders … stats> when a JSX prop comes first (the reference layout's shape)
I-5  AGENT.md: a text naming an ipal-<name> skill means iapl-<name> (the vendored ext-* skills)
I-6  leftover text in the skills-current message
I-7  iapl-skills removes the old pointer block when both are in AGENTS.md
I-8, I-11  changelog: the doctor's summary line, IAPL_DOCTOR_STATUS, --strict in CI until the skills are refreshed
I-9  env.md: an empty IAPL_ variable does not switch the IPAL_ one off
I-10 verifyLimit.keyPrefix undefined or empty is 'not given'

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 18:45:36 +01:00
Radosław SmolińskiandClaude Fable 5.2 03452376f9 IAPL rename: three places where the brand rule had replaced a path segment or a test's needle
scripts/starter-gate.mjs (node_modules/@intecion/ipal-kit), dev/tsconfig.json (the 'ipal-kit' path alias),
test/starter.test.ts (the lockfile must not contain 'ipal-kit'); two JSDoc import lines.
Found by pnpm starter:gate.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 18:04:26 +01:00
Radosław SmolińskiandClaude Fable 5.2 5a0ea924ff Reference e2e setup clears the 2FA counter under the site's own key prefix (iapl)
The reference site has storageNames: 'iapl'; the setup cleared only ipal:2fa-verify:*, so attempts of one
e2e run counted against the next (found by the Turbopack run after the webpack run).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:59:00 +01:00
Radosław SmolińskiandClaude Fable 5.2 e0f7fa1add legacyNameForms: the MCP server name and a pattern fragment in the list
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:53:52 +01:00
Radosław SmolińskiandClaude Fable 5.2 0e54789abd Rename plan: what was carried out and where it differs
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:48:00 +01:00
Radosław SmolińskiandClaude Fable 5.2 630b736344 IAPL rename: instructions say 'pnpm exec iapl-skills', which works whatever the project's script is called
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:47:39 +01:00
Radosław SmolińskiandClaude Fable 5.2 3d5106bc4a IAPL rename: readEnv exported, the MCP server name left as it was, legacy:site needs a database
- readEnv / legacyEnvName exported from the root and /env (a project's own code reads IAPL_* with the IPAL_* fallback);
  the name constants hold the IAPL_ spelling — changelog and env.md say so
- createMcpRoute: the default serverName stays 'ipal-site' (clients see it); the scripted step had changed it
- legacy:site: the builds read the database; the script and PROGRAMISTA say which

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:47:11 +01:00
Radosław SmolińskiandClaude Fable 5.2 926ba4a67e IAPL rename: gate checks, and two breaks they found on an unedited 1.16.7 site
- pnpm legacy:site (scripts/legacy-site-check.mjs): the reference site of v1.16.7, unedited, installed against
  this build — old commands, doctor without errors, import map unchanged, tsc, builds with webpack and Turbopack
- test/legacyNameForms.test.ts: the remaining spellings with 'ipal' as a closed list; a new one fails
- found by legacy:site and fixed: 'ipal-tokens --check' called a tokens.css written before 1.17.0 out of date
  (its header names the command); the doctor's env-example rule did not accept IPAL_* in .env.example
- the doctor's seed rules catch IPAL_SEED_ALLOW_FULL=1 as before
- PROGRAMISTA: the new release check

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:41:26 +01:00
Radosław SmolińskiandClaude Fable 5.2 b91984fbcd IAPL rename: docs, agent guide, skills, reference site and starter on the new names; changelog draft
- docs, AGENT.md, the 16 skills, PROGRAMISTA and README use the preferred names (scripted, same list of forms);
  past CHANGELOG entries and the proposals in docs/dev are not rewritten
- AGENT.md: 'Names: IAPL and ipal-kit' — old name, new name, state in 1.x; what is not renamed; storageNames
- iapl-upgrade '→ 1.17.0', PROGRAMISTA §6 item 72, CHANGELOG 1.17.0 (draft): nothing required
- env.md, doctor.md (legacy-names, storage-names), stats.md, security.md, project-starter.md, iapl-reference, iapl-setup
- skill scripts read ipal-audit-skip and IPAL_IP_HEADER too; audit rule ids stay what they were
- reference site: iapl(), iapl-doctor.json, iapl-* skills, storageNames: 'iapl'; INDEX.md regenerated

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:36:09 +01:00
Radosław SmolińskiandClaude Fable 5.2 425fac14fb 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]>
2026-11-25 17:31:13 +01:00
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:24:21 +01:00
Radosław SmolińskiandClaude Fable 5.2 414a4702df Rename plan: the owner's answers, and the second cookie name and kv prefix for new sites
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:21:53 +01:00
Radosław SmolińskiandClaude Fable 5.2 b785a27b7d Plan: rename ipal-kit to IAPL in 1.17.0 (inventory, sorting, shape, order, questions)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 13:09:57 +01:00
Radosław SmolińskiandClaude Opus 5.5 619a4e06ca 1.16.8 upgrade notes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 10:26:51 +01:00
Radosław SmolińskiandClaude Opus 5.5 dfec3fca46 1.16.8
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 10:26:33 +01:00
Radosław SmolińskiandClaude Opus 5.5 e29ceeffb0 Merge claude/security-copy-rules: copied staff collections, a rule that cannot widen
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 10:26:04 +01:00
Radosław SmolińskiandClaude Opus 5.5 1316509565 Merge claude/security-1168: account rules where an account can hold editor or admin, no package.json among public files, pnpm e2e:built
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 10:26:04 +01:00
Radosław SmolińskiandClaude Fable 5.2 a19fa0d17b L-1 and one changelog entry for the release: what gets narrower on a copy, the collection that becomes staff later
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 10:03:31 +01:00
Radosław SmolińskiandClaude Fable 5.2 20809ba933 L-2: a config collection that becomes staff later keeps the rules it had at config time
A collection of the config that is not named as staff and that a plugin listed after
ipalKit makes the panel's (admin.user) was adopted as a late collection: the plugin's
rule went in front of every rule, also the ones the project wrote. The marker now
holds the operations that had a rule at config time (own); those are left as written
when the collection is handled again, and an operation without one gets the plugin's.
The start log tells this case from a collection a later plugin added.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 10:03:31 +01:00
Radosław SmolińskiandClaude Fable 5.2 a743479276 Copied staff collections: the unit fixture's roles field holds a list (after the rebase on K-1)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 03:52:56 +01:00
Radosław SmolińskiandClaude Fable 5.2 c9540d291a Copied staff collections: access guide, API table, changelog, reference index
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 03:48:21 +01:00
Radosław SmolińskiandClaude Fable 5.2 8dcc123b99 Copied staff collections: the plugin's rule goes in front, nothing is replaced (a rule that cannot widen)
A plugin listed after ipalKit that copies a staff collection under a new slug, or reuses its access object, brings
rules the plugin wrote for the ORIGINAL. On 1.16.7 the copy also carried the boolean 'seen' marker and was left
alone: 'the account itself' then meant an account of the original — with numeric ids the original's account with
the same id changed the copy's account (17 of 40 measured shapes).
Design: the plugin never replaces and never rewrites a rule on such a collection. It puts its rule for the copy's
own slug in front, and both must allow: on a copy named as staff in front of every rule; on a copy that is not
staff or keeps its own rules (custom.ipal.accountRules: false) in front of the rules marked as the plugin's for
another collection. The roles field of every copy is guarded. The mark on the plugin's functions says only
{ slug, self }; custom.ipalAccounts says { slug, staff } (a collection named as staff during next dev is handled
on the reload). The plugin's rules are marked before its 2FA guard, which carries the mark.
Accepted cost: a copy's own account cannot edit itself through a copied rule (as on 1.16.7); the copy writes
access.update — one documented line.
Proof: test/accountCopyTableSuite.ts — 40 shapes x accounts x operations, each row not wider than the measurement
taken on 1.16.7 (test/fixtures/copyRulesBaseline.json) and not wider than the plugin's rule; 2FA off and on.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 03:48:09 +01:00
Radosław SmolińskiandClaude Fable 5.2 4c7b722aed K-3: docs — fields that hold a list, a relationship counts, a rule of your own replaces the protection, known limitations
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 03:44:25 +01:00
Radosław SmolińskiandClaude Fable 5.2 c3d95988e1 K-1, K-2: only a roles field that holds a LIST counts; the start-up check asks each collection its own way
K-1 the plugin counts roles only from an array (getRoles). A single-valued roles field — a select, text or
    relationship without hasMany, a radio — never makes a plugin admin, yet canHoldStaffRole said true: on a
    project's own login collection with a single role select nobody could create, change, delete or unlock accounts,
    the account holding admin included. rolesAreAList(collection) is now a precondition of the admin rules. The same
    for hasPluginRoles: a single select whose values are all the plugin's had the admin rules already in 1.16.7 and
    gets 'an account of this collection' now — its accounts manage each other again; the value still grants nothing.
    A relationship with hasMany counts (ids that are text).
K-2 staffCollectionsNobodyManages returns { stuck, unchecked } and checks collection by collection: no query where
    the field cannot hold admin; a count for a select with hasMany; for text / json / relationship the accounts are
    read and the plugin's own test is applied. Where it cannot check it says so and claims nothing.
Tests: the reviewer's shapes over HTTP and the warning's table against a running Payload, 2FA off and on.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 03:44:25 +01:00
Radosław SmolińskiandClaude Fable 5.2 ccc6f85924 Security follow-ups to 1.16.7: changelog, access guide, skills, API table, release gate, reference index
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 02:59:44 +01:00
Radosław SmolińskiandClaude Fable 5.2 be2e6d52d9 A staff collection whose accounts can hold editor or admin gets the admin rules (H-2, J-3)
In the released 1.16.7. The plugin's checks go by the value on the account, but a project's own staff collection
without rules got the admin rules only when ALL its role values were the plugin's; otherwise 'an account of this
collection' could create, change and delete accounts. Measured on bc0fa65 (SQLite; the first shape also on Postgres
and MongoDB, 2FA off and on): with roles user/editor/admin/boss, with a text and with a json roles field, config-time
and added by a later plugin, an account with the role user creates an admin (201) who reads Site integrations, changes
another staff collection's roles and lists the panel's accounts (200 / 200 / 200), takes the admin over and deletes it;
with viewer/editor a viewer creates an editor who gets past the access rule of Site settings.
canHoldStaffRole(collection): a roles select with editor or admin among its values, or a roles field whose values
cannot be listed. Then: create / delete / unlock an admin, update an admin or the account itself, roles only by an
admin. A project's own rules win. A warning at start when no staff account is an admin and such a collection exists.
The built-site fixture gets a config-time and a late collection of that kind; nothing here touches copied collections.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 02:59:44 +01:00
Radosław SmolińskiandClaude Fable 5.2 01219b69d3 F-3: pnpm e2e:built puts the reference site's generated files back, also on failure
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 02:53:41 +01:00
Radosław SmolińskiandClaude Fable 5.2 e77c607bca R4-3: pnpm e2e:built (webpack and Turbopack); Playwright runs reset the test admins first
The command builds the reference site with both bundlers, checks the public files for a package manifest and runs
the late-staff spec and the published-files check against each built site. A global setup resets the test admins
and their stored 2FA attempt counts before every run, so a spec no longer depends on what ran before it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 02:53:41 +01:00
Radosław SmolińskiandClaude Fable 5.2 9a648b0498 The plugin's version is a constant: no package.json among a site's public assets
pluginVersion() named package.json relative to its own module. A bundler takes such a file for an asset:
a Turbopack build of a site copied the plugin's whole package.json (dependency lists, scripts, the registry
and repository addresses; no secret) to /_next/static/media/package.<hash>.json, served to anyone. Webpack kept
it on the server side. The version now comes from src/version.ts (scripts/write-version.mjs, run by the
`version` script; a test fails when it differs from package.json). A smoke test of the built site: nothing
under .next/static is a package manifest.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 02:53:41 +01:00
Radosław SmolińskiandClaude Opus 5.5 bc0fa65fd7 1.16.7 upgrade notes
CI / check (push) Failing after 5m54s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 00:40:20 +01:00
Radosław SmolińskiandClaude Opus 5.5 14c44d082d 1.16.7
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 00:40:07 +01:00
Radosław SmolińskiandClaude Opus 5.5 7b2a2759ab Merge claude/security-m1-hardening (rebased): write-only secrets, account rules, password rule, 2FA attempts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 00:39:30 +01:00
Radosław SmolińskiandClaude Fable 5.2 8a01c72c2a M1 review round 3: a built-site e2e for a late staff collection (both bundlers); docs follow
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:24 +01:00
Radosław SmolińskiandClaude Fable 5.2 6e0ad26b2c M1 review round 3: late staff collections without guessing Payload's default; rules survive a dev reload
R3-1 nothing is decided by a function's name any more (a production build renames it): on a collection that
     arrives after ipalKit the plugin's rule is put in FRONT of the rule that is there and both must allow
     (bothAllow). unlock follows the same table. The log says exactly what was put.
R3-2 the adoption walks the live config (payload.config), which Payload swaps first on a dev reload.
R3-3 readVersions gets the read rule on staff collections.
R3-5 a secret that is not text is refused.
Also: the async check of requireSetup.exempt compares the constructor, not its name.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:24 +01:00
Radosław SmolińskiandClaude Fable 5.2 3e44863c98 M1 review round 2: docs, agent guide, skills, changelog; the reference types without the removed field
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:24 +01:00
Radosław SmolińskiandClaude Fable 5.2 7002ebbfa6 M1 review round 2: the transport is no way round, nobody raises its own role, late staff collections
R2-1 the SMTP password is bound to server, port and user whatever the transport says; the transport alone is not bound.
R2-2 where the plugin's update rule is in force the roles field is closed for the account itself
     (the plugin's roles: only an admin; roles of the project's own: never one's own).
R2-3 auth collections a later plugin adds get the account rules, the password rule and the first-user endpoint when
     the config goes live; a staff slug that is not an auth collection stops the start.
R2-4 smtpRequireTls is taken out: the branch adds no field, column or collection.
Also: read (a staff account) and unlock (an admin) defaults on staff collections (accounts.staffOnlyRead);
doctor staff-own-roles and read / unlock in staff-accounts-open; r1 NULL against the default, also inside a row;
r2 bound values compared exactly.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:24 +01:00
Radosław SmolińskiandClaude Fable 5.2 a32329fbb4 M1 review: reference site types and an e2e check of the bound SMTP password
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:23 +01:00
Radosław SmolińskiandClaude Fable 5.2 fd203de326 M1 review: docs, agent guide, skills and changelog follow the fixes
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:23 +01:00
Radosław SmolińskiandClaude Fable 5.2 1141c749de M1 review: account rules before 2FA, the SMTP password stays with its server, the rest of the findings
M1-1 the first-user route is the plugin's own endpoint in front of Payload's; nothing is read from the path.
M1-2 the account rules are put on the collections before the 2FA package wraps them.
M1-6 the admin rule only where the roles are the plugin's; other staff collections: an account of that collection.
     update / delete get the matching defaults (accounts.adminOnlyWrite); doctor rule staff-accounts-open.
M1-5 access.firstUserAdmin: false with a role below the panel role: the default panel role steps aside, an explicit one is refused.
M1-3 a save that changes the SMTP server, port, user or encryption must send the password again (secrets.reenterOnChange);
     new panel field smtpRequireTls.
M1-4 a restore of a version masks the secrets (maskSecretsOnRestore).
M1-7 a refused origin is logged once with the ways to allow it; default ports are normalised.
Minors: m1 day boundary, m3 e-mail check on reset and bulk update, m4 text of 'all', m5 the mask is never kept.
The account suite runs with 2FA off and on.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:23 +01:00
Radosław SmolińskiandClaude Fable 5.2 81cee02e78 M1: the reference e2e suite follows the stored 2FA verify count
The verify count now survives a restart of the site, so the specs can no longer
share one test admin across server runs: create-test-admin.ts makes two test
admins and clears their stored counts; the setup spec signs in as the second.
The whole suite passes in one run (20 passed, 1 skipped).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:23 +01:00
Radosław SmolińskiandClaude Fable 5.2 83356ab4ed M1: docs, agent guide, skills and changelog for the hardening items
security.md (stored secrets, own-origin 2FA attempts, stored verify count,
dashboard alerts by role), access.md (account rules: panel role, no
self-registration, passwords), turnstile.md (the deprecated env secret,
forms.turnstileOnConfigError), doctor.md (five new rules, the deep status),
AGENT.md, ipal-setup, ipal-upgrade, ipal-debug, ipal-reference (+ api.md),
ipal-doctor and their mirrors, PROGRAMISTA row 69, CHANGELOG under an unreleased
heading with "Requires project changes".

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:23 +01:00
Radosław SmolińskiandClaude Opus 5.5 cff355a541 Merge claude/docs-isadmin-client-import: role checks importable in client components
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 f7296edc71 M1 (8): 2FA attempts only from the own origin; the verify count is stored
R3-2. (b) POST /api/verify-totp and /api/setup-totp refuse a request that a
browser marks as coming from another origin (Origin, Sec-Fetch-Site) — before it
is counted, so another page (a sibling subdomain included) cannot burn an
account's attempts and lock its owner out. Own origins: the request's host,
serverURL, Payload's csrf / cors lists, twoFactor.sameOrigin.origins; requests
without those headers pass. twoFactor.sameOrigin: false turns it off.
(a) The verify count is kept in memory (exact for parallel bursts) and in
Payload's key-value store (payload.kv, no new collection), so a restart or a
second instance does not reset it; the higher count decides, and a failing store
never opens the gate. verifyLimit.store: 'memory' = this instance only.
Doctor: csrf-empty (static, warning) when neither serverURL nor csrf is set.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 0b4c4e8295 M1 (9): dashboard alerts by role
IntegrationAlerts reads the admin-only Site integrations global with access
control off and showed its error texts to everyone who opened the dashboard.
Now: an admin sees what is failing and the link, an editor a neutral "an
integration needs attention — ask an administrator", anyone else nothing.
CookieCrawlAlert is shown to editors and above (the role that may read the crawl
result). Both use userMeetsRole, so a session that still owes its second factor
sees neither. dashboardAlerts: { integrations: 'admin' | 'editor' | 'all',
cookies: 'editor' | 'all' } loosens it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 5d35b2c3f4 M1 (7): a password rule for staff accounts (accounts.password)
When a password is set on a staff collection — a new account, the first-user
screen, a change, a reset by e-mail; panel, API and Local API alike — it must
have at least 12 characters and not be the account's own e-mail address.
Existing passwords are never checked: a shorter one keeps logging in and meets
the rule when it is next changed. accounts.password: { minLength } | false.
No breached-password lookup; checkPassword and the hook are exported.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 c6fc0d21fe M1 (6): nobody creates an account for themselves
accounts.adminOnlyCreate (on): a staff collection without a create rule gets
"an admin, fully signed in" instead of Payload's "any logged-in user" — also the
project's own collection; a rule the project wrote stays.
accounts.firstUserRoute ('panel'): Payload's first-user route answers only for
the collection the panel logs in with. For any other empty auth collection it is
refused, unless that collection's own create rule lets an anonymous request in.
Checked and closed: an empty second staff collection, whose first visitor became
a staff admin (test/accountRulesOff.test.ts records the old behaviour, which
accounts: false / firstUserRoute: 'all' still give).
Doctor: open-signup (deep, info) names auth collections with open sign-up.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 cd60b73685 M1 (5): the lowest role stays out of the admin panel (accounts.panelRole)
The panel opens for editor and above by default: Payload's access.admin on the
collection that carries the roles. An account that holds only `user` sees
"Unauthorized" there; the API is not touched. The rule looks at the role, not
at the second factor, so the 2FA screens stay reachable. accounts.panelRole:
'user' | false (everyone, as before) | 'admin'; accounts: false turns the account
rules off; the project's own access.admin wins. At start the log says how many
accounts the rule keeps out, and is an error when it keeps everyone out.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 463fd5d664 M1 (4): forms.turnstileOnConfigError — a form with files is refused while Turnstile cannot check
While Turnstile is degraded (wrong or missing secret, Cloudflare down) a text
form is still accepted, as before; a submission to the file endpoint is refused
by default. forms.turnstileOnConfigError sets it for every form or per kind
('allow' | 'reject' | { text, files }); a value at a call site still wins.
Nothing changes when Turnstile is off. The gates and the resolver are exported
from the server entry.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 42fdad8c2d M1 (2, 3): the Turnstile env secret is deprecated; doctor rules access-missing, turnstile-degraded, turnstile-env-key
(2) Stage one of the deprecation: TURNSTILE_SECRET_KEY from the environment still
works when the panel field is empty, logs once that it is deprecated, and the
doctor's deep status reports it (rule turnstile-env-key, warning). Nothing is
removed.
(3) access-missing (static, warning): ipalKit without `access` means every panel
account is an admin. turnstile-degraded (deep): Turnstile is not checking forms —
warning, error after a day. The deep status carries the recorded state and where
the secret comes from, never a key.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 8fa71238ce M1 (1): stored secrets are write-only
smtpPassword and turnstileSecretKey in the Site integrations global are returned
as '********' to every read that goes through access control (REST, GraphQL, the
panel's form state); the Local API with access control off still gets the value.
A save that sends nothing, an empty value or the mask keeps the stored one;
'[[clear]]' removes it. MaskedField says that a value is set and offers to
remove it. Off: secrets: { writeOnly: false }. writeOnlySecret(s) and the hooks
are exported for a project's own fields.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Opus 5.5 de414a81a8 Role checks in client components: export them from /client, fix the docs
access.md and the 1.16.4 upgrade notes led projects to import isAdmin from
'@intecion/ipal-kit' in a client component; with `next build --webpack` that
fails ('server-only' cannot be imported from a Client Component module).
No existing entry had a client-safe one, so '@intecion/ipal-kit/client' now
exports hasMinimumRole, isAdmin, isEditor and the type Role; the main entry
keeps them for server code.

Docs: access.md (snippet with imports, server vs client, useConfig() carries
admin.user only), AGENT.md, ipal-debug, ipal-reference, ipal-upgrade, the
1.16.4 note, an Unreleased changelog entry. Tests: /client reaches no
server-only module, the predicates' answers with a client config, no
client-component example in the docs imports the main entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 22:00:27 +01:00
Radosław SmolińskiandClaude Opus 5.5 1270ebc3d1 1.16.6 upgrade notes
CI / check (push) Failing after 5m28s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 20:38:42 +01:00
Radosław SmolińskiandClaude Opus 5.5 0356a329ca 1.16.6
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 20:38:42 +01:00
Radosław SmolińskiandClaude Opus 5.5 b3a5ea1323 Merge claude/2fa-setup-required: an account without 2FA can only set it up (twoFactor.requireSetup)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 20:38:00 +01:00
Radosław SmolińskiandClaude Fable 5.2 b52193ae47 2FA setup required: the missing-column log reads the error's cause chain
R3-1: the SQL adapters throw "Failed query: …" and put the database's own words
("column … does not exist", "no such column") in the error's cause, so the loud
start-up line never appeared on a real Postgres or SQLite. The reason is now
built from the whole cause chain; other failures (ECONNREFUSED, a locked
database) still only warn. Tested with wrapped errors and against the real
adapter with the column dropped.

Docs and the doctor's fix text name how the migration is applied
(deployment.md 4.3) wherever they said only "before the site serves".

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 20:31:44 +01:00
Radosław SmolińskiandClaude Fable 5.2 01e3813723 2FA setup required: review round 2 — no SVG from the icon endpoint, migrations at container start
R2-1: /api/ipal/admin-icon answers with bytes only for a bitmap recognised by its
first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF). An SVG favicon keeps the redirect
to the media file: a site-wide CSP rule overrides a route's own sandbox header,
so the header alone protected nothing in a built site. buildUploadSecurityHeaders
also returns a rule for the icon path, as a second layer.
R2-2: the SQL migration runs when the new container starts (prodMigrations, or
the start command), never in Coolify's pre-deployment command; docs and the log
line say so and point to deployment.md 4.3.
R2-3: requireSetup: null is the default. R2-4: the missing-column log line only
for a column error. R2-5, R2-6: the resetAccess example keeps the code check;
with guard: false the reset endpoint does not exist.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 20:18:47 +01:00
Radosław SmolińskiandClaude Fable 5.2 75a6f5209e 2FA setup required: review fixes (SR-1 to SR-9)
SR-1: /api/ipal/admin-icon sends the upload security headers (sandbox policy,
nosniff) with the bytes: an SVG is shown, never run. fetchPublicImage stops
reading at the size limit.
SR-2: requireSetup.exempt exempts only on exactly true; an async function, and a
windowHours that is not a number or false, stop the start.
SR-3: on Postgres / SQLite the missing column makes every login fail: the log
says so, the docs call the migration a required step of the same deploy, and
ipal-doctor reports a SQL project without it.
SR-4: an admin's reset also ends the account's sessions.
SR-5: the reset needs a session that entered its own TOTP code by default.
SR-6: the doctor's import-map rule covers TwoFactorStatusField and TwoFactorAlert.
SR-7: building blocks exported; dashboard notice, status field, setup notice and
the server-side image fetch can be switched off one by one.
SR-8: totpSetupFrom is on the 2FA collection whenever 2FA is on.
SR-9: both ways out of "every administrator is blocked" in security.md.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 19:32:34 +01:00
Radosław SmolińskiandClaude Fable 5.2 9d2ab43438 2FA setup required: the window of existing accounts starts once, at the first start after the upgrade
Owner's decision: for accounts that exist before the upgrade the 72 hours
count from the first start after it. The code already stamped them then; this
adds the tests that the moment is written once per account (a restart, two
instances starting at once, edits and logins do not move it; 71 h after it setup
is open, 73 h after it the account is blocked) and says so in the docs.

After the rebase on 1.16.5: tests that the setup-required notice and the stale
import-map notice both stand above the screen and never replace the code form,
and that requireSetup, safeBack and guard switch independently.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 18:56:07 +01:00
Radosław SmolińskiandClaude Fable 5.2 5d44ac3135 2FA screens: the brand image loads for a session that still owes its code; browser spec checks it
The tab icon endpoint answers with the image itself instead of a redirect
to the media file, and the logo components hand a session that owes its
2FA code (or has not set 2FA up) the picture fetched without credentials,
as an anonymous visitor gets it. Who can read media is unchanged; when the
file is not public or is larger than 512 KB the site name is used.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 18:46:32 +01:00
Radosław SmolińskiandClaude Fable 5.2 2aaaaa115a 2FA setup required: an account without TOTP reaches only setup, within a 72 h window
twoFactor.requireSetup (on by default with 2FA): an account of the 2FA
collection that has not set TOTP up is refused by ipal-kit's second-factor
check on every collection, global and plugin endpoint; the setup screen and
/api/setup-totp are all it reaches. It has 72 hours from its creation or
from an admin's reset (field totpSetupFrom, stamped by a hook); after that
setup is refused too until an admin reopens it.

Accounts that existed before get their window at the first start after the
upgrade (backfill in onInit), so nobody is blocked when a site upgrades.

Admin side: status and reset / 'Reopen setup' button on the account page
(TwoFactorStatusField), POST /api/ipal/two-factor/reset, a dashboard notice
(TwoFactorAlert), a notice on the setup screen; texts in English and Polish.
ipal-doctor reports blocked accounts and a switched-off mode.

Overridable: requireSetup false, windowHours (false / 0 = none), exempt for
a service account, resetAccess; the per-entity second-factor opt-out applies.
API keys, seeds, bearer-token routes and sites with twoFactor false are not
affected.

HTTP tests (REST, GraphQL, first admin on an empty database) run on SQLite,
Postgres and MongoDB; a browser test on the reference site covers the first
admin, a new editor and the admin's reset. Docs, guide, skills, changelog.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 18:46:32 +01:00
Radosław SmolińskiandClaude Opus 5.5 45d52c4690 1.16.5 upgrade notes
CI / check (push) Failing after 5m27s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:50:25 +01:00
Radosław SmolińskiandClaude Opus 5.5 bef3a682b8 1.16.5
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:50:25 +01:00
Radosław SmolińskiandClaude Opus 5.5 f96b5c15d0 Merge claude/2fa-safe-back: the back link of the 2FA screens is checked on the server (twoFactor.safeBack)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:49:47 +01:00
Radosław SmolińskiandClaude Fable 5.2 3eee841dd0 ipal-doctor: the raw 2FA view warning only for a view component
R3-1: the warning fired on any mention of the 2FA package's setup / verify view
in the config, so it stayed after the fix its own text suggests (SafeTotpView
with the path as ipalTotpView, plus the path in admin.dependencies). It now
warns only when the path is a view's Component.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 17:49:06 +01:00
Radosław SmolińskiandClaude Fable 5.2 b2c1dca5da 2FA back link: the stale import-map notice never replaces the screen
R2-1: the notice was rendered instead of the 2FA screen, and its flag is a text
search of the importMap.js on disk — not the map in the build. A false alarm
(map generated in the build with the repository's file in the running image, a
re-exporting map) hid a working code form and locked everyone out. The notice
is now rendered above the screen, the log line says "may be", and the flag goes
to ipal-kit's own provider only.

R2-2: views are compared against copies, so a factory that reuses its view
objects is guarded too; copyViews, changedViewKeys, SAFE_TOTP_VIEW,
totpViewImportKey, findImportMapFile and missingImportMapEntries are exported;
ipal-doctor warns when the config registers the 2FA package's own view; docs
wording and a misplaced comment fixed.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 16:35:16 +01:00
Radosław SmolińskiandClaude Fable 5.2 ad51456eaa 2FA back link: review fixes — views guarded by object, client views, a loud stale import map
SB-1: the 2FA package replaces a view that already stands under its keys, so a
key that existed before the factory ran was wrongly treated as the project's own
and left unguarded (also with a double registration, or ipalKit over its own
output). Views are now compared by object, right after the factory.

SB-2: SafeTotpView renders through Payload's RenderServerComponent: a client
component set as a 2FA view gets only client props plus the checked back.

SB-3: a production build with the previous import map shows an empty 2FA screen.
twoFactor.importMapCheck (on, production only) reads the committed map at start:
an error in the log and a message on the 2FA screens. Docs name the real symptom.

SB-4: enabled: false restores admin.dependencies; wrapTotpViews keeps exportName.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 16:16:39 +01:00
Radosław SmolińskiandClaude Fable 5.2 93e75426ab 2FA screens: the back link is checked on the server (twoFactor.safeBack)
@clocklimited/payload-2fa sends the browser to the `back` query value after a
valid code without checking it (GHSA-rffw-fq79-g3ch upstream, not fixed in the
fork): a prepared link ran script in the panel or left the site.

SafeTotpView now stands in front of the package's setup and verify views and
passes on a checked value: a path on the site's origin inside the admin route,
else the admin root. The package's views stay in the import map through
admin.dependencies, so ipal-kit still never imports the package.

twoFactor.safeBack: false turns it off, a function replaces the rule;
safeAdminBack, wrapTotpViews and SafeTotpView are exported. Projects with 2FA
must regenerate the admin import map.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 15:29:06 +01:00
Radosław SmolińskiandClaude Opus 5.5 39309c5c1c CHANGELOG 1.16.4: the verify limit counts every try; lockout from a sibling subdomain
CI / check (push) Failing after 5m29s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 09:36:54 +01:00
Radosław SmolińskiandClaude Opus 5.5 d722157e20 1.16.4 upgrade notes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 09:35:08 +01:00
Radosław SmolińskiandClaude Opus 5.5 03443fd7ee 1.16.4
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 09:35:08 +01:00
Radosław SmolińskiandClaude Opus 5.5 f0f26393a3 Merge claude/security-fix-staff-check-2fa: staff checks only for staff collections; 2FA covers everything
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 02:26:56 +01:00
Radosław SmolińskiandClaude Fable 5.2 dc5326ea1c Review round 3: job-queue rules keep Payload's own defaults; a failed 2FA lookup fails closed
Job queue (R3-1): only a rule that exists is wrapped. At config time that
is what the project wrote; Payload fills in the rest when it builds the
config (3.94.1: run, queue and cancel are all defaultAccess, a logged-in
user) and the sweep of the running config wraps those. No default is
invented, so a request without a user gets what Payload itself answers.

hasTotp false while the account's record carries a TOTP secret (the 2FA
package's own lookup failed, R3-4): the account owes its code, not
'not set up yet'.

Docs: the two-configs-in-one-process case for calls without a source, and
that a half-logged-in editor's browser is refused media files.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 02:22:04 +01:00
Radosław SmolińskiandClaude Fable 5.2 c56f0d41b8 Security review round 2: no exception by name, staff list fails closed, verify limit
R2-1: the sweep skipped every collection whose slug starts with payload-,
so a plugin's payload-... collection added after ipalKit was never guarded.
There is no exception by name or prefix now: every collection and global
is guarded, Payload's own included, and the job queue's run / queue /
cancel rules too.

R2-2: role predicates called without a source fail closed where the staff
collections are not known (browser bundle, middleware, edge): nobody is
staff. They accept req.payload, a config (also the client config) or
{ staffCollections } as the source.

R2-3: the staff list is filed per config / Payload instance; a call without
a source gets only what every config in the process calls staff.

R2-4: payload.config is watched on the instance, so a config swapped in by
a dev reload is guarded before any request or Local API call.

R2-5: verify attempts are limited per account (default 5 in 10 minutes,
twoFactor.verifyLimit), counted in memory, never skipped.

R2-6: a user object without collection owes the second factor; endpoints
the 2FA package may add on collections or globals are guarded too; a
warning names staff collections that 2FA does not cover; docs state what
is not covered, fix the one-argument examples and the doctor example.

HTTP tests for each on payload-2fa beta.7, run on SQLite, Postgres and
MongoDB (test adapter added).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 01:46:25 +01:00
Radosław SmolińskiandClaude Fable 5.2 32faaa5e30 Security review fixes: staff collection first everywhere, 2FA package endpoints guarded, per-entity opt-out, hot reload
F1: roles count only for accounts of a staff collection, in every exported
predicate and access builder (isAdmin, isEditor, hasMinimumRole, adminOnly,
adminOrEditor, requireRole, adminOrSelf, adminOrSelfIn, the Field variants,
the roles field) and first in userMeetsRole. An account of another auth
collection with its own roles: ['admin'] gets nothing. Staff collections:
admin.user, access.authCollection, access.staffCollections. Predicates take
req.payload as an optional last argument and otherwise use the staff
collections of the config ipalKit built in this process.

F2: every endpoint @clocklimited/payload-2fa registers answers accounts of
the 2FA collection only (setup-totp wrote the secret into the 2FA collection
under the caller's id, whatever collection the caller came from); remove and
the admin reset/remove endpoints also need the second factor.

F3: per-entity opt-out honoured, operation by operation: the package's
custom.totp.disableAccessWrapper and ipal-kit's custom.ipal.secondFactor
(passed on to the package); the package's global disableAccessWrapper too.

F4: a no-user auth strategy on the 2FA collection guards the live config at
the start of each request, so entities from plugins listed after ipalKit
stay guarded after a dev hot reload and with disableOnInit.

Tests through HTTP for all four; the 2FA tests now run on payload-2fa
3.0.0-beta.7 (what client sites use), a second file on beta.1 (alias), and
the HTTP files can run against Postgres (IPAL_TEST_POSTGRES_URI). Docs,
agent guide, skills and changelog updated; the not-yet-enrolled limitation
is stated plainly.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 01:02:34 +01:00
Radosław SmolińskiandClaude Fable 5.2 97ee1289aa Reference smoke test: send the site origin so the login cookie counts; test typing
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 00:38:01 +01:00
Radosław SmolińskiandClaude Fable 5.2 0c61ac231b Security: staff checks only for staff collections; 2FA covers what the plugin adds
Staff check (userMeetsRole): the 'no roles field = every account passes'
rule applied to the account's own collection, so an account of a second
auth collection (customers) passed every staff check. It now applies only
to staff collections: the panel's login collection plus the new
access.staffCollections. The injected auth collection uses the new
adminOrSelfIn(slug), so an account of another collection with the same
numeric id is not 'self'.

2FA: @clocklimited/payload-2fa wraps the collections and globals present
when it runs; ipalKit's own globals and collections were added later and
stayed unwrapped, so a password without the TOTP code opened them over
REST and GraphQL. ipal-kit now has its own second-factor check
(secondFactorPassed / requireSecondFactor): applied to every collection
and global at the end of ipalKit, again in onInit for entities added by
plugins listed after it, and inside userMeetsRole and the endpoints that
take a project access function. It fails closed: an unrecognised user
shape is refused, and startup stops when the injected 2FA plugin lacks
the parts the check reads (twoFactor.guard: false opts out).

Tests through real HTTP requests (REST and GraphQL) against Payload's
route handlers, plus the reference smoke test. Docs, agent guide, skills
and the reference skills copy updated; changelog entry without a version.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 00:31:55 +01:00
Radosław SmolińskiandClaude Opus 5.5 bc1045a5b7 Merge claude/drift-decisions-1163: PAYLOAD_SECRET minimum in production, doctor seen in CI, create --external
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:09:26 +01:00
Radosław SmolińskiandClaude Opus 5.5 71fea221f1 Merge claude/docs-drift-1163: docs brought in line with the 1.16.3 code
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:09:26 +01:00
Radosław SmolińskiandClaude Opus 5.5 0d8d906653 Comments: tab name Search engines, credit text, generateStaticParams scope
Comments and the ipal-kit usage line only (adds ipal-doctor); no behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:19 +01:00
Radosław SmolińskiandClaude Opus 5.5 b5df59691c ipal-kit create: a bare --external installs every external skill
Matches the help text and docs/project-starter.md; a list stays as given,
no flag leaves it to the answers. resolveExternal() + test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:19 +01:00
Radosław SmolińskiandClaude Opus 5.5 5cd0224ebd ipal-doctor: never write first-seen dates when CI is set
The CLI ignored CI (writeSeen was only !sites && !json); docs and comments
already said "not in CI". shouldWriteSeen() + test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 36f8f69f82 ipalEnvRules: PAYLOAD_SECRET at least 32 characters in production
New option secretMinLength (default 32, 0 turns it off); checked only with
NODE_ENV=production. Docs: env table, deployment (what changing the secret
does, checked in Payload 3.94.1 and payload-2fa), AGENT.md, ipal-reference,
ipal-setup. Tests: short secret fails in production, passes in dev, 0 and a
custom minimum.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 40fed78da2 Docs: forms reject text over 5000 characters; Site settings update is editor+
(a) The code rejects an over-long value (kind 'too_long', validation text at
the field, answers kept); the limit is fixed. (c) Site settings update needs
the editor role; overridable with globalOverrides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 37592764b5 Docs: fix doc/code drift found against 1.16.3 (docs only)
Verified the IAWL summary's "Doc/code" notes against the code and swept
CLI flags, option names/defaults and env vars. Fixed in the docs:
admin groups (consent-records, cookie-review → Privacy; Form messages
global → Forms), tab labels (More, Spam protection, E-mail sending,
Search engines; Sending method), construction field labels, {field} =
label, globalOverrides instead of "a plugin after ipalKit", enabled:false
keeps globals, pages role labels en+pl, switchLocalePath prefix,
accessibility cookie (necessary), seeding summary() shape, prepublishOnly
chain, doctor --strict --offline in the starter, package files list,
ipal-skills --external in PROGRAMISTA, DATABASE_URI (not _URL),
uploadsCollection exists, SiteProviders nonce, buildLinksField labels,
MCP list_pages limit wording, IPAL_DOCTOR_TOKEN in the env table; shipped
seo-check message "Search engines". Reference skills copy refreshed.

Open questions (not changed): forms over-long text, PAYLOAD_SECRET
length, Site settings update access, doctor seen in CI, bare
`ipal-kit create --external`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 23:47:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 e603561de4 1.16.3: renumber the prepared release (was 1.17.0)
CI / check (push) Failing after 6m22s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:53:57 +01:00
Radosław SmolińskiandClaude Opus 5.5 e29f882aa6 1.17.0 upgrade notes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:46:47 +01:00
Radosław SmolińskiandClaude Opus 5.5 195ca3ab11 1.17.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:46:40 +01:00
Radosław SmolińskiandClaude Opus 5.5 b9df570e84 Merge claude/deps-payload-3-94: Payload 3.94.1, dependency updates, overrides re-checked
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:43:23 +01:00
Radosław SmolińskiandClaude Opus 5.5 a0c576e54c Dev audit: @swc/cli 0.8.2, vite 7.3.8; Node 22.23.5 check in Coolify
@swc/cli 0.8.0 still resolved piscina 4.9.3 and @xhmikosr/decompress 10.2.1
(the two criticals). 0.8.2 with refreshed transitive deps and vite 7.3.8 as a
direct dev dependency take the dev-tree audit from 31 to 4 (0 high, 0 critical).
Docs: Payload 3.94 needs Node 22.23.5+ also in Coolify; how to check it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:43:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 ab51027617 Payload 3.94.1, dependency updates, overrides re-checked
- payload and every @payloadcms/* 3.94.1 in the plugin's dev dependencies, the
  reference site and the starter (peer range unchanged: ^3.90.2); react/react-dom
  19.3.1; reference engines node >=22.23.5 <23 (Payload 3.94's minimum).
- Overrides re-checked: dompurify and happy-dom still needed; mongoose (3.90–3.93)
  and undici (3.90–3.91) only on an older Payload; graphql-scalars no longer needed
  (GHSA-x8rm-f576-gq67 covers 1.24.1–2.0.0; Payload pins 1.22.2). Reference keeps
  dompurify + happy-dom; plugin root drops graphql-scalars.
- ipal-doctor transitive-min: the mongoose fix names the Payload upgrade first.
- nodemailer 10.6.1; dev: playwright 1.65.1, vitest 5.1.1, prettier 3.10.1,
  @swc/cli 0.8, rimraf 6 (clean uses --glob), cross-env 10, open 11,
  sort-package-json 4, @swc-node/register 1.12.1, vite-tsconfig-paths 6.1.1;
  reference tailwind 4.3.5, postcss 8.5.33.
- Kept back: typescript 7, eslint 10, graphql 17, @types/node 26, lucide-react 1.x.
- AGENT.md §4 item 12, ipal-setup, ipal-upgrade, README, PROGRAMISTA §1, forms.md,
  doctor.md; reference skills copy; CHANGELOG Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 15:18:58 +01:00
Radosław SmolińskiandClaude Opus 5.5 13b66413f8 1.16.2 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.16.2" section. PROGRAMISTA §6: item 63. Reference site: skills
and the AGENTS.md pointer on 1.16.2; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 00:19:11 +01:00
Radosław SmolińskiandClaude Opus 5.5 5d9bc10cfd 1.16.2
Version bump; the Unreleased section becomes 1.16.2: pnpm.overrides for Payload's
mongoose (8.24.1 → ~8.24.10; GHSA-pcrw-h46h-c93h critical and four more) and
happy-dom (20.x → ^21.0.4; two highs) in the reference site and the starter; new
ipal-doctor rule transitive-min and DoctorContext.installedAll(name). What projects
must update: every MongoDB site adds the two override lines (Postgres/SQLite: the
happy-dom one), reinstalls, rebuilds and redeploys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 00:19:11 +01:00
Radosław SmolińskiandClaude Opus 5.5 1917686b52 Merge claude/inspiring-goldstine-66f9c2: mongoose and happy-dom overrides, doctor rule transitive-min
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 00:18:49 +01:00
Radosław SmolińskiandClaude Fable 5.2 de8362820f Overrides for Payload's mongoose and happy-dom advisories; doctor rule transitive-min
@payloadcms/db-mongodb pins mongoose 8.24.1 (one critical, two high, two moderate
advisories, fixed by 8.24.7) and @lexical/headless 0.50 brings happy-dom 20.x (two
high, fixed by 21.0.4). Payload 3.93.0 fixes neither.

- reference/package.json (and so the starter): pnpm.overrides for mongoose
  (~8.24.10) and happy-dom (^21.0.4); pnpm audit --prod on the reference is clean
- root package.json: the happy-dom override for the plugin's own dev tree
- ipal-doctor: transitive-min reports mongoose 8.x < 8.24.7 (error) and
  happy-dom < 21.0.4 (warning) from the lockfile and prints the override line;
  DoctorContext.installedAll(name)
- AGENT.md §4 item 12, ipal-setup, ipal-upgrade, doctor.md, README, CHANGELOG

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-17 00:01:58 +01:00
Radosław SmolińskiandClaude Opus 5.5 7c034a07ef 1.16.1 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.16.1" section. PROGRAMISTA §6: item 62. Reference site: skills
and the AGENTS.md pointer on 1.16.1; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:49:14 +01:00
Radosław SmolińskiandClaude Opus 5.5 5c9eeaf330 1.16.1
Version bump; the Unreleased section becomes 1.16.1: Next.js 16.4.6 in the plugin,
the reference site and the starter; minimum safe version 16.4.5 because of
GHSA-mfr8-8qww-v76h (16.3.0–16.4.4); ipal-doctor next-min raised. What projects
must update: every site below 16.4.5 runs
`pnpm add [email protected] [email protected]` and redeploys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:49:10 +01:00
Radosław SmolińskiandClaude Opus 5.5 ad6011b66a Merge claude/next-16-4-6: Next.js 16.4.6, minimum safe 16.4.5 (GHSA-mfr8-8qww-v76h)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:49:02 +01:00
Radosław SmolińskiandClaude Opus 5.5 9b03c94979 Next.js 16.4.6; minimum safe version 16.4.5 (GHSA-mfr8-8qww-v76h)
Next.js 16.3.0–16.4.4 is affected by GHSA-mfr8-8qww-v76h (CVE-2026-119790, moderate:
information disclosure across root params when a 'use cache' function is called
through unstable_cache()), first patched in 16.4.5.

- next and eslint-config-next 16.4.6 in the plugin's dev dependencies and the
  reference site (the starter is generated from it); lockfiles refreshed.
- ipal-doctor next-min: error below 16.4.5, naming the advisory; fix
  `pnpm add [email protected] [email protected]`; still silenceable. Tests.
- AGENT.md §4 item 11, ipal-setup, ipal-upgrade, doctor.md: minimum 16.4.5;
  reference skills copy refreshed. CHANGELOG Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:45:17 +01:00
Radosław SmolińskiandClaude Opus 5.5 ba3d57a77a 1.16.0 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.16.0" section. PROGRAMISTA §6: item 61. Reference site: skills
and the AGENTS.md pointer on 1.16.0; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 17:19:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 7f0c2f9d72 1.16.0
Version bump; the Unreleased section becomes 1.16.0: files on panel forms, checked,
e-mailed to the company and never stored (forms.attachments, File field, streamed
endpoint with the security wall and abort/timeout handling); attachments over SMTP
and Microsoft Graph (upload session, mailbox copy deleted); test e-mail with a
10 MB file; Turnstile reset and BuilderForm honeypot fixes; Graph token cache.
What projects must update: nothing required; to use files — option, File field,
migration on Postgres/SQLite, formClasses keys, proxy body limit, Graph
Mail.ReadWrite or SMTP. Verify on real systems: Graph 10 MB send and cleanup,
Traefik timeout on a slow upload, SMTP size limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 17:18:50 +01:00
Radosław SmolińskiandClaude Opus 5.5 3cde9974d0 Merge claude/form-attachments-9694cb: files on forms, e-mailed and never stored
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 17:13:55 +01:00
Radosław SmolińskiandClaude Fable 5.2 6f006825a4 Form files: an upload aborted while the gates are pending no longer leaves its attempt key registered
Re-review of 1.16.0: beforeFiles could resume after the request was answered and
register the attempt key with nobody left to release it. It now stops after every
await once the request is over; the registration has no await before it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:09:14 +01:00
Radosław SmolińskiandClaude Fable 5.2 7ecfb26eb1 Reference: refreshed skills copy (upload timeouts)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:04:03 +01:00
Radosław SmolińskiandClaude Fable 5.2 e24c918d4b Form files: a dropped, stalled or endless upload is aborted and frees its slot, attempt key and buffers
Security review of 1.16.0 (blocking): a request body that errored mid-file never
resolved, leaking the concurrency slot and the attempt key. Also: idle and request
timeouts (submit.idleTimeoutMs / timeoutMs), ImmutableId preference on every Graph
draft call, the remaining total in the too-large message, files sent to a form
without a File field are refused and logged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:02:10 +01:00
Radosław SmolińskiandClaude Fable 5.2 cd74d7decb Reference: refreshed skills copy and generated types for the file messages
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:52:18 +01:00
Radosław SmolińskiandClaude Fable 5.2 97202ee03e Form files: the visitor is told when the problem is the file — why and what to do; UTF-8 file names
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:51:05 +01:00
Radosław SmolińskiandClaude Fable 5.2 b6f9f34705 Form attachments: tests for project options and the concurrency guard
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:44:41 +01:00
Radosław SmolińskiandClaude Fable 5.2 ea43d94dd2 Reference index: describe the mail sink
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:43:41 +01:00
Radosław SmolińskiandClaude Fable 5.2 fdb6140c09 Form attachments: reference smoke test with a mail sink, Turnstile reset fix, docs
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:42:39 +01:00
Radosław SmolińskiandClaude Fable 5.2 387debc88c WIP: reference site — File field on the quote form, mail sink smoke test
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:34:34 +01:00
Radosław SmolińskiandClaude Fable 5.2 b7fb1b0e31 WIP: form attachments — agent guide, skills, seed template, changelog
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:32:45 +01:00
Radosław SmolińskiandClaude Fable 5.2 344574d6bd WIP: form attachments docs (forms, email, security, storage, deployment, notifications), honeypot value sent
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:30:44 +01:00
Radosław SmolińskiandClaude Fable 5.2 701bb420c1 WIP: form attachments — unit tests, test e-mail with attachment, lint
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:28:22 +01:00
Radosław SmolińskiandClaude Fable 5.2 02b1e96d3d WIP: form attachments tests
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:24:27 +01:00
Radosław SmolińskiandClaude Fable 5.2 6003b3d7d7 WIP: form attachments (e-mail only) — core, endpoint, Graph large upload
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:20:02 +01:00
Radosław SmolińskiandClaude Fable 5.2 0ba0014ed5 Form attachments proposal: Graph upload session recommended (Mail.ReadWrite already granted)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:04:07 +01:00
Radosław SmolińskiandClaude Fable 5.2 62bed415ed Form attachments proposal: e-mail only, no storage (revision 2)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:01:18 +01:00
Radosław SmolińskiandClaude Fable 5.2 d2caf8c2ae Form attachments: design proposal
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 15:55:45 +01:00
Radosław SmolińskiandClaude Opus 5.5 755f510c9f 1.15.5 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.5" section. PROGRAMISTA §6: item 60. Reference site: skills
and the AGENTS.md pointer on 1.15.5; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:35:22 +01:00
Radosław SmolińskiandClaude Opus 5.5 970307f3ab 1.15.5
Version bump; the Unreleased section becomes 1.15.5: required fields with
references are seeded complete; a stricter dry run (missing $form / $page is an
error there too). What projects must update: nothing required; a required reference
cycle now fails clearly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:35:22 +01:00
Radosław Smoliński c7e198fd92 Merge claude/seeder-required-refs: required fields with references are created complete
createSeeder's first pass resolves { $page } / { $form } references to existing
records, so a required layout is created complete; a forward $page is filled in
pass 2 and a record whose required field needs it waits for that page. Required
cycles and never-appearing targets are an error with nothing written; the dry run
reports the same, including a missing $form. Guards, create-only, the edit check
and SEED_ONLY are unchanged. Reported from vanstevpl-web.
2026-11-13 14:31:52 +01:00
Radosław SmolińskiandClaude Opus 5.5 748ef9286f Seeder: required fields with references are created complete (1.15.5)
A page whose required layout holds a { $page } / { $form } reference could not be
created: pass 1 left the whole field out, validation rejected the record, and the
dry run reported a create (vanstevpl-web, 1.15.4).

- pass 1 resolves references to records that exist (or were created earlier in
  the run), so the field is written complete
- a { $page } to a page later in the same call is null in pass 1 and filled in
  pass 2; a record whose required field needs it is retried once that page exists
- required links in a cycle and references to pages or forms that never appear
  are an error with nothing written; unknown page targets are found while
  planning, so the dry run reports them too
- dry run: a missing form is an error (was a placeholder); a form planned earlier
  in the same dry run counts as existing
- real-Payload tests (pl, en, de): the report's careers page, an existing form
  target, optional and required forward links, a cycle, missing page and form,
  create-only second runs, dry-run parity
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:29:41 +01:00
Radosław SmolińskiandClaude Opus 5.5 179d5b0d79 1.15.4 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.4" section (repair with SEED_UPDATE, live site with SEED_ONLY,
edited records and global arrays by hand). PROGRAMISTA §6: item 59. Reference site:
skills and the AGENTS.md pointer on 1.15.4; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:39:27 +01:00
Radosław SmolińskiandClaude Opus 5.5 2f00fe3ad6 1.15.4
Version bump; the Unreleased section becomes 1.15.4: seeding whole localized arrays
keeps every language. What projects must update: nothing required; repairing records
an earlier seed wrote needs SEED_UPDATE=1 (locally first; on production with SEED_ONLY
and IPAL_SEED_ALLOW_PROD_UPDATE=1 after a backup), edited records and global arrays
by hand.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:39:26 +01:00
Radosław Smoliński a79740cd44 Merge claude/seeder-localized-arrays: whole localized arrays keep every language
createSeeder / writeLocales: a value seeded per language as a whole (form fields,
nested select options, page layouts, global arrays) keeps the stored row ids in
every locale instead of only the last language surviving; localized: true fields
keep rows per locale. Seed guards, the edit check and SEED_ONLY are unchanged.
Reported from vanstevpl-web.
2026-11-12 15:35:38 +01:00
Radosław SmolińskiandClaude Opus 5.5 00e814e3ca Seeder: whole localized arrays keep every language (1.15.4)
createSeeder / writeLocales: a value written per locale as a whole —
fields: { pl: [...], en: [...], de: [...] }, a page layout, a global array —
returned the picked locale without walking into it, so each locale write made new
shared rows and only the last language survived (vanstevpl-web, 1.15.3).

- localize() localizes the picked value again with the stored rows, so row ids
  are shared across locales (arrays, blocks, nested arrays in blocks, groups)
- writeLocales passes the target's fields: a field that is itself localized
  (localized: true layout) never reuses another locale's row ids
- real-Payload regression test (pl, en, de): form with blocks and nested select
  options, shared and localized page layouts, global array via fillGlobal; a later
  PL save validates
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:33:35 +01:00
761 changed files with 53633 additions and 6158 deletions
+9 -9
View File
@@ -47,12 +47,12 @@ jobs:
- run: pnpm build
# file:.. + injected: the site gets a copy of the built plugin with its peers from the site (README.md)
- run: pnpm --dir reference install --frozen-lockfile --ignore-workspace
- run: pnpm --dir reference exec ipal-tokens --check
- run: pnpm --dir reference exec iapl-tokens --check
- run: pnpm --dir reference generate:importmap && git diff --exit-code reference/src/app
- run: pnpm --dir reference generate:types && git diff --exit-code reference/src/payload-types.ts
- run: pnpm --dir reference typecheck
# ipal-doctor (static, docs/doctor.md): the reference site is the zero-findings example — any unsilenced finding fails
- run: node bin/ipal-doctor.mjs reference --strict --offline
# iapl-doctor (static, docs/doctor.md): the reference site is the zero-findings example — any unsilenced finding fails
- run: node bin/iapl-doctor.mjs reference --strict --offline
# Full run on main (and before a release): MongoDB, seed, production build, smoke tests.
reference-full:
@@ -68,10 +68,10 @@ jobs:
DATABASE_URI: mongodb://127.0.0.1:27017/example-studiopl_dev
PAYLOAD_SECRET: ci-reference-secret-0123456789abcdef
NEXT_PUBLIC_SERVER_URL: http://localhost:3100
IPAL_IP_HEADER: x-forwarded-for
# cookieScanner.crawl → ipalEnvRules({ cookieCrawl }) requires both in production; CI never starts a crawl
IPAL_COOKIE_SCAN_URL: http://127.0.0.1:9/crawl
IPAL_COOKIE_SCAN_TOKEN: ci-cookie-scan-token-0123456789
IAPL_IP_HEADER: x-forwarded-for
# cookieScanner.crawl → iaplEnvRules({ cookieCrawl }) requires both in production; CI never starts a crawl
IAPL_COOKIE_SCAN_URL: http://127.0.0.1:9/crawl
IAPL_COOKIE_SCAN_TOKEN: ci-cookie-scan-token-0123456789
NEXT_PUBLIC_TURNSTILE_SITE_KEY: 1x00000000000000000000AA
TURNSTILE_SECRET_KEY: 1x0000000000000000000000000000000AA
ALLOW_LOCAL_MEDIA: '1'
@@ -98,8 +98,8 @@ jobs:
- run: pnpm --dir reference build
- run: pnpm --dir reference exec playwright install --with-deps chromium
- run: pnpm --dir reference test:e2e
# ipal-doctor (deep + HTTP): read-only database counts, the import map, the env rules, and the running site
# iapl-doctor (deep + HTTP): read-only database counts, the import map, the env rules, and the running site
- run: |
PORT=3100 pnpm --dir reference start &
for i in $(seq 1 60); do curl -sf http://localhost:3100/api/health >/dev/null && break; sleep 2; done
node bin/ipal-doctor.mjs reference --strict --offline --deep --url http://localhost:3100
node bin/iapl-doctor.mjs reference --strict --offline --deep --url http://localhost:3100
+2
View File
@@ -56,3 +56,5 @@ next-env.d.ts
# pnpm starter:gate work folder
.starter-gate/
.legacy-site-*/
.tmp-consent-upgrade-*
+2 -2
View File
@@ -5,7 +5,7 @@ Start with `.claude/skills/payload/SKILL.md` for a quick reference, then see `.c
## Main rule: the plugin helps projects, never limits them
ipal-kit is a plugin. Every change must leave the consuming project free to adapt it.
IAPL (Intecion Advanced Payload Library, package `@intecion/ipal-kit`, formerly ipal-kit) is a plugin. Every change must leave the consuming project free to adapt it.
- Every module and feature can be turned off on its own. Turning one off never takes away anything the project still needs.
- Every default can be overridden: access rules, fields, hooks, labels, routes, collections and globals. The project's own config is merged with the plugin's and wins.
@@ -15,7 +15,7 @@ ipal-kit is a plugin. Every change must leave the consuming project free to adap
## Rule: an agent that adds the plugin gets the complete guide
When an agent adds ipal-kit to a project, `docs/agent/AGENT.md` and the `ipal-*` skills (installed by `ipal-skills`) must tell it how to set up and use every function the plugin supports.
When an agent adds IAPL to a project, `docs/agent/AGENT.md` and the `iapl-*` skills (installed by `iapl-skills`) must tell it how to set up and use every function the plugin supports.
- Every export, option, env var, route, middleware, layout component, admin import-map entry and hook a project must wire is documented, with steps and a way to verify it.
- A change that adds or alters a feature updates the agent guide and the matching skill in the same change.
+27 -22
View File
@@ -1,13 +1,15 @@
# @intecion/ipal-kit
# IAPL (`@intecion/ipal-kit`)
Intecion Payload Advanced Library — a plugin for Payload CMS 3.
IAPL, the Intecion Advanced Payload Library — a plugin for Payload CMS 3. It was called ipal-kit before 1.17.0;
the package name, `@intecion/ipal-kit`, is unchanged, and every older name keeps working
([names table](./docs/agent/AGENT.md#names-iapl-and-ipal-kit)).
Provides internationalization (per-locale routing, hreflang, language switcher),
SEO (metadata, canonical, sitemap, robots), forms (Turnstile, rate limiting,
validation), consent management (consent mode), analytics (GA4/GTM), and a
blog/archive system (collections under an archive page, listing, pagination).
**Principle:** ipal-kit helps projects, never limits them — every module can be
**Principle:** IAPL helps projects, never limits them — every module can be
turned off on its own, every default (access, fields, hooks, labels, routes,
collections, globals) can be overridden and the project's config wins, and the
building blocks are exported, not only the finished features. Where the code
@@ -50,7 +52,7 @@ You *can* install straight from the repo
quick throwaway test it works. But prefer the registry for real projects:
- **Client components resolve correctly.** A git install unpacks into a
commit-hashed path (`.pnpm/@intecion+ipal-kit@git+https…#hash/…`) that breaks
commit-hashed path (`.pnpm/@intecion+IAPL@git+https…#hash/…`) that breaks
Next.js's React Client Manifest — the consent banner, analytics, and Turnstile
components fail at runtime with "Could not find the module … in the React
Client Manifest". The registry unpacks to a clean `node_modules/@intecion/…`
@@ -77,30 +79,33 @@ site with every team convention, installs it from a shipped lockfile and makes t
`nodemailer`, `lucide-react`, `slugify` and `server-only` are regular
`dependencies` of the plugin — they install with it; don't add them yourself.
The plugin's `nodemailer` 10 needs **Node.js 20 or later**.
The plugin's `nodemailer` 10 needs **Node.js 20 or later**; Payload 3.94 itself needs **Node.js 22.23.5 or later**
on the 22 line.
What you provide are the **peer dependencies** — packages the plugin shares with
your project — in a version matching your Payload:
your project — in a version matching your Payload. The plugin accepts Payload `^3.90.2`; the reference site and the starter use
**3.94.1** (with `react` / `react-dom` 19.3.1, which Payload 3.94 requires):
| Peer | Range | Notes |
|---|---|---|
| `payload`, `@payloadcms/next`, `@payloadcms/ui`, `@payloadcms/richtext-lexical` | `^3.90.2` | already in a `create-payload-app` project |
| `next`, `react` | `>=15`, `^19.0.0` | already in a `create-payload-app` project |
| `@payloadcms/plugin-seo`, `@payloadcms/plugin-form-builder` | `^3.90.2` | **add these** |
| `@clocklimited/payload-2fa` | `^3.0.0-0` | optional peer, but **needed by default**: 2FA is enforced and `ipalKit()` throws at startup unless you pass `twoFactor: { issuer, plugin: payloadTotp }` (or opt out with `twoFactor: false`) |
| `@clocklimited/payload-2fa` | `^3.0.0-0` | optional peer, but **needed by default**: 2FA is enforced and `iapl()` throws at startup unless you pass `twoFactor: { issuer, plugin: payloadTotp }` (or opt out with `twoFactor: false`) |
| `@payloadcms/storage-s3` | `^3.90.2` | optional — only when media go to Cloudflare R2 ([docs/storage.md](./docs/storage.md)) |
```bash
pnpm add @payloadcms/[email protected]0.2 @payloadcms/[email protected]0.2 \
pnpm add @payloadcms/[email protected]4.1 @payloadcms/[email protected]4.1 \
@clocklimited/payload-2fa
pnpm add @payloadcms/[email protected]0.2 # only with R2 media
pnpm add @payloadcms/[email protected]4.1 # only with R2 media
```
Keep every `@payloadcms/*` at exactly the same version as `payload`
(`pnpm.overrides` — see PROGRAMISTA.md §1). Then run `pnpm audit --prod`: with
`payload` 3.90.x, Payload's own tree pins a vulnerable `undici`, `dompurify` and
`graphql-scalars` (the last one even in the latest Payload) — add the three overrides from [AGENT.md §4 item 12](./docs/agent/AGENT.md) (recommended, not
required by the plugin). Upload optimization and image
(`pnpm.overrides` — see PROGRAMISTA.md §1). Then run `pnpm audit --prod`: even
Payload 3.94.1 brings a vulnerable `happy-dom` (via Lexical) and `dompurify` — add
the two overrides from [AGENT.md §4 item 12](./docs/agent/AGENT.md); an older Payload
also needs the `mongoose` (MongoDB adapter, up to 3.93) and `undici` (up to 3.91)
ones listed there (recommended, not required by the plugin). Upload optimization and image
placeholders also use the `sharp` you pass to `buildConfig({ sharp })`
(standard in a `create-payload-app` project).
@@ -112,19 +117,19 @@ placeholders also use the `sharp` you pass to `buildConfig({ sharp })`
**Working with an AI agent?** Run this right after installing (and after every upgrade):
```bash
pnpm exec ipal-skills
pnpm exec iapl-skills
```
It copies the `ipal-*` agent skills into `.agents/skills/` and adds a marked
`<!-- ipal-kit:start -->` block to `AGENTS.md` (plus a `CLAUDE.md` that imports it, if you
have none) pointing the agent at the full guide: `AGENT.md`, the `ipal-reference` skill
(every option, env var, route and export) and the `ipal-setup` skill. Only the text between
It copies the `iapl-*` agent skills into `.agents/skills/` and adds a marked
`<!-- iapl:start -->` block to `AGENTS.md` (plus a `CLAUDE.md` that imports it, if you
have none) pointing the agent at the full guide: `AGENT.md`, the `iapl-reference` skill
(every option, env var, route and export) and the `iapl-setup` skill. Only the text between
the markers is ever rewritten. `--no-pointer` skips that step. There is no `postinstall` script.
`pnpm exec ipal-skills --external` also adds a few well-known third-party skills as `ext-*` folders — Vercel's
`pnpm exec iapl-skills --external` also adds a few well-known third-party skills as `ext-*` folders — Vercel's
React best practices and composition patterns, Addy Osmani's accessibility skill, Anthropic's frontend-design
skill and the official Payload 3 skill. They are vendored into the package at pinned commits (text only, each
with its licence and source), so nothing is downloaded, and each starts with a note that ipal-kit's rules win.
with its licence and source), so nothing is downloaded, and each starts with a note that IAPL's rules win.
Pick some with `--external ext-accessibility,ext-payload`.
*Updating the pins (plugin maintainers):* change the commit in `scripts/vendor-external-skills.mjs`, run
@@ -161,7 +166,7 @@ clean working tree):
```bash
npm version patch # 1.0.0 → 1.0.1 (commit + tag)
npm publish # prepublishOnly runs: pnpm clean && pnpm build && pnpm test:int
npm publish # prepublishOnly runs: pnpm clean && pnpm build && pnpm build:starter && pnpm test:int && pnpm starter:gate
git push && git push --tags
```
@@ -191,7 +196,7 @@ Everything lives in the **[docs/](./docs)** directory. To get started:
| `404` on `pnpm add @intecion/...` | the `@intecion:registry` line is missing from `.npmrc` — the install went to public npm instead of Gitea |
| `Could not find the module … in the React Client Manifest` | installed from git, not the registry — reinstall from the registry (clean path) |
| two versions of `lucide-react` | your project uses a `lucide-react` outside the plugin's `^0.400.0` (= `0.400.x`) — align them |
| `[ipal] 2FA is enforced but no 2FA plugin was injected` | install `@clocklimited/payload-2fa` and pass `twoFactor: { issuer, plugin: payloadTotp }` |
| `[iapl] 2FA is enforced but no 2FA plugin was injected` | install `@clocklimited/payload-2fa` and pass `twoFactor: { issuer, plugin: payloadTotp }` |
| `missing secret key … to secure Payload` | `PAYLOAD_SECRET` isn't set in the runtime environment (not a plugin issue) |
If you get stuck, see **[docs/dev/PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** or message the
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env node
// iapl-blocks — the block library's command line.
// pnpm exec iapl-blocks list → the library blocks
// pnpm exec iapl-blocks eject faq → src/blocks/Faq/{config.ts,Component.tsx}
// pnpm exec iapl-blocks eject faq --dest src/blocks --dry-run
// Eject copies one block's source into the project, with its imports pointing at the
// package entries, so the project owns it: same slug and data shape, no migration.
// Then: use the ejected builder in Pages.layout instead of the library one, pass the ejected
// component as createBlockRegistry({ components: { faq: FaqBlock } }), record it in AGENTS.md.
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join, relative, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const args = process.argv.slice(2)
const [command, slug] = args
const dryRun = args.includes('--dry-run')
const destArg = args.indexOf('--dest')
const dest = resolve(process.cwd(), destArg >= 0 ? args[destArg + 1] : 'src/blocks')
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const libRoot = join(pkgRoot, 'src/modules/block-library')
const blocksRoot = join(libRoot, 'blocks')
if (!command || command === '--help' || command === '-h') {
console.log('Usage: iapl-blocks list | iapl-blocks eject <block> [--dest src/blocks] [--dry-run]')
process.exit(0)
}
const slugs = existsSync(blocksRoot) ? readdirSync(blocksRoot).sort() : []
if (command === 'list') {
console.log(slugs.join('\n'))
process.exit(0)
}
if (command !== 'eject' || !slug) {
console.error('Usage: iapl-blocks eject <block>')
process.exit(1)
}
if (!slugs.includes(slug)) {
console.error(`Unknown block "${slug}". Blocks: ${slugs.join(', ')}`)
process.exit(1)
}
/**
* Where an import inside the library goes in a project, by the file it points at.
* Config files (no React) take the Payload-side entries; components take /rsc and /client.
*/
const ROOT = '@intecion/ipal-kit'
const BLOCKS = '@intecion/ipal-kit/blocks'
const RSC = '@intecion/ipal-kit/blocks/rsc'
function target(file, isComponent) {
const rel = relative(join(pkgRoot, 'src/modules'), file).replace(/\\/g, '/').replace(/\.js$/, '')
if (rel.startsWith('block-library/')) {
const inner = rel.slice('block-library/'.length)
if (/^(define|fields|options|shared|types|faq|library|manifest|thumbnails)$/.test(inner)) {return BLOCKS}
return RSC // context, data, texts, ui/*
}
if (rel === 'lightbox/LightboxProvider' || rel === 'richtext/TableOfContents') {return '@intecion/ipal-kit/client'}
if (rel === 'forms/RenderForm' || rel === 'richtext/RenderRichText') {return '@intecion/ipal-kit/rsc'}
if (rel === 'richtext/headings') {return isComponent ? '@intecion/ipal-kit/rsc' : ROOT}
return ROOT
}
/** Rewrites relative imports to package entries and merges imports of the same entry. */
function rewrite(source, file) {
const isComponent = file.endsWith('.tsx')
const merged = new Map()
const body = source.replace(/^import (type )?\{([^}]*)\} from '(\.[^']+)'\n/gm, (_, type, names, spec) => {
const entry = target(resolve(dirname(file), spec), isComponent)
const key = `${type ? 'type ' : ''}${entry}`
const set = merged.get(key) ?? new Set()
for (const n of names.split(',').map((s) => s.trim()).filter(Boolean)) {set.add(n)}
merged.set(key, set)
return ''
})
const lines = [...merged].map(([key, set]) => {
const [type, entry] = key.startsWith('type ') ? ['type ', key.slice(5)] : ['', key]
return `import ${type}{ ${[...set].sort().join(', ')} } from '${entry}'`
})
return body.replace(/^((?:import [^\n]*\n)*)/, (head) => `${head}${lines.join('\n')}\n`).replace(/\n{3,}/g, '\n\n')
}
const folder = slug[0].toUpperCase() + slug.slice(1)
const outDir = join(dest, folder)
const files = readdirSync(join(blocksRoot, slug)).filter((f) => /\.(ts|tsx)$/.test(f))
for (const name of files) {
const from = join(blocksRoot, slug, name)
const to = join(outDir, name)
if (existsSync(to)) {
console.error(`skip ${relative(process.cwd(), to)} (exists — delete it first to eject again)`)
continue
}
const out = `// Ejected from @intecion/ipal-kit (block library: ${slug}). The project owns this file now.\n${rewrite(readFileSync(from, 'utf8'), from)}`
console.log(`${dryRun ? 'would write' : 'write'} ${relative(process.cwd(), to)}`)
if (!dryRun) {
mkdirSync(outDir, { recursive: true })
writeFileSync(to, out)
}
}
console.log(`\nNext: Pages.layout → the ejected build${folder}Block; registry → components: { ${slug}: ${folder}Block }; AGENTS.md → "Project decisions".`)
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env node
// iapl-doctor — checks a site against the IAPL team rules and lists every gap with a fix hint
// (docs/doctor.md). Static by default: reads files, writes nothing (except a first-seen date in
// iapl-doctor.json outside CI).
// pnpm exec iapl-doctor → this project, human-readable
// pnpm exec iapl-doctor --strict --offline → CI on a new site: any finding fails
// pnpm exec iapl-doctor --deep --url http://localhost:3000
// pnpm exec iapl-doctor --json > doctor.json
// pnpm dlx --package=@intecion/ipal-kit@latest iapl-doctor → the newest rules
// Exit: 0 ok · 1 findings · 2 could not run · 3 a rule crashed.
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
const { runDoctorCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'doctor', 'cli.js')).href)
process.exit(await runDoctorCli(process.argv.slice(2), { packageRoot: pkgRoot }))
+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env node
// iapl-skills — copies the IAPL agent skills into the project.
// pnpm exec iapl-skills → ./.agents/skills/iapl-*
// pnpm exec iapl-skills --dry-run → show what would change
// pnpm exec iapl-skills --dest .claude/skills
// pnpm exec iapl-skills --no-pointer → skills only, leave AGENTS.md / CLAUDE.md alone
// pnpm exec iapl-skills --external → also the vendored third-party skills (ext-*, pinned, text only)
// 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-<something> 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.
import { createHash } from 'node:crypto'
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { basename, dirname, join, relative, resolve, sep } from 'node:path'
import { fileURLToPath } from 'node:url'
const args = process.argv.slice(2)
if (args.includes('--help') || args.includes('-h')) {
console.log('Usage: iapl-skills [--dest <dir>] [--dry-run] [--no-pointer] [--external [ext-a,ext-b]]\nDefault dest: .agents/skills')
process.exit(0)
}
const dryRun = args.includes('--dry-run')
const pointer = !args.includes('--no-pointer')
const externalArg = args.indexOf('--external')
const externalPick = externalArg >= 0 && args[externalArg + 1] && !args[externalArg + 1].startsWith('-')
? args[externalArg + 1].split(',').map((n) => n.trim()).filter(Boolean)
: null
const destArg = args.indexOf('--dest')
const destValue = destArg >= 0 ? args[destArg + 1] : '.agents/skills'
// A missing value would resolve to cwd and remove every iapl-* folder there.
if (!destValue || destValue.startsWith('-')) {
console.error('iapl-skills: --dest needs a directory, e.g. --dest .claude/skills')
process.exit(1)
}
const dest = resolve(process.cwd(), destValue)
// Compared AFTER resolving links: `--dest root-link` (a link to `.`), `..` or `/` would otherwise pass and lose
// the iapl-* folders of the project root, its parent or the filesystem root. A folder that does not exist yet is
// resolved through its nearest existing parent.
const real = (path) => {
const rest = []
let at = path
while (!existsSync(at) && dirname(at) !== at) {
rest.unshift(basename(at))
at = dirname(at)
}
return join(realpathSync(at), ...rest)
}
const realDest = real(dest)
const realRoot = real(resolve(process.cwd()))
if (realDest === realRoot || realRoot.startsWith(realDest.endsWith(sep) ? realDest : `${realDest}${sep}`)) {
console.error(`iapl-skills: --dest must be a folder inside the project or elsewhere, not the project root or a folder that holds it (${destValue} is ${realDest})`)
process.exit(1)
}
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const src = join(pkgRoot, 'docs', 'agent', 'skills')
if (!existsSync(src)) {
console.error(`iapl-skills: no skills found in ${src} — is @intecion/ipal-kit installed with docs?`)
process.exit(1)
}
// Validate --external before anything is copied.
const extSrc = join(pkgRoot, 'docs', 'agent', 'external')
const manifest = externalArg >= 0 ? JSON.parse(readFileSync(join(extSrc, 'manifest.json'), 'utf8')) : { skills: [] }
const known = manifest.skills.map((skill) => skill.name)
const unknown = (externalPick ?? []).filter((name) => !known.includes(name))
if (unknown.length) {
console.error(`iapl-skills: unknown external skill(s): ${unknown.join(', ')} — available: ${known.join(', ')}`)
process.exit(1)
}
// 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)),
...(existsSync(dest) ? readdirSync(dest).filter((n) => LEGACY_SKILLS.includes(n) && isDir(dest, n)) : []),
]
if (!dryRun) mkdirSync(dest, { recursive: true })
for (const name of shipped) {
const action = existing.includes(name) ? 'update' : 'add '
console.log(`${action} ${name}`)
if (!dryRun) {
rmSync(join(dest, name), { recursive: true, force: true }) // drop files removed upstream
cpSync(join(src, name), join(dest, name), { recursive: true })
}
}
for (const name of retired) {
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}`)
// Third-party skills, vendored into the package at pinned commits (docs/agent/external,
// scripts/vendor-external-skills.mjs). Nothing is downloaded here: every file is checked
// against manifest.json before it is copied.
if (externalArg >= 0) {
const MARK = 'Vendored by @intecion/ipal-kit'
const ours = (name) => existsSync(join(dest, name, 'SOURCE.md')) && readFileSync(join(dest, name, 'SOURCE.md'), 'utf8').includes(MARK)
const filesOf = (dir) => readdirSync(dir).flatMap((n) => (statSync(join(dir, n)).isDirectory() ? filesOf(join(dir, n)).map((f) => `${n}/${f}`) : [n]))
for (const skill of manifest.skills.filter((s) => !externalPick || externalPick.includes(s.name))) {
const from = join(extSrc, skill.name)
const files = filesOf(from).sort()
const tampered = files.filter((f) => skill.files[f] !== createHash('sha256').update(readFileSync(join(from, f))).digest('hex'))
if (tampered.length || files.length !== Object.keys(skill.files).length) {
console.error(`iapl-skills: ${skill.name} does not match manifest.json (${tampered.join(', ') || 'file list'}) — skipped`)
process.exitCode = 1
continue
}
if (existsSync(join(dest, skill.name)) && !ours(skill.name)) {
console.warn(`skip ${skill.name} (a folder of that name exists and is not from IAPL)`)
continue
}
console.log(`${existsSync(join(dest, skill.name)) ? 'update' : 'add '} ${skill.name} (${skill.publisher}, ${skill.license}, ${skill.commit.slice(0, 12)})`)
if (!dryRun) {
rmSync(join(dest, skill.name), { recursive: true, force: true })
cpSync(from, join(dest, skill.name), { recursive: true })
}
}
const retiredExt = existsSync(dest)
? readdirSync(dest).filter((n) => n.startsWith('ext-') && !known.includes(n) && ours(n))
: []
for (const name of retiredExt) {
console.log(`remove ${name} (no longer in IAPL)`)
if (!dryRun) rmSync(join(dest, name), { recursive: true, force: true })
}
}
// Pointer block: an agent opening the project must find the guide without being told.
// AGENTS.md is read by Codex/Cursor/Antigravity, CLAUDE.md by Claude Code (which also
// follows `@AGENTS.md` imports, so a CLAUDE.md that imports AGENTS.md needs no copy).
if (pointer) {
const START = '<!-- iapl:start -->'
const END = '<!-- iapl:end -->'
const OLD_START = '<!-- ipal-kit:start -->'
const OLD_END = '<!-- ipal-kit:end -->'
const version = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')).version
const skillsDir = relative(process.cwd(), dest).split('\\').join('/')
const block = [
START,
`## IAPL ${version} — agent guide`,
'',
'<!-- Managed by `pnpm exec iapl-skills` — edits between the markers are overwritten. -->',
'This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code:',
'',
'1. Rules: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`.',
`2. Everything the plugin provides (options, env vars, routes, layout, hooks, collections, globals, every export): the \`iapl-reference\` skill — \`${skillsDir}/iapl-reference/SKILL.md\`.`,
`3. New project or missing foundation: the \`iapl-setup\` skill; a whole site: \`iapl-site\`. All skills: \`${skillsDir}/\`.`,
'4. Module details: `node_modules/@intecion/ipal-kit/docs/<module>.md`.',
'5. IAPL first: if the plugin has it, use it. Broken or not enough → report it with the `iapl-plugin-gap` skill and wait for the owner — no hand-built replacement, never patch `node_modules`.',
'6. Before you set up a site: ask the owner the architecture questions (AGENT.md "Ask before you build") and wait for the answers; record them under "Project decisions".',
'7. IAPL docs, this guide and the skills are in English; write rules, AGENTS.md entries and gap reports in English.',
END,
].join('\n')
const upsert = (file, { create }) => {
const path = join(process.cwd(), file)
const text = existsSync(path) ? readFileSync(path, 'utf8') : null
let next
if (text === null) {
if (!create) return
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)
// both blocks (an upgrade, a rollback whose installer added the old block again, an upgrade): the old one goes
if (next.includes(OLD_START) && next.includes(OLD_END)) {
next = (next.slice(0, next.indexOf(OLD_START)).replace(/\s*$/, '') + '\n\n' + next.slice(next.indexOf(OLD_END) + OLD_END.length).replace(/^\s*/, '')).replace(/\s*$/, '\n')
}
} 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`
}
if (next === text) return console.log(`ok ${file}`)
console.log(`${text === null ? 'create' : 'update'} ${file}`)
if (!dryRun) writeFileSync(path, next)
}
upsert('AGENTS.md', { create: 'block' })
const claude = join(process.cwd(), 'CLAUDE.md')
const importsAgents = existsSync(claude) && /^@AGENTS\.md\s*$/m.test(readFileSync(claude, 'utf8'))
// CLAUDE.md that imports AGENTS.md already sees the block — don't duplicate it.
if (!importsAgents) upsert('CLAUDE.md', { create: 'import' })
}
// Skills ship .ts/.tsx templates and scripts. A Next tsconfig ("include": ["**/*.tsx"]) would
// type-check them as project code and break `tsc` / `next build` → they must be excluded.
const tsconfig = join(process.cwd(), 'tsconfig.json')
const top = relative(process.cwd(), dest).split(/[\\/]/)[0]
if (existsSync(tsconfig) && top && !top.startsWith('..')) {
const text = readFileSync(tsconfig, 'utf8')
const exclude = text.match(/"exclude"\s*:\s*\[([^\]]*)\]/)?.[1] ?? ''
const entries = [...exclude.matchAll(/"([^"]*)"/g)].map((m) => m[1].replace(/^\.\//, '').replace(/\/(\*\*)?$/, ''))
if (!entries.includes(top)) {
console.warn(`\n⚠ tsconfig.json does not exclude "${top}" — skill templates would be type-checked and break the build.`)
console.warn(` Add it: "exclude": ["node_modules", "${top}"]`)
process.exitCode = 1
}
}
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env node
// iapl-tokens — the brand's design tokens: src/design/tokens.ts → src/design/tokens.css,
// plus a WCAG contrast check (docs/design-tokens.md).
// pnpm exec iapl-tokens → write src/design/tokens.css, print the contrast report
// pnpm exec iapl-tokens --check → fail when the CSS is out of date (CI, iapl-doctor)
// pnpm exec iapl-tokens --in x.ts --out y.css --warn-only
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
const { runTokensCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'tokens', 'cli.js')).href)
process.exit(await runTokensCli(process.argv.slice(2)))
Executable
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env node
// 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@<version> 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 <package>` runs the bin named after the package, so every subcommand lives here.
// The other tools keep their own bins: iapl-skills, iapl-blocks, iapl-tokens, iapl-doctor.
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const USAGE = `Usage: iapl <command> [options]
create <domain> a new client site from the reference site (iapl create --help)
Other tools: iapl-skills, iapl-blocks, iapl-tokens, iapl-doctor`
const [command, ...args] = process.argv.slice(2)
if (command !== 'create') {
console.log(USAGE)
process.exit(command === undefined || command === '--help' || command === '-h' ? 0 : 1)
}
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
const { runCreateCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'starter', 'cli.js')).href)
process.exit(await runCreateCli(args))
+2 -101
View File
@@ -1,102 +1,3 @@
#!/usr/bin/env node
// ipal-blocks — the block library's command line.
// pnpm exec ipal-blocks list → the library blocks
// pnpm exec ipal-blocks eject faq → src/blocks/Faq/{config.ts,Component.tsx}
// pnpm exec ipal-blocks eject faq --dest src/blocks --dry-run
// Eject copies one block's source into the project, with its imports pointing at the
// package entries, so the project owns it: same slug and data shape, no migration.
// Then: use the ejected builder in Pages.layout instead of the library one, pass the ejected
// component as createBlockRegistry({ components: { faq: FaqBlock } }), record it in AGENTS.md.
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join, relative, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const args = process.argv.slice(2)
const [command, slug] = args
const dryRun = args.includes('--dry-run')
const destArg = args.indexOf('--dest')
const dest = resolve(process.cwd(), destArg >= 0 ? args[destArg + 1] : 'src/blocks')
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const libRoot = join(pkgRoot, 'src/modules/block-library')
const blocksRoot = join(libRoot, 'blocks')
if (!command || command === '--help' || command === '-h') {
console.log('Usage: ipal-blocks list | ipal-blocks eject <block> [--dest src/blocks] [--dry-run]')
process.exit(0)
}
const slugs = existsSync(blocksRoot) ? readdirSync(blocksRoot).sort() : []
if (command === 'list') {
console.log(slugs.join('\n'))
process.exit(0)
}
if (command !== 'eject' || !slug) {
console.error('Usage: ipal-blocks eject <block>')
process.exit(1)
}
if (!slugs.includes(slug)) {
console.error(`Unknown block "${slug}". Blocks: ${slugs.join(', ')}`)
process.exit(1)
}
/**
* Where an import inside the library goes in a project, by the file it points at.
* Config files (no React) take the Payload-side entries; components take /rsc and /client.
*/
const ROOT = '@intecion/ipal-kit'
const BLOCKS = '@intecion/ipal-kit/blocks'
const RSC = '@intecion/ipal-kit/blocks/rsc'
function target(file, isComponent) {
const rel = relative(join(pkgRoot, 'src/modules'), file).replace(/\\/g, '/').replace(/\.js$/, '')
if (rel.startsWith('block-library/')) {
const inner = rel.slice('block-library/'.length)
if (/^(define|fields|options|shared|types|faq|library|manifest|thumbnails)$/.test(inner)) {return BLOCKS}
return RSC // context, data, texts, ui/*
}
if (rel === 'lightbox/LightboxProvider' || rel === 'richtext/TableOfContents') {return '@intecion/ipal-kit/client'}
if (rel === 'forms/RenderForm' || rel === 'richtext/RenderRichText') {return '@intecion/ipal-kit/rsc'}
if (rel === 'richtext/headings') {return isComponent ? '@intecion/ipal-kit/rsc' : ROOT}
return ROOT
}
/** Rewrites relative imports to package entries and merges imports of the same entry. */
function rewrite(source, file) {
const isComponent = file.endsWith('.tsx')
const merged = new Map()
const body = source.replace(/^import (type )?\{([^}]*)\} from '(\.[^']+)'\n/gm, (_, type, names, spec) => {
const entry = target(resolve(dirname(file), spec), isComponent)
const key = `${type ? 'type ' : ''}${entry}`
const set = merged.get(key) ?? new Set()
for (const n of names.split(',').map((s) => s.trim()).filter(Boolean)) {set.add(n)}
merged.set(key, set)
return ''
})
const lines = [...merged].map(([key, set]) => {
const [type, entry] = key.startsWith('type ') ? ['type ', key.slice(5)] : ['', key]
return `import ${type}{ ${[...set].sort().join(', ')} } from '${entry}'`
})
return body.replace(/^((?:import [^\n]*\n)*)/, (head) => `${head}${lines.join('\n')}\n`).replace(/\n{3,}/g, '\n\n')
}
const folder = slug[0].toUpperCase() + slug.slice(1)
const outDir = join(dest, folder)
const files = readdirSync(join(blocksRoot, slug)).filter((f) => /\.(ts|tsx)$/.test(f))
for (const name of files) {
const from = join(blocksRoot, slug, name)
const to = join(outDir, name)
if (existsSync(to)) {
console.error(`skip ${relative(process.cwd(), to)} (exists — delete it first to eject again)`)
continue
}
const out = `// Ejected from @intecion/ipal-kit (block library: ${slug}). The project owns this file now.\n${rewrite(readFileSync(from, 'utf8'), from)}`
console.log(`${dryRun ? 'would write' : 'write'} ${relative(process.cwd(), to)}`)
if (!dryRun) {
mkdirSync(outDir, { recursive: true })
writeFileSync(to, out)
}
}
console.log(`\nNext: Pages.layout → the ejected build${folder}Block; registry → components: { ${slug}: ${folder}Block }; AGENTS.md → "Project decisions".`)
// The path this command had before 1.17.0 (scripts and skills of older projects call it by path). Removed in 2.0.
import './iapl-blocks.mjs'
+2 -16
View File
@@ -1,17 +1,3 @@
#!/usr/bin/env node
// ipal-doctor — checks a site against the ipal-kit team rules and lists every gap with a fix hint
// (docs/doctor.md). Static by default: reads files, writes nothing (except a first-seen date in
// ipal-doctor.json outside CI).
// pnpm exec ipal-doctor → this project, human-readable
// pnpm exec ipal-doctor --strict --offline → CI on a new site: any finding fails
// pnpm exec ipal-doctor --deep --url http://localhost:3000
// pnpm exec ipal-doctor --json > doctor.json
// pnpm dlx --package=@intecion/ipal-kit@latest ipal-doctor → the newest rules
// Exit: 0 ok · 1 findings · 2 could not run · 3 a rule crashed.
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
const { runDoctorCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'doctor', 'cli.js')).href)
process.exit(await runDoctorCli(process.argv.slice(2), { packageRoot: pkgRoot }))
// The path this command had before 1.17.0 (scripts and skills of older projects call it by path). Removed in 2.0.
import './iapl-doctor.mjs'
+2 -22
View File
@@ -1,23 +1,3 @@
#!/usr/bin/env node
// ipal-kit — the plugin's command line.
// pnpm dlx @intecion/ipal-kit@<version> create intecion.com → a new client site (docs/project-starter.md)
// pnpm exec ipal-kit create intecion.com --dir ../intecioncom-web --answers answers.json
// `pnpm dlx <package>` runs the bin named after the package, so every subcommand lives here.
// The other tools keep their own bins: ipal-skills, ipal-blocks, ipal-tokens.
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const USAGE = `Usage: ipal-kit <command> [options]
create <domain> a new client site from the reference site (ipal-kit create --help)
Other tools: ipal-skills, ipal-blocks, ipal-tokens`
const [command, ...args] = process.argv.slice(2)
if (command !== 'create') {
console.log(USAGE)
process.exit(command === undefined || command === '--help' || command === '-h' ? 0 : 1)
}
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
const { runCreateCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'starter', 'cli.js')).href)
process.exit(await runCreateCli(args))
// The path this command had before 1.17.0 (scripts and skills of older projects call it by path). Removed in 2.0.
import './iapl.mjs'
+2 -175
View File
@@ -1,176 +1,3 @@
#!/usr/bin/env node
// ipal-skills — copies the ipal-kit agent skills into the project.
// pnpm ipal-skills → ./.agents/skills/ipal-*
// pnpm ipal-skills --dry-run → show what would change
// pnpm ipal-skills --dest .claude/skills
// pnpm ipal-skills --no-pointer → skills only, leave AGENTS.md / CLAUDE.md alone
// pnpm ipal-skills --external → also the vendored third-party skills (ext-*, pinned, text only)
// pnpm ipal-skills --external ext-accessibility,ext-payload → only those
// Only folders named ipal-* are touched; the project's own skills stay as they are.
// ipal-* folders that no longer exist in the package are removed (renamed/retired skills).
// ext-* folders are touched only with --external, and only those carrying ipal-kit's SOURCE.md.
// AGENTS.md (and CLAUDE.md) get a marked ipal-kit block pointing at the guide — only the
// text between the markers is ever rewritten; the project's own content stays as it is.
import { createHash } from 'node:crypto'
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { dirname, join, relative, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const args = process.argv.slice(2)
if (args.includes('--help') || args.includes('-h')) {
console.log('Usage: ipal-skills [--dest <dir>] [--dry-run] [--no-pointer] [--external [ext-a,ext-b]]\nDefault dest: .agents/skills')
process.exit(0)
}
const dryRun = args.includes('--dry-run')
const pointer = !args.includes('--no-pointer')
const externalArg = args.indexOf('--external')
const externalPick = externalArg >= 0 && args[externalArg + 1] && !args[externalArg + 1].startsWith('-')
? args[externalArg + 1].split(',').map((n) => n.trim()).filter(Boolean)
: null
const destArg = args.indexOf('--dest')
const destValue = destArg >= 0 ? args[destArg + 1] : '.agents/skills'
// A missing value would resolve to cwd and remove every ipal-* folder there.
if (!destValue || destValue.startsWith('-')) {
console.error('ipal-skills: --dest needs a directory, e.g. --dest .claude/skills')
process.exit(1)
}
const dest = resolve(process.cwd(), destValue)
if (dest === resolve(process.cwd())) {
console.error('ipal-skills: --dest must be a subdirectory, not the project root')
process.exit(1)
}
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const src = join(pkgRoot, 'docs', 'agent', 'skills')
if (!existsSync(src)) {
console.error(`ipal-skills: no skills found in ${src} — is @intecion/ipal-kit installed with docs?`)
process.exit(1)
}
// Validate --external before anything is copied.
const extSrc = join(pkgRoot, 'docs', 'agent', 'external')
const manifest = externalArg >= 0 ? JSON.parse(readFileSync(join(extSrc, 'manifest.json'), 'utf8')) : { skills: [] }
const known = manifest.skills.map((skill) => skill.name)
const unknown = (externalPick ?? []).filter((name) => !known.includes(name))
if (unknown.length) {
console.error(`ipal-skills: unknown external skill(s): ${unknown.join(', ')} — available: ${known.join(', ')}`)
process.exit(1)
}
const isSkillDir = (base, name) => name.startsWith('ipal-') && statSync(join(base, name)).isDirectory()
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))
if (!dryRun) mkdirSync(dest, { recursive: true })
for (const name of shipped) {
const action = existing.includes(name) ? 'update' : 'add '
console.log(`${action} ${name}`)
if (!dryRun) {
rmSync(join(dest, name), { recursive: true, force: true }) // drop files removed upstream
cpSync(join(src, name), join(dest, name), { recursive: true })
}
}
for (const name of retired) {
console.log(`remove ${name} (no longer in ipal-kit)`)
if (!dryRun) rmSync(join(dest, name), { recursive: true, force: true })
}
console.log(`${dryRun ? '[dry-run] ' : ''}${shipped.length} skill(s) → ${dest}`)
// Third-party skills, vendored into the package at pinned commits (docs/agent/external,
// scripts/vendor-external-skills.mjs). Nothing is downloaded here: every file is checked
// against manifest.json before it is copied.
if (externalArg >= 0) {
const MARK = 'Vendored by @intecion/ipal-kit'
const ours = (name) => existsSync(join(dest, name, 'SOURCE.md')) && readFileSync(join(dest, name, 'SOURCE.md'), 'utf8').includes(MARK)
const filesOf = (dir) => readdirSync(dir).flatMap((n) => (statSync(join(dir, n)).isDirectory() ? filesOf(join(dir, n)).map((f) => `${n}/${f}`) : [n]))
for (const skill of manifest.skills.filter((s) => !externalPick || externalPick.includes(s.name))) {
const from = join(extSrc, skill.name)
const files = filesOf(from).sort()
const tampered = files.filter((f) => skill.files[f] !== createHash('sha256').update(readFileSync(join(from, f))).digest('hex'))
if (tampered.length || files.length !== Object.keys(skill.files).length) {
console.error(`ipal-skills: ${skill.name} does not match manifest.json (${tampered.join(', ') || 'file list'}) — skipped`)
process.exitCode = 1
continue
}
if (existsSync(join(dest, skill.name)) && !ours(skill.name)) {
console.warn(`skip ${skill.name} (a folder of that name exists and is not from ipal-kit)`)
continue
}
console.log(`${existsSync(join(dest, skill.name)) ? 'update' : 'add '} ${skill.name} (${skill.publisher}, ${skill.license}, ${skill.commit.slice(0, 12)})`)
if (!dryRun) {
rmSync(join(dest, skill.name), { recursive: true, force: true })
cpSync(from, join(dest, skill.name), { recursive: true })
}
}
const retiredExt = existsSync(dest)
? readdirSync(dest).filter((n) => n.startsWith('ext-') && !known.includes(n) && ours(n))
: []
for (const name of retiredExt) {
console.log(`remove ${name} (no longer in ipal-kit)`)
if (!dryRun) rmSync(join(dest, name), { recursive: true, force: true })
}
}
// Pointer block: an agent opening the project must find the guide without being told.
// AGENTS.md is read by Codex/Cursor/Antigravity, CLAUDE.md by Claude Code (which also
// follows `@AGENTS.md` imports, so a CLAUDE.md that imports AGENTS.md needs no copy).
if (pointer) {
const START = '<!-- ipal-kit:start -->'
const END = '<!-- ipal-kit:end -->'
const version = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')).version
const skillsDir = relative(process.cwd(), dest).split('\\').join('/')
const block = [
START,
`## ipal-kit ${version} — agent guide`,
'',
'<!-- Managed by `pnpm exec ipal-skills` — edits between the markers are overwritten. -->',
'This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code:',
'',
'1. Rules: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`.',
`2. Everything the plugin provides (options, env vars, routes, layout, hooks, collections, globals, every export): the \`ipal-reference\` skill — \`${skillsDir}/ipal-reference/SKILL.md\`.`,
`3. New project or missing foundation: the \`ipal-setup\` skill; a whole site: \`ipal-site\`. All skills: \`${skillsDir}/\`.`,
'4. Module details: `node_modules/@intecion/ipal-kit/docs/<module>.md`.',
'5. ipal-kit first: if the plugin has it, use it. Broken or not enough → report it with the `ipal-plugin-gap` skill and wait for the owner — no hand-built replacement, never patch `node_modules`.',
'6. Before you set up a site: ask the owner the architecture questions (AGENT.md "Ask before you build") and wait for the answers; record them under "Project decisions".',
'7. ipal-kit docs, this guide and the skills are in English; write rules, AGENTS.md entries and gap reports in English.',
END,
].join('\n')
const upsert = (file, { create }) => {
const path = join(process.cwd(), file)
const text = existsSync(path) ? readFileSync(path, 'utf8') : null
let next
if (text === null) {
if (!create) return
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 {
next = `${text.replace(/\s*$/, '')}\n\n${block}\n`
}
if (next === text) return console.log(`ok ${file}`)
console.log(`${text === null ? 'create' : 'update'} ${file}`)
if (!dryRun) writeFileSync(path, next)
}
upsert('AGENTS.md', { create: 'block' })
const claude = join(process.cwd(), 'CLAUDE.md')
const importsAgents = existsSync(claude) && /^@AGENTS\.md\s*$/m.test(readFileSync(claude, 'utf8'))
// CLAUDE.md that imports AGENTS.md already sees the block — don't duplicate it.
if (!importsAgents) upsert('CLAUDE.md', { create: 'import' })
}
// Skills ship .ts/.tsx templates and scripts. A Next tsconfig ("include": ["**/*.tsx"]) would
// type-check them as project code and break `tsc` / `next build` → they must be excluded.
const tsconfig = join(process.cwd(), 'tsconfig.json')
const top = relative(process.cwd(), dest).split(/[\\/]/)[0]
if (existsSync(tsconfig) && top && !top.startsWith('..')) {
const text = readFileSync(tsconfig, 'utf8')
const exclude = text.match(/"exclude"\s*:\s*\[([^\]]*)\]/)?.[1] ?? ''
const entries = [...exclude.matchAll(/"([^"]*)"/g)].map((m) => m[1].replace(/^\.\//, '').replace(/\/(\*\*)?$/, ''))
if (!entries.includes(top)) {
console.warn(`\n⚠ tsconfig.json does not exclude "${top}" — skill templates would be type-checked and break the build.`)
console.warn(` Add it: "exclude": ["node_modules", "${top}"]`)
process.exitCode = 1
}
}
// The path this command had before 1.17.0 (scripts and skills of older projects call it by path). Removed in 2.0.
import './iapl-skills.mjs'
+2 -12
View File
@@ -1,13 +1,3 @@
#!/usr/bin/env node
// ipal-tokens — the brand's design tokens: src/design/tokens.ts → src/design/tokens.css,
// plus a WCAG contrast check (docs/design-tokens.md).
// pnpm exec ipal-tokens → write src/design/tokens.css, print the contrast report
// pnpm exec ipal-tokens --check → fail when the CSS is out of date (CI, ipal-doctor)
// pnpm exec ipal-tokens --in x.ts --out y.css --warn-only
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
const { runTokensCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'tokens', 'cli.js')).href)
process.exit(await runTokensCli(process.argv.slice(2)))
// The path this command had before 1.17.0 (scripts and skills of older projects call it by path). Removed in 2.0.
import './iapl-tokens.mjs'
+112
View File
@@ -0,0 +1,112 @@
# Changelog of the wire contract
## 1.7.1 — 2026-11-25 (not released; no tag yet)
Wording only; nothing for a client to change, and a copy of 1.7.0 need not be refreshed for it.
- **1.7.0 is required, not optional.** A client of 1.6 or older gets `400 invalid-request` on every request
that carries a token, because it does not send `X-Intecion-Site`. By the rule for development versions (§9)
it was numbered as a minor; read it as a breaking step. No client of 1.6 or older was released.
## 1.7.0 — 2026-11-25 (never released)
From the independent review of the first client. What a client built against 1.6.0 has to change is marked.
- **New, required: the header `X-Intecion-Site: <own host>` on every request that carries a token.** Missing:
`400 invalid-request`. Not the token's host: the new code **`403 host-mismatch`** (forget the token, enrol as
yourself). **Client: send the header; handle the code.** All examples with a token carry it; two new
examples (`send-host-mismatch`, `status-no-site-header`).
- **A client stores the host with the token and compares it with its own before use**, and compares the `host`
of `/v1/status` (§8, checklist 3). **Client: add the check.**
- **The confirm endpoint's limiter counts only refused calls**, after the nonce was looked up; never by the
caller's address first (§2). **Client: check the order.**
## 1.6.0 — 2026-11-25 (never released)
From the first client built against the contract (IAPL's). **The service did not change**; these are the
contract's words. What a client built against 1.5.0 has to change is marked.
- **An answer that is not the service's JSON** is no longer "like `503 unavailable`" for the report: with a
status from 400 to 499 it is *not sent*, with any other status (200 included) *not confirmed*.
**Client: change the report for that case.** Retrying it is as before.
- **A client that cannot keep key and bytes** (§1): no retry by itself after the report; a repeat by a person
is a new message; keys derived from the message's record are described, and for such a key
`idempotency-conflict` means "already handled". **Client: nothing must change; derived keys are an option.**
- **A site with a hand-issued token** does not enrol on `reverify` / `invalid-token`; it reports
`relay-refused` and what to ask Intecion for. **Client: nothing, if it already does this.**
- **`Origin` / `Sec-Fetch-Site`:** a client sends neither; said in §1. **Client: nothing for Node.**
- A stand-in need not reproduce the service's lists; said in §10.
## 1.5.0 — 2026-11-25 (never released)
After the third review.
- `new-recipients`: `account` mail is outside it; a form's confirmations may use four fifths of it.
- Failed sends: those in flight are counted in.
- Wording: `backend-failed`, `internal` and unknown codes mean "probably not sent"; the checklist asks a client
to limit "forgot password" itself.
## 1.4.0 — 2026-11-25 (never released)
After the second review.
- **Limits by kind:** `security-alert` has a budget of its own (`limit: "alerts"`, `limits.securityAlertsPerDay`)
outside hour and day; `account` mail may use the whole hour and day, every other kind four fifths. The
`quota` of a send answer is for that kind. `recipient` counts `form-confirmation` messages only.
- **The idempotency promise is now what the service does:** a key whose message was handed to the mail back end
is never sent again within 24 hours; when the result was not recorded it answers `in-progress` until then.
- **Failed sends** have a limit of their own: `429 rate-limited` after 60 in an hour.
- **Retrying:** three attempts, 30 seconds each, ten seconds of waiting in all; an enrolment on the way does
not count.
- **Subject:** U+200D, U+200C and U+00AD are allowed; everything else as before, with the rule a client strips by.
- Any mail of a site to Intecion's own address gets `[host]` in front of its subject.
- The confirm address: no redirect is followed — the usual causes and what to do; `given.quota` gains
`hour-share-used`.
## 1.3.0 — 2026-11-25 (never released)
- **The confirm path is fixed per product** (owner, 2026-11-25): `iapl` → `/api/iapl/mail-relay/confirm`,
`iawl` → `/?rest_route=/iawl/v1/mail-relay/confirm`. **`callbackPath` is gone from the enrolment request**
(a request that carries it is refused). A site that serves its API elsewhere has its path set by Intecion.
- Suppression is account-wide and stays so (owner, 2026-11-25): said in the code table.
## 1.2.0 — 2026-11-25 (never released)
After the first independent review. The wire format is the same; the text now has one reading where it had two.
- **Retrying:** at most three attempts in ten seconds, and the ten seconds win over `retryAfter`; "no answer"
and `in-progress` are reported as *not confirmed*, never as *not sent*.
- **Idempotency:** "the same body" is the same bytes; a client encodes a message once.
- **The confirm endpoint:** exactly `200` and the JSON object, at most 1024 bytes, within 8 seconds; the site
keeps its earlier token until `/v1/enrol` answers 200.
- **An answer that is not JSON** is `unavailable`, retryable.
- `Authorization: Bearer` in any case.
- **Schema:** `code` and `warnings` are open strings (new ones are minor changes); `to` is required unless the
kind is `security-alert`; recipients' `maxItems` is the service's bound, the site's limit is in `/v1/status`;
base64 is padded to a multiple of four (said in words: a pattern for it overflows on large files); lengths are
in code points.
- **Changed behaviour:** the per-recipient limit refuses `form-confirmation` only; a subject may not start with
the service's name in brackets; a `security-alert` gets the site's host in front of its subject;
`attachment-refused` names the file in `field` (suggested status `relay-attachment-refused`);
invisible characters (all of Unicode category Cf) are refused in subject and file names.
- Added: `limits.serverAddresses` in `/v1/status`; what happens beyond it.
- Before the first release tag, versions are development versions (§9).
## 1.1.0 — 2026-11-25 (never released)
- **The base address is `https://webservices.intecion.net/mail`**: one host for Intecion's web services, this
one under the path `/mail`. Paths in the contract are relative to the base address, as before; a client that
kept the base address as one constant changes that constant and nothing else.
- Added: `service.name` in the answer of `/v1/status` ("Intecion Notifications Webservice").
- The service sends from `[email protected]` (owner, 2026-11-25).
Minor, by the contract's own rule (§9): an answer field was added. No copy of 1.0.0 was released; a client that
copied it during development copies the folder again.
## 1.0.0 — 2026-11-25 (never released)
First version: `/v1/enrol` with the call-back and its confirmation, `/v1/send`, `/v1/status`, `/v1/rotate`,
`/v1/revoke`, `/health`; the error codes; the examples and the runner.
Differs from the design proposal (draft 4) in one visible point: the site's confirm endpoint answers `200` with
a `confirmation` (SHA-256 of nonce and token), not a bare `204`. Reason: `services/mail-relay/DECISIONS.md`, D1.
+64
View File
@@ -0,0 +1,64 @@
3d5c4b7ed53fe6fe2c7c28826c0cf666f9c1d0b79f861b404503e7029728a61f README.md
53da77d5dfff9948d68fca26b828563e21f83418245053d78b03a5aecac6c1d1 CHANGELOG.md
249182a01164b81a5f7af87e5c5cdbd3344a80a7a66dfca624cecfb1501b2420 VERSION
2ff0ad5b6a245365c0fa8733fa17b7bbd3ab91d4825981709d0fd02b762b939f schema.json
9d8381d2e3465e97dc801a61f598fcf822e27e73a2c0729877744ec307097910 runner.mjs
7c46860adee597e570832c72bcdb418752a20b9f7d1b2d7a656ed065f9632b2a checksums.mjs
df6015faf02a7cf7e9b5816b9e22b2e82968678ddd72a61c1f9665a8c0897ddf examples/callback-confirm-wordpress.json
f5018ca4fb7d25794ee92168d715aaf47feeba3d907c0550651b16c10a691ceb examples/callback-confirm.json
27bd95712cc36a71519cddc52c03d857b1009c2c384940dbc052022d86bc4231 examples/callback-unknown-nonce.json
de693b060c10c3d0f88fb8edfcd38c491cf141628d747328beee1b50c700c19b examples/enrol-address-literal.json
7c4cf75eb9ab156a3031336ab2688e7c9dcd4cd266b7b7e5e4592285dcbd25ba examples/enrol-callback-no-content.json
64466afc5bf0fecfa36f986d973cd987bbe1f64867e01cdf35e0de40838eb0d1 examples/enrol-callback-not-found.json
0000bcb2b3b676e4fda6c30b8de6e062c88f98c1fa2cc9f75bcd350d65dc0db4 examples/enrol-callback-path-given.json
8b522f16bc9b9980a5c849e94cea35fb268b0ba664dcd5a2e8e0fedd67c2c034 examples/enrol-callback-redirect.json
1e6483ebd85e3851848357266d8e16628a70420428b30d3ddb15253cdc2d9a0d examples/enrol-callback-wrong-confirmation.json
f64e4c75ced60e70b0f2f8e16adbde151be888fe5ac75813cdbe7eb5ecf8a00b examples/enrol-from-browser.json
218f463c95fd79868916390d4616c796d66154398a9864615f9ad0768f801aff examples/enrol-listed-active.json
b628eb5b30e693767e6830de58e0fd172497336f67b76a49a5fb06bfa626c481 examples/enrol-localhost.json
93304590382de5153a47fa88ee98356d0a5ba8039e195959291acd3c33e4a406 examples/enrol-short-nonce.json
e86e6ab23088c1c985ba18f287f66b49c50f51a584a7ca679b8b768597130efd examples/enrol-suspended.json
fe38f1fd1394a7fd42b1a1b0b74aa604578f17ab52590bf95a462a0c0f7d6087 examples/enrol-unlisted-pending.json
b9f71fe993dc39bdbc07e775e925a37175e18e1682fd8bffcc72b3581919be17 examples/health.json
5dff4194764f6f61b01a3f7f504907e578306a486d214e22d1a70b1a207e5ca3 examples/not-found.json
94943f85503cd891f1fb6f0258ab97b2eb48ec10e5f7ea233d349d4da97b8a1b examples/revoke-ok.json
1b467eac1040d56369276e5b8c12540a84942c8b7e3c2e458fc8da5b4f027c86 examples/rotate-ok.json
348f96a160c168797ab27ff0739b17df1762cc2ffdd72cb0a2b3ec2c695093bc examples/rotate-previous-token.json
39774a2ce0434dc791d79f9efb4b14f23203b7e8d58138acc7654265a875609b examples/send-attachments-too-large.json
75ec4de22780b36b41f198f065e38937beb4a50879fd204e080bdb935c2b5e8f examples/send-backend-failed.json
e3331a33604c2239c91c889d3dd338e473fd9b5d80fccb84a39491810bcceac0 examples/send-bearer-any-case.json
26f4f8a2929d132598bcb87e813616cef7b6277249c657cc618f4ede4cb4d906 examples/send-day-quota.json
660dbe2a747686077788f46fe45f269c3eb57e4579225979f91841e9f00fae7b examples/send-display-name-recipient.json
1c6bd0ed454f51acf545f0213fe6108f3639af975fb0751ef8d23bd92da9d4c7 examples/send-executable-attachment.json
ed6869754e418cc5e2a809e52a0242680d79f1bbc2eedd391de04375f29f7b9a examples/send-from-browser.json
e39d197f857b56103726b0f165c67a3476a06207961a59c6f6a1cf333bc3e7e9 examples/send-from-field.json
5c826cd0c297c773510ce37b66a0f6a6425e6282abc1ad30094fd5b545ae9193 examples/send-headers-field.json
3918635b33b32783db96ae17ebbd4296d2deca05d092b55573c574be172601ec examples/send-host-mismatch.json
a6809a8d475106f8e31ba432e56b46e9bf8683a0eca9d62378b1392cd6c44305 examples/send-hour-quota-account.json
c46852c9d9fc7eb83ac6bc3ca2a7c5b79100d2cae93a5cee6720b702b4c22490 examples/send-hour-quota.json
dc0f9c1c946d256aded0de70588c1d1f95740d333b234127f9bce8a4ed8beefb examples/send-key-reused.json
69edbf23c9723337f6327484e587b8cb7603c23e4b4954ebd275a0a794171325 examples/send-no-sender-name.json
bcbf5adcd0c224edb81c3b4188f261252835f715f541030db10432fa7ebd71a4 examples/send-no-token.json
32125ac9ff5460991633cce55febcb310247ca518eae7c650ef634e3f86376e0 examples/send-ok.json
7d8b14d372730f013ee7192021dda68859f779337b8d535bc564ac955a00e325 examples/send-pending.json
e3bbb041217d0a4f378285c06584a093d5e808d223d564e735c559f461fae8b8 examples/send-previous-token.json
53132e3e2177937dc2a35f7fe87f2f383f45ab001fc0306490941b44bb466e3c examples/send-recipient-quota-other-kinds.json
aff454882faab57d4a697be7250fdbac0272bcc2e0c099a6a27c50e0a980ac70 examples/send-recipient-quota.json
d514bc65a75f522389c90f1239d9afa43d96c7c2e7bd31fe0e85dd4c9d543ebd examples/send-recipient-suppressed.json
eb68d83a8d582a3722bf99330246d3d641e49a53e08bbe48e04e09a970cbb866 examples/send-replay.json
189dbdb3df1f0da0b6a1e8fdd0e90babf9dbfe9cfcaeb423ba24e2d59802b663 examples/send-security-alert.json
f299bc4f5193de0619d78551653a0b133a4ae5774dba93b23812b689a074a87d examples/send-sender-name-replaced.json
39a09b2bd01fc12d0e8cb2f93b71b24f31a4f2d0f639fe93b6bf37a7357be0ae examples/send-subject-direction-mark.json
ce4cbea2306f73bd5905249c10ab451a2599cb779e2386828971f40c97b8c591 examples/send-subject-imitates-service.json
247619f5575e898bd558ff7f7674f241c39f3a1e0ae51f589eb6a6dc2fe21e2b examples/send-subject-line-break.json
59175981e46a6f782ce3b4ed9c885699d7766823d660e5a524e89a4f2c6c459a examples/send-subject-visitor-text.json
987a2b4433161b4f2a6502d0487bf18f512f7a630a930ac66b1038cd6e000dc3 examples/send-suspended.json
91cd894526eef28e4dfb2456e476ba0be381e6d621ea833761cc9c63fe247e03 examples/send-text-plain.json
9c6278fcb13d7e06e0dd38ef34eba1abfbcb9c75100994b93c1c5a5444c35f85 examples/send-to-intecion-marked.json
1a1faf5a451220a35f2f0d66bb906e0d9944ed0a71c8209e07da419734a82567 examples/send-too-many-recipients.json
43d04c99549a4fe3c64af6f68b598299e92486af5a52432a2c93c3f9564f7959 examples/send-unknown-address.json
28e05f3c53cab6433b6af4d425511fa6655d0673df2e840af1fed9d25294a123 examples/send-unknown-token.json
f105c38ab11ab5fc508ba0ed3f23f69108c318765c2670029b230b5b9a83912a examples/status-active.json
89009ee9ab8f38e9ec290fb5412f206e1be28ad10fce6a7071d4406ac52dd4f0 examples/status-no-site-header.json
c9f49fa0dae1f0beacaacfe01660b467d06f990228c35a653307c8793f3c97a5 examples/status-pending.json
afdb07ba8279479b6bbfdc4289efda657d4e5a9eccd94b8de165ec728b4a2386 examples/status-unknown-address.json
+540
View File
@@ -0,0 +1,540 @@
# Intecion Notifications Webservice — wire contract
Version: see [`VERSION`](VERSION) (this text describes **1.7.1**). Path prefix of this major version: `/v1`.
This is the whole agreement between the Intecion Notifications Webservice ("the service" below) and a client (the mail transport built into a
site's plugin). It names no product: nothing here says Payload, WordPress, IAPL or IAWL except the values of
the `product` field. A client written from this document, in any language, works with the service.
| File | What |
|---|---|
| `README.md` | This document. Where it and the schema disagree, the schema wins and that is a bug to report |
| `schema.json` | JSON Schema (2020-12) of every body, under `$defs` |
| `examples/*.json` | One request and its answer per file, with the state it needs. They are the contract tests |
| `runner.mjs` | Runs the examples against anything that speaks the contract. No dependency; works in Node and in the Workers runtime |
| `checksums.mjs`, `CHECKSUMS` | SHA-256 of every file above, to detect a hand-edited copy |
| `VERSION`, `CHANGELOG.md` | Semantic version of the contract and what changed |
## 1. Basics
- **Base address: `https://webservices.intecion.net/mail`** — a client keeps it as one constant, host and path
together. Every path in this document and in the examples is relative to it: `POST /v1/send` is
`POST https://webservices.intecion.net/mail/v1/send`, `GET /health` is `…/mail/health`. A client joins the
base address and the path as text; it never resolves a path against the host alone.
- HTTPS only. Bodies are JSON in UTF-8. A request with a body carries `Content-Type: application/json`.
- **The service is for servers, not browsers.** It sends no CORS header, and it refuses any request that
carries an `Origin` header or a `Sec-Fetch-Site` header other than `none` (`403 browser-not-allowed`).
A client must send neither. A server runtime's `fetch` that adds them by itself has to be told not to, or the
header removed, or the service will take the site for a browser. (`Sec-Fetch-Mode` and `Sec-Fetch-Dest` are
not looked at: Node's `fetch` sends `sec-fetch-mode: cors` and passes.)
- **Requests are closed:** an unknown field is refused with `400 invalid-request` and the field's name. A
client cannot set `From`, `Sender`, `Return-Path` or any free header — there are no such fields.
- **Answers are open:** a client ignores fields it does not know.
- A client identifies itself with `User-Agent: <product>/<version>` (not checked, used for the log).
- **An answer that is not the service's JSON** — an error page of the network in front of the service, an empty
body, a cut-off answer — is no answer of the service. The client may retry it (as if `retryable` were true),
and what it means for a message depends on the status alone:
- status **400 to 499**: the request was turned away before the service handled it — **not sent**;
- **any other status, `200` included**: the service may have handled the request and only its answer was
lost — **not confirmed**, exactly like no answer at all (§1, "Retrying").
### Answers
Success is status `200` and a body with `"ok": true`.
Every refusal has the same body ([`Error`](schema.json)) — with one exception: `/health` answers only
`{ "ok": false }`.
```json
{ "ok": false, "code": "quota-exceeded", "message": "…", "retryable": false, "limit": "hour", "retryAfter": 1260 }
```
- `code` is what a client acts on. `message` is English text for a log or an administrator; never show it to a visitor.
- **`retryable` decides whether to try again, not the status.** `429 quota-exceeded` is not retryable;
`429 rate-limited` is.
- `retryAfter` (seconds) is also sent as the `Retry-After` header.
- The list of codes grows with minor versions. A client that meets a code it does not know acts on `retryable`
and shows the `message` to an administrator.
### All codes
| Status | `code` | Meaning | Retry | What a client does | Suggested site status |
|---|---|---|---|---|---|
| 400 | `invalid-request` | Body, header or field is wrong; `field` names it | no | Report a bug | — |
| 401 | `invalid-token` | No token, or one the service does not know (unknown, expired, revoked) | no | Enrol again, then send once more (§2, "Which token") | — |
| 401 | `reverify` | The token is good but comes from a server address the service has not seen for this site | no | Enrol again (the same call-back), then send once more | — |
| 403 | `site-pending` | Enrolled, waiting for approval by Intecion | no | Keep the token; show "waiting for approval" | `relay-pending` |
| 403 | `site-suspended` | Stopped by Intecion | no | Keep the token; show it; do not enrol again | `relay-suspended` |
| 403 | `host-not-allowed` | Enrolment: the host is not a public DNS name | no | Show it (a local or private site cannot use the service) | `relay-refused` |
| 403 | `enrolment-closed` | Enrolment is closed for this product, or altogether | no | Show it | `relay-refused` |
| 403 | `host-mismatch` | The token is good and comes from a known address, but the request's `X-Intecion-Site` names another site than the token's | no | Forget the token (it is another site's — a copied database, a token pasted into the wrong site), enrol as your own host, then send once more | — |
| 403 | `browser-not-allowed` | The request came from a browser | no | — | — |
| 404 | `not-found` | No such route | no | Report a bug | — |
| 405 | `method-not-allowed` | Wrong method | no | Report a bug | — |
| 409 | `enrolment-in-progress` | Another enrolment for this host is running right now | **yes** | Wait `retryAfter`, read your own store again (another process may have the token by now), enrol only if still without one | — |
| 409 | `in-progress` | A send with this `Idempotency-Key` is running right now — or was handed to the mail back end and its result was never recorded (then `retryAfter` is long, and the message may be out) | **yes** | Retry with the same key within the ten seconds; then report "not confirmed" | — |
| 409 | `idempotency-conflict` | This `Idempotency-Key` was used for a different message | no | Report a bug | — |
| 409 | `already-rotated` | `/v1/rotate` with a token that is no longer the current one | no | Read your own store again; if it has no newer token, enrol again | — |
| 413 | `too-large` | `limit` says what: `request`, `body` or `attachments` | no | Show it | `relay-too-large` |
| 415 | `unsupported-media-type` | Not `application/json` | no | Report a bug | — |
| 422 | `callback-failed` | Enrolment: the site's confirm endpoint did not confirm; `reason` is `unreachable`, `timeout`, `redirect`, `status` or `confirmation` | no | Show it, with the reason: firewall or wrong public host (`unreachable`, `timeout`); the site answers the confirm address with a redirect (`redirect`, §2); the endpoint is missing, blocked, or served at another path than its product's (`status`); something prints around the JSON (`confirmation`) | `relay-refused` |
| 422 | `too-many-recipients` | More than the allowed number in To, CC and BCC together | no | Show it | `relay-quota` |
| 422 | `attachment-refused` | A file type the service never carries, or a bad file name; `field` says which file (`attachments[0]`) | no | Show it; the message can be sent without that file | `relay-attachment-refused` |
| 422 | `recipient-suppressed` | The back end refuses one of the recipients (it bounced or complained before — for any site: **the suppression list is one for the whole service, and there is none per site**; an address that bounced for one client's site is refused for every other site too, until Intecion removes it). **Nothing was sent, to anybody.** The service is not told which address it is | no | Show it. With several recipients a client may send to each alone, each with a new key, to find the one | `relay-recipient-suppressed` |
| 429 | `rate-limited` | Too many requests from this address — or too many of this site's sends were refused or failed at the mail back end within the hour (60; a send that fails costs no quota, so it has a limit of its own; account mail and alerts are counted apart from the rest) | **yes** | Wait `retryAfter`; when that is longer than the ten seconds, report | `relay-unreachable` if it persists |
| 429 | `quota-exceeded` | A limit of the site (`limit`: `hour`, `day`, `recipient`, `new-recipients`, `alerts`) or of the whole service (`service`) | no | Show it; the message is not sent | `relay-quota` |
| 502 | `backend-failed` | The mail back end failed, or refused this message | **as `retryable` says** | Retry with the same key when `retryable` is true | `relay-unreachable` if it persists |
| 503 | `unavailable` | The service cannot work right now | **as `retryable` says** | Retry when `retryable` is true | `relay-unreachable` if it persists |
| 500 | `internal` | A fault in the service | **yes** | Retry | `relay-unreachable` if it persists |
A network error or a time-out is treated like `503`. The "suggested site status" column is advice, in the words
the IAPL design uses; a product may name its own. The warning `sender-name-replaced` (below) maps to
`relay-name-replaced`.
**Retrying — the one rule.** A client makes at most **three attempts** for one message, the same
`Idempotency-Key` and the same bytes each time, and only after an answer with `retryable: true` (or no usable
answer at all). Between the attempts it waits **at most ten seconds in all**. **The ten seconds win over
`retryAfter`:** when `retryAfter` is longer than what is left of them, the client stops at once and reports.
- **One attempt** has a time-out of **30 seconds** from sending the request to the end of the answer (a 10 MB
attachment has to fit). An attempt that times out counts as "no answer".
- **An enrolment made on the way** — because the client had no token, or got `invalid-token` or `reverify` — is
not one of the three attempts and its time (up to 10 seconds: the call-back has 8) is not part of the ten
seconds. A client enrols at most once per message.
What the client reports:
| The last thing that happened | The message | Report |
|---|---|---|
| `200` | was accepted | sent |
| A refusal with `retryable: false` | was not sent | the status of that code |
| `rate-limited`, `unavailable`, `enrolment-in-progress` (as the service's own JSON), or an answer that is not the service's JSON with a status from 400 to 499 | was not sent | `relay-unreachable` |
| `backend-failed`, `internal`, or a code the client does not know | **probably** not sent — the mail back end failed in a way it does not explain, and it does not say whether such a message can still go out | `relay-unreachable`, worded as "probably not sent". Like the next row: the same key and bytes if it is tried again |
| **No answer** (time-out, connection lost), an answer that is not the service's JSON with any status outside 400–499, or `409 in-progress` | **may have been sent** — the service cannot say yet, or will never be able to | `relay-unreachable`, worded as "not confirmed", never as "not sent". If the client tries this message again later it uses the **same key and bytes**: within 24 hours of the first attempt that cannot produce a second mail — once the service has handed a message to the mail back end, its key either answers with the result or goes on answering `in-progress`; it is never sent again. A client never sends the message under a new key by itself |
**"The same key and bytes" — and a client that cannot keep them.** The promise that a message is not sent
twice holds for as long as the client still has the message's key and its encoded bytes. What a client does
depends on what it can keep:
- **Within one attempt to deliver a message** (the three tries above) every client keeps both in memory.
- **A client with storage for unsent mail** keeps key and bytes with the message and may try again later.
- **A client without such storage** does not try again by itself once it has reported. "Not confirmed" is then
final for that message: the report says that the mail may or may not have gone out. If a person causes the
mail again — submits the form again, presses "send again" — that is a **new message with a new key**, and
when the first one did go out, the recipient gets it twice. The service cannot prevent that and a client
need not; it should say "not confirmed" in a way that does not invite an immediate repeat.
- **A key derived from the message's own record** narrows this without storing the mail: when the mail belongs
to something the site stores anyway (a form submission, a password-reset request), the client may build the
key from that record's id and the mail's role in it (for example the SHA-256 of both, in the key's
alphabet). A second attempt for the same record — after a restart, from another process — then arrives under
the same key, and the service answers it with the first result (`replayed`), with `in-progress`, or, when the
bytes differ because the mail was built again, with `409 idempotency-conflict`. For a derived key the client
treats **`idempotency-conflict` as "this record's mail was already handled"**, not as a bug: no second mail
either way. A deliberate "send again" by a person uses a new key (the record's id and a counter).
## 2. Enrolment — `POST /v1/enrol`
A site gets its token by proving that it is served at its host. No authentication, nothing to type.
1. The site makes a random **nonce** (32 to 128 characters of `A–Z a–z 0–9 _ -`; at least 128 bits of
randomness), keeps it for 5 minutes, and sends:
```json
{ "host": "example.com", "nonce": "…", "product": "iapl", "productVersion": "1.17.0" }
```
- `host`: the site's public DNS name, lowercase, punycode. No scheme, port, path, address literal, single
label, or private suffix (`.local`, `.internal`, `.test`, `localhost` …).
- There is **no call-back address in the request.** Where a site is called back is fixed per product
(below); a request that names a path is refused (`400`, field `callbackPath`).
2. Before it answers, the service calls the site: `POST https://<host><confirm path of the product>`, port 443,
no redirect followed, **8 seconds** for the whole exchange, body ([`CallbackRequest`](schema.json)):
```json
{ "nonce": "…", "token": "ims_…", "state": "active" }
```
3. **The site's confirm endpoint** accepts the call only if it holds exactly this nonce (compare in constant
time; single use; not expired). Then it stores the token and answers `200` with
```json
{ "confirmation": "<lowercase hex SHA-256 of nonce + \".\" + token>" }
```
In every other case it answers `404` and changes nothing.
**It is a public route: limit it — but only the calls it refuses.** Look the nonce up **first**. A call that
carries the nonce the site holds is the service's and is always answered; only calls that do **not** match
a held nonce count towards a limit. Do not limit by the caller's address before that look-up: the service's
calls come from addresses that every Worker on Cloudflare shares, so a stranger who sends a few requests
from a Worker of their own would use up "the service's" allowance and block the site's enrolment. (When the
site holds no nonce at all — it started no enrolment in the last five minutes — every call is a refused one
and can be answered `404` without any work.)
**Exactly this answer and nothing else.** Status `200` (not 201, not 204). The body is the JSON object alone,
UTF-8, at most 1024 bytes, the hex in lower case. Anything printed before or after it — a PHP notice, a
debug toolbar, a wrapper of the framework — makes the enrolment fail with `callback-failed`, reason
`confirmation`. The service reads no more than 1024 bytes and waits no longer than the 8 seconds.
**Which token.** The call-back arrives *before* `/v1/enrol` has answered. The site stores the new token
**beside** the one it has, and makes it the token it uses when `/v1/enrol` answers `200`. If that answer
never arrives, the site tries the new token on its next request and goes back to the earlier one on
`401 invalid-token` (the service may have failed after the call-back; the earlier token is then still good).
A site never throws a working token away for one it has not seen accepted.
4. The service checks the confirmation. Only then does the token become valid, the calling server's address
become one of the site's known addresses, and `/v1/enrol` answer `200`:
```json
{ "ok": true, "state": "active" }
```
`state` is `active` (the site may send) or `pending` (waiting for approval; sends answer `403 site-pending`
until Intecion approves, then the same token works). **The answer never carries the token.**
Why the confirmation, and not a bare `204`: plenty of ordinary endpoints answer "no content" to any POST (a
report collector, for one). Only an endpoint that knows the nonce *and* has read the token can compute the
confirmation, so nothing else on the host can be mistaken for the confirm endpoint.
Rules a client must know:
- **Enrolling again is the same call** and is how a site heals: after `401 invalid-token`, after `401 reverify`,
after a lost token. The earlier token stays valid for 24 hours (so other processes of the same site are not
cut off), the state is kept — a suspended site stays suspended (`403 site-suspended`, no call-back is made).
- A failed enrolment changes nothing on the service: tokens and addresses stay as they were.
- `409 enrolment-in-progress`: an enrolment for this host from this server is already running (or the
registry changed while the site was being called). It is retryable and is not counted against the site.
- **The confirm path is fixed per product**; a site cannot choose it:
| `product` | The service calls | Notes |
|---|---|---|
| `iapl` | `POST https://<host>/api/iapl/mail-relay/confirm` | Under Payload's default API route (`/api`) |
| `iawl` | `POST https://<host>/?rest_route=/iawl/v1/mail-relay/confirm` | WordPress's REST API addressed by query: the same address works with and without pretty permalinks. The route is `mail-relay/confirm` in the namespace `iawl/v1` |
The service calls **exactly that address and follows no redirect.** A site that redirects it fails with
reason `redirect` — the usual causes: the site adds or removes a trailing slash (Next.js `trailingSlash`),
sends `example.com` to `www.example.com` (enrol the host the site really answers on), or redirects `/` by
language. On WordPress, a security plugin or a setting that blocks or redirects `?rest_route=` gives
`status`. In each case either the site is changed to answer at the address, or Intecion sets the address it
does answer at (a path ending in `/confirm/`, for a site with trailing slashes).
**A project that serves its API somewhere else** — Payload with another `routes.api`, WordPress installed in a
sub-folder, a path prefix in front of the site — cannot say so in the request. Its path is set for its host
**by Intecion** (`ims callback-path <host> <path>`), before the site enrols; until then the enrolment fails
with `callback-failed`, reason `status`. A client shows that as "ask Intecion to set this site's confirm
address", with the address it serves. When an enrolled host confirms at another path than before, Intecion
is told.
- **Server addresses.** A site may send from a limited number of server addresses at a time
(`limits.serverAddresses` in `/v1/status`, 8 unless Intecion set another number). Each new address enrols by
itself after `401 reverify`; beyond the limit the address used longest ago is dropped and gets `reverify`
again. A site whose requests leave from many changing addresses (serverless hosting, a pool of egress
addresses) must have the limit raised by Intecion, or it will enrol in a loop.
- **A site with a token issued by hand cannot heal by itself.** It holds such a token because it cannot be
called back, so "enrol again" is not open to it. Its client does **not** enrol on `401 reverify` or
`401 invalid-token`; it stops and reports `relay-refused`, with what the administrator has to ask Intecion
for: after `reverify` (the site sends from a server address Intecion does not know yet — after a move, or
from a second server) that the new address be added; after `invalid-token` a new token. A client knows that
its token was issued by hand because it was pasted into it; the service's answer does not say so.
- A site on `localhost` or behind a firewall cannot be called back. Intecion can issue a token by hand; the
site stores it the same way.
- Use the token only from the site's server. Never print it, never send it to a browser.
## 3. Sending — `POST /v1/send`
Headers (`Bearer` in any case; one space; then the token exactly):
```
Authorization: Bearer ims_…
X-Intecion-Site: example.com
Idempotency-Key: <16 to 128 characters of A–Z a–z 0–9 _ ->
Content-Type: application/json
```
Body ([`SendRequest`](schema.json)):
```json
{
"product": "iapl", "productVersion": "1.17.0",
"kind": "form-notification",
"to": ["[email protected]"],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "…", "html": "…",
"attachments": [{ "filename": "cv.pdf", "contentType": "application/pdf", "content": "<base64>" }]
}
```
- **`kind`** (required): `form-notification`, `form-confirmation`, `account`, `security-alert`, `system`, `test`.
Mail whose purpose the client does not know is `system`. **The kind decides which limits apply (§3.3), so a
client must set it truthfully for its own mail:** `account` only for mail to an account holder (password
reset, invitation), `form-confirmation` for mail to an address a visitor typed.
- **`to`, `cc`, `bcc`**: bare addresses (`name@domain`), ASCII, no display names. At least one `to` (for every
kind but `security-alert`). The total over the three lists is limited per site
(`limits.recipientsPerMessage` in `/v1/status`; the schema's 50 is only the service's upper bound).
- **`security-alert` is addressed by the service.** `to`, `cc` and `bcc` may be left out and are ignored;
whoever controls a site cannot redirect its alerts. The service puts the site's host in front of the
subject: `[example.com] …` — as it does for **any** mail of a site that has Intecion's own address among its
recipients.
- **`replyTo`**: one bare address. The sender address has no mailbox, so send one whenever a reply makes sense.
- **`senderName`**: the display name. Optional; without it the mail leaves under the site's host. See §3.1.
- **`subject`**: 1 to 300 characters, **no line breaks, no control characters, no characters that hide or
reorder text** — Unicode categories Cc, Zl, Zp, Co, lone surrogates, and Cf (zero-width space, direction
marks and overrides, word joiner, byte-order mark, tag characters) **except three that are ordinary text**:
the zero-width joiner U+200D (inside emoji), the zero-width non-joiner U+200C (Persian and other scripts) and
the soft hyphen U+00AD. A subject is often a visitor's own words: **the client strips what is not allowed
before sending** (a regular expression for it: `/[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}]|(?![\u200C\u200D\u00AD])\p{Cf}/gu`);
the service refuses, it does not repair, and a refused message is a lost one. A subject must not start with the
service's name in brackets (`[Intecion Notifications Webservice] …`): that is how the service's own notices
begin.
- **`text` and/or `html`**: at least one. Together at most `limits.maxBodyBytes` (UTF-8).
- **`senderName`**, **`subject`**: lengths are counted in characters (Unicode code points), not bytes.
- **`attachments`**: `content` is base64 (standard alphabet, padded to a multiple of four, no line breaks).
Decoded, all files together are at most `limits.maxAttachmentBytes`. File names: no path, no quotes, no
control or invisible characters. Programs and scripts are refused by extension
(`422 attachment-refused`, with `field` naming the file).
- The sender address is fixed by the service. It adds `X-Intecion-Site: <host>` and `X-Intecion-Product: <product>`
to the mail.
Answer ([`SendResponse`](schema.json)):
```json
{ "ok": true, "id": "…", "messageId": "…", "replayed": false,
"senderName": "Kancelaria Example", "warnings": [],
"quota": { "hour": { "limit": 30, "remaining": 29 }, "day": { "limit": 200, "remaining": 199 } } }
```
`200` means the back end accepted the message for delivery, not that it arrived.
### 3.1 The sender name
The service cleans the name and may replace it. A name that is not accepted is **not** a failed send: the mail
leaves under the site's host instead, and the answer carries `"warnings": ["sender-name-replaced"]` and the
name used in `senderName`.
Accepted: at most 64 characters; letters, digits, spaces and `. , & ' - ( ) /`; letters of one script only.
The guard errs on the careful side and will now and then replace an honest name (one that contains a word
from the list, or reads like a web address: "Dom.Pl"). **A client shows the warning in its panel, with the name
that was used,** so that the site's owner can choose another.
Not accepted: `@ < > " \`, anything that looks like an e-mail or web address (the site's own host is allowed),
and names on the service's list of names that are never a client's (mailbox providers, banks, "support",
"security", "administrator", "no-reply" …). The list is the service's and can change without a new contract
version.
### 3.2 `Idempotency-Key`
- One key per message; the same key on every retry of that message.
- **"The same body" means the same bytes.** A client encodes a message to JSON **once**, keeps those bytes with
the key, and sends exactly them on every retry. Encoding the same message again is not safe: another order of
the fields, `\/` instead of `/`, or other spacing is another body.
- The same key with the same bytes within 24 hours: no second mail; the first answer comes back with
`"replayed": true`.
- The same key with other bytes: `409 idempotency-conflict`.
- A send that was refused or failed does not use up its key.
### 3.3 Limits
A message that would pass a limit is refused whole with `429 quota-exceeded` and `limit`:
| `limit` | Counted | Applies to |
|---|---|---|
| `hour` | messages in the last 60 minutes | every kind but `security-alert`. **`account` mail may use all of it; every other kind only four fifths** (24 of 30), so that a busy or abused form cannot use up the room for a password reset |
| `day` | messages this UTC day | the same: four fifths (160 of 200) for everything but `account` |
| `alerts` | `security-alert` messages this UTC day | `security-alert` only: a budget of its own (`limits.securityAlertsPerDay`, 20), outside `hour` and `day` in both directions — alerts use up nothing else, and nothing else can use up the alerts |
| `recipient` | `form-confirmation` messages to one address this UTC day | `form-confirmation` only: it is for addresses a visitor typed into a form. Other mail to one address (a form's notification to the client's office) is never refused by it |
| `new-recipients` | addresses this site has not mailed in the last 30 days, this UTC day | every kind but `account` and `security-alert`. **A form's confirmations may use four fifths of it** (40 of 50); the rest is kept for the site's other mail, so that addresses a stranger invents in a form cannot keep a notification from an office the site has not written to for a month. `account` mail is outside it altogether: a password reset goes to whoever asked |
| `service` | all sites together this UTC day | every kind |
The numbers are the service's, per site, and are reported by `/v1/status` (`limits`; its `quota` is the whole
hour and day). The `quota` in the answer to a send is what is left **for a message of that kind**. A refused or
failed send costs no quota (failed ones are limited by themselves: 60 an hour per site, the sends that are
with the mail back end at that moment counted in, then `rate-limited`, §1). With a limit below
five nothing is set apart.
## 4. Status — `GET /v1/status`
`Authorization: Bearer ims_…`. Answers for a pending and a suspended site too, so a panel can say why mail does
not go out ([`StatusResponse`](schema.json)):
```json
{ "ok": true, "state": "active", "host": "example.com", "product": "iapl",
"service": { "name": "Intecion Notifications Webservice", "version": "1.0.0", "contract": "1.7.1" },
"sender": { "address": "[email protected]" },
"limits": { "messagesPerHour": 30, "messagesPerDay": 200, "recipientsPerMessage": 10,
"perRecipientPerDay": 10, "newRecipientsPerDay": 50,
"maxBodyBytes": 512000, "maxAttachmentBytes": 10485760, "maxAttachments": 20 },
"quota": { "hour": { "limit": 30, "remaining": 30 }, "day": { "limit": 200, "remaining": 200 } },
"kinds": ["form-notification", "form-confirmation", "account", "security-alert", "system", "test"],
"token": { "issuedAt": "2026-11-25T10:00:00.000Z", "rotateAfter": "2027-02-23T10:00:00.000Z" } }
```
A client takes its attachment limit from `limits.maxAttachmentBytes`, never from a constant of its own.
## 5. Rotation — `POST /v1/rotate`
`Authorization: Bearer ims_…`, no body. When `token.rotateAfter` has passed (90 days after issue), the client
asks for a new token. The answer carries it ([`RotateResponse`](schema.json)):
```json
{ "ok": true, "token": "ims_…", "previousValidUntil": "2027-02-24T10:00:00.000Z" }
```
- Store the new token at once. The previous one stays valid for 24 hours.
- Only the **current** token can rotate. With several processes on one site, exactly one rotation wins; the
others get `409 already-rotated` and read the shared store again.
- If the answer is lost, the new token is lost: the old one works for 24 hours, then `401 invalid-token` leads
to a new enrolment. A client that gets `already-rotated` and finds no newer token in its store enrols again
at once instead of waiting for that.
## 6. Giving up the token — `POST /v1/revoke`
`Authorization: Bearer ims_…`, no body. Every token of the site stops working at once; `{ "ok": true }`. The
site's state is kept. To send again the site enrols again.
## 7. `GET /health`
No authentication. `200 { "ok": true }` or `503 { "ok": false }`, nothing else. For an uptime check, not for a client.
## 8. Authentication, in one place
- The token is `ims_` and 43 characters. It is opaque; the service keeps only its SHA-256.
- Every route except `/v1/enrol` and `/health` needs it, **and** needs the request to come from a server
address the site enrolled from (IPv6: the same `/64`). A good token from another address gets `401 reverify`
and nothing else — not even the site's state.
- **A token belongs to one host and cannot act for another — and both sides hold it to that.**
- **Every request with a token carries `X-Intecion-Site: <the site's own public host>`** (the host it
enrolled as, lower case). Without the header: `400 invalid-request`. With a host that is not the token's:
`403 host-mismatch` — nothing is sent, read, rotated or revoked.
- **A client stores the host together with the token** (at the confirm endpoint: the host it is enrolling
as) and, before it uses a token, compares that stored host with its own public host of this moment. When
they differ the token is not its own — the database was copied from another site (staging from
production, a restored backup of another project), or somebody pasted a foreign token: the client does not
use it, forgets it, and enrols as itself.
- A client that reads `/v1/status` compares the `host` in the answer with its own the same way.
This is a guard against an honest mistake, not against a thief — whoever steals a token can name its host;
the address binding is what stops them. Without the guard, a copy of a site running on the same server as
the original would send mail as the original, on the original's limits.
## 9. Versions
- `VERSION` is `major.minor.patch`. The major is the path prefix (`/v1`).
- **Minor:** something was added that an older client need not know — a new optional request field, a new
answer field, a new `kind`, a new error `code` (treat an unknown code by its `retryable`), a new warning.
For that reason `code` and `warnings` are open strings in the schema, not closed lists.
- **Before the first release** (the first `mail-relay-contract/v…` tag) these are development versions: any
change of behaviour bumps the minor, and nobody is promised that an older copy still works. From the first
tag on the rules above hold strictly.
- **Patch:** wording, examples.
- **Major:** anything else. The service keeps answering the previous major for as long as any released client
speaks it.
- `/v1/status` reports the contract version the service speaks. A client carries the `VERSION` of its copy.
## 10. The examples and the runner
Each file in `examples/` is one case:
```json
{
"id": "send-hour-quota",
"title": "…",
"given": { "site": "active", "quota": "hour-exhausted" },
"request": { "method": "POST", "path": "/v1/send",
"headers": { "authorization": "Bearer {{token}}", "idempotency-key": "{{idempotencyKey}}", "content-type": "application/json" },
"schema": "SendRequest", "body": { } },
"response": { "status": 429, "schema": "Error", "body": { "ok": false, "code": "quota-exceeded", "limit": "hour" } },
"then": { "mails": 0 },
"client": { "retry": false, "reEnrol": false, "status": "relay-quota" }
}
```
- **`given`** names the state the case needs; whoever runs the examples arranges it (table below).
- **`request`** is sent as written, after `{{name}}` is replaced. `schema` names the `$defs` entry the body
must match (left out when the body is wrong on purpose). `{ "$base64Bytes": n }` stands for the base64 of
`n` bytes.
- **`response.body`** is a subset: every field written must be there with that value; more may be there.
- **`then`** says what must be true afterwards: `mails` (how many messages reached the back end in this case)
and `mail` (fields of the one message).
- **`client`** says what a client does with this answer: `retry`, `reEnrol`, and the suggested site status.
Use it to test a client against a canned answer.
- `"direction": "service-to-site"` marks a case that describes the call-back: the request is what the
service sends, the response what the site's confirm endpoint answers.
### `given`
| Key | Values | Meaning |
|---|---|---|
| `site` | `none`, `pending`, `active`, `suspended` | State of `{{host}}` in the registry. Anything but `none` implies a token in `{{token}}` |
| `listed` | `true`, `false` | Enrolment: whether `{{host}}` is on Intecion's list |
| `callback` | `ok`, `not-found`, `wrong-confirmation`, `redirect`, `no-content` | Enrolment: how the site's confirm endpoint behaves. `no-content` answers a bare `204` |
| `token` | `current`, `unknown`, `previous`, `none` | Which token `{{token}}` is. `previous` is a token replaced less than 24 hours ago. `none`: the header is left out |
| `address` | `known`, `unknown` | Whether the request comes from an address the site enrolled from |
| `quota` | `fresh`, `hour-exhausted`, `day-exhausted`, `recipient-exhausted`, `hour-share-used` | The site's counters. `recipient-exhausted`: `{{recipient}}` got the day's maximum of form confirmations. `hour-share-used`: mail other than `account` has used its four fifths of the hour |
| `idempotency` | `fresh`, `sent-same`, `sent-other` | Whether `{{idempotencyKey}}` was already used: for this very body, or for another |
| `backend` | `ok`, `recipient-suppressed`, `failure` | How the mail back end answers |
Variables: `{{host}}`, `{{token}}`, `{{nonce}}`, `{{idempotencyKey}}`, `{{recipient}}`, and — read from the
service — `{{senderAddress}}`, `{{alertRecipient}}`.
### Running them
```js
import { runExample } from './runner.mjs'
const driver = {
// Arrange `given`; return the variables for {{…}}.
async arrange(given, example) { return { host, token, nonce, idempotencyKey, recipient, senderAddress, alertRecipient } },
// Send one request to the thing under test.
async request({ method, path, headers, body }) { return { status, headers, body } },
// Optional: validate `value` against schema.json#/$defs/<name>; return a list of problems.
validate(name, value) { return [] },
// Optional: the messages that reached the back end since arrange().
async mails() { return [{ from, fromName, to, cc, bcc, replyTo, subject, headers }] },
}
for (const example of examples) await runExample(example, driver) // throws on the first mismatch
```
The service runs every example against the Worker under the local Workers runtime
(`services/mail-relay/test/contract.test.ts`). A client's local stand-in for the service runs the same files.
**A stand-in is not the service.** The examples are chosen so that the rules stated in this document decide
them (a sender name with an address in it; a file called `.exe`). The service's own lists — names that are
never a client's, file types it does not carry — are not part of the contract, can change without a new
version, and need not be reproduced: a stand-in approximates them, and a client must not rely on a name or a
file type passing because its stand-in let it pass.
## 11. Using the contract in a client
Until a client lives in this repository it **copies** this folder (all of it, `CHECKSUMS` included) from a
`mail-relay-contract/v…` tag, and has one test that runs `node checksums.mjs --check` on the copy, so a
hand-edited copy fails. The copy's `VERSION` says which contract the client speaks.
Checklist for a client:
1. Constants: the base address, the contract version. No secret.
2. A confirm endpoint (public; `404` unless it holds the nonce; the nonce looked up before any limiter, and
only refused calls counted by it; constant-time compare, single use, answers the confirmation as the only output, keeps the earlier token until the new one is accepted).
3. A token store that is never readable from outside and never printed — holding the token **and the host it
was issued to**. Before every use: is that host still this site's own public host? If not, do not use the
token; enrol as this site. Send `X-Intecion-Site` with every request that carries a token; on
`403 host-mismatch` forget the token and enrol.
4. Enrol on the first send without a token, after `invalid-token` and after `reverify` — unless the token was
issued by hand: then stop and report (§2). Guard against two processes enrolling at once
(`enrolment-in-progress`).
5. One `Idempotency-Key` per message and one encoding of it, both kept across retries; at most three attempts,
30 seconds each, ten seconds of waiting in all, only when `retryable`; an enrolment on the way does not
count; "no answer", `in-progress` and an answer that is not the service's JSON (unless its status is 400 to
499) are reported as not confirmed, never as not sent. No `Origin` or `Sec-Fetch-Site` header. Without
storage for unsent mail: no retry after the report; consider keys derived from the record (§1).
6. **Limit what a visitor can make the site send as `account` mail.** "Forgot password" for an address somebody
types is a visitor's lever like a form: the service lets `account` mail use the whole hour and day and no
limit per address, so thirty requests use up the site's hour. The client's own limiter (per address and per
visitor) is what decides; the service cannot tell a wanted reset from an unwanted one.
7. Strip from the subject what §3 does not allow (line breaks, control characters, direction marks and other
invisible characters — not only line breaks); bare addresses only; the right `kind` for each mail.
8. Read limits from `/v1/status`; rotate after `token.rotateAfter`.
9. Run the examples: the `client` block of each against canned answers, and the whole set against your local
stand-in.
+1
View File
@@ -0,0 +1 @@
1.7.1
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env node
// SHA-256 of every contract file, so a hand-edited copy is noticed.
// node checksums.mjs --check compare the files with CHECKSUMS (exit 1 on any difference)
// node checksums.mjs --write rewrite CHECKSUMS (only in the IWDL repository, when the contract changes)
// Node only, no dependency. Works on a copy of this folder anywhere.
import { createHash } from 'node:crypto'
import { readFileSync, readdirSync, writeFileSync, existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const FIXED = ['README.md', 'CHANGELOG.md', 'VERSION', 'schema.json', 'runner.mjs', 'checksums.mjs']
function files() {
const examples = readdirSync(join(here, 'examples'))
.filter((f) => f.endsWith('.json'))
.sort()
.map((f) => `examples/${f}`)
return [...FIXED, ...examples]
}
function sums() {
return files()
.map((f) => `${createHash('sha256').update(readFileSync(join(here, f))).digest('hex')} ${f}`)
.join('\n') + '\n'
}
const mode = process.argv[2]
if (mode === '--write') {
writeFileSync(join(here, 'CHECKSUMS'), sums())
console.log(`CHECKSUMS written (${files().length} files)`)
} else if (mode === '--check') {
if (!existsSync(join(here, 'CHECKSUMS'))) {
console.error('CHECKSUMS is missing')
process.exit(1)
}
const want = new Map(
readFileSync(join(here, 'CHECKSUMS'), 'utf8').split('\n').filter(Boolean).map((l) => {
const [sum, name] = l.split(' ')
return [name, sum]
}),
)
const have = new Map(sums().split('\n').filter(Boolean).map((l) => {
const [sum, name] = l.split(' ')
return [name, sum]
}))
const problems = []
for (const [name, sum] of have) {
if (!want.has(name)) problems.push(`not in CHECKSUMS: ${name}`)
else if (want.get(name) !== sum) problems.push(`changed: ${name}`)
}
for (const name of want.keys()) if (!have.has(name)) problems.push(`missing: ${name}`)
if (problems.length) {
console.error(problems.join('\n'))
console.error('\nThe contract files do not match CHECKSUMS. Copy them again from IWDL; do not edit a copy.')
process.exit(1)
}
console.log(`contract ${readFileSync(join(here, 'VERSION'), 'utf8').trim()}: ${have.size} files match CHECKSUMS`)
} else {
console.error('usage: node checksums.mjs --check | --write')
process.exit(2)
}
@@ -0,0 +1,25 @@
{
"id": "callback-confirm-wordpress",
"direction": "service-to-site",
"title": "IAWL (WordPress) sites: the same call at the REST route addressed by query, which works with and without pretty permalinks",
"request": {
"method": "POST",
"path": "/?rest_route=/iawl/v1/mail-relay/confirm",
"headers": {
"content-type": "application/json"
},
"schema": "CallbackRequest",
"body": {
"nonce": "EXAMPLEnonceEXAMPLEnonceEXAMPLEnonce00000000",
"token": "ims_EXAMPLEtokenEXAMPLEtokenEXAMPLEtoken0000000",
"state": "active"
}
},
"response": {
"status": 200,
"schema": "CallbackResponse",
"body": {
"confirmation": "1d5818782053c1f5aae3f9abd898a530cf974c59526d240902c9e19619e0462b"
}
}
}
@@ -0,0 +1,25 @@
{
"id": "callback-confirm",
"direction": "service-to-site",
"title": "IAPL (Payload) sites: the call the service makes, and the only answer that enrols. confirmation = hex SHA-256 of nonce + \".\" + token",
"request": {
"method": "POST",
"path": "/api/iapl/mail-relay/confirm",
"headers": {
"content-type": "application/json"
},
"schema": "CallbackRequest",
"body": {
"nonce": "EXAMPLEnonceEXAMPLEnonceEXAMPLEnonce00000000",
"token": "ims_EXAMPLEtokenEXAMPLEtokenEXAMPLEtoken0000000",
"state": "active"
}
},
"response": {
"status": 200,
"schema": "CallbackResponse",
"body": {
"confirmation": "1d5818782053c1f5aae3f9abd898a530cf974c59526d240902c9e19619e0462b"
}
}
}
@@ -0,0 +1,21 @@
{
"id": "callback-unknown-nonce",
"direction": "service-to-site",
"title": "A call with a nonce the site does not hold: 404, nothing stored",
"request": {
"method": "POST",
"path": "/api/iapl/mail-relay/confirm",
"headers": {
"content-type": "application/json"
},
"schema": "CallbackRequest",
"body": {
"nonce": "UNKNOWNnonceUNKNOWNnonceUNKNOWNnonce00000000",
"token": "ims_EXAMPLEtokenEXAMPLEtokenEXAMPLEtoken0000000",
"state": "active"
}
},
"response": {
"status": 404
}
}
@@ -0,0 +1,33 @@
{
"id": "enrol-address-literal",
"title": "An address literal is not a host",
"given": {
"site": "none"
},
"request": {
"method": "POST",
"path": "/v1/enrol",
"headers": {
"content-type": "application/json"
},
"body": {
"host": "192.0.2.10",
"nonce": "{{nonce}}",
"product": "iapl",
"productVersion": "1.17.0"
}
},
"response": {
"status": 403,
"schema": "Error",
"body": {
"ok": false,
"code": "host-not-allowed"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-refused"
}
}
@@ -0,0 +1,37 @@
{
"id": "enrol-callback-no-content",
"title": "An endpoint that answers 204 to anything is not a confirm endpoint",
"given": {
"site": "none",
"listed": true,
"callback": "no-content"
},
"request": {
"method": "POST",
"path": "/v1/enrol",
"headers": {
"content-type": "application/json"
},
"schema": "EnrolRequest",
"body": {
"host": "{{host}}",
"nonce": "{{nonce}}",
"product": "iapl",
"productVersion": "1.17.0"
}
},
"response": {
"status": 422,
"schema": "Error",
"body": {
"ok": false,
"code": "callback-failed",
"reason": "status"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-refused"
}
}
@@ -0,0 +1,38 @@
{
"id": "enrol-callback-not-found",
"title": "Enrolment for a host whose confirm endpoint does not hold the nonce (a host the caller does not control) yields nothing",
"given": {
"site": "none",
"listed": true,
"callback": "not-found"
},
"request": {
"method": "POST",
"path": "/v1/enrol",
"headers": {
"content-type": "application/json"
},
"schema": "EnrolRequest",
"body": {
"host": "{{host}}",
"nonce": "{{nonce}}",
"product": "iapl",
"productVersion": "1.17.0"
}
},
"response": {
"status": 422,
"schema": "Error",
"body": {
"ok": false,
"code": "callback-failed",
"reason": "status",
"retryable": false
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-refused"
}
}
@@ -0,0 +1,37 @@
{
"id": "enrol-callback-path-given",
"title": "A site cannot say where it is to be called back: the path is fixed per product",
"given": {
"site": "none",
"listed": true,
"callback": "ok"
},
"request": {
"method": "POST",
"path": "/v1/enrol",
"headers": {
"content-type": "application/json"
},
"body": {
"host": "{{host}}",
"callbackPath": "/api/iapl/mail-relay/confirm",
"nonce": "{{nonce}}",
"product": "iapl",
"productVersion": "1.17.0"
}
},
"response": {
"status": 400,
"schema": "Error",
"body": {
"ok": false,
"code": "invalid-request",
"field": "callbackPath"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,37 @@
{
"id": "enrol-callback-redirect",
"title": "A redirect is never followed",
"given": {
"site": "none",
"listed": true,
"callback": "redirect"
},
"request": {
"method": "POST",
"path": "/v1/enrol",
"headers": {
"content-type": "application/json"
},
"schema": "EnrolRequest",
"body": {
"host": "{{host}}",
"nonce": "{{nonce}}",
"product": "iapl",
"productVersion": "1.17.0"
}
},
"response": {
"status": 422,
"schema": "Error",
"body": {
"ok": false,
"code": "callback-failed",
"reason": "redirect"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-refused"
}
}
@@ -0,0 +1,37 @@
{
"id": "enrol-callback-wrong-confirmation",
"title": "A 200 answer without the right confirmation does not enrol",
"given": {
"site": "none",
"listed": true,
"callback": "wrong-confirmation"
},
"request": {
"method": "POST",
"path": "/v1/enrol",
"headers": {
"content-type": "application/json"
},
"schema": "EnrolRequest",
"body": {
"host": "{{host}}",
"nonce": "{{nonce}}",
"product": "iapl",
"productVersion": "1.17.0"
}
},
"response": {
"status": 422,
"schema": "Error",
"body": {
"ok": false,
"code": "callback-failed",
"reason": "confirmation"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-refused"
}
}
@@ -0,0 +1,37 @@
{
"id": "enrol-from-browser",
"title": "A cross-site POST from a browser is refused",
"given": {
"site": "none",
"listed": true,
"callback": "ok"
},
"request": {
"method": "POST",
"path": "/v1/enrol",
"headers": {
"content-type": "application/json",
"origin": "https://evil.example.net"
},
"schema": "EnrolRequest",
"body": {
"host": "{{host}}",
"nonce": "{{nonce}}",
"product": "iapl",
"productVersion": "1.17.0"
}
},
"response": {
"status": 403,
"schema": "Error",
"body": {
"ok": false,
"code": "browser-not-allowed"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,36 @@
{
"id": "enrol-listed-active",
"title": "A host on Intecion's list enrols and is active at once; the answer has no token",
"given": {
"site": "none",
"listed": true,
"callback": "ok"
},
"request": {
"method": "POST",
"path": "/v1/enrol",
"headers": {
"content-type": "application/json"
},
"schema": "EnrolRequest",
"body": {
"host": "{{host}}",
"nonce": "{{nonce}}",
"product": "iapl",
"productVersion": "1.17.0"
}
},
"response": {
"status": 200,
"schema": "EnrolResponse",
"body": {
"ok": true,
"state": "active"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,33 @@
{
"id": "enrol-localhost",
"title": "A local name cannot be enrolled",
"given": {
"site": "none"
},
"request": {
"method": "POST",
"path": "/v1/enrol",
"headers": {
"content-type": "application/json"
},
"body": {
"host": "shop.localhost",
"nonce": "{{nonce}}",
"product": "iapl",
"productVersion": "1.17.0"
}
},
"response": {
"status": 403,
"schema": "Error",
"body": {
"ok": false,
"code": "host-not-allowed"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-refused"
}
}
@@ -0,0 +1,36 @@
{
"id": "enrol-short-nonce",
"title": "A short nonce is refused",
"given": {
"site": "none",
"listed": true,
"callback": "ok"
},
"request": {
"method": "POST",
"path": "/v1/enrol",
"headers": {
"content-type": "application/json"
},
"body": {
"host": "{{host}}",
"nonce": "short",
"product": "iapl",
"productVersion": "1.17.0"
}
},
"response": {
"status": 400,
"schema": "Error",
"body": {
"ok": false,
"code": "invalid-request",
"field": "nonce"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,35 @@
{
"id": "enrol-suspended",
"title": "A suspended site cannot enrol its way back",
"given": {
"site": "suspended",
"callback": "ok"
},
"request": {
"method": "POST",
"path": "/v1/enrol",
"headers": {
"content-type": "application/json"
},
"schema": "EnrolRequest",
"body": {
"host": "{{host}}",
"nonce": "{{nonce}}",
"product": "iapl",
"productVersion": "1.17.0"
}
},
"response": {
"status": 403,
"schema": "Error",
"body": {
"ok": false,
"code": "site-suspended"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-suspended"
}
}
@@ -0,0 +1,36 @@
{
"id": "enrol-unlisted-pending",
"title": "A host that is not on the list enrols and waits for approval",
"given": {
"site": "none",
"listed": false,
"callback": "ok"
},
"request": {
"method": "POST",
"path": "/v1/enrol",
"headers": {
"content-type": "application/json"
},
"schema": "EnrolRequest",
"body": {
"host": "{{host}}",
"nonce": "{{nonce}}",
"product": "iapl",
"productVersion": "1.17.0"
}
},
"response": {
"status": 200,
"schema": "EnrolResponse",
"body": {
"ok": true,
"state": "pending"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-pending"
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"id": "health",
"title": "Health says yes or no and nothing else",
"given": {},
"request": {
"method": "GET",
"path": "/health",
"headers": {}
},
"response": {
"status": 200,
"schema": "HealthResponse",
"body": {
"ok": true
}
}
}
@@ -0,0 +1,18 @@
{
"id": "not-found",
"title": "An unknown route",
"given": {},
"request": {
"method": "GET",
"path": "/v2/send",
"headers": {}
},
"response": {
"status": 404,
"schema": "Error",
"body": {
"ok": false,
"code": "not-found"
}
}
}
@@ -0,0 +1,27 @@
{
"id": "revoke-ok",
"title": "The site gives up its token",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/revoke",
"headers": {
"authorization": "Bearer {{token}}",
"x-intecion-site": "{{host}}"
}
},
"response": {
"status": 200,
"schema": "RevokeResponse",
"body": {
"ok": true
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,27 @@
{
"id": "rotate-ok",
"title": "The current token rotates; the answer carries the new one",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/rotate",
"headers": {
"authorization": "Bearer {{token}}",
"x-intecion-site": "{{host}}"
}
},
"response": {
"status": 200,
"schema": "RotateResponse",
"body": {
"ok": true
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,29 @@
{
"id": "rotate-previous-token",
"title": "A token that was already replaced cannot rotate",
"given": {
"site": "active",
"token": "previous"
},
"request": {
"method": "POST",
"path": "/v1/rotate",
"headers": {
"authorization": "Bearer {{token}}",
"x-intecion-site": "{{host}}"
}
},
"response": {
"status": 409,
"schema": "Error",
"body": {
"ok": false,
"code": "already-rotated"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,56 @@
{
"id": "send-attachments-too-large",
"title": "Attachments over the limit",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello.",
"attachments": [
{
"filename": "big.pdf",
"contentType": "application/pdf",
"content": {
"$base64Bytes": 10485761
}
}
]
}
},
"response": {
"status": 413,
"schema": "Error",
"body": {
"ok": false,
"code": "too-large",
"limit": "attachments"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-too-large"
}
}
@@ -0,0 +1,48 @@
{
"id": "send-backend-failed",
"title": "The back end fails; the client may retry with the same key",
"given": {
"site": "active",
"backend": "failure"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 502,
"schema": "Error",
"body": {
"ok": false,
"code": "backend-failed",
"retryable": true
}
},
"then": {
"mails": 0
},
"client": {
"retry": true,
"reEnrol": false,
"status": "relay-unreachable"
}
}
@@ -0,0 +1,48 @@
{
"id": "send-bearer-any-case",
"title": "The word \"Bearer\" in any case",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 200,
"schema": "SendResponse",
"body": {
"ok": true,
"replayed": false,
"senderName": "Kancelaria Example",
"warnings": []
}
},
"then": {
"mails": 1
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,49 @@
{
"id": "send-day-quota",
"title": "The daily limit refuses the message",
"given": {
"site": "active",
"quota": "day-exhausted"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 429,
"schema": "Error",
"body": {
"ok": false,
"code": "quota-exceeded",
"limit": "day",
"retryable": false
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-quota"
}
}
@@ -0,0 +1,46 @@
{
"id": "send-display-name-recipient",
"title": "Recipients are bare addresses",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"Jan <[email protected]>"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 400,
"schema": "Error",
"body": {
"ok": false,
"code": "invalid-request",
"field": "to"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,54 @@
{
"id": "send-executable-attachment",
"title": "A program is never carried",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello.",
"attachments": [
{
"filename": "invoice.pdf.exe",
"contentType": "application/pdf",
"content": "TVqQAAMAAAA="
}
]
}
},
"response": {
"status": 422,
"schema": "Error",
"body": {
"ok": false,
"code": "attachment-refused",
"field": "attachments[0]"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-attachment-refused"
}
}
@@ -0,0 +1,47 @@
{
"id": "send-from-browser",
"title": "A request with an Origin header is refused whatever the token",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"origin": "https://evil.example.net",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 403,
"schema": "Error",
"body": {
"ok": false,
"code": "browser-not-allowed"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,47 @@
{
"id": "send-from-field",
"title": "The sender address cannot be set",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello.",
"from": "[email protected]"
}
},
"response": {
"status": 400,
"schema": "Error",
"body": {
"ok": false,
"code": "invalid-request",
"field": "from"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,49 @@
{
"id": "send-headers-field",
"title": "Free headers cannot be set",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello.",
"headers": {
"Return-Path": "[email protected]"
}
}
},
"response": {
"status": 400,
"schema": "Error",
"body": {
"ok": false,
"code": "invalid-request",
"field": "headers"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,47 @@
{
"id": "send-host-mismatch",
"title": "A token used by a site that names another host (a copy of the site's database, a token pasted into the wrong site) is refused",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "copy-of-{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 403,
"schema": "Error",
"body": {
"ok": false,
"code": "host-mismatch",
"retryable": false
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": true,
"status": null
}
}
@@ -0,0 +1,46 @@
{
"id": "send-hour-quota-account",
"title": "When other mail has used its share of the hour, account mail (a password reset) still goes out",
"given": {
"site": "active",
"quota": "hour-share-used"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "account",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 200,
"schema": "SendResponse",
"body": {
"ok": true
}
},
"then": {
"mails": 1
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,49 @@
{
"id": "send-hour-quota",
"title": "The hourly limit refuses the message and says so",
"given": {
"site": "active",
"quota": "hour-exhausted"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 429,
"schema": "Error",
"body": {
"ok": false,
"code": "quota-exceeded",
"limit": "hour",
"retryable": false
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-quota"
}
}
@@ -0,0 +1,47 @@
{
"id": "send-key-reused",
"title": "The same Idempotency-Key for another message",
"given": {
"site": "active",
"idempotency": "sent-other"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 409,
"schema": "Error",
"body": {
"ok": false,
"code": "idempotency-conflict"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,49 @@
{
"id": "send-no-sender-name",
"title": "Without a sender name the mail leaves under the host, with no warning",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 200,
"schema": "SendResponse",
"body": {
"ok": true,
"senderName": "{{host}}",
"warnings": []
}
},
"then": {
"mails": 1,
"mail": {
"fromName": "{{host}}"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,47 @@
{
"id": "send-no-token",
"title": "No Authorization header",
"given": {
"site": "active",
"token": "none"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 401,
"schema": "Error",
"body": {
"ok": false,
"code": "invalid-token"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": true,
"status": null
}
}
@@ -0,0 +1,61 @@
{
"id": "send-ok",
"title": "An active site sends one message",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 200,
"schema": "SendResponse",
"body": {
"ok": true,
"replayed": false,
"senderName": "Kancelaria Example",
"warnings": []
}
},
"then": {
"mails": 1,
"mail": {
"from": "{{senderAddress}}",
"fromName": "Kancelaria Example",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"subject": "New enquiry",
"headers": {
"X-Intecion-Site": "{{host}}",
"X-Intecion-Product": "iapl"
}
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,46 @@
{
"id": "send-pending",
"title": "A site waiting for approval sends nothing",
"given": {
"site": "pending"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 403,
"schema": "Error",
"body": {
"ok": false,
"code": "site-pending"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-pending"
}
}
@@ -0,0 +1,46 @@
{
"id": "send-previous-token",
"title": "A token replaced less than 24 hours ago still sends",
"given": {
"site": "active",
"token": "previous"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 200,
"schema": "SendResponse",
"body": {
"ok": true
}
},
"then": {
"mails": 1
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,46 @@
{
"id": "send-recipient-quota-other-kinds",
"title": "Other mail to the same address is not refused by that limit (a form's notification to the client's office)",
"given": {
"site": "active",
"quota": "recipient-exhausted"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 200,
"schema": "SendResponse",
"body": {
"ok": true
}
},
"then": {
"mails": 1
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,48 @@
{
"id": "send-recipient-quota",
"title": "A form's confirmation: one address gets only so many a day",
"given": {
"site": "active",
"quota": "recipient-exhausted"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-confirmation",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 429,
"schema": "Error",
"body": {
"ok": false,
"code": "quota-exceeded",
"limit": "recipient"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-quota"
}
}
@@ -0,0 +1,48 @@
{
"id": "send-recipient-suppressed",
"title": "The back end refuses a suppressed recipient",
"given": {
"site": "active",
"backend": "recipient-suppressed"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 422,
"schema": "Error",
"body": {
"ok": false,
"code": "recipient-suppressed",
"retryable": false
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-recipient-suppressed"
}
}
@@ -0,0 +1,47 @@
{
"id": "send-replay",
"title": "The same Idempotency-Key and body again: no second mail",
"given": {
"site": "active",
"idempotency": "sent-same"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 200,
"schema": "SendResponse",
"body": {
"ok": true,
"replayed": true
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,53 @@
{
"id": "send-security-alert",
"title": "A security alert is addressed by the service and marked with the site's host; the recipients in the request are ignored",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "security-alert",
"to": [
"[email protected]"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 200,
"schema": "SendResponse",
"body": {
"ok": true
}
},
"then": {
"mails": 1,
"mail": {
"to": [
"{{alertRecipient}}"
],
"cc": [],
"bcc": [],
"subject": "[{{host}}] New enquiry"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,52 @@
{
"id": "send-sender-name-replaced",
"title": "A sender name that looks like an address is replaced by the host; the mail still goes out",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "PayPal <[email protected]>",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 200,
"schema": "SendResponse",
"body": {
"ok": true,
"senderName": "{{host}}",
"warnings": [
"sender-name-replaced"
]
}
},
"then": {
"mails": 1,
"mail": {
"fromName": "{{host}}"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-name-replaced"
}
}
@@ -0,0 +1,47 @@
{
"id": "send-subject-direction-mark",
"title": "A direction override in the subject is refused: the client strips such characters first",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "Invoice ‮fdp.exe",
"text": "Hello."
}
},
"response": {
"status": 400,
"schema": "Error",
"body": {
"ok": false,
"code": "invalid-request",
"field": "subject"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,47 @@
{
"id": "send-subject-imitates-service",
"title": "A subject that starts like one of the service's own notices is refused",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "[Intecion Notifications Webservice] example.com waits for approval",
"text": "Hello."
}
},
"response": {
"status": 400,
"schema": "Error",
"body": {
"ok": false,
"code": "invalid-request",
"field": "subject"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,47 @@
{
"id": "send-subject-line-break",
"title": "A line break in the subject (header injection) is refused, not repaired",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "Hello\r\nBcc: [email protected]",
"text": "Hello."
}
},
"response": {
"status": 400,
"schema": "Error",
"body": {
"ok": false,
"code": "invalid-request",
"field": "subject"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,51 @@
{
"id": "send-subject-visitor-text",
"title": "A subject with what visitors write — an emoji made of several, a soft hyphen — is carried as it is",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "👩‍💻 Straßen­bahn",
"text": "Hello."
}
},
"response": {
"status": 200,
"schema": "SendResponse",
"body": {
"ok": true,
"replayed": false,
"senderName": "Kancelaria Example",
"warnings": []
}
},
"then": {
"mails": 1,
"mail": {
"subject": "👩‍💻 Straßen­bahn"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,46 @@
{
"id": "send-suspended",
"title": "A suspended site sends nothing",
"given": {
"site": "suspended"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 403,
"schema": "Error",
"body": {
"ok": false,
"code": "site-suspended"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-suspended"
}
}
@@ -0,0 +1,46 @@
{
"id": "send-text-plain",
"title": "A form post (text/plain) is refused",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "text/plain",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 415,
"schema": "Error",
"body": {
"ok": false,
"code": "unsupported-media-type"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,51 @@
{
"id": "send-to-intecion-marked",
"title": "Any mail of a site that reaches Intecion's own address gets the site's host in front of its subject",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "system",
"to": [
"{{alertRecipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 200,
"schema": "SendResponse",
"body": {
"ok": true
}
},
"then": {
"mails": 1,
"mail": {
"to": [
"{{alertRecipient}}"
],
"subject": "[{{host}}] New enquiry"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,60 @@
{
"id": "send-too-many-recipients",
"title": "More than ten recipients over To, CC and BCC",
"given": {
"site": "active"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello.",
"cc": [
"[email protected]",
"[email protected]",
"[email protected]"
],
"bcc": [
"[email protected]",
"[email protected]"
]
}
},
"response": {
"status": 422,
"schema": "Error",
"body": {
"ok": false,
"code": "too-many-recipients"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-quota"
}
}
@@ -0,0 +1,48 @@
{
"id": "send-unknown-address",
"title": "A good token from a server address the site never enrolled from (a stolen token)",
"given": {
"site": "active",
"address": "unknown"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 401,
"schema": "Error",
"body": {
"ok": false,
"code": "reverify",
"retryable": false
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": true,
"status": null
}
}
@@ -0,0 +1,47 @@
{
"id": "send-unknown-token",
"title": "A token the service does not know",
"given": {
"site": "active",
"token": "unknown"
},
"request": {
"method": "POST",
"path": "/v1/send",
"headers": {
"authorization": "Bearer {{token}}",
"idempotency-key": "{{idempotencyKey}}",
"content-type": "application/json",
"x-intecion-site": "{{host}}"
},
"schema": "SendRequest",
"body": {
"product": "iapl",
"productVersion": "1.17.0",
"kind": "form-notification",
"to": [
"{{recipient}}"
],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "Hello."
}
},
"response": {
"status": 401,
"schema": "Error",
"body": {
"ok": false,
"code": "invalid-token"
}
},
"then": {
"mails": 0
},
"client": {
"retry": false,
"reEnrol": true,
"status": null
}
}
@@ -0,0 +1,36 @@
{
"id": "status-active",
"title": "Status of an active site",
"given": {
"site": "active"
},
"request": {
"method": "GET",
"path": "/v1/status",
"headers": {
"authorization": "Bearer {{token}}",
"x-intecion-site": "{{host}}"
}
},
"response": {
"status": 200,
"schema": "StatusResponse",
"body": {
"ok": true,
"state": "active",
"host": "{{host}}",
"product": "iapl",
"service": {
"name": "Intecion Notifications Webservice"
},
"sender": {
"address": "{{senderAddress}}"
}
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,28 @@
{
"id": "status-no-site-header",
"title": "Every request with a token names its site",
"given": {
"site": "active"
},
"request": {
"method": "GET",
"path": "/v1/status",
"headers": {
"authorization": "Bearer {{token}}"
}
},
"response": {
"status": 400,
"schema": "Error",
"body": {
"ok": false,
"code": "invalid-request",
"field": "X-Intecion-Site"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": null
}
}
@@ -0,0 +1,28 @@
{
"id": "status-pending",
"title": "Status answers for a pending site too",
"given": {
"site": "pending"
},
"request": {
"method": "GET",
"path": "/v1/status",
"headers": {
"authorization": "Bearer {{token}}",
"x-intecion-site": "{{host}}"
}
},
"response": {
"status": 200,
"schema": "StatusResponse",
"body": {
"ok": true,
"state": "pending"
}
},
"client": {
"retry": false,
"reEnrol": false,
"status": "relay-pending"
}
}
@@ -0,0 +1,29 @@
{
"id": "status-unknown-address",
"title": "Status gives nothing to a token from an unknown address",
"given": {
"site": "active",
"address": "unknown"
},
"request": {
"method": "GET",
"path": "/v1/status",
"headers": {
"authorization": "Bearer {{token}}",
"x-intecion-site": "{{host}}"
}
},
"response": {
"status": 401,
"schema": "Error",
"body": {
"ok": false,
"code": "reverify"
}
},
"client": {
"retry": false,
"reEnrol": true,
"status": null
}
}
+160
View File
@@ -0,0 +1,160 @@
// Contract test runner for the Intecion Notifications Webservice.
// No dependency. Works in Node 20+ and in the Workers runtime (uses only WebCrypto, btoa and TextEncoder).
// How to use it: README.md, "The examples and the runner".
export const CONTRACT_VERSION = '1.7.1'
export class ContractError extends Error {
constructor(exampleId, message) {
super(`[${exampleId}] ${message}`)
this.name = 'ContractError'
this.exampleId = exampleId
}
}
/** The confirmation a site's confirm endpoint answers with: lowercase hex SHA-256 of nonce + "." + token. */
export async function confirmationFor(nonce, token) {
const bytes = new TextEncoder().encode(`${nonce}.${token}`)
const digest = await crypto.subtle.digest('SHA-256', bytes)
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
}
/** Base64 of `n` zero bytes, built without holding the bytes. */
export function base64OfBytes(n) {
const full = Math.floor(n / 3)
const rest = n % 3
return 'AAAA'.repeat(full) + (rest === 1 ? 'AA==' : rest === 2 ? 'AAA=' : '')
}
/** Replace {{name}} and { "$base64Bytes": n } everywhere in a value. Unknown names are an error. */
export function expand(value, vars, exampleId = '?') {
if (typeof value === 'string') {
return value.replace(/\{\{([A-Za-z]+)\}\}/g, (_, name) => {
if (vars[name] === undefined || vars[name] === null) {
throw new ContractError(exampleId, `the driver's arrange() gave no value for {{${name}}}`)
}
return String(vars[name])
})
}
if (Array.isArray(value)) return value.map((v) => expand(v, vars, exampleId))
if (value && typeof value === 'object') {
if (typeof value.$base64Bytes === 'number') return base64OfBytes(value.$base64Bytes)
const out = {}
for (const [k, v] of Object.entries(value)) out[k] = expand(v, vars, exampleId)
return out
}
return value
}
/** Every field of `expected` must be in `actual` with that value; `actual` may have more. Arrays must be equal. */
export function subsetMismatch(actual, expected, path = '') {
if (expected === null || typeof expected !== 'object') {
return Object.is(actual, expected) ? null : `${path || 'value'}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`
}
if (Array.isArray(expected)) {
if (!Array.isArray(actual) || actual.length !== expected.length) {
return `${path || 'value'}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`
}
for (let i = 0; i < expected.length; i++) {
const m = subsetMismatch(actual[i], expected[i], `${path}[${i}]`)
if (m) return m
}
return null
}
if (actual === null || typeof actual !== 'object') {
return `${path || 'value'}: expected an object, got ${JSON.stringify(actual)}`
}
for (const [k, v] of Object.entries(expected)) {
const m = subsetMismatch(actual[k], v, path ? `${path}.${k}` : k)
if (m) return m
}
return null
}
function headerLookup(headers) {
const out = {}
for (const [k, v] of Object.entries(headers ?? {})) out[k.toLowerCase()] = v
return out
}
/**
* Run one example (direction site-to-service) against a driver. Throws ContractError on the first mismatch.
* Returns { request, response, vars } for further checks by the caller.
*/
export async function runExample(example, driver) {
const id = example.id
if (example.direction === 'service-to-site') {
throw new ContractError(id, 'this example describes the call-back; use runCallbackExample()')
}
const given = example.given ?? {}
const vars = (await driver.arrange(given, example)) ?? {}
const headers = expand(example.request.headers ?? {}, given.token === 'none' ? { ...vars, token: '' } : vars, id)
if (given.token === 'none') delete headers.authorization
const body = example.request.body === undefined ? undefined : expand(example.request.body, vars, id)
if (example.request.schema && driver.validate) {
const problems = driver.validate(example.request.schema, body)
if (problems.length) throw new ContractError(id, `the example's request does not match ${example.request.schema}: ${problems.join('; ')}`)
}
const request = { method: example.request.method, path: example.request.path, headers, body }
const response = await driver.request(request)
if (response.status !== example.response.status) {
throw new ContractError(id, `status: expected ${example.response.status}, got ${response.status} ${JSON.stringify(response.body)}`)
}
if (example.response.schema && driver.validate) {
const problems = driver.validate(example.response.schema, response.body)
if (problems.length) throw new ContractError(id, `the answer does not match ${example.response.schema}: ${problems.join('; ')}`)
}
if (example.response.body !== undefined) {
const m = subsetMismatch(response.body, expand(example.response.body, vars, id))
if (m) throw new ContractError(id, `body: ${m}`)
}
if (response.body && response.body.ok === false) {
const got = headerLookup(response.headers)
if (typeof response.body.retryAfter === 'number' && got['retry-after'] !== undefined && String(got['retry-after']) !== String(response.body.retryAfter)) {
throw new ContractError(id, `Retry-After header (${got['retry-after']}) differs from retryAfter (${response.body.retryAfter})`)
}
if (example.client && typeof example.client.retry === 'boolean' && response.body.retryable !== example.client.retry) {
throw new ContractError(id, `retryable: expected ${example.client.retry}, got ${response.body.retryable}`)
}
}
const cors = headerLookup(response.headers)['access-control-allow-origin']
if (cors !== undefined) throw new ContractError(id, 'the service must not send CORS headers')
if (example.then && driver.mails) {
const mails = await driver.mails()
if (typeof example.then.mails === 'number' && mails.length !== example.then.mails) {
throw new ContractError(id, `mails handed to the back end: expected ${example.then.mails}, got ${mails.length}`)
}
if (example.then.mail) {
const m = subsetMismatch(mails[0], expand(example.then.mail, vars, id), 'mail')
if (m) throw new ContractError(id, m)
}
}
return { request, response, vars }
}
/**
* Run a call-back example against a site's confirm endpoint.
* `site.prepare(body)` makes the site hold (or not hold) the nonce; `site.confirm(request)` calls the endpoint.
*/
export async function runCallbackExample(example, site) {
const id = example.id
if (example.direction !== 'service-to-site') throw new ContractError(id, 'not a call-back example')
const holds = example.response.status === 200
await site.prepare({ ...example.request.body, held: holds })
const response = await site.confirm({ ...example.request })
if (response.status !== example.response.status) {
throw new ContractError(id, `status: expected ${example.response.status}, got ${response.status}`)
}
if (holds) {
const expected = await confirmationFor(example.request.body.nonce, example.request.body.token)
if (!response.body || response.body.confirmation !== expected) {
throw new ContractError(id, 'the confirmation is not hex SHA-256 of nonce + "." + token')
}
}
return response
}
+624
View File
@@ -0,0 +1,624 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://webservices.intecion.net/mail/contract/v1/schema.json",
"title": "Intecion Notifications Webservice — wire contract v1",
"description": "Bodies of every request and answer. Requests are closed (an unknown field is refused); answers are open (a client ignores fields it does not know).",
"$defs": {
"Host": {
"description": "A public DNS name, lowercase, punycode for international names. No scheme, port, path or address literal.",
"type": "string",
"minLength": 4,
"maxLength": 253,
"pattern": "^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]([a-z0-9-]{0,61}[a-z0-9])$"
},
"Product": {
"description": "The client product. The list is the service's.",
"type": "string",
"enum": [
"iapl",
"iawl"
]
},
"ProductVersion": {
"type": "string",
"minLength": 1,
"maxLength": 32,
"pattern": "^[0-9A-Za-z][0-9A-Za-z.+_-]*$"
},
"Kind": {
"type": "string",
"enum": [
"form-notification",
"form-confirmation",
"account",
"security-alert",
"system",
"test"
]
},
"SiteState": {
"type": "string",
"enum": [
"pending",
"active",
"suspended"
]
},
"Address": {
"description": "A bare e-mail address. No display name, no angle brackets, no comment.",
"type": "string",
"minLength": 6,
"maxLength": 254,
"pattern": "^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z]([A-Za-z0-9-]{0,61}[A-Za-z0-9])$"
},
"Nonce": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{32,128}$"
},
"Token": {
"description": "Opaque. Never logged, never shown.",
"type": "string",
"pattern": "^ims_[A-Za-z0-9_-]{43}$"
},
"Window": {
"type": "object",
"required": [
"limit",
"remaining"
],
"properties": {
"limit": {
"type": "integer",
"minimum": 0
},
"remaining": {
"type": "integer",
"minimum": 0
}
}
},
"Quota": {
"type": "object",
"required": [
"hour",
"day"
],
"properties": {
"hour": {
"$ref": "#/$defs/Window"
},
"day": {
"$ref": "#/$defs/Window"
}
}
},
"EnrolRequest": {
"type": "object",
"additionalProperties": false,
"required": [
"host",
"nonce",
"product",
"productVersion"
],
"properties": {
"host": {
"$ref": "#/$defs/Host"
},
"nonce": {
"$ref": "#/$defs/Nonce"
},
"product": {
"$ref": "#/$defs/Product"
},
"productVersion": {
"$ref": "#/$defs/ProductVersion"
}
},
"description": "No call-back path: the service calls the path fixed for the product (README §2)."
},
"EnrolResponse": {
"description": "Never carries the token: it went to the site's confirm endpoint.",
"type": "object",
"required": [
"ok",
"state"
],
"properties": {
"ok": {
"const": true
},
"state": {
"$ref": "#/$defs/SiteState"
}
},
"not": {
"required": [
"token"
]
}
},
"CallbackRequest": {
"description": "Sent BY the service TO the site's confirm endpoint: POST https://<host><the product's confirm path>.",
"type": "object",
"additionalProperties": false,
"required": [
"nonce",
"token",
"state"
],
"properties": {
"nonce": {
"$ref": "#/$defs/Nonce"
},
"token": {
"$ref": "#/$defs/Token"
},
"state": {
"$ref": "#/$defs/SiteState"
}
}
},
"CallbackResponse": {
"description": "The site's answer: status 200, a body of at most 1024 bytes that is this JSON object and nothing else, within 8 seconds. confirmation = lowercase hex SHA-256 of the UTF-8 text nonce + \".\" + token.",
"type": "object",
"required": [
"confirmation"
],
"properties": {
"confirmation": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
}
}
},
"Attachment": {
"type": "object",
"additionalProperties": false,
"required": [
"filename",
"contentType",
"content"
],
"properties": {
"filename": {
"type": "string",
"minLength": 1,
"maxLength": 255
},
"contentType": {
"type": "string",
"maxLength": 127,
"pattern": "^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*$"
},
"content": {
"description": "Base64, standard alphabet, no line breaks, padded: the length is a multiple of four. The pattern states the alphabet only — a pattern that also stated the length would overflow regular-expression engines on a 10 MB file; the service checks the length.",
"type": "string",
"minLength": 4,
"pattern": "^[A-Za-z0-9+/]+={0,2}$"
}
}
},
"SendRequest": {
"type": "object",
"additionalProperties": false,
"required": [
"product",
"productVersion",
"kind",
"subject"
],
"properties": {
"product": {
"$ref": "#/$defs/Product"
},
"productVersion": {
"$ref": "#/$defs/ProductVersion"
},
"kind": {
"$ref": "#/$defs/Kind"
},
"to": {
"description": "Bare addresses. The number over to, cc and bcc together is limited per site: limits.recipientsPerMessage in /v1/status (the schema only states the service's upper bound).",
"type": "array",
"items": {
"$ref": "#/$defs/Address"
},
"maxItems": 50
},
"cc": {
"description": "Bare addresses. The number over to, cc and bcc together is limited per site: limits.recipientsPerMessage in /v1/status (the schema only states the service's upper bound).",
"type": "array",
"items": {
"$ref": "#/$defs/Address"
},
"maxItems": 50
},
"bcc": {
"description": "Bare addresses. The number over to, cc and bcc together is limited per site: limits.recipientsPerMessage in /v1/status (the schema only states the service's upper bound).",
"type": "array",
"items": {
"$ref": "#/$defs/Address"
},
"maxItems": 50
},
"replyTo": {
"$ref": "#/$defs/Address"
},
"senderName": {
"description": "At most 256 characters (Unicode code points).",
"type": "string",
"maxLength": 256
},
"subject": {
"description": "1 to 300 characters (code points). No line breaks, control characters or characters that hide or reorder text (README §3 has the exact rule and the three exceptions); must not start with the service's name in brackets.",
"type": "string",
"minLength": 1,
"maxLength": 300
},
"text": {
"type": "string",
"minLength": 1
},
"html": {
"type": "string",
"minLength": 1
},
"attachments": {
"type": "array",
"items": {
"$ref": "#/$defs/Attachment"
},
"maxItems": 20
}
},
"anyOf": [
{
"required": [
"text"
]
},
{
"required": [
"html"
]
}
],
"allOf": [
{
"if": {
"properties": {
"kind": {
"const": "security-alert"
}
},
"required": [
"kind"
]
},
"else": {
"required": [
"to"
],
"properties": {
"to": {
"minItems": 1
}
}
}
}
]
},
"SendResponse": {
"type": "object",
"required": [
"ok",
"id",
"replayed",
"senderName",
"warnings",
"quota"
],
"properties": {
"ok": {
"const": true
},
"id": {
"description": "The service's id of this message in its log.",
"type": "string",
"minLength": 1
},
"messageId": {
"description": "The back end's id, when it gave one.",
"type": "string"
},
"replayed": {
"description": "true when this Idempotency-Key was already sent and no second mail went out.",
"type": "boolean"
},
"senderName": {
"description": "The name the mail left under.",
"type": "string"
},
"warnings": {
"description": "Known today: sender-name-replaced. A client ignores a warning it does not know.",
"type": "array",
"items": {
"type": "string"
}
},
"quota": {
"description": "What is left for a message of the kind just sent.",
"$ref": "#/$defs/Quota"
}
}
},
"StatusResponse": {
"type": "object",
"required": [
"ok",
"state",
"host",
"product",
"service",
"sender",
"limits",
"quota",
"kinds",
"token"
],
"properties": {
"ok": {
"const": true
},
"state": {
"$ref": "#/$defs/SiteState"
},
"host": {
"$ref": "#/$defs/Host"
},
"product": {
"$ref": "#/$defs/Product"
},
"service": {
"type": "object",
"required": [
"version",
"contract"
],
"properties": {
"name": {
"description": "The service's name, for a panel to show.",
"type": "string"
},
"version": {
"type": "string"
},
"contract": {
"type": "string",
"pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"
}
}
},
"sender": {
"type": "object",
"required": [
"address"
],
"properties": {
"address": {
"$ref": "#/$defs/Address"
}
}
},
"limits": {
"type": "object",
"required": [
"messagesPerHour",
"messagesPerDay",
"recipientsPerMessage",
"perRecipientPerDay",
"newRecipientsPerDay",
"maxBodyBytes",
"maxAttachmentBytes",
"maxAttachments"
],
"properties": {
"messagesPerHour": {
"type": "integer",
"minimum": 0
},
"messagesPerDay": {
"type": "integer",
"minimum": 0
},
"recipientsPerMessage": {
"type": "integer",
"minimum": 1
},
"perRecipientPerDay": {
"type": "integer",
"minimum": 0
},
"newRecipientsPerDay": {
"type": "integer",
"minimum": 0
},
"maxBodyBytes": {
"type": "integer",
"minimum": 0
},
"maxAttachmentBytes": {
"type": "integer",
"minimum": 0
},
"maxAttachments": {
"type": "integer",
"minimum": 0
},
"serverAddresses": {
"description": "Server addresses the site may send from at a time.",
"type": "integer",
"minimum": 1
},
"securityAlertsPerDay": {
"description": "Security alerts a day: a budget of their own, outside the hour and day limits.",
"type": "integer",
"minimum": 0
}
}
},
"quota": {
"$ref": "#/$defs/Quota"
},
"kinds": {
"type": "array",
"items": {
"type": "string"
}
},
"token": {
"type": "object",
"required": [
"issuedAt",
"rotateAfter"
],
"properties": {
"issuedAt": {
"type": "string",
"format": "date-time"
},
"rotateAfter": {
"type": "string",
"format": "date-time"
}
}
},
"senderName": {
"description": "The name the last mail left under, when there was one.",
"type": "string"
}
}
},
"RotateResponse": {
"type": "object",
"required": [
"ok",
"token",
"previousValidUntil"
],
"properties": {
"ok": {
"const": true
},
"token": {
"$ref": "#/$defs/Token"
},
"previousValidUntil": {
"type": "string",
"format": "date-time"
}
}
},
"RevokeResponse": {
"type": "object",
"required": [
"ok"
],
"properties": {
"ok": {
"const": true
}
}
},
"HealthResponse": {
"description": "No detail on purpose — also when it says no: the one answer that is not an Error.",
"type": "object",
"additionalProperties": false,
"required": [
"ok"
],
"properties": {
"ok": {
"type": "boolean"
}
}
},
"ErrorCode": {
"type": "string",
"enum": [
"invalid-request",
"invalid-token",
"reverify",
"site-pending",
"site-suspended",
"host-not-allowed",
"enrolment-closed",
"enrolment-in-progress",
"callback-failed",
"host-mismatch",
"browser-not-allowed",
"not-found",
"method-not-allowed",
"unsupported-media-type",
"idempotency-conflict",
"in-progress",
"already-rotated",
"too-large",
"too-many-recipients",
"attachment-refused",
"recipient-suppressed",
"rate-limited",
"quota-exceeded",
"backend-failed",
"unavailable",
"internal"
],
"description": "The codes the service answers with today. The list grows with minor versions; that is why Error.code is an open string."
},
"Error": {
"type": "object",
"required": [
"ok",
"code",
"message",
"retryable"
],
"properties": {
"ok": {
"const": false
},
"code": {
"description": "One of ErrorCode today. A client that meets a code it does not know acts on `retryable`.",
"type": "string",
"minLength": 1
},
"message": {
"description": "For a log or an administrator. English. Never shown to a visitor.",
"type": "string"
},
"retryable": {
"description": "true: the same request, with the same Idempotency-Key, may be sent again after a short wait.",
"type": "boolean"
},
"retryAfter": {
"description": "Seconds.",
"type": "integer",
"minimum": 0
},
"field": {
"description": "With invalid-request: the field at fault. With attachment-refused: which file, as attachments[n] (n from 0).",
"type": "string"
},
"limit": {
"description": "With quota-exceeded: hour, day, alerts, recipient, new-recipients or service. With too-large: request, body or attachments.",
"type": "string"
},
"reason": {
"description": "With callback-failed: unreachable, timeout, redirect, status or confirmation.",
"type": "string"
}
}
}
}
}
+1 -1
View File
@@ -1420,7 +1420,7 @@ export interface CookieSetting {
}[]
| null;
/**
* Cookies the site uses — shown on the cookie policy page (<CookieTable>). Fill it from a scan: ipal-consent-check → cookie-scan.
* Cookies the site uses — shown on the cookie policy page (<CookieTable>). Fill it from a scan: iapl-consent-check → cookie-scan.
*/
cookies?:
| {
+4 -4
View File
@@ -1,7 +1,7 @@
import { payloadTotp } from '@clocklimited/payload-2fa'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { ipalKit } from '../src/index.js'
import { iapl } from '../src/index.js'
import path from 'path'
import { buildConfig } from 'payload'
import sharp from 'sharp'
@@ -64,18 +64,18 @@ export default buildConfig({
await seed(payload)
},
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
i18n: i18nConfig,
consentLog: true,
// Cookie review + "Crawl site" (needs IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN and a running services/cookie-crawler).
// Cookie review + "Crawl site" (needs IAPL_COOKIE_SCAN_URL / IAPL_COOKIE_SCAN_TOKEN and a running services/cookie-crawler).
cookieScanner: { crawl: true },
forms: {},
seo: { collections: ['posts', 'pages'] },
stats: true,
// 2FA is enforced by default; the dev sandbox opts out so it boots without an authenticator.
// IPAL_DEV_2FA=1 turns it on (first-login setup and verify screens).
twoFactor: process.env.IPAL_DEV_2FA ? { issuer: 'ipal-kit dev', plugin: payloadTotp } : false,
twoFactor: process.env.IPAL_DEV_2FA ? { issuer: 'IAPL dev', plugin: payloadTotp } : false,
// Panel logo/icon from Site settings and the technology support credit.
whiteLabel: true,
}),
+1370 -2
View File
File diff suppressed because it is too large Load Diff
+10 -9
View File
@@ -1,8 +1,8 @@
# @intecion/ipal-kit documentation
All ipal-kit docs, the agent guide and the agent skills are written in English.
All IAPL docs, the agent guide and the agent skills are written in English.
**Main rule — the plugin helps, never limits:** ipal-kit is a plugin — it helps projects and never
**Main rule — the plugin helps, never limits:** IAPL is a plugin — it helps projects and never
limits them. Every module can be turned off on its own, every default can be overridden (the project
config wins), safe defaults have an option to relax them, and the plugin exports building blocks
(helpers, builders, hooks), not only finished features. Every module page has a "Turn off, override,
@@ -11,9 +11,9 @@ extend" section that describes the current code.
| Who you are | Read |
|---|---|
| **AI agent** working in a project | [AGENT.md](./agent/AGENT.md) — rules, structure, building sections, checks before "done" |
| **AI agent — skills** | [agent/skills/](./agent/skills) — 15 `ipal-*` skills for Antigravity/Claude Code, including `ipal-reference` (full map of the plugin and every export), `ipal-setup` (complete installation), `ipal-site` (a site from brief to report) and the check scripts (copied into the project: `pnpm exec ipal-skills`, AGENT.md §14) |
| **AI agent — skills** | [agent/skills/](./agent/skills) — 15 `iapl-*` skills for Antigravity/Claude Code, including `iapl-reference` (full map of the plugin and every export), `iapl-setup` (complete installation), `iapl-site` (a site from brief to report) and the check scripts (copied into the project: `pnpm exec iapl-skills`, AGENT.md §14) |
| **Developer** | [PROGRAMISTA.md](./dev/PROGRAMISTA.md) — installation, new project, env, deployment, upgrades, releasing the plugin, Gitea; deployment and health check: [deployment.md](./deployment.md) |
| **Person driving an AI agent** | [vibe.md](./dev/vibe.md) — autonomous mode (`/ipal-site`) and ready-made step-by-step prompts |
| **Person driving an AI agent** | [vibe.md](./dev/vibe.md) — autonomous mode (`/iapl-site`) and ready-made step-by-step prompts |
API details — one file per module:
@@ -24,15 +24,16 @@ API details — one file per module:
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
| Blocks, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
| Block library: ready sections, page templates | [block-library.md](./block-library.md) |
| Cookie consent, banner, settings window (in the bar / modal / large with cookie details) | [consent.md](./consent.md) |
| Cookie consent, banner, settings window (in the bar / modal / large with cookie details), Global Privacy Control | [consent.md](./consent.md) |
| The consent behaviour IAPL and IAWL share (record, categories, GPC, equal prominence, tests) | [consent-behaviour-spec.md](./consent-behaviour-spec.md) |
| Cookie scanner: review list of drafts, "Scan cookies", Open Cookie Database lookup (optional) | [cookie-scanner.md](./cookie-scanner.md) |
| Under construction — locks subpages behind a popup (developer tool) | [construction.md](./construction.md) |
| Routing, archives, redirects, Markdown, search | [content.md](./content.md) |
| Site frontend: `createContentHelpers` (`@/lib/content`), `createPageRoute`, `SiteProviders` | [frontend.md](./frontend.md) |
| New site in one command (`ipal-kit create`, `@intecion/ipal-kit/starter`) | [project-starter.md](./project-starter.md) |
| New site in one command (`iapl create`, `@intecion/ipal-kit/starter`) | [project-starter.md](./project-starter.md) |
| Deployment, production variables, health check | [deployment.md](./deployment.md) |
| Seeds: create-only, dry run, backup, production update guard | [seeding.md](./seeding.md) |
| Email SMTP / Graph | [email.md](./email.md) |
| E-mail: the mail service (default), SMTP, Graph (deprecated) | [email.md](./email.md) |
| Env validation | [env.md](./env.md) |
| Forms, useForm, honeypot | [forms.md](./forms.md) |
| GA4 + Meta Pixel through GTM (form events) | [gtm-meta-pixel.md](./gtm-meta-pixel.md) |
@@ -52,10 +53,10 @@ API details — one file per module:
| Stats in the admin panel (no cookies; visitor history with consent) | [stats.md](./stats.md) |
| Auto-slug | [slug.md](./slug.md) |
| Light / dark theme, switcher | [theme.md](./theme.md) |
| Design tokens (`--ipal-*`, `tokens.css`, `tailwind.css`, `ipal-tokens`, DESIGN.md) | [design-tokens.md](./design-tokens.md) |
| Design tokens (`--ipal-*`, `tokens.css`, `tailwind.css`, `iapl-tokens`, DESIGN.md) | [design-tokens.md](./design-tokens.md) |
| R2, `buildImagesConfig`, `MediaPreconnect`, `YouTubeEmbed` | [storage.md](./storage.md) |
| Turnstile | [turnstile.md](./turnstile.md) |
| ipal-doctor (the site against the team standard, `ipal-doctor.json`) | [doctor.md](./doctor.md) |
| iapl-doctor (the site against the team standard, `iapl-doctor.json`) | [doctor.md](./doctor.md) |
| Admin panel white-label | [white-label.md](./white-label.md) |
Maintenance rule: a module's API changes → update its file in the same commit. New working rules →
+363 -23
View File
@@ -7,12 +7,13 @@ predicates and ready access functions (collection-level and field-level).
## Config (payload.config.ts)
```ts
ipalKit({
iapl({
access: {
authCollection: 'users', // slug of your auth collection (required)
// defaultRole: 'user', // role of new accounts
// firstUserAdmin: true, // the account from "Create first user" → admin
// authAccess: { … }, // access of the injected auth collection (your keys win)
// staffCollections: ['partners'], // more auth collections whose accounts are staff
},
// globalOverrides: { … }, // access / admin / hooks / fields of the plugin's globals
})
@@ -22,8 +23,9 @@ ipalKit({
|---|---|---|
| `access.authCollection` | — (required) | the auth collection that gets the `roles` field |
| `access.defaultRole` | `'user'` | role of a new account when an admin did not set one |
| `access.firstUserAdmin` | `true` | the account from the "Create first user" screen (`…/first-register` on an empty collection) gets `['admin']`, even when the form picked `user`; `false` = it gets what was submitted |
| `access.firstUserAdmin` | `true` | the account from the "Create first user" screen (`…/first-register` on an empty collection) gets `['admin']`, even when the form picked `user`; `false` = it gets what was submitted — then mind the panel role, [Account rules](#account-rules-accounts) |
| `access.authAccess` | see the table below | `access` of the **injected** auth collection, merged over the default (your keys win) |
| `access.staffCollections` | `[]` | more auth collections whose accounts count as **staff**, besides the one the panel logs in with (`admin.user`); see "Who is staff" |
| `globalOverrides` | — | changes to the plugin's globals: an object merges `access` / `admin` key by key (your keys win) and appends `hooks` (yours run after the plugin's), other keys (label, fields, …) replace; a function `(global) => global` takes over the whole global |
The `roles` field (select hasMany, required, `saveToJWT`): readable without limits; only an admin
@@ -40,7 +42,7 @@ only checks that someone is logged in.
| Resource | Read | Write | How to change |
|---|---|---|---|
| auth collection **injected** by the plugin, with roles | admin: everyone; others: only themselves | `create` / `delete` / `unlock`: admin; `update`: admin or self | `access.authAccess`, or your own collection |
| auth collection **injected** by the plugin, with roles | admin: everyone; other accounts **of that collection**: only themselves (`adminOrSelfIn`) | `create` / `delete` / `unlock`: admin; `update`: admin or self | `access.authAccess`, or your own collection |
| Site settings, Cookie banner, Notifications | public | `editor+` | `globalOverrides` |
| Site integrations | admin | admin | `globalOverrides` |
| Forms | public (Emails tab only `editor+`) | `editor+` | `forms.formOverrides.access`, the Emails field in `formOverrides.fields` |
@@ -48,7 +50,7 @@ only checks that someone is logged in.
```ts
import { authenticated } from '@intecion/ipal-kit'
ipalKit({
iapl({
access: { authCollection: 'users', authAccess: { read: authenticated } }, // editors see the account list
globalOverrides: {
notifications: { access: { update: authenticated } }, // any logged-in account edits the texts
@@ -58,37 +60,116 @@ ipalKit({
```
The project's own auth collection keeps its own `access` — the plugin only adds the
`roles` field. Give it at least `update: adminOrSelf`, `delete: adminOnly`, `create: adminOnly`,
`roles` field. Give it at least `update: adminOrSelfIn('users')`, `delete: adminOnly`, `create: adminOnly`,
`unlock: adminOnly`: Payload's default lets any logged-in account change the email and password
of another account and unlock any account. A collection injected **without** `access` (no roles)
keeps Payload's default rules — without roles all accounts are equal.
> **Without `access` there is no `roles` field**, so `isAdmin` always returns `false`. The plugin's own
> staff features therefore check with `userMeetsRole(req, minimum)`: when the user's auth collection has no
> `roles` field, every logged-in account passes (as in Payload's default — without roles all accounts are
> equal). That keeps Site integrations, the settings globals, `/api/ipal/test-email`, stats, consent records
> and form submissions reachable. To narrow them without roles: `globalOverrides` for the globals,
> `forms.formSubmissionOverrides` for submissions, or add `access` to get roles.
## Who is staff
**Staff collections** are the auth collections whose accounts work in the panel:
- the one the admin panel logs in with (`admin.user`; Payload's default is the **first** auth collection in the
list — set `admin: { user: 'users' }` yourself as soon as the project has two);
- the one that carries the plugin's roles (`access.authCollection`);
- the ones named in `access.staffCollections`.
An account of **any other auth collection** — `customers`, `members`, a client zone — is a visitor to the
plugin. **Nothing in the plugin counts a role for it**, also when its own collection has a `roles` field with
the value `admin`: not `userMeetsRole`, not `isAdmin` / `isEditor` / `hasMinimumRole`, not `adminOnly`,
`adminOrEditor`, `requireRole`, `adminOrSelf`, `adminOrSelfIn` or the `…Field` variants, not the `roles` field
itself. The staff-collection check always comes first.
The plugin's own staff features — Site integrations, the settings globals, form submissions, consent records,
stats, the cookie scanner, `/api/ipal/test-email` — check with `userMeetsRole(req, minimum)`, in this order:
1. the account belongs to a staff collection;
2. with 2FA on: the account has set TOTP up and has entered the code in this session
([security.md](./security.md) → "What the second factor covers", "Setup required");
3. it holds at least the role `minimum` — **or** its collection has no `roles` field at all. Then every account
of that staff collection passes, as in Payload's default (without roles all accounts are equal).
What follows:
- **Without `access`** there is no `roles` field, so `isAdmin` always returns `false` and rule 3 keeps the
staff features reachable: every account of the panel collection is admin to the plugin. To narrow that
without roles: `globalOverrides` for the globals, `forms.formSubmissionOverrides` for submissions, or add
`access` to get roles.
- **A second staff collection** (e.g. `partners` who edit content): name it in
`access.staffCollections`. That is the one switch that makes its roles count. Without a `roles` field every
partner passes every staff check, admin ones included; to tell them apart add the field:
`fields: [buildRolesField('editor')]` in that collection. **2FA covers one collection** (`twoFactor.collectionSlug`,
by default the panel's): accounts of a further staff collection are staff with a password alone. iapl says
so in the log at start (`[iapl] 2FA covers "users" only…`); name such a collection only when that is acceptable.
- **Payload's own default** for a collection or global without `access` is "any logged-in account" — an account
of a visitor collection included. In a project with a second auth collection give every collection and global
explicit `access` (`adminOrEditor`, `requireRole(…)`, …).
- **A visitor collection that should reach one thing** (e.g. customers read their own form submissions):
do not make it staff. Write that one rule yourself — `forms.formSubmissionOverrides.access.read`,
`globalOverrides`, `collectionOverrides` of the module — and check `req.user.collection` in it.
- **A user object you build yourself** (Local API with `overrideAccess: false`, a custom auth strategy) must
carry `collection`: `{ ...doc, collection: 'users' }`. Payload's own strategies and `payload.auth()` set it. An
account without it is not staff.
> **Changed in 1.16.4.** Before, a role or the "no roles field" rule counted for an account
> of any auth collection: an account of a second auth collection passed staff checks — every one when its
> collection had no `roles` field, and the matching ones when it had its own `roles` field. A project with one
> auth collection sees no difference. A project that relied on a second collection being staff sets
> `access.staffCollections`.
## Predicates (front end / hooks / access)
```ts
import { isAdmin, isEditor, hasMinimumRole, userMeetsRole } from '@intecion/ipal-kit'
import { isAdmin, isEditor, hasMinimumRole, staffCollectionSlugs, userMeetsRole } from '@intecion/ipal-kit'
isAdmin(user) // admin?
isEditor(user) // editor or admin (hierarchy)
hasMinimumRole(user, 'editor') // at least editor
userMeetsRole(req, 'admin') // admin — or any logged-in user when the auth collection has no roles field
isAdmin(req.user, req.payload) // a staff account with the admin role
isEditor(req.user, req.payload) // editor or admin (hierarchy)
hasMinimumRole(req.user, 'editor', req.payload) // at least editor
userMeetsRole(req, 'admin') // the plugin's staff check: staff collection, second factor, role ("Who is staff")
staffCollectionSlugs(req.payload) // ['users', …]
```
They take a loosely typed user (like `req.user`) and read `roles` defensively.
They take a loosely typed user (like `req.user`) and read `roles` defensively. The last argument tells them
which collections are staff:
| Where you call it | Pass | Without it |
|---|---|---|
| access functions, hooks, endpoints (server, the config is loaded) | `req.payload` | works: the staff collections of the config `iapl` built in this process. With two different configs in one process, only collections that are staff in **both** count — pass `req.payload` to get that config's own answer |
| client components — import from **`@intecion/ipal-kit/client`** | the config from `useConfig()` (it has `admin.user`, the panel's login collection), or `{ staffCollections: ['users', …] }` | **always `false`** — the browser bundle has no config |
| Next middleware / `proxy.ts`, the edge runtime | `{ staffCollections: ['users'] }` | **always `false`** — the config is not loaded there |
```tsx
'use client'
import { isAdmin } from '@intecion/ipal-kit/client' // not '@intecion/ipal-kit'
import { useAuth, useConfig } from '@payloadcms/ui'
export function AdminOnlyHint() {
const { config } = useConfig()
const { user } = useAuth()
// a hint only — the server decides
return isAdmin(user, config) ? <p>…</p> : null
}
```
- **The import in a client component is `/client`** (`hasMinimumRole`, `isAdmin`, `isEditor`, the type `Role`). The main
entry reaches `server-only` modules: with `next build --webpack` it fails with `'server-only' cannot be imported from
a Client Component module` (Turbopack builds it, but the import does not belong there either).
In 1.16.4–1.16.6 `/client` does not have them — upgrade.
- **On the server** (config, hooks, access functions, endpoints, server components, `proxy.ts`) import from
`@intecion/ipal-kit`: `/client` is a `'use client'` entry, a server component that calls a function from it fails.
- `useConfig()` carries `admin.user` only (Payload strips `config.custom` from the client config). Accounts of
`access.staffCollections` need the list: `isAdmin(user, { staffCollections: ['users', 'partners'] })`.
They fail closed: where the staff collections are not known, nobody is staff, and an account without
`collection` is nobody. `isAdmin` and the others do **not** check the second factor; `userMeetsRole` and every
`access` function in the config do.
## Ready access functions
### Collection-level (return boolean | Where)
```ts
import { adminOnly, adminOrEditor, adminOrSelf, requireRole, authenticated } from '@intecion/ipal-kit'
import { adminOnly, adminOrEditor, adminOrSelf, adminOrSelfIn, readPublished, requireRole, authenticated } from '@intecion/ipal-kit'
export const Articles = {
slug: 'articles',
@@ -101,13 +182,28 @@ export const Articles = {
// ...
}
// Users: everyone sees themselves, an admin sees everyone
access: { read: adminOrSelf }
// Users: everyone sees themselves, an admin sees everyone.
// adminOrSelfIn(slug): "self" = an account of THAT collection. Use it for an auth collection whenever
// the project has more than one: adminOrSelf only compares ids, and with numeric ids (Postgres, SQLite)
// customer no. 5 would match staff account no. 5.
access: { read: adminOrSelfIn('users') }
access: { read: adminOrSelf } // fine with a single auth collection
// any minimum threshold
access: { update: requireRole('editor') }
// a collection with drafts: editors (or the role you name) read everything; visitors, plain `user` accounts and a
// session that still owes its second factor read published documents only — by id, in lists, with ?draft=true and
// over GraphQL. Payload's open `read: () => true` answers ?draft=true with the draft itself (1.17.1).
access: { read: readPublished(), readVersions: readPublished() }
access: { read: readPublished('admin') }
```
A role name the plugin does not know (`requireRole('Admin')`, `readPublished('superadmin')`) throws where the rule
is written; `hasMinimumRole` / `userMeetsRole` answer `false` for it (before 1.17.1 every staff account met it).
`readPublished` with `?draft=true` on a page whose newest version is a draft answers a visitor `404` (Payload applies
the rule to that version), never the draft.
### Field-level (return boolean)
```ts
@@ -137,16 +233,260 @@ injectRoles(config, { authCollection: 'members' }) // add the field to a
applyGlobalOverrides(globals, { notifications: { … } }) // the same logic as the globalOverrides option
```
Types: `AccessOption`, `Role`, `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug`.
Types: `AccessOption`, `Role`, `GlobalOverride`, `GlobalOverrides`, `IaplGlobalSlug`.
## Account rules (`accounts`)
Rules for the accounts of the staff collection. All on by default; each has its own switch, and
`iapl({ accounts: false })` turns them all off.
```ts
iapl({
access: { authCollection: 'users' },
// accounts: { panelRole: 'user' }, // every account may open the panel (as before)
// accounts: { adminOnlyCreate: false }, // Payload's default `create` on your own staff collection
// accounts: { adminOnlyWrite: false }, // Payload's default `update` / `delete` / `unlock` there, roles field left alone
// accounts: { staffOnlyRead: false }, // Payload's default `read` there
// accounts: { firstUserRoute: 'all' }, // Payload's first-user route for every empty auth collection
// accounts: { firstUserRoute: ['users', 'partners'] },
// accounts: { password: { minLength: 16 } }, // or password: false
// accounts: false, // none of the rules
})
```
### Who may open the panel (`accounts.panelRole`, default `'editor'`)
The lowest role, `user`, is what a new account gets (`access.defaultRole`) and has no business in the panel. The
panel opens for `editor` and above: it is Payload's `access.admin` on the collection that carries the roles. An
account that holds only `user` (or no role) logs in and sees Payload's "Unauthorized" screen. **The API is not
touched** — such an account still gets over REST / GraphQL what its role allows. The rule looks at the role, not
at the second factor, so the 2FA screens stay reachable.
- **What an existing site sees on the first start:** the log line `[iapl] N account(s) of "users" are below the
role "editor" and cannot open the admin panel` — give those people `editor`, or set `panelRole: 'user'`. When
**no** account has the role it is an error (`NOBODY can open the admin panel`): give one account the role with
a script (`payload.update`, Local API) or set `accounts: { panelRole: false }` and redeploy.
- `'admin'` = admins only; `'user'` or `false` = everyone, as before. Needs `access` (the roles). Your own
`access.admin` on the collection, or `access.authAccess.admin`, wins. Building blocks: `panelAccess(role)`,
`applyPanelRole`, `resolvePanelRole`, `countBelowPanelRole`, `DEFAULT_PANEL_ROLE`.
- **Check:** log in to `/admin` as an account with the role `user` → "Unauthorized"; `GET /api/access` for it →
`canAccessAdmin: false`; `GET /api/users/me` still answers.
### Nobody creates an account for themselves, or takes one over (`accounts.adminOnlyCreate`, `accounts.adminOnlyWrite`, `accounts.staffOnlyRead`, `accounts.firstUserRoute`)
By default only the first account of a site can be registered by a visitor, and it becomes admin
(`access.firstUserAdmin`); every other account is made by an admin, and an account is changed by an admin or by
its owner.
Payload's default for a collection without access rules is "any logged-in user" for `create`, `read`, `update`,
`delete` and `unlock` — an account of **any** auth collection. On a project's own staff collection a visitor
account (`customers`) could therefore create a staff account, `PATCH` a staff account's password and roles,
list the staff accounts, and lift the lock after failed logins.
| | Before | Now (default) |
|---|---|---|
| Anonymous `POST /api/users`, GraphQL `createUser` | refused | refused |
| The first account: `POST /api/users/first-register` on an empty collection | 200, role `admin` | the same |
| A signed-in editor or plain user creates an account in the plugin's injected collection | refused | refused |
| …in **the project's own** staff collection that has no `create` rule | **allowed** (Payload's default) | refused — an admin, fully signed in |
| A visitor account (`customers`) changes or deletes an account of the project's own staff collection that has no `update` / `delete` rule | **allowed** (Payload's default) | refused |
| A visitor account lists the accounts of such a collection, or unlocks one | **allowed** (Payload's default) | refused |
| An account of such a collection changes its **own** `roles` (the field has no access of its own) | **allowed** | refused — with the plugin's roles only an admin changes roles |
| `POST /api/<slug>/first-register` on another empty auth collection (`members`) | **200** | 403 |
| …on an empty **second staff collection** (`access.staffCollections`) | **200, and that account was staff** | 403 — an admin of the panel's collection creates its first account |
| A collection that allows sign-up (`customers` with `create: () => true`) | allowed | allowed, its first-user route too |
**Which rule a staff collection gets** (the panel's login collection, `access.authCollection`,
`access.staffCollections`) — only for an operation it has **no** rule for; a rule you wrote always stays:
| The collection | `create`, `delete`, `unlock` | `update` | the `roles` field (when it has no `access.update`) | `read`, `readVersions` |
|---|---|---|---|---|
| carries **the plugin's roles**: it is `access.authCollection`, or has a `roles` select **with `hasMany`** whose values are all `user` / `editor` / `admin` (`hasPluginRoles`), **or one whose accounts can hold `editor` or `admin`**, whatever else its `roles` field offers (`canHoldStaffRole`, below) | an admin (`staffCreateAccess`) | an admin, or the account itself (`staffUpdateAccess(slug)`) | only an admin changes it (`rolesByAdminOnly`) | a staff account (`staffReadAccess`) |
| has **roles of its own that hold neither `editor` nor `admin`** (`superadmin`, `writer`, …) or no `roles` field — the plugin cannot tell who its admins are | an account of that same collection, or a plugin admin of another staff collection (`sameStaffCollectionAccess(slug)`) | the same | an account never changes its **own** (`rolesNotOwn(slug)`) | a staff account |
Always "fully signed in": a session that still owes its second factor passes none of them.
**A `roles` field that can hold `editor` or `admin`.** The plugin's checks go by the **value on the account**
(`isAdmin`, `isEditor`): an account of a staff collection whose `roles` — an **array** — holds `admin` is a plugin
admin, one that holds `editor` edits the site's settings, whatever else the field offers. So wherever an account
of the collection **can** hold one of the two, the collection gets the admin rules (`canHoldStaffRole`):
| The collection's `roles` field | Rules |
|---|---|
| a select **with `hasMany`** and `editor` or `admin` among its values — `user, editor, admin, boss`; `viewer, editor` | the admin rules (first row above) |
| a field that holds a list whose values cannot be listed — text with `hasMany`, json, a relationship with `hasMany` (to documents whose ids are text, the ids are the roles), a select without options, a type the plugin does not know: anything can be written there | the admin rules |
| a select with `hasMany` whose values are all your own and hold neither — `lead, member` | "an account of that same collection" (second row) |
| a field that holds **one** value — a select, text or relationship without `hasMany`, a radio, a number (`rolesAreAList` is false) | second row. The plugin counts roles only from an array: an account whose `roles` is the single value `admin` is **not** a plugin admin, so there is nothing of the plugin's to protect and the collection's accounts keep managing each other. If your own code gives rights by that value, write the collection's own rules |
| no `roles` field | second row; every account of it is an admin to the plugin (below) |
Otherwise any account of such a collection could hand the value out: create an `admin` and be in Site
integrations and every other staff collection, or create an `editor` and change the site's settings. (Until this
change these collections got the second row, and an account with the lowest role could do exactly that.)
**What it means for your accounts:** a role the plugin does not know (`boss`, `viewer`) carries no rights of the
plugin's — such an account no longer creates, deletes or unlocks accounts there, changes another account or
anybody's roles. Give it what it needs with rules of your own (`access.create` / `update` / `delete`, field
access on `roles`), which win as always. In a collection where nobody can be an `admin` (`viewer, editor`) the
accounts are managed by an admin of another staff collection — the panel's.
**A rule of your own replaces the protection for that operation.** The plugin fills only what you left open: with
your own `create: ({ req }) => Boolean(req.user)` any account still creates an `admin` there; with your own
`access.update: () => true` on the `roles` field an account still raises itself. And the plugin sees the field's
declared values, not your code: a value that a hook of yours puts into `roles` (an `afterRead` that returns
`['admin']` from a checkbox, a virtual field) is not seen — such a collection is judged by its declared field.
**If no staff account holds `admin` at all**, nobody can create, delete or unlock accounts in such a collection.
The start log says so: `[iapl] No staff account holds the role "admin", so NOBODY can create, delete or unlock
accounts in "…"`. Way out: give one account the role with a script (`payload.update`, Local API), or write the
collection's own rules. The check asks each staff collection in the way its field allows (a count for a select,
reading the accounts for text / json / relationship fields, up to 1000 of them); where it cannot check a
collection it says `[iapl] Could not check whether an account of "…" holds the role "admin"` instead and claims
nothing.
**Roles of your own — what the plugin does and does not hold.** It cannot rank `superadmin` against `writer`,
so inside such a collection it enforces one thing only: an account does not change its own roles. Everything
else that was allowed inside the collection stays allowed — **every account of it may still create an account
with any role, and change or delete another account**. That is a hole only you can close: write the
collection's `create` / `update` / `delete` rules and the field access of its `roles` field from your roles.
`iapl-doctor --url` names such a collection (`staff-own-roles`, warning). What the plugin closes for you is the
door for accounts of **other** collections.
**A staff collection without a `roles` field:** every account of it is an admin to the plugin (unchanged), so
it may also manage the accounts of the other staff collections. Give it the plugin's roles
(`buildRolesField`), or write its rules.
**A staff collection that a plugin listed after iapl adds** gets the same rules, the password rule and the
first-user endpoint when the config goes live — at start and on every dev reload. The log says exactly what was
put: `[iapl] "late-staff" was added after iapl: put on it — access rules for create, update, delete, unlock,
read, readVersions, roles; the password rule; the first-user endpoint.` One difference from a collection of your
own config: by then Payload has sanitized the collection and filled every missing rule with its default, and
that default cannot be told from a rule somebody wrote (a production build renames every function). So the
plugin does not guess: **its rule is put in front of whatever rule is there, and both must allow**
(`bothAllow`). With Payload's default behind it the result is the plugin's rule; a rule of the collection's own
is kept and can only narrow it. To keep a late collection's rules exactly as they are — an open `create`, a
wider `read` — say so on the collection: `custom: { ipal: { accountRules: false } }` (the password rule and the
first-user endpoint still apply), or list that plugin before iapl.
**A collection of your own config that becomes staff later** — it is in the config, you did not name it as staff,
and a plugin listed after iapl sets `admin.user` to it — is handled at the same moment, with one difference:
the plugin saw it at config time and wrote down which operations had a rule of yours (the marker's `own`). **Those
rules stay exactly as written; an operation that had no rule gets the plugin's** — the same result as for a
collection named in `access.staffCollections`, and its `roles` field is guarded where the plugin's `update` rule
is the one in force. The log: `[iapl] "people" became a staff collection after iapl ran: put on it — access
rules for update, delete, unlock, read, readVersions, roles; the password rule. Its own rules for create are kept
as written.` Without rules of its own such a collection ran on Payload's defaults before (any signed-in account,
a customer included, created and changed panel accounts). Simpler and clearer: name the collection in
`access.staffCollections`, or list that plugin before iapl. Verify: sign in as an account of a non-staff
collection and `POST /api/<slug>` — 403 unless your own `create` rule lets it through.
**A copy of a staff collection** — a later plugin that spreads one into a new slug (`{ ...staff, slug: 'copy' }`),
or a new collection that reuses a staff collection's `access` object — brings along rules the plugin wrote for
the ORIGINAL: "an account of `staff`", "the account itself" = one of the original's. The plugin sees them by a
mark it puts on its own functions (`staffRuleOf(rule)` → `{ slug, self }`; the mark counts only on the very
function it was made for, so a wrapper of yours around a plugin rule is your rule). What it does is one thing,
in every case:
> **The plugin's rule for THIS collection goes in front of the rule that is there, and both must allow.**
> Nothing is replaced and nothing is rewritten.
| The copy | Where the plugin's rule goes in front |
|---|---|
| named in `access.staffCollections` | of every rule — as on any late staff collection |
| not named as staff, or with `custom: { ipal: { accountRules: false } }` | only of the rules the plugin wrote for the original; your own rules there stay as they are |
| its `roles` field | guarded on every copy (the plugin's roles: only an admin changes them; others: never one's own) unless the field has an `access.update` of its own — then the guard goes in front only of a rule the plugin wrote for the original |
So a copy is never opened wider than its rules were before, and never wider than the plugin's rule — whatever
role values it has, whichever operation it uses a copied rule for, however it wraps it. The original's account
with the same id is not "the account itself" in the copy.
**The cost, and the one line that pays it:** a copied rule that says "an admin, or the account itself" still
means the ORIGINAL's accounts, so in the copy only an admin passes it — the copy's own accounts cannot edit
themselves until the copy says who may:
```ts
import { adminOrSelfIn } from '@intecion/ipal-kit'
// in the plugin that makes the copy:
{ ...staff, slug: 'copy', access: { ...staff.access, update: adminOrSelfIn('copy') } }
```
A rule you write there is not marked, so on a staff copy it is combined with the plugin's rule for `copy`
("an admin, or the account itself" of the copy) and works. The password rule is on a copy once
(`isPasswordRuleHook`). The marker `custom.ipalAccounts` (`{ slug, staff, own? }`, type `AccountsMarker`) records which
collection the plugin has handled, whether as staff, and — for a collection that was not staff at config time —
which operations had a rule of the project's then (`own`): a copy carries the original's marker and is handled under
its own slug; in `next dev` a collection named as staff in an edit is handled on the reload. A marker for the
collection's own slug means "handled" — only your own config can write one, like `accountRules: false`.
**A slug in `access.staffCollections` or `access.authCollection` that is not an auth collection of the config:**
Payload does not start. The log names the slug and the auth collections it knows. The process stays up, but
every Payload call fails — `/api/health` answers 503, `/api/*` and the panel 500; a page that needs no Payload
call may still answer. With a health check ([deployment.md](./deployment.md) §4.4) Coolify keeps the old
container serving, so a wrong slug never goes live (`unknownStaffCollections`).
- `adminOnlyCreate: false` = Payload's default `create`; `adminOnlyWrite: false` = Payload's default `update`,
`delete` and `unlock`, and the `roles` field is left alone; `staffOnlyRead: false` = Payload's default `read`.
The rules are put on the collections **before** the 2FA package wraps them, so they hold with 2FA on and off.
- `read` = "a fully signed-in account of a staff collection": staff sees staff (the panel needs it for
relationship fields and the account list), a visitor account sees nothing. The injected collection keeps its
stricter "admin or self". **A front end that shows staff accounts to logged-in visitors** needs its own `read`
rule on that collection (a rule you wrote wins), or `staffOnlyRead: false`.
- `firstUserRoute`: `'panel'` (default) = the collection the panel logs in with; a list of slugs = those;
`'all'` = Payload's behaviour. A collection whose own `create` rule lets an anonymous request through keeps
its route. The plugin puts its own `POST /first-register` endpoint in front of Payload's on every auth
collection (`buildFirstUserEndpoint`): it refuses, or hands the request to Payload's handler. It does not read
the request path, so the spelling of the URL (`/First-Register`) changes nothing. A collection with
`endpoints: false` is left alone.
- **A fresh site:** whoever opens the panel first becomes the admin — create the first account right after the
first deploy.
- **`access.firstUserAdmin: false`** gives the first account the default role. If that role is below the panel
role, nobody could open the panel on a fresh site: with the default panel role the plugin then does **not**
apply it and says so at start; with `accounts.panelRole` set by you the config is refused at start. Set
`access.defaultRole: 'editor'`, or `accounts: { panelRole: false }`.
- **What an existing site sees:** nothing, unless its own staff collection relied on Payload's defaults
(non-admins creating accounts in a collection with the plugin's roles; accounts of another collection writing
to it) — then write the rule you want, or set `adminOnlyCreate: false` / `adminOnlyWrite: false`.
- `iapl-doctor --url`: `open-signup` (info) lists auth collections with open sign-up; `staff-own-roles` (warning)
a staff collection with role values of its own on the default rules; `staff-accounts-open`
(error) names a staff collection an account of another collection may create in, read (a warning), update, delete from or unlock
(the rules are off, or your own rule is wider).
- Building blocks: `staffCreateAccess`, `staffUpdateAccess`, `staffReadAccess`, `sameStaffCollectionAccess`,
`rolesByAdminOnly`, `rolesNotOwn`, `bothAllow`, `hasPluginRoles`, `applyStaffAccountAccess`, `adoptLateAuthCollections`,
`unknownStaffCollections`, `buildFirstUserEndpoint`, `applyFirstUserRoute`, `openSignUpCollections`,
`staffCollectionsOpenToOthers`, `staffCollectionsOnOwnRoles`.
- **Check:** `curl -X POST <site>/api/members/first-register -H 'content-type: application/json' -d
'{"email":"x@example.com","password":"a-long-password-1"}'` → `403`, also as `/First-Register`; the same for
`/api/users` → `403`. Logged in as a visitor account: `PATCH /api/users/<id>` and `GET /api/users` → `403`. As a
non-admin of a staff collection: `PATCH` your own account with `roles` → the roles do not change.
### Passwords (`accounts.password`, default 12 characters)
When a password is **set** on a staff collection — a new account, the first-user screen, a change, a reset by
e-mail; in the panel, over the API and through the Local API — it must have at least 12 characters and must not
be the account's own e-mail address (Payload's own rule is 3 characters). **Existing passwords are never
checked:** an account with a shorter one keeps logging in, and meets the rule the next time its password is
changed. The message is in the panel's language, English or Polish ("The password must have at least 12
characters."; texts `passwordTooShort`, `passwordIsEmail` in `i18n.translations.<lang>.ipal`).
- `password: { minLength: 16 }`; `password: false` = Payload's rule. Visitor collections are not touched.
- Checked against the account's address also where the request carries none: a change by id, a reset by e-mail
(the account is found by its token), a bulk update (every account it matches). A password that is not text
(a number, a list) is refused with the same message.
- No breached-password lookup (it would send part of a hash of every new password to an outside service);
build one on `checkPassword` / `buildPasswordRuleHook` if a project needs it.
- A script or seed that creates a staff account with a shorter password now fails with a validation error.
- Building blocks: `checkPassword`, `buildPasswordRuleHook`, `applyPasswordRule`, `resolvePasswordRule`,
`DEFAULT_PASSWORD_MIN_LENGTH`.
- **Check:** create an account with an 11-character password → "The password must have at least 12 characters.".
## Turn off, override, extend
- **Account rules:** `accounts: false`, or one by one — `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`,
`staffOnlyRead`, `firstUserRoute`, `password` (above).
- **Turn off:** leave out `access` — no `roles` field, the auth collection keeps Payload's rules
(or yours). `access.firstUserAdmin: false` stops giving admin to the first account.
- **Override:** `access.authAccess` (injected collection), your own auth collection (wins whole),
- **Override:** `access.staffCollections` (who is staff), `access.authAccess` (injected collection), your own auth collection (wins whole),
`globalOverrides` (globals), `forms.formOverrides` / `formSubmissionOverrides` (forms),
`defaultRole`. The role hierarchy (`ROLE_HIERARCHY`) is fixed.
- **Extend:** `requireRole` / `requireRoleField`, predicates, `buildRolesField`, `injectRoles`,
- **Extend:** `requireRole` / `requireRoleField`, `adminOrSelfIn`, predicates (`userMeetsRole`, `staffCollectionSlugs`), `buildRolesField`, `injectRoles`,
`applyGlobalOverrides` in your own collections and globals.
- **Check:** log in with a `user` account → `PATCH /api/globals/site-settings` = 403,
`DELETE /api/users/<admin id>` = 403; the account from "Create first user" has the `admin` role.
+4 -1
View File
@@ -172,6 +172,9 @@ The provider re-applies and syncs on the client anyway. This only removes the fl
### State and attributes (`A11yState`)
Cookie `a11y-prefs` (`A11Y_COOKIE`, JSON, `path=/`, `max-age` 1 year, `samesite=lax`).
It is written only when the visitor changes a setting, with no consent check: a preference the visitor
chose, no tracking (the same reasoning as the theme choice, theme.md). List it as **necessary** in the
cookie list — the scanner does not declare it, add it with `declarations` (cookie-scanner.md).
Widget texts: `texts` prop wins, otherwise `A11Y_DEFAULT_TEXTS[locale]` (`en`, `pl`; prop `locale`,
incl. `texts.on` / `texts.off` for the switches).
The helpers `A11Y_COOKIE`, `A11Y_DEFAULT`, `parseA11y`, `serializeA11y`, `a11yAttributes`
@@ -222,7 +225,7 @@ sell the client "we have a widget = we are WCAG compliant". See [dev/PROGRAMISTA
## Turn off, override, extend
- **Turn off:** the module is opt-in — without `AccessibilityProvider` / `AccessibilityWidget` nothing happens
(no option in `ipalKit`, no fields in the panel).
(no option in `iapl`, no fields in the panel).
- **Override:** the widget's `classNames` and `texts`; the whole look of the effects is project CSS.
- **Extend:** your own UI on `useAccessibility()` (`state`, `set`, `reset`); SSR helpers
`parseA11y` / `a11yAttributes` / `serializeA11y` / `A11Y_DEFAULT`. The option set (`A11yState`) currently
+479 -196
View File
File diff suppressed because it is too large Load Diff
+136 -46
View File
@@ -2,12 +2,12 @@
<!-- Generated by scripts/reference-index.mjs from reference/ — do not edit by hand (pnpm reference:index). -->
The reference site is one complete client site on ipal-kit 1.15.3 ("Example Studio", made up) that uses
The reference site is one complete client site on IAPL 1.17.1 ("Example Studio", made up) that uses
every convention in AGENT.md. It lives in the plugin repo (`reference/`, not in the npm package). Copy the
PATTERN of the file you need; change only the project's content. Files up to
40 lines are below in full; open the rest in the repo at the tag of your plugin version:
`https://git.intecion.net/IntecionSoftware/ipal-kit/src/tag/v<version>/reference/<path>`.
If this index and AGENT.md disagree, report it with ipal-plugin-gap — it is a plugin bug.
If this index and AGENT.md disagree, report it with iapl-plugin-gap — it is a plugin bug.
## Project files
@@ -24,12 +24,12 @@ Rules: AGENT.md §13, §0a.
| `DESIGN.md` | the human source of the look, matching src/design/tokens.ts |
| `README.md` | how to run the reference site and what is where |
| `docs/DEPLOY.md` | the Coolify runbook: local check, app settings, MongoDB resource, env, targeted seeds, DNS, rollback |
| `ipal-doctor.json` | the production domain and launch state for ipal-doctor (below) |
| `iapl-doctor.json` | the production domain and launch state for iapl-doctor (below) |
| `next.config.ts` | security headers, enforced CSP, admin CSP, upload headers, images, no X-Powered-By |
| `package.json` | scripts (build, start, seed, tokens, generate), pinned Payload versions and overrides |
| `playwright.config.ts` | smoke tests against the built, seeded site (below) |
| `postcss.config.mjs` | Tailwind 4 through PostCSS (below) |
| `starter.manifest.json` | what `ipal-kit create` keeps, drops and turns into placeholders |
| `starter.manifest.json` | what `iapl create` keeps, drops and turns into placeholders |
| `tsconfig.json` | paths @/ and @payload-config, .agents excluded (below) |
### `.gitignore`
@@ -58,7 +58,7 @@ legacy-peer-deps=true
22
```
### `ipal-doctor.json`
### `iapl-doctor.json`
```json
{
@@ -93,7 +93,10 @@ try {
}
/**
* Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts.
* Smoke tests against a built, seeded site: pnpm seed && pnpm build.
* The 2FA verify limit (5 attempts per account in 10 minutes) is stored in the database; the global setup resets the
* test admins and clears their counts before every run (e2e/global-setup.ts; E2E_SKIP_ADMIN_SETUP=1 for a run that
* needs an EMPTY database, the fresh-site spec).
* E2E_BASE_URL picks the port (default 3100). Playwright starts its own server there and fails when the port is
* taken, so another project's dev server is never tested by mistake; E2E_REUSE_SERVER=1 uses a server you started.
*/
@@ -101,6 +104,8 @@ const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:3100'
export default defineConfig({
forbidOnly: !!process.env.CI,
// makes every run independent of the one before: test admins reset, stored 2FA attempt counts cleared
globalSetup: './e2e/global-setup.ts',
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
reporter: process.env.CI ? 'line' : 'list',
retries: process.env.CI ? 1 : 0,
@@ -108,7 +113,9 @@ export default defineConfig({
use: { baseURL, trace: 'retain-on-failure' },
webServer: {
command: 'pnpm start',
env: { PORT: new URL(baseURL).port || '3000' },
// E2E_MAIL_RELAY_URL: the mail service's stand-in that e2e/mail-relay.spec.ts starts (nothing listens there otherwise,
// and the other specs send through the SMTP sink, so the site never calls it)
env: { E2E_MAIL_RELAY_URL: `http://127.0.0.1:${process.env.E2E_RELAY_PORT ?? 2527}/mail`, PORT: new URL(baseURL).port || '3000' },
reuseExistingServer: process.env.E2E_REUSE_SERVER === '1',
url: `${baseURL}/api/health`,
},
@@ -153,7 +160,7 @@ export default { plugins: { '@tailwindcss/postcss': {} } }
## Configuration
Rules: AGENT.md §3, ipal-setup stage 3.
Rules: AGENT.md §3, iapl-setup stage 3.
| File | What it shows |
|---|---|
@@ -161,7 +168,7 @@ Rules: AGENT.md §3, ipal-setup stage 3.
| `src/db.ts` | the database adapter, alone in one file (MongoDB) (below) |
| `src/i18n.config.ts` | the ONLY source of languages (below) |
| `src/instrumentation.ts` | env validation at startup (assertEnv, database name rule) (below) |
| `src/payload.config.ts` | ipalKit with every module the site uses, R2, mail, 2FA, white-label |
| `src/payload.config.ts` | iapl with every module the site uses, R2, mail, 2FA, white-label |
| `src/proxy.ts` | the locale proxy with Markdown negotiation (not middleware.ts) (below) |
### `src/content.config.ts`
@@ -215,21 +222,21 @@ export type Locale = (typeof i18nConfig.locales)[number]['code']
### `src/instrumentation.ts`
```ts
import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env'
import { assertEnv, iaplEnvRules } from '@intecion/ipal-kit/env'
export function register() {
if (process.env.NEXT_RUNTIME !== 'nodejs') {return}
// storage: R2 is required in production. ALLOW_LOCAL_MEDIA=1 lets a production build run on local disk for
// local checks and CI only — never set it in Coolify.
// @starter:if crawl
// cookieCrawl: IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN in production (cookieScanner.crawl, the shared service).
// cookieCrawl: IAPL_COOKIE_SCAN_URL / IAPL_COOKIE_SCAN_TOKEN in production (cookieScanner.crawl, the shared service).
// @starter:endif
// databaseName: DATABASE_URI must name example-studiopl_dev / example-studiopl_prod (databaseNamesFor).
// R2_PUBLIC_URL optional: media are served through the app by default (storage.md, env.md).
assertEnv(
ipalEnvRules({
iaplEnvRules({
// @starter:if crawl
cookieCrawl: true, // IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN in production — the shared cookie-crawler service
cookieCrawl: true, // IAPL_COOKIE_SCAN_URL / IAPL_COOKIE_SCAN_TOKEN in production — the shared cookie-crawler service
// @starter:endif
databaseName: { domain: 'example-studio.pl' },
// @starter:if graph
@@ -258,12 +265,12 @@ import { i18nConfig } from '@/i18n.config'
export const proxy = createProxy(i18nConfig, { markdown: true, NextResponse })
// Inline LITERAL — Next reads the matcher statically (importing DEFAULT_PROXY_MATCHER breaks /admin)
export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }
export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] }
```
## Collections and globals
Rules: AGENT.md §5, ipal-nav, ipal-collection.
Rules: AGENT.md §5, iapl-nav, iapl-collection.
| File | What it shows |
|---|---|
@@ -290,7 +297,7 @@ import { entryFields } from './entryFields'
const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath })
/** The project's own archive collection (skill ipal-collection) — the library has no case-study type. */
/** The project's own archive collection (skill iapl-collection) — the library has no case-study type. */
export const CaseStudies: CollectionConfig = {
slug: 'caseStudies',
admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' },
@@ -477,7 +484,7 @@ import type { GlobalConfig } from 'payload'
import { buildGlobalRevalidateHook, buildLinkField, rowLabel } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'
/** ipal-nav: link columns and a note. Legal links come from System pages (getSystemLinks), not from here. */
/** iapl-nav: link columns and a note. Legal links come from System pages (getSystemLinks), not from here. */
export const Footer: GlobalConfig = {
slug: 'footer',
access: { read: () => true },
@@ -513,7 +520,7 @@ import type { GlobalConfig } from 'payload'
import { buildGlobalRevalidateHook, buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'
/** ipal-nav: menu with one submenu level, a CTA button, the mobile menu label. Logo comes from Site settings. */
/** iapl-nav: menu with one submenu level, a CTA button, the mobile menu label. Logo comes from Site settings. */
export const Header: GlobalConfig = {
slug: 'header',
access: { read: () => true },
@@ -636,7 +643,7 @@ Rules: docs/design-tokens.md.
| File | What it shows |
|---|---|
| `src/app/(frontend)/[locale]/design/page.tsx` | the design-token styleguide page (noindex) (below) |
| `src/components/design/TokenPanel.tsx` | one styleguide panel built from IPAL_TOKENS |
| `src/components/design/TokenPanel.tsx` | one styleguide panel built from IAPL_TOKENS |
| `src/design/tokens.css` | GENERATED by `pnpm tokens` from tokens.ts — never edited by hand (below) |
| `src/design/tokens.ts` | the brand: the ONLY file edited to rebrand the site (below) |
@@ -658,7 +665,7 @@ export default function DesignPage() {
return (
<Container className="grid gap-10 py-section">
<header className="grid gap-stack">
<p className="text-sm uppercase tracking-heading text-fg-muted">ipal-kit</p>
<p className="text-sm uppercase tracking-heading text-fg-muted">IAPL</p>
<h1 className="font-heading text-h1 leading-heading text-fg-strong">Design tokens</h1>
<p className="max-w-measure text-lead text-fg-muted">
src/design/tokens.ts → pnpm tokens → src/design/tokens.css. The panels set data-theme=&quot;light&quot; and data-theme=&quot;dark&quot;
@@ -681,8 +688,8 @@ export const generateStaticParams = () => i18nConfig.locales.map(({ code }) => (
```css
/*
* GENERATED by `ipal-tokens` from src/design/tokens.ts — do not edit; change src/design/tokens.ts and run
* `pnpm exec ipal-tokens`. Import it in styles.css after @intecion/ipal-kit/tokens.css (and tailwind.css).
* GENERATED by `iapl-tokens` from src/design/tokens.ts — do not edit; change src/design/tokens.ts and run
* `pnpm exec iapl-tokens`. Import it in styles.css after @intecion/ipal-kit/tokens.css (and tailwind.css).
*/
:root {
@@ -770,7 +777,7 @@ import type { Locale } from '@/i18n.config'
import { getCachedPayload } from './content'
/** Cached getters for the project's own globals — the layout passes them down as props (ipal-nav). */
/** Cached getters for the project's own globals — the layout passes them down as props (iapl-nav). */
export const getHeader = cache(async (locale: string) => (await getCachedPayload()).findGlobal({ slug: 'header', depth: 1, locale: locale as Locale }))
export const getFooter = cache(async (locale: string) => (await getCachedPayload()).findGlobal({ slug: 'footer', depth: 1, locale: locale as Locale }))
export const getCompany = cache(async (locale: string) => (await getCachedPayload()).findGlobal({ slug: 'company', locale: locale as Locale }))
@@ -778,7 +785,7 @@ export const getCompany = cache(async (locale: string) => (await getCachedPayloa
## Layout and components
Rules: AGENT.md §6.8, ipal-nav, ipal-form.
Rules: AGENT.md §6.8, iapl-nav, iapl-form.
| File | What it shows |
|---|---|
@@ -840,7 +847,7 @@ export const generateStaticParams = route.generateStaticParams
```ts
'use server'
// ONE server action for every builder form: honeypot → client IP (IPAL_IP_HEADER) → submitForm
// ONE server action for every builder form: honeypot → client IP (IAPL_IP_HEADER) → submitForm
// (rate limit, Turnstile, validation, consent, save) → the message from Notifications.
import { createSubmitAction } from '@intecion/ipal-kit/server'
import { headers } from 'next/headers'
@@ -898,7 +905,7 @@ import { buttonClass } from '@intecion/ipal-kit/blocks/rsc'
const control =
'w-full rounded-control border border-border bg-surface px-3 py-2 text-fg placeholder:text-fg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus'
/** The ONLY place panel forms are styled (ipal-form). Token utilities only — no hex, no dark:. */
/** The ONLY place panel forms are styled (iapl-form). Token utilities only — no hex, no dark:. */
export const formClasses: BuilderFormClassNames = {
actions: 'flex flex-wrap gap-3',
back: buttonClass('secondary'),
@@ -911,6 +918,11 @@ export const formClasses: BuilderFormClassNames = {
fields: 'grid grid-cols-12 gap-4',
form: 'grid gap-6',
formError: 'rounded-control bg-danger-surface p-3 text-danger',
file: 'block w-full text-fg file:mr-3 file:rounded-control file:border-0 file:bg-surface-muted file:px-3 file:py-2 file:text-fg-strong',
fileItem: 'flex flex-wrap items-center gap-2',
fileList: 'mt-2 grid gap-1 text-sm',
fileRemove: 'underline underline-offset-2',
help: 'mt-1 text-sm text-fg-muted',
input: control,
label: 'mb-1 block font-medium text-fg-strong',
legend: 'mb-1 font-medium text-fg-strong',
@@ -961,7 +973,7 @@ import type { NavItem } from '@intecion/ipal-kit'
import Link from 'next/link'
import { useEffect, useState } from 'react'
/** Mobile menu: open state only, data via props (ipal-nav). Esc closes it. */
/** Mobile menu: open state only, data via props (iapl-nav). Esc closes it. */
export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) {
const [open, setOpen] = useState(false)
useEffect(() => {
@@ -999,7 +1011,7 @@ export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: s
## SEO, GEO and ops routes
Rules: AGENT.md §0b, ipal-setup stages 7–8.
Rules: AGENT.md §0b, iapl-setup stages 7–8.
| File | What it shows |
|---|---|
@@ -1152,41 +1164,113 @@ Rules: AGENT.md §8a.
| File | What it shows |
|---|---|
| `e2e/create-test-admin.ts` | a test admin with a known TOTP secret (local / CI database only) (below) |
| `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms, sitemap, SEO/GEO, headers, consent, 2FA |
| `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test (below) |
| `e2e/closed-doors.spec.ts` | closed doors from outside (run by `pnpm e2e:built` in both bundlers): every door of e2e/closed-doors.ts asked on the production build as an anonymous visitor, a customer (the fixture's `e2e-visitors`) and an editor; doors still open while the owner decides are asserted open (`test.fail`) |
| `e2e/closed-doors.ts` | the doors that must stay closed, who each is closed for and how a closed answer looks; a project adds its own (security.md "Closed doors from outside") |
| `e2e/create-test-admin.ts` | two test admins with a known TOTP secret (the specs share out the five 2FA verify attempts per account), their stored verify counts cleared, and e-mail sending pointed at the tests' mail sink (local / CI database only) |
| `e2e/global-setup.ts` | Playwright global setup: resets the test admins and clears their stored 2FA attempt counts before every run, so specs do not depend on run order (below) |
| `e2e/late-staff-fixture.ts` | test fixture, on only with E2E_LATE_STAFF=1: one plugin before iapl (staff collections of the config: roles with one more value, the plugin's roles, roles of the project's own) and one after it (a staff collection without rules, one whose roles field is text, copies of staff collections under new slugs — plain, with rules of their own, one rule used for another operation, other role values, the opt-out, not staff — and a visitor collection with open sign-up) |
| `e2e/late-staff.spec.ts` | the account rules on a BUILT site (run by `pnpm e2e:built` after a webpack and a Turbopack build): a staff collection a later plugin adds, staff collections whose accounts can hold `admin`, and copies of staff collections — a visitor account gets nothing, nobody raises its own role or makes an admin, a copy is never wider than the plugin's rule |
| `e2e/mail-relay-fixture.ts` | test fixture, on only with E2E_MAIL_RELAY_URL: points the mail service's client at the stand-in the spec starts; never in a real site (a real site names no address) (below) |
| `e2e/mail-relay-setup.ts` | for the mail-service spec: empties the SMTP fields and the stored token, so the next e-mail enrols and goes through the mail service (local database only) (below) |
| `e2e/mail-relay.spec.ts` | the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives |
| `e2e/routes.snapshot.json` | every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list `routes:check` compares with |
| `e2e/routes.ts` | `routes:check`: the site's public routes against e2e/routes.snapshot.json (`pnpm payload run e2e/routes.ts [update]`; from the repository `pnpm routes:check`) (below) |
| `e2e/sign-in-look.spec.ts` | browser test of the sign-in look (whiteLabel.signIn): the panel comes with the form, sits above it on a phone in both themes, is on forgot / reset / logout too, the language links work, the 2FA code screen keeps its boxes (now named) |
| `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA |
| `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) |
| `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test, and the addresses of the second test admin and the test editor (below) |
| `e2e/two-factor-back.spec.ts` | browser test of the 2FA screens' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed |
| `e2e/two-factor-setup.spec.ts` | browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator's reset on the account page |
### `e2e/create-test-admin.ts`
### `e2e/global-setup.ts`
```ts
import { execFileSync } from 'node:child_process'
/**
* Before every Playwright run: the test admins are made (or reset) and their stored 2FA attempt counts cleared
* (e2e/create-test-admin.ts). The count is kept in the database — 5 verify attempts per account in 10 minutes —
* so without this a second run within ten minutes, or one spec run after the whole suite, would find the test
* admin locked out: the result would depend on what ran before. Skipped when the test admin is not configured
* (the specs that need it skip themselves) or with E2E_SKIP_ADMIN_SETUP=1.
*/
export default function globalSetup(): void {
const { E2E_ADMIN_EMAIL, E2E_ADMIN_PASSWORD, E2E_SKIP_ADMIN_SETUP, E2E_TOTP_SECRET } = process.env
if (E2E_SKIP_ADMIN_SETUP === '1' || !E2E_ADMIN_EMAIL || !E2E_ADMIN_PASSWORD || !E2E_TOTP_SECRET) {return}
execFileSync('pnpm', ['payload', 'run', 'e2e/create-test-admin.ts'], { env: { ...process.env, NODE_ENV: 'development' }, stdio: 'inherit' })
}
```
### `e2e/mail-relay-fixture.ts`
```ts
/**
* Creates (or resets) the smoke-test admin with a known TOTP secret, so e2e/smoke.spec.ts signs in through
* the real 2FA screen instead of skipping it. LOCAL / CI database only:
* pnpm payload run e2e/create-test-admin.ts
* Values come from E2E_ADMIN_EMAIL / E2E_ADMIN_PASSWORD / E2E_TOTP_SECRET (.env.example). Not a seed: seeds
* never create users (docs/seeding.md).
* Test fixture, on only with E2E_MAIL_RELAY_URL (e2e/mail-relay.spec.ts): points the mail service's client at
* a stand-in the spec starts on this machine, so the spec can watch a built site enrol through its own confirm
* route and send — without the real service. Never part of a real site: the starter drops `e2e/` and the lines
* that use this file; a real site names no address (the plugin's own is used).
*/
export const E2E_MAIL_RELAY_URL = process.env.E2E_MAIL_RELAY_URL || undefined
/** `iapl({ mail })` for the test, `undefined` (the plugin's defaults) otherwise. */
export const e2eMail = E2E_MAIL_RELAY_URL ? { relay: { retryBackoffMs: 50, url: E2E_MAIL_RELAY_URL } } : undefined
/**
* `iapl({ developmentHosts })` for a test that plays a development address on this machine (the built-in
* pattern, `*.dev.netscale.pl`, cannot be served from localhost): E2E_DEVELOPMENT_HOSTS, comma-separated
* patterns. `undefined` (the plugin's built-in list) otherwise.
*/
export const e2eDevelopmentHosts = process.env.E2E_DEVELOPMENT_HOSTS ? process.env.E2E_DEVELOPMENT_HOSTS.split(',').map((p) => p.trim()).filter(Boolean) : undefined
```
### `e2e/mail-relay-setup.ts`
```ts
/**
* For e2e/mail-relay.spec.ts — LOCAL / CI database only:
* pnpm payload run e2e/mail-relay-setup.ts the site has no SMTP server and no token: its next e-mail
* goes to the mail service, enrolling first
* Afterwards the spec runs e2e/create-test-admin.ts again, which points e-mail back at the tests' SMTP sink.
*/
import config from '@payload-config'
import { RELAY_KV_KEY } from '@intecion/ipal-kit'
import { isLocalDatabase } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload'
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: totpSecret } = process.env
if (!email || !password || !totpSecret) {throw new Error('Set E2E_ADMIN_EMAIL, E2E_ADMIN_PASSWORD and E2E_TOTP_SECRET (.env.example).')}
if (process.env.NODE_ENV === 'production' && !process.env.CI) {throw new Error('Refusing: NODE_ENV=production outside CI.')}
if (!isLocalDatabase(process.env.DATABASE_URI ?? '')) {throw new Error('Refusing: DATABASE_URI is not a local database.')}
const payload = await getPayload({ config })
const data = { email, hasTotp: true, password, roles: ['admin'], totpSecret }
const found = await payload.find({ collection: 'users', limit: 1, overrideAccess: true, where: { email: { equals: email } } })
if (found.docs[0]) {
await payload.update({ id: found.docs[0].id, collection: 'users', data: data as never, overrideAccess: true })
} else {
await payload.create({ collection: 'users', data: data as never, overrideAccess: true })
await payload.updateGlobal({
slug: 'site-integrations',
context: { ipalIntegrationStatus: true },
data: { emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailMethod: 'relay', emailTransport: 'smtp', smtpFromAddress: 'site@example-studio.test', smtpFromName: 'Example Studio', smtpHost: null, smtpPassword: null, smtpUser: null } as never,
overrideAccess: true,
})
for (const key of await payload.kv.keys()) {
if (key === RELAY_KV_KEY || key.startsWith(`${RELAY_KV_KEY}:`)) {await payload.kv.delete(key)}
}
console.log(`[e2e] test admin ready: ${email}`)
console.log('[e2e] no SMTP server and no mail-service token: the next e-mail enrols and goes through the mail service')
process.exit(0)
```
### `e2e/routes.ts`
```ts
/**
* routes:check — every public route of this site (REST, GraphQL, Next route files) against the judged list in
* e2e/routes.snapshot.json (docs/security.md "Routes nobody has judged"). Reads the config only, never the database.
* pnpm payload run e2e/routes.ts → fails on a route nobody has judged
* pnpm payload run e2e/routes.ts update → adds new routes with an empty reason (judge them), drops gone ones
* (`payload run` drops `--flags`, so the word is `update`.) From the plugin repository: pnpm routes:check [--update],
* also the first step of pnpm e2e:built.
*/
import config from '@payload-config'
import { runRouteCheck } from '@intecion/ipal-kit/doctor'
process.exit(await runRouteCheck({ config: await config, update: process.argv.slice(2).includes('update') }))
```
### `e2e/totp.ts`
```ts
@@ -1205,4 +1289,10 @@ export function totp(secret: string, now = Date.now()): string {
const code = (hmac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000
return code.toString().padStart(6, '0')
}
/** The second smoke-test admin (create-test-admin.ts makes both): `e2e-admin@…` → `e2e-admin-2@…`. */
export const secondTestAdmin = (email: string): string => email.replace('@', '-2@')
/** The smoke-test editor (create-test-admin.ts makes it): `e2e-admin@…` → `e2e-admin-editor@…`, role `editor`, the same password and secret. */
export const editorTestAccount = (email: string): string => email.replace('@', '-editor@')
```
@@ -1,9 +1,9 @@
---
name: ipal-audit
description: Audits an ipal-kit (Payload 3 + Next 16) project against AGENT.md rules with a deterministic script — the mandatory feature set (SEO, JSON-LD, llms.txt, Markdown, MCP, R2, Turnstile, panel forms, consent, 2FA, health, env, security headers, X-Powered-By, CSP), forbidden replacements (own forms, nodemailer, reCAPTCHA, hand-written JSON-LD), hardcoded texts/links, forbidden field names, monolithic sections, middleware.ts, missing ISR/generateStaticParams, hex colors, server imports in client components, extra collections, then tsc and build. Use before saying a task is done, after any block/collection/layout change, after an Impeccable pass, and when asked to review or audit the project.
name: iapl-audit
description: Audits an IAPL (Payload 3 + Next 16) project against AGENT.md rules with a deterministic script — the mandatory feature set (SEO, JSON-LD, llms.txt, Markdown, MCP, R2, Turnstile, panel forms, consent, 2FA, health, env, security headers, X-Powered-By, CSP), forbidden replacements (own forms, nodemailer, reCAPTCHA, hand-written JSON-LD), hardcoded texts/links, forbidden field names, monolithic sections, middleware.ts, missing ISR/generateStaticParams, hex colors, server imports in client components, extra collections, then tsc and build. Use before saying a task is done, after any block/collection/layout change, after an Impeccable pass, and when asked to review or audit the project.
---
# ipal-audit
# iapl-audit
The checks from AGENT.md §11 as a script — always the same, no interpretation.
@@ -11,8 +11,8 @@ The checks from AGENT.md §11 as a script — always the same, no interpretation
1. From the project root, run:
```bash
bash .agents/skills/ipal-audit/scripts/audit.sh --quick # while working
bash .agents/skills/ipal-audit/scripts/audit.sh # before "done" (+ tsc + build)
bash .agents/skills/iapl-audit/scripts/audit.sh --quick # while working
bash .agents/skills/iapl-audit/scripts/audit.sh # before "done" (+ tsc + build)
```
Options: `--help`. Do not read the script source — the output is enough.
2. Show the user the **full output** (summary + list of violations).
@@ -27,7 +27,7 @@ The checks from AGENT.md §11 as a script — always the same, no interpretation
## "missing: …" — the mandatory set (AGENT.md §0b)
Every `[ERROR] missing: X` is an item of the set that the code lacks. Wire it
following the hint (PROGRAMISTA §2) — do not ask whether it is needed. The only exception:
a client decision recorded in `AGENTS.md` as `ipal-audit-skip: <keys> — <reason>` (keys
a client decision recorded in `AGENTS.md` as `iapl-audit-skip: <keys> — <reason>` (keys
in AGENT.md §0b). Never add that line yourself just to make the audit pass.
## Polish text and panel labels (AGENT.md §2, §6.5a)
@@ -40,17 +40,24 @@ in AGENT.md §0b). Never add that line yourself just to make the audit pass.
The script checks: hex in classes and inline styles (error), `dark:` on colour utilities and `var(--color-…)` in
classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warning — a site not yet migrated),
next/font in `--font-body` with the preset (warning), and with `src/design/tokens.ts`: no `DESIGN.md` (warning) and
`ipal-tokens --check` — a stale `src/design/tokens.css` or a WCAG AA contrast failure is an error.
`iapl-tokens --check` — a stale `src/design/tokens.css` or a WCAG AA contrast failure is an error.
## ipal-audit and ipal-doctor
`ipal-audit` checks the **code** inside the edit loop (and tsc + build). `pnpm exec ipal-doctor` checks the **site**
## iapl-audit and iapl-doctor
`iapl-audit` checks the **code** inside the edit loop (and tsc + build). `pnpm exec iapl-doctor` checks the **site**
against the team standard: it runs this script (`--quick`) from the installed package, reports its findings under its
own rule ids (`i18n-literals`, `blocks-tokens`, `audit:<title>`, one per file), and adds versions, Node, layout, database
names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` — the running site and the database
(the `ipal-doctor` skill, docs/doctor.md). An approved exception for the doctor goes into `ipal-doctor.json` with a reason.
(the `iapl-doctor` skill, docs/doctor.md). An approved exception for the doctor goes into `iapl-doctor.json` with a reason.
## What the script does not check (do it by hand)
- **Closed doors and judged routes** (security.md "Closed doors from outside", "Routes nobody has judged"):
`resources/closed-doors.spec.template.ts` → `tests/closed-doors.spec.ts` (add the project's own doors; run on a
production build as anonymous, customer and editor) and `resources/routes.template.ts` → `tests/routes.ts`
(`pnpm payload run tests/routes.ts update` once, write a reason per route, commit the snapshot; then
`pnpm payload run tests/routes.ts` fails on a route nobody has judged). A new custom endpoint, collection or
route file of the project = a new snapshot entry with its reason, and a door in `DOORS` if it must stay closed.
- **Editor test** (AGENT.md §11): every text, image, button, section,
menu, footer and SEO field can be changed in the panel, in every language.
- **Cookie consent:** in Network, before accepting, there are no requests to
@@ -60,11 +67,22 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` —
- **Response headers** (on a running build — `pnpm build && pnpm start`, or the deployed domain):
```bash
U=http://localhost:3000
for p in /pl /admin /api/health; do echo "== $p"; curl -sI "$U$p" | grep -iE 'x-powered-by|content-security-policy'; done
for p in /pl /admin /api/health; do echo "== $p"; curl -sI "$U$p" | grep -iE 'x-powered-by|content-security-policy|critical-ch'; done
```
`x-powered-by` anywhere → ERROR (`withSecurityConfig`, security.md → "X-Powered-By"). No
`x-powered-by` anywhere → ERROR (`withSecurityConfig`, security.md → "X-Powered-By"). `critical-ch` on `/pl` or
`/api/health` → INFO: Chrome repeats the first request of every visit; make `withSecurityConfig` the outer wrapper,
`withSecurityConfig(withPayload(nextConfig))` (security.md → "Client hints"); on `/admin` it belongs. No
`content-security-policy` / `content-security-policy-report-only` on `/pl` and `/admin` → WARNING (CSP not
rolled out). Report-only for more than a few weeks with clean reports → WARNING (switch to `mode: 'enforce'`).
Then open `/pl` and `/admin` in the browser: CSP lines in the console = missing sources (flags / `extra`).
- **Drafts and locales over the API** (a collection with `versions: { drafts: true }`): without a session,
`curl -s "$U/api/<slug>?draft=true&limit=100" | grep -c '"_status":"draft"'` → `0`, else ERROR: give it
`access: { read: readPublished(), readVersions: readPublished() }` (access.md). `curl -sI "$U/md/xx"` → `404`
(no stand-in locale); a 404 page assigned in System pages must be published.
- **Secrets out of queries** (as an admin, with versions on for Site integrations or a collection using
`writeOnlySecret`): `curl -s -H "Authorization: JWT $T" "$U/api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true"`
answers an error with no `totalDocs`, else ERROR (the field lost `secretReadAccess`, e.g. an override replaced its
`access`).
Do not say "done" until the full audit (without `--quick`) has no errors.
@@ -0,0 +1,105 @@
/**
* Closed doors from outside — every door of the site that must stay CLOSED, asked on a PRODUCTION build (`pnpm build
* && pnpm start`: Payload's GraphQL playground and introspection, among others, behave differently outside
* production) as an anonymous visitor, a customer and an editor (IAPL docs/security.md "Closed doors from outside").
* Copy to tests/closed-doors.spec.ts and run:
*
* BASE_URL=http://localhost:3000 pnpm exec playwright test tests/closed-doors.spec.ts
*
* Callers (each is skipped when its variables are missing):
* anonymous always;
* customer a site with a visitor login collection: E2E_CUSTOMER_COLLECTION (its slug), E2E_CUSTOMER_EMAIL,
* E2E_CUSTOMER_PASSWORD — an existing test account of that collection;
* editor E2E_EDITOR_EMAIL, E2E_EDITOR_PASSWORD, E2E_EDITOR_TOTP_SECRET — a staff test account with the role
* `editor` and a known 2FA secret, on a LOCAL or staging database only (never production accounts).
* Add the project's own doors to DOORS (a custom endpoint, a collection only staff may read, a global with secrets).
* A write door is asked with a body that changes nothing when the door is open (an id that does not exist, `{}`).
*/
import { type APIRequestContext, expect, test } from '@playwright/test'
import { createHmac } from 'node:crypto'
type Caller = 'anonymous' | 'customer' | 'editor'
type Answer = { body: unknown; status: number }
type Door = { body?: unknown; closed?: (a: Answer) => boolean; closedFor: Caller[]; graphql?: string; method?: 'DELETE' | 'GET' | 'PATCH' | 'POST'; name: string; path?: string }
const BASE = (process.env.BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '')
const ALL: Caller[] = ['anonymous', 'customer', 'editor']
const OUTSIDERS: Caller[] = ['anonymous', 'customer']
const NO_ID = '000000000000000000000000' // MongoDB; use 999999999 on Postgres / SQLite
const refused = ({ status }: Answer) => [401, 403, 404].includes(status)
const status = (code: number) => (a: Answer) => a.status === code
const noData = (field: string) => ({ body, status: s }: Answer) => {
const b = body as { data?: Record<string, unknown> | null; errors?: unknown[] } | null
return s >= 400 || Boolean(b?.errors?.length) || b?.data?.[field] == null
}
const DOORS: Door[] = [
// the plugin's own — keep them
{ closedFor: ALL, name: 'Site integrations cannot be read', path: '/api/globals/site-integrations' },
{ body: {}, closedFor: ALL, method: 'POST', name: 'Site integrations cannot be saved', path: '/api/globals/site-integrations' },
{ closedFor: ALL, graphql: '{ SiteIntegration { smtpHost } }', closed: noData('SiteIntegration'), name: 'Site integrations over GraphQL' },
{ closedFor: ALL, name: 'the key-value store (2FA counts, the mail-service token)', path: '/api/payload-kv' },
{ closedFor: ALL, name: 'the consent log', path: '/api/consent-records' },
{ closedFor: ALL, name: 'the deep doctor status without its token', path: '/api/ipal/doctor', closed: status(404) },
{ closedFor: ALL, method: 'POST', name: 'a test e-mail', path: '/api/ipal/test-email', body: { to: '[email protected]' } },
{ closedFor: ALL, name: 'the mail-service status', path: '/api/iapl/mail-relay/status' },
{ closedFor: ALL, method: 'POST', name: 'the crawler\'s call-back without its token', path: '/api/ipal/cookie-crawl/results', body: { jobId: 'x', ok: true } },
{ closedFor: OUTSIDERS, method: 'POST', name: 'a crawl without the schedule\'s token', path: '/api/ipal/cookie-crawl' },
{ closedFor: OUTSIDERS, name: 'form submissions', path: '/api/form-submissions' },
{ body: { email: '[email protected]', password: 'Door-Password-1234', roles: ['admin'] }, closedFor: ALL, method: 'POST', name: 'nobody creates a staff account', path: '/api/users', closed: status(403) },
{ body: { email: '[email protected]', password: 'Door-Password-1234' }, closedFor: ALL, method: 'POST', name: 'the first-user route once an account exists', path: '/api/users/first-register', closed: status(403) },
{ body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Site settings cannot be saved', path: '/api/globals/site-settings', closed: status(403) },
{ closedFor: ALL, name: 'the GraphQL playground (production)', path: '/api/graphql-playground', closed: status(404) },
{ closedFor: ALL, graphql: '{ __schema { queryType { name } } }', closed: ({ body }) => Boolean((body as { errors?: unknown[] })?.errors?.length), name: 'GraphQL introspection (production)' },
{ closedFor: ALL, name: 'Payload\'s job queue (a site without jobs)', path: '/api/payload-jobs/run', closed: status(404) },
// the project's own doors: add them here
// { closedFor: OUTSIDERS, body: {}, method: 'PATCH', name: 'pages cannot be changed', path: `/api/pages/${NO_ID}`, closed: status(403) },
]
/** RFC 6238 TOTP (SHA-1, 6 digits, 30 s) for a base32 secret. */
function totp(secret: string): string {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
let bits = ''
for (const ch of secret.replace(/=+$/, '').toUpperCase()) {bits += alphabet.indexOf(ch).toString(2).padStart(5, '0')}
const key = Buffer.from((bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2)))
const counter = Buffer.alloc(8)
counter.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 30_000)))
const h = createHmac('sha1', key).update(counter).digest()
return (((h.readUInt32BE(h[h.length - 1]! & 0xf) & 0x7fffffff) % 1_000_000).toString().padStart(6, '0'))
}
async function signIn(caller: Caller, playwright: { request: { newContext: (o: object) => Promise<APIRequestContext> } }): Promise<APIRequestContext | null> {
const api = await playwright.request.newContext({ baseURL: BASE, extraHTTPHeaders: { origin: BASE } })
const env = process.env
if (caller === 'customer') {
if (!env.E2E_CUSTOMER_COLLECTION || !env.E2E_CUSTOMER_EMAIL || !env.E2E_CUSTOMER_PASSWORD) {return null}
expect((await api.post(`/api/${env.E2E_CUSTOMER_COLLECTION}/login`, { data: { email: env.E2E_CUSTOMER_EMAIL, password: env.E2E_CUSTOMER_PASSWORD } })).status()).toBe(200)
}
if (caller === 'editor') {
if (!env.E2E_EDITOR_EMAIL || !env.E2E_EDITOR_PASSWORD || !env.E2E_EDITOR_TOTP_SECRET) {return null}
expect((await api.post('/api/users/login', { data: { email: env.E2E_EDITOR_EMAIL, password: env.E2E_EDITOR_PASSWORD } })).status()).toBe(200)
expect((await (await api.post('/api/verify-totp', { data: { token: totp(env.E2E_EDITOR_TOTP_SECRET) } })).json()).ok).toBe(true)
}
return api
}
for (const caller of ALL) {
test.describe(`closed doors as ${caller}`, () => {
let api: APIRequestContext | null = null
test.beforeAll(async ({ playwright }) => {
api = await signIn(caller, playwright)
})
for (const door of DOORS.filter((d) => d.closedFor.includes(caller))) {
test(door.name, async () => {
test.skip(!api, `no ${caller} test account configured`)
const res = door.graphql
? await api!.post('/api/graphql', { data: { query: door.graphql } })
: await api!.fetch(door.path!, { data: door.body, maxRedirects: 0, method: door.method ?? 'GET' })
const text = await res.text()
let body: unknown = text
try { body = JSON.parse(text) } catch { /* not JSON */ }
expect((door.closed ?? refused)({ body, status: res.status() }), `${door.graphql ?? door.path} → ${res.status()} ${text.slice(0, 200)}`).toBe(true)
})
}
})
}
@@ -0,0 +1,24 @@
/**
* Routes nobody has judged — every public route of this site (REST, GraphQL, Next route files) against the judged
* list in tests/routes.snapshot.json (IAPL docs/security.md "Routes nobody has judged"). Reads the config, never the
* database: the same on MongoDB, Postgres and SQLite. Copy to tests/routes.ts, then:
*
* pnpm payload run tests/routes.ts update → writes tests/routes.snapshot.json, every route with an EMPTY reason
* (write one line per route: who may use it and why it is open, or that it is closed and to whom)
* pnpm payload run tests/routes.ts → fails on a route nobody has judged or an entry without a reason
*
* Run it in CI and after every Payload / IAPL / plugin upgrade; an upgrade that adds a route fails here until somebody
* judges it (`update` adds it with an empty reason; review the diff). `payload run` drops `--flags`: the word is `update`.
*/
import config from '@payload-config'
import { runRouteCheck } from '@intecion/ipal-kit/doctor'
process.exit(
await runRouteCheck({
config: await config,
snapshot: 'tests/routes.snapshot.json',
// appDir: 'src/app', // where the Next routes live
// graphql: false, // a site that deleted app/(payload)/api/graphql
update: process.argv.slice(2).includes('update'),
}),
)
@@ -1,9 +1,9 @@
#!/usr/bin/env bash
# ipal-audit — deterministic checks of an ipal-kit project against AGENT.md.
# iapl-audit — deterministic checks of an IAPL project against AGENT.md.
# Run from the project root:
# bash .agents/skills/ipal-audit/scripts/audit.sh # all checks + tsc + build
# bash .agents/skills/ipal-audit/scripts/audit.sh --quick # static checks only
# bash .agents/skills/ipal-audit/scripts/audit.sh --help
# bash .agents/skills/iapl-audit/scripts/audit.sh # all checks + tsc + build
# bash .agents/skills/iapl-audit/scripts/audit.sh --quick # static checks only
# bash .agents/skills/iapl-audit/scripts/audit.sh --help
# Exit code: 0 = no errors (warnings allowed), 1 = at least one error.
set -u
@@ -22,7 +22,7 @@ for arg in "$@"; do
done
if [ ! -d src ]; then
echo "ipal-audit: run from the project root (no ./src found)." >&2
echo "iapl-audit: run from the project root (no ./src found)." >&2
exit 2
fi
@@ -52,7 +52,7 @@ dirs() { for d in "$@"; do [ -d "$d" ] && printf '%s ' "$d"; done; }
BLOCKS=$(dirs src/blocks)
UI=$(dirs src/blocks src/components)
echo "ipal-audit — $(pwd)"
echo "iapl-audit — $(pwd)"
# --- Skill templates must not be compiled as project code ---
if [ -d .agents ] && [ -f tsconfig.json ]; then
@@ -162,7 +162,7 @@ if [ -n "$UI" ]; then
report WARNING "old colour variables in classes" "§6.11 use the preset utilities (bg-primary, text-fg) — not var(--color-…)" \
"$(g '\[var\(--color-' $UI --include=*.tsx)"
report ERROR "hex colors in inline styles" "§6.11 use design tokens — IPAL_TOKENS / ipalVar() for a dynamic style" \
report ERROR "hex colors in inline styles" "§6.11 use design tokens — IAPL_TOKENS / iaplVar() for a dynamic style" \
"$(g "style=\{\{[^}]*['\"]#[0-9a-fA-F]{3,8}['\"]" $UI --include=*.tsx)"
report ERROR "barrel index.ts" "§6.12 import files directly" \
@@ -184,14 +184,14 @@ if [ -n "$STYLES" ]; then
"$(grep -q 'ipal-kit/tailwind.css' "$STYLES" && g "variable: ['\"]--font-(body|heading|mono)['\"]" src/app --include=*.ts --include=*.tsx)"
fi
if [ -f src/design/tokens.ts ]; then
[ -f DESIGN.md ] || report WARNING "no DESIGN.md" "§6.11 the brand is described in DESIGN.md (template: ipal-setup/resources/DESIGN.md)" "DESIGN.md missing"
TOKENS_BIN=node_modules/@intecion/ipal-kit/bin/ipal-tokens.mjs
[ -f DESIGN.md ] || report WARNING "no DESIGN.md" "§6.11 the brand is described in DESIGN.md (template: iapl-setup/resources/DESIGN.md)" "DESIGN.md missing"
TOKENS_BIN=node_modules/@intecion/ipal-kit/bin/iapl-tokens.mjs
if [ -f "$TOKENS_BIN" ]; then
TOKENS_OUT=$(node "$TOKENS_BIN" --check 2>&1)
[ $? -ne 0 ] && report ERROR "ipal-tokens --check" "§6.11 run pnpm exec ipal-tokens: the CSS is stale or a contrast pair fails WCAG AA" \
"$(printf '%s\n' "$TOKENS_OUT" | grep -E '✗|out of date|ipal-tokens:' || echo 'ipal-tokens --check failed')"
[ $? -ne 0 ] && report ERROR "iapl-tokens --check" "§6.11 run pnpm exec iapl-tokens: the CSS is stale or a contrast pair fails WCAG AA" \
"$(printf '%s\n' "$TOKENS_OUT" | grep -E '✗|out of date|iapl-tokens:' || echo 'iapl-tokens --check failed')"
else
report WARNING "ipal-tokens not installed" "§6.11 @intecion/ipal-kit 1.15+ ships the ipal-tokens bin" "$TOKENS_BIN missing"
report WARNING "iapl-tokens not installed" "§6.11 @intecion/ipal-kit 1.15+ ships the iapl-tokens bin" "$TOKENS_BIN missing"
fi
fi
@@ -199,7 +199,7 @@ fi
if [ -d src/collections ]; then
report ERROR "forbidden collection" "§5.3 settings/nav/footer are globals; FAQ/hero are blocks" \
"$(ls src/collections | grep -iE '^(settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')"
report WARNING "own users collection" "§5.3 ipalKit injects the auth collection — keep your own only to add fields (roles + 2FA still attach)" \
report WARNING "own users collection" "§5.3 IAPL injects the auth collection — keep your own only to add fields (roles + 2FA still attach)" \
"$(ls src/collections | grep -iE '^(users|user)\.ts$')"
report WARNING "collections present — confirm each passed the §5.3 test" "minimum: Pages, Media" \
"$(ls src/collections | grep -viE '^(pages|media|users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')"
@@ -261,8 +261,8 @@ done <<< "$(printf '%s\n' "$HTML" | cut -d'|' -f1-2 | sort -u)"
# --- Mandatory feature set (AGENT.md §0b) ---
# Every site wires all of these through the plugin. A missing one is an ERROR
# unless AGENTS.md records the client's decision: `ipal-audit-skip: mcp, llms-full — reason`.
SKIP=$(grep -hiE '^[-* ]*ipal-audit-skip:' AGENTS.md 2>/dev/null | sed 's/^[^:]*://; s/—.*//; s/ - .*//' | tr ',' ' ')
# unless AGENTS.md records the client's decision: `iapl-audit-skip: mcp, llms-full — reason`.
SKIP=$(grep -hiE '^[-* ]*(iapl|ipal)-audit-skip:' AGENTS.md 2>/dev/null | sed 's/^[^:]*://; s/—.*//; s/ - .*//' | tr ',' ' ')
skipped() { for k in $SKIP; do [ "$k" = "$1" ] && return 0; done; return 1; }
# has <regex> <paths…> — true when any file under the paths matches
has() { local re="$1"; shift; grep -rqE "$re" "$@" 2>/dev/null; }
@@ -294,9 +294,9 @@ if [ -n "$APP" ]; then
need WARNING '' "AI summary field" "buildSummaryField() in Pages + createContentHelpers({ summaryField: 'aiSummary' })" 'buildSummaryField' src
# Ops
need ERROR '' "health route" "src/app/api/health/route.ts → export { healthRoute as GET } from '@/lib/content'" 'healthRoute|createHealthRoute' src/app
need ERROR '' "env validation" "src/instrumentation.ts → assertEnv(ipalEnvRules({...})) from @intecion/ipal-kit/env" 'assertEnv' src/instrumentation.ts instrumentation.ts
need ERROR '' "env validation" "src/instrumentation.ts → assertEnv(iaplEnvRules({...})) from @intecion/ipal-kit/env" 'assertEnv' src/instrumentation.ts instrumentation.ts
need ERROR '' "security headers" "next.config.ts → buildSecurityHeaders" 'buildSecurityHeaders' next.config.ts next.config.mjs next.config.js
need WARNING '' "X-Powered-By hidden" "next.config.ts → export default withPayload(withSecurityConfig(nextConfig)) — Next and withPayload send X-Powered-By: Next.js, Payload (security.md)" 'withSecurityConfig|poweredByHeader: *false' next.config.ts next.config.mjs next.config.js
need WARNING '' "X-Powered-By hidden" "next.config.ts → export default withSecurityConfig(withPayload(nextConfig)) — Next and withPayload send X-Powered-By: Next.js, Payload (security.md)" 'withSecurityConfig|poweredByHeader: *false' next.config.ts next.config.mjs next.config.js
need WARNING csp "Content-Security-Policy" "next.config.ts → buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } }) + buildAdminCspHeaders on /admin/:path*, then 'enforce' (security.md → ROLL OUT CSP)" "csp: *\\{|csp,|buildCsp|Content-Security-Policy" next.config.ts next.config.mjs next.config.js src/proxy.ts proxy.ts
# Consent, analytics, Turnstile (layout)
need ERROR '' "cookie consent" "<SiteProviders> (or ConsentProvider + CookieBanner + CookieButton) in [locale]/layout.tsx" 'SiteProviders|CookieBanner' src/app
@@ -305,21 +305,21 @@ if [ -n "$APP" ]; then
need WARNING turnstile "Turnstile site key" "getSiteShell(locale) (or getTurnstileConfig(payload)) — off unless BOTH keys are set" 'getSiteShell|getTurnstileConfig' src
need WARNING '' "MediaPreconnect" "<SiteProviders> (adds it) or <MediaPreconnect/> in the layout" 'SiteProviders|MediaPreconnect' src/app
# Forms
need ERROR '' "form submission via the plugin" "actions.ts → export const sendForm = createSubmitAction({ getCachedPayload, headers }) (ipal-form)" 'createSubmitAction|submitForm' src
need ERROR '' "form submission via the plugin" "actions.ts → export const sendForm = createSubmitAction({ getCachedPayload, headers }) (iapl-form)" 'createSubmitAction|submitForm' src
need WARNING '' "upload sandbox headers" "next.config.ts → ...buildUploadSecurityHeaders() (uploaded SVG can't run script)" 'buildUploadSecurityHeaders' next.config.ts next.config.mjs next.config.js
need WARNING '' "images preset" "next.config.ts → images: { ...buildImagesConfig() } (AVIF/WebP, R2 domain)" 'buildImagesConfig' next.config.ts next.config.mjs next.config.js
fi
if [ -n "$CFG" ]; then
need ERROR '' "forms in ipalKit" "$CFG → ipalKit({ forms: {…} }) — forms are built in the panel" 'forms *:' "$CFG"
need ERROR '' "forms in iapl" "$CFG → iapl({ forms: {…} }) — forms are built in the panel" 'forms *:' "$CFG"
need ERROR '' "mailAdapter" "$CFG → email: mailAdapter() — form e-mails go through the panel transport" 'mailAdapter\(' "$CFG"
need ERROR r2 "R2 storage" "$CFG → buildR2Storage(['media'], { s3Storage }) — always wired, local disk only without R2_* env" 'buildR2Storage' "$CFG"
# pnpm dev / generate:importmap with ipal-kit < 1.12.2 and no R2_* env dropped the storage-s3
# pnpm dev / generate:importmap with IAPL < 1.12.2 and no R2_* env dropped the storage-s3
# client handler → blank admin in production (where R2 is on)
if grep -q 'buildR2Storage' "$CFG" 2>/dev/null; then
for IM in src/app/\(payload\)/*/importMap.js; do
[ -f "$IM" ] || continue
report ERROR "import map without the R2 upload handler" "storage.md — pnpm payload generate:importmap (ipal-kit ≥ 1.12.2 writes it with or without R2_* env); without it the production admin renders blank" \
report ERROR "import map without the R2 upload handler" "storage.md — pnpm payload generate:importmap (IAPL ≥ 1.12.2 writes it with or without R2_* env); without it the production admin renders blank" \
"$(grep -q 'S3ClientUploadHandler' "$IM" || echo "$IM")"
done
fi
@@ -331,10 +331,10 @@ fi
# A form seed: scripts/seed-form-*.ts, or a seed file (src/seed, scripts) that seeds the forms collection.
FORM_SEED=$(ls scripts/seed-form* 2>/dev/null; grep -rlE "collection: *['\"]forms['\"]|upsertBy\( *['\"]forms['\"]|seed\.form\(|\.forms?\(" $(dirs src/seed scripts) 2>/dev/null)
if [ -n "$CFG" ] && grep -qE 'forms *:' "$CFG" 2>/dev/null && [ -z "$FORM_SEED" ] && ! skipped forms-seed; then
report WARNING "no form seed" "ipal-form §5 — every form from a seed (scripts/seed-form-*.ts or src/seed/forms.ts: notification + sender confirmation, all languages)" "scripts/seed-form-*.ts"
report WARNING "no form seed" "iapl-form §5 — every form from a seed (scripts/seed-form-*.ts or src/seed/forms.ts: notification + sender confirmation, all languages)" "scripts/seed-form-*.ts"
fi
need WARNING r2 "R2 env in .env.example" ".env.example lists R2_BUCKET, R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_PUBLIC_URL" 'R2_BUCKET' .env.example
need WARNING '' "IPAL_IP_HEADER in .env.example" "header the rate limit trusts, e.g. cf-connecting-ip (forms.md)" 'IPAL_IP_HEADER' .env.example
need WARNING '' "IAPL_IP_HEADER in .env.example" "header the rate limit trusts, e.g. cf-connecting-ip (forms.md)" '(IAPL|IPAL)_IP_HEADER' .env.example
# Plugin replacements (§0b "Forbidden substitutes")
report ERROR "own form / mail / captcha stack" "§0b — forms come from the panel builder, mail from mailAdapter, bot check from Turnstile" \
@@ -349,7 +349,7 @@ report WARNING "<form> outside the form renderer" "§0b — panel forms render v
"$(g '<form[ >]' src --include=*.tsx | grep -v 'components/forms/')"
# Project copies of what the plugin now ships (import instead of code)
report WARNING "own form engine" "ipal-form §3 — <RenderForm> / useBuilderForm (steps, choices, Turnstile, honeypot; Emails tab never reaches the browser)" \
report WARNING "own form engine" "iapl-form §3 — <RenderForm> / useBuilderForm (steps, choices, Turnstile, honeypot; Emails tab never reaches the browser)" \
"$(g 'buildValidator|useForm\(' src --include=*.tsx | grep -v 'useBuilderForm')"
report WARNING "own image lightbox" "lightbox.md — <LightboxTrigger> + lightboxImage, one <SiteProviders lightbox>; labels from Notifications → Lightbox" \
"$(g "['\"](glightbox|photoswipe|yet-another-react-lightbox|react-medium-image-zoom|fslightbox-react)['\"]" src --include=*.ts --include=*.tsx)"
@@ -383,5 +383,5 @@ if [ "$QUICK" -eq 0 ]; then
fi
echo
echo "ipal-audit: $ERRORS error(s), $WARNINGS warning(s)$( [ "$QUICK" -eq 1 ] && echo ' (quick: no tsc/build)')"
echo "iapl-audit: $ERRORS error(s), $WARNINGS warning(s)$( [ "$QUICK" -eq 1 ] && echo ' (quick: no tsc/build)')"
[ "$ERRORS" -eq 0 ]
@@ -4,7 +4,7 @@
// Reads the syntax tree (the project's TypeScript), so comments never count and multi-line forms work.
// Not reported: the panel's own labels (AGENT.md §6.5a), only in a schema file — a .ts file under
// collections/, globals/, fields/ or blocks/, or one importing Payload's schema types; never a .tsx file:
// - adminText('Title', 'Tytuł') from @intecion/ipal-kit
// - adminText('Title', 'Tytuł') from @intecion/ipal-kit/blocks
// - { en: 'Title', pl: 'Tytuł' } as the value of label, singular, plural, description, placeholder or group
// - rowLabel('title', { en: 'Item', pl: 'Pozycja' }) from @intecion/ipal-kit
// - const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' }
@@ -28,7 +28,7 @@ const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/
const SCHEMA_KEYS = new Set(['label', 'singular', 'plural', 'description', 'placeholder', 'group'])
const SCHEMA_DIR = /(?:^|\/)(?:collections|globals|fields|blocks)\//
const SCHEMA_TYPES = /import\s+type\s*\{[^}]*\b(?:Block|CollectionConfig|Field|GlobalConfig|Tab)\b[^}]*\}\s*from\s*['"]payload['"]/
const IPAL = /^@intecion\/ipal-kit(?:\/|$)/
const IAPL = /^@intecion\/ipal-kit(?:\/|$)/
const files = []
const walk = (p) => {
@@ -50,7 +50,7 @@ for (const file of files) {
// Local names of the plugin's helpers (`import { adminText as t } …`); a lookalike of your own does not count.
const helpers = new Map()
for (const st of source.statements) {
if (!ts.isImportDeclaration(st) || !IPAL.test(st.moduleSpecifier.text)) continue
if (!ts.isImportDeclaration(st) || !IAPL.test(st.moduleSpecifier.text)) continue
const named = st.importClause?.namedBindings
if (!named || !ts.isNamedImports(named)) continue
for (const el of named.elements) {
@@ -1,12 +1,12 @@
---
name: ipal-block
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — first a block of the plugin's block library (libraryBlocks / createBlockRegistry, 15 ready sections) or its variant or options, and only when none fits an own block with a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short `{ en, pl }` labels per docs/dev/admin-ux.md, no empty spare fields), shared fields from the plugin (buildSectionHeaderField, buildLinksField, buildLinkField, buildSectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
name: iapl-block
description: Builds or refactors one page section (Payload block + React component) in an IAPL project the correct way — first a block of the plugin's block library (libraryBlocks / createBlockRegistry, 15 ready sections) or its variant or options, and only when none fits an own block with a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short `{ en, pl }` labels per docs/dev/admin-ux.md, no empty spare fields), shared fields from the plugin (buildSectionHeaderField, buildLinksField, buildLinkField, buildSectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
---
# ipal-block
# iapl-block
**ipal-kit first (hard rule, AGENT.md "ipal-kit first"):** anything the plugin covers is built with the
plugin's feature. It does not work or is not enough → report it with **ipal-plugin-gap** and wait for the owner's
**IAPL first (hard rule, AGENT.md "IAPL first"):** anything the plugin covers is built with the
plugin's feature. It does not work or is not enough → report it with **iapl-plugin-gap** and wait for the owner's
decision on that part; no hand-built replacement, no silent workaround. **Code rules:** AGENT.md "Code rules"
(one job per file/component/function, no duplicates, typed, texts from the panel, a check for new behaviour).
@@ -24,12 +24,12 @@ The plugin ships 15 blocks: `hero`, `textMedia`, `featureGrid`, `cta`, `richText
(own `{ label: { en, pl }, value }` + `components` / `classNames` in the registry), `settings: { backgrounds }`,
`links`, `maxItems`. Another look of one part → `createBlockRegistry(content, { classNames: { faq: { item: '…' } } })`;
another primitive everywhere → `ui: { Media }`.
3. The project must own it completely → `pnpm exec ipal-blocks eject <block>` (same slug and data, no migration),
3. The project must own it completely → `pnpm exec iapl-blocks eject <block>` (same slug and data, no migration),
then the ejected builder in `pageBlocks` and `components: { <slug>: <Name>Block }` in the registry.
4. Nothing fits → an own block (below), with the library's builders (`buildItemsField`, `buildMediaField`,
`buildVariantField`, `buildContentField`, `defineLibraryBlock`) and primitives (`Section`, `SectionHeader`, `Media`,
`CMSLink`, `Card` from `@intecion/ipal-kit/blocks/rsc`), added to `extra` in `createBlockRegistry`.
Record the reason in AGENTS.md → "Project decisions" (`ipal-doctor` warns about own blocks that copy a library block).
Record the reason in AGENTS.md → "Project decisions" (`iapl-doctor` warns about own blocks that copy a library block).
**Check (library block):** `pnpm generate:types` → `pnpm payload generate:importmap` → Postgres/SQLite
`pnpm payload migrate:create`; add the block to a page in the panel (en and pl labels, ≤ 6 fields), the page shows
@@ -83,6 +83,6 @@ File patterns (Hero, FeatureGrid + FeatureCard): `resources/section-code.md`.
readable in English and Polish (switch the admin language in Account),
"+ Add Button / Add Feature", collapsed rows showing their content, every field shows something.
First `rowLabel` in the project → `pnpm payload generate:importmap`.
- Run the **ipal-audit** skill (`--quick`), fix every `[ERROR]`.
- Run the **iapl-audit** skill (`--quick`), fix every `[ERROR]`.
- Refactoring an existing block with renamed fields: **migrate the data first**
(old field → new), and only then remove the old fields (AGENT.md §6.7).
@@ -1,6 +1,6 @@
# Section code — ready files for the project
> Resources of the **ipal-block** skill. The rules (why, and what not to do) are in
> Resources of the **iapl-block** skill. The rules (why, and what not to do) are in
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6 — this file is only the code
> to create in the project **1:1**. Links (`buildLinkField`, `buildLinksField`,
> `resolveLink`), section fields (`buildSectionHeaderField`, `buildSectionSettingsField`) and the menu
@@ -325,7 +325,7 @@ The design-token standard (`node_modules/@intecion/ipal-kit/docs/design-tokens.m
`text-fg-strong`, `text-fg-muted`, `text-on-primary`, `border-border`, `text-link`, `outline-focus`, `text-h1`…,
`py-section`, `px-gutter`, `gap-gap`, `rounded-control`, `rounded-card`, `shadow-sm`, `max-w-container`.
**Never** hex, `bg-[#ff6600]`, `var(--color-…)`, or `dark:` for colours (the roles switch with the theme).
- The brand is `src/design/tokens.ts` → `pnpm exec ipal-tokens` → `src/design/tokens.css`; `DESIGN.md` describes it.
- The brand is `src/design/tokens.ts` → `pnpm exec iapl-tokens` → `src/design/tokens.css`; `DESIGN.md` describes it.
- Fonts via `next/font` with `variable: '--font-family-body'` / `'--font-family-heading'` on `<html>`.
- No CSS Modules and no `style={{…}}` — exception: a dynamic value from data.
- Visual variants → `Record<Variant, string>` (§6.3), not ternary chains.
@@ -336,7 +336,7 @@ The design-token standard (`node_modules/@intecion/ipal-kit/docs/design-tokens.m
@import "@intecion/ipal-kit/fluid-wide.css";
@import "@intecion/ipal-kit/tokens.css";
@import "@intecion/ipal-kit/tailwind.css";
@import "../../design/tokens.css"; /* generated by ipal-tokens from src/design/tokens.ts */
@import "../../design/tokens.css"; /* generated by iapl-tokens from src/design/tokens.ts */
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";
```
@@ -1,12 +1,12 @@
---
name: ipal-collection
description: Decides whether something should be a Payload collection, a global, or a block, and builds a content collection the ipal-kit way (title, buildSlugField, SEO tab, buildNoindexField, trackSlugHistoryHook, revalidate hook, archive page from System pages, sitemap and routing via content option). Use when the user asks for a blog, news, products, portfolio, testimonials, authors, categories, or any new collection — and whenever you are about to create a file in src/collections.
name: iapl-collection
description: Decides whether something should be a Payload collection, a global, or a block, and builds a content collection the IAPL way (title, buildSlugField, SEO tab, buildNoindexField, trackSlugHistoryHook, revalidate hook, archive page from System pages, sitemap and routing via content option). Use when the user asks for a blog, news, products, portfolio, testimonials, authors, categories, or any new collection — and whenever you are about to create a file in src/collections.
---
# ipal-collection
# iapl-collection
**ipal-kit first (hard rule, AGENT.md "ipal-kit first"):** anything the plugin covers is built with the
plugin's feature. It does not work or is not enough → report it with **ipal-plugin-gap** and wait for the owner's
**IAPL first (hard rule, AGENT.md "IAPL first"):** anything the plugin covers is built with the
plugin's feature. It does not work or is not enough → report it with **iapl-plugin-gap** and wait for the owner's
decision on that part; no hand-built replacement, no silent workaround. **Code rules:** AGENT.md "Code rules"
(one job per file/component/function, no duplicates, typed, texts from the panel, a check for new behaviour).
@@ -22,7 +22,7 @@ Answer these 4 questions for the user — all must be YES:
Any NO → it is not a collection:
- one set of data (company, menu, footer, settings) → **global**,
- part of a page (FAQ, hero, testimonials in a section) → **block** (ipal-block skill),
- part of a page (FAQ, hero, testimonials in a section) → **block** (iapl-block skill),
- `users` → the plugin injects it when the project has none; create your own collection with that slug
only to add fields (it wins over the injected one; roles and 2FA attach to it).
@@ -46,11 +46,19 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
**No URL prefix in code** — the editor assigns the archive page in
Site settings (`<slug>Archive`). The plugin handles routing, sitemap,
generateStaticParams, hreflang.
**With drafts** (`versions: { drafts: true }`): `access: { read: readPublished(), readVersions: readPublished() }`
— Payload's open `read: () => true` answers `?draft=true` with the draft over REST and GraphQL. Check:
`curl -i <site>/api/<slug>/<draft id>?draft=true` without a session → `404`; the same with an editor's token → the draft.
3. Entry list = a block (EntriesList) with `getEntries`; the entry page uses
`resolveRoute` (type `entry`); JSON-LD per seo.md (e.g. Article).
4. `pnpm generate:types`, `pnpm payload generate:importmap`.
5. Postgres with migrations → `pnpm payload migrate:create`.
4. **An auth collection for visitors** (`auth: true`: customers, members) only when the client requires it
(AGENT.md §5 "A second auth collection"): `admin: { user: 'users' }` in `buildConfig`, `access` with
`adminOrSelfIn('<slug>')` for read / update and an explicit `create`, never in `access.staffCollections`.
Its accounts pass none of the plugin's staff checks, and 2FA (setup required included) does not apply to them. Check: its token → `403` from
`/api/globals/site-integrations` and `/api/form-submissions`.
5. `pnpm generate:types`, `pnpm payload generate:importmap`.
6. Postgres with migrations → `pnpm payload migrate:create`.
## 4. Check
The **ipal-audit** skill. By hand: an entry in the panel → visible at `/<locale>/<archive>/<slug>`,
The **iapl-audit** skill. By hand: an entry in the panel → visible at `/<locale>/<archive>/<slug>`,
in the sitemap; changing the slug → 308 from the old address.
@@ -1,9 +1,9 @@
---
name: ipal-consent-check
description: Proves in a real browser (Playwright) that an ipal-kit site respects cookie consent — no Meta/Clarity/LinkedIn/TikTok/Ads requests and no tracking cookies before a decision or after "reject", Google only with Consent Mode "denied" signals, tags starting after "accept". Use after adding analytics, pixels, embeds (YouTube, maps, chat) or third-party scripts, before handing a site over, and whenever GDPR/RODO or cookie banner behaviour is in question.
name: iapl-consent-check
description: Proves in a real browser (Playwright) that an IAPL site respects cookie consent — no Meta/Clarity/LinkedIn/TikTok/Ads requests and no tracking cookies before a decision or after "reject", Google only with Consent Mode "denied" signals, tags starting after "accept", Global Privacy Control honoured, "Reject" as prominent as "Accept all", withdrawal deleting the cookies. Use after adding analytics, pixels, embeds (YouTube, maps, chat) or third-party scripts, before handing a site over, and whenever GDPR/RODO or cookie banner behaviour is in question.
---
# ipal-consent-check
# iapl-consent-check
GDPR: non-Google tags load **only after consent**; Google (GA4/GTM) may
load earlier only with the Consent Mode "denied" signal and without cookies.
@@ -19,11 +19,12 @@ before analytics or marketing consent — check the project's choice in "Project
2. Start the app (`pnpm build && pnpm start`) and check **a page with tags**
(ideally the homepage and a page with a form/video):
```bash
node .agents/skills/ipal-consent-check/scripts/consent-check.mjs http://localhost:3000/pl
node .agents/skills/iapl-consent-check/scripts/consent-check.mjs http://localhost:3000/pl
```
`--wait 6000` when tags start slowly (`defer` mode in Analytics).
3. Output: three runs in clean profiles — no decision, "Accept",
"Reject" + reload. Every `[ERROR]` is a violation — fix it:
3. Output: five runs in clean profiles — no decision, "Accept", "Reject" + reload, **Global Privacy Control**
(`Sec-GPC: 1` and `navigator.globalPrivacyControl`), "Accept" then withdraw (cookie button → "Reject").
Every `[ERROR]` is a violation — fix it:
| Violation | Cause → fix |
|---|---|
@@ -31,19 +32,36 @@ before analytics or marketing consent — check the project's choice in "Project
| tracking cookie set without consent | same; or GTM fires a tag without an `ad_storage` condition (analytics.md → GTM) |
| GA hit with consent GRANTED | `setDefaultConsent` not before the tag — `<Analytics>` must be inside `<ConsentProvider>` (`SiteProviders` does this itself) |
| YouTube / Maps before consent (warning) | `ConsentScript` (consent.md), `youtube-nocookie.com` or "click to load" |
| "Reject" is not as prominent as "Accept all" / no "Reject" on the first layer | `equalChoice={false}`, a `rejectButton` class or an `order` without `'reject'` in the layout → remove it (the default is equal; consent.md → "Compliance defaults") |
| Global Privacy Control: the Google tag loaded | IAPL before 1.17.0, a hand-made tag loader, or GTM started by hand → update; `<Analytics>` from the plugin |
| Global Privacy Control: banner shown (warning) | `gpc="ask"` / `gpc={false}` in the layout — fine only if it is a recorded project decision |
| withdraw: tracking cookie still set | the cookie is not in `DEFAULT_COOKIE_MAP`, `cookieMap` or the panel's cookie list → add it to the list (scan → approve) or `<ConsentProvider cookieMap>` |
| YouTube thumbnail / Google Fonts / Maps API before a choice (warning) | `<YouTubeEmbed poster>` with an uploaded poster; fonts through `next/font`; maps behind `ConsentScript` or click-to-load |
4. The "after accept" section shows what starts after consent — compare it with the IDs in Site
Integrations (e.g. is Meta Pixel there, if the client has one). Nothing starts
but IDs are filled in → report it as a problem to diagnose (**ipal-debug**).
but IDs are filled in → report it as a problem to diagnose (**iapl-debug**).
5. Banner not found (`data-ipal="banner"`) → `<CookieBanner/>` is not
rendered, or an older ipal-kit version without `data-ipal` attributes on the buttons → **ipal-upgrade**.
rendered, or an older IAPL version without `data-ipal` attributes on the buttons → **iapl-upgrade**.
6. Banner at first paint (1.17.0, consent.md → "First paint"): the banner is in the server HTML and an inline
script shows or hides it before the browser paints; pages stay static.
```bash
curl -s http://localhost:3000/pl | grep -c 'data-ipal="banner-script"' # 1
curl -sI http://localhost:3000/pl | grep -i cache-control # still s-maxage=… (static / ISR)
```
`0` → `firstPaint={false}`, a custom banner, or a wrapper that renders the banner only after mount
(remove it). Under a nonce CSP the browser console must not report the inline script as refused: pass
`nonce` to `<SiteProviders>`. A visitor who decided must never see the banner on reload; one whose
decision is from an older Policy version must see it at once. A click on a button before hydration
counts (the checks above click as soon as the button is visible).
The script needs buttons with `data-ipal="accept"` / `"reject"` — the plugin's
`CookieBanner` has them in every `settings` mode (`inline`, `modal`, `detailed`). A custom banner in the project violates AGENT.md §7.
## Cookie list from the panel (`cookieScanner`)
When the project has `ipalKit({ cookieScanner: true })` (cookie-scanner.md), the editor fills the
When the project has `iapl({ cookieScanner: true })` (cookie-scanner.md), the editor fills the
list in the panel and you check it:
1. Not on yet → turn it on, `pnpm generate:importmap`, `pnpm payload migrate:create cookie-scanner`
@@ -51,7 +69,7 @@ list in the panel and you check it:
chat): add them as `cookieScanner.declarations` (or an `integrations` entry with `isEnabled`) —
never a hand-typed list in code.
2. *Privacy → Cookies → Review and approve* → **Scan cookies** (with `adminLayout: 'separate'`: *Privacy → Cookie review*). "Integrations in use" must match the IDs in Site
Integrations; a filled ID that is missing → **ipal-debug**.
Integrations; a filled ID that is missing → **iapl-debug**.
3. Run the browser scan below and paste every cookie it reports as unknown into **More cookie
names**, scan again. Cookies marked **Needs description** need provider, category and
purpose: ask the client, do not guess (Edit on the approval page opens the entry).
@@ -73,9 +91,9 @@ list in the panel and you check it:
When the project has `cookieScanner: { crawl: true }` (cookie-scanner.md → Browser crawl):
1. Not on yet and the client wants it → turn it on; env `IPAL_COOKIE_SCAN_URL` +
`IPAL_COOKIE_SCAN_TOKEN` (`openssl rand -hex 32`) in Coolify; ask the team to add
`<host>=<token>` to the scanner service's `IPAL_CRAWLER_SITES`; `generate:importmap`,
1. Not on yet and the client wants it → turn it on; env `IAPL_COOKIE_SCAN_URL` +
`IAPL_COOKIE_SCAN_TOKEN` (`openssl rand -hex 32`) in Coolify; ask the team to add
`<host>=<token>` to the scanner service's `IAPL_CRAWLER_SITES`; `generate:importmap`,
`migrate:create cookie-crawl`. Never add Playwright or Chromium to the site.
2. *Cookie review* → **Check site**. "Check site" disabled → the box names the missing variable.
Failed → *Privacy → Cookie check → Error* ("Could not reach the scanner service" = URL / DNS /
@@ -88,7 +106,7 @@ When the project has `cookieScanner: { crawl: true }` (cookie-scanner.md → Bro
before handover. A crawl never adds anything to the cookie banner by itself.
5. Optional: recipients in *Cookie check → Warning e-mails to* (the e-mail also says when cookies
wait for approval and links to the approval page), and a weekly Coolify scheduled task
`curl -X POST -H "Authorization: Bearer $IPAL_COOKIE_SCAN_TOKEN" $NEXT_PUBLIC_SERVER_URL/api/ipal/cookie-crawl`.
`curl -X POST -H "Authorization: Bearer $IAPL_COOKIE_SCAN_TOKEN" $NEXT_PUBLIC_SERVER_URL/api/ipal/cookie-crawl`.
Record both in `AGENTS.md` → "Project decisions".
## Cookie list for the cookie policy (cookie-scan)
@@ -99,7 +117,7 @@ unknown names to the panel scan above instead of step 2):
1. Scan the running site (without consent and after "Accept all", homepage + up to 10 pages from the sitemap):
```bash
node .agents/skills/ipal-consent-check/scripts/cookie-scan.mjs http://localhost:3000 --lang pl
node .agents/skills/iapl-consent-check/scripts/cookie-scan.mjs http://localhost:3000 --lang pl
```
Output: `cookie-scan/cookies.json` and `cookie-scan/cookies.md` (table). `[ERROR]` = a
**non-necessary cookie set before consent** — fix it as in the table above. `[WARNING] unknown` —
@@ -107,7 +125,7 @@ unknown names to the panel scan above instead of step 2):
in `cookies.json`. Do not guess — ask if you do not know.
2. Import into the panel (Cookies → Cookie list), each language separately (scan with `--lang en` for English):
```bash
LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json
LOCALE=pl pnpm payload run .agents/skills/iapl-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json
```
It merges by name and does not overwrite editor changes (`OVERWRITE=1` forces it). It does not delete cookies
the scan did not see — the editor does that in the panel. The same list feeds the

Some files were not shown because too many files have changed in this diff Show More