Q2 (IAWL idea 16): Payload locks a staff account after 5 wrong passwords from anybody, so a stranger kept the owner out without a password. Failed sign-ins are now counted per client IP and typed address (folded: NFKC, lower case, trim): 5 in 15 min, then 429 for that IP and address only; only failures count (a place taken before the compare, given back on success or refusal; "try again in a moment" while others are being checked). Payload's own lock stays as the net at 50 failures for an hour where the project set none. The mail service's account-mail limit now counts per address per visitor (5) with 20 per address in all, so one stranger no longer blocks the owner's own reset mail. Q3 (idea 7): staff login, forgot and reset password refuse a request a browser marks as coming from another origin (403 before anything is counted or sent); visitor collections untouched. Q5 (idea 29): an account that changes its own e-mail, username or password must send its current password (panel field on the account page via the plugin's MaskedField, no import-map change; REST and GraphQL). Admins changing others, server code and API keys are not asked; wrong ones count like failed sign-ins. Options accounts.signInLimit / signInSameOrigin / confirmOwnChanges, all validated at start. Tests: 15 HTTP tests (2FA on/off, all off), fail before on 1.17.1; built-site spec own-account.spec.ts in e2e:built. Co-Authored-By: Claude Opus 5.5 <[email protected]>
87 lines
5.4 KiB
TypeScript
87 lines
5.4 KiB
TypeScript
/**
|
|
* Sign-in rules of the staff collections (1.18.0, accounts.signInLimit / signInSameOrigin / confirmOwnChanges), through
|
|
* real HTTP requests against a running Payload. Shared by signInRules.test.ts (2FA on), signInRules2faOff.test.ts and
|
|
* signInRulesOff.test.ts (every rule switched off): one Payload per file.
|
|
* Database: SQLite in memory, or IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts).
|
|
*/
|
|
import type { Payload } from 'payload'
|
|
|
|
import { payloadTotp } from '@clocklimited/payload-2fa'
|
|
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
|
import { getPayload } from 'payload'
|
|
import { afterAll, beforeAll } from 'vitest'
|
|
|
|
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'
|
|
import { totp } from './http/totp.js'
|
|
|
|
export const SECRET = 'JBSWY3DPEHPK3PXP'
|
|
export const PASSWORD = 'a-long-test-password-1'
|
|
export const FOREIGN = { origin: 'https://blog.site.example', 'sec-fetch-site': 'same-site' }
|
|
|
|
export type Answer = { body: string; status: number }
|
|
|
|
export function signInSite({ off = false, twoFactor = true }: { off?: boolean; twoFactor?: boolean } = {}) {
|
|
const state = {} as { mails: string[]; payload: Payload; server: TestServer }
|
|
beforeAll(async () => {
|
|
state.mails = []
|
|
const config = buildTestConfig({
|
|
admin: { user: 'users' },
|
|
collections: [
|
|
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
|
|
{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-sign-in-rules-media' } },
|
|
],
|
|
db: testDatabase('signinrules'),
|
|
editor: lexicalEditor(),
|
|
email: () => ({ name: 'count', defaultFromAddress: '[email protected]', defaultFromName: 'Site', sendEmail: async (m: { to?: unknown }) => void state.mails.push(String(m.to)) }) as never,
|
|
plugins: [
|
|
iapl({
|
|
access: { authCollection: 'users' },
|
|
...(off ? { accounts: { confirmOwnChanges: false, signInLimit: false, signInSameOrigin: false } } : {}),
|
|
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
|
|
mail: { relay: false },
|
|
twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp } : false,
|
|
}),
|
|
],
|
|
secret: 'integration-test-secret-0123456789',
|
|
telemetry: false,
|
|
})
|
|
state.payload = await getPayload({ config })
|
|
state.server = await startPayloadServer(config)
|
|
const make = (email: string, roles: string[]) =>
|
|
state.payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles, ...(twoFactor ? { totpSecret: SECRET } : {}) } as never })
|
|
for (const [email, role] of [['[email protected]', 'admin'], ['[email protected]', 'admin'], ['[email protected]', 'editor'], ['[email protected]', 'editor'], ['[email protected]', 'editor'], ['[email protected]', 'editor']] as const) {
|
|
await make(email, [role])
|
|
}
|
|
await state.payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
|
|
}, 120_000)
|
|
afterAll(async () => {
|
|
await state.server?.close()
|
|
await state.payload?.destroy?.()
|
|
})
|
|
|
|
const call = async (path: string, body: unknown, headers: Record<string, string> = {}, method = 'POST'): Promise<Answer> => {
|
|
const res = await fetch(`${state.server.url}/api${path}`, { body: JSON.stringify(body), headers: { 'content-type': 'application/json', ...headers }, method })
|
|
return { body: await res.text(), status: res.status }
|
|
}
|
|
const login = (email: string, password: string, ip: string, extra: Record<string, string> = {}) => call('/users/login', { email, password }, { 'x-real-ip': ip, ...extra })
|
|
const gqlLogin = async (email: string, password: string, ip: string, extra: Record<string, string> = {}) => {
|
|
const res = await call('/graphql', { query: `mutation { loginUser(email: ${JSON.stringify(email)}, password: ${JSON.stringify(password)}) { token } }` }, { 'x-real-ip': ip, ...extra })
|
|
const error = (JSON.parse(res.body) as { errors?: { extensions?: { statusCode?: number }; message: string }[] }).errors?.[0]
|
|
return { message: error?.message, status: error?.extensions?.statusCode }
|
|
}
|
|
/** A fully signed-in session (password, then the code when 2FA is on): the cookie header. */
|
|
const session = async (email: string, password = PASSWORD, ip = '203.0.113.200') => {
|
|
const res = await fetch(`${state.server.url}/api/users/login`, { body: JSON.stringify({ email, password }), headers: { 'content-type': 'application/json', 'x-real-ip': ip }, method: 'POST' })
|
|
const first = cookiesOf(res)
|
|
if (!twoFactor) {return first.join('; ')}
|
|
const verify = await fetch(`${state.server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(SECRET) }), headers: { 'content-type': 'application/json', cookie: first.join('; ') }, method: 'POST' })
|
|
return [...first, ...cookiesOf(verify)].join('; ')
|
|
}
|
|
const idOf = async (email: string) => ((await state.payload.find({ collection: 'users' as never, overrideAccess: true, where: { email: { equals: email } } })).docs[0] as { id: number | string }).id
|
|
const stored = async (email: string) => (await state.payload.find({ collection: 'users' as never, overrideAccess: true, showHiddenFields: true, where: { email: { equals: email } } })).docs[0] as { lockUntil?: null | string } | undefined
|
|
return { call, gqlLogin, idOf, login, session, state, stored }
|
|
}
|