Compare commits
@@ -25,3 +25,81 @@ jobs:
|
||||
- run: pnpm lint
|
||||
- run: pnpm test:int
|
||||
- run: pnpm build
|
||||
|
||||
# The reference site (reference/, docs/dev/reference-site-proposal.md). Fast part on every push and PR:
|
||||
# install against the freshly built plugin, committed generated files current, typecheck.
|
||||
reference:
|
||||
runs-on: ubuntu-latest
|
||||
needs: check
|
||||
env:
|
||||
PAYLOAD_SECRET: ci-reference-secret-0123456789abcdef
|
||||
DATABASE_URI: mongodb://127.0.0.1:27017/example-studiopl_dev
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile --ignore-scripts
|
||||
- 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 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
|
||||
# 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:
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
needs: reference
|
||||
services:
|
||||
mongo:
|
||||
image: mongo:7
|
||||
ports: ['27017:27017']
|
||||
env:
|
||||
CI: '1'
|
||||
DATABASE_URI: mongodb://127.0.0.1:27017/example-studiopl_dev
|
||||
PAYLOAD_SECRET: ci-reference-secret-0123456789abcdef
|
||||
NEXT_PUBLIC_SERVER_URL: http://localhost:3100
|
||||
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'
|
||||
E2E_BASE_URL: http://localhost:3100
|
||||
E2E_ADMIN_EMAIL: [email protected]
|
||||
E2E_ADMIN_PASSWORD: ci-e2e-password-not-secret
|
||||
E2E_TOTP_SECRET: JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile --ignore-scripts
|
||||
- run: pnpm build
|
||||
- run: pnpm --dir reference install --frozen-lockfile --ignore-workspace
|
||||
- run: pnpm --dir reference seed
|
||||
# the documented production seed path (Coolify Terminal): one named record, dry run
|
||||
- run: SEED_ONLY="pages:kontakt" SEED_DRY_RUN=1 pnpm --dir reference seed
|
||||
- run: pnpm --dir reference payload run e2e/create-test-admin.ts
|
||||
- run: pnpm --dir reference build
|
||||
- run: pnpm --dir reference exec playwright install --with-deps chromium
|
||||
- run: pnpm --dir reference test:e2e
|
||||
# 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/iapl-doctor.mjs reference --strict --offline --deep --url http://localhost:3100
|
||||
|
||||
@@ -53,3 +53,8 @@ next-env.d.ts
|
||||
|
||||
# build output — produced by `pnpm build` (prepare/prepublishOnly), not committed
|
||||
/dist
|
||||
|
||||
# pnpm starter:gate work folder
|
||||
.starter-gate/
|
||||
.legacy-site-*/
|
||||
.tmp-consent-upgrade-*
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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/…`
|
||||
@@ -61,36 +63,49 @@ quick throwaway test it works. But prefer the registry for real projects:
|
||||
Keep the git install only for pulling a specific unreleased commit during
|
||||
plugin development.
|
||||
|
||||
### A new site in one command
|
||||
|
||||
```bash
|
||||
pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create intecion.com
|
||||
```
|
||||
|
||||
Asks the architecture questions (or reads `--answers answers.json`), generates the site from the reference
|
||||
site with every team convention, installs it from a shipped lockfile and makes the first commit. Needs the
|
||||
`@intecion` registry line in `~/.npmrc`. Details: [docs/project-starter.md](./docs/project-starter.md).
|
||||
|
||||
---
|
||||
|
||||
## Finish setting up your project
|
||||
|
||||
`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` and `dompurify` —
|
||||
add the two 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).
|
||||
|
||||
@@ -102,15 +117,25 @@ 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 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 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
|
||||
`node scripts/vendor-external-skills.mjs`, review `git diff docs/agent/external`, and run
|
||||
`pnpm vitest run test/externalSkills.test.ts`.
|
||||
|
||||
From here, the guide takes over: **[docs/dev/PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** —
|
||||
from an empty project to a working site.
|
||||
|
||||
@@ -141,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
|
||||
```
|
||||
|
||||
@@ -171,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
|
||||
|
||||
Executable
+102
@@ -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".`)
|
||||
Executable
+17
@@ -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 }))
|
||||
Executable
+211
@@ -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
|
||||
}
|
||||
}
|
||||
Executable
+13
@@ -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
@@ -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))
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env node
|
||||
// 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'
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env node
|
||||
// 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'
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env node
|
||||
// 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
-121
@@ -1,122 +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
|
||||
// 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).
|
||||
// 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 { 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]\nDefault dest: .agents/skills')
|
||||
process.exit(0)
|
||||
}
|
||||
const dryRun = args.includes('--dry-run')
|
||||
const pointer = !args.includes('--no-pointer')
|
||||
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)
|
||||
}
|
||||
|
||||
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}`)
|
||||
|
||||
// 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. If the plugin has it, use it. If an option is missing, use the `ipal-plugin-gap` skill — never patch `node_modules`.',
|
||||
'6. 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'
|
||||
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env node
|
||||
// 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'
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -0,0 +1 @@
|
||||
1.7.1
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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ßenbahn",
|
||||
"text": "Hello."
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"schema": "SendResponse",
|
||||
"body": {
|
||||
"ok": true,
|
||||
"replayed": false,
|
||||
"senderName": "Kancelaria Example",
|
||||
"warnings": []
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"mails": 1,
|
||||
"mail": {
|
||||
"subject": "👩💻 Straßenbahn"
|
||||
}
|
||||
},
|
||||
"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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,12 @@ export default async function LocaleLayout({ children, params }: Props) {
|
||||
<body>
|
||||
<SiteProviders banner={<CookieBanner controls="switch" equalChoice settings="detailed" />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)} stats={{ locale }}>
|
||||
<main>{children}</main>
|
||||
{/* A footer with links in the bottom-left corner: CookieButton must not cover them. */}
|
||||
<footer style={{ borderTop: '1px solid #e5e5e5', display: 'flex', gap: '1.5rem', marginTop: '60vh', padding: '1.5rem 1rem' }}>
|
||||
<a href={`/${locale}`}>Home</a>
|
||||
<a href={`/${locale}/kontakt`}>Kontakt</a>
|
||||
<a href={`/${locale}/polityka-prywatnosci`}>Polityka prywatności</a>
|
||||
</footer>
|
||||
</SiteProviders>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { TOTPField as TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
|
||||
import { OverviewComponent as OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
|
||||
import { MetaTitleComponent as MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
|
||||
import { MetaDescriptionComponent as MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
|
||||
@@ -33,15 +34,25 @@ import { IntegrationStatusBanner as IntegrationStatusBanner_7568fe47d582ff15ce85
|
||||
import { MaskedField as MaskedField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { TestEmailButton as TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { RowLabel as RowLabel_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CookieReviewTab as CookieReviewTab_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CookieSiteCheckTab as CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { AdminIcon as AdminIcon_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { AdminLogo as AdminLogo_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { IntecionCredit as IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { StatsNavLink as StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CookieCrawlAlert as CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { StatsWidget as StatsWidget_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { IntegrationAlerts as IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { TotpRedirectProvider as TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { TOTPSetup as TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
|
||||
import { TOTPVerify as TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
|
||||
import { CookieApprovalView as CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { StatsView as StatsView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
|
||||
|
||||
/** @type import('payload').ImportMap */
|
||||
export const importMap = {
|
||||
"@clocklimited/payload-2fa/rsc#TOTPField": TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128,
|
||||
"@payloadcms/plugin-seo/client#OverviewComponent": OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860,
|
||||
"@payloadcms/plugin-seo/client#MetaTitleComponent": MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860,
|
||||
"@payloadcms/plugin-seo/client#MetaDescriptionComponent": MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860,
|
||||
@@ -77,10 +88,19 @@ export const importMap = {
|
||||
"@intecion/ipal-kit/admin#MaskedField": MaskedField_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#TestEmailButton": TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#RowLabel": RowLabel_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#CookieReviewTab": CookieReviewTab_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#CookieSiteCheckTab": CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#AdminIcon": AdminIcon_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#AdminLogo": AdminLogo_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#IntecionCredit": IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#StatsNavLink": StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#CookieCrawlAlert": CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#StatsWidget": StatsWidget_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#IntegrationAlerts": IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#TotpRedirectProvider": TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@clocklimited/payload-2fa/rsc#TOTPSetup": TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128,
|
||||
"@clocklimited/payload-2fa/rsc#TOTPVerify": TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128,
|
||||
"@intecion/ipal-kit/admin#CookieApprovalView": CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#StatsView": StatsView_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
|
||||
}
|
||||
|
||||
@@ -1238,7 +1238,7 @@ export interface SiteSetting {
|
||||
/**
|
||||
* Separates the page title from the site name in browser tabs.
|
||||
*/
|
||||
titleSeparator?: ('|' | '–' | '-' | '·' | '/') | null;
|
||||
titleSeparator?: ('pipe' | 'endash' | 'hyphen' | 'middot' | 'slash') | null;
|
||||
/**
|
||||
* Primary site logo.
|
||||
*/
|
||||
@@ -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?:
|
||||
| {
|
||||
|
||||
@@ -1,6 +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'
|
||||
@@ -63,17 +64,20 @@ 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.
|
||||
twoFactor: false,
|
||||
// IPAL_DEV_2FA=1 turns it on (first-login setup and verify screens).
|
||||
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,
|
||||
}),
|
||||
],
|
||||
secret: process.env.PAYLOAD_SECRET || 'test-secret_key',
|
||||
|
||||
+1881
-2
File diff suppressed because it is too large
Load Diff
+11
-6
@@ -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:
|
||||
|
||||
@@ -23,14 +23,17 @@ API details — one file per module:
|
||||
| Accessibility widget (optional) | [accessibility.md](./accessibility.md) |
|
||||
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
|
||||
| Blocks, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
|
||||
| Cookie consent, banner, settings window (in the bar / modal / large with cookie details) | [consent.md](./consent.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), 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 (`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) |
|
||||
@@ -50,8 +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`, `iapl-tokens`, DESIGN.md) | [design-tokens.md](./design-tokens.md) |
|
||||
| R2, `buildImagesConfig`, `MediaPreconnect`, `YouTubeEmbed` | [storage.md](./storage.md) |
|
||||
| Turnstile | [turnstile.md](./turnstile.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
@@ -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.
|
||||
|
||||
+12
-3
@@ -75,8 +75,14 @@ the plugin only needs `A11yTexts` for the current locale.
|
||||
|
||||
## 2. CSS that reacts to the attributes (MANDATORY — project)
|
||||
|
||||
The widget sets attributes on `<html>`. Without this CSS nothing happens. Copy it
|
||||
into the project's global CSS (adapt it to the design):
|
||||
The widget sets attributes on `<html>`. Without CSS for them nothing happens.
|
||||
|
||||
**Ready file (1.15.0):** `@import "@intecion/ipal-kit/a11y.css";` in `styles.css` — the rules below, working through
|
||||
the design tokens ([design-tokens.md](./design-tokens.md)): the readable font swaps `--ipal-font-body/-heading` (set
|
||||
`--ipal-font-readable` to change it), "no animations" zeroes the `--ipal-duration-*` tokens, contrast + grayscale
|
||||
combine, the big cursor is built in. Check: tick each option in the widget and see the page change.
|
||||
|
||||
Or copy this into the project's global CSS (adapt it to the design):
|
||||
|
||||
```css
|
||||
/* Text size */
|
||||
@@ -166,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`
|
||||
@@ -216,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
|
||||
|
||||
+634
-168
File diff suppressed because it is too large
Load Diff
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Addy Osmani
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+475
@@ -0,0 +1,475 @@
|
||||
---
|
||||
name: ext-accessibility
|
||||
description: Audit and improve web accessibility following WCAG 2.2 guidelines. Use when asked to "improve accessibility", "a11y audit", "WCAG compliance", "screen reader support", "keyboard navigation", or "make accessible".
|
||||
license: MIT
|
||||
metadata:
|
||||
author: web-quality-skills
|
||||
version: "2.0"
|
||||
---
|
||||
|
||||
> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
|
||||
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`, the project's `AGENTS.md` or `DESIGN.md`, those win:
|
||||
> ipal-kit features first (the `ipal-reference` skill), Payload 3 + Next 16 App Router, data from Server Components
|
||||
> through Payload / `@/lib/content`, every visible text from the CMS, design values from `DESIGN.md` tokens.
|
||||
> Never add a dependency this skill suggests without the owner's decision.
|
||||
>
|
||||
> **Tools:** never run `npx lighthouse` / `npx @axe-core/cli` unpinned — add them as devDependencies at fixed versions
|
||||
> first. Use the ipal-kit components (CookieBanner, AccessibilityWidget, RenderForm…) and fix their markup through
|
||||
> their props or a plugin gap report, not by copying them.
|
||||
|
||||
|
||||
# Accessibility (a11y)
|
||||
|
||||
Comprehensive accessibility guidelines based on WCAG 2.2 and Lighthouse accessibility audits. Goal: make content usable by everyone, including people with disabilities.
|
||||
|
||||
## Evidence-led audit workflow
|
||||
|
||||
When a rendered page is available:
|
||||
|
||||
1. Run a live Lighthouse Accessibility audit when that capability is available; with Chrome DevTools MCP, use `lighthouse_audit`. Use mobile navigation mode for a general public page or snapshot mode when reloading would lose authenticated or user-created state.
|
||||
2. Use failed audit nodes to localize the relevant component or template instead of searching the whole repository for generic patterns.
|
||||
3. Inspect a rendered accessibility-tree snapshot for names, roles, states, landmarks, and heading structure; with Chrome DevTools MCP, use `take_snapshot`. Exercise the affected flow with the keyboard.
|
||||
4. Fix the source, then re-run the same audit and manual interaction.
|
||||
|
||||
If the live tools are unavailable, use Lighthouse CLI or axe for automated coverage and complete the same manual checks. Automated tools detect only a subset of accessibility barriers: a score of 100 is not WCAG conformance, and a low score does not replace issue-level evidence.
|
||||
|
||||
## WCAG Principles: POUR
|
||||
|
||||
| Principle | Description |
|
||||
|-----------|-------------|
|
||||
| **P**erceivable | Content can be perceived through different senses |
|
||||
| **O**perable | Interface can be operated by all users |
|
||||
| **U**nderstandable | Content and interface are understandable |
|
||||
| **R**obust | Content works with assistive technologies |
|
||||
|
||||
## Conformance levels
|
||||
|
||||
| Level | Requirement | Target |
|
||||
|-------|-------------|--------|
|
||||
| **A** | Minimum accessibility | Must pass |
|
||||
| **AA** | Standard compliance | Should pass (legal requirement in many jurisdictions) |
|
||||
| **AAA** | Enhanced accessibility | Nice to have |
|
||||
|
||||
---
|
||||
|
||||
## Perceivable
|
||||
|
||||
### Text alternatives (1.1)
|
||||
|
||||
**Images require alt text:**
|
||||
```html
|
||||
<!-- ❌ Missing alt -->
|
||||
<img src="chart.png">
|
||||
|
||||
<!-- ✅ Descriptive alt -->
|
||||
<img src="chart.png" alt="Bar chart showing 40% increase in Q3 sales">
|
||||
|
||||
<!-- ✅ Decorative image (empty alt) -->
|
||||
<img src="decorative-border.png" alt="" role="presentation">
|
||||
|
||||
<!-- ✅ Complex image with longer description -->
|
||||
<figure>
|
||||
<img src="infographic.png" alt="2024 market trends infographic"
|
||||
aria-describedby="infographic-desc">
|
||||
<figcaption id="infographic-desc">
|
||||
<!-- Detailed description -->
|
||||
</figcaption>
|
||||
</figure>
|
||||
```
|
||||
|
||||
**Icon buttons need accessible names:**
|
||||
```html
|
||||
<!-- ❌ No accessible name -->
|
||||
<button><svg><!-- menu icon --></svg></button>
|
||||
|
||||
<!-- ✅ Using aria-label -->
|
||||
<button aria-label="Open menu">
|
||||
<svg aria-hidden="true"><!-- menu icon --></svg>
|
||||
</button>
|
||||
|
||||
<!-- ✅ Using visually hidden text -->
|
||||
<button>
|
||||
<svg aria-hidden="true"><!-- menu icon --></svg>
|
||||
<span class="visually-hidden">Open menu</span>
|
||||
</button>
|
||||
```
|
||||
|
||||
**Visually hidden class:**
|
||||
```css
|
||||
.visually-hidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
```
|
||||
|
||||
### Color contrast (1.4.3, 1.4.6)
|
||||
|
||||
| Text Size | AA minimum | AAA enhanced |
|
||||
|-----------|------------|--------------|
|
||||
| Normal text (< 18px / < 14px bold) | 4.5:1 | 7:1 |
|
||||
| Large text (≥ 18px / ≥ 14px bold) | 3:1 | 4.5:1 |
|
||||
| UI components & graphics | 3:1 | 3:1 |
|
||||
|
||||
```css
|
||||
/* ❌ Low contrast (2.5:1) */
|
||||
.low-contrast {
|
||||
color: #999;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
/* ✅ Sufficient contrast (7:1) */
|
||||
.high-contrast {
|
||||
color: #333;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
/* ✅ Focus states need contrast too (3:1 against background, WCAG 1.4.11) */
|
||||
:focus-visible {
|
||||
outline: 2px solid currentColor;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
```
|
||||
|
||||
**Don't rely on color alone:**
|
||||
```html
|
||||
<!-- ❌ Only color indicates error -->
|
||||
<input class="error-border">
|
||||
<style>.error-border { border-color: red; }</style>
|
||||
|
||||
<!-- ✅ Color + icon + text -->
|
||||
<div class="field-error">
|
||||
<input aria-invalid="true" aria-describedby="email-error">
|
||||
<span id="email-error" class="error-message">
|
||||
<svg aria-hidden="true"><!-- error icon --></svg>
|
||||
Please enter a valid email address
|
||||
</span>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Media alternatives (1.2)
|
||||
|
||||
```html
|
||||
<!-- Video with captions -->
|
||||
<video controls>
|
||||
<source src="video.mp4" type="video/mp4">
|
||||
<track kind="captions" src="captions.vtt" srclang="en" label="English" default>
|
||||
<track kind="descriptions" src="descriptions.vtt" srclang="en" label="Descriptions">
|
||||
</video>
|
||||
|
||||
<!-- Audio with transcript -->
|
||||
<audio controls>
|
||||
<source src="podcast.mp3" type="audio/mp3">
|
||||
</audio>
|
||||
<details>
|
||||
<summary>Transcript</summary>
|
||||
<p>Full transcript text...</p>
|
||||
</details>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Operable
|
||||
|
||||
### Keyboard accessible (2.1)
|
||||
|
||||
**All functionality must be keyboard accessible.** Prefer native interactive elements — `<button>`, `<a href>`, and form controls handle Enter/Space activation, focus, and assistive-tech semantics for free. Only add manual keyboard handling when you cannot use a native element.
|
||||
|
||||
```html
|
||||
<!-- ❌ Non-interactive element with click only: not focusable, no keyboard activation -->
|
||||
<div class="card" onclick="handleAction()">Open</div>
|
||||
|
||||
<!-- ✅ Best: use a native button -->
|
||||
<button type="button" onclick="handleAction()">Open</button>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// ✅ When you MUST use a non-interactive element (e.g. div with role="button"),
|
||||
// make it focusable AND handle keyboard activation. Do NOT add this to a native
|
||||
// <button> — Enter/Space already fire click, so you'd double-trigger.
|
||||
element.setAttribute('role', 'button');
|
||||
element.setAttribute('tabindex', '0');
|
||||
element.addEventListener('click', handleAction);
|
||||
element.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleAction();
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**No keyboard traps.** Users must be able to Tab into and out of every component. Use the [modal focus trap pattern](references/A11Y-PATTERNS.md#modal-focus-trap) for dialogs—the native `<dialog>` element handles this automatically.
|
||||
|
||||
### Focus visible (2.4.7)
|
||||
|
||||
```css
|
||||
/* ❌ Never remove focus outlines */
|
||||
*:focus { outline: none; }
|
||||
|
||||
/* ✅ Use :focus-visible for keyboard-only focus */
|
||||
:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
:focus-visible {
|
||||
outline: 2px solid currentColor; /* inherits text color → already contrast-checked */
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ✅ Or pick a brand color and verify ≥3:1 contrast against every background it lands on */
|
||||
button:focus-visible {
|
||||
box-shadow: 0 0 0 3px rgba(0, 95, 204, 0.5);
|
||||
}
|
||||
```
|
||||
|
||||
### Focus not obscured (2.4.11) — new in 2.2
|
||||
|
||||
When an element receives keyboard focus, it must not be entirely hidden by other author-created content such as sticky headers, footers, or overlapping panels. At Level AAA (2.4.12), no part of the focused element may be hidden.
|
||||
|
||||
```css
|
||||
/* ✅ Account for sticky headers when scrolling to focused elements */
|
||||
:target {
|
||||
scroll-margin-top: 80px;
|
||||
}
|
||||
|
||||
/* ✅ Ensure focused items clear fixed/sticky bars */
|
||||
:focus {
|
||||
scroll-margin-top: 80px;
|
||||
scroll-margin-bottom: 60px;
|
||||
}
|
||||
```
|
||||
|
||||
### Skip links (2.4.1)
|
||||
|
||||
Provide a skip link so keyboard users can bypass repetitive navigation. See the [skip link pattern](references/A11Y-PATTERNS.md#skip-link) for full markup and styles.
|
||||
|
||||
### Target size (2.5.8) — new in 2.2
|
||||
|
||||
Interactive targets must be at least **24 × 24 CSS pixels** (AA). Exceptions: inline text links, elements where the browser controls the size, and targets where a 24px circle centered on the bounding box does not overlap another target.
|
||||
|
||||
```css
|
||||
/* ✅ Minimum target size */
|
||||
button,
|
||||
[role="button"],
|
||||
input[type="checkbox"] + label,
|
||||
input[type="radio"] + label {
|
||||
min-width: 24px;
|
||||
min-height: 24px;
|
||||
}
|
||||
|
||||
/* ✅ Comfortable target size (recommended 44×44) */
|
||||
.touch-target {
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
```
|
||||
|
||||
### Dragging movements (2.5.7) — new in 2.2
|
||||
|
||||
Any action that requires dragging must have a single-pointer alternative (e.g., buttons, inputs). See the [dragging movements pattern](references/A11Y-PATTERNS.md#dragging-movements) for a sortable-list example.
|
||||
|
||||
### Timing (2.2)
|
||||
|
||||
```javascript
|
||||
// Allow users to extend time limits
|
||||
function showSessionWarning() {
|
||||
const modal = createModal({
|
||||
title: 'Session Expiring',
|
||||
content: 'Your session will expire in 2 minutes.',
|
||||
actions: [
|
||||
{ label: 'Extend session', action: extendSession },
|
||||
{ label: 'Log out', action: logout }
|
||||
],
|
||||
timeout: 120000
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Motion (2.3)
|
||||
|
||||
```css
|
||||
/* Respect reduced motion preference */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Understandable
|
||||
|
||||
### Page language (3.1.1)
|
||||
|
||||
```html
|
||||
<!-- ❌ No language specified -->
|
||||
<html>
|
||||
|
||||
<!-- ✅ Language specified -->
|
||||
<html lang="en">
|
||||
|
||||
<!-- ✅ Language changes within page -->
|
||||
<p>The French word for hello is <span lang="fr">bonjour</span>.</p>
|
||||
```
|
||||
|
||||
### Consistent navigation (3.2.3)
|
||||
|
||||
```html
|
||||
<!-- Navigation should be consistent across pages -->
|
||||
<nav aria-label="Main">
|
||||
<ul>
|
||||
<li><a href="/" aria-current="page">Home</a></li>
|
||||
<li><a href="/products">Products</a></li>
|
||||
<li><a href="/about">About</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
```
|
||||
|
||||
### Consistent help (3.2.6) — new in 2.2
|
||||
|
||||
If a help mechanism (contact info, chat widget, FAQ link, self-help option) is repeated across multiple pages, it must appear in the **same relative order** each time. Users who rely on consistent placement shouldn't have to hunt for help on every page.
|
||||
|
||||
### Form labels (3.3.2)
|
||||
|
||||
Every input needs a programmatically associated label. See the [form labels pattern](references/A11Y-PATTERNS.md#form-labels) for explicit, implicit, and instructional examples.
|
||||
|
||||
### Error handling (3.3.1, 3.3.3)
|
||||
|
||||
Announce errors to screen readers with `role="alert"` or `aria-live`, set `aria-invalid="true"` on invalid fields, and focus the first error on submit. See the [error handling pattern](references/A11Y-PATTERNS.md#error-handling) for full markup and JS.
|
||||
|
||||
### Redundant entry (3.3.7) — new in 2.2
|
||||
|
||||
Don't force users to re-enter information they already provided in the same session. Auto-populate from earlier steps, or let users select from previously entered values. Exceptions: security re-confirmation and content that has expired.
|
||||
|
||||
```html
|
||||
<!-- ✅ Auto-fill shipping address from billing -->
|
||||
<fieldset>
|
||||
<legend>Shipping address</legend>
|
||||
<label>
|
||||
<input type="checkbox" id="same-as-billing" checked>
|
||||
Same as billing address
|
||||
</label>
|
||||
<!-- Fields auto-populated when checked -->
|
||||
</fieldset>
|
||||
```
|
||||
|
||||
### Accessible authentication (3.3.8) — new in 2.2
|
||||
|
||||
Login flows must not rely on cognitive function tests (e.g., remembering a password, solving a puzzle) unless at least one of:
|
||||
- A copy-paste or autofill mechanism is available
|
||||
- An alternative method exists (e.g., passkey, SSO, email link)
|
||||
- The test uses object recognition or personal content (AA only; AAA removes this exception)
|
||||
|
||||
```html
|
||||
<!-- ✅ Allow paste in password fields -->
|
||||
<input type="password" id="password" autocomplete="current-password">
|
||||
|
||||
<!-- ✅ Offer passwordless alternatives -->
|
||||
<button type="button">Sign in with passkey</button>
|
||||
<button type="button">Email me a login link</button>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Robust
|
||||
|
||||
### ARIA usage (4.1.2)
|
||||
|
||||
**Prefer native elements:**
|
||||
```html
|
||||
<!-- ❌ ARIA role on div -->
|
||||
<div role="button" tabindex="0">Click me</div>
|
||||
|
||||
<!-- ✅ Native button -->
|
||||
<button>Click me</button>
|
||||
|
||||
<!-- ❌ ARIA checkbox -->
|
||||
<div role="checkbox" aria-checked="false">Option</div>
|
||||
|
||||
<!-- ✅ Native checkbox -->
|
||||
<label><input type="checkbox"> Option</label>
|
||||
```
|
||||
|
||||
**When ARIA is needed,** use the correct roles and states. See the [ARIA tabs pattern](references/A11Y-PATTERNS.md#aria-tabs) for a complete tablist example.
|
||||
|
||||
### Live regions (4.1.3)
|
||||
|
||||
Use `aria-live` regions to announce dynamic content changes without moving focus. See the [live regions pattern](references/A11Y-PATTERNS.md#live-regions-and-notifications) for markup and a `showNotification()` helper.
|
||||
|
||||
---
|
||||
|
||||
## Testing checklist
|
||||
|
||||
### Automated testing
|
||||
|
||||
Prefer a live Lighthouse audit that returns failing rendered nodes directly to the agent. With Chrome DevTools MCP, this is `lighthouse_audit`. Otherwise:
|
||||
|
||||
```bash
|
||||
# Lighthouse accessibility audit
|
||||
npx lighthouse https://example.com --only-categories=accessibility
|
||||
|
||||
# axe-core
|
||||
npm install @axe-core/cli -g
|
||||
axe https://example.com
|
||||
```
|
||||
|
||||
### Manual testing
|
||||
|
||||
- [ ] **Keyboard navigation:** Tab through entire page, use Enter/Space to activate
|
||||
- [ ] **Screen reader:** Test with VoiceOver (Mac), NVDA (Windows), or TalkBack (Android)
|
||||
- [ ] **Zoom:** Content usable at 200% zoom
|
||||
- [ ] **High contrast:** Test with Windows High Contrast Mode
|
||||
- [ ] **Reduced motion:** Test with `prefers-reduced-motion: reduce`
|
||||
- [ ] **Focus order:** Logical and follows visual order
|
||||
- [ ] **Target size:** Interactive elements meet 24×24px minimum
|
||||
|
||||
See the [screen reader commands reference](references/A11Y-PATTERNS.md#screen-reader-commands) for VoiceOver and NVDA shortcuts.
|
||||
|
||||
---
|
||||
|
||||
## Common issues by impact
|
||||
|
||||
### Critical (fix immediately)
|
||||
1. Missing form labels
|
||||
2. Missing image alt text
|
||||
3. Insufficient color contrast
|
||||
4. Keyboard traps
|
||||
5. No focus indicators
|
||||
|
||||
### Serious (fix before launch)
|
||||
1. Missing page language
|
||||
2. Missing heading structure
|
||||
3. Non-descriptive link text
|
||||
4. Auto-playing media
|
||||
5. Missing skip links
|
||||
|
||||
### Moderate (fix soon)
|
||||
1. Missing ARIA labels on icons
|
||||
2. Inconsistent navigation
|
||||
3. Missing error identification
|
||||
4. Timing without controls
|
||||
5. Missing landmark regions
|
||||
|
||||
## References
|
||||
|
||||
- [WCAG 2.2 Quick Reference](https://www.w3.org/WAI/WCAG22/quickref/)
|
||||
- [WAI-ARIA Authoring Practices](https://www.w3.org/WAI/ARIA/apg/)
|
||||
- [Deque axe Rules](https://dequeuniversity.com/rules/axe/)
|
||||
- [Web Quality Audit](../web-quality-audit/SKILL.md)
|
||||
- [WCAG criteria reference](references/WCAG.md)
|
||||
- [Accessibility code patterns](references/A11Y-PATTERNS.md)
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
# ext-accessibility
|
||||
|
||||
Vendored by @intecion/ipal-kit (`ipal-skills --external`). Do not edit — regenerate with
|
||||
`scripts/vendor-external-skills.mjs` in the ipal-kit repository.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Publisher | Addy Osmani |
|
||||
| Source | https://github.com/addyosmani/web-quality-skills/tree/afa8da942115f2961fdbfa80807ea0b232ff6c00/skills/accessibility |
|
||||
| Commit | `afa8da942115f2961fdbfa80807ea0b232ff6c00` |
|
||||
| Licence | MIT (see the LICENSE file in this folder) |
|
||||
|
||||
Changes from the upstream text: the `name` in the SKILL.md frontmatter is `ext-accessibility`, and an
|
||||
override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
|
||||
@@ -0,0 +1,233 @@
|
||||
# Accessibility Code Patterns
|
||||
|
||||
Practical, copy-paste-ready patterns for common accessibility requirements. Each pattern is self-contained and linked from the main [SKILL.md](../SKILL.md).
|
||||
|
||||
---
|
||||
|
||||
## Modal focus trap
|
||||
|
||||
Trap keyboard focus inside a modal dialog so Tab/Shift+Tab cycle through its focusable elements and Escape closes it.
|
||||
|
||||
```javascript
|
||||
function openModal(modal) {
|
||||
const focusableElements = modal.querySelectorAll(
|
||||
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
|
||||
);
|
||||
const firstElement = focusableElements[0];
|
||||
const lastElement = focusableElements[focusableElements.length - 1];
|
||||
|
||||
modal.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Tab') {
|
||||
if (e.shiftKey && document.activeElement === firstElement) {
|
||||
e.preventDefault();
|
||||
lastElement.focus();
|
||||
} else if (!e.shiftKey && document.activeElement === lastElement) {
|
||||
e.preventDefault();
|
||||
firstElement.focus();
|
||||
}
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
closeModal();
|
||||
}
|
||||
});
|
||||
|
||||
firstElement.focus();
|
||||
}
|
||||
```
|
||||
|
||||
The native `<dialog>` element handles focus trapping automatically—prefer it when browser support allows.
|
||||
|
||||
---
|
||||
|
||||
## Skip link
|
||||
|
||||
Allows keyboard users to bypass repetitive navigation and jump straight to main content.
|
||||
|
||||
```html
|
||||
<body>
|
||||
<a href="#main-content" class="skip-link">Skip to main content</a>
|
||||
<header><!-- navigation --></header>
|
||||
<main id="main-content" tabindex="-1">
|
||||
<!-- main content -->
|
||||
</main>
|
||||
</body>
|
||||
```
|
||||
|
||||
```css
|
||||
.skip-link {
|
||||
position: absolute;
|
||||
top: -40px;
|
||||
left: 0;
|
||||
background: #000;
|
||||
color: #fff;
|
||||
padding: 8px 16px;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.skip-link:focus {
|
||||
top: 0;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error handling
|
||||
|
||||
Announce errors to screen readers and focus the first invalid field on submit.
|
||||
|
||||
```html
|
||||
<form novalidate>
|
||||
<div class="field" aria-live="polite">
|
||||
<label for="email">Email</label>
|
||||
<input type="email" id="email"
|
||||
aria-invalid="true"
|
||||
aria-describedby="email-error">
|
||||
<p id="email-error" class="error" role="alert">
|
||||
Please enter a valid email address (e.g., name@example.com)
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
```
|
||||
|
||||
```javascript
|
||||
form.addEventListener('submit', (e) => {
|
||||
const firstError = form.querySelector('[aria-invalid="true"]');
|
||||
if (firstError) {
|
||||
e.preventDefault();
|
||||
firstError.focus();
|
||||
|
||||
const errorSummary = document.getElementById('error-summary');
|
||||
errorSummary.textContent =
|
||||
`${errors.length} errors found. Please fix them and try again.`;
|
||||
errorSummary.focus();
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Form labels
|
||||
|
||||
Every input needs an associated label—either explicit (`for`/`id`) or implicit (wrapping `<label>`).
|
||||
|
||||
```html
|
||||
<!-- ❌ No label association -->
|
||||
<input type="email" placeholder="Email">
|
||||
|
||||
<!-- ✅ Explicit label -->
|
||||
<label for="email">Email address</label>
|
||||
<input type="email" id="email" name="email"
|
||||
autocomplete="email" required>
|
||||
|
||||
<!-- ✅ Implicit label -->
|
||||
<label>
|
||||
Email address
|
||||
<input type="email" name="email" autocomplete="email" required>
|
||||
</label>
|
||||
|
||||
<!-- ✅ With instructions -->
|
||||
<label for="password">Password</label>
|
||||
<input type="password" id="password"
|
||||
aria-describedby="password-requirements">
|
||||
<p id="password-requirements">
|
||||
Must be at least 8 characters with one number.
|
||||
</p>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Dragging movements
|
||||
|
||||
Any action triggered by dragging must offer a single-pointer alternative (WCAG 2.5.7).
|
||||
|
||||
```html
|
||||
<!-- ❌ Drag-only reorder -->
|
||||
<ul class="sortable-list" draggable="true">
|
||||
<li>Item 1</li>
|
||||
<li>Item 2</li>
|
||||
</ul>
|
||||
|
||||
<!-- ✅ Drag + button alternatives -->
|
||||
<ul class="sortable-list">
|
||||
<li>
|
||||
<span>Item 1</span>
|
||||
<button aria-label="Move Item 1 up">↑</button>
|
||||
<button aria-label="Move Item 1 down">↓</button>
|
||||
</li>
|
||||
<li>
|
||||
<span>Item 2</span>
|
||||
<button aria-label="Move Item 2 up">↑</button>
|
||||
<button aria-label="Move Item 2 down">↓</button>
|
||||
</li>
|
||||
</ul>
|
||||
```
|
||||
|
||||
Also applies to sliders, map panning, colour pickers, and similar drag-based widgets—always provide an equivalent click/tap or keyboard path.
|
||||
|
||||
---
|
||||
|
||||
## ARIA tabs
|
||||
|
||||
Tabs require `role="tablist"`, `role="tab"`, and `role="tabpanel"` with proper `aria-selected`, `aria-controls`, and keyboard support.
|
||||
|
||||
```html
|
||||
<div role="tablist" aria-label="Product information">
|
||||
<button role="tab" id="tab-1" aria-selected="true"
|
||||
aria-controls="panel-1">Description</button>
|
||||
<button role="tab" id="tab-2" aria-selected="false"
|
||||
aria-controls="panel-2" tabindex="-1">Reviews</button>
|
||||
</div>
|
||||
<div role="tabpanel" id="panel-1" aria-labelledby="tab-1">
|
||||
<!-- Panel content -->
|
||||
</div>
|
||||
<div role="tabpanel" id="panel-2" aria-labelledby="tab-2" hidden>
|
||||
<!-- Panel content -->
|
||||
</div>
|
||||
```
|
||||
|
||||
Arrow keys should move focus between tabs; the active tab receives `tabindex="0"` while inactive tabs use `tabindex="-1"`.
|
||||
|
||||
---
|
||||
|
||||
## Live regions and notifications
|
||||
|
||||
Use `aria-live` to announce dynamic content changes to screen readers without moving focus.
|
||||
|
||||
```html
|
||||
<!-- Status updates (polite — waits for pause in speech) -->
|
||||
<div aria-live="polite" aria-atomic="true" class="status">
|
||||
<!-- Content updates announced to screen readers -->
|
||||
</div>
|
||||
|
||||
<!-- Urgent alerts (assertive — interrupts) -->
|
||||
<div role="alert" aria-live="assertive">
|
||||
<!-- Interrupts current announcement -->
|
||||
</div>
|
||||
```
|
||||
|
||||
```javascript
|
||||
function showNotification(message, type = 'polite') {
|
||||
const container = document.getElementById(`${type}-announcer`);
|
||||
container.textContent = '';
|
||||
requestAnimationFrame(() => {
|
||||
container.textContent = message;
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Clear the container before writing to ensure the same message triggers a new announcement.
|
||||
|
||||
---
|
||||
|
||||
## Screen reader commands
|
||||
|
||||
Quick reference for the most common screen reader shortcuts.
|
||||
|
||||
| Action | VoiceOver (Mac) | NVDA (Windows) |
|
||||
|--------|-----------------|----------------|
|
||||
| Start/Stop | ⌘ + F5 | Ctrl + Alt + N |
|
||||
| Next item | VO + → | ↓ |
|
||||
| Previous item | VO + ← | ↑ |
|
||||
| Activate | VO + Space | Enter |
|
||||
| Headings list | VO + U, then arrows | H / Shift + H |
|
||||
| Links list | VO + U | K / Shift + K |
|
||||
@@ -0,0 +1,191 @@
|
||||
# WCAG 2.2 Quick Reference
|
||||
|
||||
## Success criteria by level
|
||||
|
||||
### Level A (minimum)
|
||||
|
||||
| Criterion | Description |
|
||||
|-----------|-------------|
|
||||
| **1.1.1** Non-text Content | All images, icons have text alternatives |
|
||||
| **1.2.1** Audio-only/Video-only | Provide transcript or audio description |
|
||||
| **1.2.2** Captions | Video with audio has captions |
|
||||
| **1.2.3** Audio Description | Video has audio description |
|
||||
| **1.3.1** Info and Relationships | Information conveyed through presentation is available programmatically |
|
||||
| **1.3.2** Meaningful Sequence | Reading order is logical |
|
||||
| **1.3.3** Sensory Characteristics | Instructions don't rely solely on shape, color, size, location, orientation, or sound |
|
||||
| **1.4.1** Use of Color | Color is not the only visual means of conveying information |
|
||||
| **1.4.2** Audio Control | Audio playing automatically can be paused/stopped |
|
||||
| **2.1.1** Keyboard | All functionality available via keyboard |
|
||||
| **2.1.2** No Keyboard Trap | Keyboard focus can be moved away from any component |
|
||||
| **2.1.4** Character Key Shortcuts | Single-key shortcuts can be turned off or remapped |
|
||||
| **2.2.1** Timing Adjustable | Time limits can be extended |
|
||||
| **2.2.2** Pause, Stop, Hide | Moving/blinking content can be paused |
|
||||
| **2.3.1** Three Flashes | Nothing flashes more than 3 times per second |
|
||||
| **2.4.1** Bypass Blocks | Skip link or landmark navigation available |
|
||||
| **2.4.2** Page Titled | Pages have descriptive titles |
|
||||
| **2.4.3** Focus Order | Focus order preserves meaning |
|
||||
| **2.4.4** Link Purpose | Link purpose clear from link text or context |
|
||||
| **2.5.1** Pointer Gestures | Multi-point gestures have single-pointer alternatives |
|
||||
| **2.5.2** Pointer Cancellation | Down-event doesn't trigger action (use up-event or click) |
|
||||
| **2.5.3** Label in Name | Accessible name contains visible label text |
|
||||
| **2.5.4** Motion Actuation | Motion-triggered functions have alternatives |
|
||||
| **3.1.1** Language of Page | Default language specified in HTML |
|
||||
| **3.2.1** On Focus | Focus doesn't trigger unexpected changes |
|
||||
| **3.2.2** On Input | Input doesn't trigger unexpected changes |
|
||||
| **3.2.6** Consistent Help | Help mechanisms appear in the same relative order across pages |
|
||||
| **3.3.1** Error Identification | Input errors clearly described |
|
||||
| **3.3.2** Labels or Instructions | Form inputs have labels or instructions |
|
||||
| **3.3.7** Redundant Entry | Information previously entered is auto-populated or available to select |
|
||||
| **4.1.2** Name, Role, Value | UI components have accessible names and correct roles |
|
||||
|
||||
### Level AA (standard)
|
||||
|
||||
| Criterion | Description |
|
||||
|-----------|-------------|
|
||||
| **1.2.4** Captions (Live) | Live audio has captions |
|
||||
| **1.2.5** Audio Description | Pre-recorded video has audio description |
|
||||
| **1.3.4** Orientation | Content doesn't restrict orientation |
|
||||
| **1.3.5** Identify Input Purpose | Input purpose can be programmatically determined |
|
||||
| **1.4.3** Contrast (Minimum) | 4.5:1 for normal text, 3:1 for large text |
|
||||
| **1.4.4** Resize Text | Text can be resized to 200% without loss of functionality |
|
||||
| **1.4.5** Images of Text | Text used instead of images of text |
|
||||
| **1.4.10** Reflow | Content reflows at 320px width without horizontal scroll |
|
||||
| **1.4.11** Non-text Contrast | UI components have 3:1 contrast |
|
||||
| **1.4.12** Text Spacing | Content adapts to text spacing changes |
|
||||
| **1.4.13** Content on Hover/Focus | Additional content is dismissible, hoverable, persistent |
|
||||
| **2.4.5** Multiple Ways | Multiple ways to find pages |
|
||||
| **2.4.6** Headings and Labels | Headings and labels are descriptive |
|
||||
| **2.4.7** Focus Visible | Focus indicator is visible |
|
||||
| **2.4.11** Focus Not Obscured (Minimum) | Focused element is not entirely hidden by author-created content |
|
||||
| **2.5.7** Dragging Movements | Dragging actions have single-pointer alternatives |
|
||||
| **2.5.8** Target Size (Minimum) | Interactive targets are at least 24×24 CSS pixels (with exceptions) |
|
||||
| **3.1.2** Language of Parts | Language changes are marked |
|
||||
| **3.2.3** Consistent Navigation | Navigation is consistent across pages |
|
||||
| **3.2.4** Consistent Identification | Same functionality uses same labels |
|
||||
| **3.3.3** Error Suggestion | Error corrections suggested when known |
|
||||
| **3.3.4** Error Prevention (Legal) | Actions can be reversed or confirmed |
|
||||
| **3.3.8** Accessible Authentication (Minimum) | No cognitive function test for login unless an alternative or assistance is provided |
|
||||
| **4.1.3** Status Messages | Status messages announced to screen readers |
|
||||
|
||||
### Level AAA (enhanced)
|
||||
|
||||
| Criterion | Description |
|
||||
|-----------|-------------|
|
||||
| **1.4.6** Contrast (Enhanced) | 7:1 for normal text, 4.5:1 for large text |
|
||||
| **1.4.8** Visual Presentation | Foreground/background colors can be selected |
|
||||
| **1.4.9** Images of Text (No Exception) | No images of text |
|
||||
| **2.1.3** Keyboard (No Exception) | All functionality keyboard accessible |
|
||||
| **2.2.3** No Timing | No time limits |
|
||||
| **2.2.4** Interruptions | Interruptions can be postponed |
|
||||
| **2.2.5** Re-authenticating | Data preserved on re-authentication |
|
||||
| **2.2.6** Timeouts | Users warned about data loss from inactivity |
|
||||
| **2.3.2** Three Flashes | No content flashes more than 3 times |
|
||||
| **2.3.3** Animation from Interactions | Motion animation can be disabled |
|
||||
| **2.4.8** Location | User location within site is available |
|
||||
| **2.4.9** Link Purpose (Link Only) | Link purpose clear from link text alone |
|
||||
| **2.4.10** Section Headings | Sections have headings |
|
||||
| **2.4.12** Focus Not Obscured (Enhanced) | No part of the focused element is hidden by author-created content |
|
||||
| **2.4.13** Focus Appearance | Focus indicator has sufficient area, contrast, and is not obscured |
|
||||
| **3.1.3** Unusual Words | Definitions available for unusual words |
|
||||
| **3.1.4** Abbreviations | Abbreviations expanded |
|
||||
| **3.1.5** Reading Level | Alternative content for complex text |
|
||||
| **3.1.6** Pronunciation | Pronunciation available where needed |
|
||||
| **3.2.5** Change on Request | Changes initiated only by user |
|
||||
| **3.3.5** Help | Context-sensitive help available |
|
||||
| **3.3.6** Error Prevention (All) | All form submissions can be reviewed |
|
||||
| **3.3.9** Accessible Authentication (Enhanced) | No cognitive function test for login (no object or personal content recognition exceptions) |
|
||||
|
||||
## Common ARIA patterns
|
||||
|
||||
### Buttons
|
||||
```html
|
||||
<button>Label</button>
|
||||
<!-- or -->
|
||||
<button aria-label="Close dialog">×</button>
|
||||
```
|
||||
|
||||
### Links
|
||||
```html
|
||||
<a href="/page">Descriptive link text</a>
|
||||
<!-- External links -->
|
||||
<a href="https://external.com" target="_blank" rel="noopener">
|
||||
External site
|
||||
<span class="visually-hidden">(opens in new tab)</span>
|
||||
</a>
|
||||
```
|
||||
|
||||
### Form fields
|
||||
```html
|
||||
<label for="email">Email address</label>
|
||||
<input type="email" id="email" aria-describedby="email-hint">
|
||||
<p id="email-hint">We'll never share your email.</p>
|
||||
```
|
||||
|
||||
### Error states
|
||||
```html
|
||||
<label for="email">Email</label>
|
||||
<input type="email" id="email" aria-invalid="true" aria-describedby="email-error">
|
||||
<p id="email-error" role="alert">Please enter a valid email address.</p>
|
||||
```
|
||||
|
||||
### Navigation
|
||||
```html
|
||||
<nav aria-label="Main">
|
||||
<ul>
|
||||
<li><a href="/" aria-current="page">Home</a></li>
|
||||
<li><a href="/about">About</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
```
|
||||
|
||||
### Modals
|
||||
```html
|
||||
<div role="dialog" aria-modal="true" aria-labelledby="dialog-title">
|
||||
<h2 id="dialog-title">Confirm Action</h2>
|
||||
<!-- content -->
|
||||
</div>
|
||||
```
|
||||
|
||||
### Live regions
|
||||
```html
|
||||
<!-- Polite (waits for pause in speech) -->
|
||||
<div aria-live="polite">Status update here</div>
|
||||
|
||||
<!-- Assertive (interrupts immediately) -->
|
||||
<div aria-live="assertive" role="alert">Error message here</div>
|
||||
|
||||
<!-- Status (polite, implicit) -->
|
||||
<div role="status">Loading complete</div>
|
||||
```
|
||||
|
||||
## What changed from 2.1 to 2.2
|
||||
|
||||
| Change | Criterion | Level |
|
||||
|--------|-----------|-------|
|
||||
| **Removed** | 4.1.1 Parsing | A |
|
||||
| **Added** | 2.4.11 Focus Not Obscured (Minimum) | AA |
|
||||
| **Added** | 2.4.12 Focus Not Obscured (Enhanced) | AAA |
|
||||
| **Added** | 2.4.13 Focus Appearance | AAA |
|
||||
| **Added** | 2.5.7 Dragging Movements | AA |
|
||||
| **Added** | 2.5.8 Target Size (Minimum) | AA |
|
||||
| **Added** | 3.2.6 Consistent Help | A |
|
||||
| **Added** | 3.3.7 Redundant Entry | A |
|
||||
| **Added** | 3.3.8 Accessible Authentication (Minimum) | AA |
|
||||
| **Added** | 3.3.9 Accessible Authentication (Enhanced) | AAA |
|
||||
|
||||
## Testing tools
|
||||
|
||||
| Tool | Type | URL |
|
||||
|------|------|-----|
|
||||
| axe DevTools | Browser extension | [deque.com/axe](https://www.deque.com/axe/) |
|
||||
| WAVE | Browser extension | [wave.webaim.org](https://wave.webaim.org/) |
|
||||
| Lighthouse | Built into Chrome | DevTools → Lighthouse |
|
||||
| NVDA | Screen reader (Windows) | [nvaccess.org](https://www.nvaccess.org/) |
|
||||
| VoiceOver | Screen reader (Mac) | Built into macOS |
|
||||
| Colour Contrast Analyser | Desktop app | [tpgi.com](https://www.tpgi.com/color-contrast-checker/) |
|
||||
|
||||
## Sources
|
||||
|
||||
- [WCAG 2.2 W3C Recommendation](https://www.w3.org/TR/WCAG22/)
|
||||
- [WCAG 2.2 Quick Reference](https://www.w3.org/WAI/WCAG22/quickref/)
|
||||
- [What's New in WCAG 2.2](https://www.w3.org/WAI/standards-guidelines/wcag/new-in-22/)
|
||||
@@ -0,0 +1,946 @@
|
||||
# React Composition Patterns
|
||||
|
||||
**Version 1.0.0**
|
||||
Engineering
|
||||
January 2026
|
||||
|
||||
> **Note:**
|
||||
> This document is mainly for agents and LLMs to follow when maintaining,
|
||||
> generating, or refactoring React codebases using composition. Humans
|
||||
> may also find it useful, but guidance here is optimized for automation
|
||||
> and consistency by AI-assisted workflows.
|
||||
|
||||
---
|
||||
|
||||
## Abstract
|
||||
|
||||
Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Component Architecture](#1-component-architecture) — **HIGH**
|
||||
- 1.1 [Avoid Boolean Prop Proliferation](#11-avoid-boolean-prop-proliferation)
|
||||
- 1.2 [Use Compound Components](#12-use-compound-components)
|
||||
2. [State Management](#2-state-management) — **MEDIUM**
|
||||
- 2.1 [Decouple State Management from UI](#21-decouple-state-management-from-ui)
|
||||
- 2.2 [Define Generic Context Interfaces for Dependency Injection](#22-define-generic-context-interfaces-for-dependency-injection)
|
||||
- 2.3 [Lift State into Provider Components](#23-lift-state-into-provider-components)
|
||||
3. [Implementation Patterns](#3-implementation-patterns) — **MEDIUM**
|
||||
- 3.1 [Create Explicit Component Variants](#31-create-explicit-component-variants)
|
||||
- 3.2 [Prefer Composing Children Over Render Props](#32-prefer-composing-children-over-render-props)
|
||||
4. [React 19 APIs](#4-react-19-apis) — **MEDIUM**
|
||||
- 4.1 [React 19 API Changes](#41-react-19-api-changes)
|
||||
|
||||
---
|
||||
|
||||
## 1. Component Architecture
|
||||
|
||||
**Impact: HIGH**
|
||||
|
||||
Fundamental patterns for structuring components to avoid prop
|
||||
proliferation and enable flexible composition.
|
||||
|
||||
### 1.1 Avoid Boolean Prop Proliferation
|
||||
|
||||
**Impact: CRITICAL (prevents unmaintainable component variants)**
|
||||
|
||||
Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
|
||||
|
||||
component behavior. Each boolean doubles possible states and creates
|
||||
|
||||
unmaintainable conditional logic. Use composition instead.
|
||||
|
||||
**Incorrect: boolean props create exponential complexity**
|
||||
|
||||
```tsx
|
||||
function Composer({
|
||||
onSubmit,
|
||||
isThread,
|
||||
channelId,
|
||||
isDMThread,
|
||||
dmId,
|
||||
isEditing,
|
||||
isForwarding,
|
||||
}: Props) {
|
||||
return (
|
||||
<form>
|
||||
<Header />
|
||||
<Input />
|
||||
{isDMThread ? (
|
||||
<AlsoSendToDMField id={dmId} />
|
||||
) : isThread ? (
|
||||
<AlsoSendToChannelField id={channelId} />
|
||||
) : null}
|
||||
{isEditing ? (
|
||||
<EditActions />
|
||||
) : isForwarding ? (
|
||||
<ForwardActions />
|
||||
) : (
|
||||
<DefaultActions />
|
||||
)}
|
||||
<Footer onSubmit={onSubmit} />
|
||||
</form>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct: composition eliminates conditionals**
|
||||
|
||||
```tsx
|
||||
// Channel composer
|
||||
function ChannelComposer() {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Attachments />
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Thread composer - adds "also send to channel" field
|
||||
function ThreadComposer({ channelId }: { channelId: string }) {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<AlsoSendToChannelField id={channelId} />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Edit composer - different footer actions
|
||||
function EditComposer() {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.CancelEdit />
|
||||
<Composer.SaveEdit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Each variant is explicit about what it renders. We can share internals without
|
||||
|
||||
sharing a single monolithic parent.
|
||||
|
||||
### 1.2 Use Compound Components
|
||||
|
||||
**Impact: HIGH (enables flexible composition without prop drilling)**
|
||||
|
||||
Structure complex components as compound components with a shared context. Each
|
||||
|
||||
subcomponent accesses shared state via context, not props. Consumers compose the
|
||||
|
||||
pieces they need.
|
||||
|
||||
**Incorrect: monolithic component with render props**
|
||||
|
||||
```tsx
|
||||
function Composer({
|
||||
renderHeader,
|
||||
renderFooter,
|
||||
renderActions,
|
||||
showAttachments,
|
||||
showFormatting,
|
||||
showEmojis,
|
||||
}: Props) {
|
||||
return (
|
||||
<form>
|
||||
{renderHeader?.()}
|
||||
<Input />
|
||||
{showAttachments && <Attachments />}
|
||||
{renderFooter ? (
|
||||
renderFooter()
|
||||
) : (
|
||||
<Footer>
|
||||
{showFormatting && <Formatting />}
|
||||
{showEmojis && <Emojis />}
|
||||
{renderActions?.()}
|
||||
</Footer>
|
||||
)}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct: compound components with shared context**
|
||||
|
||||
```tsx
|
||||
const ComposerContext = createContext<ComposerContextValue | null>(null)
|
||||
|
||||
function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
|
||||
return (
|
||||
<ComposerContext value={{ state, actions, meta }}>
|
||||
{children}
|
||||
</ComposerContext>
|
||||
)
|
||||
}
|
||||
|
||||
function ComposerFrame({ children }: { children: React.ReactNode }) {
|
||||
return <form>{children}</form>
|
||||
}
|
||||
|
||||
function ComposerInput() {
|
||||
const {
|
||||
state,
|
||||
actions: { update },
|
||||
meta: { inputRef },
|
||||
} = use(ComposerContext)
|
||||
return (
|
||||
<TextInput
|
||||
ref={inputRef}
|
||||
value={state.input}
|
||||
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ComposerSubmit() {
|
||||
const {
|
||||
actions: { submit },
|
||||
} = use(ComposerContext)
|
||||
return <Button onPress={submit}>Send</Button>
|
||||
}
|
||||
|
||||
// Export as compound component
|
||||
const Composer = {
|
||||
Provider: ComposerProvider,
|
||||
Frame: ComposerFrame,
|
||||
Input: ComposerInput,
|
||||
Submit: ComposerSubmit,
|
||||
Header: ComposerHeader,
|
||||
Footer: ComposerFooter,
|
||||
Attachments: ComposerAttachments,
|
||||
Formatting: ComposerFormatting,
|
||||
Emojis: ComposerEmojis,
|
||||
}
|
||||
```
|
||||
|
||||
**Usage:**
|
||||
|
||||
```tsx
|
||||
<Composer.Provider state={state} actions={actions} meta={meta}>
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</Composer.Provider>
|
||||
```
|
||||
|
||||
Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
|
||||
|
||||
---
|
||||
|
||||
## 2. State Management
|
||||
|
||||
**Impact: MEDIUM**
|
||||
|
||||
Patterns for lifting state and managing shared context across
|
||||
composed components.
|
||||
|
||||
### 2.1 Decouple State Management from UI
|
||||
|
||||
**Impact: MEDIUM (enables swapping state implementations without changing UI)**
|
||||
|
||||
The provider component should be the only place that knows how state is managed.
|
||||
|
||||
UI components consume the context interface—they don't know if state comes from
|
||||
|
||||
useState, Zustand, or a server sync.
|
||||
|
||||
**Incorrect: UI coupled to state implementation**
|
||||
|
||||
```tsx
|
||||
function ChannelComposer({ channelId }: { channelId: string }) {
|
||||
// UI component knows about global state implementation
|
||||
const state = useGlobalChannelState(channelId)
|
||||
const { submit, updateInput } = useChannelSync(channelId)
|
||||
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Input
|
||||
value={state.input}
|
||||
onChange={(text) => sync.updateInput(text)}
|
||||
/>
|
||||
<Composer.Submit onPress={() => sync.submit()} />
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct: state management isolated in provider**
|
||||
|
||||
```tsx
|
||||
// Provider handles all state management details
|
||||
function ChannelProvider({
|
||||
channelId,
|
||||
children,
|
||||
}: {
|
||||
channelId: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { state, update, submit } = useGlobalChannel(channelId)
|
||||
const inputRef = useRef(null)
|
||||
|
||||
return (
|
||||
<Composer.Provider
|
||||
state={state}
|
||||
actions={{ update, submit }}
|
||||
meta={{ inputRef }}
|
||||
>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
// UI component only knows about the context interface
|
||||
function ChannelComposer() {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Usage
|
||||
function Channel({ channelId }: { channelId: string }) {
|
||||
return (
|
||||
<ChannelProvider channelId={channelId}>
|
||||
<ChannelComposer />
|
||||
</ChannelProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Different providers, same UI:**
|
||||
|
||||
```tsx
|
||||
// Local state for ephemeral forms
|
||||
function ForwardMessageProvider({ children }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
const forwardMessage = useForwardMessage()
|
||||
|
||||
return (
|
||||
<Composer.Provider
|
||||
state={state}
|
||||
actions={{ update: setState, submit: forwardMessage }}
|
||||
>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
// Global synced state for channels
|
||||
function ChannelProvider({ channelId, children }) {
|
||||
const { state, update, submit } = useGlobalChannel(channelId)
|
||||
|
||||
return (
|
||||
<Composer.Provider state={state} actions={{ update, submit }}>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The same `Composer.Input` component works with both providers because it only
|
||||
|
||||
depends on the context interface, not the implementation.
|
||||
|
||||
### 2.2 Define Generic Context Interfaces for Dependency Injection
|
||||
|
||||
**Impact: HIGH (enables dependency-injectable state across use-cases)**
|
||||
|
||||
Define a **generic interface** for your component context with three parts:
|
||||
|
||||
`state`, `actions`, and `meta`. This interface is a contract that any provider
|
||||
|
||||
can implement—enabling the same UI components to work with completely different
|
||||
|
||||
state implementations.
|
||||
|
||||
**Core principle:** Lift state, compose internals, make state
|
||||
|
||||
dependency-injectable.
|
||||
|
||||
**Incorrect: UI coupled to specific state implementation**
|
||||
|
||||
```tsx
|
||||
function ComposerInput() {
|
||||
// Tightly coupled to a specific hook
|
||||
const { input, setInput } = useChannelComposerState()
|
||||
return <TextInput value={input} onChangeText={setInput} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct: generic interface enables dependency injection**
|
||||
|
||||
```tsx
|
||||
// Define a GENERIC interface that any provider can implement
|
||||
interface ComposerState {
|
||||
input: string
|
||||
attachments: Attachment[]
|
||||
isSubmitting: boolean
|
||||
}
|
||||
|
||||
interface ComposerActions {
|
||||
update: (updater: (state: ComposerState) => ComposerState) => void
|
||||
submit: () => void
|
||||
}
|
||||
|
||||
interface ComposerMeta {
|
||||
inputRef: React.RefObject<TextInput>
|
||||
}
|
||||
|
||||
interface ComposerContextValue {
|
||||
state: ComposerState
|
||||
actions: ComposerActions
|
||||
meta: ComposerMeta
|
||||
}
|
||||
|
||||
const ComposerContext = createContext<ComposerContextValue | null>(null)
|
||||
```
|
||||
|
||||
**UI components consume the interface, not the implementation:**
|
||||
|
||||
```tsx
|
||||
function ComposerInput() {
|
||||
const {
|
||||
state,
|
||||
actions: { update },
|
||||
meta,
|
||||
} = use(ComposerContext)
|
||||
|
||||
// This component works with ANY provider that implements the interface
|
||||
return (
|
||||
<TextInput
|
||||
ref={meta.inputRef}
|
||||
value={state.input}
|
||||
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Different providers implement the same interface:**
|
||||
|
||||
```tsx
|
||||
// Provider A: Local state for ephemeral forms
|
||||
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
const inputRef = useRef(null)
|
||||
const submit = useForwardMessage()
|
||||
|
||||
return (
|
||||
<ComposerContext
|
||||
value={{
|
||||
state,
|
||||
actions: { update: setState, submit },
|
||||
meta: { inputRef },
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ComposerContext>
|
||||
)
|
||||
}
|
||||
|
||||
// Provider B: Global synced state for channels
|
||||
function ChannelProvider({ channelId, children }: Props) {
|
||||
const { state, update, submit } = useGlobalChannel(channelId)
|
||||
const inputRef = useRef(null)
|
||||
|
||||
return (
|
||||
<ComposerContext
|
||||
value={{
|
||||
state,
|
||||
actions: { update, submit },
|
||||
meta: { inputRef },
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ComposerContext>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**The same composed UI works with both:**
|
||||
|
||||
```tsx
|
||||
// Works with ForwardMessageProvider (local state)
|
||||
<ForwardMessageProvider>
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Submit />
|
||||
</Composer.Frame>
|
||||
</ForwardMessageProvider>
|
||||
|
||||
// Works with ChannelProvider (global synced state)
|
||||
<ChannelProvider channelId="abc">
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Submit />
|
||||
</Composer.Frame>
|
||||
</ChannelProvider>
|
||||
```
|
||||
|
||||
**Custom UI outside the component can access state and actions:**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageDialog() {
|
||||
return (
|
||||
<ForwardMessageProvider>
|
||||
<Dialog>
|
||||
{/* The composer UI */}
|
||||
<Composer.Frame>
|
||||
<Composer.Input placeholder="Add a message, if you'd like." />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
|
||||
{/* Custom UI OUTSIDE the composer, but INSIDE the provider */}
|
||||
<MessagePreview />
|
||||
|
||||
{/* Actions at the bottom of the dialog */}
|
||||
<DialogActions>
|
||||
<CancelButton />
|
||||
<ForwardButton />
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</ForwardMessageProvider>
|
||||
)
|
||||
}
|
||||
|
||||
// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
|
||||
function ForwardButton() {
|
||||
const {
|
||||
actions: { submit },
|
||||
} = use(ComposerContext)
|
||||
return <Button onPress={submit}>Forward</Button>
|
||||
}
|
||||
|
||||
// This preview lives OUTSIDE Composer.Frame but can read composer's state!
|
||||
function MessagePreview() {
|
||||
const { state } = use(ComposerContext)
|
||||
return <Preview message={state.input} attachments={state.attachments} />
|
||||
}
|
||||
```
|
||||
|
||||
The provider boundary is what matters—not the visual nesting. Components that
|
||||
|
||||
need shared state don't have to be inside the `Composer.Frame`. They just need
|
||||
|
||||
to be within the provider.
|
||||
|
||||
The `ForwardButton` and `MessagePreview` are not visually inside the composer
|
||||
|
||||
box, but they can still access its state and actions. This is the power of
|
||||
|
||||
lifting state into providers.
|
||||
|
||||
The UI is reusable bits you compose together. The state is dependency-injected
|
||||
|
||||
by the provider. Swap the provider, keep the UI.
|
||||
|
||||
### 2.3 Lift State into Provider Components
|
||||
|
||||
**Impact: HIGH (enables state sharing outside component boundaries)**
|
||||
|
||||
Move state management into dedicated provider components. This allows sibling
|
||||
|
||||
components outside the main UI to access and modify state without prop drilling
|
||||
|
||||
or awkward refs.
|
||||
|
||||
**Incorrect: state trapped inside component**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageComposer() {
|
||||
const [state, setState] = useState(initialState)
|
||||
const forwardMessage = useForwardMessage()
|
||||
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Footer />
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Problem: How does this button access composer state?
|
||||
function ForwardMessageDialog() {
|
||||
return (
|
||||
<Dialog>
|
||||
<ForwardMessageComposer />
|
||||
<MessagePreview /> {/* Needs composer state */}
|
||||
<DialogActions>
|
||||
<CancelButton />
|
||||
<ForwardButton /> {/* Needs to call submit */}
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect: useEffect to sync state up**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageDialog() {
|
||||
const [input, setInput] = useState('')
|
||||
return (
|
||||
<Dialog>
|
||||
<ForwardMessageComposer onInputChange={setInput} />
|
||||
<MessagePreview input={input} />
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardMessageComposer({ onInputChange }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
useEffect(() => {
|
||||
onInputChange(state.input) // Sync on every change 😬
|
||||
}, [state.input])
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect: reading state from ref on submit**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageDialog() {
|
||||
const stateRef = useRef(null)
|
||||
return (
|
||||
<Dialog>
|
||||
<ForwardMessageComposer stateRef={stateRef} />
|
||||
<ForwardButton onPress={() => submit(stateRef.current)} />
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct: state lifted to provider**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
const forwardMessage = useForwardMessage()
|
||||
const inputRef = useRef(null)
|
||||
|
||||
return (
|
||||
<Composer.Provider
|
||||
state={state}
|
||||
actions={{ update: setState, submit: forwardMessage }}
|
||||
meta={{ inputRef }}
|
||||
>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardMessageDialog() {
|
||||
return (
|
||||
<ForwardMessageProvider>
|
||||
<Dialog>
|
||||
<ForwardMessageComposer />
|
||||
<MessagePreview /> {/* Custom components can access state and actions */}
|
||||
<DialogActions>
|
||||
<CancelButton />
|
||||
<ForwardButton /> {/* Custom components can access state and actions */}
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</ForwardMessageProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardButton() {
|
||||
const { actions } = use(Composer.Context)
|
||||
return <Button onPress={actions.submit}>Forward</Button>
|
||||
}
|
||||
```
|
||||
|
||||
The ForwardButton lives outside the Composer.Frame but still has access to the
|
||||
|
||||
submit action because it's within the provider. Even though it's a one-off
|
||||
|
||||
component, it can still access the composer's state and actions from outside the
|
||||
|
||||
UI itself.
|
||||
|
||||
**Key insight:** Components that need shared state don't have to be visually
|
||||
|
||||
nested inside each other—they just need to be within the same provider.
|
||||
|
||||
---
|
||||
|
||||
## 3. Implementation Patterns
|
||||
|
||||
**Impact: MEDIUM**
|
||||
|
||||
Specific techniques for implementing compound components and
|
||||
context providers.
|
||||
|
||||
### 3.1 Create Explicit Component Variants
|
||||
|
||||
**Impact: MEDIUM (self-documenting code, no hidden conditionals)**
|
||||
|
||||
Instead of one component with many boolean props, create explicit variant
|
||||
|
||||
components. Each variant composes the pieces it needs. The code documents
|
||||
|
||||
itself.
|
||||
|
||||
**Incorrect: one component, many modes**
|
||||
|
||||
```tsx
|
||||
// What does this component actually render?
|
||||
<Composer
|
||||
isThread
|
||||
isEditing={false}
|
||||
channelId='abc'
|
||||
showAttachments
|
||||
showFormatting={false}
|
||||
/>
|
||||
```
|
||||
|
||||
**Correct: explicit variants**
|
||||
|
||||
```tsx
|
||||
// Immediately clear what this renders
|
||||
<ThreadComposer channelId="abc" />
|
||||
|
||||
// Or
|
||||
<EditMessageComposer messageId="xyz" />
|
||||
|
||||
// Or
|
||||
<ForwardMessageComposer messageId="123" />
|
||||
```
|
||||
|
||||
Each implementation is unique, explicit and self-contained. Yet they can each
|
||||
|
||||
use shared parts.
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```tsx
|
||||
function ThreadComposer({ channelId }: { channelId: string }) {
|
||||
return (
|
||||
<ThreadProvider channelId={channelId}>
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<AlsoSendToChannelField channelId={channelId} />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</ThreadProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function EditMessageComposer({ messageId }: { messageId: string }) {
|
||||
return (
|
||||
<EditMessageProvider messageId={messageId}>
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.CancelEdit />
|
||||
<Composer.SaveEdit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</EditMessageProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardMessageComposer({ messageId }: { messageId: string }) {
|
||||
return (
|
||||
<ForwardMessageProvider messageId={messageId}>
|
||||
<Composer.Frame>
|
||||
<Composer.Input placeholder="Add a message, if you'd like." />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Mentions />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</ForwardMessageProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Each variant is explicit about:
|
||||
|
||||
- What provider/state it uses
|
||||
|
||||
- What UI elements it includes
|
||||
|
||||
- What actions are available
|
||||
|
||||
No boolean prop combinations to reason about. No impossible states.
|
||||
|
||||
### 3.2 Prefer Composing Children Over Render Props
|
||||
|
||||
**Impact: MEDIUM (cleaner composition, better readability)**
|
||||
|
||||
Use `children` for composition instead of `renderX` props. Children are more
|
||||
|
||||
readable, compose naturally, and don't require understanding callback
|
||||
|
||||
signatures.
|
||||
|
||||
**Incorrect: render props**
|
||||
|
||||
```tsx
|
||||
function Composer({
|
||||
renderHeader,
|
||||
renderFooter,
|
||||
renderActions,
|
||||
}: {
|
||||
renderHeader?: () => React.ReactNode
|
||||
renderFooter?: () => React.ReactNode
|
||||
renderActions?: () => React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<form>
|
||||
{renderHeader?.()}
|
||||
<Input />
|
||||
{renderFooter ? renderFooter() : <DefaultFooter />}
|
||||
{renderActions?.()}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
// Usage is awkward and inflexible
|
||||
return (
|
||||
<Composer
|
||||
renderHeader={() => <CustomHeader />}
|
||||
renderFooter={() => (
|
||||
<>
|
||||
<Formatting />
|
||||
<Emojis />
|
||||
</>
|
||||
)}
|
||||
renderActions={() => <SubmitButton />}
|
||||
/>
|
||||
)
|
||||
```
|
||||
|
||||
**Correct: compound components with children**
|
||||
|
||||
```tsx
|
||||
function ComposerFrame({ children }: { children: React.ReactNode }) {
|
||||
return <form>{children}</form>
|
||||
}
|
||||
|
||||
function ComposerFooter({ children }: { children: React.ReactNode }) {
|
||||
return <footer className='flex'>{children}</footer>
|
||||
}
|
||||
|
||||
// Usage is flexible
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<CustomHeader />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<SubmitButton />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
```
|
||||
|
||||
**When render props are appropriate:**
|
||||
|
||||
```tsx
|
||||
// Render props work well when you need to pass data back
|
||||
<List
|
||||
data={items}
|
||||
renderItem={({ item, index }) => <Item item={item} index={index} />}
|
||||
/>
|
||||
```
|
||||
|
||||
Use render props when the parent needs to provide data or state to the child.
|
||||
|
||||
Use children when composing static structure.
|
||||
|
||||
---
|
||||
|
||||
## 4. React 19 APIs
|
||||
|
||||
**Impact: MEDIUM**
|
||||
|
||||
React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
|
||||
|
||||
### 4.1 React 19 API Changes
|
||||
|
||||
**Impact: MEDIUM (cleaner component definitions and context usage)**
|
||||
|
||||
> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
|
||||
|
||||
In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
|
||||
|
||||
**Incorrect: forwardRef in React 19**
|
||||
|
||||
```tsx
|
||||
const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {
|
||||
return <TextInput ref={ref} {...props} />
|
||||
})
|
||||
```
|
||||
|
||||
**Correct: ref as a regular prop**
|
||||
|
||||
```tsx
|
||||
function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) {
|
||||
return <TextInput ref={ref} {...props} />
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect: useContext in React 19**
|
||||
|
||||
```tsx
|
||||
const value = useContext(MyContext)
|
||||
```
|
||||
|
||||
**Correct: use instead of useContext**
|
||||
|
||||
```tsx
|
||||
const value = use(MyContext)
|
||||
```
|
||||
|
||||
`use()` can also be called conditionally, unlike `useContext()`.
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
1. [https://react.dev](https://react.dev)
|
||||
2. [https://react.dev/learn/passing-data-deeply-with-context](https://react.dev/learn/passing-data-deeply-with-context)
|
||||
3. [https://react.dev/reference/react/use](https://react.dev/reference/react/use)
|
||||
@@ -0,0 +1,17 @@
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of
|
||||
the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
||||
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
The upstream repository (https://github.com/vercel-labs/agent-skills) declares the MIT licence in its README and in
|
||||
the SKILL.md frontmatter; it ships no LICENSE file with a copyright line. Copyright: Vercel.
|
||||
@@ -0,0 +1,60 @@
|
||||
# React Composition Patterns
|
||||
|
||||
A structured repository for React composition patterns that scale. These
|
||||
patterns help avoid boolean prop proliferation by using compound components,
|
||||
lifting state, and composing internals.
|
||||
|
||||
## Structure
|
||||
|
||||
- `rules/` - Individual rule files (one per rule)
|
||||
- `_sections.md` - Section metadata (titles, impacts, descriptions)
|
||||
- `_template.md` - Template for creating new rules
|
||||
- `area-description.md` - Individual rule files
|
||||
- `metadata.json` - Document metadata (version, organization, abstract)
|
||||
- **`AGENTS.md`** - Compiled output (generated)
|
||||
|
||||
## Rules
|
||||
|
||||
### Component Architecture (CRITICAL)
|
||||
|
||||
- `architecture-avoid-boolean-props.md` - Don't add boolean props to customize
|
||||
behavior
|
||||
- `architecture-compound-components.md` - Structure as compound components with
|
||||
shared context
|
||||
|
||||
### State Management (HIGH)
|
||||
|
||||
- `state-lift-state.md` - Lift state into provider components
|
||||
- `state-context-interface.md` - Define clear context interfaces
|
||||
(state/actions/meta)
|
||||
- `state-decouple-implementation.md` - Decouple state management from UI
|
||||
|
||||
### Implementation Patterns (MEDIUM)
|
||||
|
||||
- `patterns-children-over-render-props.md` - Prefer children over renderX props
|
||||
- `patterns-explicit-variants.md` - Create explicit component variants
|
||||
|
||||
## Core Principles
|
||||
|
||||
1. **Composition over configuration** — Instead of adding props, let consumers
|
||||
compose
|
||||
2. **Lift your state** — State in providers, not trapped in components
|
||||
3. **Compose your internals** — Subcomponents access context, not props
|
||||
4. **Explicit variants** — Create ThreadComposer, EditComposer, not Composer
|
||||
with isThread
|
||||
|
||||
## Creating a New Rule
|
||||
|
||||
1. Copy `rules/_template.md` to `rules/area-description.md`
|
||||
2. Choose the appropriate area prefix:
|
||||
- `architecture-` for Component Architecture
|
||||
- `state-` for State Management
|
||||
- `patterns-` for Implementation Patterns
|
||||
3. Fill in the frontmatter and content
|
||||
4. Ensure you have clear examples with explanations
|
||||
|
||||
## Impact Levels
|
||||
|
||||
- `CRITICAL` - Foundational patterns, prevents unmaintainable code
|
||||
- `HIGH` - Significant maintainability improvements
|
||||
- `MEDIUM` - Good practices for cleaner code
|
||||
@@ -0,0 +1,99 @@
|
||||
---
|
||||
name: ext-composition-patterns
|
||||
description:
|
||||
React composition patterns that scale. Use when refactoring components with
|
||||
boolean prop proliferation, building flexible component libraries, or
|
||||
designing reusable APIs. Triggers on tasks involving compound components,
|
||||
render props, context providers, or component architecture. Includes React 19
|
||||
API changes.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: vercel
|
||||
version: '1.0.0'
|
||||
---
|
||||
|
||||
> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
|
||||
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`, the project's `AGENTS.md` or `DESIGN.md`, those win:
|
||||
> ipal-kit features first (the `ipal-reference` skill), Payload 3 + Next 16 App Router, data from Server Components
|
||||
> through Payload / `@/lib/content`, every visible text from the CMS, design values from `DESIGN.md` tokens.
|
||||
> Never add a dependency this skill suggests without the owner's decision.
|
||||
>
|
||||
> **Blocks:** composition applies inside a block's own components; the block schema, shared fields and
|
||||
> `RenderBlocks` follow AGENT.md §6.
|
||||
|
||||
|
||||
# React Composition Patterns
|
||||
|
||||
Composition patterns for building flexible, maintainable React components. Avoid
|
||||
boolean prop proliferation by using compound components, lifting state, and
|
||||
composing internals. These patterns make codebases easier for both humans and AI
|
||||
agents to work with as they scale.
|
||||
|
||||
## When to Apply
|
||||
|
||||
Reference these guidelines when:
|
||||
|
||||
- Refactoring components with many boolean props
|
||||
- Building reusable component libraries
|
||||
- Designing flexible component APIs
|
||||
- Reviewing component architecture
|
||||
- Working with compound components or context providers
|
||||
|
||||
## Rule Categories by Priority
|
||||
|
||||
| Priority | Category | Impact | Prefix |
|
||||
| -------- | ----------------------- | ------ | --------------- |
|
||||
| 1 | Component Architecture | HIGH | `architecture-` |
|
||||
| 2 | State Management | MEDIUM | `state-` |
|
||||
| 3 | Implementation Patterns | MEDIUM | `patterns-` |
|
||||
| 4 | React 19 APIs | MEDIUM | `react19-` |
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### 1. Component Architecture (HIGH)
|
||||
|
||||
- `architecture-avoid-boolean-props` - Don't add boolean props to customize
|
||||
behavior; use composition
|
||||
- `architecture-compound-components` - Structure complex components with shared
|
||||
context
|
||||
|
||||
### 2. State Management (MEDIUM)
|
||||
|
||||
- `state-decouple-implementation` - Provider is the only place that knows how
|
||||
state is managed
|
||||
- `state-context-interface` - Define generic interface with state, actions, meta
|
||||
for dependency injection
|
||||
- `state-lift-state` - Move state into provider components for sibling access
|
||||
|
||||
### 3. Implementation Patterns (MEDIUM)
|
||||
|
||||
- `patterns-explicit-variants` - Create explicit variant components instead of
|
||||
boolean modes
|
||||
- `patterns-children-over-render-props` - Use children for composition instead
|
||||
of renderX props
|
||||
|
||||
### 4. React 19 APIs (MEDIUM)
|
||||
|
||||
> **⚠️ React 19+ only.** Skip this section if using React 18 or earlier.
|
||||
|
||||
- `react19-no-forwardref` - Don't use `forwardRef`; use `use()` instead of `useContext()`
|
||||
|
||||
## How to Use
|
||||
|
||||
Read individual rule files for detailed explanations and code examples:
|
||||
|
||||
```
|
||||
rules/architecture-avoid-boolean-props.md
|
||||
rules/state-context-interface.md
|
||||
```
|
||||
|
||||
Each rule file contains:
|
||||
|
||||
- Brief explanation of why it matters
|
||||
- Incorrect code example with explanation
|
||||
- Correct code example with explanation
|
||||
- Additional context and references
|
||||
|
||||
## Full Compiled Document
|
||||
|
||||
For the complete guide with all rules expanded: `AGENTS.md`
|
||||
@@ -0,0 +1,14 @@
|
||||
# ext-composition-patterns
|
||||
|
||||
Vendored by @intecion/ipal-kit (`ipal-skills --external`). Do not edit — regenerate with
|
||||
`scripts/vendor-external-skills.mjs` in the ipal-kit repository.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Publisher | Vercel |
|
||||
| Source | https://github.com/vercel-labs/agent-skills/tree/1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62/skills/composition-patterns |
|
||||
| Commit | `1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62` |
|
||||
| Licence | MIT (see the LICENSE file in this folder) |
|
||||
|
||||
Changes from the upstream text: the `name` in the SKILL.md frontmatter is `ext-composition-patterns`, and an
|
||||
override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"organization": "Engineering",
|
||||
"date": "January 2026",
|
||||
"abstract": "Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.",
|
||||
"references": [
|
||||
"https://react.dev",
|
||||
"https://react.dev/learn/passing-data-deeply-with-context",
|
||||
"https://react.dev/reference/react/use"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
# Sections
|
||||
|
||||
This file defines all sections, their ordering, impact levels, and descriptions.
|
||||
The section ID (in parentheses) is the filename prefix used to group rules.
|
||||
|
||||
---
|
||||
|
||||
## 1. Component Architecture (architecture)
|
||||
|
||||
**Impact:** HIGH
|
||||
**Description:** Fundamental patterns for structuring components to avoid prop
|
||||
proliferation and enable flexible composition.
|
||||
|
||||
## 2. State Management (state)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** Patterns for lifting state and managing shared context across
|
||||
composed components.
|
||||
|
||||
## 3. Implementation Patterns (patterns)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** Specific techniques for implementing compound components and
|
||||
context providers.
|
||||
|
||||
## 4. React 19 APIs (react19)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user