M1 review: account rules before 2FA, the SMTP password stays with its server, the rest of the findings
M1-1 the first-user route is the plugin's own endpoint in front of Payload's; nothing is read from the path.
M1-2 the account rules are put on the collections before the 2FA package wraps them.
M1-6 the admin rule only where the roles are the plugin's; other staff collections: an account of that collection.
update / delete get the matching defaults (accounts.adminOnlyWrite); doctor rule staff-accounts-open.
M1-5 access.firstUserAdmin: false with a role below the panel role: the default panel role steps aside, an explicit one is refused.
M1-3 a save that changes the SMTP server, port, user or encryption must send the password again (secrets.reenterOnChange);
new panel field smtpRequireTls.
M1-4 a restore of a version masks the secrets (maskSecretsOnRestore).
M1-7 a refused origin is logged once with the ways to allow it; default ports are normalised.
Minors: m1 day boundary, m3 e-mail check on reset and bulk update, m4 text of 'all', m5 the mask is never kept.
The account suite runs with 2FA off and on.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
81cee02e78
commit
1141c749de
@@ -51,23 +51,41 @@ export function buildPasswordRuleHook({ minLength = DEFAULT_PASSWORD_MIN_LENGTH
|
||||
if (operation !== 'create' && operation !== 'update' && operation !== 'resetPassword') {return args}
|
||||
const data = (args as { data?: { email?: unknown; password?: unknown } }).data
|
||||
const password = data?.password
|
||||
if (typeof password !== 'string' || password === '') {return args} // no password in this request: nothing is being set
|
||||
let email = typeof data?.email === 'string' ? data.email : null
|
||||
const id = (args as { id?: number | string }).id
|
||||
if (!email && operation === 'update' && id !== undefined && req?.payload) {
|
||||
try {
|
||||
const doc = (await req.payload.findByID({ id, collection: collection.slug as never, depth: 0, overrideAccess: true, req })) as { email?: unknown }
|
||||
email = typeof doc?.email === 'string' ? doc.email : null
|
||||
} catch {
|
||||
email = null
|
||||
}
|
||||
}
|
||||
const problem = checkPassword(password, { email, minLength })
|
||||
if (problem) {
|
||||
if (password === undefined || password === null || password === '') {return args} // no password in this request: nothing is being set
|
||||
const refuse = (problem: 'email' | 'short'): never => {
|
||||
const i18n = req?.i18n as Parameters<typeof serverText>[0]
|
||||
const message = problem === 'short' ? serverText(i18n, 'passwordTooShort', { min: minLength }) : serverText(i18n, 'passwordIsEmail')
|
||||
throw new ValidationError({ collection: collection.slug, errors: [{ message, path: 'password' }] }, req?.t)
|
||||
}
|
||||
// a number, a list, an object: not a password (it used to end in a server error further on)
|
||||
if (typeof password !== 'string') {return refuse('short')}
|
||||
// The address(es) the password must differ from: the one in the request, else the account(s)
|
||||
// the request is about — by id, by the reset token, or every account a bulk update matches.
|
||||
const emails: string[] = typeof data?.email === 'string' ? [data.email] : []
|
||||
if (!emails.length && req?.payload) {
|
||||
const { id, where } = args as { id?: number | string; where?: unknown }
|
||||
const token = (data as { token?: unknown }).token
|
||||
const query =
|
||||
operation === 'update' && id !== undefined
|
||||
? { id: { equals: id } }
|
||||
: operation === 'update' && where && typeof where === 'object'
|
||||
? where
|
||||
: operation === 'resetPassword' && typeof token === 'string' && token
|
||||
? { resetPasswordToken: { equals: token } }
|
||||
: null
|
||||
if (query) {
|
||||
try {
|
||||
const found = await req.payload.find({ collection: collection.slug as never, depth: 0, limit: 0, overrideAccess: true, pagination: false, req, where: query as never })
|
||||
for (const doc of found.docs as { email?: unknown }[]) {
|
||||
if (typeof doc?.email === 'string') {emails.push(doc.email)}
|
||||
}
|
||||
} catch {
|
||||
/* the account cannot be looked up: the length is still checked */
|
||||
}
|
||||
}
|
||||
}
|
||||
const problem = checkPassword(password, { minLength }) ?? (emails.some((email) => checkPassword(password, { email, minLength }) === 'email') ? 'email' : null)
|
||||
if (problem) {return refuse(problem)}
|
||||
return args
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,10 @@ export function buildRolesField(defaultRole: Role = 'user', { firstUserAdmin = t
|
||||
hooks: {
|
||||
beforeChange: [
|
||||
async ({ collection, operation, req, value }) => {
|
||||
if (operation !== 'create' || !collection || !req.pathname?.endsWith('/first-register')) {return value}
|
||||
// The first-user route: marked by the plugin's own endpoint (selfRegistration.ts); where that is off
|
||||
// (accounts.firstUserRoute: 'all'), by Payload's path, in any letter case — as Payload's router matches it.
|
||||
const first = req.context?.ipalFirstRegister === true || /\/first-register\/?$/i.test(req.pathname ?? '')
|
||||
if (operation !== 'create' || !collection || !first) {return value}
|
||||
const { totalDocs } = await req.payload.count({ collection: collection.slug, overrideAccess: true, req })
|
||||
return totalDocs === 0 ? ['admin'] : value
|
||||
},
|
||||
|
||||
@@ -1,91 +1,161 @@
|
||||
import type { Access, CollectionBeforeOperationHook, Config } from 'payload'
|
||||
import type { Access, CollectionConfig, Config, Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import { Forbidden } from 'payload'
|
||||
|
||||
import { userMeetsRole } from './predicates.js'
|
||||
import { secondFactorPassed } from '../security/totp/secondFactor.js'
|
||||
import { staffCollectionSlugs, userMeetsRole } from './predicates.js'
|
||||
import { ROLE_HIERARCHY } from './types.js'
|
||||
|
||||
/**
|
||||
* Nobody creates an account for themselves.
|
||||
* Nobody creates an account for themselves, and nobody takes one over.
|
||||
*
|
||||
* Two doors, both closed by default (`accounts.adminOnlyCreate`, `accounts.firstUserRoute`):
|
||||
* Payload's defaults for a collection without access rules are "any logged-in user" for
|
||||
* `create`, `update` and `delete` — an account of ANY auth collection. On a project's own
|
||||
* staff collection that let a visitor account (`customers`) create a staff account, or change
|
||||
* a staff account's password and roles. And Payload's first-user route
|
||||
* (`POST /api/<slug>/first-register`) answers for EVERY auth collection while it is empty —
|
||||
* on an empty second staff collection the first visitor became a staff account.
|
||||
*
|
||||
* 1. **`create` on a staff collection.** Payload's default for a collection without a `create`
|
||||
* rule is "any logged-in user". On a project's own staff collection that let every signed-in
|
||||
* account — the lowest role included — make accounts. Default now: an admin (a staff account
|
||||
* that passes `userMeetsRole(req, 'admin')`, the second factor included). A `create` rule the
|
||||
* project wrote stays.
|
||||
* Defaults now, for the staff collections (`accounts.adminOnlyCreate`, `accounts.adminOnlyWrite`,
|
||||
* `accounts.firstUserRoute`) — a rule the project wrote always stays:
|
||||
*
|
||||
* 2. **Payload's first-user route** (`POST /api/<slug>/first-register`) exists for EVERY auth
|
||||
* collection and answers while that collection is empty — also for one that allows no
|
||||
* sign-up, and for a second staff collection, whose first account would be staff. Default
|
||||
* now: only the collection the panel logs in with (the first account of a site, which
|
||||
* becomes admin). Another collection's route answers only when that collection's own
|
||||
* `create` rule lets an anonymous request through (it allows sign-up anyway).
|
||||
* - a collection whose roles are the plugin's (`roles` with user / editor / admin):
|
||||
* create — an admin; update — an admin, or the account itself; delete — an admin;
|
||||
* - a staff collection with other roles, or none (the plugin cannot tell who its admins
|
||||
* are): an account of that same collection, or a plugin admin of another staff
|
||||
* collection. A visitor account, and an editor of another staff collection, are refused;
|
||||
* - the first-user route answers only for the collection the panel logs in with, unless a
|
||||
* collection's own `create` rule lets an anonymous request through.
|
||||
*
|
||||
* A visitor collection that allows sign-up (`customers` with `create: () => true`) is not
|
||||
* touched by either.
|
||||
* Always "fully signed in": the second factor is part of every one of these rules. They are
|
||||
* put on the collections BEFORE the 2FA package runs, because that package gives every
|
||||
* collection a `create` / `update` / `delete` function of its own (Payload's default, wrapped)
|
||||
* — afterwards a missing rule can no longer be told from one the project wrote.
|
||||
*/
|
||||
|
||||
/** `create` for a staff collection: an admin, fully signed in. */
|
||||
type Staffish = Pick<CollectionConfig, 'fields' | 'slug'>
|
||||
|
||||
/** True when the collection carries the plugin's roles: a top-level `roles` select whose values are all the plugin's. */
|
||||
export function hasPluginRoles(collection: Staffish): boolean {
|
||||
const field = (collection.fields ?? []).find((f) => 'name' in f && f.name === 'roles') as { options?: unknown[]; type?: string } | undefined
|
||||
if (!field || field.type !== 'select' || !Array.isArray(field.options) || !field.options.length) {return false}
|
||||
return field.options.every((option) => ROLE_HIERARCHY.includes((typeof option === 'string' ? option : (option as { value?: unknown })?.value) as never))
|
||||
}
|
||||
|
||||
const collectionOf = (req: PayloadRequest): string | undefined => (req.user as { collection?: string } | null | undefined)?.collection
|
||||
|
||||
/** `create` / `delete` where the roles are the plugin's: an admin, fully signed in. */
|
||||
export const staffCreateAccess: Access = ({ req }) => userMeetsRole(req, 'admin')
|
||||
|
||||
/** Adds `staffCreateAccess` to the named collections where the project wrote no `create` rule. */
|
||||
export function applyAdminOnlyCreate(config: Config, staffSlugs: string[]): Config {
|
||||
/** `update` where the roles are the plugin's: an admin, or the account itself (fully signed in). */
|
||||
export const staffUpdateAccess =
|
||||
(slug: string): Access =>
|
||||
({ req }) => {
|
||||
if (userMeetsRole(req, 'admin')) {return true}
|
||||
if (!req.user || collectionOf(req) !== slug || !secondFactorPassed(req)) {return false}
|
||||
return { id: { equals: req.user.id } }
|
||||
}
|
||||
|
||||
/**
|
||||
* Any operation on a staff collection whose roles are NOT the plugin's: an account of that same
|
||||
* collection (the project's own roles decide the rest), or a plugin admin of another staff
|
||||
* collection. Never an account of a collection that is not staff.
|
||||
*/
|
||||
export const sameStaffCollectionAccess =
|
||||
(slug: string): Access =>
|
||||
({ req }) => {
|
||||
if (!req.user || !secondFactorPassed(req)) {return false}
|
||||
const from = collectionOf(req)
|
||||
if (from === slug) {return staffCollectionSlugs(req.payload).includes(slug)}
|
||||
return userMeetsRole(req, 'admin')
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the defaults on the named staff collections where the project wrote no rule.
|
||||
* `pluginRoles`: slugs that will carry the plugin's roles although the field is not there yet
|
||||
* (`access.authCollection`, whose field is injected later).
|
||||
*/
|
||||
export function applyStaffAccountAccess(config: Config, staffSlugs: string[], { create = true, pluginRoles = [], write = true }: { create?: boolean; pluginRoles?: string[]; write?: boolean } = {}): Config {
|
||||
if (!create && !write) {return config}
|
||||
return {
|
||||
...config,
|
||||
collections: (config.collections ?? []).map((collection) =>
|
||||
collection.auth && staffSlugs.includes(collection.slug) && !collection.access?.create ? { ...collection, access: { ...collection.access, create: staffCreateAccess } } : collection,
|
||||
),
|
||||
collections: (config.collections ?? []).map((collection) => {
|
||||
if (!collection.auth || !staffSlugs.includes(collection.slug)) {return collection}
|
||||
const ours = pluginRoles.includes(collection.slug) || hasPluginRoles(collection)
|
||||
const other = sameStaffCollectionAccess(collection.slug)
|
||||
const access = { ...collection.access }
|
||||
if (create && !access.create) {access.create = ours ? staffCreateAccess : other}
|
||||
if (write && !access.update) {access.update = ours ? staffUpdateAccess(collection.slug) : other}
|
||||
if (write && !access.delete) {access.delete = ours ? staffCreateAccess : other}
|
||||
return { ...collection, access }
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/** `accounts.firstUserRoute`: `'panel'` (default) = the panel's login collection only; slugs = those; `'all'` = Payload's behaviour. */
|
||||
export type FirstUserRouteOption = 'all' | 'panel' | string[]
|
||||
|
||||
const FIRST_REGISTER = /\/first-register\/?$/
|
||||
const FIRST_REGISTER = '/first-register'
|
||||
|
||||
/**
|
||||
* `beforeOperation` hook for an auth collection: refuses the first-user route unless the
|
||||
* collection is allowed (see above). Not involved in any other create.
|
||||
* The plugin's own `POST /first-register` for a collection. It is put in front of Payload's
|
||||
* (a collection's own endpoints are matched before the built-in ones, with the same matcher —
|
||||
* so whatever spelling reaches Payload's route reaches this one first): refuses unless the
|
||||
* collection is allowed, then hands the request to Payload's handler. Nothing is decided
|
||||
* from the request's path.
|
||||
*/
|
||||
export function buildFirstUserGuard(option: FirstUserRouteOption = 'panel'): CollectionBeforeOperationHook {
|
||||
return async ({ args, collection, operation, req }) => {
|
||||
if (operation !== 'create' || !req?.pathname || !FIRST_REGISTER.test(req.pathname)) {return args}
|
||||
const slug = collection.slug
|
||||
const allowed = Array.isArray(option) ? option.includes(slug) : slug === req.payload.config.admin?.user
|
||||
if (allowed) {return args}
|
||||
// a collection that lets a visitor sign up anyway may keep its first-user route
|
||||
let open = false
|
||||
try {
|
||||
open = Boolean(await collection.access?.create?.({ data: (args as { data?: unknown }).data, req: { ...req, user: null } } as never))
|
||||
} catch {
|
||||
open = false
|
||||
}
|
||||
if (!open) {throw new Forbidden(req.t)}
|
||||
return args
|
||||
export function buildFirstUserEndpoint(option: FirstUserRouteOption = 'panel'): Endpoint {
|
||||
const endpoint: Endpoint = {
|
||||
custom: { ipalFirstUser: true },
|
||||
handler: async (req) => {
|
||||
const slug = (req.routeParams as { collection?: string } | undefined)?.collection
|
||||
const collection = slug ? req.payload.collections[slug as never] : undefined
|
||||
const refused = () => Response.json({ errors: [{ message: req.t('error:notAllowedToPerformAction' as never) }] }, { status: 403 })
|
||||
if (!slug || !collection) {return refused()}
|
||||
let allowed = Array.isArray(option) ? option.includes(slug) : slug === req.payload.config.admin?.user
|
||||
if (!allowed) {
|
||||
// a collection that lets a visitor sign up anyway may keep its first-user route
|
||||
try {
|
||||
allowed = Boolean(await collection.config.access?.create?.({ data: req.data, req: { ...req, user: null } } as never))
|
||||
} catch {
|
||||
allowed = false
|
||||
}
|
||||
}
|
||||
if (!allowed) {return refused()}
|
||||
// Payload's own handler: the built-in endpoint of this collection with the same path and method.
|
||||
const builtIn = (collection.config.endpoints || []).find((e) => e !== endpoint && e.method === 'post' && e.path === FIRST_REGISTER && !(e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)
|
||||
if (!builtIn) {return refused()}
|
||||
// for hooks that need to know (the roles field makes the first account an admin)
|
||||
req.context = { ...req.context, ipalFirstRegister: true }
|
||||
return builtIn.handler(req)
|
||||
},
|
||||
method: 'post',
|
||||
path: FIRST_REGISTER,
|
||||
}
|
||||
return endpoint
|
||||
}
|
||||
|
||||
/** Adds the guard to every auth collection (it lets the allowed ones through itself). `'all'` adds nothing. */
|
||||
/** Puts the first-user endpoint in front of Payload's on every auth collection. `'all'` adds nothing. */
|
||||
export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption = 'panel'): Config {
|
||||
if (option === 'all') {return config}
|
||||
if (option !== 'panel' && !Array.isArray(option)) {
|
||||
throw new Error(`[ipal] accounts.firstUserRoute must be 'panel', 'all' or a list of collection slugs, got ${JSON.stringify(option)}.`)
|
||||
}
|
||||
const guard = buildFirstUserGuard(option)
|
||||
return {
|
||||
...config,
|
||||
collections: (config.collections ?? []).map((collection) =>
|
||||
collection.auth ? { ...collection, hooks: { ...collection.hooks, beforeOperation: [guard, ...(collection.hooks?.beforeOperation ?? [])] } } : collection,
|
||||
),
|
||||
collections: (config.collections ?? []).map((collection) => {
|
||||
if (!collection.auth || collection.endpoints === false) {return collection}
|
||||
const own = (collection.endpoints ?? []).filter((e) => !(e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)
|
||||
return { ...collection, endpoints: [buildFirstUserEndpoint(option), ...own] }
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
type LivePayload = { collections: Record<string, { config: { access?: { create?: Access; delete?: Access; update?: Access }; auth?: unknown; slug: string } }>; config?: unknown }
|
||||
|
||||
/**
|
||||
* Auth collections whose `create` rule lets an anonymous request through — open sign-up.
|
||||
* For the doctor (slugs only). A rule that throws, or needs more than `{ req }`, counts as closed.
|
||||
*/
|
||||
export async function openSignUpCollections(payload: { collections: Record<string, { config: { access?: { create?: Access }; auth?: unknown; slug: string } }> }): Promise<string[]> {
|
||||
export async function openSignUpCollections(payload: LivePayload): Promise<string[]> {
|
||||
const open: string[] = []
|
||||
for (const { config } of Object.values(payload.collections ?? {})) {
|
||||
if (!config.auth) {continue}
|
||||
@@ -97,3 +167,27 @@ export async function openSignUpCollections(payload: { collections: Record<strin
|
||||
}
|
||||
return open.sort()
|
||||
}
|
||||
|
||||
/**
|
||||
* Staff collections that an account of ANOTHER, non-staff auth collection may create in,
|
||||
* update or delete from — `'users:update'`. For the doctor. Asked with a made-up account of a
|
||||
* collection that is not staff; a rule that throws counts as closed.
|
||||
*/
|
||||
export async function staffCollectionsOpenToOthers(payload: LivePayload): Promise<string[]> {
|
||||
const staff = staffCollectionSlugs(payload as never)
|
||||
const outsider = { id: '__ipal-outsider__', collection: '__ipal-outsider__' }
|
||||
const open: string[] = []
|
||||
for (const { config } of Object.values(payload.collections ?? {})) {
|
||||
if (!config.auth || !staff.includes(config.slug)) {continue}
|
||||
for (const operation of ['create', 'update', 'delete'] as const) {
|
||||
try {
|
||||
const rule = config.access?.[operation]
|
||||
// no rule = Payload's default: any logged-in user
|
||||
if (!rule || (await rule({ id: '__ipal-other__', req: { payload, user: outsider } } as never))) {open.push(`${config.slug}:${operation}`)}
|
||||
} catch {
|
||||
/* closed */
|
||||
}
|
||||
}
|
||||
}
|
||||
return open.sort()
|
||||
}
|
||||
|
||||
@@ -19,10 +19,23 @@ export type AccountsOptions = {
|
||||
* Only an admin creates accounts in a staff collection (the one the panel
|
||||
* logs in with, `access.authCollection`, `access.staffCollections`) — also
|
||||
* in the project's own collection, where Payload's default would let any
|
||||
* logged-in account do it. A `create` rule the project wrote stays.
|
||||
* `false` = Payload's default on collections without a rule, as before.
|
||||
* logged-in account do it. Where the collection's roles are not the
|
||||
* plugin's (role values of its own, or no `roles` field) the plugin cannot
|
||||
* tell who is an admin there: an account of that same collection, or a
|
||||
* plugin admin of another staff collection. A `create` rule the project
|
||||
* wrote stays. `false` = Payload's default on collections without a rule.
|
||||
*/
|
||||
adminOnlyCreate?: false
|
||||
/**
|
||||
* The same for `update` and `delete` on a staff collection without those
|
||||
* rules: an admin, or — `update` only — the account itself. Payload's
|
||||
* default ("any logged-in user") let an account of ANOTHER auth collection
|
||||
* (a `customers` visitor) change a staff account's password. On a staff
|
||||
* collection whose roles are not the plugin's: an account of that same
|
||||
* collection, or a plugin admin. A rule the project wrote stays.
|
||||
* `false` = Payload's default on collections without a rule, as before.
|
||||
*/
|
||||
adminOnlyWrite?: false
|
||||
/**
|
||||
* Which auth collections Payload's first-user route
|
||||
* (`POST /api/<slug>/first-register`) answers for while they are empty.
|
||||
|
||||
Reference in New Issue
Block a user