M1 review round 2: the transport is no way round, nobody raises its own role, late staff collections

R2-1 the SMTP password is bound to server, port and user whatever the transport says; the transport alone is not bound.
R2-2 where the plugin's update rule is in force the roles field is closed for the account itself
     (the plugin's roles: only an admin; roles of the project's own: never one's own).
R2-3 auth collections a later plugin adds get the account rules, the password rule and the first-user endpoint when
     the config goes live; a staff slug that is not an auth collection stops the start.
R2-4 smtpRequireTls is taken out: the branch adds no field, column or collection.
Also: read (a staff account) and unlock (an admin) defaults on staff collections (accounts.staffOnlyRead);
doctor staff-own-roles and read / unlock in staff-accounts-open; r1 NULL against the default, also inside a row;
r2 bound values compared exactly.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 00:39:24 +01:00
co-authored by Claude Fable 5.2
parent a32329fbb4
commit 7002ebbfa6
20 changed files with 519 additions and 122 deletions
@@ -93,19 +93,6 @@ export const smtpFields: Field[] = [
},
],
},
{
name: 'smtpRequireTls',
type: 'checkbox',
admin: {
condition: usesSmtp,
description: {
en: 'The password is sent only over an encrypted connection; without one, no e-mail is sent.',
pl: 'Hasło jest wysyłane tylko szyfrowanym połączeniem; bez niego e-mail nie zostanie wysłany.',
},
},
defaultValue: false,
label: { en: 'Require encryption', pl: 'Wymagaj szyfrowania' },
},
{
name: 'smtpUser',
type: 'text',
+3 -8
View File
@@ -11,8 +11,8 @@ type BuildSiteIntegrationsArgs = {
/** Extra fields injected by the client project */
additionalFields?: Field[]
/**
* A save in the panel that changes the SMTP server, port, user name, transport or "require
* encryption" must send the password again (or remove it). Default true; needs write-only
* A save through access control that changes the SMTP server, port or user name must send the
* password again (or remove it), whatever the transport. Default true; needs write-only
* secrets. `false` = the stored password follows the new server, as before.
*/
reenterSecretOnChange?: boolean
@@ -42,12 +42,7 @@ export function buildSiteIntegrations({
writeOnlySecrets: writeOnly = true,
}: BuildSiteIntegrationsArgs = {}): GlobalConfig {
const secret = (fields: Field[]) =>
writeOnly ? writeOnlySecrets(fields, INTEGRATION_SECRET_FIELDS, reenterSecretOnChange
? {
// not when the save switches to Microsoft Graph: the password is not used there, and its field is hidden
smtpPassword: { appliesWhen: (data) => data.emailTransport !== 'graph', boundTo: SMTP_PASSWORD_BOUND_TO },
}
: {}) : fields
writeOnly ? writeOnlySecrets(fields, INTEGRATION_SECRET_FIELDS, reenterSecretOnChange ? { smtpPassword: { boundTo: SMTP_PASSWORD_BOUND_TO } } : {}) : fields
return {
slug: 'site-integrations',
access: {
+7
View File
@@ -25,16 +25,23 @@ export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, r
export { applyPasswordRule, buildPasswordRuleHook, checkPassword, DEFAULT_PASSWORD_MIN_LENGTH, resolvePasswordRule } from './modules/access/passwordRule.js'
export type { PasswordRuleOptions } from './modules/access/passwordRule.js'
export {
adoptLateAuthCollections,
applyFirstUserRoute,
applyStaffAccountAccess,
buildFirstUserEndpoint,
hasPluginRoles,
openSignUpCollections,
rolesByAdminOnly,
rolesNotOwn,
sameStaffCollectionAccess,
staffCollectionsOnOwnRoles,
staffCollectionsOpenToOthers,
staffCreateAccess,
staffReadAccess,
staffUpdateAccess,
unknownStaffCollections,
} from './modules/access/selfRegistration.js'
export type { 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'
+175 -24
View File
@@ -33,13 +33,6 @@ import { ROLE_HIERARCHY } from './types.js'
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. */
@@ -68,28 +61,173 @@ export const sameStaffCollectionAccess =
return userMeetsRole(req, 'admin')
}
/** `read` on a staff collection: a fully signed-in account of a staff collection. Never a visitor account. */
export const staffReadAccess: Access = ({ req }) => {
const from = collectionOf(req)
return Boolean(req.user && from && staffCollectionSlugs(req.payload).includes(from) && secondFactorPassed(req))
}
type FieldAccessArgs = { id?: number | string; req: PayloadRequest }
/** `roles` where the roles are the plugin's: only an admin changes them — nobody raises itself. */
export const rolesByAdminOnly = ({ req }: FieldAccessArgs): boolean => 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).
* `roles` where the role values are the project's own (the plugin cannot rank them): an account
* never changes its OWN roles. Another account of the collection, or a plugin admin, may.
*/
export function applyStaffAccountAccess(config: Config, staffSlugs: string[], { create = true, pluginRoles = [], write = true }: { create?: boolean; pluginRoles?: string[]; write?: boolean } = {}): Config {
if (!create && !write) {return config}
export const rolesNotOwn =
(slug: string) =>
({ id, req }: FieldAccessArgs): boolean =>
!(req.user && collectionOf(req) === slug && id !== undefined && String(req.user.id) === String(id))
type FieldLike = { access?: { update?: unknown }; fields?: FieldLike[]; name?: string; tabs?: { fields: FieldLike[]; name?: string }[] }
/** The `roles` field of a collection: at the top level of the data (also inside a row, a collapsible or an unnamed tab). */
function findRolesField(fields: FieldLike[] | undefined): FieldLike | undefined {
for (const field of fields ?? []) {
if (field.name === 'roles') {return field}
if (!field.name && field.fields) {
const found = findRolesField(field.fields)
if (found) {return found}
}
for (const tab of field.tabs ?? []) {
const found = tab.name ? undefined : findRolesField(tab.fields)
if (found) {return found}
}
}
return undefined
}
/** True when the collection carries the plugin's roles: a `roles` select at the top level of the data (also inside a row or an unnamed tab) whose values are all the plugin's. */
export function hasPluginRoles(collection: Staffish): boolean {
const field = findRolesField(collection.fields as FieldLike[]) 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))
}
/** What the plugin put on a staff collection (`custom.ipalAccountRules`) — for the doctor and for late collections. */
export type StaffAccountRules = { applied: string[]; ownRoles: boolean }
/** Payload's own default ("any logged-in user"), as a sanitized config holds it where the project wrote no rule. */
const isPayloadDefault = (rule: unknown): boolean => !rule || (typeof rule === 'function' && rule.name === 'defaultAccess')
export type StaffAccountAccessOptions = {
/** `create` (accounts.adminOnlyCreate). */
create?: boolean
/** Slugs that will carry the plugin's roles although the field is not there yet (`access.authCollection`). */
pluginRoles?: string[]
/** `read` (accounts.staffOnlyRead). */
read?: boolean
/** `update`, `delete`, `unlock`, and the `roles` field (accounts.adminOnlyWrite). */
write?: boolean
}
/**
* 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.
*/
function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions): StaffAccountRules {
const slug = collection.slug
const ours = pluginRoles.includes(slug) || hasPluginRoles(collection)
const other = sameStaffCollectionAccess(slug)
const access = (collection.access ?? {}) as Record<string, unknown>
const applied: string[] = []
const put = (operation: string, rule: unknown) => {
if (!isPayloadDefault(access[operation])) {return}
access[operation] = rule
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)}
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')
}
}
// "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
}
/** A copy of the field tree down to the `roles` field, so the project's own objects are not changed. */
const copyToRoles = (fields: FieldLike[] | undefined): FieldLike[] | undefined =>
fields?.map((field) => {
if (field.name === 'roles') {return { ...field }}
if (!field.name && field.fields) {return { ...field, fields: copyToRoles(field.fields) }}
if (field.tabs) {return { ...field, tabs: field.tabs.map((tab) => (tab.name ? tab : { ...tab, fields: copyToRoles(tab.fields)! })) }}
return field
})
/**
* Puts the defaults on the named staff collections where the project wrote no rule: `create`,
* `update`, `delete`, `unlock`, `read`, and `roles` cannot be raised by its own account.
*/
export function applyStaffAccountAccess(config: Config, staffSlugs: string[], options: StaffAccountAccessOptions = {}): Config {
const { create = true, read = true, write = true } = options
if (!create && !write && !read) {return config}
return {
...config,
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 }
const copy = { ...collection, access: { ...collection.access }, fields: copyToRoles(collection.fields as FieldLike[]) as CollectionConfig['fields'] }
ruleStaffCollection(copy, options)
return copy
}),
}
}
type LiveCollections = Record<string, { config: CollectionConfig }>
/**
* Collections that were not in the config when ipalKit ran — a plugin listed after it added them.
* Called when a config goes live (start, dev reload): a late STAFF collection gets the same
* defaults, and every late auth collection the first-user endpoint. Changes the live config in
* place; returns the slugs it adopted. `beforeOperation`: the password rule's hook for staff.
*/
export function adoptLateAuthCollections(
payload: { collections: LiveCollections },
staffSlugs: string[],
{ access, beforeOperation, firstUserRoute = 'panel' }: { access?: false | StaffAccountAccessOptions; beforeOperation?: unknown; firstUserRoute?: FirstUserRouteOption } = {},
): string[] {
const adopted: string[] = []
for (const { config } of Object.values(payload.collections ?? {})) {
if (!config.auth || (config.custom as { ipalAccounts?: boolean } | undefined)?.ipalAccounts) {continue}
config.custom = { ...config.custom, ipalAccounts: true }
adopted.push(config.slug)
if (staffSlugs.includes(config.slug)) {
if (access !== false) {ruleStaffCollection(config, access ?? {})}
if (beforeOperation) {
const hooks = (config.hooks ?? {}) as { beforeOperation?: unknown[] }
hooks.beforeOperation = [...(hooks.beforeOperation ?? []), beforeOperation]
config.hooks = hooks as CollectionConfig['hooks']
}
}
if (firstUserRoute !== 'all' && Array.isArray(config.endpoints) && !config.endpoints.some((e) => (e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)) {
config.endpoints.unshift(buildFirstUserEndpoint(firstUserRoute))
}
}
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)) }
}
/** Slugs named as staff that are not auth collections of the live config. */
export function unknownStaffCollections(payload: { collections: LiveCollections }, staffSlugs: string[]): string[] {
return staffSlugs.filter((slug) => !payload.collections?.[slug]?.config?.auth)
}
/** `accounts.firstUserRoute`: `'panel'` (default) = the panel's login collection only; slugs = those; `'all'` = Payload's behaviour. */
export type FirstUserRouteOption = 'all' | 'panel' | string[]
@@ -149,7 +287,7 @@ export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption
}
}
type LivePayload = { collections: Record<string, { config: { access?: { create?: Access; delete?: Access; update?: Access }; auth?: unknown; slug: string } }>; config?: unknown }
type LivePayload = { collections: Record<string, { config: { access?: { create?: Access; delete?: Access; read?: Access; unlock?: Access; update?: Access }; auth?: unknown; slug: string } }>; config?: unknown }
/**
* Auth collections whose `create` rule lets an anonymous request through — open sign-up.
@@ -169,9 +307,9 @@ export async function openSignUpCollections(payload: LivePayload): Promise<strin
}
/**
* 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.
* Staff collections that an account of ANOTHER, non-staff auth collection may create in, read,
* update, delete from or unlock — `'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)
@@ -179,7 +317,7 @@ export async function staffCollectionsOpenToOthers(payload: LivePayload): Promis
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) {
for (const operation of ['create', 'read', 'update', 'delete', 'unlock'] as const) {
try {
const rule = config.access?.[operation]
// no rule = Payload's default: any logged-in user
@@ -191,3 +329,16 @@ export async function staffCollectionsOpenToOthers(payload: LivePayload): Promis
}
return open.sort()
}
/**
* Staff collections with role values of their OWN that run on the plugin's defaults: inside such a
* collection every account may create, change and delete accounts — the plugin cannot rank the
* project's roles. For the doctor: the project should write its own rules. Slugs only.
*/
export function staffCollectionsOnOwnRoles(payload: LivePayload): string[] {
return Object.values(payload.collections ?? {})
.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)
.sort()
}
+11
View File
@@ -33,6 +33,10 @@ export type AccountsOptions = {
* (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.
* With it: `unlock` gets the admin rule, and the collection's `roles`
* field (when it has no `access.update` of its own) cannot be raised by
* its own account — with the plugin's roles only an admin changes roles;
* with role values of the project's own, never the account itself.
* `false` = Payload's default on collections without a rule, as before.
*/
adminOnlyWrite?: false
@@ -63,6 +67,13 @@ export type AccountsOptions = {
* logging in. `false` = Payload's own rule (3 characters).
*/
password?: false | PasswordRuleOptions
/**
* `read` on a staff collection without a `read` rule: a fully signed-in
* account of a staff collection. Payload's default let any logged-in
* account — a `customers` visitor — list the staff accounts. A rule the
* project wrote stays. `false` = Payload's default, as before.
*/
staffOnlyRead?: false
}
/**
+2 -2
View File
@@ -16,7 +16,7 @@ export const integrationsTexts = defineTexts({
maskedRemoved: 'The stored value will be removed when you save.',
maskedSet: 'A value is set. It is not shown; type a new one to replace it.',
maskedShow: 'Show',
secretReenter: 'Enter the password again: the server, port, user name or encryption setting changed. To use the server without a password, remove the stored value.',
secretReenter: 'Enter the password again: the server, port or user name changed. To use the server without a password, remove the stored value.',
// Status banner on an integration's tab (IntegrationStatusBanner)
statusCode: 'Code: {{code}}.',
@@ -75,7 +75,7 @@ export const integrationsTexts = defineTexts({
maskedRemoved: 'Zapisana wartość zostanie usunięta po zapisaniu.',
maskedSet: 'Wartość jest ustawiona. Nie jest wyświetlana; wpisz nową, aby ją zastąpić.',
maskedShow: 'Pokaż',
secretReenter: 'Wpisz hasło ponownie: zmienił się serwer, port, nazwa użytkownika lub szyfrowanie. Aby używać serwera bez hasła, usuń zapisaną wartość.',
secretReenter: 'Wpisz hasło ponownie: zmienił się serwer, port lub nazwa użytkownika. Aby używać serwera bez hasła, usuń zapisaną wartość.',
statusCode: 'Kod: {{code}}.',
statusEmailFailing: 'Wysyłka e-mail nie działa. Powiadomienia z formularzy mogą nie docierać.',
+24 -3
View File
@@ -191,16 +191,37 @@ export const securityRules: DoctorRule[] = [
check: (ctx) =>
(ctx.deep?.staffOpenToOthers ?? []).map((entry) => {
const [slug, operation] = entry.split(':')
const what: Record<string, string> = {
create: ': it can make itself a staff account',
read: ': it can list the staff accounts (addresses, roles)',
unlock: ': it can lift the lock after failed logins, which helps guessing a password',
update: ": it can change a staff account's password",
}
const option = operation === 'create' ? 'adminOnlyCreate' : operation === 'read' ? 'staffOnlyRead' : 'adminOnlyWrite'
return {
fix: `give "${slug}" an access.${operation} rule that asks for a staff account (staffCreateAccess, staffUpdateAccess('${slug}'), adminOrSelfIn('${slug}')), or drop accounts: false / accounts.adminOnly${operation === 'create' ? 'Create' : 'Write'}: false`,
message: `an account of another auth collection may ${operation} in the staff collection "${slug}"${operation === 'create' ? ': it can make itself a staff account' : operation === 'update' ? ": it can change a staff account's password" : ''}`,
severity: 'error' as const,
fix: `give "${slug}" an access.${operation} rule that asks for a staff account (staffCreateAccess, staffUpdateAccess('${slug}'), staffReadAccess, adminOrSelfIn('${slug}')), or drop accounts: false / accounts.${option}: false`,
message: `an account of another auth collection may ${operation} in the staff collection "${slug}"${what[operation] ?? ''}`,
severity: operation === 'read' ? ('warning' as const) : ('error' as const),
}
}),
docs: 'docs/access.md',
group: 'security',
source: 'deep',
},
{
// A staff collection with role values of its own on the plugin's default rules: the plugin cannot rank
// those roles, so inside the collection every account may create an account with any role.
id: 'staff-own-roles',
check: (ctx) =>
(ctx.deep?.staffOnOwnRoles ?? []).map((slug) => ({
fix: `write "${slug}"'s own access.create / update / delete rules (and field access on its roles field) from its own roles`,
message: `the staff collection "${slug}" has role values of its own and no access rules: accounts of other collections are kept out, but inside it every account may create, change and delete accounts, with any role`,
severity: 'warning' as const,
})),
docs: 'docs/access.md',
group: 'security',
source: 'deep',
},
{
// Turnstile lets submissions through while it is misconfigured or Cloudflare fails ("degraded") — visible here.
id: 'turnstile-degraded',
+8 -2
View File
@@ -5,7 +5,7 @@ import { readFileSync } from 'node:fs'
import type { DoctorStatus } from './types.js'
import { openSignUpCollections, staffCollectionsOpenToOthers } from '../access/selfRegistration.js'
import { openSignUpCollections, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers } from '../access/selfRegistration.js'
import { countPendingCookies } from '../consent/scanner/approval.js'
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
@@ -74,7 +74,13 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
} catch {
staffOpenToOthers = null
}
return { node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
let staffOnOwnRoles: null | string[] = null
try {
staffOnOwnRoles = staffCollectionsOnOwnRoles(payload as never)
} catch {
staffOnOwnRoles = null
}
return { node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
}
export type DoctorEndpointOptions = {
+7 -2
View File
@@ -66,8 +66,13 @@ export type DoctorStatus = {
pendingCookies?: null | number
plugin?: string
/**
* Staff collections an account of ANOTHER, non-staff auth collection may create in, update or
* delete from: `'users:update'`. Slugs and operations only.
* Staff collections with role values of their own that run on the plugin's default account rules:
* inside them every account may create, change and delete accounts. Slugs only.
*/
staffOnOwnRoles?: null | string[]
/**
* Staff collections an account of ANOTHER, non-staff auth collection may create in, read, update,
* delete from or unlock: `'users:update'`. Slugs and operations only.
*/
staffOpenToOthers?: null | string[]
/** The Turnstile integration's recorded state (Site integrations): never a key, only the state. null = not known. */
-3
View File
@@ -9,7 +9,6 @@ type SmtpIntegrations = {
smtpHost?: null | string
smtpPassword?: null | string
smtpPort?: null | number
smtpRequireTls?: boolean | null
smtpUser?: null | string
}
@@ -88,8 +87,6 @@ export const panelSmtpAdapter =
auth: { pass, user },
host,
port,
// "Require an encrypted connection" in the panel: no STARTTLS offered = no login, nothing sent
requireTLS: smtp.smtpRequireTls === true && port !== 465,
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
})
-3
View File
@@ -13,7 +13,6 @@ type SmtpIntegrations = {
smtpHost?: null | string
smtpPassword?: null | string
smtpPort?: null | number
smtpRequireTls?: boolean | null
smtpUser?: null | string
}
@@ -76,8 +75,6 @@ export async function sendEmail({
auth: { pass, user },
host,
port,
// "Require an encrypted connection" in the panel: no STARTTLS offered = no login, nothing sent
requireTLS: smtp.smtpRequireTls === true && port !== 465,
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
})
+30 -8
View File
@@ -22,7 +22,7 @@ import { SECRET_CLEAR, SECRET_MASK } from './constants.js'
* - **replaced** when a save sends a new value, and **removed** when it sends `SECRET_CLEAR`;
* - **asked for again** when a save through access control changes a field the secret is
* bound to (`boundTo`) and sends no new secret. The SMTP password is bound to the server,
* the port, the user name, the transport and "require encryption": otherwise a stolen admin
* the port and the user name, whatever the transport: otherwise a stolen admin
* session points the server at its own machine, sends a test e-mail and reads the password
* off the wire. `secrets: { reenterOnChange: false }` turns that off.
*
@@ -62,10 +62,27 @@ export type WriteOnlySecretOptions = {
boundTo?: string[]
}
/** Two values of a bound field are the same setting: compared as trimmed, lower-case text. */
const asText = (value: unknown): string => (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? String(value) : value === undefined || value === null ? '' : JSON.stringify(value)).trim().toLowerCase()
/** Two values of a bound field are the same setting: the same text, exactly (`587` and `'587'` are the same; another letter case or a space is a change). */
const asText = (value: unknown): string => (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? String(value) : value === undefined || value === null ? '' : JSON.stringify(value))
const sameSetting = (a: unknown, b: unknown): boolean => asText(a) === asText(b)
/** A field by name among the siblings — also inside a row or a collapsible, which add no level to the data. */
const siblingField = (fields: unknown, name: string): { defaultValue?: unknown } | undefined => {
for (const field of (Array.isArray(fields) ? fields : []) as { defaultValue?: unknown; fields?: unknown; name?: string; tabs?: { fields?: unknown; name?: string }[] }[]) {
if (field.name === name) {return field}
if (!field.name && field.fields) {
const found = siblingField(field.fields, name)
if (found) {return found}
}
for (const tab of field.tabs ?? []) {
if (tab.name) {continue}
const found = siblingField(tab.fields, name)
if (found) {return found}
}
}
return undefined
}
/** The stored value of the secret — never the mask (the original document is read with access control off; a mask there is not a secret). */
const storedSecret = (originalDoc: unknown, path: (number | string)[]): null | string => {
const stored = dig(originalDoc, path)
@@ -88,9 +105,10 @@ export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOp
const next = (siblingData as Record<string, unknown> | undefined)?.[name]
if (next === undefined) {return false} // not part of this save
// a value never saved counts as the field's default (an older document, a field added since)
const fallback = (siblingFields as { defaultValue?: unknown; name?: string }[] | undefined)?.find((f) => f.name === name)?.defaultValue
const was = before?.[name] ?? (typeof fallback === 'function' ? undefined : fallback)
return !sameSetting(next, was)
// (a SQL row can hold NULL where MongoDB holds nothing; the field may sit inside a row)
const fallback = siblingField(siblingFields, name)?.defaultValue
const byDefault = typeof fallback === 'function' ? undefined : fallback
return !sameSetting(next ?? byDefault, before?.[name] ?? byDefault)
})
if (changed.length) {
const message = req?.t ? ipalT(req.t as never, 'secretReenter') : 'Enter the password again: the settings it belongs to have changed.'
@@ -177,5 +195,9 @@ export const maskSecretsOnRestore: CollectionAfterReadHook & GlobalAfterReadHook
/** The plugin's own stored secrets (Site integrations). */
export const INTEGRATION_SECRET_FIELDS = ['smtpPassword', 'turnstileSecretKey']
/** What the SMTP password belongs to: changing one of these in the panel asks for the password again. */
export const SMTP_PASSWORD_BOUND_TO = ['emailTransport', 'smtpHost', 'smtpPort', 'smtpUser', 'smtpRequireTls']
/**
* What the SMTP password belongs to: changing one of these through access control asks for the password again —
* whatever the transport says. `emailTransport` is not in the list: the mail adapter falls back to SMTP when Graph
* is not configured, so the transport decides nothing about where the password goes; the server, port and user do.
*/
export const SMTP_PASSWORD_BOUND_TO = ['smtpHost', 'smtpPort', 'smtpUser']
+28 -7
View File
@@ -14,8 +14,8 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
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, resolvePasswordRule } from './modules/access/passwordRule.js'
import { applyFirstUserRoute, applyStaffAccountAccess } from './modules/access/selfRegistration.js'
import { applyPasswordRule, buildPasswordRuleHook, resolvePasswordRule } from './modules/access/passwordRule.js'
import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, 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'
@@ -193,6 +193,17 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const adoptConfig = (payload: BasePayload) => {
const token = (payload.config.custom as { ipal?: { staffToken?: object } } | undefined)?.ipal?.staffToken
registerStaffCollections(payload, staffCollectionSlugs(payload), token)
// Auth collections a plugin listed after ipalKit added: the account rules for them too — BEFORE the
// 2FA guard below wraps their access (it needs the rule inside its wrapper).
if (accounts) {
const rule = resolvePasswordRule(accounts.password)
const lateAccounts = adoptLateAuthCollections(payload as never, staffCollectionSlugs(payload), {
access: { ...accountAccess, pluginRoles: [] },
beforeOperation: rule ? buildPasswordRuleHook(rule) : undefined,
firstUserRoute: accounts.firstUserRoute,
})
if (lateAccounts.length) {payload.logger.info(`[ipal] Account rules also put on auth collections added after ipalKit: ${lateAccounts.join(', ')}.`)}
}
if (!secondFactorGuard) {return}
const late = ensurePayloadGuarded(payload)
if (late?.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)}
@@ -206,6 +217,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
let panelRoleSkipped: null | string = null
/** `accounts: false` turns every account rule off. */
const accounts: AccountsOptions | null = options.accounts === false ? null : (options.accounts ?? {})
/** Which of the staff defaults are on (accounts.adminOnlyCreate / adminOnlyWrite / staffOnlyRead). */
const accountAccess = { create: accounts?.adminOnlyCreate !== false, read: accounts?.staffOnlyRead !== false, write: accounts?.adminOnlyWrite !== false }
/** requireSetup.setupNotice / statusField (on unless switched off). */
let setupNotice = true
let statusField = false
@@ -215,11 +228,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
if (accounts) {
const panelSlug = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
const staffSlugs = [...new Set([panelSlug, options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]
config = applyStaffAccountAccess(config, staffSlugs, {
create: accounts.adminOnlyCreate !== false,
pluginRoles: options.access?.authCollection ? [options.access.authCollection] : [],
write: accounts.adminOnlyWrite !== false,
})
config = applyStaffAccountAccess(config, staffSlugs, { ...accountAccess, pluginRoles: options.access?.authCollection ? [options.access.authCollection] : [] })
}
if (options.twoFactor !== false) {
const tf = options.twoFactor
@@ -883,6 +892,16 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const incomingOnInit = config.onInit
config.onInit = async (payload) => {
if (incomingOnInit) {await incomingOnInit(payload)}
// A staff collection that does not exist protects nothing and hides a typo: its accounts would not be staff,
// or — worse — a collection of that name added later would be, without anyone having decided it.
const unknownStaff = unknownStaffCollections(payload as never, [...new Set([options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))])
if (unknownStaff.length) {
throw new Error(
`[ipal] access names ${unknownStaff.map((s) => `"${s}"`).join(', ')} as a staff collection, but this config has no auth collection with that slug ` +
`(auth collections: ${Object.values(payload.collections).filter((c) => c.config.auth).map((c) => c.config.slug).join(', ') || 'none'}). ` +
'Fix the slug in access.authCollection / access.staffCollections, or add the collection (docs/access.md "Who is staff").',
)
}
adoptConfig(payload)
// Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once.
watchPayloadConfig(payload, adoptConfig)
@@ -945,6 +964,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
payload.logger.info('[ipal] Plugin initialized.')
}
// Every auth collection of this config has been seen: what appears later is a late one (adoptConfig).
if (accounts) {config = markSeenAuthCollections(config)}
return config
}
}
+2 -2
View File
@@ -214,8 +214,8 @@ export type IpalOptions = {
* read the global, as before 1.16.7.
*
* The SMTP password is bound to its server: a save in the panel that changes
* the server, the port, the user name, the transport or "require an encrypted
* connection" must send the password again, or remove it — otherwise a stolen
* the server, the port or the user name must send the password again, or
* remove it (whatever the transport says) — otherwise a stolen
* admin session points the server at its own machine and a test e-mail hands
* the password over. `{ reenterOnChange: false }` = the stored password
* follows the new server. docs/security.md "Stored secrets".