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:
co-authored by
Claude Opus 5.5
parent
cff76c2a69
commit
4911da7112
+8
-4
@@ -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)
|
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.
|
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
|
> **Without `access` there is no `roles` field**, so `isAdmin` always returns `false`. The plugin's own
|
||||||
> Integrations global and the `/api/ipal/test-email` endpoint then work only through the Local API
|
> staff features therefore check with `userMeetsRole(req, minimum)`: when the user's auth collection has no
|
||||||
> (`overrideAccess`). The seed / first user must have `roles: ['admin']`.
|
> `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)
|
## Predicates (front end / hooks / access)
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import { isAdmin, isEditor, hasMinimumRole } from '@intecion/ipal-kit'
|
import { isAdmin, isEditor, hasMinimumRole, userMeetsRole } from '@intecion/ipal-kit'
|
||||||
|
|
||||||
isAdmin(user) // admin?
|
isAdmin(user) // admin?
|
||||||
isEditor(user) // editor or admin (hierarchy)
|
isEditor(user) // editor or admin (hierarchy)
|
||||||
hasMinimumRole(user, 'editor') // at least editor
|
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.
|
They take a loosely typed user (like `req.user`) and read `roles` defensively.
|
||||||
|
|||||||
@@ -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 |
|
| `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` |
|
| `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) |
|
| `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 |
|
| `server-only` in the client | import from `@intecion/ipal-kit/server` in `'use client'` | call it through a server action |
|
||||||
|
|
||||||
### Admin panel (`/admin`)
|
### Admin panel (`/admin`)
|
||||||
|
|||||||
+4
-4
@@ -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) |
|
| `DATABASE_URI` | ✅ | infra | database connection (read by the project config, not the plugin) |
|
||||||
| `PAYLOAD_SECRET` | ✅ | infra | Payload secret (as above) |
|
| `PAYLOAD_SECRET` | ✅ | infra | Payload secret (as above) |
|
||||||
| `NEXT_PUBLIC_SERVER_URL` | ✅ | infra | public URL (canonical, OG, sitemap, IndexNow) |
|
| `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_TENANT_ID` | ⬜ | email | Azure tenant (Graph) |
|
||||||
| `GRAPH_CLIENT_ID` | ⬜ | email | Azure app id |
|
| `GRAPH_CLIENT_ID` | ⬜ | email | Azure app id |
|
||||||
| `GRAPH_CLIENT_SECRET` | ⬜ | email | Azure secret |
|
| `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_ENDPOINT` | ⬜ (✅ prod) | storage | R2 S3 endpoint |
|
||||||
| `R2_ACCESS_KEY_ID` | ⬜ (✅ prod) | storage | R2 key |
|
| `R2_ACCESS_KEY_ID` | ⬜ (✅ prod) | storage | R2 key |
|
||||||
| `R2_SECRET_ACCESS_KEY` | ⬜ (✅ prod) | storage | R2 secret |
|
| `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 |
|
| `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 |
|
| `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) |
|
| `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
|
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
|
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
|
passes through the app (next/image caches optimized variants); `ipalEnvRules({ storage: true })` accepts an
|
||||||
`ipalEnvRules` (env.md). Details: storage.md.
|
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.
|
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
|
`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.
|
cache rules included; for media-heavy sites.
|
||||||
|
|||||||
+11
-13
@@ -59,7 +59,7 @@ use).
|
|||||||
|
|
||||||
```ts
|
```ts
|
||||||
ipalEnvRules({
|
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)
|
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-])
|
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
|
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.
|
read; DB/secret are Payload variables — their names can be overridden.
|
||||||
|
|
||||||
**`storage: true` — when R2_* are required** (evaluated when `ipalEnvRules` is called):
|
**`storage: true` — when R2_* are required** (evaluated when `ipalEnvRules` is called):
|
||||||
- `NODE_ENV=production` → all 5 (`R2_PUBLIC_URL` as an absolute URL);
|
- `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 (`R2_BUCKET`, `R2_ACCESS_KEY_ID`,
|
- outside production, when any of the 4 keys is set → all 4 (all or none);
|
||||||
`R2_SECRET_ACCESS_KEY`, `R2_ENDPOINT`) → all 5 (all or none);
|
|
||||||
- outside production without keys → none required (local disk); `R2_PUBLIC_URL` alone passes
|
- outside production without keys → none required (local disk); `R2_PUBLIC_URL` alone passes
|
||||||
(read-only mode, storage.md).
|
(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
|
**`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
|
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
|
## `R2_PUBLIC_URL` — production vs dev
|
||||||
|
|
||||||
`ipalEnvRules({ storage: true })` requires a full URL in **production**
|
`R2_PUBLIC_URL` is optional in `ipalEnvRules({ storage: true })`: our default is media served through the app
|
||||||
(`https://media.klient-media.com`). Our default, though, is media served through the app with
|
with `R2_PUBLIC_URL` **empty** (the client zones are not on Cloudflare — storage.md, deployment.md §6). When it is
|
||||||
`R2_PUBLIC_URL` **empty** (the client zones are not on Cloudflare — storage.md, deployment.md §6) — then make the
|
set, **production** requires a full URL (`https://media.klient-media.com`). A project that always uses a media
|
||||||
rule optional (the URL format is still checked when set):
|
domain requires it:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
assertEnv(
|
assertEnv(ipalEnvRules({ storage: { requirePublicUrl: true }, ipHeader: true }))
|
||||||
ipalEnvRules({ storage: true, ipHeader: true }).map((r) =>
|
|
||||||
r.name === 'R2_PUBLIC_URL' ? { ...r, required: false } : r,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Outside production it allows a relative path
|
Outside production it allows a relative path
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ ipalKit({
|
|||||||
// autoFill: false, // turn off auto-fill
|
// autoFill: false, // turn off auto-fill
|
||||||
// descriptionCheck: { settingsSlug: 'site-settings', siteDescriptionField: 'siteDescription' },
|
// descriptionCheck: { settingsSlug: 'site-settings', siteDescriptionField: 'siteDescription' },
|
||||||
// descriptionCheck: false, // no hint under the description
|
// descriptionCheck: false, // no hint under the description
|
||||||
|
// uploadsCollection: 'images', // meta image upload collection (default 'media')
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|||||||
+2
-9
@@ -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
|
- **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
|
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).
|
`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:
|
- **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).
|
||||||
```ts
|
|
||||||
assertEnv(
|
|
||||||
ipalEnvRules({ storage: true, ipHeader: true }).map((r) =>
|
|
||||||
r.name === 'R2_PUBLIC_URL' ? { ...r, required: false } : r,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
```
|
|
||||||
- next/image treats the URLs as local images; CSP `img-src 'self'` already covers them; `MediaPreconnect` renders
|
- 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.
|
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`,
|
- Cost: every original file request passes through the app (bandwidth/CPU). Page images go through `/_next/image`,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { GlobalConfig } from 'payload'
|
import type { GlobalConfig } from 'payload'
|
||||||
|
|
||||||
import { adminOrEditor } from '../../modules/access/index.js'
|
import { userMeetsRole } from '../../modules/access/index.js'
|
||||||
import { cookieSettingsFields } from './fields.js'
|
import { cookieSettingsFields } from './fields.js'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -12,7 +12,7 @@ export function buildCookieSettings(): GlobalConfig {
|
|||||||
slug: 'cookie-settings',
|
slug: 'cookie-settings',
|
||||||
access: {
|
access: {
|
||||||
read: () => true,
|
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: {
|
admin: {
|
||||||
group: 'Settings',
|
group: 'Settings',
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { GlobalConfig } from 'payload'
|
import type { GlobalConfig } from 'payload'
|
||||||
|
|
||||||
import { adminOrEditor } from '../../modules/access/index.js'
|
import { userMeetsRole } from '../../modules/access/index.js'
|
||||||
import { notificationsFields } from './fields.js'
|
import { notificationsFields } from './fields.js'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -13,7 +13,7 @@ export function buildNotifications(): GlobalConfig {
|
|||||||
slug: 'notifications',
|
slug: 'notifications',
|
||||||
access: {
|
access: {
|
||||||
read: () => true, // texts are public-facing (shown to end users)
|
read: () => true, // texts are public-facing (shown to end users)
|
||||||
update: adminOrEditor,
|
update: ({ req }) => userMeetsRole(req, 'editor'),
|
||||||
},
|
},
|
||||||
admin: { group: 'Settings' },
|
admin: { group: 'Settings' },
|
||||||
fields: notificationsFields,
|
fields: notificationsFields,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { Field, GlobalConfig } from 'payload'
|
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 { indexNowFields } from '../../modules/seo/indexNow.js'
|
||||||
import { analyticsFields } from './fields/analytics.js'
|
import { analyticsFields } from './fields/analytics.js'
|
||||||
import { smtpFields } from './fields/smtp.js'
|
import { smtpFields } from './fields/smtp.js'
|
||||||
@@ -31,8 +31,9 @@ export function buildSiteIntegrations({
|
|||||||
access: {
|
access: {
|
||||||
// Admin-only — secrets live here. Anonymous and non-admin users get
|
// 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.
|
// nothing through the API; admins read/edit in the panel and via Local API.
|
||||||
read: ({ req: { user } }) => isAdmin(user),
|
// Without roles (no `access` option) every logged-in account is admin.
|
||||||
update: ({ req: { user } }) => isAdmin(user),
|
read: ({ req }) => userMeetsRole(req, 'admin'),
|
||||||
|
update: ({ req }) => userMeetsRole(req, 'admin'),
|
||||||
},
|
},
|
||||||
admin: {
|
admin: {
|
||||||
group: 'Settings',
|
group: 'Settings',
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { Field, GlobalConfig } from 'payload'
|
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 { generalFields } from './fields/general.js'
|
||||||
import { themeFields } from './fields/theme.js'
|
import { themeFields } from './fields/theme.js'
|
||||||
|
|
||||||
@@ -48,7 +48,7 @@ export function buildSiteSettings({
|
|||||||
read: () => true,
|
read: () => true,
|
||||||
// Editors and admins only — a plain 'user' account (open sign-up) must
|
// Editors and admins only — a plain 'user' account (open sign-up) must
|
||||||
// not rewrite the brand, homepage or construction mode.
|
// not rewrite the brand, homepage or construction mode.
|
||||||
update: adminOrEditor,
|
update: ({ req }) => userMeetsRole(req, 'editor'),
|
||||||
},
|
},
|
||||||
admin: {
|
admin: {
|
||||||
group: 'Settings',
|
group: 'Settings',
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ export {
|
|||||||
requireRole,
|
requireRole,
|
||||||
requireRoleField,
|
requireRoleField,
|
||||||
ROLE_HIERARCHY,
|
ROLE_HIERARCHY,
|
||||||
|
userMeetsRole,
|
||||||
} from './modules/access/index.js'
|
} from './modules/access/index.js'
|
||||||
// Concrete files, not module barrels: a barrel that also re-exports 'use client'
|
// 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).
|
// components would load React UI into payload.config / the CLI (test/entryGraph).
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ export {
|
|||||||
requireRoleField,
|
requireRoleField,
|
||||||
} from './access.js'
|
} from './access.js'
|
||||||
export { injectRoles } from './injectRoles.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 { buildRolesField } from './rolesField.js'
|
||||||
export type { AccessOption, Role } from './types.js'
|
export type { AccessOption, Role } from './types.js'
|
||||||
export { ROLE_HIERARCHY } from './types.js'
|
export { ROLE_HIERARCHY } from './types.js'
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { BasePayload } from 'payload'
|
||||||
|
|
||||||
import type { Role } from './types.js'
|
import type { Role } from './types.js'
|
||||||
|
|
||||||
import { ROLE_HIERARCHY } 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 {
|
export function isEditor(user: MaybeUser): boolean {
|
||||||
return hasMinimumRole(user, 'editor')
|
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')
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload'
|
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 { createDailyPurge } from '../shared/purge.js'
|
||||||
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
|
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
|
||||||
import { CONSENT_CATEGORIES } from './categories.js'
|
import { CONSENT_CATEGORIES } from './categories.js'
|
||||||
@@ -30,8 +30,8 @@ export function buildConsentLogCollection(): CollectionConfig {
|
|||||||
access: {
|
access: {
|
||||||
// Written only by the endpoint (Local API); read and pruned by admins.
|
// Written only by the endpoint (Local API); read and pruned by admins.
|
||||||
create: () => false,
|
create: () => false,
|
||||||
delete: ({ req: { user } }) => isAdmin(user),
|
delete: ({ req }) => userMeetsRole(req, 'admin'),
|
||||||
read: ({ req: { user } }) => isAdmin(user),
|
read: ({ req }) => userMeetsRole(req, 'admin'),
|
||||||
update: () => false,
|
update: () => false,
|
||||||
},
|
},
|
||||||
admin: {
|
admin: {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { Endpoint, PayloadRequest } from 'payload'
|
|||||||
|
|
||||||
import { addDataAndFileToRequest } 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
|
* Custom endpoint: send a test email to a given address through whatever
|
||||||
@@ -24,7 +24,7 @@ export const testEmailEndpoint: Endpoint = {
|
|||||||
if (!req.user) {
|
if (!req.user) {
|
||||||
return Response.json({ error: 'Unauthorized', ok: false }, { status: 401 })
|
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 })
|
return Response.json({ error: 'Forbidden', ok: false }, { status: 403 })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Vendored
+12
-7
@@ -17,12 +17,16 @@ export type IpalEnvFeatures = {
|
|||||||
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
|
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
|
||||||
serverUrlVar?: string
|
serverUrlVar?: string
|
||||||
/**
|
/**
|
||||||
* R2 object storage (buildR2Storage). Adds the R2_* vars — required in
|
* R2 object storage (buildR2Storage). Adds the R2_* vars — the credentials
|
||||||
* production (media on a container disk vanish on redeploy). Outside
|
* are required in production (media on a container disk vanish on redeploy).
|
||||||
* production they're optional (media go to the local disk), but a partial
|
* Outside production they're optional (media go to the local disk), but a
|
||||||
* set is an error: buildR2Storage needs all of them.
|
* 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
|
* Cloudflare Turnstile. true uses the common var names
|
||||||
* (NEXT_PUBLIC_TURNSTILE_SITE_KEY + TURNSTILE_SECRET_KEY); pass an object to
|
* (NEXT_PUBLIC_TURNSTILE_SITE_KEY + TURNSTILE_SECRET_KEY); pass an object to
|
||||||
@@ -74,6 +78,7 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
|
|||||||
]
|
]
|
||||||
|
|
||||||
if (storage) {
|
if (storage) {
|
||||||
|
const requirePublicUrl = typeof storage === 'object' && storage.requirePublicUrl === true
|
||||||
const r2Credentials = ['R2_BUCKET', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_ENDPOINT']
|
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).
|
// 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.
|
// 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_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url', required: r2Required },
|
||||||
{
|
{
|
||||||
name: 'R2_PUBLIC_URL',
|
name: 'R2_PUBLIC_URL',
|
||||||
description: 'Public base URL media is served from (custom domain of the bucket)',
|
description: 'Public base URL media is served from (custom domain of the bucket); empty = served by the app',
|
||||||
required: r2Required,
|
required: requirePublicUrl && r2Required,
|
||||||
// Production: absolute URL (https://media.example.com). Outside production a
|
// Production: absolute URL (https://media.example.com). Outside production a
|
||||||
// site-relative path ('/media') is accepted — buildR2Storage prefixes it with
|
// site-relative path ('/media') is accepted — buildR2Storage prefixes it with
|
||||||
// NEXT_PUBLIC_SERVER_URL (e.g. a dev rewrite /media → bucket).
|
// NEXT_PUBLIC_SERVER_URL (e.g. a dev rewrite /media → bucket).
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-f
|
|||||||
|
|
||||||
import type { FormsOption } from './types.js'
|
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 { checkboxGroupBlock, stepBlock, timeBlock, withPlaceholder, withShowWhen } from './builderBlocks.js'
|
||||||
import { buildEmailLayoutHook } from './emailLayout.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 —
|
* form-builder default lets ANY account of the admin collection read them —
|
||||||
* including a plain 'user' from an open sign-up.
|
* including a plain 'user' from an open sign-up.
|
||||||
*/
|
*/
|
||||||
const submissionsReadAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, 'editor')
|
const submissionsReadAccess = ({ req }: AccessArgs) => userMeetsRole(req, 'editor')
|
||||||
const submissionsDeleteAccess = ({ req }: AccessArgs) => isAdmin(req.user as never)
|
const submissionsDeleteAccess = ({ req }: AccessArgs) => userMeetsRole(req, 'admin')
|
||||||
/**
|
/**
|
||||||
* Forms carry recipient addresses (Emails → To/BCC): a plain 'user' account
|
* Forms carry recipient addresses (Emails → To/BCC): a plain 'user' account
|
||||||
* editing a form could BCC every submission to itself. Editors and admins only.
|
* 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
|
* Forms stay publicly readable (their fields render the form), but the Emails
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import type { SeoOption } from './types.js'
|
|||||||
|
|
||||||
type BuildSeoPluginArgs = {
|
type BuildSeoPluginArgs = {
|
||||||
seo: SeoOption
|
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
|
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
|
* slug) already sit in the collection, leaving an empty SEO tab. Instead the
|
||||||
* SEO UI fields are injected into a controlled tab by injectSeoTabs.
|
* 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({
|
return seoPlugin({
|
||||||
collections: seo.collections,
|
collections: seo.collections,
|
||||||
fields: ({ defaultFields }) => [
|
fields: ({ defaultFields }) => [
|
||||||
|
|||||||
@@ -45,6 +45,8 @@ export type SeoOption = {
|
|||||||
* aiCrawlers, llmsIntro) or read your own fields in your routes.
|
* aiCrawlers, llmsIntro) or read your own fields in your routes.
|
||||||
*/
|
*/
|
||||||
searchSettings?: ((defaults: Field[]) => Field[]) | false
|
searchSettings?: ((defaults: Field[]) => Field[]) | false
|
||||||
|
/** Upload collection the meta image (`meta.image`) relates to. Default 'media'. */
|
||||||
|
uploadsCollection?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { Gutter } from '@payloadcms/ui'
|
|||||||
|
|
||||||
import type { StatsVisit } from '../collection.js'
|
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 { VISITOR_ID_PATTERN } from '../parse.js'
|
||||||
import { loadRecentVisitors, loadStats, loadVisitor } from './loadStats.js'
|
import { loadRecentVisitors, loadStats, loadVisitor } from './loadStats.js'
|
||||||
import { STATS_CSS, VisitsChart } from './VisitsChart.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
|
const visitorId = visitorParam && VISITOR_ID_PATTERN.test(visitorParam) ? visitorParam : undefined
|
||||||
|
|
||||||
let content: React.ReactNode
|
let content: React.ReactNode
|
||||||
if (!isAdmin(req.user)) {
|
if (!userMeetsRole(req, 'admin')) {
|
||||||
content = <p>Statistics are available to administrators only.</p>
|
content = <p>Statistics are available to administrators only.</p>
|
||||||
} else if (visitorId) {
|
} else if (visitorId) {
|
||||||
content = <VisitorHistory base={base} timeZone={timeZone} visitorId={visitorId} visits={await loadVisitor(req.payload, visitorId)} />
|
content = <VisitorHistory base={base} timeZone={timeZone} visitorId={visitorId} visits={await loadVisitor(req.payload, visitorId)} />
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { Payload, PayloadRequest } from 'payload'
|
import type { Payload, PayloadRequest } from 'payload'
|
||||||
|
|
||||||
import { isAdmin } from '../../access/predicates.js'
|
import { userMeetsRole } from '../../access/predicates.js'
|
||||||
import { loadStats } from './loadStats.js'
|
import { loadStats } from './loadStats.js'
|
||||||
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
|
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@ type Props = {
|
|||||||
* any error (DB not ready, collection missing).
|
* any error (DB not ready, collection missing).
|
||||||
*/
|
*/
|
||||||
export async function StatsWidget({ adminRoute = '/admin', payload, req, timeZone = 'Europe/Warsaw', user }: Props) {
|
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
|
let stats
|
||||||
try {
|
try {
|
||||||
stats = await loadStats(payload, { timeZone })
|
stats = await loadStats(payload, { timeZone })
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { CollectionConfig } from 'payload'
|
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).
|
* 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
|
// Written only by the hit endpoint (Local API); read and deleted by admins
|
||||||
// (deleting is how a visitor's erasure request is handled).
|
// (deleting is how a visitor's erasure request is handled).
|
||||||
create: () => false,
|
create: () => false,
|
||||||
delete: ({ req: { user } }) => isAdmin(user),
|
delete: ({ req }) => userMeetsRole(req, 'admin'),
|
||||||
read: ({ req: { user } }) => isAdmin(user),
|
read: ({ req }) => userMeetsRole(req, 'admin'),
|
||||||
update: () => false,
|
update: () => false,
|
||||||
},
|
},
|
||||||
admin: {
|
admin: {
|
||||||
|
|||||||
+16
-2
@@ -12,10 +12,10 @@ const r2 = {
|
|||||||
R2_SECRET_ACCESS_KEY: 's',
|
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()
|
vi.unstubAllEnvs()
|
||||||
for (const [k, v] of Object.entries(env)) {vi.stubEnv(k, v)}
|
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())
|
afterEach(() => vi.unstubAllEnvs())
|
||||||
@@ -26,6 +26,20 @@ describe('ipalEnvRules({ storage })', () => {
|
|||||||
expect(check({ ...base, ...r2, NODE_ENV: 'production' })).not.toThrow()
|
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)', () => {
|
test('development: no R2 at all is fine (local disk)', () => {
|
||||||
expect(check({ ...base, NODE_ENV: 'development' })).not.toThrow()
|
expect(check({ ...base, NODE_ENV: 'development' })).not.toThrow()
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -86,3 +86,60 @@ describe('ipalKit — auth collection', () => {
|
|||||||
expect(users?.[0].fields.some((f) => 'name' in f && f.name === 'fullName')).toBe(true)
|
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)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user