/** * 2FA verify and setup attempts only from the site's own origin. * * The verify limit counts every attempt of an account. A page on another origin that the * browser still sends the login cookie to — a sibling subdomain is "same site", so * `SameSite=Lax` does not stop it, and Payload's own `csrf` list is empty unless `serverURL` * or `csrf` is set — could post wrong codes in the owner's name: no password needed, the * owner's five attempts burnt, the owner locked out for the window. So a request that a * browser marks as coming from elsewhere is refused BEFORE it is counted. * * What counts as the site's own origin: the host the request came in on (`Host`, * `X-Forwarded-Host`, the request URL), `serverURL`, Payload's `csrf` and `cors` lists, and * `twoFactor.sameOrigin.origins`. A request with neither `Origin` nor `Sec-Fetch-Site` is not * a browser's cross-site request (a script, `curl`, a server) and passes: it cannot ride on * somebody's cookie. * * A reverse proxy that rewrites `Host` and sends no `X-Forwarded-Host` (nginx's plain * `proxy_pass`) hides the site's address from the server: without `serverURL` the site's own * pages are then refused. That must not happen in silence — the first refusal of every origin * is written to the log with the ways to allow it (`reportRefusedOrigin`). */ type RequestLike = { headers?: { get(name: string): null | string } payload?: { config?: { cors?: unknown; csrf?: unknown; serverURL?: unknown }; logger?: { warn(message: string): void } } url?: null | string } /** `site.example:443` is `site.example` for https, `:80` for http — a proxy may write the port out. */ const withoutDefaultPort = (host: string, protocol: string): string => { const lower = host.toLowerCase() if (protocol === 'https:' && lower.endsWith(':443')) {return lower.slice(0, -4)} if (protocol === 'http:' && lower.endsWith(':80')) {return lower.slice(0, -3)} return lower } const originOf = (value: unknown): null | string => { if (typeof value !== 'string' || !value) {return null} try { return new URL(value).origin } catch { return null } } /** Origins and hosts this request may come from. */ export function ownOrigins(req: RequestLike, extra: string[] = []): { hosts: Set; origins: Set } { const config = req.payload?.config const cors = config?.cors const listed = [ config?.serverURL, ...(Array.isArray(config?.csrf) ? (config.csrf as unknown[]) : []), ...(Array.isArray(cors) ? (cors as unknown[]) : Array.isArray((cors as { origins?: unknown } | undefined)?.origins) ? ((cors as { origins: unknown[] }).origins) : []), ...extra, ] const origins = new Set(listed.map(originOf).filter((o): o is string => o !== null)) const hosts = new Set() for (const name of ['host', 'x-forwarded-host']) { // a proxy may list several; the first is the one the browser asked for const value = req.headers?.get(name)?.split(',')[0]?.trim().toLowerCase() if (value) {hosts.add(value)} } const fromUrl = originOf(req.url) if (fromUrl) {hosts.add(new URL(fromUrl).host)} return { hosts, origins } } /** False when a browser says the request comes from another origin (see the top of the file). */ export function requestFromOwnOrigin(req: RequestLike, extra: string[] = []): boolean { const origin = req.headers?.get('origin') if (origin) { const parsed = originOf(origin) if (!parsed) {return false} // "null" (a sandboxed page, a redirect chain) or garbage const { hosts, origins } = ownOrigins(req, extra) if (origins.has(parsed)) {return true} // `URL.origin` has already dropped the default port; a `Host` / `X-Forwarded-Host` may carry it const { host, protocol } = new URL(parsed) return [...hosts].some((own) => withoutDefaultPort(own, protocol) === host.toLowerCase()) } const site = req.headers?.get('sec-fetch-site') if (site) {return site === 'same-origin' || site === 'none'} return true } const reported = new Set() const MAX_REPORTED = 50 /** * Says in the log, once per origin and process, that a 2FA attempt was refused and how to allow * that origin. Without it a site behind a proxy that hides its address has a panel nobody can * enter and a silent log. Returns true when a line was written. */ export function reportRefusedOrigin(req: RequestLike, extra: string[] = []): boolean { const origin = req.headers?.get('origin') const key = origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}` if (reported.has(key) || reported.size >= MAX_REPORTED) {return false} reported.add(key) const { hosts, origins } = ownOrigins(req, extra) const known = [...origins, ...[...hosts].map((h) => `host ${h}`)].join(', ') || 'none' const how = originOf(origin) ? `If "${originOf(origin)}" is this site's own address (a reverse proxy that rewrites Host and sends no X-Forwarded-Host), set serverURL to it in the Payload config, ` + `or pass twoFactor: { sameOrigin: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. ` : 'The browser did not name an origin this site knows. ' req.payload?.logger?.warn( `[iapl] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` + how + 'If it is a foreign page, this is the protection working. twoFactor: { sameOrigin: false } turns the check off (docs/security.md "Verify and setup attempts only from the site\'s own origin"). Said once per origin.', ) return true } /** For tests: forget which origins were reported. */ export const clearReportedOrigins = (): void => reported.clear()