Staff sign-in rules: failures per IP and address, own origin, current password for own changes (1.18.0)
Q2 (IAWL idea 16): Payload locks a staff account after 5 wrong passwords from anybody, so a stranger kept the owner out without a password. Failed sign-ins are now counted per client IP and typed address (folded: NFKC, lower case, trim): 5 in 15 min, then 429 for that IP and address only; only failures count (a place taken before the compare, given back on success or refusal; "try again in a moment" while others are being checked). Payload's own lock stays as the net at 50 failures for an hour where the project set none. The mail service's account-mail limit now counts per address per visitor (5) with 20 per address in all, so one stranger no longer blocks the owner's own reset mail. Q3 (idea 7): staff login, forgot and reset password refuse a request a browser marks as coming from another origin (403 before anything is counted or sent); visitor collections untouched. Q5 (idea 29): an account that changes its own e-mail, username or password must send its current password (panel field on the account page via the plugin's MaskedField, no import-map change; REST and GraphQL). Admins changing others, server code and API keys are not asked; wrong ones count like failed sign-ins. Options accounts.signInLimit / signInSameOrigin / confirmOwnChanges, all validated at start. Tests: 15 HTTP tests (2FA on/off, all off), fail before on 1.17.1; built-site spec own-account.spec.ts in e2e:built. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
fc70a34f3e
commit
52710021ef
+13
-1
@@ -50,6 +50,18 @@ export {
|
||||
} from './modules/access/selfRegistration.js'
|
||||
export type { AccountsMarker, LateAdoption, StaffAccountAccessOptions, StaffAccountRules } from './modules/access/selfRegistration.js'
|
||||
export type { FirstUserRouteOption } from './modules/access/selfRegistration.js'
|
||||
export {
|
||||
applySignInRules,
|
||||
buildCurrentPasswordField,
|
||||
buildSignInBeforeOperation,
|
||||
CURRENT_PASSWORD_FIELD,
|
||||
foldSignInName,
|
||||
passwordMatches,
|
||||
releaseSignInPlace,
|
||||
resolveSignInRules,
|
||||
settleFailedSignIn,
|
||||
} from './modules/access/signInRules.js'
|
||||
export type { SignInLimitOptions, SignInRulesOptions, SignInSameOriginOptions } from './modules/access/signInRules.js'
|
||||
export type { AccountsOptions } from './modules/access/types.js'
|
||||
// Concrete files, not module barrels: a barrel that also re-exports 'use client'
|
||||
// components would load React UI into payload.config / the CLI (test/entryGraph).
|
||||
@@ -568,7 +580,7 @@ export { applyCollectionOverride } from './modules/shared/collectionOverride.js'
|
||||
export type { CollectionOverride } from './modules/shared/collectionOverride.js'
|
||||
// Development addresses by pattern (no env): the built-in list and the matcher behind `developmentHosts`.
|
||||
export { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from './modules/shared/developmentHosts.js'
|
||||
export { clientIp, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
|
||||
export { clientIp, releaseRateLimit, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
|
||||
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
|
||||
export { buildSlugField, toSlug } from './modules/slug/index.js'
|
||||
export { STATS_SLUG } from './modules/stats/index.js'
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
import type { CollectionAfterLoginHook, CollectionBeforeOperationHook, CollectionConfig, Field, PayloadRequest } from 'payload'
|
||||
|
||||
import { pbkdf2, timingSafeEqual } from 'node:crypto'
|
||||
import { APIError, Forbidden, ValidationError } from 'payload'
|
||||
|
||||
import { serverText } from '../integrations/texts.js'
|
||||
import { reportRefusedOrigin, requestFromOwnOrigin } from '../security/totp/sameOrigin.js'
|
||||
import { clientIp, consumeRateLimit, releaseRateLimit } from '../shared/rateLimit.js'
|
||||
import { userMeetsRole } from './predicates.js'
|
||||
|
||||
/**
|
||||
* Sign-in rules of the staff collections (1.18.0; IAWL ideas 16, 7 and 29 — the owner's Q2, Q3 and Q5).
|
||||
*
|
||||
* 1. **A stranger cannot lock a staff account out** (`accounts.signInLimit`). Payload locks an account after
|
||||
* `maxLoginAttempts` wrong passwords (5) for `lockTime` (10 min) — wrong passwords from ANYBODY, no password
|
||||
* needed: five posts kept the owner out, again and again. Now failures are counted per client IP and typed
|
||||
* address (`perAddress`, default 5 in `windowMinutes`, 15): the sixth try of one IP for one address gets `429`,
|
||||
* everybody else is untouched. Payload's own per-account lock stays as the net against a spray from many IPs,
|
||||
* at a much higher count (`accountLock`: 50 failures, locked for an hour) — set only where the project did not
|
||||
* set `maxLoginAttempts` / `lockTime` itself. The typed address is folded like a database that folds the most
|
||||
* (case, width, compatibility forms: NFKC + lower case), so spellings of one address share one count. Only
|
||||
* failures stay counted: a place is taken before the password is compared (a burst cannot slip under) and given
|
||||
* back when the sign-in worked or was refused without a compare; a refusal caused only by sign-ins still being
|
||||
* checked says "try again in a moment". The answer for "too many" is the same for a real and an invented address.
|
||||
* 2. **Staff sign-in only from the site's own origin** (`accounts.signInSameOrigin`). Login, "forgot password" and
|
||||
* "reset password" of a staff collection refuse (`403`, before anything is counted or sent) a request a browser
|
||||
* marks as coming from another origin — a foreign page could otherwise sign a visitor's browser into an account
|
||||
* of the attacker's choosing, or have visitors' browsers request reset mails. The rule of the 2FA endpoints
|
||||
* (sameOrigin.ts); a request with neither `Origin` nor `Sec-Fetch-Site` (a script, `curl`) passes.
|
||||
* 3. **Changing one's own e-mail or password asks for the current password** (`accounts.confirmOwnChanges`), in the
|
||||
* panel and over REST / GraphQL: a stolen session alone can no longer take the account over (new e-mail, then
|
||||
* "forgot password"). The panel gets a "Current password" field on the account's own page (the plugin's
|
||||
* `MaskedField`, already in every site's import map). An administrator changing ANOTHER account is not asked;
|
||||
* server code (`overrideAccess`) and API keys are not asked. Wrong current passwords count like failed sign-ins.
|
||||
*
|
||||
* Server code (the Local API) is never limited or checked here.
|
||||
*/
|
||||
export type SignInLimitOptions = {
|
||||
/** Payload's per-account lock for staff collections that do not set their own. Default `{ maxLoginAttempts: 50, lockTime: 3_600_000 }`; `false` = Payload's defaults (5, 10 min). */
|
||||
accountLock?: { lockTime?: number; maxLoginAttempts?: number } | false
|
||||
/** Failed sign-ins per client IP and typed address in the window. Default 5. */
|
||||
perAddress?: number
|
||||
/** The window, in minutes. Default 15. */
|
||||
windowMinutes?: number
|
||||
}
|
||||
export type SignInSameOriginOptions = { origins?: string[] }
|
||||
|
||||
export type SignInRulesOptions = {
|
||||
confirmOwnChanges?: false
|
||||
signInLimit?: false | SignInLimitOptions
|
||||
signInSameOrigin?: false | SignInSameOriginOptions
|
||||
}
|
||||
|
||||
/** The name of the panel's "Current password" field (and the body key over REST / GraphQL). */
|
||||
export const CURRENT_PASSWORD_FIELD = 'currentPassword'
|
||||
const SCOPE = 'iapl-signin'
|
||||
|
||||
/** A typed address folded like the database that folds the most: case, width and compatibility forms, spaces. */
|
||||
export const foldSignInName = (value: unknown): string => (typeof value === 'string' ? value.normalize('NFKC').toLowerCase().trim() : '')
|
||||
|
||||
const isLocal = (req: PayloadRequest | undefined) => !req || (req as { payloadAPI?: string }).payloadAPI === 'local' || !req.headers
|
||||
|
||||
/** Places taken by sign-ins of one IP + address still being checked (this instance). */
|
||||
const inFlight = new Map<string, number>()
|
||||
const flightKey = (scope: string, ip: string) => `${scope}|${ip}`
|
||||
const flight = (key: string, by: number) => {
|
||||
const next = Math.max(0, (inFlight.get(key) ?? 0) + by)
|
||||
if (next) {inFlight.set(key, next)} else {inFlight.delete(key)}
|
||||
}
|
||||
/** For tests. */
|
||||
export const clearSignInFlights = (): void => inFlight.clear()
|
||||
|
||||
type Place = { ip: string; max: number; scope: string; windowMs: number }
|
||||
const PLACE = Symbol.for('iapl.signInPlace')
|
||||
type WithPlace = { [PLACE]?: Place }
|
||||
|
||||
/** Takes a place for one sign-in (or current-password check). Throws 429 when the IP + address has used its failures. */
|
||||
async function takePlace(req: PayloadRequest, name: string, limit: Required<Omit<SignInLimitOptions, 'accountLock'>>): Promise<Place> {
|
||||
const ip = clientIp(req.headers)
|
||||
const scope = `${SCOPE}:${name}`
|
||||
const windowMs = limit.windowMinutes * 60_000
|
||||
const place: Place = { ip, max: limit.perAddress, scope, windowMs }
|
||||
const busy = inFlight.get(flightKey(scope, ip)) ?? 0
|
||||
const { ok, retryAfter } = await consumeRateLimit({ key: ip, max: limit.perAddress, scope, windowMs })
|
||||
if (!ok) {
|
||||
// refused without a compare: the place goes back at once
|
||||
await releaseRateLimit({ key: ip, max: limit.perAddress, scope, windowMs })
|
||||
const i18n = req.i18n as never
|
||||
if (busy > 0) {throw new APIError(serverText(i18n, 'signInBusy'), 429, null, true)}
|
||||
throw new APIError(serverText(i18n, 'signInTooMany', { minutes: Math.max(1, Math.ceil(retryAfter / 60)) }), 429, null, true)
|
||||
}
|
||||
flight(flightKey(scope, ip), 1)
|
||||
return place
|
||||
}
|
||||
|
||||
async function givePlaceBack(place: Place | undefined, kept: boolean): Promise<void> {
|
||||
if (!place) {return}
|
||||
flight(flightKey(place.scope, place.ip), -1)
|
||||
if (!kept) {await releaseRateLimit({ key: place.ip, max: place.max, scope: place.scope, windowMs: place.windowMs })}
|
||||
}
|
||||
|
||||
/** Payload's own check of a stored password hash (auth/strategies/local), for the current-password rule. */
|
||||
const HASH_PREFIXES: Record<string, number> = { 'pbkdf2-sha256-100k-v1:': 100_000, 'pbkdf2-sha256-v1:': 600_000 }
|
||||
export async function passwordMatches(stored: { hash?: unknown; salt?: unknown }, password: string): Promise<boolean> {
|
||||
const { hash, salt } = stored
|
||||
if (typeof hash !== 'string' || typeof salt !== 'string' || !password) {return false}
|
||||
const prefix = Object.keys(HASH_PREFIXES).find((p) => hash.startsWith(p))
|
||||
// a hash with a prefix of a later Payload this code does not know: refused (fail closed), never accepted
|
||||
if (!prefix && /^[a-z0-9-]+:/i.test(hash)) {return false}
|
||||
const [hex, iterations, keyLength] = prefix ? [hash.slice(prefix.length), HASH_PREFIXES[prefix], 32] : [hash, 25_000, 512]
|
||||
const derived = await new Promise<Buffer>((resolve, reject) => pbkdf2(password, salt, iterations, keyLength, 'sha256', (err, key) => (err ? reject(err) : resolve(key))))
|
||||
const expected = Buffer.from(hex, 'hex')
|
||||
return expected.length === derived.length && timingSafeEqual(expected, derived)
|
||||
}
|
||||
|
||||
type Resolved = { confirm: boolean; limit: false | Required<Omit<SignInLimitOptions, 'accountLock'>>; origins: false | string[]; /** the field is the plugin's (virtual): its value is taken out of the save */ stripField?: boolean }
|
||||
|
||||
const signInOriginOk = (req: PayloadRequest, origins: string[]): boolean => {
|
||||
if (requestFromOwnOrigin(req as never, origins)) {return true}
|
||||
reportRefusedOrigin(req as never, origins, {
|
||||
docs: 'docs/access.md "Staff sign-in only from the site\'s own origin"',
|
||||
option: 'iapl({ accounts: { signInSameOrigin',
|
||||
what: 'a staff sign-in',
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
/** `beforeOperation` for a staff collection: the origin rule, the failure count and the current-password rule. */
|
||||
export function buildSignInBeforeOperation(slug: string, rules: Resolved): CollectionBeforeOperationHook {
|
||||
return async ({ args, operation, req }) => {
|
||||
if (isLocal(req)) {return args}
|
||||
const data = ((args as { data?: Record<string, unknown> }).data ?? {})
|
||||
if (operation === 'login' || operation === 'forgotPassword' || operation === 'resetPassword') {
|
||||
if (rules.origins && !signInOriginOk(req, rules.origins)) {throw new Forbidden(req.t)}
|
||||
if (operation === 'login' && rules.limit) {
|
||||
const name = foldSignInName(data.email ?? data.username)
|
||||
;(req as WithPlace)[PLACE] = await takePlace(req, name, rules.limit)
|
||||
}
|
||||
return args
|
||||
}
|
||||
if (operation === 'update' && rules.confirm) {await confirmOwnChange(slug, args as never, req, rules)}
|
||||
return args
|
||||
}
|
||||
}
|
||||
|
||||
/** `afterLogin`: the sign-in worked, its place goes back. */
|
||||
export const releaseSignInPlace: CollectionAfterLoginHook = async ({ req }) => {
|
||||
const place = (req as WithPlace)[PLACE]
|
||||
delete (req as WithPlace)[PLACE]
|
||||
await givePlaceBack(place, false)
|
||||
}
|
||||
|
||||
/** An `afterError` (config level): a sign-in that failed keeps its place but is no longer "being checked". */
|
||||
export const settleFailedSignIn = ({ req }: { req?: PayloadRequest }): void => {
|
||||
const place = req ? (req as WithPlace)[PLACE] : undefined
|
||||
if (!place || !req) {return}
|
||||
delete (req as WithPlace)[PLACE]
|
||||
flight(flightKey(place.scope, place.ip), -1)
|
||||
}
|
||||
|
||||
async function confirmOwnChange(slug: string, args: { data?: Record<string, unknown>; id?: number | string; overrideAccess?: boolean }, req: PayloadRequest, rules: Resolved): Promise<void> {
|
||||
const data = args.data
|
||||
if (!data || args.overrideAccess === true) {return}
|
||||
const typed = data[CURRENT_PASSWORD_FIELD]
|
||||
if (rules.stripField !== false) {delete data[CURRENT_PASSWORD_FIELD]}
|
||||
const user = req.user as ({ _strategy?: string; collection?: string; email?: string; id: number | string; username?: string } & Record<string, unknown>) | null
|
||||
if (!user || user.collection !== slug || user._strategy === 'api-key') {return}
|
||||
const own = args.id !== undefined ? String(args.id) === String(user.id) : !userMeetsRole(req, 'admin')
|
||||
if (!own) {return}
|
||||
const changesEmail = typeof data.email === 'string' && foldSignInName(data.email) !== foldSignInName(user.email)
|
||||
const changesName = typeof data.username === 'string' && foldSignInName(data.username) !== foldSignInName(user.username)
|
||||
const changesPassword = typeof data.password === 'string' && data.password !== ''
|
||||
if (!changesEmail && !changesName && !changesPassword) {return}
|
||||
const i18n = req.i18n as never
|
||||
const fail = (key: 'currentPasswordRequired' | 'currentPasswordWrong') =>
|
||||
new ValidationError({ collection: slug, errors: [{ message: serverText(i18n, key), path: CURRENT_PASSWORD_FIELD }] }, req.t)
|
||||
if (typeof typed !== 'string' || typed === '') {throw fail('currentPasswordRequired')}
|
||||
const place = rules.limit ? await takePlace(req, foldSignInName(user.email ?? user.username ?? String(user.id)), rules.limit) : undefined
|
||||
let right = false
|
||||
try {
|
||||
const stored = await (req.payload).db.findOne({ collection: slug, req, where: { id: { equals: user.id } } })
|
||||
right = await passwordMatches((stored ?? {}) as { hash?: unknown; salt?: unknown }, typed)
|
||||
} finally {
|
||||
await givePlaceBack(place, !right)
|
||||
}
|
||||
if (!right) {throw fail('currentPasswordWrong')}
|
||||
}
|
||||
|
||||
/** The panel's "Current password" field: virtual, never stored, never read back, shown only on one's own account. */
|
||||
export function buildCurrentPasswordField(): Field {
|
||||
return {
|
||||
name: CURRENT_PASSWORD_FIELD,
|
||||
type: 'text',
|
||||
admin: {
|
||||
components: { Field: '@intecion/ipal-kit/admin#MaskedField' },
|
||||
condition: (data, _sibling, ctx) => {
|
||||
const user = (ctx as { user?: { id?: unknown } | null } | undefined)?.user
|
||||
return Boolean(user && data?.id !== undefined && String(user.id) === String(data.id))
|
||||
},
|
||||
description: ({ t }) => serverText({ language: (t as unknown as { i18n?: { language?: string } })?.i18n?.language } as never, 'currentPasswordDescription'),
|
||||
},
|
||||
hooks: { afterRead: [() => undefined] },
|
||||
label: ({ t }) => serverText({ language: (t as unknown as { i18n?: { language?: string } })?.i18n?.language } as never, 'currentPasswordLabel'),
|
||||
virtual: true,
|
||||
} as Field
|
||||
}
|
||||
|
||||
/** Resolves the three options (with their defaults). */
|
||||
export function resolveSignInRules(options: SignInRulesOptions = {}): Resolved {
|
||||
const limit = options.signInLimit === false ? false : { perAddress: options.signInLimit?.perAddress ?? 5, windowMinutes: options.signInLimit?.windowMinutes ?? 15 }
|
||||
const origins = options.signInSameOrigin === false ? false : (options.signInSameOrigin?.origins ?? [])
|
||||
return { confirm: options.confirmOwnChanges !== false, limit, origins }
|
||||
}
|
||||
|
||||
/** Puts the rules on one staff collection of a (not yet sanitized) config. A project's own `maxLoginAttempts` / `lockTime` stay. */
|
||||
export function applySignInRules(collection: CollectionConfig, options: SignInRulesOptions = {}): CollectionConfig {
|
||||
if (!collection.auth) {return collection}
|
||||
const rules = resolveSignInRules(options)
|
||||
const auth = typeof collection.auth === 'object' ? collection.auth : {}
|
||||
const lock = options.signInLimit === false || options.signInLimit?.accountLock === false ? null : { lockTime: options.signInLimit?.accountLock?.lockTime ?? 3_600_000, maxLoginAttempts: options.signInLimit?.accountLock?.maxLoginAttempts ?? 50 }
|
||||
const ownField = (collection.fields ?? []).some((f) => (f as { name?: string }).name === CURRENT_PASSWORD_FIELD)
|
||||
return {
|
||||
...collection,
|
||||
auth: {
|
||||
...auth,
|
||||
...(lock && auth.maxLoginAttempts === undefined ? { maxLoginAttempts: lock.maxLoginAttempts } : {}),
|
||||
...(lock && auth.lockTime === undefined ? { lockTime: lock.lockTime } : {}),
|
||||
},
|
||||
fields: rules.confirm && !ownField ? [...(collection.fields ?? []), buildCurrentPasswordField()] : collection.fields,
|
||||
hooks: {
|
||||
...collection.hooks,
|
||||
afterLogin: [...(collection.hooks?.afterLogin ?? []), releaseSignInPlace],
|
||||
beforeOperation: [buildSignInBeforeOperation(collection.slug, { ...rules, stripField: !ownField }), ...(collection.hooks?.beforeOperation ?? [])],
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
import type { PasswordRuleOptions } from './passwordRule.js'
|
||||
import type { SignInLimitOptions, SignInSameOriginOptions } from './signInRules.js'
|
||||
|
||||
/**
|
||||
* Role hierarchy, lowest to highest privilege.
|
||||
@@ -40,6 +41,13 @@ export type AccountsOptions = {
|
||||
* `false` = Payload's default on collections without a rule, as before.
|
||||
*/
|
||||
adminOnlyWrite?: false
|
||||
/**
|
||||
* Changing one's OWN e-mail address, username or password asks for the current password — in the panel (a
|
||||
* "Current password" field on the account's own page) and over REST / GraphQL (`currentPassword` in the body).
|
||||
* An administrator changing another account, server code and API keys are not asked (1.18.0).
|
||||
* `false` = no question, as before.
|
||||
*/
|
||||
confirmOwnChanges?: false
|
||||
/**
|
||||
* Which auth collections Payload's first-user route
|
||||
* (`POST /api/<slug>/first-register`) answers for while they are empty.
|
||||
@@ -67,6 +75,20 @@ export type AccountsOptions = {
|
||||
* logging in. `false` = Payload's own rule (3 characters).
|
||||
*/
|
||||
password?: false | PasswordRuleOptions
|
||||
/**
|
||||
* Failed sign-ins to a staff collection are counted per client IP and typed address: the sixth failure of one
|
||||
* IP for one address in 15 minutes gets `429`; nobody else is affected — a stranger can no longer lock the owner
|
||||
* out. Payload's per-account lock stays as the net against many IPs, at 50 failures for an hour (where the
|
||||
* project did not set `auth.maxLoginAttempts` / `lockTime` itself). Only failures count (1.18.0).
|
||||
* `false` = Payload's lock as it was (5 failures from anywhere, 10 minutes) and no per-IP count.
|
||||
*/
|
||||
signInLimit?: false | SignInLimitOptions
|
||||
/**
|
||||
* Login, "forgot password" and "reset password" of a staff collection refuse (`403`) a request a browser marks as
|
||||
* coming from another origin (1.18.0). `origins` adds origins (a panel front end on another domain).
|
||||
* `false` = no check, as before.
|
||||
*/
|
||||
signInSameOrigin?: false | SignInSameOriginOptions
|
||||
/**
|
||||
* `read` on a staff collection without a `read` rule: a fully signed-in
|
||||
* account of a staff collection. Payload's default let any logged-in
|
||||
|
||||
@@ -3,8 +3,14 @@ import { defineTexts } from '../define.js'
|
||||
/** Admin component texts — two-step verification (2FA). Placeholders use Payload's {{name}} syntax. */
|
||||
export const securityTexts = defineTexts({
|
||||
en: {
|
||||
currentPasswordDescription: 'Needed only to change your own e-mail address or password.',
|
||||
currentPasswordLabel: 'Current password',
|
||||
currentPasswordRequired: 'Enter your current password to change your e-mail address or password.',
|
||||
currentPasswordWrong: 'The current password is not right.',
|
||||
passwordIsEmail: 'The password cannot be the same as the e-mail address.',
|
||||
passwordTooShort: 'The password must have at least {{min}} characters.',
|
||||
signInBusy: 'Another sign-in to this account from here is being checked right now. Try again in a moment.',
|
||||
signInTooMany: 'Too many failed sign-ins to this address from here. Try again in {{minutes}} min.',
|
||||
twoFactorAlertBlocked: 'Blocked because the time for setup has passed: {{count}}. Open the account in the user list and choose "Reopen setup".',
|
||||
twoFactorAlertLink: 'Open the user list',
|
||||
twoFactorAlertPending: 'Accounts without two-step verification: {{count}}. Until it is set up, such an account cannot use the panel.',
|
||||
@@ -29,8 +35,14 @@ export const securityTexts = defineTexts({
|
||||
twoFactorTooManyAttempts: 'Too many codes were tried for this account. Wait {{minutes}} min, then enter the current code from your app.',
|
||||
},
|
||||
pl: {
|
||||
currentPasswordDescription: 'Potrzebne tylko do zmiany własnego adresu e-mail lub hasła.',
|
||||
currentPasswordLabel: 'Obecne hasło',
|
||||
currentPasswordRequired: 'Wpisz obecne hasło, aby zmienić adres e-mail lub hasło.',
|
||||
currentPasswordWrong: 'Obecne hasło jest nieprawidłowe.',
|
||||
passwordIsEmail: 'Hasło nie może być takie samo jak adres e-mail.',
|
||||
passwordTooShort: 'Hasło musi mieć co najmniej {{min}} znaków.',
|
||||
signInBusy: 'Właśnie sprawdzamy inne logowanie na to konto z tego miejsca. Spróbuj ponownie za chwilę.',
|
||||
signInTooMany: 'Zbyt wiele nieudanych logowań na ten adres z tego miejsca. Spróbuj ponownie za {{minutes}} min.',
|
||||
twoFactorAlertBlocked: 'Zablokowane, bo minął czas na konfigurację: {{count}}. Otwórz konto na liście użytkowników i wybierz „Otwórz konfigurację ponownie”.',
|
||||
twoFactorAlertLink: 'Otwórz listę użytkowników',
|
||||
twoFactorAlertPending: 'Konta bez weryfikacji dwuetapowej: {{count}}. Dopóki nie zostanie ustawiona, takie konto nie może korzystać z panelu.',
|
||||
|
||||
@@ -25,7 +25,7 @@ export const RELAY_KV_KEY = 'iapl:mail-relay'
|
||||
|
||||
export const RELAY_DEFAULTS = {
|
||||
/** A visitor's lever: "forgot password" mail per address and per visitor in the window (accountMail option). */
|
||||
accountMail: { perAddress: 5, perVisitor: 10, windowMinutes: 60 },
|
||||
accountMail: { perAddress: 5, perAddressTotal: 20, perVisitor: 10, windowMinutes: 60 },
|
||||
/** Requests for one message, the same key and bytes each time. */
|
||||
attempts: 3,
|
||||
/** One attempt, from sending the request to the end of the answer. */
|
||||
|
||||
@@ -20,9 +20,11 @@ export type RelayOptions = {
|
||||
/**
|
||||
* "Forgot password" is a visitor's lever like a form: the service lets `account` mail use the site's
|
||||
* whole hour. So the plugin limits it itself, per address and per visitor (the request's address).
|
||||
* Default 5 per address and 10 per visitor an hour; `false` = no limit of the plugin's.
|
||||
* Default an hour: 5 to one address from one visitor (`perAddress`), 20 to one address from everybody
|
||||
* (`perAddressTotal`, 1.18.0 — before, 5 from anybody filled it for the owner too), 10 from one visitor;
|
||||
* `false` = no limit of the plugin's.
|
||||
*/
|
||||
accountMail?: { perAddress?: number; perVisitor?: number; windowMinutes?: number } | false
|
||||
accountMail?: { perAddress?: number; perAddressTotal?: number; perVisitor?: number; windowMinutes?: number } | false
|
||||
/** Calls to the public confirm route per address. Default 10 a minute. */
|
||||
confirmRateLimit?: { max?: number; windowMs?: number }
|
||||
/**
|
||||
|
||||
@@ -137,12 +137,21 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
const perAddress = own.perAddress ?? RELAY_DEFAULTS.accountMail.perAddress
|
||||
const checks = [
|
||||
...(marked?.visitor ? [{ key: `visitor:${marked.visitor}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
|
||||
...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].map((address) => ({ key: `to:${sha256Hex(address.toLowerCase())}`, max: perAddress })),
|
||||
// 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: to, max: own.perAddressTotal ?? RELAY_DEFAULTS.accountMail.perAddressTotal },
|
||||
]
|
||||
}),
|
||||
]
|
||||
for (const check of checks) {
|
||||
const { ok } = await consumeRateLimit({ ...check, scope: 'mail-relay-account', windowMs })
|
||||
const { ok } = await consumeRateLimit({ scope: 'mail-relay-account', ...check, windowMs })
|
||||
if (!ok) {
|
||||
payload.logger.warn(`[iapl] mail service: an account e-mail was held back (more than ${check.max} ${check.key.startsWith('visitor:') ? 'from one visitor' : 'to one address'} in the window; mail.relay.accountMail).`)
|
||||
payload.logger.warn(`[iapl] mail service: an account e-mail was held back (more than ${check.max} ${check.key.startsWith('visitor:') ? 'from one visitor' : 'scope' in check ? 'to one address from one visitor' : 'to one address'} in the window; mail.relay.accountMail).`)
|
||||
return failure('relay-quota', 'client-account-mail-limit', 'Too many account e-mails to one address or from one visitor; held back by the site (mail.relay.accountMail).')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,21 +89,29 @@ const MAX_REPORTED = 50
|
||||
* that origin. Without it a site behind a proxy that hides its address has a panel nobody can
|
||||
* enter and a silent log. Returns true when a line was written.
|
||||
*/
|
||||
export function reportRefusedOrigin(req: RequestLike, extra: string[] = []): boolean {
|
||||
/** What a refusal line names: the request, the option that allows an origin, and the doc section. Default: 2FA. */
|
||||
export type RefusalContext = { docs: string; option: string; what: string }
|
||||
const TWO_FACTOR_REFUSAL: RefusalContext = {
|
||||
docs: 'docs/security.md "Verify and setup attempts only from the site\'s own origin"',
|
||||
option: 'twoFactor: { sameOrigin',
|
||||
what: '2FA: a code',
|
||||
}
|
||||
|
||||
export function reportRefusedOrigin(req: RequestLike, extra: string[] = [], context: RefusalContext = TWO_FACTOR_REFUSAL): boolean {
|
||||
const origin = req.headers?.get('origin')
|
||||
const key = origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`
|
||||
const key = `${context.option}|${origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`}`
|
||||
if (reported.has(key) || reported.size >= MAX_REPORTED) {return false}
|
||||
reported.add(key)
|
||||
const { hosts, origins } = ownOrigins(req, extra)
|
||||
const known = [...origins, ...[...hosts].map((h) => `host ${h}`)].join(', ') || 'none'
|
||||
const how = originOf(origin)
|
||||
? `If "${originOf(origin)}" is this site's own address (a reverse proxy that rewrites Host and sends no X-Forwarded-Host), set serverURL to it in the Payload config, ` +
|
||||
`or pass twoFactor: { sameOrigin: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. `
|
||||
`or pass ${context.option}: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. `
|
||||
: 'The browser did not name an origin this site knows. '
|
||||
req.payload?.logger?.warn(
|
||||
`[iapl] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` +
|
||||
`[iapl] ${context.what} from ${origin ? `origin "${origin}"` : `a ${key.split('|')[1]} request`} was refused${context === TWO_FACTOR_REFUSAL ? ' and not counted' : ''} — it is not one of this site's own origins (${known}). ` +
|
||||
how +
|
||||
'If it is a foreign page, this is the protection working. twoFactor: { sameOrigin: false } turns the check off (docs/security.md "Verify and setup attempts only from the site\'s own origin"). Said once per origin.',
|
||||
`If it is a foreign page, this is the protection working. ${context.option}: false } turns the check off (${context.docs}). Said once per origin.`,
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -166,6 +166,28 @@ export async function consumeRateLimit({
|
||||
return { ok: bucket.count <= max, retryAfter }
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives back one place that `consumeRateLimit` took (`cost` 1) — for a limiter that counts only failures: it takes
|
||||
* a place before it compares (a burst cannot slip under the limit) and gives it back when the attempt was right.
|
||||
* Never below zero in memory; with a shared store, `hit(id, -cost)` (a store that cannot take a negative cost
|
||||
* simply keeps the place: fewer attempts, never more).
|
||||
*/
|
||||
export async function releaseRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope = 'form', windowMs = 60_000 }: CheckArgs): Promise<void> {
|
||||
const resolved = resolveKey(rawKey, rawMax)
|
||||
if (!resolved) {return}
|
||||
const id = `${scope}:${resolved.key}`
|
||||
if (store) {
|
||||
try {
|
||||
await store.hit(id, -cost, windowMs)
|
||||
} catch {
|
||||
// the place stays taken until the window ends
|
||||
}
|
||||
return
|
||||
}
|
||||
const bucket = buckets.get(id)
|
||||
if (bucket && bucket.resetAt > Date.now()) {bucket.count = Math.max(0, bucket.count - cost)}
|
||||
}
|
||||
|
||||
/** 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}`)
|
||||
|
||||
@@ -50,6 +50,28 @@ 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.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) {
|
||||
assertBooleanSwitch('accounts.confirmOwnChanges', accounts.confirmOwnChanges)
|
||||
assertSwitchOrObject('accounts.signInLimit', accounts.signInLimit, { allowTrue: false })
|
||||
const limit = bag(accounts.signInLimit)
|
||||
if (limit) {
|
||||
assertNumberSwitch('accounts.signInLimit.perAddress', limit.perAddress, { min: 1 })
|
||||
assertNumberSwitch('accounts.signInLimit.windowMinutes', limit.windowMinutes, { exclusive: true, min: 0 })
|
||||
assertSwitchOrObject('accounts.signInLimit.accountLock', limit.accountLock, { allowTrue: false })
|
||||
const lock = bag(limit.accountLock)
|
||||
if (lock) {
|
||||
assertNumberSwitch('accounts.signInLimit.accountLock.maxLoginAttempts', lock.maxLoginAttempts, { min: 1 })
|
||||
assertNumberSwitch('accounts.signInLimit.accountLock.lockTime', lock.lockTime, { exclusive: true, min: 0 })
|
||||
}
|
||||
}
|
||||
assertSwitchOrObject('accounts.signInSameOrigin', accounts.signInSameOrigin, { allowTrue: false })
|
||||
const same = bag(accounts.signInSameOrigin)
|
||||
if (same && same.origins !== undefined && !(Array.isArray(same.origins) && same.origins.every((o) => typeof o === 'string'))) {
|
||||
throw new Error(`${where('accounts.signInSameOrigin.origins')} must be a list of origins such as ['https://panel.example.com'] (received ${JSON.stringify(same.origins)}).`)
|
||||
}
|
||||
}
|
||||
|
||||
// Opt-in features that add public endpoints or outbound calls: `'false'` switched them ON.
|
||||
for (const name of ['cookieScanner', 'stats', 'consentLog', 'adminMeta', 'whiteLabel'] as const) {
|
||||
@@ -106,6 +128,7 @@ export function assertPluginSwitches(options: Record<string, unknown>): void {
|
||||
if (!limits) {throw new Error(`${where('mail.relay.accountMail')} must be false or an object (received ${JSON.stringify(accountMail)}).`)}
|
||||
assertNumberSwitch('mail.relay.accountMail.windowMinutes', limits.windowMinutes, { exclusive: true, min: 0 })
|
||||
assertNumberSwitch('mail.relay.accountMail.perAddress', limits.perAddress, { min: 1 })
|
||||
assertNumberSwitch('mail.relay.accountMail.perAddressTotal', limits.perAddressTotal, { min: 1 })
|
||||
assertNumberSwitch('mail.relay.accountMail.perVisitor', limits.perVisitor, { min: 1 })
|
||||
}
|
||||
const confirm = bag(relay.confirmRateLimit)
|
||||
|
||||
@@ -16,6 +16,7 @@ import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffC
|
||||
import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js'
|
||||
import { applyPasswordRule, buildPasswordRuleHook, resolvePasswordRule } from './modules/access/passwordRule.js'
|
||||
import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, markStaffRules, staffCollectionsNobodyManages, unknownStaffCollections } from './modules/access/selfRegistration.js'
|
||||
import { applySignInRules, settleFailedSignIn } from './modules/access/signInRules.js'
|
||||
import { ROLE_HIERARCHY } from './modules/access/types.js'
|
||||
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
|
||||
import { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
|
||||
@@ -258,6 +259,12 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
const panelSlug = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
|
||||
const staffSlugs = [...new Set([panelSlug, options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]
|
||||
config = applyStaffAccountAccess(config, staffSlugs, { ...accountAccess, pluginRoles: options.access?.authCollection ? [options.access.authCollection] : [] })
|
||||
// Sign-in rules of the staff collections: failures per IP + address, own origin, current password (1.18.0).
|
||||
config = {
|
||||
...config,
|
||||
collections: (config.collections ?? []).map((c) => (staffSlugs.includes(c.slug) ? applySignInRules(c, accounts) : c)),
|
||||
hooks: { ...config.hooks, afterError: [...(config.hooks?.afterError ?? []), settleFailedSignIn as never] },
|
||||
}
|
||||
}
|
||||
if (options.twoFactor !== false) {
|
||||
const tf = options.twoFactor
|
||||
|
||||
Reference in New Issue
Block a user