import type { AdminViewServerProps } from 'payload' import { getFromImportMap } from 'payload/shared' import React from 'react' import { safeAdminBack, type SafeBackRule } from './safeBack.js' export type SafeTotpViewProps = { /** `twoFactor.safeBack` as a function: replaces the default rule. */ ipalSafeBack?: SafeBackRule /** Import-map path of the 2FA package's own view (`@clocklimited/payload-2fa/rsc#TOTPVerify`). */ ipalTotpView: string } & AdminViewServerProps const originOf = (serverURL: unknown): string | undefined => { if (typeof serverURL !== 'string' || !serverURL) {return undefined} try { return new URL(serverURL).origin } catch { return undefined } } /** * In front of the 2FA package's setup and verify views: replaces the `back` query value with a * checked one (safeBack.ts) and renders the package's view with it. The package's form sends * the browser to `back` after a valid code, so what it receives must be safe to navigate to. * * ipalKit registers it (twoFactor.safeBack, on by default). A project that builds its own 2FA * screens can use it too: give it `ipalTotpView` and list that path in `admin.dependencies`. */ export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode { const { ipalSafeBack, ipalTotpView, ...rest } = props const config = props.initPageResult?.req?.payload?.config ?? props.payload?.config const raw = (props.searchParams as Record | undefined)?.back const back = (ipalSafeBack ?? safeAdminBack)(typeof raw === 'string' ? raw : undefined, { adminRoute: config?.routes?.admin ?? '/admin', origin: originOf(config?.serverURL), }) const View = getFromImportMap>>({ importMap: props.importMap, PayloadComponent: ipalTotpView, schemaPath: '', silent: true, }) if (!View) { throw new Error( `[ipal] The admin import map has no "${ipalTotpView}" (the 2FA screen ipal-kit puts its back-link check in front of). ` + 'Run `pnpm payload generate:importmap` and commit the result.', ) } return }