Merge local main (1.17.2) into security-a-118
Conflicts resolved by keeping both sides: lockedAnswer + sign-in rules in plugin.ts and switches.ts, IPv6 grouping in the mail service's new per-visitor address count, both built-site specs in e2e:built, docs and skills (reference copies synced). The lockedAnswer suite and the sign-in-answers spec now reach Payload's lock the 1.18.0 way: a spray from 50 IPs, one failure each (one IP alone gets 429 after five). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -21,17 +21,51 @@ export const requireRole = (minimum: Role): Access => {
|
||||
return ({ req }) => hasMinimumRole(req.user, minimum, req.payload)
|
||||
}
|
||||
|
||||
/** Marks a `readPublished()` rule, so the plugin can give `readVersions` the version form of it (a symbol, not a name). */
|
||||
export const READ_PUBLISHED = Symbol.for('iapl.readPublished')
|
||||
|
||||
/**
|
||||
* Read rule for a collection with drafts: staff of `minimum` role or higher (default editor) read everything,
|
||||
* drafts and versions included; everybody else (visitors, plain `user` accounts, a session that still owes its
|
||||
* Read rule for a collection (or a global) with drafts: staff of `minimum` role or higher (default editor) read
|
||||
* everything, drafts included; everybody else (visitors, plain `user` accounts, a session that still owes its
|
||||
* second factor) reads 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 (IAWL idea 23).
|
||||
*
|
||||
* access: { read: readPublished(), readVersions: readPublished() }
|
||||
* For `read`. Version history (`readVersions`) asks for the status at another path (`version._status`): use
|
||||
* `readPublishedVersions()` there. Given to `readVersions` of a collection or global that iapl() sees, this rule
|
||||
* is swapped for `readPublishedVersions()` with the same role (1.17.2; in 1.17.1 it answered 500 there).
|
||||
*
|
||||
* access: { read: readPublished(), readVersions: readPublishedVersions() }
|
||||
*/
|
||||
export const readPublished = (minimum: Role = 'editor'): Access => {
|
||||
assertKnownRole('readPublished', minimum)
|
||||
return ({ req }) => (hasMinimumRole(req.user, minimum, req.payload) ? true : { _status: { equals: 'published' } })
|
||||
const rule: Access = ({ req }) => (hasMinimumRole(req.user, minimum, req.payload) ? true : { _status: { equals: 'published' } })
|
||||
return Object.assign(rule, { [READ_PUBLISHED]: minimum })
|
||||
}
|
||||
|
||||
/**
|
||||
* The version-history form of `readPublished()`, for `readVersions`: staff of `minimum` role or higher read every
|
||||
* version; everybody else reads published versions only — the list, one version by id, the count, REST, GraphQL,
|
||||
* the Local API with access control. A version query runs on the versions collection, where the status is
|
||||
* `version._status` (a `_status` condition there is an unknown path: 500 on every database adapter).
|
||||
*/
|
||||
export const readPublishedVersions = (minimum: Role = 'editor'): Access => {
|
||||
assertKnownRole('readPublishedVersions', minimum)
|
||||
return ({ req }) => (hasMinimumRole(req.user, minimum, req.payload) ? true : { 'version._status': { equals: 'published' } })
|
||||
}
|
||||
|
||||
type WithAccess = { access?: { readVersions?: unknown } }
|
||||
|
||||
/**
|
||||
* Gives every `readVersions: readPublished()` the version form (`readPublishedVersions()` with the same role).
|
||||
* iapl() runs it on the collections and globals it sees; a plugin listed after iapl() uses
|
||||
* `readPublishedVersions()` itself, or runs this on its own entities.
|
||||
*/
|
||||
export function withVersionReadRules<T extends WithAccess>(entities: T[] | undefined): T[] | undefined {
|
||||
return entities?.map((entity) => {
|
||||
const rule = entity.access?.readVersions as (object & Partial<Record<typeof READ_PUBLISHED, Role>>) | undefined
|
||||
const minimum = rule && typeof rule === 'function' ? rule[READ_PUBLISHED] : undefined
|
||||
return minimum ? { ...entity, access: { ...entity.access, readVersions: readPublishedVersions(minimum) } } : entity
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,9 +6,12 @@ export {
|
||||
adminOrSelf,
|
||||
adminOrSelfIn,
|
||||
authenticated,
|
||||
READ_PUBLISHED,
|
||||
readPublished,
|
||||
readPublishedVersions,
|
||||
requireRole,
|
||||
requireRoleField,
|
||||
withVersionReadRules,
|
||||
} from './access.js'
|
||||
export { injectRoles } from './injectRoles.js'
|
||||
export { clearStaffRegistry, hasMinimumRole, isAdmin, isEditor, registerStaffCollections, staffCollectionSlugs, userMeetsRole } from './predicates.js'
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { AfterErrorHook, Config, SanitizedCollectionConfig } from 'payload'
|
||||
|
||||
import { AuthenticationError, formatNames, toWords } from 'payload'
|
||||
|
||||
import { staffCollectionSlugs } from './predicates.js'
|
||||
|
||||
/**
|
||||
* A locked staff account answers its login exactly like a wrong password (`accounts.lockedAnswer`, 1.17.2).
|
||||
*
|
||||
* Payload checks the lock BEFORE the password: after five wrong passwords for `owner@site` any password gets
|
||||
* `401 "This user is locked due to having too many failed login attempts."` (GraphQL: `LockedAuth`), while an
|
||||
* address that has no account always gets `401 "The email or password provided is incorrect."`. Anybody could
|
||||
* tell which addresses have a staff account with no password at all (IAWL idea 6). This hook turns Payload's
|
||||
* `LockedAuth` on a staff collection's login into the `AuthenticationError` answer — same status, same body, same
|
||||
* GraphQL `extensions.name`. The price: the owner, while locked, is told "wrong e-mail or password" too.
|
||||
*
|
||||
* The lock itself is not touched (it still holds for `lockTime`). `accounts: { lockedAnswer: 'payload' }` keeps
|
||||
* Payload's message. The error is recognised by its `name` (`'LockedAuth'`, a string Payload sets — not a function
|
||||
* name, so a minified bundle keeps it) and by the collection: a staff collection only.
|
||||
*/
|
||||
export type LockedAnswerOption = 'payload' | 'wrong'
|
||||
|
||||
const isLocked = (error: unknown): boolean => (error as { name?: unknown } | null)?.name === 'LockedAuth'
|
||||
|
||||
/** The GraphQL login mutation's name of a collection, as @payloadcms/graphql builds it (`login${singularName}`). */
|
||||
export function graphqlLoginName(collection: Pick<SanitizedCollectionConfig, 'graphQL' | 'slug'>): null | string {
|
||||
const graphQL = collection.graphQL as { singularName?: string } | false | undefined
|
||||
if (graphQL === false) {return null}
|
||||
const singular = graphQL?.singularName ? toWords(graphQL.singularName, true) : formatNames(collection.slug).singular
|
||||
return `login${singular}`
|
||||
}
|
||||
|
||||
type T = ConstructorParameters<typeof AuthenticationError>[0]
|
||||
|
||||
/** The config-level `afterError` hook (REST and GraphQL). */
|
||||
export const lockedLooksWrong: AfterErrorHook = (args) => {
|
||||
const { collection, error, req } = args as { error: unknown; graphqlResult?: Record<string, unknown> } & Parameters<AfterErrorHook>[0]
|
||||
const payload = req?.payload
|
||||
if (!payload) {return}
|
||||
const staff = staffCollectionSlugs(payload)
|
||||
const wrong = new AuthenticationError(req.t as T)
|
||||
// GraphQL: the error is wrapped (`originalError`), the collection only shows in the mutation's name.
|
||||
const graphqlResult = (args as { graphqlResult?: { extensions?: Record<string, unknown>; path?: unknown[] } }).graphqlResult
|
||||
if (graphqlResult) {
|
||||
const original = (error as { originalError?: unknown }).originalError
|
||||
if (!isLocked(original)) {return}
|
||||
const field = Array.isArray(graphqlResult.path) ? graphqlResult.path[0] : undefined
|
||||
const names = new Set((payload.config.collections ?? []).filter((c) => staff.includes(c.slug)).map(graphqlLoginName))
|
||||
if (typeof field !== 'string' || !names.has(field)) {return}
|
||||
return {
|
||||
graphqlResult: {
|
||||
...graphqlResult,
|
||||
extensions: { ...graphqlResult.extensions, name: wrong.name, statusCode: wrong.status },
|
||||
message: wrong.message,
|
||||
},
|
||||
} as never
|
||||
}
|
||||
if (!isLocked(error) || !collection || !staff.includes(collection.slug)) {return}
|
||||
return { response: { errors: [{ message: wrong.message }] }, status: wrong.status } as never
|
||||
}
|
||||
|
||||
/** Adds the hook to a config (idempotent). */
|
||||
export function withLockedAnswer(config: Config): Config {
|
||||
const own = config.hooks?.afterError ?? []
|
||||
if (own.includes(lockedLooksWrong)) {return config}
|
||||
return { ...config, hooks: { ...config.hooks, afterError: [...own, lockedLooksWrong] } }
|
||||
}
|
||||
@@ -57,6 +57,13 @@ export type AccountsOptions = {
|
||||
* whose own `create` rule allows an anonymous request keeps its route.
|
||||
*/
|
||||
firstUserRoute?: 'all' | 'panel' | string[]
|
||||
/**
|
||||
* What a staff account that Payload has locked (too many wrong passwords) is told when it logs in.
|
||||
* Default (1.17.2): exactly what a wrong password gets — same status, message and GraphQL error name — so
|
||||
* nobody can find out which addresses have a staff account by locking them. The lock itself is unchanged.
|
||||
* `'wrong'` = the default, said out loud. `'payload'` = Payload's own "This user is locked due to having too many failed login attempts."
|
||||
*/
|
||||
lockedAnswer?: 'payload' | 'wrong'
|
||||
/**
|
||||
* The lowest role that may open the admin panel. Default `'editor'`: an
|
||||
* account that holds only `user` (the default role of a new account) sees
|
||||
|
||||
@@ -9,6 +9,7 @@ export const consentTexts = defineTexts({
|
||||
cookieIntegrationStats: 'Built-in statistics',
|
||||
cookieIntegrationTheme: 'Theme choice',
|
||||
cookieSourceProject: 'Project',
|
||||
policyVersionDown: 'The consent version cannot go down: it is {{stored}} now. Raise it to ask every visitor again, or leave it as it is.',
|
||||
},
|
||||
pl: {
|
||||
cookieIntegrationAdmin: 'Logowanie do panelu',
|
||||
@@ -17,5 +18,6 @@ export const consentTexts = defineTexts({
|
||||
cookieIntegrationStats: 'Wbudowane statystyki',
|
||||
cookieIntegrationTheme: 'Wybór motywu',
|
||||
cookieSourceProject: 'Projekt',
|
||||
policyVersionDown: 'Wersji zgody nie można obniżyć: teraz wynosi {{stored}}. Podnieś ją, aby ponownie zapytać odwiedzających, albo zostaw bez zmian.',
|
||||
},
|
||||
})
|
||||
|
||||
@@ -2,21 +2,35 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
|
||||
import { Cookie } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
|
||||
import { useConsentContext } from './ConsentContext.js'
|
||||
import { COOKIE_BUTTON_RESERVE, cookieButtonSpaceScript, reserveCookieButtonSpace } from './cookieButtonSpace.js'
|
||||
import { consentDecidedScript } from './firstPaint.js'
|
||||
|
||||
/** Elements the button moves up for, so it never covers footer links. */
|
||||
/**
|
||||
* The site footer: the selector of the placement before 1.17.2, when the button moved up by the visible part of
|
||||
* the footer. `<CookieButton avoid={COOKIE_BUTTON_AVOID} />` brings that placement back.
|
||||
*/
|
||||
export const COOKIE_BUTTON_AVOID = 'footer, [role="contentinfo"]'
|
||||
|
||||
export type CookieButtonProps = {
|
||||
/**
|
||||
* CSS selector of elements the button lifts above while they are on screen
|
||||
* (default: the site footer). `false` = never move.
|
||||
* Placement before 1.17.2: a CSS selector of elements the button lifts above while they are on screen
|
||||
* (`COOKIE_BUTTON_AVOID` = the site footer; no room is reserved then). Default: none — the button stays in the
|
||||
* bottom corner of the window and never moves. `false` = the same as the default (kept for sites that set it).
|
||||
*/
|
||||
avoid?: false | string
|
||||
/** Replaces the default classes (look and position). The lift above `avoid` still applies. */
|
||||
className?: string
|
||||
/**
|
||||
* Room for the button at the end of the page, so the footer's last row ends above it and nothing stays covered:
|
||||
* a CSS selector of the block that gets the bottom padding (the last match; default `COOKIE_BUTTON_RESERVE`, the
|
||||
* footer; no match: `<body>`). Only while the button is shown, only as much as is missing (the block's own
|
||||
* bottom padding counts, an empty corner needs none). `false` = no room. A fixed amount instead of the measured
|
||||
* one: `--ipal-cookie-button-space` on that block (`0` = none, also per breakpoint).
|
||||
*/
|
||||
reserve?: false | string
|
||||
/** Corner. Default 'left'. */
|
||||
side?: 'left' | 'right'
|
||||
}
|
||||
@@ -26,19 +40,42 @@ export type CookieButtonProps = {
|
||||
* after deciding (GDPR: withdrawing consent must be as easy as giving it).
|
||||
* Hidden while the banner is showing.
|
||||
*
|
||||
* Placement (1.17.2): fixed in the bottom corner of the window, on every page and at every scroll position. It
|
||||
* never moves — it does not climb above the footer any more. So that it covers nothing at the very end of a page,
|
||||
* the footer gets room under its last row while the button is shown (`reserve`, cookieButtonSpace.ts). The
|
||||
* placement before 1.17.2 (riding on the footer's top edge): `avoid={COOKIE_BUTTON_AVOID}`.
|
||||
*
|
||||
* Colours follow the same design tokens as CookieBanner (--ipal-surface,
|
||||
* --ipal-border, --ipal-hover, --ipal-text). Position: --ipal-cookie-button-offset
|
||||
* (distance from the bottom, default 1rem), --ipal-cookie-button-inset (from the
|
||||
* side, default 1rem), z-index --ipal-z-header. When the footer scrolls into
|
||||
* view the button moves up by the visible part of it, so footer links stay free.
|
||||
* side, default 1rem), both plus the device's safe-area inset; z-index --ipal-z-header (below the banner and dialogs).
|
||||
*/
|
||||
export function CookieButton({ avoid = COOKIE_BUTTON_AVOID, className, side = 'left' }: CookieButtonProps = {}) {
|
||||
const { decided, reopen, texts } = useConsentContext()
|
||||
const lift = useLiftAbove(avoid, decided)
|
||||
export function CookieButton({ avoid, className, reserve = COOKIE_BUTTON_RESERVE, side = 'left' }: CookieButtonProps = {}) {
|
||||
const { decided, gpcMode, hydrated, nonce, reopen, serverRead, texts } = useConsentContext()
|
||||
const buttonRef = useRef<HTMLButtonElement>(null)
|
||||
const lift = useLiftAbove(avoid ?? false, decided)
|
||||
// the old placement keeps the button off the footer by itself
|
||||
const room = avoid ? false : reserve
|
||||
useReservedSpace({ active: decided, buttonRef, selector: room, side })
|
||||
|
||||
// `decided` is the server's value while hydrating (no decision on a static page, so nothing is rendered — or the
|
||||
// cookie the server read, <ConsentProvider cookieValue>, and then the button is in the HTML), the browser's after.
|
||||
if (!decided) {return null}
|
||||
if (!decided) {
|
||||
// Static HTML, the same for every visitor: for one who already decided, the room is made before the first
|
||||
// paint, so nothing shifts when the button appears with hydration. Only in the server HTML (a script React
|
||||
// creates in the browser never runs); a button with classes of its own is measured once it is there.
|
||||
if (hydrated || serverRead || !room || className) {return null}
|
||||
return (
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: cookieButtonSpaceScript({ decided: consentDecidedScript({ gpc: gpcMode, version: texts.version }), selector: room, side }),
|
||||
}}
|
||||
data-ipal="cookie-button-script"
|
||||
nonce={nonce}
|
||||
suppressHydrationWarning
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const cls =
|
||||
className ??
|
||||
@@ -50,7 +87,7 @@ export function CookieButton({ avoid = COOKIE_BUTTON_AVOID, className, side = 'l
|
||||
: {
|
||||
bottom: 'calc(var(--ipal-cookie-button-offset, 1rem) + env(safe-area-inset-bottom, 0px))',
|
||||
position: 'fixed',
|
||||
[side]: 'var(--ipal-cookie-button-inset, 1rem)',
|
||||
[side]: `calc(var(--ipal-cookie-button-inset, 1rem) + env(safe-area-inset-${side}, 0px))`,
|
||||
zIndex: 'var(--ipal-z-header, 40)' as unknown as number,
|
||||
}
|
||||
|
||||
@@ -61,6 +98,7 @@ export function CookieButton({ avoid = COOKIE_BUTTON_AVOID, className, side = 'l
|
||||
className={cls}
|
||||
data-ipal="cookie-button"
|
||||
onClick={reopen}
|
||||
ref={buttonRef}
|
||||
style={{ ...position, ...(lift ? { transform: `translateY(-${lift}px)` } : {}) }}
|
||||
type="button"
|
||||
>
|
||||
@@ -103,5 +141,37 @@ function useLiftAbove(selector: false | string, active: boolean): number {
|
||||
observer?.disconnect()
|
||||
}
|
||||
}, [selector, active])
|
||||
return selector ? lift : 0
|
||||
return selector && active ? lift : 0
|
||||
}
|
||||
|
||||
type ReservedSpaceOptions = {
|
||||
active: boolean
|
||||
buttonRef: { current: HTMLButtonElement | null }
|
||||
selector: false | string
|
||||
side: 'left' | 'right'
|
||||
}
|
||||
|
||||
/** Keeps the room for the button while it is shown; takes it away when the button goes (banner reopened, unmount). */
|
||||
function useReservedSpace({ active, buttonRef, selector, side }: ReservedSpaceOptions): void {
|
||||
// before the browser paints the button: the room is there in the same frame (and already is, after the inline script)
|
||||
useLayoutEffect(() => {
|
||||
if (!active || !selector) {return}
|
||||
let frame = 0
|
||||
const apply = () => reserveCookieButtonSpace({ button: buttonRef.current, selector, side })
|
||||
const later = () => {
|
||||
cancelAnimationFrame(frame)
|
||||
frame = requestAnimationFrame(apply)
|
||||
}
|
||||
apply()
|
||||
window.addEventListener('resize', later)
|
||||
// fonts, images, content that loads later: the footer's last row may end somewhere else
|
||||
const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(later)
|
||||
observer?.observe(document.body)
|
||||
return () => {
|
||||
cancelAnimationFrame(frame)
|
||||
window.removeEventListener('resize', later)
|
||||
observer?.disconnect()
|
||||
reserveCookieButtonSpace({ release: true, selector, side })
|
||||
}
|
||||
}, [active, buttonRef, selector, side])
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ export { CookieBanner } from './CookieBanner.js'
|
||||
export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from './CookieBanner.js'
|
||||
export { bottomOverlap, COOKIE_BUTTON_AVOID, CookieButton } from './CookieButton.js'
|
||||
export type { CookieButtonProps } from './CookieButton.js'
|
||||
export { COOKIE_BUTTON_RESERVE, COOKIE_BUTTON_SPACE_ATTRIBUTE, reserveCookieButtonSpace } from './cookieButtonSpace.js'
|
||||
export type { CookieButtonSpaceOptions } from './cookieButtonSpace.js'
|
||||
// Client-only consent exports — hook, provider, and UI components.
|
||||
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
|
||||
export type { ConsentCookieMap } from './useConsent.js'
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* Room for the cookie button at the end of the page (1.17.2).
|
||||
*
|
||||
* The button is fixed in the bottom corner of the window and never moves. At the very end of a page whatever is in
|
||||
* that corner — usually the footer's last row — would stay under it for good. So while the button is shown, the
|
||||
* page's last block (`reserve`, default the footer) gets just enough bottom padding for its content to end above the
|
||||
* button. Measured, not guessed: only what lies in the button's column counts, the block's own bottom padding is
|
||||
* used first, and a page with nothing in that corner gets nothing.
|
||||
*
|
||||
* NO IMPORTS, NO OUTER NAMES in `reserveCookieButtonSpace`: <CookieButton> also puts the function's own source into
|
||||
* an inline script (`cookieButtonSpaceScript`), so that a returning visitor's page has the room before the first
|
||||
* paint and nothing shifts when the button appears.
|
||||
*/
|
||||
|
||||
/** Attribute on the block that carries the room: its inline `padding-bottom` from before (may be empty). */
|
||||
export const COOKIE_BUTTON_SPACE_ATTRIBUTE = 'data-ipal-cookie-space'
|
||||
|
||||
/** The block that gets the room: the last one on the page that matches (the site footer). No match: `<body>`. */
|
||||
export const COOKIE_BUTTON_RESERVE = 'footer, [role="contentinfo"]'
|
||||
|
||||
export type CookieButtonSpaceOptions = {
|
||||
/** The button, when it is on the page. Without it the default button's box is measured with a probe. */
|
||||
button?: HTMLElement | null
|
||||
/** `true` takes the room away (the button is gone or the banner is open). */
|
||||
release?: boolean
|
||||
/** CSS selector of the block that gets the room. */
|
||||
selector: string
|
||||
/**
|
||||
* Before hydration: put the padding in a constructed style sheet instead of on the element, so React finds the
|
||||
* server's markup untouched (no hydration warning). The next call without it moves the room onto the element.
|
||||
*/
|
||||
sheet?: boolean
|
||||
/** The button's corner. */
|
||||
side: 'left' | 'right'
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the page's last block the room the button needs, or takes it away. Returns the pixels added (0 = none).
|
||||
* Safe to call again and again: it measures the block without its own addition each time.
|
||||
*/
|
||||
export function reserveCookieButtonSpace(options: CookieButtonSpaceOptions): number {
|
||||
const ATTRIBUTE = 'data-ipal-cookie-space'
|
||||
const GAP = 8
|
||||
const SHEET = '__iaplCookieSpaceSheet'
|
||||
const doc = document
|
||||
const store = window as unknown as Record<string, CSSStyleSheet | undefined>
|
||||
let i: number
|
||||
// put back what an earlier call changed — every measurement starts from the page as the project made it
|
||||
const marked = doc.querySelectorAll('[' + ATTRIBUTE + ']')
|
||||
for (i = 0; i < marked.length; i++) {
|
||||
const was = marked[i] as HTMLElement
|
||||
was.style.paddingBottom = was.getAttribute(ATTRIBUTE) || ''
|
||||
was.removeAttribute(ATTRIBUTE)
|
||||
}
|
||||
const before = store[SHEET]
|
||||
if (before) {
|
||||
doc.adoptedStyleSheets = doc.adoptedStyleSheets.filter(function (sheet) {return sheet !== before})
|
||||
store[SHEET] = undefined
|
||||
}
|
||||
if (options.release || !doc.body) {return 0}
|
||||
|
||||
const found = doc.querySelectorAll(options.selector)
|
||||
let target: HTMLElement = doc.body
|
||||
for (i = found.length - 1; i >= 0; i--) {
|
||||
if ((found[i] as HTMLElement).getBoundingClientRect().height > 0) {
|
||||
target = found[i] as HTMLElement
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// the button's box; before the button exists, a probe with the default button's size and place
|
||||
let button = options.button || null
|
||||
let probe: HTMLElement | null = null
|
||||
if (!button) {
|
||||
probe = doc.createElement('div')
|
||||
probe.style.cssText =
|
||||
'position:fixed;visibility:hidden;pointer-events:none;width:2.75rem;height:2.75rem;' +
|
||||
'bottom:calc(var(--ipal-cookie-button-offset, 1rem) + env(safe-area-inset-bottom, 0px));' +
|
||||
options.side + ':calc(var(--ipal-cookie-button-inset, 1rem) + env(safe-area-inset-' + options.side + ', 0px))'
|
||||
doc.body.appendChild(probe)
|
||||
button = probe
|
||||
}
|
||||
const fixed = getComputedStyle(button).position === 'fixed'
|
||||
const box = button.getBoundingClientRect()
|
||||
if (probe) {doc.body.removeChild(probe)}
|
||||
// a button the project placed in the flow (className) covers nothing at the end of the page
|
||||
if (!fixed || box.height <= 0) {return 0}
|
||||
|
||||
const style = getComputedStyle(target)
|
||||
const own = parseFloat(style.paddingBottom) || 0
|
||||
const give = function (value: string): boolean {
|
||||
if (!options.sheet) {
|
||||
target.setAttribute(ATTRIBUTE, target.style.paddingBottom)
|
||||
target.style.paddingBottom = value
|
||||
return true
|
||||
}
|
||||
if (typeof CSSStyleSheet !== 'function' || !('adoptedStyleSheets' in doc)) {return false}
|
||||
// the one element, without marking it: its path from <body>
|
||||
let path = ''
|
||||
for (let el: Element | null = target; el && el !== doc.body; el = el.parentElement) {
|
||||
let nth = 1
|
||||
for (let prev = el.previousElementSibling; prev; prev = prev.previousElementSibling) {nth++}
|
||||
path = ' > ' + el.tagName.toLowerCase() + ':nth-child(' + nth + ')' + path
|
||||
}
|
||||
const sheet = new CSSStyleSheet()
|
||||
sheet.replaceSync('body' + path + '{padding-bottom:' + value + ' !important}')
|
||||
doc.adoptedStyleSheets = doc.adoptedStyleSheets.concat(sheet)
|
||||
store[SHEET] = sheet
|
||||
return true
|
||||
}
|
||||
// a project's own amount: --ipal-cookie-button-space (any length; 0 = none on this breakpoint)
|
||||
const token = style.getPropertyValue('--ipal-cookie-button-space').replace(/^\s+|\s+$/g, '')
|
||||
if (token) {
|
||||
if (/^[+-]?(?:0+(?:\.0+)?|\.0+)[a-z%]*$/i.test(token)) {return 0}
|
||||
if (!give('calc(' + own + 'px + ' + token + ')')) {return 0}
|
||||
return Math.max(0, (parseFloat(getComputedStyle(target).paddingBottom) || 0) - own)
|
||||
}
|
||||
|
||||
// from the window's bottom edge up to the button's top, plus a gap: what must be free at the end of the page
|
||||
const zone = window.innerHeight - box.top + GAP
|
||||
let free: number
|
||||
if (target === doc.body) {
|
||||
free = own
|
||||
} else {
|
||||
// the lowest thing in the button's column: text and replaced elements, by their real boxes
|
||||
let lowest = -Infinity
|
||||
const note = function (rects: ArrayLike<{ bottom: number; height: number; left: number; right: number; width: number }>) {
|
||||
for (let k = 0; k < rects.length; k++) {
|
||||
const r = rects[k]
|
||||
if (r.width > 0 && r.height > 0 && r.right > box.left - GAP && r.left < box.right + GAP && r.bottom > lowest) {lowest = r.bottom}
|
||||
}
|
||||
}
|
||||
const walker = doc.createTreeWalker(target, 4) // NodeFilter.SHOW_TEXT
|
||||
const range = doc.createRange()
|
||||
let node = walker.nextNode()
|
||||
while (node) {
|
||||
if (/\S/.test(node.nodeValue || '')) {
|
||||
range.selectNodeContents(node)
|
||||
note(range.getClientRects())
|
||||
}
|
||||
node = walker.nextNode()
|
||||
}
|
||||
const solid = target.querySelectorAll('img, svg, video, canvas, iframe, input, select, textarea, button')
|
||||
for (i = 0; i < solid.length; i++) {note([solid[i].getBoundingClientRect()])}
|
||||
if (lowest === -Infinity) {return 0}
|
||||
// where the page ends, in the same (window) coordinates
|
||||
free = doc.documentElement.scrollHeight - window.scrollY - lowest
|
||||
}
|
||||
const extra = Math.ceil(Math.min(zone, zone - free))
|
||||
if (extra <= 0) {return 0}
|
||||
return give(own + extra + 'px') ? extra : 0
|
||||
}
|
||||
|
||||
export type CookieButtonSpaceScriptOptions = {
|
||||
/** JavaScript that leaves `true` in a variable `d` when the visitor has a current decision (consentDecidedScript). */
|
||||
decided: string
|
||||
selector: string
|
||||
side: 'left' | 'right'
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline script for the server HTML of a static page: for a visitor who already decided (the button will appear
|
||||
* after hydration) the room is there before the first paint. Nothing happens for a visitor who has not.
|
||||
*/
|
||||
export function cookieButtonSpaceScript({ decided, selector, side }: CookieButtonSpaceScriptOptions): string {
|
||||
const options = JSON.stringify({ selector, sheet: true, side: side === 'right' ? 'right' : 'left' })
|
||||
.replace(/</g, '\\u003c')
|
||||
.split(String.fromCharCode(0x2028)).join('\\u2028')
|
||||
.split(String.fromCharCode(0x2029)).join('\\u2029')
|
||||
return `(function(){try{${decided}if(d){(${reserveCookieButtonSpace.toString()})(${options})}}catch(e){}})()`
|
||||
}
|
||||
@@ -37,7 +37,12 @@ export type ConsentBannerScriptOptions = {
|
||||
* Exported for a project that renders its own banner: put `hidden` and `suppressHydrationWarning` on the banner's
|
||||
* root, and this script in a `<script>` (with the nonce) as its next sibling.
|
||||
*/
|
||||
export function consentBannerScript({ cookieName = CONSENT_COOKIE, gpc = 'honour', version = CONSENT_VERSION }: ConsentBannerScriptOptions = {}): string {
|
||||
/**
|
||||
* JavaScript statements that leave `true` in a variable `d` when this browser holds a current decision (or sends
|
||||
* Global Privacy Control under `gpc: 'honour'`), decided exactly as readConsentRecord / resolveConsent do. The shared
|
||||
* start of the inline scripts that act before the first paint (the banner's, the cookie button's room).
|
||||
*/
|
||||
export function consentDecidedScript({ cookieName = CONSENT_COOKIE, gpc = 'honour', version = CONSENT_VERSION }: ConsentBannerScriptOptions = {}): string {
|
||||
// JSON string literal, safe inside <script>: no `</script>`, no line separators
|
||||
const name = JSON.stringify(`${cookieName}=`)
|
||||
.replace(/</g, '\\u003c')
|
||||
@@ -45,11 +50,17 @@ export function consentBannerScript({ cookieName = CONSENT_COOKIE, gpc = 'honour
|
||||
.split(String.fromCharCode(0x2029)).join('\\u2029')
|
||||
const v = Number.isFinite(version) ? Number(version) : CONSENT_VERSION
|
||||
return (
|
||||
`(function(){try{var s=document.currentScript,b=s&&s.previousElementSibling;if(!b){return}` +
|
||||
`var n=${name},d=false,c=document.cookie?document.cookie.split("; "):[];` +
|
||||
`for(var i=0;i<c.length;i++){if(c[i].indexOf(n)===0){try{d=JSON.parse(decodeURIComponent(c[i].split("=")[1])).version===${v}}catch(e){}break}}` +
|
||||
// Global Privacy Control honoured: no banner, the same decision React makes (resolveConsent)
|
||||
(gpc === 'honour' ? `if(!d&&navigator.globalPrivacyControl===true){d=true}` : '') +
|
||||
(gpc === 'honour' ? `if(!d&&navigator.globalPrivacyControl===true){d=true}` : '')
|
||||
)
|
||||
}
|
||||
|
||||
export function consentBannerScript({ cookieName = CONSENT_COOKIE, gpc = 'honour', version = CONSENT_VERSION }: ConsentBannerScriptOptions = {}): string {
|
||||
return (
|
||||
`(function(){try{var s=document.currentScript,b=s&&s.previousElementSibling;if(!b){return}` +
|
||||
consentDecidedScript({ cookieName, gpc, version }) +
|
||||
`if(d){b.style.display="none"}else{b.removeAttribute("hidden");` +
|
||||
// a click on a banner button before the page has hydrated is kept for <CookieBanner> to carry out
|
||||
`b.addEventListener("click",function(e){if(b.hasAttribute("${BANNER_READY_ATTRIBUTE}")){return}` +
|
||||
|
||||
@@ -11,7 +11,7 @@ export type { ConsentCategory, ConsentState } from './categories.js'
|
||||
export { CONSENT_CATEGORY_LABELS, consentCategoryOptions } from './categoryLabels.js'
|
||||
export { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_MAX_BYTES, CONSENT_LOG_PATH, CONSENT_LOG_SLUG, readCappedBody } from './consentLog.js'
|
||||
export type { ConsentLogOptions } from './consentLog.js'
|
||||
export { consentBannerScript } from './firstPaint.js'
|
||||
export { consentBannerScript, consentDecidedScript } from './firstPaint.js'
|
||||
export type { ConsentBannerScriptOptions } from './firstPaint.js'
|
||||
export { CONSENT_FALLBACK, CONSENT_FALLBACK_PL, consentFallback, getConsentTexts, getCookieTable } from './getConsentTexts.js'
|
||||
export type { CookieTableRow } from './getConsentTexts.js'
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { CookieScannerOptions, CookieStorage } from './types.js'
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { secondFactorPassed } from '../../security/totp/secondFactor.js'
|
||||
import { accessAllowed } from '../../shared/accessAnswer.js'
|
||||
import { CONSENT_CATEGORIES } from '../categories.js'
|
||||
import { COOKIE_REVIEW_SLUG } from './collection.js'
|
||||
import { textFor } from './merge.js'
|
||||
@@ -156,7 +157,7 @@ export async function approveCookies({
|
||||
export function buildCookieApprovalEndpoints(options: CookieScannerOptions): Endpoint[] {
|
||||
const approval = typeof options.approval === 'object' ? options.approval : {}
|
||||
const allowed = async (req: PayloadRequest) =>
|
||||
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
return [
|
||||
{
|
||||
handler: async (req) => {
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { CookieCrawlOptions, CookieScanContext, CookieScannerOptions } from
|
||||
|
||||
import { userMeetsRole } from '../../../access/predicates.js'
|
||||
import { secondFactorPassed } from '../../../security/totp/secondFactor.js'
|
||||
import { accessAllowed } from '../../../shared/accessAnswer.js'
|
||||
import {
|
||||
COOKIE_CRAWL_PATH,
|
||||
COOKIE_CRAWL_RESULTS_PATH,
|
||||
@@ -60,7 +61,7 @@ export function buildCookieCrawlEndpoints({
|
||||
}): Endpoint[] {
|
||||
const crawl: CookieCrawlOptions = typeof options.crawl === 'object' ? options.crawl : {}
|
||||
const isStaff = async (req: PayloadRequest) =>
|
||||
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
const read = async (req: PayloadRequest) =>
|
||||
(await req.payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0, overrideAccess: true, req })) as CrawlDoc
|
||||
const write = (req: PayloadRequest, data: Partial<CrawlDoc>) =>
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { CookieIntegration, CookieScanContext, CookieScannerOptions } from
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { secondFactorPassed } from '../../security/totp/secondFactor.js'
|
||||
import { accessAllowed } from '../../shared/accessAnswer.js'
|
||||
import { DEFAULT_COOKIE_INTEGRATIONS, integrationLabel } from './integrations.js'
|
||||
import { cookieScanContext, enabledCookieIntegrations, parseCookieNames, runCookieScan } from './scan.js'
|
||||
|
||||
@@ -17,7 +18,7 @@ export const COOKIE_SCAN_PATH = '/ipal/cookie-scan'
|
||||
*/
|
||||
export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin: CookieScanContext['plugin']): Endpoint[] {
|
||||
const allowed = async (req: PayloadRequest) =>
|
||||
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
|
||||
// Names in the admin language of the editor who asks.
|
||||
const list = (items: CookieIntegration[], req: PayloadRequest) =>
|
||||
|
||||
@@ -16,6 +16,9 @@ type Row = {
|
||||
|
||||
type Entry = { name: string; storage?: null | string } & CookieReviewValues
|
||||
|
||||
/** How many times a write is worked out again when the list changed under it. */
|
||||
const WRITE_ATTEMPTS = 5
|
||||
|
||||
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
|
||||
|
||||
/**
|
||||
@@ -52,13 +55,12 @@ export async function addToCookieList({
|
||||
const common = { slug: 'cookie-settings' as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
|
||||
let result: 'added' | 'filled' | 'unchanged' = 'unchanged'
|
||||
|
||||
for (const [i, locale] of locales.entries()) {
|
||||
const g = (await payload.findGlobal({ ...common, locale: locale as never })) as { cookies?: Row[] }
|
||||
const rows = [...(g.cookies ?? [])]
|
||||
/** Adds or fills the entry's row in `rows` (in place); what happened, or null when nothing changed. */
|
||||
const applyEntry = (rows: Row[], i: number): 'added' | 'filled' | null => {
|
||||
const locale = locales[i]
|
||||
const row = rows.find((r) => Boolean(r.name?.trim()) && sameCookie(r.name!.trim(), entry.name))
|
||||
let changed = false
|
||||
if (!row) {
|
||||
if (i > 0) {continue} // added in the default locale; Payload keeps the row in every locale
|
||||
if (i > 0) {return null} // added in the default locale; Payload keeps the row in every locale
|
||||
rows.push({
|
||||
name: entry.name,
|
||||
category: entry.category ?? 'necessary',
|
||||
@@ -67,28 +69,46 @@ export async function addToCookieList({
|
||||
purpose: text(entry.purpose, locale),
|
||||
storage: entry.storage ?? 'cookie',
|
||||
})
|
||||
changed = true
|
||||
result = 'added'
|
||||
} else {
|
||||
const fill = (key: 'duration' | 'provider' | 'purpose', value: null | string | undefined) => {
|
||||
if (empty(row[key]) && !empty(value)) {
|
||||
row[key] = value
|
||||
changed = true
|
||||
}
|
||||
return 'added'
|
||||
}
|
||||
let changed = false
|
||||
const fill = (key: 'duration' | 'provider' | 'purpose', value: null | string | undefined) => {
|
||||
if (empty(row[key]) && !empty(value)) {
|
||||
row[key] = value
|
||||
changed = true
|
||||
}
|
||||
if (i === 0) {
|
||||
fill('provider', entry.vendor)
|
||||
// A row from before the type existed has none; the type is shared by every language.
|
||||
if (empty(row.storage) && entry.storage) {
|
||||
row.storage = entry.storage
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (i === 0) {
|
||||
fill('provider', entry.vendor)
|
||||
// A row from before the type existed has none; the type is shared by every language.
|
||||
if (empty(row.storage) && entry.storage) {
|
||||
row.storage = entry.storage
|
||||
changed = true
|
||||
}
|
||||
fill('purpose', text(entry.purpose, locale))
|
||||
fill('duration', text(entry.retention, locale))
|
||||
if (changed && result === 'unchanged') {result = 'filled'}
|
||||
}
|
||||
fill('purpose', text(entry.purpose, locale))
|
||||
fill('duration', text(entry.retention, locale))
|
||||
return changed ? 'filled' : null
|
||||
}
|
||||
|
||||
// The list is written whole (Payload has no "add one row"): right before writing, it is read again, and when an
|
||||
// editor's save changed it since, the change is worked out again on what is there now (owner's decision Q3,
|
||||
// 1.18.0). What is left is the moment between that check and the write itself.
|
||||
const read = async (locale: string | undefined) =>
|
||||
[...(((await payload.findGlobal({ ...common, locale: locale as never })) as { cookies?: Row[] }).cookies ?? [])]
|
||||
const same = (a: Row[], b: Row[]) => JSON.stringify(a) === JSON.stringify(b)
|
||||
|
||||
for (const [i, locale] of locales.entries()) {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const seen = await read(locale)
|
||||
const rows = structuredClone(seen)
|
||||
const outcome = applyEntry(rows, i)
|
||||
if (!outcome) {break}
|
||||
if (attempt < WRITE_ATTEMPTS - 1 && !same(await read(locale), seen)) {continue}
|
||||
await payload.updateGlobal({ ...common, data: { cookies: rows } as never, locale: locale as never })
|
||||
if (outcome === 'added' || result === 'unchanged') {result = outcome}
|
||||
break
|
||||
}
|
||||
if (changed) {await payload.updateGlobal({ ...common, data: { cookies: rows } as never, locale: locale as never })}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Drafts as related documents (owner's decision Q5, 1.18.0).
|
||||
*
|
||||
* The public helpers read with `depth` (a page at 2, Site settings and archive entries at 1) and Payload fills
|
||||
* in every related document whatever its status: a block, a menu or a System pages link pointing at a page that
|
||||
* was never published showed that page's title and slug (and llms-full / the Markdown printed its text). Since
|
||||
* 1.18.0 such a related document is left out of what the helpers answer, as if it did not exist:
|
||||
* - a single relationship becomes `null` (a link to it resolves to nothing, a menu item drops out);
|
||||
* - in a list of relationships it is removed;
|
||||
* - in a polymorphic one (`{ relationTo, value }`) the `value` becomes `null`.
|
||||
* A related document counts as a draft when it carries `_status` other than `'published'`, which is what a
|
||||
* never-published (or unpublished) document of a collection with drafts holds. Documents without `_status`
|
||||
* (collections without drafts, uploads) are never touched. The document itself is not judged here (the
|
||||
* helpers already do), only what it points at.
|
||||
*
|
||||
* `draftRelations: 'keep'` (createContentHelpers, resolveRoute, getArchiveEntries, resolveNotFoundPage,
|
||||
* collectSiteIndex) keeps the old behaviour. A preview (`draft: true`) keeps them too.
|
||||
*/
|
||||
|
||||
export type DraftRelations = 'hide' | 'keep'
|
||||
|
||||
const isDraftDoc = (value: unknown): boolean => {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {return false}
|
||||
const v = value as { _status?: unknown; id?: unknown }
|
||||
return v.id !== undefined && typeof v._status === 'string' && v._status !== 'published'
|
||||
}
|
||||
|
||||
/**
|
||||
* The same value with every related document that is a draft left out (see above). Returns the SAME object
|
||||
* when nothing needed changing; otherwise only the path to each change is copied (cached reads are not mutated).
|
||||
*/
|
||||
export function withoutDraftRelations<T>(value: T): T {
|
||||
return walk(value, true) as T
|
||||
}
|
||||
|
||||
function walk(value: unknown, root: boolean): unknown {
|
||||
if (Array.isArray(value)) {
|
||||
let changed = false
|
||||
const next: unknown[] = []
|
||||
for (const item of value) {
|
||||
if (isDraftDoc(item)) {
|
||||
changed = true
|
||||
continue
|
||||
}
|
||||
const out = walk(item, false)
|
||||
if (out !== item) {changed = true}
|
||||
next.push(out)
|
||||
}
|
||||
return changed ? next : value
|
||||
}
|
||||
if (!value || typeof value !== 'object' || value instanceof Date) {return value}
|
||||
if (!root && isDraftDoc(value)) {return null}
|
||||
const obj = value as Record<string, unknown>
|
||||
let result: null | Record<string, unknown> = null
|
||||
for (const key of Object.keys(obj)) {
|
||||
const item = obj[key]
|
||||
// a polymorphic relationship keeps its shape: { relationTo, value: null }
|
||||
const out = isDraftDoc(item) ? null : walk(item, false)
|
||||
if (out !== item) {
|
||||
result ??= { ...obj }
|
||||
result[key] = out
|
||||
}
|
||||
}
|
||||
return result ?? value
|
||||
}
|
||||
|
||||
/** `withoutDraftRelations` unless the caller keeps them (`'keep'`) or reads a preview (`draft`). */
|
||||
export function applyDraftRelations<T>(value: T, { draft = false, draftRelations = 'hide' }: { draft?: boolean; draftRelations?: DraftRelations } = {}): T {
|
||||
return draft || draftRelations === 'keep' ? value : withoutDraftRelations(value)
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { applyDraftRelations, type DraftRelations } from './draftRelations.js'
|
||||
|
||||
export type ArchiveEntries<T = Record<string, unknown>> = {
|
||||
docs: T[]
|
||||
hasNextPage: boolean
|
||||
@@ -17,6 +19,8 @@ type GetArchiveEntriesArgs = {
|
||||
depth?: number
|
||||
/** Preview (draftMode): include unpublished entries and latest drafts. Default false. */
|
||||
draft?: boolean
|
||||
/** Related documents that are drafts: `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
|
||||
draftRelations?: DraftRelations
|
||||
locale: string
|
||||
/** 1-based. Values below 1 are clamped. */
|
||||
page?: number
|
||||
@@ -45,6 +49,7 @@ export async function getArchiveEntries<T = Record<string, unknown>>({
|
||||
collection,
|
||||
depth = 1,
|
||||
draft = false,
|
||||
draftRelations,
|
||||
locale,
|
||||
page = 1,
|
||||
payload,
|
||||
@@ -69,7 +74,7 @@ export async function getArchiveEntries<T = Record<string, unknown>>({
|
||||
})
|
||||
|
||||
return {
|
||||
docs: result.docs as T[],
|
||||
docs: applyDraftRelations(result.docs, { draft, draftRelations }) as T[],
|
||||
hasNextPage: result.hasNextPage,
|
||||
hasPrevPage: result.hasPrevPage,
|
||||
page: result.page ?? 1,
|
||||
|
||||
@@ -2,6 +2,7 @@ export { buildArchiveFields } from './archiveFields.js'
|
||||
export { blocksToMarkdown } from './blocksToMarkdown.js'
|
||||
export { createMarkdownRenderer, createMarkdownRoute, markdownResponse } from './createMarkdownRenderer.js'
|
||||
export { createSearchRoute } from './createSearchRoute.js'
|
||||
export { applyDraftRelations, type DraftRelations, withoutDraftRelations } from './draftRelations.js'
|
||||
export { getArchiveEntries } from './getArchiveEntries.js'
|
||||
export type { ArchiveEntries } from './getArchiveEntries.js'
|
||||
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { applyDraftRelations, type DraftRelations } from './draftRelations.js'
|
||||
import { isPublishedDoc } from './resolveRoute.js'
|
||||
|
||||
type ResolveNotFoundPageArgs = {
|
||||
/** Related documents that are drafts: `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
|
||||
draftRelations?: DraftRelations
|
||||
locale: string
|
||||
/** Client's Pages collection slug. Defaults to 'pages'. */
|
||||
pagesSlug?: string
|
||||
@@ -24,6 +27,7 @@ type ResolveNotFoundPageArgs = {
|
||||
* deleted page just yields null, so the 404 view can't crash the build.
|
||||
*/
|
||||
export async function resolveNotFoundPage({
|
||||
draftRelations,
|
||||
locale,
|
||||
pagesSlug = 'pages',
|
||||
payload,
|
||||
@@ -52,7 +56,7 @@ export async function resolveNotFoundPage({
|
||||
locale: locale as never,
|
||||
})
|
||||
// a page never published (or unpublished) is a draft: the built-in view, not its text (IAWL idea 23)
|
||||
return isPublishedDoc(doc) ? (doc as Record<string, unknown>) : null
|
||||
return isPublishedDoc(doc) ? applyDraftRelations(doc as Record<string, unknown>, { draftRelations }) : null
|
||||
} catch (error) {
|
||||
console.warn('[iapl] resolveNotFoundPage: falling back to built-in 404 view:', error)
|
||||
return null
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { BasePayload } from 'payload'
|
||||
|
||||
import type { ContentOption } from './types.js'
|
||||
|
||||
import { applyDraftRelations, type DraftRelations } from './draftRelations.js'
|
||||
import { archiveFieldName } from './types.js'
|
||||
|
||||
type ArchivePage = { id: number | string; slug?: unknown }
|
||||
@@ -37,6 +38,11 @@ type ResolveRouteArgs = {
|
||||
* requests only ever see published content.
|
||||
*/
|
||||
draft?: boolean
|
||||
/**
|
||||
* Related documents that are drafts (never published) in what the route answers: `'hide'` (default since 1.18.0)
|
||||
* leaves them out — `null` for one, removed from a list — `'keep'` answers them as before. A preview keeps them.
|
||||
*/
|
||||
draftRelations?: DraftRelations
|
||||
locale: string
|
||||
/** Page number from the query string (?page=2). Defaults to 1. */
|
||||
page?: number
|
||||
@@ -99,7 +105,16 @@ export function isSiteLocale(payload: { config?: { localization?: unknown } }, l
|
||||
return typeof locale === 'string' && localization.localeCodes.includes(locale)
|
||||
}
|
||||
|
||||
export async function resolveRoute({
|
||||
export async function resolveRoute(args: ResolveRouteArgs): Promise<null | ResolvedRoute> {
|
||||
const route = await resolveRouteDocs(args)
|
||||
if (!route) {return null}
|
||||
const hide = <T,>(value: T) => applyDraftRelations(value, args)
|
||||
return 'archive' in route && route.type === 'entry'
|
||||
? { ...route, archive: hide(route.archive), doc: hide(route.doc) }
|
||||
: { ...route, doc: hide(route.doc) }
|
||||
}
|
||||
|
||||
async function resolveRouteDocs({
|
||||
content,
|
||||
draft = false,
|
||||
locale,
|
||||
|
||||
@@ -202,11 +202,19 @@ export const securityRules: DoctorRule[] = [
|
||||
{
|
||||
// Payload accepts the login cookie from ANY origin while its `csrf` list is empty — and it is empty
|
||||
// unless `csrf` or `serverURL` is set. A page on a sibling subdomain can then act with a panel user's cookie.
|
||||
// The plugin's own-origin checks (2FA verify / setup / reset, the panel actions — 1.17.2) then know the site
|
||||
// only from the request's Host: behind a proxy that rewrites it, the site's own panel would be refused.
|
||||
id: 'csrf-empty',
|
||||
check: (ctx) => {
|
||||
const fix = "serverURL: process.env.NEXT_PUBLIC_SERVER_URL (Payload then trusts that origin only; the plugin's own-origin checks know the site's address), or csrf: ['https://<site>']"
|
||||
const why = 'Payload accepts the login cookie from any origin (a risk when other applications share the domain), and behind a proxy that rewrites Host the plugin cannot tell the panel\'s own requests (2FA, panel actions) from foreign ones'
|
||||
// deep (the running config) wins over reading the file: serverURL may come from a spread or a helper
|
||||
if (ctx.deep && typeof ctx.deep.originKnown === 'boolean') {
|
||||
return ctx.deep.originKnown ? [] : [{ fix, message: `the running config has neither \`serverURL\` nor \`csrf\`: ${why}`, severity: 'warning' }]
|
||||
}
|
||||
const code = cfg(ctx)
|
||||
if (!/buildConfig\s*\(/.test(code) || /\bcsrf\s*:/.test(code) || /\bserverURL\s*:/.test(code)) {return []}
|
||||
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "serverURL: process.env.NEXT_PUBLIC_SERVER_URL (Payload then trusts that origin only), or csrf: ['https://<site>']", message: 'neither `serverURL` nor `csrf` is set: Payload accepts the login cookie from any origin (a risk when other applications share the domain)', severity: 'warning' }]
|
||||
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix, message: `neither \`serverURL\` nor \`csrf\` is set: ${why}`, severity: 'warning' }]
|
||||
},
|
||||
docs: 'docs/security.md',
|
||||
group: 'security',
|
||||
@@ -225,6 +233,30 @@ export const securityRules: DoctorRule[] = [
|
||||
group: 'security',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// An account of a visitor login collection (customers, members) may write content or settings: Payload fills a
|
||||
// missing rule with "any signed-in account", and the plugin narrows only its own entities (owner's Q3, 1.17.2).
|
||||
id: 'visitor-writes',
|
||||
check: (ctx) => {
|
||||
const byEntity = new Map<string, string[]>()
|
||||
for (const entry of ctx.deep?.visitorWrites ?? []) {
|
||||
const at = entry.lastIndexOf(':')
|
||||
byEntity.set(entry.slice(0, at), [...(byEntity.get(entry.slice(0, at)) ?? []), entry.slice(at + 1)])
|
||||
}
|
||||
return [...byEntity].map(([entity, operations]) => {
|
||||
const global = entity.startsWith('globals/')
|
||||
const slug = global ? entity.slice('globals/'.length) : entity
|
||||
return {
|
||||
fix: `give ${global ? 'the global' : 'the collection'} "${slug}" its own ${operations.map((o) => `access.${o}`).join(' / ')} (adminOrEditor, requireRole('editor'), …) — Payload's default lets every signed-in account in (access.md "Who is staff")`,
|
||||
message: `an account of a visitor login collection may ${operations.join(', ')} ${global ? 'the global' : 'in'} "${slug}"`,
|
||||
severity: 'warning' as const,
|
||||
}
|
||||
})
|
||||
},
|
||||
docs: 'docs/access.md',
|
||||
group: 'security',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// A staff collection that an account of another auth collection (a customer, a member) may write to:
|
||||
// it can create a staff account, or change a staff account's password. The plugin's default rules close
|
||||
|
||||
@@ -12,9 +12,11 @@ import { graphAvailable } from '../email/mailAdapter.js'
|
||||
import { mailPanelState } from '../email/relay/panel.js'
|
||||
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
|
||||
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
|
||||
import { accessAllowed } from '../shared/accessAnswer.js'
|
||||
import { readEnv } from '../shared/envName.js'
|
||||
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
|
||||
import { turnstileSecretFromEnv } from '../turnstile/config.js'
|
||||
import { visitorWritableEntities } from './visitorWrites.js'
|
||||
|
||||
/** The plugin's own version — a constant (src/version.ts), never a file read at run time. */
|
||||
export function pluginVersion(): string {
|
||||
@@ -111,7 +113,15 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
} catch {
|
||||
staffOnOwnRoles = null
|
||||
}
|
||||
return { mail, node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
|
||||
let visitorWrites: null | string[] = null
|
||||
try {
|
||||
visitorWrites = await visitorWritableEntities(payload as never)
|
||||
} catch {
|
||||
visitorWrites = null
|
||||
}
|
||||
const { csrf, serverURL } = payload.config as { csrf?: unknown; serverURL?: unknown }
|
||||
const originKnown = (typeof serverURL === 'string' && serverURL.trim() !== '') || (Array.isArray(csrf) && csrf.some((o) => typeof o === 'string' && o.trim() !== ''))
|
||||
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa, visitorWrites }
|
||||
}
|
||||
|
||||
export type DoctorEndpointOptions = {
|
||||
@@ -141,7 +151,7 @@ export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoi
|
||||
const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'iapl-doctor', windowMs: 60_000 })
|
||||
if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests' })}
|
||||
const given = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '').trim()
|
||||
const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && (await options.access({ req })) : false)
|
||||
const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && accessAllowed('doctor.access', await options.access({ req })) : false)
|
||||
if (!allowed) {return Response.json({ error: 'Unauthorized' }, { status: 401 })}
|
||||
const status = await collectDoctorStatus(req.payload)
|
||||
return Response.json(status, { headers: { 'cache-control': 'no-store' } })
|
||||
|
||||
@@ -99,6 +99,11 @@ export type DoctorStatus = {
|
||||
node?: string
|
||||
/** Auth collections whose `create` rule lets an anonymous request through (slugs only). */
|
||||
openSignUp?: null | string[]
|
||||
/**
|
||||
* The running config has a `serverURL` (1.17.2), or a non-empty `csrf` list. Without either Payload takes the
|
||||
* login cookie from any origin, and the plugin's own-origin checks know the site only from the request's host.
|
||||
*/
|
||||
originKnown?: boolean
|
||||
pendingCookies?: null | number
|
||||
plugin?: string
|
||||
/**
|
||||
@@ -118,6 +123,12 @@ export type DoctorStatus = {
|
||||
/** Of `usersWithout2fa`: accounts whose setup window has passed (blocked until an admin reopens setup). */
|
||||
usersSetupClosed?: null | number
|
||||
usersWithout2fa?: null | number
|
||||
/**
|
||||
* What an account of a visitor login collection (an auth collection that is not staff) may write, as `pages:create`
|
||||
* or `globals/header:update` — rules that answer `true` for it, Payload's default included. Empty without a visitor
|
||||
* login collection; null = could not be checked.
|
||||
*/
|
||||
visitorWrites?: null | string[]
|
||||
}
|
||||
|
||||
export type DoctorLive = {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { staffCollectionSlugs } from '../access/predicates.js'
|
||||
|
||||
type Rule = ((args: never) => unknown) | undefined
|
||||
type LiveEntity = { access?: Record<string, Rule>; auth?: unknown; slug: string }
|
||||
type LivePayload = {
|
||||
collections?: Record<string, { config: LiveEntity }>
|
||||
config?: { globals?: LiveEntity[] }
|
||||
}
|
||||
|
||||
/**
|
||||
* What an account of a visitor login collection (a shop's customers, a member zone — an auth collection that is not
|
||||
* staff) may WRITE: every collection `create` / `update` / `delete` and global `update` whose rule answers a plain
|
||||
* `true` for such an account, as `pages:create` or `globals/header:update`. For the doctor's `visitor-writes` rule
|
||||
* (IAWL idea 35, the owner's Q3). Empty when the site has no visitor login collection.
|
||||
*
|
||||
* Asked by behaviour, never by the rule's name (a production build renames every function): Payload's default
|
||||
* ("any signed-in account") and a project's own rule that is as wide both answer `true`. A rule that answers a query
|
||||
* (e.g. "its own document") is not counted, nor one that throws. Staff collections are left to `staff-accounts-open`.
|
||||
*/
|
||||
export async function visitorWritableEntities(payload: LivePayload): Promise<string[]> {
|
||||
const staff = staffCollectionSlugs(payload as never)
|
||||
const collections = Object.values(payload.collections ?? {}).map(({ config }) => config)
|
||||
const visitors = collections.filter((c) => c.auth && !staff.includes(c.slug)).map((c) => c.slug)
|
||||
if (!visitors.length) {return []}
|
||||
const open = new Set<string>()
|
||||
const ask = async (rule: Rule, key: string) => {
|
||||
for (const collection of visitors) {
|
||||
const user = { id: '__iapl-visitor__', collection, email: '[email protected]' }
|
||||
try {
|
||||
// no rule = Payload's default: any signed-in account
|
||||
if (!rule || (await rule({ id: '__iapl-other__', req: { context: {}, headers: new Headers(), payload, user } } as never)) === true) {
|
||||
open.add(key)
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
/* closed */
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const config of collections) {
|
||||
if (staff.includes(config.slug)) {continue}
|
||||
for (const operation of ['create', 'update', 'delete'] as const) {await ask(config.access?.[operation], `${config.slug}:${operation}`)}
|
||||
}
|
||||
for (const global of payload.config?.globals ?? []) {await ask(global.access?.update, `globals/${global.slug}:update`)}
|
||||
return [...open].sort()
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { createHash, randomBytes } from 'node:crypto'
|
||||
|
||||
import type { ResolvedRelayOptions } from './options.js'
|
||||
|
||||
import { consumeRateLimit } from '../../shared/rateLimit.js'
|
||||
import { consumeRateLimit, ipRateKey } from '../../shared/rateLimit.js'
|
||||
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
|
||||
import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { currentMailKind, type MailKind, mailKindOf, takeExpectedMail } from './kinds.js'
|
||||
@@ -136,14 +136,14 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
const windowMs = (own.windowMinutes ?? RELAY_DEFAULTS.accountMail.windowMinutes) * 60_000
|
||||
const perAddress = own.perAddress ?? RELAY_DEFAULTS.accountMail.perAddress
|
||||
const checks = [
|
||||
...(marked?.visitor ? [{ key: `visitor:${marked.visitor}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
|
||||
...(marked?.visitor ? [{ key: `visitor:${ipRateKey(marked.visitor)}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
|
||||
// 1.18.0: one visitor (IP) gets `perAddress` mails to an address; the address gets `perAddressTotal` from everybody —
|
||||
// a stranger who fills an address's count from one IP no longer stops its owner's own reset mail (IAWL idea 16).
|
||||
...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].flatMap((address) => {
|
||||
const to = `to:${sha256Hex(address.toLowerCase())}`
|
||||
return [
|
||||
// no visitor known (server code, no IP header): all such requests are one visitor
|
||||
{ key: marked?.visitor || 'no-visitor', max: perAddress, scope: `mail-relay-account:${to}` },
|
||||
{ key: marked?.visitor ? ipRateKey(marked.visitor) : 'no-visitor', max: perAddress, scope: `mail-relay-account:${to}` },
|
||||
{ key: to, max: own.perAddressTotal ?? RELAY_DEFAULTS.accountMail.perAddressTotal },
|
||||
]
|
||||
}),
|
||||
|
||||
@@ -162,8 +162,13 @@ const builtin = (key: 'checkbox' | 'date' | 'email' | 'message' | 'number' | 'ra
|
||||
/** Text-like built-ins also get a localized "Placeholder" (select already has one). */
|
||||
const withHint = (key: 'email' | 'number' | 'text' | 'textarea') => withShowWhen(withPlaceholder(builtinBlocks[key] as Block))
|
||||
|
||||
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
|
||||
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
|
||||
/**
|
||||
* REST/GraphQL: a staff account (any role) with its second factor. Local API (submitForm) is unaffected. Before
|
||||
* 1.17.2 any signed-in account was enough — a customer of a visitor login collection could POST
|
||||
* /api/form-submissions past the rate limit, Turnstile, consent and validation, and the form's e-mails went out.
|
||||
* `formSubmissionOverrides.access.create` is the way back.
|
||||
*/
|
||||
const submissionsCreateAccess = ({ req }: AccessArgs) => userMeetsRole(req, 'user')
|
||||
/**
|
||||
* Submissions are visitors' personal data: editors and admins only. The
|
||||
* form-builder default lets ANY account of the admin collection read them —
|
||||
@@ -205,7 +210,7 @@ function hideEmails(fields: Field[]): Field[] {
|
||||
* SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e.
|
||||
* anyone can POST /api/form-submissions and skip everything submitForm enforces
|
||||
* (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL
|
||||
* creation is limited to logged-in users; the site submits through submitForm
|
||||
* creation is limited to staff accounts with their second factor; the site submits through submitForm
|
||||
* (server action → Local API, which bypasses access by design). A project that
|
||||
* really needs public REST submissions can override `formSubmissionOverrides.access.create`.
|
||||
*/
|
||||
|
||||
@@ -3,9 +3,11 @@ export {
|
||||
checkRateLimit,
|
||||
clientIp,
|
||||
consumeRateLimit,
|
||||
ipRateKey,
|
||||
retryAfterSeconds,
|
||||
setIpv6Grouping,
|
||||
setRateLimitStore,
|
||||
setUnknownIpFactor,
|
||||
tooManyRequests,
|
||||
} from '../shared/rateLimit.js'
|
||||
export type { ClientIpOptions, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js'
|
||||
export type { ClientIpOptions, Ipv6Grouping, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js'
|
||||
|
||||
@@ -21,6 +21,7 @@ import { getConsentTexts } from '../consent/getConsentTexts.js'
|
||||
import { isPathAllowed, isPathVisibleIn } from '../construction/logic.js'
|
||||
import { pathOf } from '../construction/visibility.js'
|
||||
import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
|
||||
import { applyDraftRelations, type DraftRelations } from '../content/draftRelations.js'
|
||||
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
|
||||
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
|
||||
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
|
||||
@@ -54,6 +55,12 @@ type CreateContentHelpersArgs = {
|
||||
config: Promise<SanitizedConfig> | SanitizedConfig
|
||||
/** Archive-backed collections, same value as the plugin option. */
|
||||
content?: ContentOption
|
||||
/**
|
||||
* Related documents that are drafts (never published) in what the helpers answer — pages, Site settings (menus,
|
||||
* System pages), archive entries, the 404 page, llms-full: `'hide'` (default since 1.18.0) leaves them out, as
|
||||
* if they did not exist; `'keep'` answers them as before. content.md "Drafts as related documents".
|
||||
*/
|
||||
draftRelations?: DraftRelations
|
||||
/**
|
||||
* i18n config. Required only if you want the ready-made `sitemap` / `robots`
|
||||
* handlers — they need the locale list to emit hreflang.
|
||||
@@ -190,6 +197,7 @@ export function createContentHelpers({
|
||||
baseUrl,
|
||||
config,
|
||||
content,
|
||||
draftRelations = 'hide',
|
||||
i18n,
|
||||
markdown: markdownOptions,
|
||||
markdownAlternate,
|
||||
@@ -229,7 +237,7 @@ export function createContentHelpers({
|
||||
*/
|
||||
const getSettings = cache(async (locale: string) => {
|
||||
const payload = await getCachedPayload()
|
||||
return payload.findGlobal({ slug: settingsSlug as never, depth: settingsDepth, locale: locale as never })
|
||||
return applyDraftRelations(await payload.findGlobal({ slug: settingsSlug as never, depth: settingsDepth, locale: locale as never }), { draftRelations })
|
||||
})
|
||||
|
||||
/** What does this URL point at? Routing only — no listing data. */
|
||||
@@ -243,6 +251,7 @@ export function createContentHelpers({
|
||||
const settings = (await getSettings(locale)) as Record<string, unknown>
|
||||
return resolveRouteRaw({
|
||||
content,
|
||||
draftRelations,
|
||||
locale,
|
||||
page,
|
||||
pagesSlug,
|
||||
@@ -416,7 +425,7 @@ export function createContentHelpers({
|
||||
locale: locale as never,
|
||||
})
|
||||
// a page never published (or unpublished) is a draft: the built-in view, not its text (IAWL idea 23)
|
||||
return isPublishedDoc(doc) ? (doc as Record<string, unknown>) : null
|
||||
return isPublishedDoc(doc) ? applyDraftRelations(doc as Record<string, unknown>, { draftRelations }) : null
|
||||
} catch {
|
||||
return null // DB unreachable (container build) or page deleted — fallback view
|
||||
}
|
||||
@@ -431,7 +440,7 @@ export function createContentHelpers({
|
||||
perPage: number,
|
||||
): Promise<ArchiveEntries> => {
|
||||
const payload = await getCachedPayload()
|
||||
return getArchiveEntries({ collection, locale, page, payload, perPage })
|
||||
return getArchiveEntries({ collection, draftRelations, locale, page, payload, perPage })
|
||||
},
|
||||
)
|
||||
|
||||
@@ -850,7 +859,7 @@ export function createContentHelpers({
|
||||
return () => (value ??= make())
|
||||
}
|
||||
const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
|
||||
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
|
||||
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, draftRelations, full: true, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
|
||||
const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, isPathVisible, settingsSlug, ...markdownOptions }))
|
||||
const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, isPathVisible, settingsSlug, summaryField, ...mcpOptions }))
|
||||
const health = lazy(() => createHealthRoute({ collection: pagesSlug, getCachedPayload }))
|
||||
|
||||
@@ -2,6 +2,7 @@ export {
|
||||
buildIntegrationStatusBanner,
|
||||
buildIntegrationStatusField,
|
||||
recordIntegrationStatus,
|
||||
writeGlobalFields,
|
||||
} from './status.js'
|
||||
export type { IntegrationBannerTexts, IntegrationState, IntegrationStatus } from './status.js'
|
||||
export type { IntegrationLabel } from './texts.js'
|
||||
|
||||
@@ -88,6 +88,24 @@ export function buildIntegrationStatusBanner(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes these top-level fields of a global and nothing else (owner's decision Q3, 1.18.0). Payload's
|
||||
* `updateGlobal` reads the whole document, merges the change and writes the whole result, so a status written
|
||||
* after a visitor's form submit put back an admin's SMTP or Turnstile change saved in between. This writes the
|
||||
* fields through the database adapter directly: no read of the rest, no merge, no hooks, no new version — fit for
|
||||
* the plugin's own bookkeeping fields only. A global that does not exist yet is created the usual way.
|
||||
*/
|
||||
export async function writeGlobalFields(payload: BasePayload, slug: string, data: Record<string, unknown>): Promise<void> {
|
||||
const db = (payload as { db?: Partial<BasePayload['db']> }).db
|
||||
// a stand-in without a database adapter (a test double): the usual way
|
||||
const existing = typeof db?.findGlobal === 'function' && typeof db.updateGlobal === 'function' ? await db.findGlobal({ slug, req: {} as never }) : null
|
||||
if (!existing) {
|
||||
await payload.updateGlobal({ slug: slug as never, context: { ipalIntegrationStatus: true }, data: data as never, depth: 0 })
|
||||
return
|
||||
}
|
||||
await payload.db.updateGlobal({ slug, data: { ...data, updatedAt: new Date().toISOString() }, req: {} as never, returning: false })
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist a status change. Never throws — a status write must not break the
|
||||
* request that triggered it. The same change already being written is not
|
||||
@@ -127,12 +145,7 @@ export async function recordIntegrationStatus(
|
||||
}
|
||||
const write = (async () => {
|
||||
try {
|
||||
await payload.updateGlobal({
|
||||
slug: SITE_INTEGRATIONS as never,
|
||||
context: { ipalIntegrationStatus: true },
|
||||
data: { [field]: status } as never,
|
||||
depth: 0,
|
||||
})
|
||||
await writeGlobalFields(payload, SITE_INTEGRATIONS, { [field]: status })
|
||||
} catch (err) {
|
||||
console.warn(`[iapl] could not record ${field}:`, err instanceof Error ? err.message : err)
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { Config, Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import { COOKIE_APPROVAL_PATH } from '../consent/scanner/approval.js'
|
||||
import { COOKIE_CRAWL_PATH } from '../consent/scanner/crawl/config.js'
|
||||
import { COOKIE_SCAN_PATH } from '../consent/scanner/endpoint.js'
|
||||
import { RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH } from '../email/relay/constants.js'
|
||||
import { reportRefusedOrigin, requestFromOwnOrigin } from './totp/sameOrigin.js'
|
||||
|
||||
/**
|
||||
* The plugin's panel actions only from the site's own origin (`adminSameOrigin`, 1.17.2; IAWL idea 7, owner's Q6).
|
||||
*
|
||||
* These endpoints act with the panel's login cookie and read a body whatever its `Content-Type` says — a
|
||||
* `text/plain` POST, which another origin can send without a CORS preflight. A page on a sibling subdomain is
|
||||
* "same site", so the browser sends the `SameSite=Lax` cookie along, and Payload's own CSRF list is empty unless
|
||||
* `serverURL` or `csrf` is set. Such a page could make a signed-in administrator disconnect the mail service,
|
||||
* connect it again, send test mails, run cookie scans and crawls, or approve every waiting cookie. The rule is the
|
||||
* one 2FA verify / setup / reset use (sameOrigin.ts): a request the browser marks as coming from elsewhere
|
||||
* (`Origin`, else `Sec-Fetch-Site`) gets `403` before anything is read; a request with neither header (a script,
|
||||
* `curl`) passes — it rides on nobody's cookie. Refusals are logged once per origin with the ways to allow it.
|
||||
*/
|
||||
export type AdminSameOriginOption = {
|
||||
/** More origins that may call these endpoints (a panel on another domain). */
|
||||
origins?: string[]
|
||||
} | boolean
|
||||
|
||||
/** The panel actions the rule covers: method and path (relative to the API route). */
|
||||
export const ADMIN_POST_ENDPOINTS: ReadonlyArray<readonly ['post', string]> = [
|
||||
['post', RELAY_CONNECT_PATH],
|
||||
['post', RELAY_DISCONNECT_PATH],
|
||||
['post', '/ipal/test-email'],
|
||||
['post', COOKIE_SCAN_PATH],
|
||||
['post', COOKIE_APPROVAL_PATH],
|
||||
['post', COOKIE_CRAWL_PATH],
|
||||
]
|
||||
|
||||
const ADMIN_REFUSAL = {
|
||||
docs: 'docs/security.md "Panel actions only from the site\'s own origin"',
|
||||
option: 'iapl({ adminSameOrigin',
|
||||
what: 'a panel action',
|
||||
}
|
||||
|
||||
const covered = (endpoint: Pick<Endpoint, 'method' | 'path'>): boolean =>
|
||||
ADMIN_POST_ENDPOINTS.some(([method, path]) => endpoint.method === method && endpoint.path === path)
|
||||
|
||||
/** Wraps one endpoint: `403` for a request from another origin, the endpoint's own answer otherwise. */
|
||||
export function requireOwnOrigin<T extends Pick<Endpoint, 'handler'>>(endpoint: T, origins: string[] = []): T {
|
||||
const handler = endpoint.handler as (req: PayloadRequest) => Promise<Response> | Response
|
||||
return {
|
||||
...endpoint,
|
||||
handler: (async (req: PayloadRequest) => {
|
||||
if (!requestFromOwnOrigin(req as never, origins)) {
|
||||
reportRefusedOrigin(req as never, origins, ADMIN_REFUSAL)
|
||||
return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })
|
||||
}
|
||||
return handler(req)
|
||||
}) as T['handler'],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the rule to the covered endpoints the plugin added (`ownEndpoints`: those not in the project's config
|
||||
* before iapl ran) — a project's own endpoint on the same path is left as it is.
|
||||
*/
|
||||
export function guardAdminEndpoints(config: Config, before: ReadonlySet<unknown>, option: AdminSameOriginOption | undefined): Config {
|
||||
if (option === false) {return config}
|
||||
const origins = typeof option === 'object' ? (option.origins ?? []) : []
|
||||
return {
|
||||
...config,
|
||||
endpoints: (config.endpoints ?? []).map((e) => (!before.has(e) && covered(e) ? requireOwnOrigin(e, origins) : e)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { Config, PayloadRequest } from 'payload'
|
||||
|
||||
import { createHash, timingSafeEqual } from 'node:crypto'
|
||||
|
||||
import { userMeetsRole } from '../access/predicates.js'
|
||||
|
||||
/**
|
||||
* Who may run Payload's job queue over HTTP (`GET /api/payload-jobs/run`, `/api/payload-jobs/handle-schedules`,
|
||||
* both checked by `jobs.access.run`). Payload's own default is any signed-in account of ANY auth collection — a
|
||||
* customer of a shop included (IAWL idea 35: a route open to the web is a visitor, not the system). Since 1.17.2,
|
||||
* when the project writes no `jobs.access.run`, iapl sets: an admin signed in with the second factor (an admin's API
|
||||
* key counts), or `Authorization: Bearer <CRON_SECRET>`. A project's own rule always wins; `jobsRunAccess: false`
|
||||
* keeps Payload's default. Jobs run in-process (`jobs.autoRun`, `payload jobs:run`, `payload.jobs.run()`) never
|
||||
* pass through this rule.
|
||||
*/
|
||||
export type JobsRunAccessOptions = {
|
||||
/** The variable holding the cron secret. Default `CRON_SECRET`. Shorter than 16 characters = not used. */
|
||||
secretVar?: string
|
||||
}
|
||||
|
||||
export const CRON_SECRET_ENV = 'CRON_SECRET'
|
||||
/** The secret's minimum length: a short one would be guessable over the run route. */
|
||||
export const CRON_SECRET_MIN_LENGTH = 16
|
||||
|
||||
const sha = (value: string) => createHash('sha256').update(value).digest()
|
||||
|
||||
/** True when the request carries `Authorization: Bearer <secret>` (constant-time; an unset or short secret never matches). */
|
||||
export function cronSecretMatches(req: Pick<PayloadRequest, 'headers'>, secret: string | undefined): boolean {
|
||||
const expected = secret?.trim() ?? ''
|
||||
if (expected.length < CRON_SECRET_MIN_LENGTH) {return false}
|
||||
const header = req.headers?.get?.('authorization') ?? ''
|
||||
if (!/^Bearer\s+/i.test(header)) {return false}
|
||||
return timingSafeEqual(sha(header.replace(/^Bearer\s+/i, '').trim()), sha(expected))
|
||||
}
|
||||
|
||||
/**
|
||||
* The rule iapl puts on `jobs.access.run` (exported for a project that writes its own and wants to keep this part):
|
||||
* jobs: { access: { run: (args) => jobsRunAccess()(args) || myOwnCheck(args) } }
|
||||
*/
|
||||
export function jobsRunAccess({ secretVar = CRON_SECRET_ENV }: JobsRunAccessOptions = {}) {
|
||||
return ({ req }: { req: PayloadRequest }): boolean =>
|
||||
cronSecretMatches(req, process.env[secretVar]) || userMeetsRole(req, 'admin')
|
||||
}
|
||||
|
||||
/**
|
||||
* The config with iapl's `jobs.access.run`, only when the project wrote none (checked before Payload fills its
|
||||
* default in, so a project's rule is never mistaken for Payload's). Also when the config has no `jobs` at all:
|
||||
* Payload turns the queue on by itself for collections with scheduled publishing. Marks the config
|
||||
* (`custom.iapl.jobsRunDefault`) so the start-up note knows the rule is iapl's.
|
||||
*/
|
||||
export function withJobsRunAccess(config: Config, options: false | JobsRunAccessOptions = {}): Config {
|
||||
if (options === false || config.jobs?.access?.run) {return config}
|
||||
const custom = (config.custom ?? {}) as Record<string, unknown>
|
||||
const iapl = (custom.iapl ?? {}) as Record<string, unknown>
|
||||
return {
|
||||
...config,
|
||||
custom: { ...custom, iapl: { ...iapl, jobsRunDefault: { secretVar: options.secretVar ?? CRON_SECRET_ENV } } },
|
||||
jobs: { ...config.jobs, access: { ...config.jobs?.access, run: jobsRunAccess(options) } } as Config['jobs'],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The one line said at start when the queue is on and the rule is iapl's: how a cron reaches the run route.
|
||||
* Null when there is nothing to say.
|
||||
*/
|
||||
export function jobsRunNotice(config: { custom?: unknown; jobs?: { enabled?: boolean } }): null | string {
|
||||
const own = ((config.custom as { iapl?: { jobsRunDefault?: { secretVar?: string } } } | undefined)?.iapl)?.jobsRunDefault
|
||||
if (!own || !config.jobs?.enabled) {return null}
|
||||
const secretVar = own.secretVar ?? CRON_SECRET_ENV
|
||||
const secret = process.env[secretVar]?.trim() ?? ''
|
||||
if (secret.length >= CRON_SECRET_MIN_LENGTH) {return null}
|
||||
return (
|
||||
`[iapl] Payload's job queue runs over HTTP (/api/payload-jobs/run, /handle-schedules) only for an admin signed in with the second factor ` +
|
||||
`or with "Authorization: Bearer <${secretVar}>" (1.17.2), and ${secretVar} is ${secret ? `shorter than ${CRON_SECRET_MIN_LENGTH} characters` : 'not set'}. ` +
|
||||
`A cron that calls the run route: set ${secretVar} and send the header. In-process runs (jobs.autoRun, payload jobs:run) are not affected. ` +
|
||||
'Your own jobs.access.run wins; iapl({ jobsRunAccess: false }) keeps Payload\'s default (docs/security.md "Payload\'s job queue").'
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import type { DraftRelations } from '../content/draftRelations.js'
|
||||
import type { ContentOption } from '../content/index.js'
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
import type { SiteIndexEntry } from './siteIndex.js'
|
||||
@@ -19,6 +20,8 @@ type BuildLlmsTxtArgs = {
|
||||
* collection's own plural label. Usually the most quotable content on a site.
|
||||
*/
|
||||
content?: ContentOption
|
||||
/** Related documents that are drafts (llms-full): `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
|
||||
draftRelations?: DraftRelations
|
||||
/**
|
||||
* Full-content mode (llms-full.txt). When true, each page's full body is
|
||||
* inlined as Markdown (via blocksToMarkdown) under its heading, so an agent
|
||||
@@ -78,6 +81,7 @@ export async function buildLlmsTxt({
|
||||
baseUrl,
|
||||
config,
|
||||
content,
|
||||
draftRelations,
|
||||
full = false,
|
||||
include,
|
||||
layoutField = 'layout',
|
||||
@@ -105,6 +109,7 @@ export async function buildLlmsTxt({
|
||||
config,
|
||||
content,
|
||||
depth: full ? 1 : 0,
|
||||
draftRelations,
|
||||
include,
|
||||
locales,
|
||||
pagesSlug,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import type { DraftRelations } from '../content/draftRelations.js'
|
||||
import type { ContentOption } from '../content/index.js'
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
import type { SitemapEntry } from './buildSitemapEntries.js'
|
||||
@@ -33,6 +34,8 @@ export function createLlmsTxtRoute(opts: {
|
||||
config: I18nConfig
|
||||
/** Archive-backed collections (blog…) — listed too. Same value as the plugin option. */
|
||||
content?: ContentOption
|
||||
/** Related documents that are drafts (llms-full): `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
|
||||
draftRelations?: DraftRelations
|
||||
/** Inline every page's full Markdown (llms-full.txt). Default false. */
|
||||
full?: boolean
|
||||
getCachedPayload: () => Promise<BasePayload>
|
||||
@@ -55,6 +58,7 @@ export function createLlmsTxtRoute(opts: {
|
||||
baseUrl: opts.baseUrl,
|
||||
config: opts.config,
|
||||
content: opts.content,
|
||||
draftRelations: opts.draftRelations,
|
||||
full: opts.full,
|
||||
...(allowed ? { include: (path: string) => allowed.has(normalizePath(path)) } : {}),
|
||||
pagesSlug: opts.pagesSlug,
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
|
||||
import type { ContentOption } from '../content/index.js'
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import { applyDraftRelations, type DraftRelations } from '../content/draftRelations.js'
|
||||
import { archiveFieldName } from '../content/index.js'
|
||||
import { buildLocalizedPath, getLocaleCodes, isValidLocale } from '../i18n/index.js'
|
||||
import { resolveLocalized } from '../i18n/resolveLocalized.js'
|
||||
@@ -39,6 +40,8 @@ export type CollectSiteIndexArgs = {
|
||||
content?: ContentOption
|
||||
/** Population depth of `doc`. Default 0 (1 when you render blocks with images). */
|
||||
depth?: number
|
||||
/** Related documents in `doc` that are drafts: `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
|
||||
draftRelations?: DraftRelations
|
||||
/**
|
||||
* Only paths this returns true for — e.g. the pages still open while the site
|
||||
* is under construction. Default: every path.
|
||||
@@ -128,6 +131,7 @@ export async function collectSiteIndex({
|
||||
config,
|
||||
content,
|
||||
depth = 0,
|
||||
draftRelations,
|
||||
include,
|
||||
limit,
|
||||
locales,
|
||||
@@ -162,7 +166,7 @@ export async function collectSiteIndex({
|
||||
if (collection !== pagesSlug && !prefix?.[locale]) {continue}
|
||||
let docs: Row[] = []
|
||||
try {
|
||||
docs = await readDocs(payload, collection, { depth, limit, locale })
|
||||
docs = applyDraftRelations(await readDocs(payload, collection, { depth, limit, locale }), { draftRelations })
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* The answer of a project's access callback (`cookieScanner.access`, the doctor's `access`), read the same way
|
||||
* everywhere (owner's decision Q4, 1.18.0).
|
||||
*
|
||||
* Today any truthy answer lets the request in, as before: `({ req }) => req.user` returns an account object, and
|
||||
* a function that returns `'no'` or `{}` lets the request in too. From the next minor version only `true` will
|
||||
* allow. Until then the first answer that is not a boolean is reported once per option in the server log, so a
|
||||
* project sees it before the change. (A callback needs a request to be asked, so this cannot be checked at start:
|
||||
* the warning comes with the first call.)
|
||||
*/
|
||||
const warned = new Set<string>()
|
||||
|
||||
export type AccessAnswerOptions = {
|
||||
/** Where to report (default `console.warn`). */
|
||||
warn?: (message: string) => void
|
||||
}
|
||||
|
||||
/** True when the request may pass; warns once per `option` when the answer is not a boolean. */
|
||||
export function accessAllowed(option: string, answer: unknown, { warn = (m) => console.warn(m) }: AccessAnswerOptions = {}): boolean {
|
||||
if (typeof answer !== 'boolean' && !warned.has(option)) {
|
||||
warned.add(option)
|
||||
const kind = answer === null ? 'null' : Array.isArray(answer) ? 'an array' : typeof answer === 'object' ? 'an object' : `a ${typeof answer}`
|
||||
warn(
|
||||
`[iapl] ${option} returned ${kind}, not true or false. It is still read as ${answer ? 'allowed' : 'refused'}; from the next minor version only \`true\` allows. Return a boolean, e.g. \`({ req }) => Boolean(req.user)\` (docs/security.md "Access callbacks").`,
|
||||
)
|
||||
}
|
||||
return Boolean(answer)
|
||||
}
|
||||
|
||||
/** For tests: forget which options were reported. */
|
||||
export function resetAccessWarnings(): void {
|
||||
warned.clear()
|
||||
}
|
||||
+118
-13
@@ -94,8 +94,103 @@ export function setUnknownIpFactor(factor: number): void {
|
||||
unknownIpFactor = Math.max(0, factor)
|
||||
}
|
||||
|
||||
/**
|
||||
* IPv6 is counted per network, not per address (1.17.2, IAWL idea 9). A host with IPv6 gets a whole /64
|
||||
* (2^64 addresses) — every home connection and every server does — so counting per address gave one visitor
|
||||
* as many budgets as it has addresses. Every limiter of the plugin (forms, search, MCP, consent log, stats,
|
||||
* doctor, the mail service's confirm route and account-mail limit) counts a /64 as one client. One home network
|
||||
* shares the budget then, as an IPv4 home behind one router always did.
|
||||
*
|
||||
* Optionally a second, roomier counter per wider network (`wide: 48`, `wideFactor` × the limit): one hosting
|
||||
* customer often holds a /48 (65,536 /64s). Off by default — mobile carriers can put many phones in one /48.
|
||||
*/
|
||||
export type Ipv6Grouping = {
|
||||
/** Prefix length one client is counted by. Default 64; 128 = per address (as before 1.17.2). 1–128. */
|
||||
prefix?: number
|
||||
/** A second counter per this wider prefix (e.g. 48), at `wideFactor` × the limit. Default: none. */
|
||||
wide?: false | number
|
||||
/** Multiplier for the wide counter's limit. Default 10. */
|
||||
wideFactor?: number
|
||||
}
|
||||
|
||||
let ipv6 = { prefix: 64, wide: 0, wideFactor: 10 }
|
||||
|
||||
/** How every limiter of the plugin counts IPv6 clients (call once at start). `setIpv6Grouping({ prefix: 128 })` = per address. */
|
||||
export function setIpv6Grouping(next: Ipv6Grouping = {}): void {
|
||||
const prefix = next.prefix ?? 64
|
||||
const wide = next.wide === false || next.wide === undefined ? 0 : next.wide
|
||||
const wideFactor = next.wideFactor ?? 10
|
||||
for (const [name, value, min] of [['prefix', prefix, 1], ['wide', wide, 0], ['wideFactor', wideFactor, 1]] as const) {
|
||||
if (!Number.isInteger(value) || value < min || value > (name === 'wideFactor' ? 1e6 : 128)) {
|
||||
throw new Error(`[iapl] setIpv6Grouping: ${name} must be a whole number from ${min}${name === 'wideFactor' ? '' : ' to 128'} (received ${JSON.stringify(value)}).`)
|
||||
}
|
||||
}
|
||||
if (wide && wide >= prefix) {throw new Error(`[iapl] setIpv6Grouping: wide (${wide}) must be a shorter prefix than prefix (${prefix}).`)}
|
||||
ipv6 = { prefix, wide, wideFactor }
|
||||
}
|
||||
|
||||
/** A dotted IPv4 address (no `node:net`: this module also reaches bundles that are not Node's). */
|
||||
function isIPv4(value: string): boolean {
|
||||
const parts = value.split('.')
|
||||
return parts.length === 4 && parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255)
|
||||
}
|
||||
|
||||
/** The 8 groups of an IPv6 address as numbers (brackets and a zone id allowed), or null when it is not one. */
|
||||
function ipv6Groups(address: string): null | number[] {
|
||||
let text = address.replace(/^\[|\]$/g, '').split('%')[0]
|
||||
if (!text.includes(':') || !/^[0-9a-f:.]+$/i.test(text) || text.split('::').length > 2) {return null}
|
||||
const v4 = /(?:^|:)(\d+\.\d+\.\d+\.\d+)$/.exec(text)
|
||||
if (v4) {
|
||||
if (!isIPv4(v4[1])) {return null}
|
||||
const [a, b, c, d] = v4[1].split('.').map(Number)
|
||||
text = text.slice(0, -v4[1].length) + `${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`
|
||||
} else if (text.includes('.')) {return null}
|
||||
const compressed = text.includes('::')
|
||||
const [head, tail = ''] = compressed ? text.split('::') : [text]
|
||||
const left = head ? head.split(':') : []
|
||||
const right = tail ? tail.split(':') : []
|
||||
if ([...left, ...right].some((g) => !/^[0-9a-f]{1,4}$/i.test(g))) {return null}
|
||||
const missing = 8 - left.length - right.length
|
||||
if (compressed ? missing < 1 : missing !== 0) {return null}
|
||||
return [...left, ...Array(compressed ? missing : 0).fill('0'), ...right].map((g) => parseInt(g, 16))
|
||||
}
|
||||
|
||||
/** `2001:db8:1:2::/64` for any address of that network (`bits` = prefix length). */
|
||||
function ipv6Network(groups: number[], bits: number): string {
|
||||
const out = groups.map((g, i) => {
|
||||
const start = i * 16
|
||||
if (start >= bits) {return 0}
|
||||
const keep = Math.min(16, bits - start)
|
||||
return keep === 16 ? g : g & ((0xffff << (16 - keep)) & 0xffff)
|
||||
})
|
||||
return `${out.map((g) => g.toString(16)).join(':')}/${bits}`
|
||||
}
|
||||
|
||||
/**
|
||||
* The key one client is counted by: an IPv4 address as it is, an IPv4-mapped IPv6 address (`::ffff:1.2.3.4`) as
|
||||
* its IPv4, an IPv6 address as its network (`setIpv6Grouping`, default /64). Anything else is returned unchanged.
|
||||
* Use it for a limiter of your own keyed by `clientIp()`.
|
||||
*/
|
||||
export function ipRateKey(ip: string): string {
|
||||
const value = ip.trim()
|
||||
if (!value || isIPv4(value)) {return value}
|
||||
const groups = ipv6Groups(value)
|
||||
if (!groups) {return value}
|
||||
const mapped = groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff
|
||||
if (mapped) {return `${groups[6] >> 8}.${groups[6] & 0xff}.${groups[7] >> 8}.${groups[7] & 0xff}`}
|
||||
return ipv6Network(groups, ipv6.prefix)
|
||||
}
|
||||
|
||||
/** The wide network of an IPv6 key, when the wide counter is on; null otherwise. */
|
||||
function wideKeyOf(ip: string): null | string {
|
||||
if (!ipv6.wide) {return null}
|
||||
const groups = ipv6Groups(ip.trim())
|
||||
if (!groups || (groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff)) {return null}
|
||||
return ipv6Network(groups, ipv6.wide)
|
||||
}
|
||||
|
||||
function resolveKey(key: string, max: number): { key: string; max: number } | null {
|
||||
if (key) {return { key, max }}
|
||||
if (key) {return { key: ipRateKey(key), max }}
|
||||
return unknownIpFactor > 0 ? { key: UNKNOWN_IP_KEY, max: max * unknownIpFactor } : null
|
||||
}
|
||||
|
||||
@@ -125,10 +220,16 @@ export function checkRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope =
|
||||
if (!resolved) {return true}
|
||||
const { key, max } = resolved
|
||||
const id = `${scope}:${key}`
|
||||
const current = buckets.get(id)
|
||||
const used = current && current.resetAt > Date.now() ? current.count : 0
|
||||
if (used + cost > max) {return false}
|
||||
const wide = wideKeyOf(rawKey)
|
||||
const wideId = wide ? `${scope}:${wide}` : null
|
||||
const used = (bucketId: string) => {
|
||||
const current = buckets.get(bucketId)
|
||||
return current && current.resetAt > Date.now() ? current.count : 0
|
||||
}
|
||||
if (used(id) + cost > max) {return false}
|
||||
if (wideId && used(wideId) + cost > max * ipv6.wideFactor) {return false}
|
||||
hitMemory(id, cost, windowMs)
|
||||
if (wideId) {hitMemory(wideId, cost, windowMs)}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -149,21 +250,25 @@ export async function consumeRateLimit({
|
||||
if (!resolved) {return { ok: true, retryAfter: 0 }}
|
||||
const { key, max } = resolved
|
||||
const id = `${scope}:${key}`
|
||||
const wide = wideKeyOf(rawKey)
|
||||
|
||||
let bucket: Bucket
|
||||
if (store) {
|
||||
const hit = async (bucketId: string): Promise<Bucket | null> => {
|
||||
if (!store) {return hitMemory(bucketId, cost, windowMs)}
|
||||
try {
|
||||
bucket = await store.hit(id, cost, windowMs)
|
||||
return await store.hit(bucketId, cost, windowMs)
|
||||
} catch (err) {
|
||||
console.warn('[iapl] rate limit store failed, allowing request:', err instanceof Error ? err.message : err)
|
||||
return { ok: true, retryAfter: 0 }
|
||||
return null
|
||||
}
|
||||
} else {
|
||||
bucket = hitMemory(id, cost, windowMs)
|
||||
}
|
||||
const bucket = await hit(id)
|
||||
if (!bucket) {return { ok: true, retryAfter: 0 }}
|
||||
const wideBucket = wide ? await hit(`${scope}:${wide}`) : null
|
||||
|
||||
const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000))
|
||||
return { ok: bucket.count <= max, retryAfter }
|
||||
const over = [bucket.count > max ? bucket : null, wideBucket && wideBucket.count > max * ipv6.wideFactor ? wideBucket : null].filter((b): b is Bucket => b !== null)
|
||||
const later = over.reduce((at, b) => Math.max(at, b.resetAt), bucket.resetAt)
|
||||
const retryAfter = Math.max(1, Math.ceil(((over.length ? later : bucket.resetAt) - Date.now()) / 1000))
|
||||
return { ok: over.length === 0, retryAfter }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -190,7 +295,7 @@ export async function releaseRateLimit({ cost = 1, key: rawKey, max: rawMax = 5,
|
||||
|
||||
/** Seconds until the key's IN-MEMORY window resets — for a Retry-After header. */
|
||||
export function retryAfterSeconds(key: string, scope = 'form'): number {
|
||||
const bucket = buckets.get(`${scope}:${key}`)
|
||||
const bucket = buckets.get(`${scope}:${key ? ipRateKey(key) : UNKNOWN_IP_KEY}`)
|
||||
return bucket ? Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)) : 1
|
||||
}
|
||||
|
||||
|
||||
@@ -50,9 +50,11 @@ export function assertPluginSwitches(options: Record<string, unknown>): void {
|
||||
// `accounts: 0` / `''` dropped every account rule (staff-only reads, admin-only writes, the panel role,
|
||||
// the password rule, the closed first-user route).
|
||||
assertSwitchOrObject('accounts', options.accounts, { allowTrue: false })
|
||||
// 1.17.2: only 'payload' brings Payload's "locked" answer back (it tells which addresses have an account).
|
||||
// 1.18.0: the sign-in rules. `signInLimit: 0` / `'false'` must not read as off; a limit of 0 never refuses.
|
||||
const accounts = bag(options.accounts)
|
||||
if (accounts) {
|
||||
assertOneOf('accounts.lockedAnswer', accounts.lockedAnswer, ['payload', 'wrong'])
|
||||
assertBooleanSwitch('accounts.confirmOwnChanges', accounts.confirmOwnChanges)
|
||||
assertSwitchOrObject('accounts.signInLimit', accounts.signInLimit, { allowTrue: false })
|
||||
const limit = bag(accounts.signInLimit)
|
||||
@@ -78,6 +80,12 @@ export function assertPluginSwitches(options: Record<string, unknown>): void {
|
||||
assertSwitchOrObject(name, options[name])
|
||||
}
|
||||
assertBooleanSwitch('indexNow', options.indexNow)
|
||||
// 1.17.2: `adminSameOrigin: 0` / `'false'` must not read as off (it took the origin check off the panel actions)
|
||||
assertSwitchOrObject('adminSameOrigin', options.adminSameOrigin)
|
||||
const adminSameOrigin = bag(options.adminSameOrigin)
|
||||
if (adminSameOrigin && adminSameOrigin.origins !== undefined && !(Array.isArray(adminSameOrigin.origins) && adminSameOrigin.origins.every((o) => typeof o === 'string'))) {
|
||||
throw new Error(`${where('adminSameOrigin.origins')} must be a list of origins such as ['https://panel.example.com'] (received ${JSON.stringify(adminSameOrigin.origins)}).`)
|
||||
}
|
||||
// an unknown name ('IAPL') used to mean 'ipal': the scanner declared one visitor cookie while the site set another
|
||||
assertOneOf('storageNames', options.storageNames, ['ipal', 'iapl'])
|
||||
assertBooleanSwitch('lightbox', options.lightbox)
|
||||
|
||||
Reference in New Issue
Block a user