import type { SinkMessage } from './smtp-sink' /** * twoFactor.confirmByEmail (IAPL 1.18.0, on by default): the first set-up of two-step verification waits for a link * sent to the account's e-mail. The specs read that link from the mail sink (e2e/smtp-sink.ts; create-test-admin.ts * points the site's SMTP at it). */ /** A raw message body as text: quoted-printable soft breaks and escapes undone. */ export const decodeMail = (raw: string): string => raw.replace(/=\r?\n/g, '').replace(/=([0-9A-F]{2})/g, (_, hex: string) => String.fromCharCode(parseInt(hex, 16))) /** The confirmation link of the latest message to `email`, or null. */ export function enrolmentLink(messages: SinkMessage[], email: string): null | URL { for (const message of [...messages].reverse()) { if (!message.to.some((to) => to.toLowerCase().includes(email.toLowerCase()))) {continue} const found = decodeMail(message.data).match(/https?:\/\/[^\s"<>]+\/two-factor\/confirm\?u=[^\s"<>&]+&(?:amp;)?t=[\w-]+/) if (found) {return new URL(found[0].replace('&', '&'))} } return null } /** Waits until a message with the confirmation link for `email` arrives (mail goes out right after the request). */ export async function waitForEnrolmentLink(messages: SinkMessage[], email: string, timeoutMs = 10_000): Promise { const until = Date.now() + timeoutMs for (;;) { const link = enrolmentLink(messages, email) if (link) {return link} if (Date.now() > until) {throw new Error(`no confirmation e-mail for ${email} in the mail sink`)} await new Promise((r) => setTimeout(r, 200)) } }