IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved

Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 17:24:21 +01:00
co-authored by Claude Fable 5.2
parent 414a4702df
commit 0a4f001797
262 changed files with 955 additions and 950 deletions
+1 -1
View File
@@ -43,7 +43,7 @@ describe('role predicates', () => {
})
test('where the staff collections are not known, nobody is staff (browser bundle, middleware)', () => {
// no ipalKit config in this process (test/setup.ts clears the registry) and no source given
// no iapl config in this process (test/setup.ts clears the registry) and no source given
expect(isAdmin(admin)).toBe(false)
expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false)
expect(hasMinimumRole(user, 'user')).toBe(false)
+18 -18
View File
@@ -4,7 +4,7 @@ import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = {
@@ -28,7 +28,7 @@ const run = (fn: Access | undefined, u: unknown) =>
describe('injected auth collection', () => {
test('with roles: a plain user can only see and edit itself, never create or delete', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
const access = config.collections?.find((c) => c.slug === 'users')?.access ?? {}
expect(run(access.update, user)).toEqual({ id: { equals: 3 } })
@@ -45,7 +45,7 @@ describe('injected auth collection', () => {
test("the project's own auth collection keeps its own access", async () => {
const own = { slug: 'users', access: { read: () => true }, auth: true, fields: [] }
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(
empty({ collections: [own] as CollectionConfig[] }),
)
const access = config.collections?.find((c) => c.slug === 'users')?.access
@@ -53,7 +53,7 @@ describe('injected auth collection', () => {
expect(access?.read).toBe(own.access.read)
// …and the account rules fill in only what it left out (accounts.*; `accounts: false` = nothing added)
expect(access?.admin).toBeTypeOf('function')
const untouched = await ipalKit({ access: { authCollection: 'users' }, accounts: false, i18n, twoFactor: false })(
const untouched = await iapl({ access: { authCollection: 'users' }, accounts: false, i18n, twoFactor: false })(
empty({ collections: [own] as CollectionConfig[] }),
)
expect(untouched.collections?.find((c) => c.slug === 'users')?.access).toBe(own.access)
@@ -65,7 +65,7 @@ describe('2FA wraps the auth collection people log in with', () => {
test('defaults to access.authCollection, not a literal "users"', async () => {
const plugin = totp()
await ipalKit({ access: { authCollection: 'admins' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(
await iapl({ access: { authCollection: 'admins' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(
empty(),
)
expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' }))
@@ -73,7 +73,7 @@ describe('2FA wraps the auth collection people log in with', () => {
test('defaults to admin.user when access is not configured', async () => {
const plugin = totp()
await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(
await iapl({ i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(
empty({ admin: { user: 'staff' } } as Partial<Config>),
)
expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'staff' }))
@@ -91,20 +91,20 @@ describe('2FA wraps the auth collection people log in with', () => {
test('admin.user wins over access.authCollection as the default target', async () => {
const plugin = totp()
await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(twoAuth())
await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(twoAuth())
expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' }))
})
test('a target other than the panel login collection fails at init…', async () => {
const plugin = totp()
await expect(
ipalKit({ i18n, twoFactor: { collectionSlug: 'users', issuer: 'A', plugin: plugin as never } })(twoAuth()),
iapl({ i18n, twoFactor: { collectionSlug: 'users', issuer: 'A', plugin: plugin as never } })(twoAuth()),
).rejects.toThrow(/admin panel logs in with "admins"/)
})
test('…unless allowCollectionMismatch says it is deliberate', async () => {
const plugin = totp()
await ipalKit({
await iapl({
i18n,
twoFactor: { allowCollectionMismatch: true, collectionSlug: 'users', issuer: 'A', plugin: plugin as never },
})(twoAuth())
@@ -114,7 +114,7 @@ describe('2FA wraps the auth collection people log in with', () => {
test('a target that is not an auth collection always fails', async () => {
const plugin = totp()
await expect(
ipalKit({
iapl({
i18n,
twoFactor: { allowCollectionMismatch: true, collectionSlug: 'pages', issuer: 'A', plugin: plugin as never },
})(twoAuth()),
@@ -124,7 +124,7 @@ describe('2FA wraps the auth collection people log in with', () => {
describe('globals: public read, editor+ write', () => {
test.each(['site-settings', 'cookie-settings', 'notifications'])('%s', async (slug) => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
const access = (config.globals?.find((g) => g.slug === slug) as GlobalConfig).access ?? {}
expect(run(access.read, null)).toBe(true)
expect(run(access.update, user)).toBe(false)
@@ -136,7 +136,7 @@ describe('globals: public read, editor+ write', () => {
describe('forms collection: public read, editor+ write, Emails hidden from plain users', () => {
const build = async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n, twoFactor: false })(empty())
const config = await iapl({ access: { authCollection: 'users' }, forms: {}, i18n, twoFactor: false })(empty())
return config.collections?.find((c) => c.slug === 'forms') as CollectionConfig
}
@@ -161,7 +161,7 @@ describe('forms collection: public read, editor+ write, Emails hidden from plain
describe('roles field: the first-register account becomes admin', () => {
const hook = async (totalDocs: number, value: string[], pathname = '/api/users/first-register') => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
const users = config.collections?.find((c) => c.slug === 'users') as CollectionConfig
const roles = users.fields.find((f) => 'name' in f && f.name === 'roles') as { hooks?: { beforeChange?: ((a: unknown) => unknown)[] } }
const count = vi.fn(async () => ({ totalDocs }))
@@ -188,12 +188,12 @@ describe('roles field: the first-register account becomes admin', () => {
describe('every access default can be overridden by the project', () => {
test('injected users: unlock is admin-only by default; access.authAccess keys win', async () => {
const base = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
const base = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
const def = base.collections?.find((c) => c.slug === 'users')?.access ?? {}
expect(run(def.unlock, user)).toBe(false)
expect(run(def.unlock, admin)).toBe(true)
const config = await ipalKit({
const config = await iapl({
access: { authAccess: { read: () => true }, authCollection: 'users' },
i18n,
twoFactor: false,
@@ -204,14 +204,14 @@ describe('every access default can be overridden by the project', () => {
})
test('access.firstUserAdmin: false keeps what the first-register form sent', async () => {
const config = await ipalKit({ access: { authCollection: 'users', firstUserAdmin: false }, i18n, twoFactor: false })(empty())
const config = await iapl({ access: { authCollection: 'users', firstUserAdmin: false }, i18n, twoFactor: false })(empty())
const users = config.collections?.find((c) => c.slug === 'users') as CollectionConfig
const roles = users.fields.find((f) => 'name' in f && f.name === 'roles') as { hooks?: unknown }
expect(roles.hooks).toBeUndefined()
})
test('globalOverrides: an object merges access (project wins), a function takes over', async () => {
const config = await ipalKit({
const config = await iapl({
access: { authCollection: 'users' },
globalOverrides: {
'cookie-settings': (g) => ({ ...g, label: 'Cookies' }),
@@ -229,7 +229,7 @@ describe('every access default can be overridden by the project', () => {
})
test('forms: formOverrides.access wins; a read rule on the Emails field wins', async () => {
const config = await ipalKit({
const config = await iapl({
access: { authCollection: 'users' },
forms: {
formOverrides: {
+3 -3
View File
@@ -1,7 +1,7 @@
/**
* 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
* A plugin listed after iapl 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:
*
@@ -26,7 +26,7 @@ import path from 'path'
import { getPayload } from 'payload'
import { expect, test } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer } from './http/server.js'
@@ -131,7 +131,7 @@ export function copyTableSuite(twoFactor: boolean): void {
db: testDatabase(twoFactor ? 'copy_table_2fa' : 'copy_table'),
editor: lexicalEditor(),
plugins: [
ipalKit({
iapl({
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,
+2 -2
View File
@@ -18,7 +18,7 @@ import path from 'path'
import { getPayload } from 'payload'
import { expect, test } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer } from './http/server.js'
@@ -79,7 +79,7 @@ export function adminValueSuite(twoFactor: boolean): void {
db: testDatabase(twoFactor ? 'admin_value_2fa' : 'admin_value'),
editor: lexicalEditor(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users', staffCollections: ['crew', 'agents', 'team', 'late-crew', 'viewers', 'text-roles', 'json-roles', 'late-text', 'rel-roles', ...SINGLE.map((x) => x.slug)] },
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false,
+3 -3
View File
@@ -1,6 +1,6 @@
/**
* A collection of the config that becomes staff LATER (review of the copy rules, L-2): `people` is in the config and
* is not named as staff; a plugin listed after ipalKit sets `admin.user` to it. At config time the plugin saw which
* is not named as staff; a plugin listed after iapl sets `admin.user` to it. At config time the plugin saw which
* operations had a rule of the project's (the marker's `own`); when the collection is handled again at start:
* - an operation that HAD a rule keeps it, exactly as written (here `create`: any signed-in account);
* - an operation that had none gets the plugin's rule (on 1.16.7 a visitor account changed and deleted panel
@@ -16,7 +16,7 @@ import path from 'path'
import { getPayload } from 'payload'
import { expect, test } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer } from './http/server.js'
@@ -39,7 +39,7 @@ export function lateStaffSuite(twoFactor: boolean): void {
db: testDatabase(twoFactor ? 'late_staff_2fa' : 'late_staff'),
editor: lexicalEditor(),
plugins: [
ipalKit({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }),
iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }),
panelIsPeople,
],
secret: 'integration-test-secret-0123456789',
+2 -2
View File
@@ -15,7 +15,7 @@ import { getPayload } from 'payload'
import { expect, test } from 'vitest'
import { staffCollectionsNobodyManages } from '../src/modules/access/selfRegistration.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
@@ -50,7 +50,7 @@ export function nobodyManagesSuite(twoFactor: boolean): void {
db: testDatabase(twoFactor ? 'nobody_2fa' : 'nobody'),
editor: lexicalEditor(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users', staffCollections: [...SHAPES.map((shape) => shape.slug), 'own-rules'] },
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false,
+2 -2
View File
@@ -11,7 +11,7 @@ import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
@@ -36,7 +36,7 @@ beforeAll(async () => {
],
db: testDatabase('accounts_off'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2'] }, accounts: false, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })],
plugins: [iapl({ access: { authCollection: 'users', staffCollections: ['staff2'] }, accounts: false, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
+3 -3
View File
@@ -14,7 +14,7 @@ import { getPayload } from 'payload'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { staffCollectionsOpenToOthers } from '../src/modules/access/selfRegistration.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
@@ -56,7 +56,7 @@ beforeAll(async () => {
],
db: testDatabase('accounts_own_roles'),
editor: lexicalEditor(),
plugins: [ipalKit({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } })],
plugins: [iapl({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
@@ -117,7 +117,7 @@ test('a staff collection that does not exist stops the start, with the slug and
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
db: testDatabase('accounts_ghost'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['ghost-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })],
plugins: [iapl({ access: { authCollection: 'users', staffCollections: ['ghost-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
+3 -3
View File
@@ -1,6 +1,6 @@
/**
* A dev reload (review round 3, R3-2): Payload swaps `payload.config` and runs no onInit. A staff collection that a
* plugin listed after ipalKit adds must keep the account rules on the new config — with 2FA off and on.
* plugin listed after iapl adds must keep the account rules on the new config — with 2FA off and on.
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
*/
import type { Config, Payload, Plugin, SanitizedConfig } from 'payload'
@@ -12,7 +12,7 @@ import path from 'path'
import { getPayload } from 'payload'
import { expect, test } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer } from './http/server.js'
@@ -32,7 +32,7 @@ const makeConfig = (twoFactor: boolean) =>
db: testDatabase(twoFactor ? 'reload_2fa' : 'reload'),
editor: lexicalEditor(),
plugins: [
ipalKit({ access: { authCollection: 'users', staffCollections: ['late-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }),
iapl({ access: { authCollection: 'users', staffCollections: ['late-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }),
late,
],
secret: 'integration-test-secret-0123456789',
+2 -2
View File
@@ -15,7 +15,7 @@ import path from 'path'
import { getPayload } from 'payload'
import { expect, test } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer } from './http/server.js'
@@ -36,7 +36,7 @@ export function singleLoginSuite(twoFactor: boolean): void {
],
db: testDatabase(twoFactor ? 'single_login_2fa' : 'single_login'),
editor: lexicalEditor(),
plugins: [ipalKit({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false })],
plugins: [iapl({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
+13 -13
View File
@@ -23,7 +23,7 @@ import { buildPasswordRuleHook, checkPassword, resolvePasswordRule } from '../sr
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 { iapl } from '../src/plugin.js'
import { buildTestConfig, withTotpParts } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
@@ -31,7 +31,7 @@ import { totp } from './http/totp.js'
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
/** A plugin the project lists AFTER ipalKit: its auth collections did not exist when ipalKit ran (review round 2, R2-3). */
/** A plugin the project lists AFTER iapl: its auth collections did not exist when iapl ran (review round 2, R2-3). */
const latePlugin: Plugin = (config: Config) => ({
...config,
collections: [
@@ -98,7 +98,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
],
db: testDatabase(twoFactor ? 'accounts_2fa' : 'accounts'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2', 'crew', 'agents', 'late-staff'] }, i18n, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), latePlugin],
plugins: [iapl({ access: { authCollection: 'users', staffCollections: ['staff2', 'crew', 'agents', 'late-staff'] }, i18n, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), latePlugin],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
@@ -341,7 +341,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
})
// Review round 2 (R2-3): a staff collection a later plugin adds.
test('a staff collection added by a plugin listed after ipalKit has the same rules', async () => {
test('a staff collection added by a plugin listed after iapl has the same rules', async () => {
// (the first-user spellings above created nothing: counted there)
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['admin'] }, visitor)).status).toBe(403)
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['admin'] }, editor)).status).toBe(403)
@@ -484,7 +484,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect(checkPassword('abcd', { minLength: 4 })).toBeNull()
expect(checkPassword('[email protected] ', { email: '[email protected]', minLength: 4 })).toBe('email')
const hooks = async (options: Record<string, unknown>) =>
(await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, c.hooks?.beforeOperation?.length ?? 0])
(await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, c.hooks?.beforeOperation?.length ?? 0])
expect(await hooks({})).toEqual([['customers', 0], ['users', 1]])
expect(await hooks({ accounts: { password: false } })).toEqual([['customers', 0], ['users', 0]])
expect(await hooks({ accounts: false })).toEqual([['customers', 0], ['users', 0]])
@@ -493,7 +493,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
describe('accounts.panelRole: the config', () => {
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x', ...incoming } as unknown as Config)
iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x', ...incoming } as unknown as Config)
const adminRule = (config: Config) => config.collections!.find((c) => c.slug === 'users')!.access?.admin
test('on by default at editor; a role, false and accounts: false change it', async () => {
@@ -507,7 +507,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect(adminRule(await build({ accounts: { panelRole: false } }))).toBeUndefined()
expect(adminRule(await build({ accounts: false }))).toBeUndefined()
// without `access` there are no roles to ask about
expect(adminRule(await ipalKit({ i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config))).toBeUndefined()
expect(adminRule(await iapl({ i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config))).toBeUndefined()
})
test("the project's own rule wins: on its own collection, and through access.authAccess", async () => {
@@ -537,7 +537,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
describe('accounts.adminOnlyCreate / firstUserRoute: the config', () => {
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2'] }, i18n, twoFactor: false, ...options } as never)({
iapl({ access: { authCollection: 'users', staffCollections: ['staff2'] }, i18n, twoFactor: false, ...options } as never)({
collections: [{ slug: 'staff2', auth: true, fields: [] }, { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, { slug: 'pages', fields: [] }],
secret: 'x',
...incoming,
@@ -646,7 +646,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect(of(noEndpoints, 'staff2').endpoints).toBe(false)
// without `access` the rules still apply to the panel's login collection — as "an account of this collection":
// 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)
const noAccess = await iapl({ i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config)
expect(of(noAccess, 'users').access?.create).toBeTypeOf('function')
expect(await (of(noAccess, 'users').access!.create as (a: unknown) => unknown)({ req: { payload: { staffCollections: ['users'] }, user: { id: 1, collection: 'users' } } })).toBe(true)
})
@@ -685,8 +685,8 @@ export function accountRulesSuite(twoFactor: boolean): void {
test('a config collection that becomes staff later keeps the rules it had at config time', async () => {
const own = ({ req }: { req: { user: unknown } }) => Boolean(req.user)
const rolesField = () => ({ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] })
const { ipalKit } = await import('../src/plugin.js')
const built = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false } as never)({
const { iapl } = await import('../src/plugin.js')
const built = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false } as never)({
admin: { user: 'users' },
collections: [
{ slug: 'users', auth: true, fields: [] },
@@ -775,7 +775,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
// a late auth collection that is not staff: the first-user endpoint only
expect(visitors.access.create).toBe(g)
expect(asIs.access.create).toBe(g)
// what ipalKit saw at config time, and what is not an auth collection: untouched
// what iapl saw at config time, and what is not an auth collection: untouched
expect(seen.access.create).toBe(g)
expect([seen.endpoints.length, pages.endpoints.length]).toEqual([0, 0])
// a second call (a request after the start) changes nothing
@@ -817,7 +817,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
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
// …and marking does not undo IAPL'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([[], []])
+5 -5
View File
@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, test, vi } from 'vitest'
import { buildAdminImageEndpoints } from '../src/modules/branding/adminImages.js'
import { adminMetaForSite, adminMetaStore, buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from '../src/modules/branding/adminMeta.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }
const base = (meta?: Record<string, unknown>): Config =>
@@ -97,7 +97,7 @@ describe('admin meta defaults', () => {
describe('plugin wiring', () => {
test('on by default: meta, endpoints, Site settings hook; agency in the credit', async () => {
const config = await ipalKit({ i18n, twoFactor: false, whiteLabel: true } as never)(base())
const config = await iapl({ i18n, twoFactor: false, whiteLabel: true } as never)(base())
expect(config.admin?.meta?.robots).toEqual({ follow: false, index: false })
const paths = (config.endpoints ?? []).map((e) => e.path)
expect(paths).toEqual(expect.arrayContaining(['/ipal/admin-og', '/ipal/admin-icon']))
@@ -108,7 +108,7 @@ describe('plugin wiring', () => {
})
test('every plugin global afterChange hook resolves with req: {} (no Payload instance)', async () => {
const config = await ipalKit({ cookieScanner: { crawl: true }, i18n, twoFactor: false, whiteLabel: true } as never)(base())
const config = await iapl({ cookieScanner: { crawl: true }, i18n, twoFactor: false, whiteLabel: true } as never)(base())
const calls = (config.globals ?? []).flatMap((g) =>
(g.hooks?.afterChange ?? []).map((h) => h({ context: {}, doc: {}, global: g, previousDoc: {}, req: {} } as never)),
)
@@ -117,14 +117,14 @@ describe('plugin wiring', () => {
})
test('adminMeta: false and agency: false switch the pieces off', async () => {
const config = await ipalKit({ adminMeta: false, agency: false, i18n, twoFactor: false, whiteLabel: true } as never)(base())
const config = await iapl({ adminMeta: false, agency: false, i18n, twoFactor: false, whiteLabel: true } as never)(base())
expect(config.admin?.meta?.robots).toBeUndefined()
expect((config.endpoints ?? []).some((e) => e.path === '/ipal/admin-og')).toBe(false)
expect(config.admin?.components?.afterLogin ?? []).toEqual([])
})
test('a custom agency reaches the credit; whiteLabel.credit text still wins', async () => {
const config = await ipalKit({
const config = await iapl({
agency: { name: 'Studio X', url: 'https://studio.example' },
i18n,
twoFactor: false,
+3 -3
View File
@@ -5,7 +5,7 @@ import { describe, expect, test } from 'vitest'
import { LIBRARY_BLOCK_SLUGS, libraryBlocks } from '../src/exports/blocks.js'
import { applyAdminI18n } from '../src/modules/admin-i18n/apply.js'
import { adminTexts } from '../src/modules/admin-i18n/index.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
/**
* docs/dev/admin-ux.md, enforced: every admin string the plugin adds has an
@@ -45,7 +45,7 @@ const project = (): Config =>
}) as unknown as Config
const fullConfig = () =>
ipalKit({
iapl({
access: { authCollection: 'users' },
consentLog: true,
content: { collections: [{ slug: 'posts' }] },
@@ -149,7 +149,7 @@ function checkCollection(collection: CollectionConfig, problems: Problem[]) {
walk(collection.fields, collection.slug, problems)
}
// Collections the plugin creates; fields of other plugins (form-builder, plugin-seo) are checked where ipal-kit sets them.
// Collections the plugin creates; fields of other plugins (form-builder, plugin-seo) are checked where IAPL sets them.
const PLUGIN_COLLECTIONS = ['consent-records', 'cookie-review', 'stats-visits']
describe('admin wording (docs/dev/admin-ux.md)', () => {
+8 -8
View File
@@ -2,13 +2,13 @@ import type { BasePayload, Config, Field, GlobalConfig, PayloadRequest } from 'p
import { describe, expect, test, vi } from 'vitest'
import { adminDocumentTitle, adminTexts, ipalT } from '../src/modules/admin-i18n/index.js'
import { adminDocumentTitle, adminTexts, iaplT } from '../src/modules/admin-i18n/index.js'
import { buildCookieScanEndpoints } from '../src/modules/consent/scanner/endpoint.js'
import { DEFAULT_COOKIE_INTEGRATIONS, integrationLabel } from '../src/modules/consent/scanner/integrations.js'
import { collectCookieFindings } from '../src/modules/consent/scanner/scan.js'
import { constructionCloseLabel } from '../src/modules/construction/texts.js'
import { faviconProblems } from '../src/modules/seo/faviconProblems.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
@@ -28,8 +28,8 @@ const fakePayload = (integrations: Record<string, unknown> = {}) =>
describe('statistics page title', () => {
test('tab title in the admin language, with the title suffix', () => {
expect(adminDocumentTitle(ipalT(tFor('pl'), 'statsTitle'), '- Payload')).toBe('Statystyki - Payload')
expect(adminDocumentTitle(ipalT(tFor('en'), 'statsTitle'), '- Acme')).toBe('Statistics - Acme')
expect(adminDocumentTitle(iaplT(tFor('pl'), 'statsTitle'), '- Payload')).toBe('Statystyki - Payload')
expect(adminDocumentTitle(iaplT(tFor('en'), 'statsTitle'), '- Acme')).toBe('Statistics - Acme')
expect(adminDocumentTitle('Statystyki', '')).toBe('Statystyki')
})
})
@@ -93,14 +93,14 @@ describe('favicon check', () => {
})
test('warnings read in both admin languages with the size filled in', () => {
expect(ipalT(tFor('en'), 'faviconTooSmall', { height: 32, width: 32 })).toContain('32×32 px')
expect(ipalT(tFor('pl'), 'faviconTooSmall', { height: 32, width: 32 })).toBe('Ikona ma 32×32 px. Google pokazuje ikony od 48×48 px; wgraj większą.')
expect(ipalT(tFor('pl'), 'faviconNotSquare', { height: 96, width: 192 })).toContain('192×96 px')
expect(iaplT(tFor('en'), 'faviconTooSmall', { height: 32, width: 32 })).toContain('32×32 px')
expect(iaplT(tFor('pl'), 'faviconTooSmall', { height: 32, width: 32 })).toBe('Ikona ma 32×32 px. Google pokazuje ikony od 48×48 px; wgraj większą.')
expect(iaplT(tFor('pl'), 'faviconNotSquare', { height: 96, width: 192 })).toContain('192×96 px')
})
test('Site settings shows the check under the site icon', async () => {
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false } as never)({
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false } as never)({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'media', fields: [], upload: true },
+2 -2
View File
@@ -8,7 +8,7 @@ import { parseToolOutput } from '../src/modules/doctor/rules/tooling.js'
import { runDoctor } from '../src/modules/doctor/run.js'
const packageRoot = path.resolve(import.meta.dirname, '..')
const scripts = path.join(packageRoot, 'docs/agent/skills/ipal-audit/scripts')
const scripts = path.join(packageRoot, 'docs/agent/skills/iapl-audit/scripts')
let dirs: string[] = []
function project(files: Record<string, string>): string {
@@ -137,7 +137,7 @@ describe('hardcoded Polish text: public strings are still reported', () => {
})
})
describe('ipal-audit and ipal-doctor agree', () => {
describe('iapl-audit and iapl-doctor agree', () => {
const files = {
'package.json': JSON.stringify({ name: 'examplepl-web' }),
'src/collections/Pages.ts': `${HELPER}export const Pages = { slug: 'pages', fields: [
+3 -3
View File
@@ -277,7 +277,7 @@ describe('styling: every token utility the blocks use exists in the preset', ()
})
})
describe('ipal-blocks eject', () => {
describe('iapl-blocks eject', () => {
const tmp = mkdtempSync(path.join(os.tmpdir(), 'ipal-eject-'))
afterAll(() => rmSync(tmp, { force: true, recursive: true }))
@@ -297,7 +297,7 @@ describe('ipal-blocks eject', () => {
test('every block ejects with imports that exist in the package entries', () => {
const problems: string[] = []
for (const slug of LIBRARY_BLOCK_SLUGS) {
execFileSync('node', [path.join(root, 'bin/ipal-blocks.mjs'), 'eject', slug, '--dest', tmp], { cwd: tmp, stdio: 'pipe' })
execFileSync('node', [path.join(root, 'bin/iapl-blocks.mjs'), 'eject', slug, '--dest', tmp], { cwd: tmp, stdio: 'pipe' })
const dir = path.join(tmp, slug[0].toUpperCase() + slug.slice(1))
for (const file of readdirSync(dir)) {
const src = readFileSync(path.join(dir, file), 'utf8')
@@ -318,7 +318,7 @@ describe('ipal-blocks eject', () => {
})
test('an existing file is never overwritten', () => {
const out = execFileSync('node', [path.join(root, 'bin/ipal-blocks.mjs'), 'eject', 'faq', '--dest', tmp], { cwd: tmp, encoding: 'utf8', stdio: 'pipe' })
const out = execFileSync('node', [path.join(root, 'bin/iapl-blocks.mjs'), 'eject', 'faq', '--dest', tmp], { cwd: tmp, encoding: 'utf8', stdio: 'pipe' })
expect(out).not.toMatch(/^write /m)
})
})
+2 -2
View File
@@ -10,7 +10,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { LIBRARY_BLOCK_SLUGS, libraryBlocks } from '../src/exports/blocks.js'
import { createSeeder } from '../src/exports/seed.js'
import { pageTemplates, systemPageRefs } from '../src/exports/templates.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -54,7 +54,7 @@ describe('block library in Payload', () => {
editor: lexicalEditor(),
localization: { defaultLocale: 'pl', fallback: true, locales: ['pl', 'en'] },
plugins: [
ipalKit({
iapl({
content: { collections: [{ slug: 'posts' }] },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] },
+2 -2
View File
@@ -10,7 +10,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { constructionNoticeHref, isPathAllowed, isPathVisibleIn, normalizePath } from '../src/modules/construction/logic.js'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -45,7 +45,7 @@ describe('under construction — Site Settings → createPageRoute', () => {
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
plugins: [iapl({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'construction-test-secret',
telemetry: false,
})
+3 -3
View File
@@ -18,7 +18,7 @@ import { getConsentTexts, getCookieTable } from '../src/modules/consent/getConse
import { approveCookies, buildCookieApprovalEndpoints, loadCookieApproval } from '../src/modules/consent/scanner/approval.js'
import { nextChange, runCookieScan } from '../src/modules/consent/scanner/scan.js'
import { sameCookie } from '../src/modules/consent/scanner/sync.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -53,7 +53,7 @@ beforeAll(async () => {
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, cookieScanner: true, i18n, stats: true, twoFactor: false })],
plugins: [iapl({ access: { authCollection: 'users' }, cookieScanner: true, i18n, stats: true, twoFactor: false })],
secret: 'cookie-approval-test-secret',
telemetry: false,
}),
@@ -180,7 +180,7 @@ describe('cookie approval against a real Payload', () => {
describe('cookie approval — optional', () => {
const config = (cookieScanner: unknown) =>
ipalKit({ cookieScanner: cookieScanner as never, i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config)
iapl({ cookieScanner: cookieScanner as never, i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config)
test('on by default: the view, its endpoint and the dashboard reminder', async () => {
const c = await config(true)
+2 -2
View File
@@ -20,7 +20,7 @@ import { crawlSite } from '../services/cookie-crawler/crawl.mjs'
import { CookieCrawlAlert } from '../src/modules/consent/scanner/crawl/CookieCrawlAlert.js'
import { buildCookieCrawlEndpoints } from '../src/modules/consent/scanner/crawl/endpoints.js'
import { COOKIE_SCAN_LABELS } from '../src/modules/consent/scanner/labels.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -66,7 +66,7 @@ beforeAll(async () => {
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
cookieScanner: { crawl: crawlOptions(), declarations },
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
+2 -2
View File
@@ -183,8 +183,8 @@ describe('crawl — site side', () => {
test('config: options, then env, then Payload serverURL; short tokens are not a token', () => {
const payload = { config: { serverURL: 'https://acme.pl/' } } as unknown as BasePayload
vi.stubEnv('IPAL_COOKIE_SCAN_URL', 'https://crawler.intecion.net/')
vi.stubEnv('IPAL_COOKIE_SCAN_TOKEN', 'short')
vi.stubEnv('IAPL_COOKIE_SCAN_URL', 'https://crawler.intecion.net/')
vi.stubEnv('IAPL_COOKIE_SCAN_TOKEN', 'short')
const c = resolveCrawlConfig({ maxPages: 500 }, payload)
expect(c).toMatchObject({ maxPages: 100, serviceUrl: 'https://crawler.intecion.net', siteUrl: 'https://acme.pl', token: null })
expect(resolveCrawlConfig({ token: TOKEN, trackerHosts: (d) => [...d, 'chat.example'] }, payload).trackerHosts).toContain('chat.example')
+2 -2
View File
@@ -10,7 +10,7 @@ import { cookieNameMatches, DEFAULT_COOKIE_INTEGRATIONS } from '../src/modules/c
import { COOKIE_SCAN_LABELS, labelFor, labelRecord, mergeCookieScanLabels } from '../src/modules/consent/scanner/labels.js'
import { mergeCookieReview, suggestionFor, textFor } from '../src/modules/consent/scanner/merge.js'
import { collectCookieFindings, parseCookieNames } from '../src/modules/consent/scanner/scan.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
@@ -187,7 +187,7 @@ describe('cookie scanner — labels and config', () => {
})
const run = async (cookieScanner?: unknown) =>
ipalKit({
iapl({
cookieScanner: cookieScanner as never,
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: false,
+2 -2
View File
@@ -13,7 +13,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { buildCookieScanEndpoints } from '../src/modules/consent/scanner/endpoint.js'
import { runCookieScan } from '../src/modules/consent/scanner/scan.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -54,7 +54,7 @@ beforeAll(async () => {
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
cookieScanner: { declarations },
i18n: {
+3 -3
View File
@@ -10,7 +10,7 @@ import { describe, expect, test } from 'vitest'
import { CookieCrawlAlert } from '../src/modules/consent/scanner/crawl/CookieCrawlAlert.js'
import { IntegrationAlerts } from '../src/modules/integrations/IntegrationAlerts.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
const ERROR_TEXT = 'SMTP-ERROR-DETAIL: 535 authentication failed for [email protected]'
const payloadWith = (twoFactor: boolean) => ({
@@ -91,10 +91,10 @@ describe('CookieCrawlAlert', () => {
})
})
describe('ipalKit({ dashboardAlerts })', () => {
describe('iapl({ dashboardAlerts })', () => {
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
const propsOf = async (options: Record<string, unknown>) => {
const config = await ipalKit({ cookieScanner: { crawl: true }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x' } as never)
const config = await iapl({ cookieScanner: { crawl: true }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x' } as never)
return JSON.stringify(config.admin?.components?.beforeDashboard)
}
+11 -11
View File
@@ -12,9 +12,9 @@ import {
defineTokens,
FLUID_SCALE,
fluidClamp,
IPAL_BREAKPOINTS,
IPAL_TOKENS,
ipalVar,
IAPL_BREAKPOINTS,
IAPL_TOKENS,
iaplVar,
parseColor,
resolveColors,
tokensToCss,
@@ -164,21 +164,21 @@ describe('defineTokens / tokensToCss', () => {
})
describe('names', () => {
test('IPAL_TOKENS and ipalVar give var() strings', () => {
expect(IPAL_TOKENS.primary).toBe('var(--ipal-primary)')
expect(IPAL_TOKENS['fs-h1']).toBe('var(--ipal-fs-h1)')
expect(IPAL_TOKENS['surface-dark']).toBe('var(--ipal-surface-dark)')
expect(ipalVar('surface', '#fff')).toBe('var(--ipal-surface, #fff)')
expect(IPAL_BREAKPOINTS.md).toBe(48)
test('IAPL_TOKENS and iaplVar give var() strings', () => {
expect(IAPL_TOKENS.primary).toBe('var(--ipal-primary)')
expect(IAPL_TOKENS['fs-h1']).toBe('var(--ipal-fs-h1)')
expect(IAPL_TOKENS['surface-dark']).toBe('var(--ipal-surface-dark)')
expect(iaplVar('surface', '#fff')).toBe('var(--ipal-surface, #fff)')
expect(IAPL_BREAKPOINTS.md).toBe(48)
})
})
describe('ipal-tokens CLI', () => {
describe('iapl-tokens CLI', () => {
let dir: string
let lines: string[]
const log = (line: string) => lines.push(line)
beforeEach(() => {
dir = mkdtempSync(path.join(tmpdir(), 'ipal-tokens-'))
dir = mkdtempSync(path.join(tmpdir(), 'iapl-tokens-'))
lines = []
})
afterEach(() => rmSync(dir, { force: true, recursive: true }))
+12 -12
View File
@@ -122,15 +122,15 @@ describe('docs ↔ code', () => {
test('every top-level plugin option is documented', () => {
const src = read('src/types.ts')
const body = src.slice(src.indexOf('export type IpalOptions = {'))
const body = src.slice(src.indexOf('export type IaplOptions = {'))
const keys = [...body.matchAll(/^ {2}(\w+)\??:/gm)].map((m) => m[1])
expect(keys.length).toBeGreaterThan(10)
const all = docs.map(read).join('\n')
expect(keys.filter((key) => !new RegExp(`\\b${key}\\b`).test(all))).toEqual([])
})
test('every IPAL_* env var named in the docs is read by the code', () => {
// The plugin, or a script/template shipped in the skills (e.g. IPAL_SEED_ALLOW_PROD_UPDATE).
test('every IAPL_* env var named in the docs is read by the code', () => {
// The plugin, or a script/template shipped in the skills (e.g. IAPL_SEED_ALLOW_PROD_UPDATE).
const shipped = docs.filter((f) => f.startsWith('docs/agent/skills/') && /\.(?:mjs|ts|tsx)$/.test(f))
const code = [...srcFiles(), ...shipped].map(read).join('\n')
const named = new Set([...docs, 'README.md'].flatMap((f) => [...read(f).matchAll(/\bIPAL_[A-Z0-9_]+/g)].map((m) => m[0])))
@@ -185,7 +185,7 @@ describe('docs ↔ code', () => {
expect([...contentHelperNames()].filter((name) => !new RegExp(`\\b${name}\\b`).test(page))).toEqual([])
})
test('install commands never tell projects to add packages ipal-kit already depends on', () => {
test('install commands never tell projects to add packages IAPL already depends on', () => {
const own = Object.keys(JSON.parse(read('package.json')).dependencies)
const offending: string[] = []
for (const file of ['README.md', 'docs/dev/PROGRAMISTA.md']) {
@@ -230,7 +230,7 @@ describe('docs are in English', () => {
})
/**
* The agent guide (AGENT.md + the ipal-* skills copied into projects) is all an agent in a
* The agent guide (AGENT.md + the iapl-* skills copied into projects) is all an agent in a
* consumer project reads. Every export, option and env var must be findable there, or the
* agent re-implements what the plugin already does.
*/
@@ -254,13 +254,13 @@ describe('agent guide covers the whole plugin', () => {
return [...body.matchAll(/^\s+(\w+)\??:/gm)].map((m) => m[1])
}
const keys = [
...typeKeys('src/types.ts', 'IpalOptions'),
...typeKeys('src/types.ts', 'IaplOptions'),
...typeKeys('src/modules/access/types.ts', 'AccessOption'),
...typeKeys('src/modules/content/types.ts', 'ContentCollectionOption'),
...typeKeys('src/modules/content/types.ts', 'ContentOption'),
...typeKeys('src/modules/consent/scanner/types.ts', 'CookieScannerOptions'),
...typeKeys('src/modules/consent/scanner/types.ts', 'CookieCrawlOptions'),
...typeKeys('src/modules/env/ipalEnvRules.ts', 'IpalEnvFeatures'),
...typeKeys('src/modules/env/iaplEnvRules.ts', 'IaplEnvFeatures'),
...typeKeys('src/modules/forms/types.ts', 'FormsOption'),
...typeKeys('src/modules/i18n/types.ts', 'I18nConfig'),
...typeKeys('src/modules/i18n/types.ts', 'LocaleDefinition'),
@@ -285,16 +285,16 @@ describe('agent guide covers the whole plugin', () => {
test('the working rules reach every skill that builds the site', () => {
const agent = read('docs/agent/AGENT.md')
for (const heading of ['## Ask before you build', '## ipal-kit first', '## Code rules']) {expect(agent).toContain(heading)}
const skills = ['ipal-setup', 'ipal-site', 'ipal-block', 'ipal-collection', 'ipal-form']
for (const heading of ['## Ask before you build', '## IAPL first', '## Code rules']) {expect(agent).toContain(heading)}
const skills = ['iapl-setup', 'iapl-site', 'iapl-block', 'iapl-collection', 'iapl-form']
const missing = skills.filter((name) => {
const text = read(`docs/agent/skills/${name}/SKILL.md`)
return !text.includes('ipal-kit first') || !text.includes('Code rules') || !text.includes('ipal-plugin-gap')
return !text.includes('IAPL first') || !text.includes('Code rules') || !text.includes('iapl-plugin-gap')
})
expect(missing).toEqual([])
// Both entry skills start with the architecture questions and wait for the answers.
expect(read('docs/agent/skills/ipal-setup/SKILL.md')).toContain('## 0. Architecture questions')
expect(read('docs/agent/skills/ipal-site/SKILL.md')).toContain('Architecture questions')
expect(read('docs/agent/skills/iapl-setup/SKILL.md')).toContain('## 0. Architecture questions')
expect(read('docs/agent/skills/iapl-site/SKILL.md')).toContain('Architecture questions')
})
test('every @/lib/content helper', () => {
+29 -29
View File
@@ -21,7 +21,7 @@ let dirs: string[] = []
/** A project folder from a { path: content } map; package.json objects are serialised. */
function project(files: Record<string, object | string>): string {
const root = mkdtempSync(path.join(tmpdir(), 'ipal-doctor-'))
const root = mkdtempSync(path.join(tmpdir(), 'iapl-doctor-'))
dirs.push(root)
for (const [rel, content] of Object.entries(files)) {
const file = path.join(root, rel)
@@ -154,18 +154,18 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
const run = async (config: string, only: string[], deepStatus?: object) =>
rules(await doctor(project({ ...base(), 'src/payload.config.ts': config }), only, deepStatus ? { deepStatus } : {}))
test('access-missing: ipalKit without `access` means every account is an admin', async () => {
expect(await run("plugins: [ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: payloadTotp } })]", ['access-missing'])).toEqual(['access-missing:warning'])
test('access-missing: iapl without `access` means every account is an admin', async () => {
expect(await run("plugins: [iapl({ i18n, twoFactor: { issuer: 'A', plugin: payloadTotp } })]", ['access-missing'])).toEqual(['access-missing:warning'])
// a collection's own access rules are not the plugin option
expect(await run("collections: [{ slug: 'pages', access: { read: () => true } }], plugins: [ipalKit({ i18n })]", ['access-missing'])).toEqual(['access-missing:warning'])
for (const ok of ["ipalKit({ access: { authCollection: 'users' }, i18n })", "ipalKit({ i18n, access: { defaultRole: 'editor' } })", 'ipalKit({ access: {}, i18n })', 'ipalKit({ access: accessOptions, i18n })', '// no plugin here']) {
expect(await run("collections: [{ slug: 'pages', access: { read: () => true } }], plugins: [iapl({ i18n })]", ['access-missing'])).toEqual(['access-missing:warning'])
for (const ok of ["iapl({ access: { authCollection: 'users' }, i18n })", "iapl({ i18n, access: { defaultRole: 'editor' } })", 'iapl({ access: {}, i18n })', 'iapl({ access: accessOptions, i18n })', '// no plugin here']) {
expect([ok, await run(`plugins: [${ok}]`, ['access-missing'])]).toEqual([ok, []])
}
})
test('turnstile-degraded: a warning, an error after a day', async () => {
const at = (hoursAgo: number) => new Date(Date.parse(`${TODAY}T12:00:00Z`) - hoursAgo * 3_600_000).toISOString()
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
const cfg = "iapl({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(2), state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(48), state: 'degraded' } })).toEqual(['turnstile-degraded:error'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
@@ -180,7 +180,7 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
})
test('turnstile-env-key: the secret still comes from the environment', async () => {
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
const cfg = "iapl({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['turnstile-env-key'], { turnstileSecretFromEnv: true })).toEqual(['turnstile-env-key:warning'])
expect(await run(cfg, ['turnstile-env-key'], { turnstileSecretFromEnv: false })).toEqual([])
expect(await run(cfg, ['turnstile-env-key'])).toEqual([])
@@ -189,14 +189,14 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
test('csrf-empty: without serverURL and csrf Payload takes the login cookie from any origin', async () => {
// the word is spelled in two parts: test/testConfig.test.ts refuses test files that name Payload's config builder
const build = (body: string) => `export default ${'build'}${'Config'}(${body})`
expect(await run(build("{ plugins: [ipalKit({ access: { authCollection: 'users' } })] }"), ['csrf-empty'])).toEqual(['csrf-empty:warning'])
expect(await run(build("{ plugins: [iapl({ access: { authCollection: 'users' } })] }"), ['csrf-empty'])).toEqual(['csrf-empty:warning'])
expect(await run(build('{ serverURL: process.env.NEXT_PUBLIC_SERVER_URL, plugins: [] }'), ['csrf-empty'])).toEqual([])
expect(await run(build("{ csrf: ['https://site.example'], plugins: [] }"), ['csrf-empty'])).toEqual([])
expect(await run('// not a Payload config', ['csrf-empty'])).toEqual([])
})
test('open-signup: an auth collection anyone can register in is said, as info', async () => {
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
const cfg = "iapl({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['open-signup'], { openSignUp: ['customers', 'members'] })).toEqual(['open-signup:info', 'open-signup:info'])
expect(await run(cfg, ['open-signup'], { openSignUp: [] })).toEqual([])
expect(await run(cfg, ['open-signup'], { openSignUp: null })).toEqual([])
@@ -204,7 +204,7 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
})
test('staff-accounts-open: a staff collection an account of another collection may write to is an error', async () => {
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
const cfg = "iapl({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:delete', 'agents:update', 'users:create'] })).toEqual(['staff-accounts-open:error', 'staff-accounts-open:error', 'staff-accounts-open:error'])
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:read', 'agents:unlock'] })).toEqual(expect.arrayContaining(['staff-accounts-open:warning', 'staff-accounts-open:error']))
expect(await run(cfg, ['staff-own-roles'], { staffOnOwnRoles: ['crew'] })).toEqual(['staff-own-roles:warning'])
@@ -237,7 +237,7 @@ describe('helpers', () => {
expect(parseEnvFile('# c\nA=1\nexport B="two"\n C = \'3\'\nbad line')).toEqual({ A: '1', B: 'two', C: '3' })
})
test('readAuditSkips maps keys to the reason', () => {
const skips = readAuditSkips('- ipal-audit-skip: mcp, twofactor — client decision 2026-10-01\n')
const skips = readAuditSkips('- iapl-audit-skip: mcp, twofactor — client decision 2026-10-01\n')
expect(skips.get('mcp')).toBe('client decision 2026-10-01')
expect(skips.get('twofactor')).toBe('client decision 2026-10-01')
})
@@ -250,7 +250,7 @@ describe('helpers', () => {
expect(globToRegExp('src/*.ts').test('src/a/b.ts')).toBe(false)
})
test('parseToolOutput reads the [LEVEL] title (n) — rule blocks of audit.sh and seo-check', () => {
const lines = parseToolOutput('ipal-audit\n\n[ERROR] hex colors in classes (2) — §6.11 tokens\n src/a.tsx:1: bg-[#fff]\n src/b.tsx:2: x\n[INFO] note — fine\n')
const lines = parseToolOutput('iapl-audit\n\n[ERROR] hex colors in classes (2) — §6.11 tokens\n src/a.tsx:1: bg-[#fff]\n src/b.tsx:2: x\n[INFO] note — fine\n')
expect(lines).toEqual([
{ items: ['src/a.tsx:1: bg-[#fff]', 'src/b.tsx:2: x'], level: 'error', rule: '§6.11 tokens', title: 'hex colors in classes' },
{ items: [], level: 'info', rule: 'fine', title: 'note' },
@@ -263,7 +263,7 @@ describe('helpers', () => {
})
})
describe('ipal-audit through the doctor', () => {
describe('iapl-audit through the doctor', () => {
const site = (contentTs: string) =>
project({ ...base(), 'src/lib/content.ts': contentTs, 'src/payload.config.ts': "import { payloadTotp } from '@clocklimited/payload-2fa'\n" })
const aiBots = async (root: string) => (await doctor(root, ['audit'])).findings.filter((f) => f.rule === 'audit:robots-blocks-ai-bots')
@@ -350,10 +350,10 @@ describe('versions', () => {
describe('db-name', () => {
const env = (dev: string, example = dev) => ({ ...base(), '.env': `DATABASE_URI=mongodb://127.0.0.1:27017/${dev}\n`, '.env.example': `DATABASE_URI=mongodb://USER:PASS@HOST:PORT/${example}?authSource=admin\n` })
test('<domain without dots>_dev passes', async () => {
expect(rules(await doctor(project({ ...env('examplepl_dev'), 'ipal-doctor.json': { domain: 'example.pl' } }), ['db-name']))).toEqual([])
expect(rules(await doctor(project({ ...env('examplepl_dev'), 'iapl-doctor.json': { domain: 'example.pl' } }), ['db-name']))).toEqual([])
})
test('a local .env on _prod is an error, another name too', async () => {
const report = await doctor(project({ ...env('examplepl_prod', 'dev'), 'ipal-doctor.json': { domain: 'example.pl' } }), ['db-name'])
const report = await doctor(project({ ...env('examplepl_prod', 'dev'), 'iapl-doctor.json': { domain: 'example.pl' } }), ['db-name'])
expect(report.findings.map((f) => f.message)).toEqual([
'.env points at the production database examplepl_prod — a local run or seed writes to production',
'.env.example: database "dev", expected examplepl_dev',
@@ -413,7 +413,7 @@ describe('layout, blocks, seeds, agents', () => {
expect(report.findings[0].message).toContain('src/proxy.ts')
})
test('layout.allow extends the src/ allow list; an audit skip drops its file', async () => {
const root = project({ ...base(), 'AGENTS.md': '## Project decisions\n- ipal-audit-skip: mcp — client decision\n', 'src/scripts/x.ts': '' })
const root = project({ ...base(), 'AGENTS.md': '## Project decisions\n- iapl-audit-skip: mcp — client decision\n', 'src/scripts/x.ts': '' })
const report = await doctor(root, ['layout-required', 'layout-extra'], { config: { layout: { allow: ['scripts'] } } })
expect(report.findings.map((f) => f.rule)).toEqual(['layout-required'])
expect(report.findings[0].message).not.toContain('api/mcp')
@@ -459,7 +459,7 @@ describe('layout, blocks, seeds, agents', () => {
test('seeds: helper, no deletes, no fresh script, guard on; after launch a record list', async () => {
const files = {
...base(),
'package.json': pkgJson({ scripts: { seed: 'payload run src/seed/index.ts', 'seed:fresh': 'payload run src/seed/old.ts', 'seed:full': 'IPAL_SEED_ALLOW_FULL=1 payload run src/seed/index.ts' } }),
'package.json': pkgJson({ scripts: { seed: 'payload run src/seed/index.ts', 'seed:fresh': 'payload run src/seed/old.ts', 'seed:full': 'IAPL_SEED_ALLOW_FULL=1 payload run src/seed/index.ts' } }),
'src/seed/index.ts': "import { pages } from './pages'\nconst seed = createSeeder(payload)",
'src/seed/old.ts': 'await payload.delete({ collection: "pages" })',
'src/seed/pages.ts': 'export const pages = []',
@@ -467,19 +467,19 @@ describe('layout, blocks, seeds, agents', () => {
expect(rules(await doctor(project(files), ['seed-named']))).toEqual([
'seed-named:error', // seed:fresh name
'seed-named:error', // old.ts deletes
'seed-named:error', // IPAL_SEED_ALLOW_FULL=1 in seed:full
'seed-named:error', // IAPL_SEED_ALLOW_FULL=1 in seed:full
'seed-named:warning', // old.ts without the helper (errors sort first)
])
const launched = await doctor(project({ ...files, 'package.json': pkgJson({ scripts: { seed: 'payload run src/seed/index.ts' } }) }), ['seed-named'], { config: { launched: true } })
expect(launched.findings.map((f) => f.message)).toEqual(['script "seed" has no record list — after launch every run needs SEED_ONLY'])
})
test('AGENTS.md needs a non-empty "Project decisions" and the pointer for the installed version', async () => {
const pointer = '<!-- ipal-kit:start -->\n## ipal-kit 1.14.6 — agent guide\n<!-- ipal-kit:end -->'
const pointer = '<!-- iapl:start -->\n## IAPL 1.14.6 — agent guide\n<!-- iapl:end -->'
expect(rules(await doctor(project({ ...base(), 'AGENTS.md': `# x\n${pointer}`, 'CLAUDE.md': '@AGENTS.md\n' }), ['agents-md']))).toEqual(['agents-md:error'])
expect(rules(await doctor(project({ ...base(), 'AGENTS.md': `## Project decisions\n<!-- todo -->\n${pointer}`, 'CLAUDE.md': '@AGENTS.md\n' }), ['agents-md']))).toEqual(['agents-md:warning'])
expect(rules(await doctor(project({ ...base(), 'AGENTS.md': `## Project decisions\n- pl only\n${pointer}`, 'CLAUDE.md': '@AGENTS.md\n' }), ['agents-md']))).toEqual([])
})
test('planSkills: missing, stale and retired ipal-* folders', () => {
test('planSkills: missing, stale and retired iapl-* folders', () => {
const source = project({ 'ipal-a/SKILL.md': 'a', 'ipal-b/SKILL.md': 'b' })
const dest = project({ 'ipal-b/SKILL.md': 'old', 'ipal-old/SKILL.md': 'x', 'mine/SKILL.md': 'own' })
expect(planSkills({ dest, source })).toEqual({ missing: ['ipal-a'], retired: ['ipal-old'], stale: ['ipal-b'] })
@@ -538,7 +538,7 @@ describe('security and deep status', () => {
const payload = { config: { admin: { user: 'users' }, collections: [] }, count: vi.fn() }
const call = (auth?: string) => endpoint.handler({ headers: new Headers(auth ? { authorization: auth, 'x-forwarded-for': '1.2.3.4' } : {}), payload } as never) as Promise<Response>
expect((await call()).status).toBe(404)
vi.stubEnv('IPAL_DOCTOR_TOKEN', 'x'.repeat(40))
vi.stubEnv('IAPL_DOCTOR_TOKEN', 'x'.repeat(40))
expect((await call('Bearer wrong')).status).toBe(401)
const ok = await call(`Bearer ${'x'.repeat(40)}`)
expect(ok.status).toBe(200)
@@ -546,7 +546,7 @@ describe('security and deep status', () => {
})
})
describe('silencing (ipal-doctor.json)', () => {
describe('silencing (iapl-doctor.json)', () => {
const noAgents = () => project(base())
test('off with a reason silences (kept in the report); without a reason it is ignored and reported', async () => {
const silenced = await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { off: true, reason: 'demo' } } } })
@@ -555,11 +555,11 @@ describe('silencing (ipal-doctor.json)', () => {
const noReason = await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { off: true } } } })
expect(rules(noReason)).toEqual(['doctor-config:error', 'agents-md:error'])
})
test('severity override, expired until, files filter, ipal-audit-skip', async () => {
test('severity override, expired until, files filter, iapl-audit-skip', async () => {
expect(rules(await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { reason: 'r', severity: 'info' } } } }))).toEqual(['agents-md:info'])
expect(rules(await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { off: true, reason: 'r', until: '2026-10-01' } } } }))).toEqual(['agents-md:error', 'doctor-config:warning'])
expect(rules(await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { files: ['src/**'], off: true, reason: 'r' } } } }))).toEqual(['agents-md:error'])
const skip = project({ ...base(), 'AGENTS.md': '- ipal-audit-skip: twofactor — the client signs in with SSO\n', 'src/payload.config.ts': '' })
const skip = project({ ...base(), 'AGENTS.md': '- iapl-audit-skip: twofactor — the client signs in with SSO\n', 'src/payload.config.ts': '' })
expect((await doctor(skip, ['2fa'])).findings[0]).toMatchObject({ reason: 'the client signs in with SSO', silenced: true })
})
})
@@ -595,7 +595,7 @@ describe('live (--url)', () => {
})
describe('CLI', () => {
const clean = () => project({ ...base(), 'AGENTS.md': '## Project decisions\n- x\n<!-- ipal-kit:start -->\n## ipal-kit 1.14.6 — agent guide\n<!-- ipal-kit:end -->', 'CLAUDE.md': '@AGENTS.md\n' })
const clean = () => project({ ...base(), 'AGENTS.md': '## Project decisions\n- x\n<!-- iapl:start -->\n## IAPL 1.14.6 — agent guide\n<!-- iapl:end -->', 'CLAUDE.md': '@AGENTS.md\n' })
const cli = async (args: string[], cwd: string) => {
const out: string[] = []
const code = await runDoctorCli(args, { cwd, log: (l) => out.push(l), packageRoot })
@@ -613,7 +613,7 @@ describe('CLI', () => {
expect((await cli([info, '--offline', '--only', 'versions'], info)).code).toBe(0)
expect((await cli([info, '--offline', '--only', 'versions', '--strict'], info)).code).toBe(1)
expect((await cli([project({ 'x.txt': '' })], packageRoot)).code).toBe(2)
const bad = project({ ...base(), 'ipal-doctor.json': '{ nope' })
const bad = project({ ...base(), 'iapl-doctor.json': '{ nope' })
expect((await cli([bad, '--offline', '--only', 'versions'], bad)).code).toBe(2)
})
test('--json is schema 1 with a summary; the human report lists fix and docs', async () => {
@@ -644,13 +644,13 @@ describe('CLI', () => {
})
describe('the reference site', () => {
test('reference/ipal-doctor.json silences only with reasons', () => {
const config = JSON.parse(readFileSync(path.join(packageRoot, 'reference/ipal-doctor.json'), 'utf8')) as DoctorConfig
test('reference/iapl-doctor.json silences only with reasons', () => {
const config = JSON.parse(readFileSync(path.join(packageRoot, 'reference/iapl-doctor.json'), 'utf8')) as DoctorConfig
for (const setting of Object.values(config.rules ?? {})) {expect(setting.reason?.trim()).toBeTruthy()}
})
})
describe('ipal-doctor: first-seen dates', () => {
describe('iapl-doctor: first-seen dates', () => {
test('are written only outside CI, and never with --json or --sites', () => {
expect(shouldWriteSeen({}, {})).toBe(true)
expect(shouldWriteSeen({}, { CI: 'true' })).toBe(false)
+2 -2
View File
@@ -10,7 +10,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import { resolveRoute } from '../src/modules/content/resolveRoute.js'
import { buildNoindexField } from '../src/modules/seo/buildNoindexField.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
let payload: Payload
@@ -33,7 +33,7 @@ beforeAll(async () => {
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
content: { collections: [{ slug: 'posts' }] },
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
+15 -15
View File
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest'
import { assertEnv } from '../src/modules/env/assertEnv.js'
import { checkDatabaseName, databaseNameFromUri, databaseNamesFor } from '../src/modules/env/databaseName.js'
import { ipalEnvRules } from '../src/modules/env/ipalEnvRules.js'
import { iaplEnvRules } from '../src/modules/env/iaplEnvRules.js'
const base = { DATABASE_URI: 'mongodb://db/x', NEXT_PUBLIC_SERVER_URL: 'http://localhost:3000', PAYLOAD_SECRET: 'a-long-random-test-secret-of-32-chars' }
const r2 = {
@@ -13,15 +13,15 @@ const r2 = {
R2_SECRET_ACCESS_KEY: 's',
}
function check(env: Record<string, string>, storage: NonNullable<Parameters<typeof ipalEnvRules>[0]>['storage'] = true) {
function check(env: Record<string, string>, storage: NonNullable<Parameters<typeof iaplEnvRules>[0]>['storage'] = true) {
vi.unstubAllEnvs()
for (const [k, v] of Object.entries(env)) {vi.stubEnv(k, v)}
return () => assertEnv(ipalEnvRules({ storage }), { env })
return () => assertEnv(iaplEnvRules({ storage }), { env })
}
afterEach(() => vi.unstubAllEnvs())
describe('ipalEnvRules({ storage })', () => {
describe('iaplEnvRules({ storage })', () => {
test('production: every R2_* is required', () => {
expect(check({ ...base, NODE_ENV: 'production' })).toThrow(/R2_BUCKET is required/)
expect(check({ ...base, ...r2, NODE_ENV: 'production' })).not.toThrow()
@@ -75,17 +75,17 @@ describe('database naming rule', () => {
expect(checkDatabaseName({ databaseUri: 'postgres://db/payload' })).toBeNull()
})
test('ipalEnvRules({ databaseName }) only warns — assertEnv still passes', () => {
test('iaplEnvRules({ databaseName }) only warns — assertEnv still passes', () => {
const warn = vi.fn()
const env = { DATABASE_URI: 'mongodb://mongo/payload', NEXT_PUBLIC_SERVER_URL: 'https://intecion.com', PAYLOAD_SECRET: 's' }
expect(() => assertEnv(ipalEnvRules({ databaseName: { domain: 'intecion.com', warn } }), { env })).not.toThrow()
expect(() => assertEnv(iaplEnvRules({ databaseName: { domain: 'intecion.com', warn } }), { env })).not.toThrow()
expect(warn).toHaveBeenCalledWith(expect.stringMatching(/DATABASE_URI: database "payload"[\s\S]*intecioncom_prod/))
warn.mockClear()
assertEnv(ipalEnvRules({ databaseName: { domain: 'www.intecion.com', warn } }), { env: { ...env, DATABASE_URI: 'mongodb://mongo/intecioncom_dev' } })
assertEnv(iaplEnvRules({ databaseName: { domain: 'www.intecion.com', warn } }), { env: { ...env, DATABASE_URI: 'mongodb://mongo/intecioncom_dev' } })
expect(warn).not.toHaveBeenCalled()
// true: the domain comes from NEXT_PUBLIC_SERVER_URL in process.env
vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://architektimprez.pl')
assertEnv(ipalEnvRules({ databaseName: { warn } }), { env: { ...env, DATABASE_URI: 'postgres://db/architektimprez_prod' } })
assertEnv(iaplEnvRules({ databaseName: { warn } }), { env: { ...env, DATABASE_URI: 'postgres://db/architektimprez_prod' } })
expect(warn).toHaveBeenCalledWith(expect.stringMatching(/expected "architektimprezpl_prod"/))
vi.unstubAllEnvs()
})
@@ -97,20 +97,20 @@ describe('PAYLOAD_SECRET minimum length', () => {
test('a short secret fails in production', () => {
vi.stubEnv('NODE_ENV', 'production')
expect(() => assertEnv(ipalEnvRules(), { env })).toThrow(/PAYLOAD_SECRET must be at least 32 characters in production \(got 12\)/)
expect(() => assertEnv(ipalEnvRules(), { env: { ...env, PAYLOAD_SECRET: 'x'.repeat(32) } })).not.toThrow()
expect(() => assertEnv(iaplEnvRules(), { env })).toThrow(/PAYLOAD_SECRET must be at least 32 characters in production \(got 12\)/)
expect(() => assertEnv(iaplEnvRules(), { env: { ...env, PAYLOAD_SECRET: 'x'.repeat(32) } })).not.toThrow()
})
test('a short secret passes outside production', () => {
vi.stubEnv('NODE_ENV', 'development')
expect(() => assertEnv(ipalEnvRules(), { env })).not.toThrow()
expect(() => assertEnv(iaplEnvRules(), { env })).not.toThrow()
})
test('secretMinLength: 0 turns the check off; a custom minimum is used', () => {
vi.stubEnv('NODE_ENV', 'production')
expect(() => assertEnv(ipalEnvRules({ secretMinLength: 0 }), { env })).not.toThrow()
expect(() => assertEnv(ipalEnvRules({ secretMinLength: 64 }), { env: { ...env, PAYLOAD_SECRET: 'x'.repeat(40) } })).toThrow(/at least 64 characters/)
expect(() => assertEnv(ipalEnvRules({ secretMinLength: 8 }), { env })).not.toThrow()
expect(() => assertEnv(ipalEnvRules({ secretVar: 'MY_SECRET' }), { env: { ...env, MY_SECRET: 'short' } })).toThrow(/MY_SECRET must be at least 32/)
expect(() => assertEnv(iaplEnvRules({ secretMinLength: 0 }), { env })).not.toThrow()
expect(() => assertEnv(iaplEnvRules({ secretMinLength: 64 }), { env: { ...env, PAYLOAD_SECRET: 'x'.repeat(40) } })).toThrow(/at least 64 characters/)
expect(() => assertEnv(iaplEnvRules({ secretMinLength: 8 }), { env })).not.toThrow()
expect(() => assertEnv(iaplEnvRules({ secretVar: 'MY_SECRET' }), { env: { ...env, MY_SECRET: 'short' } })).toThrow(/MY_SECRET must be at least 32/)
})
})
+6 -6
View File
@@ -1,6 +1,6 @@
/**
* Third-party agent skills vendored into the package (docs/agent/external) and installed by
* `ipal-skills --external`. They are pinned, text-only and carry their licence; the installer
* `iapl-skills --external`. They are pinned, text-only and carry their licence; the installer
* downloads nothing and leaves the project's own skill folders alone.
*/
import { execFileSync } from 'node:child_process'
@@ -47,7 +47,7 @@ describe('vendored external skills', () => {
})
test('the installer downloads nothing', () => {
const bin = read(path.join(root, 'bin/ipal-skills.mjs'))
const bin = read(path.join(root, 'bin/iapl-skills.mjs'))
expect(bin).not.toMatch(/https?:\/\/|\bfetch\(|child_process|execFile|spawn/)
})
@@ -80,12 +80,12 @@ describe('vendored external skills', () => {
})
})
describe('ipal-skills --external', () => {
describe('iapl-skills --external', () => {
const work = mkdtempSync(path.join(tmpdir(), 'ipal-ext-test-'))
afterAll(() => rmSync(work, { force: true, recursive: true }))
const skillsDir = path.join(work, '.agents/skills')
const run = (...args: string[]) =>
execFileSync('node', [path.join(root, 'bin/ipal-skills.mjs'), '--no-pointer', ...args], { cwd: work, encoding: 'utf8' })
execFileSync('node', [path.join(root, 'bin/iapl-skills.mjs'), '--no-pointer', ...args], { cwd: work, encoding: 'utf8' })
const names = () => readdirSync(skillsDir).sort()
test('adds ext-* only on request and leaves the project\'s own folders alone', () => {
@@ -103,7 +103,7 @@ describe('ipal-skills --external', () => {
expect(read(path.join(skillsDir, 'ext-mine/SKILL.md'))).toBe('own ext')
})
test('removes only retired ext-* folders that ipal-kit installed', () => {
test('removes only retired ext-* folders that IAPL installed', () => {
const retired = path.join(skillsDir, 'ext-retired')
mkdirSync(retired)
cpSync(path.join(extDir, manifest.skills[0].name, 'SOURCE.md'), path.join(retired, 'SOURCE.md'))
@@ -115,7 +115,7 @@ describe('ipal-skills --external', () => {
test('an unknown name stops the run before anything is copied', () => {
const empty = mkdtempSync(path.join(work, 'empty-'))
expect(() =>
execFileSync('node', [path.join(root, 'bin/ipal-skills.mjs'), '--no-pointer', '--external', 'ext-nope'], { cwd: empty, stdio: 'pipe' }),
execFileSync('node', [path.join(root, 'bin/iapl-skills.mjs'), '--no-pointer', '--external', 'ext-nope'], { cwd: empty, stdio: 'pipe' }),
).toThrow()
expect(readdirSync(empty)).toEqual([])
})
+3 -3
View File
@@ -16,7 +16,7 @@ import type { I18nConfig } from '../src/modules/i18n/types.js'
import { suggestionFor } from '../src/modules/consent/scanner/merge.js'
import { addToCookieList } from '../src/modules/consent/scanner/sync.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -48,7 +48,7 @@ beforeAll(async () => {
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, cookieScanner: true, i18n, twoFactor: false })],
plugins: [iapl({ access: { authCollection: 'users' }, cookieScanner: true, i18n, twoFactor: false })],
secret: 'fill-locales-test-secret',
telemetry: false,
}),
@@ -106,7 +106,7 @@ describe('fill empty locales — cookie review', () => {
describe('options', () => {
const build = (extra: Record<string, unknown>) =>
ipalKit({ i18n, twoFactor: false, ...extra } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config)
iapl({ i18n, twoFactor: false, ...extra } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config)
const global = (c: Config, slug: string) => c.globals!.find((g) => g.slug === slug)!
const tabs = (g: GlobalConfig) => (g.fields.find((f) => f.type === 'tabs') as { tabs: Tab[] } & Field).tabs
+4 -4
View File
@@ -22,7 +22,7 @@ import type { FormFileScanInput } from '../src/modules/forms/attachments/config.
import { getFormAttachments } from '../src/modules/forms/attachments/config.js'
import { formSubmitState, handleFormSubmit } from '../src/modules/forms/attachments/submitHandler.js'
import { submitForm } from '../src/modules/forms/submitForm.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -131,7 +131,7 @@ beforeAll(async () => {
editor: lexicalEditor(),
email: recordingMail,
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
forms: {
attachments: {
@@ -499,7 +499,7 @@ describe('5 · nothing is stored, nothing can be downloaded', () => {
collections: [{ slug: 'users', auth: true, fields: [] }, { slug: 'media', fields: [], upload: true }],
db: sqliteAdapter({ client: { url: 'file::memory:' } }),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, twoFactor: false })],
plugins: [iapl({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, twoFactor: false })],
secret: 'x',
})
const forms = plain.collections.find((c) => c.slug === 'forms')!
@@ -725,7 +725,7 @@ describe('options a project can set', () => {
},
}),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
forms: {
attachments: {
+2 -2
View File
@@ -11,7 +11,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { LIBRARY_BLOCK_SLUGS, libraryBlocks } from '../src/exports/blocks.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -78,7 +78,7 @@ const fullConfig = () =>
buildTestConfig({
...project(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
consentLog: true,
content: { collections: [{ slug: 'posts' }] },
+1 -1
View File
@@ -14,7 +14,7 @@ export const buildTestConfig = (config: Config) =>
buildConfig({ ...config, typescript: { ...config.typescript, autoGenerate: false } })
/**
* The parts of @clocklimited/payload-2fa that ipalKit checks for after the injected factory ran
* The parts of @clocklimited/payload-2fa that iapl checks for after the injected factory ran
* (missingTotpParts): the two fields and the `totp` strategy on the target collection.
* A fake 2FA factory in a test wraps its config in this.
*/
+2 -2
View File
@@ -75,8 +75,8 @@ describe('IndexNow hook', () => {
expect(fetchSpy).not.toHaveBeenCalled()
})
test('staging copy (IPAL_NOINDEX) sends nothing even in production', async () => {
vi.stubEnv('IPAL_NOINDEX', '1')
test('staging copy (IAPL_NOINDEX) sends nothing even in production', async () => {
vi.stubEnv('IAPL_NOINDEX', '1')
await run({ _status: 'published' })
expect(fetchSpy).not.toHaveBeenCalled()
})
+2 -2
View File
@@ -17,7 +17,7 @@ import { getConsentTexts, getCookieTable } from '../src/modules/consent/getConse
import { submitForm } from '../src/modules/forms/submitForm.js'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -44,7 +44,7 @@ beforeAll(async () => {
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
consentLog: true,
forms: {},
+3 -3
View File
@@ -5,7 +5,7 @@
import { afterEach, describe, expect, test, vi } from 'vitest'
import { passTurnstile, resolveTurnstileOnConfigError, TURNSTILE_ON_CONFIG_ERROR_DEFAULT } from '../src/modules/forms/submitForm.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
@@ -97,10 +97,10 @@ describe('forms.turnstileOnConfigError', () => {
expect(fetchMock).not.toHaveBeenCalled()
})
test('ipalKit carries the option to where the gate reads it', async () => {
test('iapl carries the option to where the gate reads it', async () => {
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
const build = async (forms: Record<string, unknown>) =>
((await ipalKit({ forms, i18n, twoFactor: false } as never)({ collections: [], secret: 'x' } as never)).custom as { ipal?: { forms?: { turnstileOnConfigError?: unknown } } }).ipal?.forms?.turnstileOnConfigError
((await iapl({ forms, i18n, twoFactor: false } as never)({ collections: [], secret: 'x' } as never)).custom as { ipal?: { forms?: { turnstileOnConfigError?: unknown } } }).ipal?.forms?.turnstileOnConfigError
expect(await build({})).toBeUndefined()
expect(await build({ turnstileOnConfigError: 'reject' })).toBe('reject')
expect(await build({ turnstileOnConfigError: { files: 'allow' } })).toEqual({ files: 'allow' })
+21 -21
View File
@@ -4,7 +4,7 @@ import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = {
@@ -21,9 +21,9 @@ const base = (): Config =>
secret: 'test',
}) as unknown as Config
describe('ipalKit — config transform', () => {
describe('iapl — config transform', () => {
test('adds globals, endpoint, localization and roles', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(base())
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']),
@@ -36,18 +36,18 @@ describe('ipalKit — config transform', () => {
})
test('enforces 2FA unless explicitly disabled', async () => {
await expect(ipalKit({ i18n } as never)(base())).rejects.toThrow(/twoFactor\.issuer is required/)
await expect(ipalKit({ i18n, twoFactor: { issuer: 'Acme' } } as never)(base())).rejects.toThrow(
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 ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: totp as never } })(base())
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 ipalKit({ access: { authCollection: 'users' }, consentLog: true, enabled: false, i18n, stats: true, twoFactor: false })(base())
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([])
@@ -56,18 +56,18 @@ describe('ipalKit — config transform', () => {
})
test('forms.consentFieldName reaches submitForm through config.custom.ipal', async () => {
const config = await ipalKit({ forms: { consentFieldName: 'zgoda' }, i18n, twoFactor: false })(base())
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(() => ipalKit({ i18n: { defaultLocale: 'de', locales: i18n.locales }, twoFactor: false })).toThrow()
expect(() => iapl({ i18n: { defaultLocale: 'de', locales: i18n.locales }, twoFactor: false })).toThrow()
})
})
describe('ipalKit — auth collection', () => {
describe('iapl — auth collection', () => {
test('injects a users auth collection when the project has none, with roles', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })({
collections: [],
secret: 'x',
} as unknown as Config)
@@ -78,7 +78,7 @@ describe('ipalKit — auth collection', () => {
test("keeps the project's own users collection", async () => {
const own = { slug: 'users', auth: true, fields: [{ name: 'fullName', type: 'text' }] }
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })({
collections: [own],
secret: 'x',
} as unknown as Config)
@@ -108,17 +108,17 @@ describe('options that keep features reachable and overridable', () => {
}) as unknown as Config
test('seo.uploadsCollection: the meta image relates to the given upload collection (default media)', async () => {
const custom = await ipalKit({ i18n, seo: { collections: ['pages'], uploadsCollection: 'images' }, twoFactor: false })(withPages())
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 ipalKit({ i18n, seo: { collections: ['pages'] }, twoFactor: false })(withPages())
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 ipalKit({ consentLog: true, forms: {}, i18n, stats: true, twoFactor: false })(base())
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
@@ -135,7 +135,7 @@ describe('options that keep features reachable and overridable', () => {
})
test('with `access` the roles still decide', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, stats: true, twoFactor: false })(base())
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
@@ -154,12 +154,12 @@ describe('gap fixes: searchSettings, collection overrides', () => {
}
test('searchSettings: false removes the Search engines tab without `seo`', async () => {
expect(tabsOf(await ipalKit({ i18n, twoFactor: false })(base()))).toContain('Search engines')
expect(tabsOf(await ipalKit({ i18n, searchSettings: false, twoFactor: false })(base()))).not.toContain('Search engines')
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 ipalKit({
const config = await iapl({
i18n,
searchSettings: (fields) => fields.filter((f) => 'name' in f && f.name === 'llmsIntro'),
seo: { collections: [], searchSettings: false },
@@ -171,12 +171,12 @@ describe('gap fixes: searchSettings, collection overrides', () => {
)!
expect(tab.fields.map((f) => f.name)).toEqual(['llmsIntro'])
// the older seo.searchSettings still works alone
expect(tabsOf(await ipalKit({ i18n, seo: { collections: [], searchSettings: false }, twoFactor: false })(base()))).not.toContain('Search engines')
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 ipalKit({
const config = await iapl({
consentLog: { collectionOverrides: { access: { read: dpoOnly as never }, admin: { group: 'Privacy' } } },
i18n,
stats: { collectionOverrides: (c) => ({ ...c, labels: { plural: 'Visits', singular: 'Visit' } }) },
+8 -8
View File
@@ -34,8 +34,8 @@ describe('clientIp', () => {
expect(clientIp(r, { header: 'x-client-ip' })).toBe('')
})
test('IPAL_IP_HEADER env pins the header', () => {
vi.stubEnv('IPAL_IP_HEADER', 'x-forwarded-for')
test('IAPL_IP_HEADER env pins the header', () => {
vi.stubEnv('IAPL_IP_HEADER', 'x-forwarded-for')
expect(clientIp(req({ 'cf-connecting-ip': '1.1.1.1', 'x-forwarded-for': '6.6.6.6, 4.4.4.4' }))).toBe('4.4.4.4')
})
@@ -107,20 +107,20 @@ describe('consumeRateLimit', () => {
})
})
describe('IPAL_IP_HEADER', () => {
describe('IAPL_IP_HEADER', () => {
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
test('ipalEnvRules({ ipHeader }) requires it in production only', async () => {
test('iaplEnvRules({ ipHeader }) requires it in production only', async () => {
const { assertEnv } = await import('../src/modules/env/assertEnv.js')
const { ipalEnvRules } = await import('../src/modules/env/ipalEnvRules.js')
const { iaplEnvRules } = await import('../src/modules/env/iaplEnvRules.js')
const base = { DATABASE_URI: 'x', NEXT_PUBLIC_SERVER_URL: 'https://acme.pl', PAYLOAD_SECRET: 'a-long-random-test-secret-of-32-chars' }
vi.stubEnv('NODE_ENV', 'production')
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: base })).toThrow(/IPAL_IP_HEADER/)
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: { ...base, IPAL_IP_HEADER: 'cf-connecting-ip' } })).not.toThrow()
expect(() => assertEnv(iaplEnvRules({ ipHeader: true }), { env: base })).toThrow(/IAPL_IP_HEADER/)
expect(() => assertEnv(iaplEnvRules({ ipHeader: true }), { env: { ...base, IAPL_IP_HEADER: 'cf-connecting-ip' } })).not.toThrow()
vi.stubEnv('NODE_ENV', 'development')
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: base })).not.toThrow()
expect(() => assertEnv(iaplEnvRules({ ipHeader: true }), { env: base })).not.toThrow()
})
})
+3 -3
View File
@@ -3,7 +3,7 @@ import type { Config, GlobalConfig } from 'payload'
import { afterEach, describe, expect, test, vi } from 'vitest'
import { buildGlobalRevalidateHook } from '../src/modules/hooks/buildRevalidateHook.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const
const run = (g: GlobalConfig | undefined, context: object = {}) =>
@@ -12,10 +12,10 @@ const run = (g: GlobalConfig | undefined, context: object = {}) =>
describe('globals revalidate the site layout on save', () => {
afterEach(() => vi.unstubAllEnvs())
test('ipalKit({ revalidatePath }) wires every plugin global', async () => {
test('iapl({ revalidatePath }) wires every plugin global', async () => {
vi.stubEnv('NEXT_RUNTIME', 'nodejs')
const revalidatePath = vi.fn()
const config = await ipalKit({ i18n, revalidatePath, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config)
const config = await iapl({ i18n, revalidatePath, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config)
for (const slug of ['site-settings', 'site-integrations', 'cookie-settings', 'notifications']) {
revalidatePath.mockClear()
run(config.globals?.find((g) => g.slug === slug))
+18 -18
View File
@@ -14,7 +14,7 @@ import type { I18nConfig } from '../src/modules/i18n/types.js'
import { findImportMapFile, missingImportMapEntries } from '../src/modules/security/totp/importMapCheck.js'
import { changedViewKeys, safeAdminBack, wrapTotpViews } from '../src/modules/security/totp/safeBack.js'
import { SafeTotpView } from '../src/modules/security/totp/SafeTotpView.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
@@ -146,9 +146,9 @@ describe('wrapTotpViews', () => {
describe.each([
['3.0.0-beta.7', payloadTotpBeta7],
['3.0.0-beta.1', payloadTotpBeta1 as unknown as typeof payloadTotpBeta7],
])('ipalKit with the real 2FA package %s', (_version, payloadTotp) => {
])('iapl with the real 2FA package %s', (_version, payloadTotp) => {
const build = (twoFactor: false | Record<string, unknown>, extra: Partial<Config> = {}, options: Record<string, unknown> = {}) =>
ipalKit({
iapl({
access: { authCollection: 'users' },
i18n,
twoFactor: twoFactor === false ? false : ({ issuer: 'Example', plugin: payloadTotp, ...twoFactor } as never),
@@ -172,13 +172,13 @@ describe.each([
expect(component(config, 'SetupTOTPBackslash')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView')
})
test('the package registered by the project too, before ipalKit: still guarded', async () => {
test('the package registered by the project too, before iapl: still guarded', async () => {
const first = payloadTotp({ collection: 'users', totp: { issuer: 'E' } } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as never)
expect(raw(first).length).toBe(4)
expect(raw(await build({}, first as never))).toEqual([])
})
test('ipalKit run over its own output (a config reused): still guarded', async () => {
test('iapl run over its own output (a config reused): still guarded', async () => {
const once = await build({})
const twice = await build({}, { admin: once.admin } as never)
expect(raw(twice)).toEqual([])
@@ -187,7 +187,7 @@ describe.each([
test('the same incoming config object built twice', async () => {
const incoming = { admin: { components: { views: {} } }, collections: [], secret: 'x' } as unknown as Config
const plugin = () => ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotp } as never })(incoming)
const plugin = () => iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotp } as never })(incoming)
expect(raw(await plugin())).toEqual([])
expect(raw(await plugin())).toEqual([])
})
@@ -221,7 +221,7 @@ describe.each([
'ipal-totp-view:@clocklimited/payload-2fa/rsc#TOTPSetup': { type: 'component', path: '@clocklimited/payload-2fa/rsc#TOTPSetup' },
'ipal-totp-view:@clocklimited/payload-2fa/rsc#TOTPVerify': { type: 'component', path: '@clocklimited/payload-2fa/rsc#TOTPVerify' },
})
// the tab title ipal-kit gives the screens is still there
// the tab title IAPL gives the screens is still there
expect((config.admin?.components?.views as Record<string, { meta?: { title?: string } }>).VerifyTOTP.meta?.title).toBeTruthy()
})
@@ -306,13 +306,13 @@ describe('SafeTotpView', () => {
})
})
// "Setup required" (requireSetup), the back-link check (safeBack) and ipal-kit's own check (guard) are separate
// "Setup required" (requireSetup), the back-link check (safeBack) and IAPL's own check (guard) are separate
// switches: each combination builds, and each part is on exactly when its own switch says so.
describe('requireSetup x safeBack x guard', () => {
const combos = [undefined, false].flatMap((requireSetup) => [undefined, false].flatMap((safeBack) => [undefined, false].map((guard) => ({ guard, requireSetup, safeBack }))))
test.each(combos)('requireSetup: $requireSetup, safeBack: $safeBack, guard: $guard', async (options) => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...options } as never })({ collections: [], secret: 'x' } as unknown as Config)
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...options } as never })({ collections: [], secret: 'x' } as unknown as Config)
const views = Object.values(config.admin?.components?.views ?? {}) as { Component: { path?: string } | string; path: string }[]
const totpViews = views.filter((v) => /(?:setup|verify)-totp$/.test(v.path))
expect(totpViews).toHaveLength(4)
@@ -320,13 +320,13 @@ describe('requireSetup x safeBack x guard', () => {
const wrapped = totpViews.filter((v) => typeof v.Component === 'object' && v.Component.path === '@intecion/ipal-kit/admin#SafeTotpView').length
expect(wrapped).toBe(options.safeBack === false ? 0 : 4)
// setup required needs ipal-kit's own check; with either off there is no status field, hook or notice
// setup required needs IAPL's own check; with either off there is no status field, hook or notice
const setupOn = options.requireSetup !== false && options.guard !== false
const users = config.collections?.find((c) => c.slug === 'users')
// the data field whenever 2FA is on (the schema does not follow the switches); the panel's status field with the mode
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom'))).toBe(true)
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus'))).toBe(setupOn)
// the administrator's reset (a lost phone) comes with ipal-kit's own check, also when setup is not required
// the administrator's reset (a lost phone) comes with IAPL's own check, also when setup is not required
expect(Boolean(config.endpoints?.some((e) => e.path === '/ipal/two-factor/reset'))).toBe(options.guard !== false)
const provider = JSON.stringify(config.admin?.components?.providers ?? [])
expect(provider.includes('"requireSetup":true')).toBe(setupOn)
@@ -339,12 +339,12 @@ describe('requireSetup x safeBack x guard', () => {
describe('requireSetup.setupNotice', () => {
const providers = async (requireSetup?: Record<string, unknown>) =>
JSON.stringify((await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup } as never })({ collections: [], secret: 'x' } as unknown as Config)).admin?.components?.providers ?? [])
JSON.stringify((await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup } as never })({ collections: [], secret: 'x' } as unknown as Config)).admin?.components?.providers ?? [])
test('on by default; false removes the notice, not the lock', async () => {
expect(await providers()).toContain('"requireSetup":true')
expect(await providers({ setupNotice: false })).not.toContain('"requireSetup":true')
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup: { setupNotice: false } } as never })({ collections: [], secret: 'x' } as unknown as Config)
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup: { setupNotice: false } } as never })({ collections: [], secret: 'x' } as unknown as Config)
expect((config.custom as { ipal: { twoFactor: { requireSetup: boolean } } }).ipal.twoFactor.requireSetup).toBe(true)
})
})
@@ -357,7 +357,7 @@ describe('a 2FA factory that hands back the same view objects on every call', ()
const factory = (o: { collection: string }) => (c: Config) =>
withTotpParts({ ...c, admin: { ...c.admin, components: { ...c.admin?.components, views: { ...c.admin?.components?.views, ...views } } } } as Config, o.collection)
const build = (incoming: Partial<Config> = {}) =>
ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: factory as never } })({ collections: [], secret: 'x', ...incoming } as unknown as Config)
iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: factory as never } })({ collections: [], secret: 'x', ...incoming } as unknown as Config)
const paths = (config: Config) => Object.values(config.admin?.components?.views ?? {}).map((v) => (v as { Component: { path: string } }).Component.path)
test('is guarded when registered once, twice, and over a config that already holds those objects', async () => {
@@ -455,11 +455,11 @@ describe('the stale import-map check', () => {
}
})
test('in production ipalKit marks the redirect provider when the map lacks the wrapper; not otherwise', async () => {
test('in production iapl marks the redirect provider when the map lacks the wrapper; not otherwise', async () => {
const stale = await project('src/app/(payload)/admin', 'export const importMap = { "@intecion/ipal-kit/admin#TotpRedirectProvider": X }')
const current = await project('src/app/(payload)/admin', `export const importMap = { "${ENTRY}": Y }`)
const flagged = async (baseDir: string, twoFactor: Record<string, unknown> = {}) => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...twoFactor } as never })({
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...twoFactor } as never })({
admin: { importMap: { baseDir } },
collections: [],
secret: 'x',
@@ -502,10 +502,10 @@ describe('the stale import-map check', () => {
}
})
test('only ipal-kit\'s own redirect provider gets the flag, not a project\'s provider', async () => {
test('only IAPL\'s own redirect provider gets the flag, not a project\'s provider', async () => {
const stale = await project('src/app/(payload)/admin', 'export const importMap = {}')
const providers = async (provider?: unknown) => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, provider } as never })({
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, provider } as never })({
admin: { importMap: { baseDir: stale } },
collections: [],
secret: 'x',
+30 -30
View File
@@ -1,6 +1,6 @@
/**
* The rules behind test/securityHttp.test.ts, one by one: who is staff (userMeetsRole), when the second
* factor counts as passed, and what ipalKit does with a 2FA plugin it does not recognise.
* factor counts as passed, and what iapl does with a 2FA plugin it does not recognise.
*/
import type { Access, Config } from 'payload'
@@ -23,7 +23,7 @@ import {
} from '../src/modules/security/totp/secondFactor.js'
import { buildTwoFactorResetEndpoint, resolveRequireSetup, strictExempt } from '../src/modules/security/totp/setupRequired.js'
import { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from '../src/modules/security/totp/verifyLimit.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
@@ -47,7 +47,7 @@ const twoAuth = (): Config =>
describe('userMeetsRole: who is staff', () => {
test('with roles: the role decides; an account of another auth collection never passes', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(twoAuth())
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(twoAuth())
const payload = payloadOf(config)
expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['user'] } }, 'editor')).toBe(false)
@@ -61,7 +61,7 @@ describe('userMeetsRole: who is staff', () => {
})
test('without `access`: every account of the panel collection passes, other auth collections do not', async () => {
const config = await ipalKit({ i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config)
const config = await iapl({ i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config)
const payload = payloadOf(config)
expect(staffCollectionSlugs(payload)).toEqual(['users'])
expect(userMeetsRole({ payload, user: { collection: 'users' } }, 'admin')).toBe(true)
@@ -69,7 +69,7 @@ describe('userMeetsRole: who is staff', () => {
})
test('access.staffCollections names more staff collections, on purpose', async () => {
const config = await ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: false })(twoAuth())
const config = await iapl({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: false })(twoAuth())
const payload = payloadOf(config)
expect(staffCollectionSlugs(payload)).toEqual(['users', 'partners'])
expect(userMeetsRole({ payload, user: { collection: 'partners' } }, 'admin')).toBe(true) // no roles field there: all equal
@@ -77,8 +77,8 @@ describe('userMeetsRole: who is staff', () => {
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
})
test('without a payload: the staff collections of the config ipalKit built last; only a held role counts', async () => {
await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config)
test('without a payload: the staff collections of the config iapl built last; only a held role counts', async () => {
await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config)
expect(userMeetsRole({ user: { collection: 'users' } }, 'user')).toBe(false)
expect(userMeetsRole({ user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
expect(userMeetsRole({ user: { collection: 'customers', roles: ['admin'] } }, 'admin')).toBe(false)
@@ -190,12 +190,12 @@ describe('secondFactorPassed', () => {
})
})
describe('ipalKit and the 2FA plugin', () => {
describe('iapl and the 2FA plugin', () => {
const passwordOnly = { id: 1, _strategy: 'local-jwt', collection: 'users', hasTotp: true, roles: ['admin'] }
const verified = { ...passwordOnly, _strategy: 'totp' }
test('every collection and global in the config is guarded, whenever it was added', async () => {
const config = await ipalKit({
const config = await iapl({
access: { authCollection: 'users' }, consentLog: true, cookieScanner: { crawl: true }, forms: {}, i18n, stats: true,
twoFactor: { issuer: 'A', plugin: fakeTotp as never },
})({ collections: [{ slug: 'pages', fields: [] }], globals: [{ slug: 'own', fields: [] }], secret: 'x' } as unknown as Config)
@@ -258,15 +258,15 @@ describe('ipalKit and the 2FA plugin', () => {
test('a 2FA plugin without the parts the guard relies on stops the start', async () => {
const unknown = () => (c: Config) => c
const run = (guard?: false) =>
ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: unknown as never, ...(guard === false ? { guard } : {}) } })({ collections: [], secret: 'x' } as unknown as Config)
iapl({ i18n, twoFactor: { issuer: 'A', plugin: unknown as never, ...(guard === false ? { guard } : {}) } })({ collections: [], secret: 'x' } as unknown as Config)
await expect(run()).rejects.toThrow(/did not add the `totpSecret` field, the `hasTotp` field, the `totp` auth strategy/)
// twoFactor.guard: false = the package alone, as before
const config = await run(false)
expect((config.custom as { ipal?: { twoFactor?: unknown } } | undefined)?.ipal?.twoFactor).toBeUndefined()
})
test('per-entity opt-out: the package key and ipal-kit\'s key, operation by operation', async () => {
const config = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({
test('per-entity opt-out: the package key and IAPL\'s key, operation by operation', async () => {
const config = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({
collections: [
{ slug: 'a', custom: { totp: { disableAccessWrapper: { read: true } } }, fields: [] },
{ slug: 'b', custom: { ipal: { secondFactor: false } }, fields: [] },
@@ -288,7 +288,7 @@ describe('ipalKit and the 2FA plugin', () => {
const g = config.globals!.find((x) => x.slug === 'g')!.access
expect(call(g, 'read')).toBe(true)
expect(call(g, 'update')).toBe(false)
// ipal-kit's key reaches the package in its own key, so the package leaves the operation alone too
// IAPL's key reaches the package in its own key, so the package leaves the operation alone too
expect((config.globals!.find((x) => x.slug === 'g')!.custom as { totp: unknown }).totp).toEqual({ disableAccessWrapper: { read: true } })
})
@@ -338,9 +338,9 @@ describe('ipalKit and the 2FA plugin', () => {
return last
}
clearVerifyLimits()
expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never } })(base()), 6)).toBe(429)
expect(await call(await iapl({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never } })(base()), 6)).toBe(429)
clearVerifyLimits()
expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never, verifyLimit: false } })(base()), 8)).toBe(200)
expect(await call(await iapl({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never, verifyLimit: false } })(base()), 8)).toBe(200)
})
// M1 (R3-2): the count is also kept in the database, so a restart or a second instance does not reset it.
@@ -475,7 +475,7 @@ describe('ipalKit and the 2FA plugin', () => {
...withTotpParts(c, o.collection),
endpoints: [...(c.endpoints ?? []), ...['/verify-totp', '/setup-totp', '/remove-totp'].map((path) => ({ handler, method: 'post' as const, path }))],
})
const build = (twoFactor: Record<string, unknown> = {}) => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoints as never, ...twoFactor } as never })({ collections: [], endpoints: [], secret: 'x' } as unknown as Config)
const build = (twoFactor: Record<string, unknown> = {}) => iapl({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoints as never, ...twoFactor } as never })({ collections: [], endpoints: [], secret: 'x' } as unknown as Config)
const call = async (config: Config, path: string, headers: Record<string, string>, user: Record<string, unknown>) =>
(await config.endpoints!.find((e) => e.path === path)!.handler({ headers: new Headers(headers), i18n: undefined, payload: { config, logger: { warn } }, url: 'https://site.example/api' + path, user: { id: 5, collection: 'users', ...user } } as never)).status
const elsewhere = { host: 'site.example', origin: 'https://blog.site.example' }
@@ -507,7 +507,7 @@ describe('ipalKit and the 2FA plugin', () => {
})
test('staff collections outside the 2FA collection are named in a warning at start', async () => {
const config = await ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({
const config = await iapl({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({
...twoAuth(),
admin: { user: 'users' },
} as Config)
@@ -528,7 +528,7 @@ describe('ipalKit and the 2FA plugin', () => {
test('setup required: on by default, with the field, the hook, the reset endpoint and the notices; every part can be changed', async () => {
const base = () => ({ collections: [], secret: 'x' }) as unknown as Config
const on = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })(base())
const on = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })(base())
const guard = (c: Config) => (c.custom as { ipal: { twoFactor: Record<string, unknown> } }).ipal.twoFactor
expect(guard(on)).toMatchObject({ collection: 'users', requireSetup: true, setupWindowMs: 72 * 3_600_000 })
const users = on.collections!.find((c) => c.slug === 'users')!
@@ -537,10 +537,10 @@ describe('ipalKit and the 2FA plugin', () => {
expect(on.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true)
expect(JSON.stringify(on.admin?.components?.beforeDashboard)).toContain('TwoFactorAlert')
const custom = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: 24 } } })(base())
const custom = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: 24 } } })(base())
expect(guard(custom).setupWindowMs).toBe(24 * 3_600_000)
const off = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: false } })(base())
const off = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: false } })(base())
expect(guard(off)).toMatchObject({ requireSetup: false })
// the data field stays whenever 2FA is on: the schema must not depend on the switch (SQL would drop the column)
const offUsers = off.collections!.find((c) => c.slug === 'users')!
@@ -548,7 +548,7 @@ describe('ipalKit and the 2FA plugin', () => {
expect(offUsers.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus')).toBe(false)
expect(offUsers.hooks?.beforeChange?.length ?? 0).toBe(0) // no stamping while the mode is off
expect(JSON.stringify(off.admin?.components?.beforeDashboard ?? [])).not.toContain('TwoFactorAlert')
const guardOff = await ipalKit({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never } })(base())
const guardOff = await iapl({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never } })(base())
expect(guardOff.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true)
// each part of the mode has its own switch
@@ -559,28 +559,28 @@ describe('ipalKit and the 2FA plugin', () => {
})
// fakeTotp registers no provider, so the setup notice is checked with the real package in test/safeBack.test.ts
expect(has(on)).toMatchObject({ dashboard: true, status: true })
const noDash = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { dashboardNotice: false } } })(base())
const noDash = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { dashboardNotice: false } } })(base())
expect(has(noDash)).toMatchObject({ dashboard: false, status: true })
const noStatus = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { statusField: false } } })(base())
const noStatus = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { statusField: false } } })(base())
expect(has(noStatus)).toMatchObject({ dashboard: true, status: false })
expect(guard(noStatus)).toMatchObject({ requireSetup: true }) // the lock itself is unchanged
expect(off.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true) // an admin can still reset a lost phone
// 2FA off: nothing of this exists
const none = await ipalKit({ i18n, twoFactor: false })(base())
const none = await iapl({ i18n, twoFactor: false })(base())
expect(none.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(false)
expect(none.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(false)
})
test.each([['24'], [-1], [Number.NaN], [Number.POSITIVE_INFINITY], [true], [null]])('requireSetup.windowHours %s stops the start (a typo must not mean "no limit")', async (windowHours) => {
await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours must be a number/)
// also when ipal-kit's own check is off: a wrong value is never silently accepted
await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours/)
await expect(Promise.resolve().then(() => iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours must be a number/)
// also when IAPL's own check is off: a wrong value is never silently accepted
await expect(Promise.resolve().then(() => iapl({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours/)
expect(() => resolveRequireSetup({ windowHours: windowHours as never })).toThrow(/windowHours/)
})
test('requireSetup: null is the default, like leaving it out', async () => {
const config = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: null as never } })({ collections: [], secret: 'x' } as unknown as Config)
const config = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: null as never } })({ collections: [], secret: 'x' } as unknown as Config)
expect((config.custom as { ipal: { twoFactor: Record<string, unknown> } }).ipal.twoFactor).toMatchObject({ requireSetup: true, setupWindowMs: 72 * 3_600_000 })
expect(JSON.stringify(config.admin?.components?.beforeDashboard)).toContain('TwoFactorAlert')
expect(resolveRequireSetup(null as never)).toEqual({ requireSetup: true, setupWindowMs: 72 * 3_600_000 })
@@ -599,7 +599,7 @@ describe('ipalKit and the 2FA plugin', () => {
test('an async function stops the start', async () => {
expect(() => resolveRequireSetup({ exempt: (async () => false) as never })).toThrow(/must not be async/)
await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { exempt: (async () => true) as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/must not be async/)
await expect(Promise.resolve().then(() => iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { exempt: (async () => true) as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/must not be async/)
expect(() => resolveRequireSetup({ exempt: 'yes' as never })).toThrow(/must be a function/)
})
@@ -740,7 +740,7 @@ describe('ipalKit and the 2FA plugin', () => {
})
test('twoFactor: false — no guard, a password is enough (as documented)', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config)
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config)
const payload = payloadOf(config)
const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: unknown) => unknown
expect(read({ req: { payload, user: { collection: 'users', roles: ['admin'] } } })).toBe(true)
+5 -5
View File
@@ -13,7 +13,7 @@ import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { numericIds, testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
@@ -25,7 +25,7 @@ vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHe
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
const PASSWORD = 'a-long-test-password-1'
/** A plugin the project lists AFTER ipalKit: its collection did not exist when ipalKit ran. */
/** A plugin the project lists AFTER iapl: its collection did not exist when iapl ran. */
const latePlugin: Plugin = (config: Config) => ({
...config,
collections: [
@@ -47,7 +47,7 @@ const projectCollections: CollectionConfig[] = [
auth: true,
fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }],
},
// The 2FA package's own per-entity opt-out, and ipal-kit's.
// The 2FA package's own per-entity opt-out, and IAPL's.
{
slug: 'open-notes',
access: { read: ({ req }) => Boolean(req.user), update: ({ req }) => Boolean(req.user) },
@@ -100,7 +100,7 @@ const makeConfig = () =>
db: testDatabase('sechttp'),
editor: lexicalEditor(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
consentLog: true,
cookieScanner: { crawl: true },
@@ -378,7 +378,7 @@ describe('per-entity opt-out from the second factor', () => {
expect((await api('/open-notes', sessions.anonymous)).status).toBe(403) // its own rule still applies
})
test("ipal-kit's key: custom.ipal.secondFactor", async () => {
test("IAPL's key: custom.ipal.secondFactor", async () => {
expect((await api('/open-tasks', sessions.passwordOnly)).status).toBe(200)
expect((await api('/open-tasks', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
})
+2 -2
View File
@@ -12,7 +12,7 @@ import { getPayload } from 'payload'
import { payloadTotp } from 'payload-2fa-beta1'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
@@ -40,7 +40,7 @@ beforeAll(async () => {
db: testDatabase('sechttp_b1'),
editor: lexicalEditor(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
+2 -2
View File
@@ -12,7 +12,7 @@ import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
@@ -31,7 +31,7 @@ beforeAll(async () => {
db: testDatabase('sechttp_first'),
editor: lexicalEditor(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
+4 -4
View File
@@ -11,7 +11,7 @@ import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
@@ -25,7 +25,7 @@ let server: TestServer
let payload: Payload
beforeAll(async () => {
process.env.IPAL_DOCTOR_TOKEN = DOCTOR_TOKEN
process.env.IAPL_DOCTOR_TOKEN = DOCTOR_TOKEN
const config = buildTestConfig({
collections: [
// The project's own staff collection, with API keys.
@@ -35,7 +35,7 @@ beforeAll(async () => {
db: testDatabase('sechttp_tok'),
editor: lexicalEditor(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
@@ -54,7 +54,7 @@ beforeAll(async () => {
}, 120_000)
afterAll(async () => {
delete process.env.IPAL_DOCTOR_TOKEN
delete process.env.IAPL_DOCTOR_TOKEN
await server?.close()
await payload?.destroy?.()
})
+7 -7
View File
@@ -8,7 +8,7 @@ import { getPayload } from 'payload'
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
import { createSeeder, editedSinceSeed, isLocalDatabase, seedHash } from '../src/exports/seed.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -126,7 +126,7 @@ describe('createSeeder', () => {
},
],
localization: { defaultLocale: 'pl', fallback: true, locales: ['pl', 'en'] },
plugins: [ipalKit({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] }, indexNow: true, pages: { slug: 'pages' }, twoFactor: false })],
plugins: [iapl({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] }, indexNow: true, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'seed-test-secret',
telemetry: false,
})
@@ -271,12 +271,12 @@ describe('createSeeder', () => {
expect(((await payload.findGlobal({ slug: 'look' as never })) as { mode: string }).mode).toBe('dark')
})
test('production guard: update refused on production or a non-local database unless IPAL_SEED_ALLOW_PROD_UPDATE=1', () => {
test('production guard: update refused on production or a non-local database unless IAPL_SEED_ALLOW_PROD_UPDATE=1', () => {
vi.stubEnv('NODE_ENV', 'production')
const only = ['pages:kontakt']
expect(() => seeder({ only, update: true })).toThrow(/update refused: NODE_ENV=production[\s\S]*Back up the database/)
expect(() => seeder({ only })).not.toThrow() // create-only of listed records is always allowed
vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1')
vi.stubEnv('IAPL_SEED_ALLOW_PROD_UPDATE', '1')
expect(seeder({ only, update: true }).update).toBe(true)
expect(lines.join('\n')).toMatch(/Did you back it up/)
@@ -285,7 +285,7 @@ describe('createSeeder', () => {
expect(() => seeder({ only, update: true })).toThrow(/update refused: the database is not local/)
expect(() => seeder({ guard: { localHosts: ['db'] }, update: true })).not.toThrow()
expect(() => seeder({ guard: false, update: true })).not.toThrow()
vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1')
vi.stubEnv('IAPL_SEED_ALLOW_PROD_UPDATE', '1')
expect(() => seeder({ force: true, only, update: true })).toThrow(/force refused/)
})
@@ -300,7 +300,7 @@ describe('createSeeder', () => {
vi.stubEnv('DATABASE_URI', 'postgres://u:p@db:5432/app')
expect(() => seeder()).toThrow(/full seed refused: the database is not local/)
expect(() => seeder({ guard: { allowFull: true } })).not.toThrow()
vi.stubEnv('IPAL_SEED_ALLOW_FULL', '1')
vi.stubEnv('IAPL_SEED_ALLOW_FULL', '1')
expect(() => seeder()).not.toThrow()
expect(() => seeder({ guard: false })).not.toThrow()
})
@@ -335,7 +335,7 @@ describe('createSeeder', () => {
test('seed writes skip IndexNow; a normal save still pings', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 202 }))
vi.stubEnv('NODE_ENV', 'production')
vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1')
vi.stubEnv('IAPL_SEED_ALLOW_PROD_UPDATE', '1')
vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.pl')
vi.stubEnv('INDEXNOW_KEY', 'k123')
+2 -2
View File
@@ -9,7 +9,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { createSeeder } from '../src/exports/seed.js'
import { localize } from '../src/modules/seed/values.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -89,7 +89,7 @@ describe('createSeeder: whole localized arrays keep every language', () => {
],
localization: { defaultLocale: 'pl', fallback: true, locales: [...LOCALES] },
plugins: [
ipalKit({
iapl({
forms: {},
i18n: { defaultLocale: 'pl', locales: LOCALES.map((code) => ({ code, label: code.toUpperCase() })) },
pages: { slug: 'pages' },
+2 -2
View File
@@ -11,7 +11,7 @@ import type { SeedResult } from '../src/exports/seed.js'
import { createSeeder } from '../src/exports/seed.js'
import { buildLinksField, buildSectionHeaderField } from '../src/index.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -64,7 +64,7 @@ describe('createSeeder: required fields with references', () => {
editor: lexicalEditor(),
localization: { defaultLocale: 'pl', fallback: true, locales: [...LOCALES] },
plugins: [
ipalKit({
iapl({
forms: {},
i18n: { defaultLocale: 'pl', locales: LOCALES.map((code) => ({ code, label: code.toUpperCase() })) },
pages: { slug: 'pages' },
+2 -2
View File
@@ -241,10 +241,10 @@ describe('buildUploadSecurityHeaders', () => {
})
})
describe('site-wide noindex (IPAL_NOINDEX) and Markdown headers', () => {
describe('site-wide noindex (IAPL_NOINDEX) and Markdown headers', () => {
test('staging blocks crawling everywhere', async () => {
const { vi } = await import('vitest')
vi.stubEnv('IPAL_NOINDEX', '1')
vi.stubEnv('IAPL_NOINDEX', '1')
try {
expect(buildRobots({ baseUrl: 'https://staging.acme.pl' })).toEqual({ rules: { disallow: ['/'], userAgent: '*' } })
expect(buildSecurityHeaders().find((h) => h.key === 'X-Robots-Tag')?.value).toBe('noindex, nofollow')
+2 -2
View File
@@ -8,7 +8,7 @@ import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -42,7 +42,7 @@ describe('SEO outputs against a real database', () => {
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
plugins: [iapl({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'seo-integration-test-secret',
telemetry: false,
})
+6 -6
View File
@@ -14,7 +14,7 @@ import { createPageMetadata } from '../src/modules/seo/createPageMetadata.js'
import { createLlmsTxtRoute, createSitemapRouteHandler, DEFAULT_SITEMAP_CACHE_CONTROL } from '../src/modules/seo/routeHandlers.js'
import { llmsIntroFrom, normalizeVerificationToken, robotsOptionsFrom, verificationFrom } from '../src/modules/seo/searchSettings.js'
import { collectSiteIndex } from '../src/modules/seo/siteIndex.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
const config: I18nConfig = {
defaultLocale: 'pl',
@@ -122,8 +122,8 @@ describe('AI crawlers (robots)', () => {
expect(rules[1]).toEqual({ disallow: ['/'], userAgent: ['Bytespider'] })
})
test('IPAL_NOINDEX still wins over every exception', () => {
vi.stubEnv('IPAL_NOINDEX', '1')
test('IAPL_NOINDEX still wins over every exception', () => {
vi.stubEnv('IAPL_NOINDEX', '1')
const r = buildRobots({ aiBotRules: [{ access: 'allow', userAgent: 'GPTBot' }], baseUrl: 'https://acme.pl' })
expect(r.rules).toEqual({ disallow: ['/'], userAgent: '*' })
})
@@ -333,16 +333,16 @@ describe('plugin: Search engines tab', () => {
}
test('on by default, off with seo.searchSettings: false', async () => {
const on = await ipalKit({ access: { authCollection: 'users' }, i18n: config, twoFactor: false })(base())
const on = await iapl({ access: { authCollection: 'users' }, i18n: config, twoFactor: false })(base())
expect(tabs(on)).toContain('Search engines')
const off = await ipalKit({
const off = await iapl({
access: { authCollection: 'users' },
i18n: config,
seo: { collections: [], searchSettings: false },
twoFactor: false,
})(base())
expect(tabs(off)).not.toContain('Search engines')
const custom = await ipalKit({
const custom = await iapl({
access: { authCollection: 'users' },
i18n: config,
seo: { collections: [], searchSettings: (fields) => fields.filter((f) => 'name' in f && f.name !== 'llmsIntro') },
+2 -2
View File
@@ -10,7 +10,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import { resolveRoute } from '../src/modules/content/resolveRoute.js'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
let payload: Payload
@@ -34,7 +34,7 @@ beforeAll(async () => {
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
content: { collections: [{ slug: 'posts' }] },
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
+2 -2
View File
@@ -14,7 +14,7 @@ import { getPayload } from 'payload'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { backfillSetupFrom } from '../src/modules/security/totp/setupRequired.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
@@ -31,7 +31,7 @@ beforeAll(async () => {
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
db: testDatabase('setupcol'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp as never } })],
plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp as never } })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
+9 -9
View File
@@ -123,13 +123,13 @@ describe('starter: answers', () => {
expect(validateAnswers(a)).toHaveLength(3)
})
it('refuses single-language and English-default sites with a pointer to ipal-setup', () => {
it('refuses single-language and English-default sites with a pointer to iapl-setup', () => {
const single = validateAnswers(answers((x) => { x.languages.locales = [{ code: 'pl', label: 'Polski' }] }))
expect(single).toHaveLength(1)
expect(single[0]).toMatch(/single-language site is not supported by `ipal-kit create` yet .*ipal-setup/)
expect(single[0]).toMatch(/single-language site is not supported by `iapl create` yet .*iapl-setup/)
const english = validateAnswers(answers((x) => { x.languages.default = 'en' }))
expect(english).toHaveLength(1)
expect(english[0]).toMatch(/default language other than "pl" \(here "en"\).*ipal-setup/)
expect(english[0]).toMatch(/default language other than "pl" \(here "en"\).*iapl-setup/)
expect(validateAnswers(answers((x) => { x.languages.locales = [{ code: 'pl', label: 'Polski' }, { code: 'de', label: 'Deutsch' }] }))[0]).toMatch(/without "en"/)
expect(validateAnswers(answers((x) => { x.languages.locales.push({ code: 'de', label: 'Deutsch' }) }))).toEqual([])
})
@@ -141,7 +141,7 @@ describe('starter: answers', () => {
writeFileSync(file, JSON.stringify(answers((x) => { x.languages.locales = [{ code: 'pl', label: 'Polski' }] })))
try {
expect(await runCreateCli(['acme-test.pl', '--answers', file, '--dir', dir, '--no-install', '--no-git'], (line) => lines.push(line))).toBe(1)
expect(lines.join('\n')).toMatch(/nothing was written[\s\S]*single-language site[\s\S]*ipal-setup/)
expect(lines.join('\n')).toMatch(/nothing was written[\s\S]*single-language site[\s\S]*iapl-setup/)
expect(existsSync(dir)).toBe(false)
} finally {
rmSync(file, { force: true })
@@ -175,7 +175,7 @@ describe('starter: generated files', () => {
'snapshots:', '', " '@intecion/ipal-kit@file:..(abc)':", ' dependencies:', ' next: 16.4.3', '', ' [email protected]: {}', '',
].join('\n')
const out = lockfileWithoutPlugin(lock)
expect(out).not.toContain('ipal-kit')
expect(out).not.toContain('IAPL')
expect(out).not.toContain('dependenciesMeta')
expect(out).toContain(" [email protected]:\n resolution: {integrity: x}")
expect(out).toContain(' [email protected]: {}')
@@ -231,8 +231,8 @@ describe.runIf(existsSync(path.join(reference, 'starter.manifest.json')))('start
expect(files['src/seed/base.ts']).toContain("email: '[email protected]'")
expect(files['pnpm-lock.yaml']).not.toContain('@intecion/ipal-kit')
const traced = renderSite(bundle, answers(), { ...ctx, source: { bundleSha256: 'abc', commit: 'def' } })
expect(JSON.parse(traced['.ipal/starter.json'] ?? '')).toMatchObject({ ipalKit: '1.15.0', source: { bundleSha256: 'abc', commit: 'def' } })
const doctor = JSON.parse(files['ipal-doctor.json'] ?? '') as { rules: Record<string, unknown> }
expect(JSON.parse(traced['.iapl/starter.json'] ?? '')).toMatchObject({ iapl: '1.15.0', source: { bundleSha256: 'abc', commit: 'def' } })
const doctor = JSON.parse(files['iapl-doctor.json'] ?? '') as { rules: Record<string, unknown> }
expect(Object.keys(doctor.rules).sort()).toEqual(['audit:collections-present', 'csp', 'i18n-literals'])
expect((JSON.parse(files['package.json'] ?? '') as { packageManager?: string }).packageManager).toMatch(/^pnpm@\d/)
})
@@ -252,8 +252,8 @@ describe.runIf(existsSync(path.join(reference, 'starter.manifest.json')))('start
expect(files['src/blocks/configs.ts']).not.toContain('entryList')
expect(files['src/instrumentation.ts']).toContain('storage: false,')
expect(files['src/lib/content.ts']).not.toMatch(/buildLocalBusinessJsonLd|getPayload/)
expect(files['AGENTS.md']).toContain('ipal-audit-skip: twofactor, r2')
expect(Object.keys((JSON.parse(files['ipal-doctor.json'] ?? '') as { rules: object }).rules).sort()).toEqual(['2fa', 'csp', 'i18n-literals'])
expect(files['AGENTS.md']).toContain('iapl-audit-skip: twofactor, r2')
expect(Object.keys((JSON.parse(files['iapl-doctor.json'] ?? '') as { rules: object }).rules).sort()).toEqual(['2fa', 'csp', 'i18n-literals'])
expect(files['src/instrumentation.ts']).not.toContain('cookieCrawl')
})
})
+4 -4
View File
@@ -9,7 +9,7 @@ import { serializeConsent } from '../src/modules/consent/storage.js'
import { buildStatsEndpoint } from '../src/modules/stats/endpoint.js'
import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath } from '../src/modules/stats/parse.js'
import { lastDays, summarize } from '../src/modules/stats/summarize.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
const CHROME = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36'
const VID = 'a'.repeat(32)
@@ -178,13 +178,13 @@ describe('stats — plugin wiring', () => {
const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
test('off by default', async () => {
const config = await ipalKit({ i18n, twoFactor: false })(base())
const config = await iapl({ i18n, twoFactor: false })(base())
expect(config.collections?.some((c) => c.slug === 'stats-visits')).toBe(false)
expect(config.endpoints?.some((e) => e.path === '/ipal/hit')).toBe(false)
})
test('stats: true adds the collection, endpoint, view, nav link and dashboard card', async () => {
const config = await ipalKit({ adminRoute: '/its', i18n, stats: true, twoFactor: false })(base())
const config = await iapl({ adminRoute: '/its', i18n, stats: true, twoFactor: false })(base())
expect(config.collections?.some((c) => c.slug === 'stats-visits')).toBe(true)
expect(config.endpoints?.some((e) => e.path === '/ipal/hit' && e.method === 'post')).toBe(true)
const components = config.admin?.components
@@ -194,7 +194,7 @@ describe('stats — plugin wiring', () => {
})
test('dashboard: false leaves the dashboard alone', async () => {
const config = await ipalKit({ i18n, stats: { dashboard: false }, twoFactor: false })(base())
const config = await iapl({ i18n, stats: { dashboard: false }, twoFactor: false })(base())
expect(JSON.stringify(config.admin?.components?.beforeDashboard)).not.toContain('StatsWidget')
})
})
+1 -1
View File
@@ -135,7 +135,7 @@ describe('submitForm — other gates', () => {
})
})
test('ipalKit forms.consentFieldName (payload.config.custom) names the consent field', async () => {
test('iapl forms.consentFieldName (payload.config.custom) names the consent field', async () => {
const { payload } = fakePayload({ forms: { f: { fields: [{ name: 'zgoda', blockType: 'checkbox' }] } } })
Object.assign(payload, { config: { custom: { ipal: { consentFieldName: 'zgoda' } } } })
expect(await submitForm({ data: { zgoda: false }, formId: 'f', ip: nextIp(), payload })).toEqual({
+2 -2
View File
@@ -19,7 +19,7 @@ import {
themeConfigFrom,
themeScript,
} from '../src/modules/theme/theme.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
function fakeStorage(initial: Record<string, string> = {}) {
const data = new Map(Object.entries(initial))
@@ -82,7 +82,7 @@ describe('theme storage key', () => {
})
test('the plugin option reaches getSiteShell through config.custom; themeConfigFrom carries it', async () => {
const config = await ipalKit({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, theme: { storageKey: 'acme-theme' }, twoFactor: false })({
const config = await iapl({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, theme: { storageKey: 'acme-theme' }, twoFactor: false })({
collections: [{ slug: 'users', auth: true, fields: [] }],
} as unknown as Config)
expect((config.custom as { ipal: { themeStorageKey: string } }).ipal.themeStorageKey).toBe('acme-theme')
+3 -3
View File
@@ -3,7 +3,7 @@ import type { Config } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { describe, expect, it } from 'vitest'
import { ipalKit } from '../src/index.js'
import { iapl } from '../src/index.js'
import { totpRedirectTarget } from '../src/modules/security/totp/totpRedirect.js'
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
@@ -64,9 +64,9 @@ describe('2FA setup redirect (fresh admin, forceSetup)', () => {
describe('twoFactor.provider', () => {
const run = (provider?: unknown) =>
ipalKit({ i18n, twoFactor: { issuer: 'Test', plugin: payloadTotp, ...(provider === undefined ? {} : { provider }) } } as never)(base())
iapl({ i18n, twoFactor: { issuer: 'Test', plugin: payloadTotp, ...(provider === undefined ? {} : { provider }) } } as never)(base())
it("replaces the package's header-based provider with ipal-kit's by default", async () => {
it("replaces the package's header-based provider with IAPL's by default", async () => {
const config = await run()
expect(providerPaths(config)).toContain('@intecion/ipal-kit/admin#TotpRedirectProvider')
expect(providerPaths(config)).not.toContain('@clocklimited/payload-2fa/rsc#TOTPProvider')
+4 -4
View File
@@ -4,7 +4,7 @@ import { describe, expect, test } from 'vitest'
import { bottomOverlap } from '../src/modules/consent/CookieButton.js'
import { TOTP_TEXTS } from '../src/modules/security/totp/totpTexts.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }
@@ -39,8 +39,8 @@ const base = (translations?: Record<string, unknown>): Config =>
type Translations = Record<string, { totpPlugin: { setup: Record<string, string>; verify: { title: string } } }>
describe('2FA texts', () => {
test('ipal-kit texts go over the package, the project over both; screens get a tab title', async () => {
const config = await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: fakeTotp } } as never)(
test('IAPL texts go over the package, the project over both; screens get a tab title', async () => {
const config = await iapl({ i18n, twoFactor: { issuer: 'Acme', plugin: fakeTotp } } as never)(
base({ en: { totpPlugin: { verify: { title: 'Project check' } } } }),
)
const t = config.i18n!.translations as Translations
@@ -53,7 +53,7 @@ describe('2FA texts', () => {
})
test("texts: false keeps the package's", async () => {
const config = await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: fakeTotp, texts: false } } as never)(base())
const config = await iapl({ i18n, twoFactor: { issuer: 'Acme', plugin: fakeTotp, texts: false } } as never)(base())
expect((config.i18n!.translations as Translations).pl.totpPlugin.verify.title).toBe('Weryfikacja')
})
+3 -3
View File
@@ -7,7 +7,7 @@ import { describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
@@ -21,8 +21,8 @@ describe('@clocklimited/payload-2fa with the real plugin', () => {
expect(payloadSeenFrom(twoFactorEntry)).toBe(payloadSeenFrom(import.meta.url))
})
test('ipalKit wraps the auth collection with TOTP: secret field, strategy and setup view', async () => {
const config = await ipalKit({
test('iapl wraps the auth collection with TOTP: secret field, strategy and setup view', async () => {
const config = await iapl({
access: { authCollection: 'users' },
i18n,
twoFactor: { issuer: 'Example', plugin: payloadTotp },
+3 -3
View File
@@ -14,7 +14,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { buildSiteIntegrations } from '../src/globals/SiteIntegrations/index.js'
import { keepSecretBeforeValidate, maskSecretAfterRead, SECRET_CLEAR, SECRET_MASK, writeOnlySecret, writeOnlySecrets } from '../src/modules/secrets/writeOnly.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
@@ -39,7 +39,7 @@ beforeAll(async () => {
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
db: testDatabase('secrets'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })],
plugins: [iapl({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
@@ -193,7 +193,7 @@ describe('the building blocks', () => {
const hooked = (fields: unknown) => JSON.stringify(fields, (_k, v) => (typeof v === 'function' ? v.name : v)).includes('maskSecretAfterRead')
expect(hooked(buildSiteIntegrations().fields)).toBe(true)
expect(hooked(buildSiteIntegrations({ writeOnlySecrets: false }).fields)).toBe(false)
const off = await ipalKit({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, secrets: { writeOnly: false }, twoFactor: false })({ collections: [], secret: 'x' } as never)
const off = await iapl({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, secrets: { writeOnly: false }, twoFactor: false })({ collections: [], secret: 'x' } as never)
expect(hooked(off.globals!.find((g) => g.slug === 'site-integrations')!.fields)).toBe(false)
})
})
+2 -2
View File
@@ -16,7 +16,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from 'vit
import { buildSiteIntegrations } from '../src/globals/SiteIntegrations/index.js'
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
import { buildKeepSecret, keepSecretBeforeValidate, maskSecretsOnRestore, maskWriteOnlySecrets, SECRET_CLEAR, SECRET_MASK, writeOnlySecret } from '../src/modules/secrets/writeOnly.js'
import { ipalKit } from '../src/plugin.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
@@ -76,7 +76,7 @@ beforeAll(async () => {
editor: lexicalEditor(),
email: mailAdapter(),
plugins: [
ipalKit({
iapl({
access: { authCollection: 'users' },
forms: {},
// a project that turns versions on for the global