Small fixes: optional R2_PUBLIC_URL, seo.uploadsCollection, staff features without roles

- ipalEnvRules({ storage: true }): R2_PUBLIC_URL optional (media served by
  the app); storage: { requirePublicUrl: true } requires it again.
- seo.uploadsCollection: upload collection of the meta image (default media).
- userMeetsRole(req, minimum): the plugin's admin/editor features (Site
  Integrations, settings globals, test e-mail, stats, consent records, form
  submissions) stay reachable when `access` is omitted — without a roles
  field every logged-in account passes, as in Payload's default.
- IndexNow skip for seed writes is covered by test/seed.test.ts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-22 18:33:35 +02:00
co-authored by Claude Opus 5.5
parent cff76c2a69
commit 4911da7112
24 changed files with 167 additions and 68 deletions
+8 -4
View File
@@ -63,18 +63,22 @@ The project's own auth collection keeps its own `access` — the plugin only add
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 Site
> Integrations global and the `/api/ipal/test-email` endpoint then work only through the Local API
> (`overrideAccess`). The seed / first user must have `roles: ['admin']`.
> **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.
## Predicates (front end / hooks / access)
```ts
import { isAdmin, isEditor, hasMinimumRole } from '@intecion/ipal-kit'
import { isAdmin, isEditor, hasMinimumRole, 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
```
They take a loosely typed user (like `req.user`) and read `roles` defensively.
+1 -1
View File
@@ -45,7 +45,7 @@ through this procedure. Ask only when you are missing something you cannot get y
| `slug.join is not a function` | `[slug]` instead of `[[...slug]]` | rename the folder |
| `Missing <html> and <body>` | `[locale]` layout without `<html>` after the root layout was removed | `<html lang>` and `<body>` in `[locale]/layout.tsx` |
| `Export fileTypeFromFile doesn't exist in target module` (Turbopack, dev start) | `instrumentation.ts` imports from the package root → Payload in the Edge bundle | import from `@intecion/ipal-kit/env` + `NEXT_RUNTIME === 'nodejs'` (env.md) |
| `R2_PUBLIC_URL must be a valid URL (got "/media")` | old version of the rule / production with a relative path | dev: `/media` allowed since the new version; production: full URL of the media domain, or leave it empty (media through the app) and make the rule optional (env.md) |
| `R2_PUBLIC_URL must be a valid URL (got "/media")` | old version of the rule / production with a relative path | dev: `/media` allowed since the new version; production: full URL of the media domain, or leave it empty (media through the app; optional since `ipalEnvRules` makes it so by default, env.md) |
| `server-only` in the client | import from `@intecion/ipal-kit/server` in `'use client'` | call it through a server action |
### Admin panel (`/admin`)
+4 -4
View File
@@ -61,7 +61,7 @@ URLs point at that domain. Outside production, `R2_PUBLIC_URL` alone → read-on
| `DATABASE_URI` | ✅ | infra | database connection (read by the project config, not the plugin) |
| `PAYLOAD_SECRET` | ✅ | infra | Payload secret (as above) |
| `NEXT_PUBLIC_SERVER_URL` | ✅ | infra | public URL (canonical, OG, sitemap, IndexNow) |
| `NODE_ENV` | ⬜ | infra | `production` tightens `ipalEnvRules` (R2, `IPAL_IP_HEADER`) and turns off read-only media mode |
| `NODE_ENV` | ⬜ | infra | `production` tightens `ipalEnvRules` (R2 keys, `IPAL_IP_HEADER`) and turns off read-only media mode |
| `GRAPH_TENANT_ID` | ⬜ | email | Azure tenant (Graph) |
| `GRAPH_CLIENT_ID` | ⬜ | email | Azure app id |
| `GRAPH_CLIENT_SECRET` | ⬜ | email | Azure secret |
@@ -70,7 +70,7 @@ URLs point at that domain. Outside production, `R2_PUBLIC_URL` alone → read-on
| `R2_ENDPOINT` | ⬜ (✅ prod) | storage | R2 S3 endpoint |
| `R2_ACCESS_KEY_ID` | ⬜ (✅ prod) | storage | R2 key |
| `R2_SECRET_ACCESS_KEY` | ⬜ (✅ prod) | storage | R2 secret |
| `R2_PUBLIC_URL` | ⬜ (✅ prod in `ipalEnvRules`) | storage | media domain attached to the bucket; empty = media through the app (§6 — then relax the rule, env.md); dev: also the `/media` path |
| `R2_PUBLIC_URL` | ⬜ (✅ prod only with `storage: { requirePublicUrl: true }`) | storage | media domain attached to the bucket; empty = media through the app (§6); dev: also the `/media` path |
| `IPAL_IP_HEADER` | ⬜ (✅ prod) | forms | header with the real IP for the rate limit (`cf-connecting-ip`, `x-forwarded-for`); without it, a warning in the log |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | ⬜ | forms | fallback when the Turnstile keys are not in Site Integrations |
| `INDEXNOW_KEY` | ⬜ | SEO | IndexNow key (takes precedence over the key from the panel) |
@@ -438,8 +438,8 @@ be attached. Options, in order of preference:
1. **Serve media through the app (default)** — leave `R2_PUBLIC_URL` empty. Files are stored in R2, Payload serves
them at `/api/media/file/<name>` on the site's own domain: no DNS record, works on any zone. Cost: media traffic
passes through the app (next/image caches optimized variants); relax the `R2_PUBLIC_URL` rule in
`ipalEnvRules` (env.md). Details: storage.md.
passes through the app (next/image caches optimized variants); `ipalEnvRules({ storage: true })` accepts an
empty `R2_PUBLIC_URL` (env.md). Details: storage.md.
2. **A dedicated media domain on Cloudflare** — a separate domain whose zone is in our Cloudflare account (e.g.
`klient-media.com`), attached as the bucket's Custom Domain → `R2_PUBLIC_URL=https://<that domain>`. CDN and
cache rules included; for media-heavy sites.
+11 -13
View File
@@ -59,7 +59,7 @@ use).
```ts
ipalEnvRules({
storage?: boolean, // R2_* (R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_ENDPOINT, R2_PUBLIC_URL)
storage?: boolean | { requirePublicUrl?: boolean }, // R2_* (R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_ENDPOINT; R2_PUBLIC_URL optional)
emailGraph?: boolean, // GRAPH_* (GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER — e-mail)
ipHeader?: boolean, // IPAL_IP_HEADER — required in production, optional outside it (header name [a-z0-9-])
turnstile?: boolean | { siteKeyVar?: string; secretVar?: string }, // NEXT_PUBLIC_TURNSTILE_SITE_KEY, TURNSTILE_SECRET_KEY
@@ -75,11 +75,13 @@ Always (core): `DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` (URL),
read; DB/secret are Payload variables — their names can be overridden.
**`storage: true` — when R2_* are required** (evaluated when `ipalEnvRules` is called):
- `NODE_ENV=production` → all 5 (`R2_PUBLIC_URL` as an absolute URL);
- outside production, when any of the 4 keys is set (`R2_BUCKET`, `R2_ACCESS_KEY_ID`,
`R2_SECRET_ACCESS_KEY`, `R2_ENDPOINT`) → all 5 (all or none);
- `NODE_ENV=production` → the 4 keys (`R2_BUCKET`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_ENDPOINT`);
- outside production, when any of the 4 keys is set → all 4 (all or none);
- outside production without keys → none required (local disk); `R2_PUBLIC_URL` alone passes
(read-only mode, storage.md).
- `R2_PUBLIC_URL` is **optional**: empty = media served by the app. When set, it must be an absolute URL in
production. `storage: { requirePublicUrl: true }` requires it wherever the 4 keys are required (a project
that always uses a media domain).
**`turnstile: true`** makes both Turnstile variables **required**, even though the plugin takes the keys
from the panel first (Site Integrations) and env is only a fallback — turn it on only when you keep the keys
@@ -154,17 +156,13 @@ import type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from '@intec
## `R2_PUBLIC_URL` — production vs dev
`ipalEnvRules({ storage: true })` requires a full URL in **production**
(`https://media.klient-media.com`). Our default, though, is media served through the app with
`R2_PUBLIC_URL` **empty** (the client zones are not on Cloudflare — storage.md, deployment.md §6) — then make the
rule optional (the URL format is still checked when set):
`R2_PUBLIC_URL` is optional in `ipalEnvRules({ storage: true })`: our default is media served through the app
with `R2_PUBLIC_URL` **empty** (the client zones are not on Cloudflare — storage.md, deployment.md §6). When it is
set, **production** requires a full URL (`https://media.klient-media.com`). A project that always uses a media
domain requires it:
```ts
assertEnv(
ipalEnvRules({ storage: true, ipHeader: true }).map((r) =>
r.name === 'R2_PUBLIC_URL' ? { ...r, required: false } : r,
),
)
assertEnv(ipalEnvRules({ storage: { requirePublicUrl: true }, ipHeader: true }))
```
Outside production it allows a relative path
+1
View File
@@ -29,6 +29,7 @@ ipalKit({
// autoFill: false, // turn off auto-fill
// descriptionCheck: { settingsSlug: 'site-settings', siteDescriptionField: 'siteDescription' },
// descriptionCheck: false, // no hint under the description
// uploadsCollection: 'images', // meta image upload collection (default 'media')
},
})
```
+2 -9
View File
@@ -98,15 +98,8 @@ Requirements and consequences:
- **Public read on the upload collection** — the file route checks the collection's `read` access, and Payload's
default is "logged-in users only" → anonymous visitors (and next/image) get 403. Add
`access: { read: () => true }` to `Media` (and every other public upload collection).
- **Env validation** — `ipalEnvRules({ storage: true })` requires `R2_PUBLIC_URL` in production; make it optional:
```ts
assertEnv(
ipalEnvRules({ storage: true, ipHeader: true }).map((r) =>
r.name === 'R2_PUBLIC_URL' ? { ...r, required: false } : r,
),
)
```
- **Env validation** — nothing to change: `ipalEnvRules({ storage: true })` treats `R2_PUBLIC_URL` as optional
(`storage: { requirePublicUrl: true }` makes it required, for projects that always use a media domain).
- next/image treats the URLs as local images; CSP `img-src 'self'` already covers them; `MediaPreconnect` renders
nothing (same origin); the plugin's sitemap / JSON-LD helpers make relative image URLs absolute.
- Cost: every original file request passes through the app (bandwidth/CPU). Page images go through `/_next/image`,
+2 -2
View File
@@ -1,6 +1,6 @@
import type { GlobalConfig } from 'payload'
import { adminOrEditor } from '../../modules/access/index.js'
import { userMeetsRole } from '../../modules/access/index.js'
import { cookieSettingsFields } from './fields.js'
/**
@@ -12,7 +12,7 @@ export function buildCookieSettings(): GlobalConfig {
slug: 'cookie-settings',
access: {
read: () => true,
update: adminOrEditor, // consent texts are legal copy — not for plain 'user' accounts
update: ({ req }) => userMeetsRole(req, 'editor'), // consent texts are legal copy — not for plain 'user' accounts
},
admin: {
group: 'Settings',
+2 -2
View File
@@ -1,6 +1,6 @@
import type { GlobalConfig } from 'payload'
import { adminOrEditor } from '../../modules/access/index.js'
import { userMeetsRole } from '../../modules/access/index.js'
import { notificationsFields } from './fields.js'
/**
@@ -13,7 +13,7 @@ export function buildNotifications(): GlobalConfig {
slug: 'notifications',
access: {
read: () => true, // texts are public-facing (shown to end users)
update: adminOrEditor,
update: ({ req }) => userMeetsRole(req, 'editor'),
},
admin: { group: 'Settings' },
fields: notificationsFields,
+4 -3
View File
@@ -1,6 +1,6 @@
import type { Field, GlobalConfig } from 'payload'
import { isAdmin } from '../../modules/access/index.js'
import { userMeetsRole } from '../../modules/access/index.js'
import { indexNowFields } from '../../modules/seo/indexNow.js'
import { analyticsFields } from './fields/analytics.js'
import { smtpFields } from './fields/smtp.js'
@@ -31,8 +31,9 @@ export function buildSiteIntegrations({
access: {
// Admin-only — secrets live here. Anonymous and non-admin users get
// nothing through the API; admins read/edit in the panel and via Local API.
read: ({ req: { user } }) => isAdmin(user),
update: ({ req: { user } }) => isAdmin(user),
// Without roles (no `access` option) every logged-in account is admin.
read: ({ req }) => userMeetsRole(req, 'admin'),
update: ({ req }) => userMeetsRole(req, 'admin'),
},
admin: {
group: 'Settings',
+2 -2
View File
@@ -1,6 +1,6 @@
import type { Field, GlobalConfig } from 'payload'
import { adminOrEditor } from '../../modules/access/index.js'
import { userMeetsRole } from '../../modules/access/index.js'
import { generalFields } from './fields/general.js'
import { themeFields } from './fields/theme.js'
@@ -48,7 +48,7 @@ export function buildSiteSettings({
read: () => true,
// Editors and admins only — a plain 'user' account (open sign-up) must
// not rewrite the brand, homepage or construction mode.
update: adminOrEditor,
update: ({ req }) => userMeetsRole(req, 'editor'),
},
admin: {
group: 'Settings',
+1
View File
@@ -16,6 +16,7 @@ export {
requireRole,
requireRoleField,
ROLE_HIERARCHY,
userMeetsRole,
} from './modules/access/index.js'
// Concrete files, not module barrels: a barrel that also re-exports 'use client'
// components would load React UI into payload.config / the CLI (test/entryGraph).
+1 -1
View File
@@ -9,7 +9,7 @@ export {
requireRoleField,
} from './access.js'
export { injectRoles } from './injectRoles.js'
export { hasMinimumRole, isAdmin, isEditor } from './predicates.js'
export { hasMinimumRole, isAdmin, isEditor, userMeetsRole } from './predicates.js'
export { buildRolesField } from './rolesField.js'
export type { AccessOption, Role } from './types.js'
export { ROLE_HIERARCHY } from './types.js'
+23
View File
@@ -1,3 +1,5 @@
import type { BasePayload } from 'payload'
import type { Role } from './types.js'
import { ROLE_HIERARCHY } from './types.js'
@@ -42,3 +44,24 @@ export function isAdmin(user: MaybeUser): boolean {
export function isEditor(user: MaybeUser): boolean {
return hasMinimumRole(user, 'editor')
}
/**
* Role check for the plugin's own staff features (Site Integrations, the
* e-mail test, stats, consent records, form submissions, the settings
* globals): true when the user holds at least `minimum` — or, when the
* user's auth collection has no `roles` field (the project omitted `access`),
* for every logged-in user. Without roles all accounts are equal, as in
* Payload's own default; nobody being "admin" would lock those features away.
*
* Pass `req` (it has `payload` and `user`). An unknown collection counts as
* having roles — the strict side. A project with its own role scheme in
* another field narrows access through globalOverrides / collection overrides.
*/
export function userMeetsRole({ payload, user }: { payload?: BasePayload; user?: unknown }, minimum: Role): boolean {
if (!user || typeof user !== 'object') {return false}
if (hasMinimumRole(user as MaybeUser, minimum)) {return true}
const slug = (user as { collection?: unknown }).collection
const fields = typeof slug === 'string' ? payload?.collections?.[slug as never]?.config.fields : undefined
if (!fields) {return false}
return !fields.some((f) => 'name' in f && f.name === 'roles')
}
+3 -3
View File
@@ -1,6 +1,6 @@
import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload'
import { isAdmin } from '../access/predicates.js'
import { userMeetsRole } from '../access/predicates.js'
import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { CONSENT_CATEGORIES } from './categories.js'
@@ -30,8 +30,8 @@ export function buildConsentLogCollection(): CollectionConfig {
access: {
// Written only by the endpoint (Local API); read and pruned by admins.
create: () => false,
delete: ({ req: { user } }) => isAdmin(user),
read: ({ req: { user } }) => isAdmin(user),
delete: ({ req }) => userMeetsRole(req, 'admin'),
read: ({ req }) => userMeetsRole(req, 'admin'),
update: () => false,
},
admin: {
+2 -2
View File
@@ -2,7 +2,7 @@ import type { Endpoint, PayloadRequest } from 'payload'
import { addDataAndFileToRequest } from 'payload'
import { isAdmin } from '../../access/predicates.js'
import { userMeetsRole } from '../../access/predicates.js'
/**
* Custom endpoint: send a test email to a given address through whatever
@@ -24,7 +24,7 @@ export const testEmailEndpoint: Endpoint = {
if (!req.user) {
return Response.json({ error: 'Unauthorized', ok: false }, { status: 401 })
}
if (!isAdmin(req.user)) {
if (!userMeetsRole(req, 'admin')) {
return Response.json({ error: 'Forbidden', ok: false }, { status: 403 })
}
+12 -7
View File
@@ -17,12 +17,16 @@ export type IpalEnvFeatures = {
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
serverUrlVar?: string
/**
* R2 object storage (buildR2Storage). Adds the R2_* vars — required in
* production (media on a container disk vanish on redeploy). Outside
* production they're optional (media go to the local disk), but a partial
* set is an error: buildR2Storage needs all of them.
* R2 object storage (buildR2Storage). Adds the R2_* vars — the credentials
* are required in production (media on a container disk vanish on redeploy).
* Outside production they're optional (media go to the local disk), but a
* partial set is an error: buildR2Storage needs all of them.
*
* R2_PUBLIC_URL is optional: empty = media served by the app
* (/api/media/file/…). `{ requirePublicUrl: true }` requires it wherever the
* credentials are required (a media domain on Cloudflare).
*/
storage?: boolean
storage?: { requirePublicUrl?: boolean } | boolean
/**
* Cloudflare Turnstile. true uses the common var names
* (NEXT_PUBLIC_TURNSTILE_SITE_KEY + TURNSTILE_SECRET_KEY); pass an object to
@@ -74,6 +78,7 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
]
if (storage) {
const requirePublicUrl = typeof storage === 'object' && storage.requirePublicUrl === true
const r2Credentials = ['R2_BUCKET', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_ENDPOINT']
// Production: always. Development: once any credential is set (all or nothing).
// R2_PUBLIC_URL alone is the read-only media mode (buildR2Storage) — allowed in dev.
@@ -86,8 +91,8 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
{ name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url', required: r2Required },
{
name: 'R2_PUBLIC_URL',
description: 'Public base URL media is served from (custom domain of the bucket)',
required: r2Required,
description: 'Public base URL media is served from (custom domain of the bucket); empty = served by the app',
required: requirePublicUrl && r2Required,
// Production: absolute URL (https://media.example.com). Outside production a
// site-relative path ('/media') is accepted — buildR2Storage prefixes it with
// NEXT_PUBLIC_SERVER_URL (e.g. a dev rewrite /media → bucket).
+4 -4
View File
@@ -5,7 +5,7 @@ import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-f
import type { FormsOption } from './types.js'
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
import { userMeetsRole } from '../access/predicates.js'
import { checkboxGroupBlock, stepBlock, timeBlock, withPlaceholder, withShowWhen } from './builderBlocks.js'
import { buildEmailLayoutHook } from './emailLayout.js'
@@ -24,13 +24,13 @@ const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
* form-builder default lets ANY account of the admin collection read them —
* including a plain 'user' from an open sign-up.
*/
const submissionsReadAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, 'editor')
const submissionsDeleteAccess = ({ req }: AccessArgs) => isAdmin(req.user as never)
const submissionsReadAccess = ({ req }: AccessArgs) => userMeetsRole(req, 'editor')
const submissionsDeleteAccess = ({ req }: AccessArgs) => userMeetsRole(req, 'admin')
/**
* Forms carry recipient addresses (Emails → To/BCC): a plain 'user' account
* editing a form could BCC every submission to itself. Editors and admins only.
*/
const staffAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, 'editor')
const staffAccess = ({ req }: AccessArgs) => userMeetsRole(req, 'editor')
/**
* Forms stay publicly readable (their fields render the form), but the Emails
+2 -2
View File
@@ -6,7 +6,7 @@ import type { SeoOption } from './types.js'
type BuildSeoPluginArgs = {
seo: SeoOption
/** Upload collection slug for the meta image (typically 'media'). */
/** Upload collection slug for the meta image. Default `seo.uploadsCollection`, then 'media'. */
uploadsCollection?: string
}
@@ -67,7 +67,7 @@ function afterDescription(fields: Field[], extra: Field | null): Field[] {
* slug) already sit in the collection, leaving an empty SEO tab. Instead the
* SEO UI fields are injected into a controlled tab by injectSeoTabs.
*/
export function buildSeoPlugin({ seo, uploadsCollection = 'media' }: BuildSeoPluginArgs): Plugin {
export function buildSeoPlugin({ seo, uploadsCollection = seo.uploadsCollection ?? 'media' }: BuildSeoPluginArgs): Plugin {
return seoPlugin({
collections: seo.collections,
fields: ({ defaultFields }) => [
+2
View File
@@ -45,6 +45,8 @@ export type SeoOption = {
* aiCrawlers, llmsIntro) or read your own fields in your routes.
*/
searchSettings?: ((defaults: Field[]) => Field[]) | false
/** Upload collection the meta image (`meta.image`) relates to. Default 'media'. */
uploadsCollection?: string
}
/**
+2 -2
View File
@@ -5,7 +5,7 @@ import { Gutter } from '@payloadcms/ui'
import type { StatsVisit } from '../collection.js'
import { isAdmin } from '../../access/predicates.js'
import { userMeetsRole } from '../../access/predicates.js'
import { VISITOR_ID_PATTERN } from '../parse.js'
import { loadRecentVisitors, loadStats, loadVisitor } from './loadStats.js'
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
@@ -88,7 +88,7 @@ export async function StatsView(props: Props) {
const visitorId = visitorParam && VISITOR_ID_PATTERN.test(visitorParam) ? visitorParam : undefined
let content: React.ReactNode
if (!isAdmin(req.user)) {
if (!userMeetsRole(req, 'admin')) {
content = <p>Statistics are available to administrators only.</p>
} else if (visitorId) {
content = <VisitorHistory base={base} timeZone={timeZone} visitorId={visitorId} visits={await loadVisitor(req.payload, visitorId)} />
+2 -2
View File
@@ -1,6 +1,6 @@
import type { Payload, PayloadRequest } from 'payload'
import { isAdmin } from '../../access/predicates.js'
import { userMeetsRole } from '../../access/predicates.js'
import { loadStats } from './loadStats.js'
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
@@ -19,7 +19,7 @@ type Props = {
* any error (DB not ready, collection missing).
*/
export async function StatsWidget({ adminRoute = '/admin', payload, req, timeZone = 'Europe/Warsaw', user }: Props) {
if (!payload || !isAdmin((req?.user ?? user) as never)) {return null}
if (!payload || !userMeetsRole({ payload, user: req?.user ?? user }, 'admin')) {return null}
let stats
try {
stats = await loadStats(payload, { timeZone })
+3 -3
View File
@@ -1,6 +1,6 @@
import type { CollectionConfig } from 'payload'
import { isAdmin } from '../access/predicates.js'
import { userMeetsRole } from '../access/predicates.js'
/**
* One document per visit (a run of page views with gaps under 30 minutes).
@@ -48,8 +48,8 @@ export function buildStatsCollection(): CollectionConfig {
// Written only by the hit endpoint (Local API); read and deleted by admins
// (deleting is how a visitor's erasure request is handled).
create: () => false,
delete: ({ req: { user } }) => isAdmin(user),
read: ({ req: { user } }) => isAdmin(user),
delete: ({ req }) => userMeetsRole(req, 'admin'),
read: ({ req }) => userMeetsRole(req, 'admin'),
update: () => false,
},
admin: {
+16 -2
View File
@@ -12,10 +12,10 @@ const r2 = {
R2_SECRET_ACCESS_KEY: 's',
}
function check(env: Record<string, string>) {
function check(env: Record<string, string>, storage: NonNullable<Parameters<typeof ipalEnvRules>[0]>['storage'] = true) {
vi.unstubAllEnvs()
for (const [k, v] of Object.entries(env)) {vi.stubEnv(k, v)}
return () => assertEnv(ipalEnvRules({ storage: true }), { env })
return () => assertEnv(ipalEnvRules({ storage }), { env })
}
afterEach(() => vi.unstubAllEnvs())
@@ -26,6 +26,20 @@ describe('ipalEnvRules({ storage })', () => {
expect(check({ ...base, ...r2, NODE_ENV: 'production' })).not.toThrow()
})
test('production: R2_PUBLIC_URL is optional by default (media served by the app)', () => {
const { R2_PUBLIC_URL: _unused, ...credentials } = r2
expect(check({ ...base, ...credentials, NODE_ENV: 'production' })).not.toThrow()
// still validated when set
expect(check({ ...base, ...r2, NODE_ENV: 'production', R2_PUBLIC_URL: '/media' })).toThrow(/absolute URL in production/)
})
test('requirePublicUrl: true makes R2_PUBLIC_URL required with the credentials', () => {
const { R2_PUBLIC_URL: _unused, ...credentials } = r2
expect(check({ ...base, ...credentials, NODE_ENV: 'production' }, { requirePublicUrl: true })).toThrow(/R2_PUBLIC_URL is required/)
expect(check({ ...base, ...r2, NODE_ENV: 'production' }, { requirePublicUrl: true })).not.toThrow()
expect(check({ ...base, NODE_ENV: 'development' }, { requirePublicUrl: true })).not.toThrow()
})
test('development: no R2 at all is fine (local disk)', () => {
expect(check({ ...base, NODE_ENV: 'development' })).not.toThrow()
})
+57
View File
@@ -86,3 +86,60 @@ describe('ipalKit — auth collection', () => {
expect(users?.[0].fields.some((f) => 'name' in f && f.name === 'fullName')).toBe(true)
})
})
describe('options that keep features reachable and overridable', () => {
const findField = (fields: unknown[], name: string): Record<string, unknown> | undefined => {
for (const f of fields as Record<string, unknown>[]) {
if (f.name === name) {return f}
const nested = [...((f.fields as unknown[]) ?? []), ...((f.tabs as { fields: unknown[] }[]) ?? []).flatMap((t) => t.fields)]
const hit = nested.length ? findField(nested, name) : undefined
if (hit) {return hit}
}
return undefined
}
const withPages = (): Config =>
({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }] },
],
secret: 'test',
}) as unknown as Config
test('seo.uploadsCollection: the meta image relates to the given upload collection (default media)', async () => {
const custom = await ipalKit({ i18n, seo: { collections: ['pages'], uploadsCollection: 'images' }, twoFactor: false })(withPages())
const meta = findField(custom.collections!.find((c) => c.slug === 'pages')!.fields, 'meta')!
expect(findField(meta.fields as unknown[], 'image')?.relationTo).toBe('images')
const plain = await ipalKit({ i18n, seo: { collections: ['pages'] }, twoFactor: false })(withPages())
const metaDefault = findField(plain.collections!.find((c) => c.slug === 'pages')!.fields, 'meta')!
expect(findField(metaDefault.fields as unknown[], 'image')?.relationTo).toBe('media')
})
test('without `access` (no roles field) admin and editor features stay reachable for logged-in users', async () => {
const config = await ipalKit({ consentLog: true, forms: {}, i18n, stats: true, twoFactor: false })(base())
const users = config.collections!.find((c) => c.slug === 'users')!
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } } }, user }) as never
const member = { id: 1, collection: 'users', email: '[email protected]' }
const run = (access: unknown, user: unknown) => (access as (a: { req: unknown }) => unknown)({ req: req(user) })
const integrations = config.globals!.find((g) => g.slug === 'site-integrations')!
expect(run(integrations.access!.read, member)).toBe(true)
expect(run(integrations.access!.read, null)).toBe(false)
expect(run(config.globals!.find((g) => g.slug === 'site-settings')!.access!.update, member)).toBe(true)
expect(run(config.collections!.find((c) => c.slug === 'stats-visits')!.access!.read, member)).toBe(true)
expect(run(config.collections!.find((c) => c.slug === 'consent-records')!.access!.read, member)).toBe(true)
expect(run(config.collections!.find((c) => c.slug === 'form-submissions')!.access!.read, member)).toBe(true)
})
test('with `access` the roles still decide', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, stats: true, twoFactor: false })(base())
const users = config.collections!.find((c) => c.slug === 'users')!
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } } }, user }) as never
const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: { req: unknown }) => unknown
expect(read({ req: req({ id: 1, collection: 'users', roles: ['editor'] }) })).toBe(false)
expect(read({ req: req({ id: 1, collection: 'users', roles: ['admin'] }) })).toBe(true)
// unknown collection = the strict side
expect(read({ req: { payload: { collections: {} }, user: { id: 1, collection: 'other' } } })).toBe(false)
})
})