Files
ipal-kit/test/plugin.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 6c4e244094 Development hosts, review V-1 to V-3: a malformed list stops the start, a trailing dot and Unicode patterns match, every send reads the store
- V-1: assertDevelopmentHosts - iapl({ developmentHosts }), mail.relay.developmentHosts and
  mailAdapter({ relay }) refuse anything but an array of non-empty host patterns, and a pattern of `*` alone
  (it would make the public site a development address). Nothing is ignored silently any more.
- V-2: one trailing dot of the host is stripped before matching; patterns are punycoded, so one written in
  Unicode matches; a `*` inside a non-ASCII label is refused.
- V-3: the 30-second memory of other hosts is gone. A dump restored into a running development site stops
  its very next e-mail.
- docs, AGENT.md, changelog draft, skills

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 10:57:32 +01:00

222 lines
13 KiB
TypeScript

import type { Config } from 'payload'
import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
import { pluginDevelopmentHosts } from '../src/modules/email/relay/options.js'
import { iapl } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
const base = (): Config =>
({
collections: [{ slug: 'users', auth: true, fields: [] }],
secret: 'test',
}) as unknown as Config
describe('iapl — config transform', () => {
test('developmentHosts: nothing in the config by default (the built-in list applies), the project\'s list when given, an empty list too', async () => {
const hosts = async (...own: [string[]?]) => {
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...(own.length ? { developmentHosts: own[0] } : {}) })(base())
return pluginDevelopmentHosts({ config } as never)
}
expect(await hosts()).toEqual(['*.dev.netscale.pl'])
expect(await hosts(['*.preview.agency-example.com'])).toEqual(['*.preview.agency-example.com'])
expect(await hosts([])).toEqual([])
// V-1: a malformed list stops the start — the plugin option, the mail option, the adapter's own
for (const bad of ['*.dev.netscale.pl', null, [1, 2], [''], ['*']]) {
await expect(hosts(bad as never), JSON.stringify(bad)).rejects.toThrow('[iapl] iapl({ developmentHosts }) must be an array of host patterns')
await expect(Promise.resolve().then(() => iapl({ access: { authCollection: 'users' }, i18n, mail: { relay: { developmentHosts: bad as never } }, twoFactor: false })(base()))).rejects.toThrow('iapl({ mail: { relay: { developmentHosts } } })')
expect(() => mailAdapter({ relay: { developmentHosts: bad as never } })({ payload: {} as never }), JSON.stringify(bad)).toThrow('mailAdapter({ relay: { developmentHosts } })')
}
})
test('adds globals, endpoint, localization and roles', async () => {
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(base())
expect(config.globals?.map((g) => g.slug)).toEqual(
expect.arrayContaining(['site-settings', 'site-integrations']),
)
expect(config.endpoints?.some((e) => e.path === '/ipal/test-email')).toBe(true)
expect(config.localization && config.localization.defaultLocale).toBe('pl')
const users = config.collections?.find((c) => c.slug === 'users')
expect(users?.fields.some((f) => 'name' in f && f.name === 'roles')).toBe(true)
})
test('enforces 2FA unless explicitly disabled', async () => {
await expect(iapl({ i18n } as never)(base())).rejects.toThrow(/twoFactor\.issuer is required/)
await expect(iapl({ i18n, twoFactor: { issuer: 'Acme' } } as never)(base())).rejects.toThrow(
/no 2FA plugin was injected/,
)
const totp = vi.fn((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection))
await iapl({ i18n, twoFactor: { issuer: 'Acme', plugin: totp as never } })(base())
expect(totp).toHaveBeenCalledWith(expect.objectContaining({ forceSetup: true, totp: { issuer: 'Acme' } }))
})
test('enabled: false keeps the schema (collections, globals) but adds no endpoints, onInit or admin components', async () => {
const config = await iapl({ access: { authCollection: 'users' }, consentLog: true, enabled: false, i18n, stats: true, twoFactor: false })(base())
expect(config.globals?.map((g) => g.slug)).toEqual(expect.arrayContaining(['site-settings', 'site-integrations', 'cookie-settings', 'notifications']))
expect(config.collections?.map((c) => c.slug)).toEqual(expect.arrayContaining(['users', 'consent-records', 'stats-visits']))
expect(config.endpoints ?? []).toEqual([])
expect(config.onInit).toBeUndefined()
expect(config.admin?.components).toBeUndefined()
})
test('forms.consentFieldName reaches submitForm through config.custom.ipal', async () => {
const config = await iapl({ forms: { consentFieldName: 'zgoda' }, i18n, twoFactor: false })(base())
expect((config.custom as { ipal?: { consentFieldName?: string } }).ipal?.consentFieldName).toBe('zgoda')
})
test('invalid i18n fails fast', () => {
expect(() => iapl({ i18n: { defaultLocale: 'de', locales: i18n.locales }, twoFactor: false })).toThrow()
})
})
describe('iapl — auth collection', () => {
test('injects a users auth collection when the project has none, with roles', async () => {
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })({
collections: [],
secret: 'x',
} as unknown as Config)
const users = config.collections?.find((c) => c.slug === 'users')
// an auth collection with Payload's defaults; the plugin only wraps the reset mail's subject (mail.accountMailAfterCommit)
expect(users?.auth).toEqual({ forgotPassword: { generateEmailSubject: expect.any(Function) } })
expect(users?.fields.some((f) => 'name' in f && f.name === 'roles')).toBe(true)
})
test("keeps the project's own users collection", async () => {
const own = { slug: 'users', auth: true, fields: [{ name: 'fullName', type: 'text' }] }
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })({
collections: [own],
secret: 'x',
} as unknown as Config)
const users = config.collections?.filter((c) => c.slug === 'users')
expect(users).toHaveLength(1)
expect(users?.[0].fields.some((f) => 'name' in f && f.name === 'fullName')).toBe(true)
})
})
describe('options that keep features reachable and overridable', () => {
const findField = (fields: unknown[], name: string): Record<string, unknown> | undefined => {
for (const f of fields as Record<string, unknown>[]) {
if (f.name === name) {return f}
const nested = [...((f.fields as unknown[]) ?? []), ...((f.tabs as { fields: unknown[] }[]) ?? []).flatMap((t) => t.fields)]
const hit = nested.length ? findField(nested, name) : undefined
if (hit) {return hit}
}
return undefined
}
const withPages = (): Config =>
({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }] },
],
secret: 'test',
}) as unknown as Config
test('seo.uploadsCollection: the meta image relates to the given upload collection (default media)', async () => {
const custom = await iapl({ i18n, seo: { collections: ['pages'], uploadsCollection: 'images' }, twoFactor: false })(withPages())
const meta = findField(custom.collections!.find((c) => c.slug === 'pages')!.fields, 'meta')!
expect(findField(meta.fields as unknown[], 'image')?.relationTo).toBe('images')
const plain = await iapl({ i18n, seo: { collections: ['pages'] }, twoFactor: false })(withPages())
const metaDefault = findField(plain.collections!.find((c) => c.slug === 'pages')!.fields, 'meta')!
expect(findField(metaDefault.fields as unknown[], 'image')?.relationTo).toBe('media')
})
test('without `access` (no roles field) admin and editor features stay reachable for logged-in users', async () => {
const config = await iapl({ consentLog: true, forms: {}, i18n, stats: true, twoFactor: false })(base())
const users = config.collections!.find((c) => c.slug === 'users')!
// `admin.user` is what Payload's sanitize fills in: the panel's login collection = the staff collection.
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } }, config: { admin: { user: 'users' } } }, user }) as never
const member = { id: 1, collection: 'users', email: '[email protected]' }
const run = (access: unknown, user: unknown) => (access as (a: { req: unknown }) => unknown)({ req: req(user) })
const integrations = config.globals!.find((g) => g.slug === 'site-integrations')!
expect(run(integrations.access!.read, member)).toBe(true)
expect(run(integrations.access!.read, null)).toBe(false)
expect(run(config.globals!.find((g) => g.slug === 'site-settings')!.access!.update, member)).toBe(true)
expect(run(config.collections!.find((c) => c.slug === 'stats-visits')!.access!.read, member)).toBe(true)
expect(run(config.collections!.find((c) => c.slug === 'consent-records')!.access!.read, member)).toBe(true)
expect(run(config.collections!.find((c) => c.slug === 'form-submissions')!.access!.read, member)).toBe(true)
})
test('with `access` the roles still decide', async () => {
const config = await iapl({ access: { authCollection: 'users' }, i18n, stats: true, twoFactor: false })(base())
const users = config.collections!.find((c) => c.slug === 'users')!
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } }, config: { admin: { user: 'users' } } }, user }) as never
const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: { req: unknown }) => unknown
expect(read({ req: req({ id: 1, collection: 'users', roles: ['editor'] }) })).toBe(false)
expect(read({ req: req({ id: 1, collection: 'users', roles: ['admin'] }) })).toBe(true)
// unknown collection = the strict side
expect(read({ req: { payload: { collections: {} }, user: { id: 1, collection: 'other' } } })).toBe(false)
})
})
describe('gap fixes: searchSettings, collection overrides', () => {
const tabsOf = (config: Config) => {
const settings = config.globals!.find((g) => g.slug === 'site-settings')!
const tabs = settings.fields.find((f) => f.type === 'tabs') as { tabs: { label?: unknown }[] }
return tabs.tabs.map((t) => (t.label as { en?: string } | undefined)?.en ?? String(t.label))
}
test('searchSettings: false removes the Search engines tab without `seo`', async () => {
expect(tabsOf(await iapl({ i18n, twoFactor: false })(base()))).toContain('Search engines')
expect(tabsOf(await iapl({ i18n, searchSettings: false, twoFactor: false })(base()))).not.toContain('Search engines')
})
test('searchSettings: a function shapes the fields; the top-level option wins over seo.searchSettings', async () => {
const config = await iapl({
i18n,
searchSettings: (fields) => fields.filter((f) => 'name' in f && f.name === 'llmsIntro'),
seo: { collections: [], searchSettings: false },
twoFactor: false,
})(base())
const settings = config.globals!.find((g) => g.slug === 'site-settings')!
const tab = (settings.fields.find((f) => f.type === 'tabs') as { tabs: { fields: { name?: string }[]; label?: unknown }[] }).tabs.find(
(t) => (t.label as { en?: string } | undefined)?.en === 'Search engines',
)!
expect(tab.fields.map((f) => f.name)).toEqual(['llmsIntro'])
// the older seo.searchSettings still works alone
expect(tabsOf(await iapl({ i18n, seo: { collections: [], searchSettings: false }, twoFactor: false })(base()))).not.toContain('Search engines')
})
test('consentLog / stats collectionOverrides: an object merges access, a function takes over', async () => {
const dpoOnly = ({ req }: { req: { user?: { email?: string } } }) => req.user?.email === '[email protected]'
const config = await iapl({
consentLog: { collectionOverrides: { access: { read: dpoOnly as never }, admin: { group: 'Privacy' } } },
i18n,
stats: { collectionOverrides: (c) => ({ ...c, labels: { plural: 'Visits', singular: 'Visit' } }) },
twoFactor: false,
})(base())
const consent = config.collections!.find((c) => c.slug === 'consent-records')!
expect(consent.access!.read).toBe(dpoOnly)
expect(consent.access!.create).toBeTypeOf('function') // plugin's rule kept
expect(consent.admin).toMatchObject({ group: 'Privacy', useAsTitle: 'consentId' })
const stats = config.collections!.find((c) => c.slug === 'stats-visits')!
expect(stats.labels).toEqual({ plural: 'Visits', singular: 'Visit' })
expect(stats.access!.read).toBeTypeOf('function')
})
test('the stats view and widget follow the collection read access', async () => {
const { canReadStats } = await import('../src/modules/stats/admin/canReadStats.js')
const payload = (read: unknown) => ({ collections: { 'stats-visits': { config: { access: { read } } } } }) as never
const onlyAnna = ({ req }: { req: { user?: { email?: string } } }) => req.user?.email === '[email protected]'
expect(await canReadStats(payload(onlyAnna), undefined, { email: '[email protected]' })).toBe(true)
expect(await canReadStats(payload(onlyAnna), { user: { email: '[email protected]' } } as never)).toBe(false)
expect(await canReadStats({ collections: {} } as never, undefined, { email: 'x' })).toBe(false)
})
})