Copied staff collections: the plugin's rule goes in front, nothing is replaced (a rule that cannot widen)

A plugin listed after ipalKit that copies a staff collection under a new slug, or reuses its access object, brings
rules the plugin wrote for the ORIGINAL. On 1.16.7 the copy also carried the boolean 'seen' marker and was left
alone: 'the account itself' then meant an account of the original — with numeric ids the original's account with
the same id changed the copy's account (17 of 40 measured shapes).
Design: the plugin never replaces and never rewrites a rule on such a collection. It puts its rule for the copy's
own slug in front, and both must allow: on a copy named as staff in front of every rule; on a copy that is not
staff or keeps its own rules (custom.ipal.accountRules: false) in front of the rules marked as the plugin's for
another collection. The roles field of every copy is guarded. The mark on the plugin's functions says only
{ slug, self }; custom.ipalAccounts says { slug, staff } (a collection named as staff during next dev is handled
on the reload). The plugin's rules are marked before its 2FA guard, which carries the mark.
Accepted cost: a copy's own account cannot edit itself through a copied rule (as on 1.16.7); the copy writes
access.update — one documented line.
Proof: test/accountCopyTableSuite.ts — 40 shapes x accounts x operations, each row not wider than the measurement
taken on 1.16.7 (test/fixtures/copyRulesBaseline.json) and not wider than the plugin's rule; 2FA off and on.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 03:48:09 +01:00
co-authored by Claude Fable 5.2
parent 4c7b722aed
commit 8dcc123b99
14 changed files with 2745 additions and 62 deletions
+31 -2
View File
@@ -10,7 +10,7 @@ import type { Config, Plugin } from 'payload'
export const E2E_LATE_STAFF = process.env.E2E_LATE_STAFF === '1'
/** Slugs the fixture names as staff (payload.config.ts → `access.staffCollections`). */
export const E2E_STAFF_SLUGS = ['late-staff', 'e2e-crew', 'e2e-late-text']
export const E2E_STAFF_SLUGS = ['late-staff', 'e2e-crew', 'e2e-late-text', 'e2e-staff', 'e2e-team', 'e2e-copy', 'e2e-copy-own-rules', 'e2e-copy-cross-op', 'e2e-copy-values', 'e2e-copy-team-admin', 'e2e-copy-opt-out']
/**
* Listed BEFORE ipalKit: a staff collection of the project's own, without rules, whose roles are the plugin's values
@@ -18,15 +18,44 @@ export const E2E_STAFF_SLUGS = ['late-staff', 'e2e-crew', 'e2e-late-text']
*/
export const e2eEarlyStaff: Plugin = (config: Config) =>
E2E_LATE_STAFF
? { ...config, collections: [...(config.collections ?? []), { slug: 'e2e-crew', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin', 'boss'], saveToJWT: true }] }] }
? {
...config,
collections: [
...(config.collections ?? []),
{ slug: 'e2e-crew', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin', 'boss'], saveToJWT: true }] },
// the two originals the later plugin copies: the plugin's roles, and roles of the project's own
{ slug: 'e2e-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }] },
{ slug: 'e2e-team', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['lead', 'member'], saveToJWT: true }] },
],
}
: config
/**
* Copies of staff collections under new slugs — the shapes in which a rule could become WIDER when the plugin
* rewrote copied rules. It never replaces a rule now: its rule for the copy's slug goes in front of what came along.
*/
const copies = (config: Config): NonNullable<Config['collections']> => {
const of = (slug: string) => (config.collections ?? []).find((c) => c.slug === slug)!
const staff = of('e2e-staff')
const roles = (options: string[]) => [{ name: 'roles', type: 'select' as const, hasMany: true as const, options, saveToJWT: true }]
return [
{ ...staff, slug: 'e2e-copy' }, // plain: the original's namesake is not "the account itself" here
{ ...staff, slug: 'e2e-copy-own-rules', access: { ...staff.access, create: () => false, delete: () => false, read: () => false, update: () => false } }, // "nobody" stays "nobody"
{ ...staff, slug: 'e2e-copy-cross-op', access: { ...staff.access, read: staff.access?.create, update: staff.access?.create } }, // the admin-only create rule used for read and update
{ ...staff, slug: 'e2e-copy-values', fields: roles(['user', 'editor', 'admin', 'boss']) }, // one more role value
{ ...of('e2e-team'), slug: 'e2e-copy-team-admin', fields: roles(['user', 'editor', 'admin']) }, // "an account of the collection" copied onto a collection with `admin`
{ ...staff, slug: 'e2e-copy-opt-out', custom: { ...staff.custom, ipal: { accountRules: false } }, fields: roles(['user', 'editor', 'admin']) }, // keeps its own rules, brings its own roles field
{ ...staff, slug: 'e2e-copy-not-staff' }, // not named as a staff collection
]
}
export const e2eLateStaff: Plugin = (config: Config) =>
E2E_LATE_STAFF
? {
...config,
collections: [
...(config.collections ?? []),
...copies(config),
// no access rules at all: Payload's defaults ("any logged-in user") are what ipalKit must replace
{ slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true },
// a late staff collection whose `roles` is a text field: any value can be written there, `admin` included
+39
View File
@@ -96,6 +96,45 @@ test.describe('a late staff collection on a built site', () => {
await api.dispose()
}
// Copies of staff collections (e2e/late-staff-fixture.ts → copies): the lowest account of each copy, and an account
// of the ORIGINAL with the role `user`, get nothing that a plugin rule or the copy's own rule refuses — whatever
// role values the copy has and wherever it uses a copied rule. (Each of these shapes was open in some version that
// REWROTE copied rules; the plugin now only ever puts its rule in front.)
const original = await admin.post('/api/e2e-staff', { data: { email: `o-${tag}@staff.example.com`, password: PASSWORD, roles: ['user'] } })
expect(original.status()).toBe(201)
const fromOriginal = await context(playwright, baseURL!)
expect((await fromOriginal.post('/api/e2e-staff/login', { data: { email: `o-${tag}@staff.example.com`, password: PASSWORD } })).status()).toBe(200)
for (const slug of ['e2e-copy', 'e2e-copy-cross-op', 'e2e-copy-values', 'e2e-copy-team-admin', 'e2e-copy-opt-out', 'e2e-copy-not-staff']) {
const top = await admin.post(`/api/${slug}`, { data: { email: `a-${tag}@${slug}.example.com`, password: PASSWORD, roles: ['admin'] } })
const lowest = await admin.post(`/api/${slug}`, { data: { email: `u-${tag}@${slug}.example.com`, password: PASSWORD, roles: ['user'] } })
expect([slug, top.status(), lowest.status()]).toEqual([slug, 201, 201])
const topId = (await top.json()).doc.id as string
const lowestId = (await lowest.json()).doc.id as string
const own = await context(playwright, baseURL!)
expect((await own.post(`/api/${slug}/login`, { data: { email: `u-${tag}@${slug}.example.com`, password: PASSWORD } })).status()).toBe(200)
for (const [who, api] of [['its own lowest account', own], ['an account of the original', fromOriginal], ['a visitor', visitor]] as [string, APIRequestContext][]) {
expect([slug, who, {
create: (await api.post(`/api/${slug}`, { data: { email: `made-${tag}-${who.length}@${slug}.example.com`, password: PASSWORD, roles: ['admin'] } })).status(),
integrations: (await api.get('/api/globals/site-integrations')).status(),
patchLowest: who === 'its own lowest account' ? 'itself' : (await api.patch(`/api/${slug}/${lowestId}`, { data: { password: `taken-${PASSWORD}` } })).status(),
patchTop: (await api.patch(`/api/${slug}/${topId}`, { data: { password: `taken-${PASSWORD}` } })).status(),
zDelete: (await api.delete(`/api/${slug}/${topId}`)).status(),
}]).toEqual([slug, who, { create: 403, integrations: 403, patchLowest: who === 'its own lowest account' ? 'itself' : 403, patchTop: 403, zDelete: 403 }])
}
await own.patch(`/api/${slug}/${lowestId}`, { data: { roles: ['admin'] } })
expect((await (await admin.get(`/api/${slug}/${lowestId}`)).json()).roles, `${slug}: its own roles`).toEqual(['user'])
for (const id of [topId, lowestId]) {expect((await admin.delete(`/api/${slug}/${id}`)).status(), `${slug}: an admin cleans up`).toBe(200)}
await own.dispose()
}
// a copy with rules of its own ("nobody"): an admin is refused too — the plugin's rule went in front, it replaced nothing
expect((await admin.post('/api/e2e-copy-own-rules', { data: { email: `x-${tag}@own.example.com`, password: PASSWORD, roles: ['admin'] } })).status(), 'own rules: create').toBe(403)
expect((await admin.get('/api/e2e-copy-own-rules')).status(), 'own rules: read').toBe(403)
// the cross-op copy: read is "an admin" there (the create rule), also for the copy's own accounts — checked above through
// create / patch; and the list itself:
expect((await fromOriginal.get('/api/e2e-copy-cross-op')).status()).toBe(403)
expect((await admin.get('/api/e2e-copy-cross-op')).status()).toBe(200)
await fromOriginal.dispose()
// an admin: everything, and it cleans up
expect((await admin.get('/api/late-staff/versions')).status()).toBe(200)
expect((await admin.post('/api/late-staff/unlock', { data: { email: `low-${tag}@example.com` } })).status()).toBe(200)
+3 -1
View File
@@ -24,6 +24,8 @@ export {
export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, resolvePanelRole } from './modules/access/panelRole.js'
export { applyPasswordRule, buildPasswordRuleHook, checkPassword, DEFAULT_PASSWORD_MIN_LENGTH, resolvePasswordRule } from './modules/access/passwordRule.js'
export type { PasswordRuleOptions } from './modules/access/passwordRule.js'
export { isPasswordRuleHook, staffRuleOf } from './modules/access/ruleMark.js'
export type { StaffRuleMark } from './modules/access/ruleMark.js'
export {
adoptLateAuthCollections,
applyFirstUserRoute,
@@ -45,7 +47,7 @@ export {
staffUpdateAccess,
unknownStaffCollections,
} from './modules/access/selfRegistration.js'
export type { LateAdoption, StaffAccountAccessOptions, StaffAccountRules } 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 type { AccountsOptions } from './modules/access/types.js'
// Concrete files, not module barrels: a barrel that also re-exports 'use client'
+4 -1
View File
@@ -3,6 +3,7 @@ import type { CollectionBeforeOperationHook, Config } from 'payload'
import { ValidationError } from 'payload'
import { serverText } from '../integrations/texts.js'
import { markPasswordRule } from './ruleMark.js'
/**
* A password rule for staff accounts.
@@ -47,7 +48,7 @@ export function checkPassword(password: string, { email, minLength = DEFAULT_PAS
* (`create`, `update`, `resetPassword`). Login, refresh and every other operation pass untouched.
*/
export function buildPasswordRuleHook({ minLength = DEFAULT_PASSWORD_MIN_LENGTH }: PasswordRuleOptions = {}): CollectionBeforeOperationHook {
return async ({ args, collection, operation, req }) => {
const hook: CollectionBeforeOperationHook = async ({ args, collection, operation, req }) => {
if (operation !== 'create' && operation !== 'update' && operation !== 'resetPassword') {return args}
const data = (args as { data?: { email?: unknown; password?: unknown } }).data
const password = data?.password
@@ -88,6 +89,8 @@ export function buildPasswordRuleHook({ minLength = DEFAULT_PASSWORD_MIN_LENGTH
if (problem) {return refuse(problem)}
return args
}
// marked on the function itself: a copied collection brings the hook along, and it is not put there twice
return markPasswordRule(hook)
}
/** Adds the rule to the named auth collections that log in with a password. */
+72
View File
@@ -0,0 +1,72 @@
/**
* The plugin's mark on an access function it put on a staff collection: "this is the plugin's
* rule, written for the collection `slug`".
*
* A later plugin may copy a collection (`{ ...staff, slug: 'copy' }`) or reuse its access object:
* the functions travel along, and a rule written for the original — "an account of `staff`",
* "the account itself" = one of the original's — then sits on a collection it does not speak of.
* The mark lets the plugin see that. It is on the function itself, so it:
* - travels with every copy (it is the same function object);
* - is on the function that ends up on the collection (set after the 2FA package wrapped the
* rule; ipal-kit's own 2FA guard gets a mark of its own for its wrapper);
* - is the same for every instance of this module (`Symbol.for`): after a `next dev` reload the
* config was built by one instance and is adopted by another.
* It counts only on the very function it was made for (`self`): a Proxy around a marked rule, a
* function with the rule as its prototype, a function that got the rule's property descriptors
* copied answer with the same property but are somebody's own rule.
*
* What the plugin DOES with a rule marked for another collection: it never replaces it. It puts
* its rule for this collection in front, and both must allow (selfRegistration.ts). So the mark
* says nothing about what the rule is — no operation, no kind: nothing is decided from it but
* "this rule speaks of another collection".
*/
const STAFF_RULE = Symbol.for('ipal.staffRule')
const PASSWORD_RULE = Symbol.for('ipal.passwordRule')
export type StaffRuleMark = {
/** The function the mark was made for. */
self: unknown
/** The collection the rule was written for. */
slug: string
}
type Marked = { [PASSWORD_RULE]?: { self: unknown }; [STAFF_RULE]?: StaffRuleMark }
const settable = (value: unknown): value is Marked => typeof value === 'function' && Object.isExtensible(value)
const setMark = (rule: Marked, slug: string): void => {
Object.defineProperty(rule, STAFF_RULE, { configurable: true, value: { slug, self: rule } satisfies StaffRuleMark })
}
/**
* A NEW function that does what `rule` does and carries the mark. Always a new one: the plugin's
* exported rules are shared (`adminOnly`), and a mark on a shared function would follow it into
* collections where the project itself used it. Not exported from the package.
*/
export function markedStaffRule<T extends (...args: never[]) => unknown>(rule: T, slug: string): T {
const marked = ((...args: never[]) => rule(...args)) as unknown as Marked & T
setMark(marked, slug)
return marked
}
/**
* The plugin's mark on a function, or undefined: then it is not a rule the plugin put there.
* Only a mark that is the function's OWN property and was made for this very function counts.
*/
export const staffRuleOf = (rule: unknown): StaffRuleMark | undefined => {
if (typeof rule !== 'function' || !Object.hasOwn(rule, STAFF_RULE)) {return undefined}
const mark = (rule as Marked)[STAFF_RULE]
return mark && typeof mark === 'object' && typeof mark.slug === 'string' && mark.self === rule ? mark : undefined
}
/** For a wrapper the PLUGIN puts around an access function (its 2FA guard): the wrapper answers for the same rule and gets a mark of its own. */
export function carryStaffRule(from: unknown, to: unknown): void {
const mark = staffRuleOf(from)
if (mark && settable(to)) {setMark(to, mark.slug)}
}
/** Marks a `beforeOperation` hook as the plugin's password rule (so it is not put on a collection twice). */
export function markPasswordRule<T>(hook: T): T {
if (settable(hook)) {Object.defineProperty(hook, PASSWORD_RULE, { configurable: true, value: { self: hook } })}
return hook
}
/** True for a hook made by `buildPasswordRuleHook` — in any instance of the module; only the hook itself, not a wrapper around it. */
export const isPasswordRuleHook = (hook: unknown): boolean => typeof hook === 'function' && Object.hasOwn(hook, PASSWORD_RULE) && (hook as Marked)[PASSWORD_RULE]?.self === hook
+167 -45
View File
@@ -2,6 +2,7 @@ import type { Access, CollectionConfig, Config, Endpoint, PayloadRequest } from
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { staffCollectionSlugs, userMeetsRole } from './predicates.js'
import { isPasswordRuleHook, markedStaffRule, staffRuleOf } from './ruleMark.js'
import { ROLE_HIERARCHY } from './types.js'
/**
@@ -152,8 +153,23 @@ export function canHoldStaffRole(collection: Staffish): boolean {
return values === null || values.some((value) => value === 'editor' || value === 'admin')
}
/** What the plugin put on a staff collection (`custom.ipalAccountRules`) — for the doctor and for late collections. */
export type StaffAccountRules = { applied: string[]; ownRoles: boolean }
/**
* What the plugin put on a collection (`custom.ipalAccountRules`) — for the doctor and the log. `slug`: the
* collection the record was written for (a copy of the collection carries the original's record along).
*/
export type StaffAccountRules = { applied: string[]; ownRoles: boolean; slug?: string }
/**
* The "seen" marker (`custom.ipalAccounts`): which collection ipalKit handled, and whether as a staff
* collection. Not a plain `true`: a later plugin may spread a collection into a new slug
* (`{ ...staff, slug: 'copy' }`) and the marker travels with it; and in `next dev` a collection object can
* outlive a reload in which it became staff.
*/
export type AccountsMarker = { slug: string; staff: boolean }
const markerOf = (collection: { custom?: unknown }): AccountsMarker | undefined => {
const marker = (collection.custom as { ipalAccounts?: unknown } | undefined)?.ipalAccounts
return marker && typeof marker === 'object' && typeof (marker as AccountsMarker).slug === 'string' ? (marker as AccountsMarker) : undefined
}
/**
* BOTH rules must allow: the plugin's and the one the collection already has. For a collection
@@ -188,50 +204,116 @@ export type StaffAccountAccessOptions = {
write?: boolean
}
/** Field access: both must allow (a `roles` field's own rule and the plugin's guard). */
const bothAllowField =
(first: (args: never) => unknown, second: unknown) =>
async (args: never): Promise<boolean> =>
Boolean(await first(args)) && (typeof second !== 'function' || Boolean(await (second as (a: never) => unknown)(args)))
/**
* Puts the defaults on ONE staff collection, in place: the operations without a rule, and the
* `roles` field when the plugin's `update` rule is the one in force. Returns what it applied.
* `late`: the collection's config is already sanitized (see `bothAllow`) — the plugin's rule is
* combined with whatever is there instead of only filling gaps.
* Puts the plugin's rules on ONE collection, in place, and returns what it put.
*
* **A rule that cannot widen.** The plugin fills an operation that has NO rule (config time), or puts its rule
* in FRONT of the rule that is there, so that both must allow (`bothAllow`). It never replaces a rule and never
* rewrites one. Whatever is on the collection — the project's rule, Payload's default, a rule the plugin wrote for
* ANOTHER collection that a copy brought along — still has to allow. So the result is never wider than what was
* there and never wider than the plugin's rule for this collection, whatever role values, operations or wrappers
* are involved.
*
* `mode`:
* - `'config'` (ipalKit is running, nothing is sanitized): an operation without a rule gets the plugin's;
* - `'late'` (a staff collection a later plugin added; the config is sanitized, so Payload's default cannot be
* told from a written rule): the plugin's rule in front of every rule;
* - `'copied'` (a late collection that is not staff, or that keeps its own rules — `custom.ipal.accountRules:
* false`): the plugin's rule goes in front ONLY of a rule the plugin wrote for another collection (its mark,
* ruleMark.ts). Such a rule says "an account of the original", "the account itself" = one of the original's;
* with this collection's rule in front, the original's namesake with the same id is not "itself" here.
* Accepted cost: where a copied rule says "itself" for the ORIGINAL's accounts, the copy's own account cannot
* edit itself (as before this change) — the copying plugin writes the copy's `access.update`.
*/
function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions, late = false): StaffAccountRules {
function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions, mode: 'config' | 'copied' | 'late' = 'config'): StaffAccountRules {
const slug = collection.slug
// the admin rules: where the roles are the plugin's, and wherever an account can hold `editor` or `admin` (canHoldStaffRole)
const ours = pluginRoles.includes(slug) || hasPluginRoles(collection) || canHoldStaffRole(collection)
const other = sameStaffCollectionAccess(slug)
const access = (collection.access ?? {}) as Record<string, unknown>
const applied: string[] = []
const put = (operation: string, rule: Access) => {
if (late) {access[operation] = bothAllow(rule, access[operation])}
else if (!access[operation]) {access[operation] = rule}
else {return} // a rule the project wrote
applied.push(operation)
}
if (create) {put('create', ours ? staffCreateAccess : other)}
if (write) {
put('update', ours ? staffUpdateAccess(slug) : other)
put('delete', ours ? staffCreateAccess : other)
put('unlock', ours ? staffCreateAccess : other)
}
if (read) {
put('read', staffReadAccess)
// a new object: a copied collection shares the original's
const access = { ...collection.access } as Record<string, unknown>
const before = (collection.custom as { ipalAccountRules?: StaffAccountRules } | undefined)?.ipalAccountRules
// what the plugin put there earlier for THIS slug (the injected collection's own rules, plugin.ts)
const applied: string[] = before?.slug === slug ? [...before.applied] : []
// The plugin's rule for each operation of THIS collection, and whether that default is switched on.
const rules: [operation: string, rule: Access, enabled: boolean][] = [
['create', ours ? staffCreateAccess : other, create],
['update', ours ? staffUpdateAccess(slug) : other, write],
['delete', ours ? staffCreateAccess : other, write],
['unlock', ours ? staffCreateAccess : other, write],
['read', staffReadAccess, read],
// versions of an account hold what the account holds (e-mail addresses, roles)
put('readVersions', staffReadAccess)
['readVersions', staffReadAccess, read],
]
/** A rule of ANOTHER collection is on this one: it is a copy, or it reuses another collection's access. */
let copied = Boolean(before?.slug && before.slug !== slug) || Boolean(markerOf(collection) && markerOf(collection)?.slug !== slug)
for (const [operation, rule, enabled] of rules) {
const there = access[operation]
// A mark — for another collection, or one that claims this one — only ever ADDS the plugin's rule in front; a
// function is never left alone because of what its mark says (whether a collection was handled is the marker's
// business, not the function's).
const mark = staffRuleOf(there)
if (mark && mark.slug !== slug) {copied = true}
if (mode === 'config') {
if (there || !enabled) {continue} // a rule the project wrote
access[operation] = rule // marked when ipalKit finishes (markStaffRules): the 2FA package wraps it first
} else if ((mode === 'late' && enabled) || mark) {
access[operation] = markedStaffRule(bothAllow(rule, there), slug)
} else {continue}
if (!applied.includes(operation)) {applied.push(operation)}
}
collection.access = access as CollectionConfig['access']
// The plugin's `update` rule lets an account change itself (or, with roles of its own, every account of
// the collection change every other): a `roles` field without access of its own would let it raise itself.
const roles = findRolesField(collection.fields as FieldLike[])
if (applied.includes('update')) {
if (roles && !roles.access?.update) {
roles.access = { ...roles.access, update: ours ? rolesByAdminOnly : rolesNotOwn(slug) }
applied.push('roles')
// The `roles` field. An account that may update itself would raise itself through a `roles` field without access of
// its own. The guard (the plugin's roles: only an admin changes them; others: never one's own) is put:
// - config: where the plugin's `update` rule is the one in force (it says "the account itself");
// - late: on every staff collection the plugin rules;
// - on every COPY, whatever the mode — also one that keeps its own rules and one that is not staff: its field came
// without a rule of its own, and its accounts must not write their own roles because the original's could not.
// A rule the field has is kept: the guard goes in front of it only when it is the plugin's rule for another collection.
let roles = findRolesField(collection.fields as FieldLike[])
if (roles) {
const guard = (ours ? rolesByAdminOnly : rolesNotOwn(slug)) as (args: never) => unknown
const there = roles.access?.update
const fieldMark = staffRuleOf(there)
const foreign = Boolean(fieldMark) && mode !== 'config'
const wanted = mode === 'config' ? write && applied.includes('update') : (mode === 'late' && write) || copied
if (foreign || (!there && wanted)) {
// the field object may be shared with the collection this one was copied from — give this one its own
if (mode !== 'config') {roles = ownCopyOfField(collection, roles)}
roles.access = { ...roles.access, update: markedStaffRule(foreign ? bothAllowField(guard, there) : guard, slug) as never }
if (!applied.includes('roles')) {applied.push('roles')}
}
}
// "roles of its own": a roles field whose values are not the plugin's (a collection without the field has no roles to rank)
const rules: StaffAccountRules = { applied, ownRoles: !ours && Boolean(roles) }
collection.custom = { ...collection.custom, ipalAccountRules: rules }
return rules
const record: StaffAccountRules = { slug, applied, ownRoles: !ours && Boolean(roles) }
// (a late collection that is not staff and brought nothing of the plugin's along gets no record)
if (applied.length || before || mode !== 'copied') {collection.custom = { ...collection.custom, ipalAccountRules: record }}
return record
}
/**
* Gives a (sanitized) collection its OWN copy of one field object, in `fields` and `flattenedFields`, and returns
* the copy: a collection made by spreading another shares the field objects — and the arrays — with it.
*/
function ownCopyOfField(collection: CollectionConfig, field: FieldLike): FieldLike {
const copy = { ...field }
const rebuild = (list: FieldLike[]): FieldLike[] =>
list.map((entry) => {
if (entry === field) {return copy}
if (!entry.name && entry.fields) {return { ...entry, fields: rebuild(entry.fields) }}
if (entry.tabs) {return { ...entry, tabs: entry.tabs.map((tab) => (tab.name ? tab : { ...tab, fields: rebuild(tab.fields) })) }}
return entry
})
const own = collection as unknown as { fields?: FieldLike[]; flattenedFields?: FieldLike[] }
if (Array.isArray(own.fields)) {own.fields = rebuild(own.fields)}
if (Array.isArray(own.flattenedFields)) {own.flattenedFields = own.flattenedFields.map((entry) => (entry === field ? copy : entry))}
return copy
}
/** A copy of the field tree down to the `roles` field, so the project's own objects are not changed. */
@@ -255,7 +337,7 @@ export function applyStaffAccountAccess(config: Config, staffSlugs: string[], op
collections: (config.collections ?? []).map((collection) => {
if (!collection.auth || !staffSlugs.includes(collection.slug)) {return collection}
const copy = { ...collection, access: { ...collection.access }, fields: copyToRoles(collection.fields as FieldLike[]) as CollectionConfig['fields'] }
ruleStaffCollection(copy, options)
ruleStaffCollection(copy, options, 'config')
return copy
}),
}
@@ -279,14 +361,23 @@ export function adoptLateAuthCollections(
): LateAdoption[] {
const adopted: LateAdoption[] = []
for (const collection of config.collections ?? []) {
const custom = collection.custom as { ipal?: { accountRules?: unknown }; ipalAccounts?: boolean } | undefined
if (!collection.auth || custom?.ipalAccounts) {continue}
collection.custom = { ...collection.custom, ipalAccounts: true }
if (!collection.auth) {continue}
const custom = collection.custom as { ipal?: { accountRules?: unknown } } | undefined
const staff = staffSlugs.includes(collection.slug)
// Handled already: under THIS slug, and as staff if it is staff now. A marker for another slug came along with
// a copy; a marker that says "not staff" on a collection that is staff now was made before it was named as one.
const marker = markerOf(collection)
if (marker?.slug === collection.slug && (marker.staff || !staff)) {continue}
const done: LateAdoption = { slug: collection.slug, applied: [], firstUser: false, password: false }
if (staffSlugs.includes(collection.slug)) {
if (access !== false && custom?.ipal?.accountRules !== false) {done.applied = ruleStaffCollection(collection, access ?? {}, true).applied}
if (beforeOperation) {
const hooks = (collection.hooks ?? {}) as { beforeOperation?: unknown[] }
// A staff collection gets the plugin's rules in front of its own. Any other late collection — not staff, or one
// that keeps its own rules — only where it carries a rule the plugin wrote for another collection (a copy).
const ruled = staff && access !== false && custom?.ipal?.accountRules !== false
done.applied = ruleStaffCollection(collection, access === false || !access ? {} : access, ruled ? 'late' : 'copied').applied
collection.custom = { ...collection.custom, ipalAccounts: { slug: collection.slug, staff } satisfies AccountsMarker }
if (staff) {
const hooks = (collection.hooks ?? {}) as { beforeOperation?: unknown[] }
// (a copied collection brings the original's hooks along: the password rule is put once)
if (beforeOperation && !(hooks.beforeOperation ?? []).some(isPasswordRuleHook)) {
hooks.beforeOperation = [...(hooks.beforeOperation ?? []), beforeOperation]
collection.hooks = hooks as CollectionConfig['hooks']
done.password = true
@@ -301,9 +392,38 @@ export function adoptLateAuthCollections(
return adopted
}
/** Marks the auth collections ipalKit has seen at config time, so `adoptLateAuthCollections` leaves them alone. */
export function markSeenAuthCollections(config: Config): Config {
return { ...config, collections: (config.collections ?? []).map((c) => (c.auth ? { ...c, custom: { ...c.custom, ipalAccounts: true } } : c)) }
/**
* Puts the plugin's mark on the rules it filled in during this run (`custom.ipalAccountRules.applied`, for the
* collection's own slug). Called AFTER the 2FA package has wrapped them — the mark must be on the function that is
* on the collection — and BEFORE ipal-kit's own 2FA guard, which carries the mark to its wrapper. Already marked
* functions are left, so it can run more than once.
*/
export function markStaffRules(config: Config): Config {
return {
...config,
collections: (config.collections ?? []).map((c) => {
const record = (c.custom as { ipalAccountRules?: StaffAccountRules } | undefined)?.ipalAccountRules
if (!c.auth || !c.access || record?.slug !== c.slug) {return c}
const access = { ...c.access } as Record<string, unknown>
for (const operation of record.applied) {
const rule = access[operation]
if (typeof rule === 'function' && !staffRuleOf(rule)) {access[operation] = markedStaffRule(rule as Access, c.slug)}
}
return { ...c, access: access as CollectionConfig['access'] }
}),
}
}
/**
* Marks the auth collections ipalKit has seen at config time — with their slug and whether they are staff — so
* `adoptLateAuthCollections` leaves exactly those alone.
*/
export function markSeenAuthCollections(config: Config, staffSlugs: string[] = []): Config {
const marked = markStaffRules(config) // (a no-op where the plugin marked them before its 2FA guard)
return {
...marked,
collections: (marked.collections ?? []).map((c) => (c.auth ? { ...c, custom: { ...c.custom, ipalAccounts: { slug: c.slug, staff: staffSlugs.includes(c.slug) } satisfies AccountsMarker } } : c)),
}
}
/** Slugs named as staff that are not auth collections of the live config. */
@@ -482,7 +602,9 @@ export async function staffCollectionsOpenToOthers(payload: LivePayload): Promis
* project's roles. For the doctor: the project should write its own rules. Slugs only.
*/
export function staffCollectionsOnOwnRoles(payload: LivePayload): string[] {
const staff = staffCollectionSlugs(payload as never)
return Object.values(payload.collections ?? {})
.filter(({ config }) => staff.includes(config.slug))
.map(({ config }) => ({ slug: config.slug, rules: (config as { custom?: { ipalAccountRules?: StaffAccountRules } }).custom?.ipalAccountRules }))
.filter(({ rules }) => rules?.ownRoles && rules.applied.some((operation) => operation === 'create' || operation === 'update' || operation === 'delete'))
.map(({ slug }) => slug)
@@ -1,5 +1,7 @@
import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payload'
import { carryStaffRule } from '../../access/ruleMark.js'
/**
* ipal-kit's own second-factor check, next to the access wrapper of
* @clocklimited/payload-2fa.
@@ -150,6 +152,8 @@ export function requireSecondFactor<T extends AnyAccess>(access?: T): T {
return access ? access(args as never) : Boolean(args.req?.user)
}) as unknown as Guarded
wrapped[GUARDED] = true
// the wrapper answers for the same rule: the plugin's mark on a staff account rule goes with it (access/ruleMark.ts)
carryStaffRule(access, wrapped)
return wrapped as unknown as T
}
+12 -2
View File
@@ -15,7 +15,7 @@ import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js'
import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js'
import { applyPasswordRule, buildPasswordRuleHook, resolvePasswordRule } from './modules/access/passwordRule.js'
import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, staffCollectionsNobodyManages, unknownStaffCollections } from './modules/access/selfRegistration.js'
import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, markStaffRules, staffCollectionsNobodyManages, unknownStaffCollections } from './modules/access/selfRegistration.js'
import { ROLE_HIERARCHY } from './modules/access/types.js'
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
import { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
@@ -159,6 +159,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
: {}),
admin: { useAsTitle: 'email' },
auth: true,
// these rules are the plugin's, written for this slug (marked as such when ipalKit finishes) — not the ones
// the project passed in access.authAccess
...(hasRoles
? { custom: { ipalAccountRules: { slug: authSlug, applied: ['create', 'delete', 'read', 'unlock', 'update'].filter((k) => !(k in (options.access?.authAccess ?? {}))), ownRoles: false } } }
: {}),
fields: [],
},
]
@@ -891,6 +896,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// collections (wrapped by the package already; twice is harmless), the
// plugin's globals and collections, the form builder's.
if (secondFactorGuard) {
// the plugin's account rules get their mark first (the 2FA package has wrapped them by now): the guard carries it over
config = markStaffRules(config)
config = guardConfigAccess(config)
}
@@ -987,7 +994,10 @@ export const ipalKit = (options: IpalOptions): Plugin => {
}
// Every auth collection of this config has been seen: what appears later is a late one (adoptConfig).
if (accounts) {config = markSeenAuthCollections(config)}
if (accounts) {
const panel = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
config = markSeenAuthCollections(config, staffCollectionSlugs({ admin: { user: panel }, custom: config.custom }))
}
return config
}
}
+9
View File
@@ -0,0 +1,9 @@
/** The copy rules as one table, 2FA off — see accountCopyTableSuite.ts. */
import { vi } from 'vitest'
import { copyTableSuite } from './accountCopyTableSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
copyTableSuite(false)
+9
View File
@@ -0,0 +1,9 @@
/** The copy rules as one table, 2FA ON — see accountCopyTableSuite.ts. */
import { vi } from 'vitest'
import { copyTableSuite } from './accountCopyTableSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
copyTableSuite(true)
+285
View File
@@ -0,0 +1,285 @@
/**
* The copy rules as ONE table (review round 4 of the follow-ups: "a rule that cannot widen").
*
* A plugin listed after ipalKit copies staff collections, reuses their access objects, wraps their rules, writes
* rules of its own next to them — every shape the reviews of 1.16.7's follow-ups tried (zzcopy3's table, R4-1, F-1,
* F-2, G-1, G-2, H-1, J-1, J-2). For every shape, every kind of account and every operation two things must hold:
*
* 1. NOT WIDER THAN 1.16.7. What an account may do is measured as a number (0 / 1, or how many documents it
* reads) and compared with the same measurement taken on the released 1.16.7
* (test/fixtures/copyRulesBaseline.json, written by this suite with IPAL_COPY_BASELINE=write on that tree).
* 2. NOT WIDER THAN THE PLUGIN'S RULE for that collection: nobody from outside, no account of another staff
* collection that is not an admin, nobody raises its own role, and — on every shape — the account with the
* same id in the ORIGINAL collection is not "the account itself" (the one thing 1.16.7 itself had open).
*
* The plugin never replaces a rule on these collections; it puts its own in front (bothAllow). So both hold by
* construction, and this table is the proof on real HTTP. SQLite by default; Postgres / MongoDB with the usual
* variables; 2FA off and on (one file each).
*/
import type { CollectionConfig, Config, Field, Payload, Plugin } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { expect, test } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer } from './http/server.js'
const PASSWORD = 'a-long-test-password-1'
const BASELINE = path.resolve(import.meta.dirname, 'fixtures/copyRulesBaseline.json')
const MARK = Symbol.for('ipal.staffRule')
const roles = (options: string[], extra: Record<string, unknown> = {}): Field => ({ name: 'roles', type: 'select', hasMany: true, options, saveToJWT: true, ...extra }) as Field
const PLUGIN = ['user', 'editor', 'admin']
const MORE = ['user', 'editor', 'admin', 'boss']
const note: Field = { name: 'note', type: 'text' }
const nobody = () => false
/** A function with a hand-made mark, as deliberate code could write one. */
const forged = <T extends (...args: never[]) => unknown>(fn: T, mark: Record<string, unknown>): T => {
Object.defineProperty(fn, MARK, { configurable: true, value: { self: fn, ...mark } })
return fn
}
/** Shapes that are NOT named in `access.staffCollections`. */
const NOT_STAFF = ['nonstaff', 'crewnon', 'crossopt', 'ownvalsnon', 'teamnon']
const late: Plugin = (config: Config) => {
const of = (slug: string) => (config.collections ?? []).find((c) => c.slug === slug)!
const a = of('agents')
const acc = a.access!
const optOut = { ...a.custom, ipal: { accountRules: false } }
const shapes: CollectionConfig[] = [
{ ...a, slug: 'plain' },
{ ...a, slug: 'ownrules', access: { ...acc, create: nobody, delete: nobody, read: ({ req }) => ((req.user as { roles?: string[] } | null)?.roles?.includes('admin') ? { email: { equals: '[email protected]' } } : false), update: nobody } },
{ ...a, slug: 'ownfield', fields: [roles(PLUGIN, { access: { update: nobody } }), note] },
{ ...a, slug: 'optout', custom: optOut },
{ ...a, slug: 'nonstaff' },
{ ...of('users'), slug: 'userscopy' },
{ ...of('proj'), slug: 'projcopy' },
{ ...a, slug: 'lesscopy', access: { create: acc.create } },
// one rule of the original used for other operations
{ ...a, slug: 'crossop', access: { ...acc, read: acc.create, update: acc.create } },
{ ...a, slug: 'crossopt', access: { ...acc, read: acc.create, update: acc.create } },
// wrappers that are not the plugin's
{ ...a, slug: 'proxied', access: { ...acc, create: new Proxy(acc.create!, { apply: nobody }), read: new Proxy(acc.read!, { apply: nobody }), update: new Proxy(acc.update!, { apply: nobody }) } },
{ ...a, slug: 'protod', access: { ...acc, update: Object.setPrototypeOf(() => false, acc.update!) as never } },
{ ...a, slug: 'mimic', access: { ...acc, update: Object.defineProperties(() => false, Object.getOwnPropertyDescriptors(acc.update!)) as never } },
{ ...a, slug: 'bound', access: { ...acc, update: acc.update!.bind(null) } },
{ ...a, slug: 'wrapnarrow', access: { ...acc, read: async (x) => Boolean(await acc.read!(x)) && Boolean((x.req.user as { roles?: string[] } | null)?.roles?.includes('admin')), update: async (x) => Boolean(await acc.update!(x)) && Boolean((x.req.user as { roles?: string[] } | null)?.roles?.includes('admin')) } },
{ ...a, slug: 'whererule', access: { ...acc, read: () => ({ email: { equals: '[email protected]' } }), update: () => ({ email: { equals: '[email protected]' } }) } },
{ ...a, slug: 'frozen', access: Object.freeze({ ...acc, update: Object.freeze(() => false) }) },
{ ...a, slug: 'shared1' },
{ ...a, slug: 'shared2', access: { ...acc, delete: acc.update } },
{ ...a, slug: 'hookproxy', hooks: { ...a.hooks, beforeOperation: (a.hooks?.beforeOperation ?? []).map((hook) => new Proxy(hook, {})) } },
// the opt-out with rules of its own
{ ...a, slug: 'optopen', access: { ...acc, create: () => true, read: () => true }, custom: optOut },
{ ...a, slug: 'optsame', custom: optOut, fields: [roles(PLUGIN), note] }, // J-2: its own roles field, no field access
{ ...a, slug: 'optvals', custom: optOut, fields: [roles(MORE), note] },
{ ...a, slug: 'optplain', custom: optOut },
// other role values than the original's
{ ...a, slug: 'ownvals', fields: [roles(MORE)] }, // H-1
{ ...a, slug: 'ownvalsnon', fields: [roles(MORE)] },
{ slug: 'freshown', access: { ...acc }, auth: true, fields: [roles(MORE)] },
{ ...a, slug: 'renamed', fields: [roles(['lead', 'member']), note] },
{ ...a, slug: 'noroles', fields: [note] },
{ ...of('crew'), slug: 'crewcopy' },
{ ...of('crew'), slug: 'crewnon' },
{ ...of('crew'), slug: 'crewadmin', fields: [roles(PLUGIN)] },
{ ...of('team'), slug: 'teamcopy' },
{ ...of('team'), slug: 'teamnon' },
{ ...of('team'), slug: 'teamadmin', fields: [roles(PLUGIN)] }, // J-1: "an account of the collection" on a collection with `admin`
{ slug: 'teamfresh', access: { ...of('team').access }, auth: true, fields: [roles(PLUGIN)] },
// hand-made marks
{ slug: 'forged', access: { create: forged(() => true, { slug: 'forged' }), update: forged(() => false, { slug: 'elsewhere' }) }, auth: true, fields: [roles(PLUGIN)] },
{ ...a, slug: 'handmark', access: { ...acc, update: Object.defineProperty(() => false, MARK, { configurable: true, value: (acc.update as unknown as Record<symbol, unknown>)[MARK] }) as never } },
{ slug: 'liar', access: { create: forged(() => true, { slug: 'agents', kind: 'bogus', operation: 'bogus' }), update: forged(() => false, { slug: 'agents', kind: 'admin', operation: 'update' }) }, auth: true, fields: [roles(PLUGIN)] },
{ slug: 'protoop', access: { create: forged(() => false, { slug: 'agents', kind: 'toString', operation: 'toString' }), read: forged(() => false, { slug: 'agents', kind: 'toString', operation: 'toString' }) }, auth: true, fields: [roles(PLUGIN)] },
]
return { ...config, collections: [...(config.collections ?? []), ...shapes] }
}
type Session = Record<string, string>
type Table = Record<string, number>
/** One Payload instance per test file: run from a file of its own for 2FA off and on. */
export function copyTableSuite(twoFactor: boolean): void {
test(`copies of staff collections: never wider than 1.16.7, never wider than the plugin's rule (2FA on: ${twoFactor})`, async () => {
let shapeSlugs: string[] = []
const capture: Plugin = (config) => {
shapeSlugs = (config.collections ?? []).filter((c) => c.auth).map((c) => c.slug).filter((slug) => !['agents', 'crew', 'customers', 'proj', 'team', 'users'].includes(slug))
return config
}
const staffShapes = (all: string[]) => all.filter((slug) => !NOT_STAFF.includes(slug))
// the slugs are needed for `access.staffCollections` before the late plugin runs: build them once from a dry call
const names = ((late({ collections: [{ slug: 'agents', access: { create: nobody, read: nobody, update: nobody }, auth: true, fields: [] }, { slug: 'users', auth: true, fields: [] }, { slug: 'proj', auth: true, fields: [] }, { slug: 'crew', auth: true, fields: [] }, { slug: 'team', auth: true, fields: [] }] } as never) as Config).collections ?? []).map((c) => c.slug).filter((slug) => !['agents', 'crew', 'proj', 'team', 'users'].includes(slug))
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'agents', auth: true, fields: [roles(PLUGIN), note] },
{ slug: 'crew', auth: true, fields: [roles(['user', 'boss', 'admin'])] },
{ slug: 'team', auth: true, fields: [roles(['lead', 'member'])] },
{ slug: 'proj', access: { update: ({ req }) => (req.user as { email?: string } | null)?.email === '[email protected]' }, auth: true, fields: [roles(PLUGIN)] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase(twoFactor ? 'copy_table_2fa' : 'copy_table'),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users', staffCollections: ['agents', 'crew', 'team', 'proj', ...staffShapes(names)] },
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false,
}),
late,
capture,
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
const payload: Payload = await getPayload({ config })
const server = await startPayloadServer(config)
const call = (method: string, pathname: string, session: Session = {}, body?: unknown) =>
fetch(`${server.url}/api${pathname}`, { body: body === undefined ? undefined : JSON.stringify(body), headers: { 'content-type': 'application/json', ...session }, method })
const make = async (collection: string, email: string, value: string[] | undefined) => {
try {
return await payload.create({ collection: collection as never, data: { email, password: PASSWORD, ...(value ? { roles: value } : {}) } as never })
} catch {
return null
}
}
const login = async (collection: string, email: string): Promise<null | Session> => {
const body = (await (await call('POST', `/${collection}/login`, {}, { email, password: PASSWORD })).json()) as { token?: string }
return body.token ? { authorization: `JWT ${body.token}` } : null
}
const rolesOf = async (collection: string, id: unknown) => JSON.stringify(((await payload.findByID({ id: id as never, collection: collection as never }).catch(() => null)) as { roles?: unknown } | null)?.roles ?? null)
const reset = (collection: string, id: unknown, data: Record<string, unknown>) => payload.update({ id: id as never, collection: collection as never, data: data as never }).catch(() => null)
try {
// the original's first account: on the SQL adapters it has the same id as the first account of every copy
await make('agents', '[email protected]', ['user'])
await make('agents', '[email protected]', ['admin'])
await call('POST', '/customers', {}, { email: '[email protected]', password: PASSWORD })
const outside: [string, Session][] = [
['anonymous', {}],
['customer', (await login('customers', '[email protected]'))!],
['namesake', (await login('agents', '[email protected]'))!], // an `agents` account with the role user
['agentsAdmin', (await login('agents', '[email protected]'))!],
]
const table: Table = {}
const shapes: Record<string, { adminRules: boolean; hasRoles: boolean; optOut: boolean; staff: boolean }> = {}
for (const slug of shapeSlugs) {
const collection = payload.collections[slug as never].config as CollectionConfig
const field = (collection.fields as { name?: string; options?: unknown[]; type?: string }[]).find((f) => f.name === 'roles')
const options = field?.type === 'select' && Array.isArray(field.options) ? field.options.map((o) => (typeof o === 'string' ? o : (o as { value: string }).value)) : null
const low = field ? [options?.includes('user') ? 'user' : (options?.at(-1) ?? 'user')] : undefined
const top = field ? [options?.includes('admin') ? 'admin' : (options?.[0] ?? 'admin')] : undefined
shapes[slug] = {
adminRules: Boolean(field) && (!options || options.some((o) => o === 'editor' || o === 'admin') || options.every((o) => PLUGIN.includes(o))),
hasRoles: Boolean(field),
optOut: (collection.custom as { ipal?: { accountRules?: unknown } } | undefined)?.ipal?.accountRules === false,
staff: !NOT_STAFF.includes(slug),
}
const mine = await make(slug, `low@${slug}.example.com`, low) // FIRST: the namesake's twin
let victim = await make(slug, `victim@${slug}.example.com`, low)
const boss = await make(slug, `top@${slug}.example.com`, top)
if (!mine || !victim || !boss) {continue} // the shape cannot hold accounts on this tree: nothing to compare
// The shape's own accounts log in at the START of their turn: a password that was put back after another
// actor's turn ends the sessions an account had (and an account that cannot log in has no rows).
const actors: [string, (() => Promise<null | Session>) | Session][] = [...outside, ['ownLow', () => login(slug, `low@${slug}.example.com`)], ['ownTop', () => login(slug, `top@${slug}.example.com`)]]
for (const [actor, who] of actors) {
const session = typeof who === 'function' ? await who() : who
if (!session) {continue}
if (actor === 'ownLow' || actor === 'ownTop') {
// a session that works at all: `me` answers with the account
const me = (await (await call('GET', `/${slug}/me`, session)).json()) as { user?: { email?: string } | null }
table[`${slug} | ${actor} | signedIn`] = me.user?.email ? 1 : 0
}
const set = (action: string, value: number) => {
table[`${slug} | ${actor} | ${action}`] = value
}
const list = await call('GET', `/${slug}?limit=100`, session)
set('read', list.status === 200 ? (((await list.json()) as { totalDocs?: number }).totalDocs ?? 0) : 0)
const made = `made-${actor}@${slug}.example.com`
set('create', (await call('POST', `/${slug}`, session, { email: made, password: PASSWORD, ...(top ? { roles: top } : {}) })).status === 201 ? 1 : 0)
await payload.delete({ collection: slug as never, where: { email: { equals: made } } }).catch(() => null)
set('patchVictim', (await call('PATCH', `/${slug}/${victim.id}`, session, { password: 'taken-over-password-1' })).status === 200 ? 1 : 0)
if (actor !== 'ownTop') {set('patchTop', (await call('PATCH', `/${slug}/${boss.id}`, session, { password: 'taken-over-password-1' })).status === 200 ? 1 : 0)}
// the account with the SAME id as the namesake's own (R4-1)
if (actor !== 'ownLow') {set('patchTwin', (await call('PATCH', `/${slug}/${mine.id}`, session, { password: 'taken-over-password-1' })).status === 200 ? 1 : 0)}
if (actor === 'ownLow') {
if (top) {
const before = await rolesOf(slug, mine.id)
await call('PATCH', `/${slug}/${mine.id}`, session, { roles: top })
await call('PATCH', `/${slug}?where[email][equals]=low@${slug}.example.com`, session, { roles: top })
set('raiseSelf', (await rolesOf(slug, mine.id)) === before ? 0 : 1)
await reset(slug, mine.id, { roles: low })
}
}
if (top) {
const before = await rolesOf(slug, victim.id)
await call('PATCH', `/${slug}/${victim.id}`, session, { roles: top })
set('rolesVictim', (await rolesOf(slug, victim.id)) === before ? 0 : 1)
await reset(slug, victim.id, { roles: low })
}
set('unlock', (await call('POST', `/${slug}/unlock`, session, { email: `victim@${slug}.example.com` })).status === 200 ? 1 : 0)
const gone = (await call('DELETE', `/${slug}/${victim.id}`, session)).status === 200
set('delete', gone ? 1 : 0)
if (gone) {victim = (await make(slug, `victim@${slug}.example.com`, low))!}
// last in its turn: a new password ends the account's own session
if (actor === 'ownLow') {set('ownPassword', (await call('PATCH', `/${slug}/${mine.id}`, session, { password: 'my-own-new-password-1' })).status === 200 ? 1 : 0)}
for (const [id, email] of [[victim.id, `victim@${slug}.example.com`], [boss.id, `top@${slug}.example.com`], [mine.id, `low@${slug}.example.com`]] as [unknown, string][]) {
await reset(slug, id, { email, password: PASSWORD })
}
}
}
expect(Object.keys(table).length).toBeGreaterThan(1000)
// the table measures something: the shapes' own accounts were signed in, and on a plain staff copy staff reads staff
expect(Object.keys(table).filter((key) => key.endsWith('| signedIn') && table[key] === 1).length).toBeGreaterThan(40)
expect(table['plain | ownTop | read']).toBeGreaterThan(0)
if (process.env.IPAL_COPY_BASELINE === 'write') {
writeFileSync(BASELINE, `${JSON.stringify(table, null, 1)}\n`)
return
}
// ── 1. not wider than 1.16.7 ──
expect(existsSync(BASELINE), 'test/fixtures/copyRulesBaseline.json (IPAL_COPY_BASELINE=write on the 1.16.7 tree)').toBe(true)
const baseline = JSON.parse(readFileSync(BASELINE, 'utf8')) as Table
const compared = Object.keys(table).filter((key) => key in baseline)
expect(compared.length).toBeGreaterThan(1000)
expect(Object.keys(shapes).filter((slug) => !compared.some((key) => key.startsWith(`${slug} | `)))).toEqual([]) // every shape is in the baseline
const wider = compared.filter((key) => table[key] > baseline[key]).map((key) => `${key}: ${baseline[key]} → ${table[key]}`)
expect(wider, 'wider than 1.16.7').toEqual([])
// ── 2. not wider than the plugin's rule ──
const over: string[] = []
const must = (key: string, most: number) => {
if (key in table && table[key] > most) {over.push(`${key}: ${table[key]} (at most ${most})`)}
}
const WRITES = ['create', 'patchVictim', 'patchTop', 'patchTwin', 'rolesVictim', 'unlock', 'delete']
for (const [slug, shape] of Object.entries(shapes)) {
// on EVERY shape: the original's account with the same id is not "the account itself", and nobody raises its own role
must(`${slug} | namesake | patchTwin`, 0)
if (shape.hasRoles) {must(`${slug} | ownLow | raiseSelf`, 0)}
if (!shape.staff || shape.optOut) {continue} // its own rules decide the rest (part 1 holds them to 1.16.7)
for (const actor of ['anonymous', 'customer']) {
for (const action of ['read', ...WRITES]) {must(`${slug} | ${actor} | ${action}`, 0)}
}
// a staff account of ANOTHER collection that is not an admin writes nothing
for (const action of WRITES) {must(`${slug} | namesake | ${action}`, 0)}
// where the admin rules apply, the collection's own lowest account writes nothing but itself
if (shape.adminRules) {
for (const action of WRITES.filter((a) => a !== 'patchTwin')) {must(`${slug} | ownLow | ${action}`, 0)}
}
}
expect(over, "wider than the plugin's rule").toEqual([])
} finally {
await server.close()
await payload.destroy?.()
}
}, 600_000)
}
+114 -10
View File
@@ -17,9 +17,12 @@ import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { adminOrSelfIn } from '../src/modules/access/index.js'
import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js'
import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js'
import { adoptLateAuthCollections, bothAllow, canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesAreAList, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js'
import { buildPasswordRuleHook, checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js'
import { isPasswordRuleHook, markedStaffRule, staffRuleOf } from '../src/modules/access/ruleMark.js'
import { adoptLateAuthCollections, bothAllow, canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesAreAList, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js'
import { requireSecondFactor } from '../src/modules/security/totp/secondFactor.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig, withTotpParts } from './helpers.js'
import { testDatabase } from './http/db.js'
@@ -555,8 +558,11 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect([of(own, 'users').access?.create, of(own, 'users').access?.update, of(own, 'users').access?.delete]).toEqual([mine, mine, mine])
// the collection that carries the plugin's roles: the admin rule, although the field is injected later
const ownNoRule = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never)
expect(of(ownNoRule, 'users').access?.create).toBe(staffCreateAccess)
expect(of(ownNoRule, 'users').access?.delete).toBe(staffCreateAccess)
// (the plugin's rules carry its mark for the slug, on the function: that is how a copy of the collection is told later)
expect(['create', 'delete', 'update', 'unlock', 'read', 'readVersions'].map((op) => staffRuleOf((of(ownNoRule, 'users').access as Record<string, unknown>)[op])?.slug)).toEqual(Array(6).fill('users'))
expect(await (of(ownNoRule, 'users').access!.create as (a: unknown) => unknown)({ req: { payload: { staffCollections: ['users'] }, user: { id: 1, collection: 'users', roles: ['editor'] } } })).toBe(false)
expect(staffRuleOf(mine)).toBeUndefined() // a rule the project wrote is not marked
expect(staffRuleOf(staffCreateAccess)).toBeUndefined() // nor the exported rule itself: the mark is on a function of its own
})
test('whose roles: the plugin\'s rule only where the roles are the plugin\'s', () => {
@@ -622,7 +628,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([1, 1, 0, 0])
expect([firstUser(on, 'users'), firstUser(on, 'staff2'), firstUser(on, 'customers'), firstUser(on, 'pages')]).toEqual([1, 1, 1, 0])
const payloadWay = await build({ accounts: { adminOnlyCreate: false, adminOnlyWrite: false, firstUserRoute: 'all', password: false } })
expect(of(payloadWay, 'staff2').access).toEqual({ read: staffReadAccess, readVersions: staffReadAccess })
expect(Object.keys(of(payloadWay, 'staff2').access ?? {}).sort()).toEqual(['read', 'readVersions'])
expect(of(await build({ accounts: { adminOnlyCreate: false, adminOnlyWrite: false, firstUserRoute: 'all', password: false, staffOnlyRead: false } }), 'staff2').access).toBeUndefined()
expect([guards(payloadWay, 'staff2'), firstUser(payloadWay, 'staff2')]).toEqual([0, 0])
// each switch on its own
@@ -642,7 +648,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
// without the plugin's roles nobody is an admin to it
const noAccess = await ipalKit({ i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config)
expect(of(noAccess, 'users').access?.create).toBeTypeOf('function')
expect(of(noAccess, 'users').access?.create).not.toBe(staffCreateAccess)
expect(await (of(noAccess, 'users').access!.create as (a: unknown) => unknown)({ req: { payload: { staffCollections: ['users'] }, user: { id: 1, collection: 'users' } } })).toBe(true)
})
test('the roles field: protected where the plugin\'s update rule is in force and the field has no access of its own', async () => {
@@ -651,7 +657,10 @@ export function accountRulesSuite(twoFactor: boolean): void {
const collections = (extra: object = {}, field: object = own) => ({ collections: [{ slug: 'staff2', auth: true, fields: [{ type: 'row', fields: [field] }], ...extra }] }) as never
const inRow = (config: Config) => (of(config, 'staff2').fields[0] as unknown as { fields: { access?: { update?: unknown } }[] }).fields[0]
// the plugin's roles: only an admin; found inside a row too; the project's own field object is not changed
expect(inRow(await build({}, collections())).access?.update).toBe(rolesByAdminOnly)
const fieldRule0 = inRow(await build({}, collections())).access?.update as (a: unknown) => boolean
expect(staffRuleOf(fieldRule0)?.slug).toBe('staff2')
expect(fieldRule0({ req: { payload: { staffCollections: ['staff2'] }, user: { id: 1, collection: 'staff2', roles: ['editor'] } } })).toBe(false)
expect(fieldRule0({ req: { payload: { staffCollections: ['staff2'] }, user: { id: 1, collection: 'staff2', roles: ['admin'] } } })).toBe(true)
expect((own as { access?: unknown }).access).toBeUndefined()
// roles of the project's own: never the account itself
const mine = inRow(await build({}, collections({}, { ...own, options: ['boss', 'worker'] }))).access?.update as (a: unknown) => boolean
@@ -676,9 +685,9 @@ export function accountRulesSuite(twoFactor: boolean): void {
const bw = ({ req }: { req: { user: unknown } }) => Boolean(req.user)
const narrow = () => false
const where = () => ({ team: { equals: 'a' } })
const hook = () => undefined
const hook = buildPasswordRuleHook() // a real one: the plugin knows its own hook by a mark on the function
const late = { slug: 'late', access: { create: g, delete: narrow, read: g, readVersions: g, unlock: bw, update: where }, auth: true, endpoints: [{ handler: () => undefined, method: 'post', path: '/first-register' }], fields: [{ name: 'roles', type: 'select', access: {}, hasMany: true, options: ['user', 'admin'] }] }
const seen = { slug: 'users', access: { create: g }, auth: true, custom: { ipalAccounts: true }, endpoints: [], fields: [] }
const seen = { slug: 'users', access: { create: g }, auth: true, custom: { ipalAccounts: { slug: 'users', staff: true } }, endpoints: [], fields: [] }
const visitors = { slug: 'visitors', access: { create: g }, auth: true, endpoints: [], fields: [] }
const asIs = { slug: 'as-is', access: { create: g }, auth: true, custom: { ipal: { accountRules: false } }, endpoints: [], fields: [] }
const pages = { slug: 'pages', access: {}, endpoints: [], fields: [] }
@@ -708,7 +717,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect(await ask('delete', admin)).toBe(false)
expect(await ask('update', admin)).toEqual({ team: { equals: 'a' } })
expect(await ask('update', own)).toEqual({ and: [{ id: { equals: 7 } }, { team: { equals: 'a' } }] })
expect((late.fields[0] as { access?: { update?: unknown } }).access?.update).toBe(rolesByAdminOnly)
expect(staffRuleOf((late.fields[0] as { access?: { update?: unknown } }).access?.update)?.slug).toBe('late')
expect((late as { hooks?: { beforeOperation?: unknown[] } }).hooks?.beforeOperation).toEqual([hook])
expect((late.endpoints[0] as { custom?: { ipalFirstUser?: boolean } }).custom?.ipalFirstUser).toBe(true) // in FRONT of Payload's
// a late auth collection that is not staff: the first-user endpoint only
@@ -727,6 +736,101 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect(await bothAllow(() => false, () => { throw new Error('not asked') })({} as never)).toBe(false)
})
// The copy rules ("a rule that cannot widen"): the HTTP proof is the table in accountCopyTableSuite.ts; here the parts.
test('the plugin\'s mark: on the function itself, never on a shared rule or through somebody\'s wrapper', async () => {
const marked = markedStaffRule(staffCreateAccess, 'agents')
expect(marked).not.toBe(staffCreateAccess)
expect(staffRuleOf(marked)).toEqual({ slug: 'agents', self: marked })
expect(staffRuleOf(staffCreateAccess)).toBeUndefined() // the exported rule is shared: a project may use it anywhere
expect(staffRuleOf(() => true)).toBeUndefined()
expect(staffRuleOf(undefined)).toBeUndefined()
expect(await marked({ req: { payload: { staffCollections: ['users'] }, user: { id: 1, collection: 'users', roles: ['admin'] } } } as never)).toBe(true)
// the plugin's own wrapper (its 2FA guard) gets a mark made for IT
const guarded = requireSecondFactor(marked)
expect(staffRuleOf(guarded)).toEqual({ slug: 'agents', self: guarded })
expect(staffRuleOf(requireSecondFactor(() => true))).toBeUndefined()
// wrappers that are not the plugin's answer with the same property — and are not the rule
const symbol = Symbol.for('ipal.staffRule')
for (const [name, fn] of [['a Proxy', new Proxy(marked, { apply: () => false })], ['the rule as prototype', Object.setPrototypeOf(() => false, marked)], ['copied descriptors', Object.defineProperties(() => false, Object.getOwnPropertyDescriptors(marked))]] as [string, unknown][]) {
expect([name, (fn as Record<symbol, unknown>)[symbol] !== undefined, staffRuleOf(fn)]).toEqual([name, true, undefined])
}
expect(staffRuleOf(marked.bind(null))).toBeUndefined()
// the password hook: marked the same way, so a copy has it once — also across module instances (a registered symbol)
const hook = buildPasswordRuleHook()
expect(isPasswordRuleHook(hook)).toBe(true)
expect((hook as unknown as Record<symbol, unknown>)[Symbol.for('ipal.passwordRule')]).toEqual({ self: hook })
expect([isPasswordRuleHook(() => undefined), isPasswordRuleHook(new Proxy(hook, {}))]).toEqual([false, false])
// with 2FA wiring that wraps every access function: the function that ENDS UP on the collection carries the mark…
const wrapping = ((o: { collection: string }) => (c: Config) => withTotpParts({ ...c, collections: (c.collections ?? []).map((col) => ({ ...col, access: Object.fromEntries(Object.entries(col.access ?? {}).map(([k, v]) => [k, (x: never) => (v as (x: never) => unknown)(x)])) })) } as Config, o.collection)) as never
const withFactory = await build({ twoFactor: { issuer: 'A', plugin: wrapping } })
expect(['create', 'update', 'delete', 'unlock', 'read', 'readVersions'].map((op) => staffRuleOf((of(withFactory, 'staff2').access as Record<string, unknown>)[op])?.slug)).toEqual(Array(6).fill('staff2'))
expect(staffRuleOf(of(withFactory, 'customers').access?.create)).toBeUndefined() // the project's own rule
// …and marking does not undo ipal-kit's 2FA guard: a plain 2FA config has nothing left to guard at start
const { ensurePayloadGuarded } = await import('../src/modules/security/totp/secondFactor.js')
const plain = await build({ twoFactor: { issuer: 'A', plugin: ((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection)) as never } })
expect([ensurePayloadGuarded({ config: plain } as never), ensurePayloadGuarded({ config: withFactory } as never)]).toEqual([[], []])
})
test('a copied collection: the plugin\'s rule for ITS slug goes in front of every rule it brought; nothing is replaced', async () => {
const mk = (slug: string, rule: unknown) => markedStaffRule(rule as () => unknown, slug)
const access = { create: mk('agents', staffCreateAccess), delete: mk('agents', staffCreateAccess), read: mk('agents', staffReadAccess), update: mk('agents', staffUpdateAccess('agents')) }
const pluginRoles = () => ({ name: 'roles', type: 'select', options: ['user', 'editor', 'admin'] }) as { access?: { update?: (a: unknown) => unknown }; name: string; options: string[]; type: string }
const agents = { slug: 'agents', access, auth: true, custom: { ipalAccountRules: { slug: 'agents', applied: Object.keys(access), ownRoles: false }, ipalAccounts: { slug: 'agents', staff: true } }, endpoints: [], fields: [pluginRoles()], hooks: { beforeOperation: [buildPasswordRuleHook()] } }
const nobody = () => false
const copy = { ...agents, slug: 'copy', endpoints: [], fields: [pluginRoles()] }
const ownRule = { ...agents, slug: 'own-rule', access: { ...access, update: nobody }, endpoints: [], fields: [pluginRoles()] }
const optOut = { ...agents, slug: 'opt-out', custom: { ...agents.custom, ipal: { accountRules: false } }, endpoints: [], fields: [pluginRoles()] }
const notStaff = { ...agents, slug: 'not-staff', endpoints: [], fields: [pluginRoles()] }
const claims = { slug: 'claims', access: { create: mk('claims', () => true) }, auth: true, endpoints: [], fields: [] } // a mark that claims this very collection
const hook = buildPasswordRuleHook()
const adopted = adoptLateAuthCollections({ collections: [agents, copy, ownRule, optOut, notStaff, claims] } as never, ['agents', 'copy', 'own-rule', 'opt-out', 'claims'], { beforeOperation: hook })
expect(adopted.map((x) => [x.slug, x.applied, x.password])).toEqual([
['copy', ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], false], // the hook came along: not put twice
['own-rule', ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], false],
['opt-out', ['create', 'update', 'delete', 'read', 'roles'], false], // only in front of the rules the plugin wrote for `agents`, and the roles field
['not-staff', ['create', 'update', 'delete', 'read', 'roles'], false],
['claims', ['create', 'update', 'delete', 'unlock', 'read', 'readVersions'], true],
])
const staff = { staffCollections: ['users', 'agents', 'copy', 'own-rule', 'opt-out', 'claims'] }
const ask = (c: { access: Record<string, unknown> }, operation: string, user: unknown) => (c.access[operation] as (a: unknown) => unknown)({ req: { payload: staff, user } })
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const namesake = { id: 7, collection: 'agents', roles: ['user'] }
for (const c of [copy, ownRule, optOut, notStaff]) {
const own = { id: 7, collection: c.slug, roles: ['user'] }
// the original's account with the same id is not "the account itself" here; nor does the copy's own account pass
// the rule that still says "an account of `agents`" — both rules must allow (the accepted cost: the copy writes its own update rule)
expect([c.slug, await ask(c, 'update', namesake), await ask(c, 'update', own), await ask(c, 'create', own), await ask(c, 'delete', own)]).toEqual([c.slug, false, false, false, false])
// the functions that came along are still inside: nothing was replaced
expect([c.slug, staffRuleOf(c.access.update)?.slug]).toEqual([c.slug, c.slug])
expect([c.slug, await ask(c, 'create', admin)]).toEqual([c.slug, true])
// the roles field of every copy is guarded, whatever the mode
const field = (c.fields[0]).access?.update
expect([c.slug, staffRuleOf(field)?.slug, await field?.({ id: 7, req: { payload: staff, user: own } })]).toEqual([c.slug, c.slug, false])
expect(c.fields[0]).not.toBe(agents.fields[0])
expect(c.access).not.toBe(agents.access)
}
expect(await ask(ownRule, 'update', admin)).toBe(false) // its own "nobody" still has to allow
expect(await ask(copy, 'update', admin)).toBe(true)
// the one line a copying plugin writes so that the copy's own accounts edit themselves (docs/access.md)
const fixed = { ...agents, slug: 'fixed', access: { ...access, update: adminOrSelfIn('fixed') }, endpoints: [], fields: [pluginRoles()] }
adoptLateAuthCollections({ collections: [fixed] } as never, ['agents', 'fixed'], { beforeOperation: hook })
const all = { staffCollections: ['users', 'agents', 'fixed'] }
const askFixed = (user: unknown) => (fixed.access.update as (a: unknown) => unknown)({ req: { payload: all, user } })
expect(await askFixed({ id: 7, collection: 'fixed', roles: ['user'] })).toEqual({ and: [{ id: { equals: 7 } }, { id: { equals: 7 } }] })
expect([await askFixed(namesake), await askFixed(admin)]).toEqual([false, true])
// a mark that claims the collection does not leave the function alone
expect([await ask(claims, 'create', { id: 9, collection: 'customers' }), await ask(claims, 'create', null), await ask(claims, 'create', admin)]).toEqual([false, false, true])
// the original is untouched
expect(await ask(agents, 'update', namesake)).toEqual({ id: { equals: 7 } })
expect(staffRuleOf(agents.access.update)?.slug).toBe('agents')
// R4-2: an object seen as NOT staff (a `next dev` edit names it as staff afterwards) is handled again; a second call changes nothing
const visitors = { slug: 'visitors', access: { create: () => true }, auth: true, endpoints: [], fields: [] }
expect(adoptLateAuthCollections({ collections: [visitors] } as never, [], { beforeOperation: hook }).map((x) => [x.slug, x.applied, x.firstUser])).toEqual([['visitors', [], true]])
expect(adoptLateAuthCollections({ collections: [visitors] } as never, ['visitors'], { beforeOperation: hook }).map((x) => [x.slug, x.applied.length > 0, x.password, x.firstUser])).toEqual([['visitors', true, true, false]])
expect(adoptLateAuthCollections({ collections: [visitors] } as never, ['visitors'], { beforeOperation: hook })).toEqual([])
expect(await (visitors.access.create as (a: unknown) => unknown)({ req: { payload: { staffCollections: ['visitors'] }, user: { id: 9, collection: 'customers' } } })).toBe(false)
})
test('the rules are on the collections BEFORE the 2FA package wraps them', async () => {
// the package gives every collection a create / update / delete of its own; afterwards "no rule" cannot be seen
const seen: Record<string, unknown> = {}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -512,7 +512,7 @@ describe('ipalKit and the 2FA plugin', () => {
admin: { user: 'users' },
} as Config)
const warnings: string[] = []
const auth = (slug: string) => ({ slug, auth: true, custom: { ipalAccounts: true }, fields: [] })
const auth = (slug: string) => ({ slug, auth: true, custom: { ipalAccounts: { slug, staff: true } }, fields: [] })
const payload = {
collections: {},
config: { admin: { user: 'users' }, collections: [auth('partners'), auth('users')], custom: config.custom, globals: [] },