Skip to content
Facteur

Playwright and 2FA: the code arrives by email, or it is computed

A two-factor journey blocks a test suite in two places: the code sent by email, which the test cannot read, and the authenticator app's code, which it cannot generate. Both can be solved, and not the same way.

The code received by email: the request leaves before the click

Same mechanics as a signup: the request leaves before the click and answers when the message arrives.

login-2fa.spec.ts TypeScript
import { expect, test } from '@playwright/test';

const INBOX = 'j3k9x2mq';

// hasOtp targets the extracted code, not a text that quotes it.
async function waitForCode(sentTo: string, since: Date) {
  const search = new URLSearchParams({ inbox: INBOX, sentTo, hasOtp: 'true', since: since.toISOString() });
  for (let attempt = 0; attempt < 30; attempt++) {
    const response = await fetch('https://api.facteur.eu/messages?' + search, {
      headers: { authorization: 'Bearer ' + process.env.FACTEUR_API_KEY },
    });
    const { messages } = await response.json();
    if (messages?.[0]) return messages[0].otp;
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }
  throw new Error('No code for ' + sentTo);
}

test('signing in asks for the code received by email', async ({ page }) => {
  const tag = 'login-' + Date.now();
  const since = new Date();

  await page.goto('/login');
  await page.getByLabel('Email').fill(tag + '@' + INBOX + '.inbox.facteur.eu');
  await page.getByRole('button', { name: 'Continue' }).click();

  // The code, extracted on arrival.
  await page.getByLabel('Code').fill(await waitForCode(tag + '@', since));
  await expect(page.getByText('Welcome')).toBeVisible();
});
A criterion that targets the code, not the text
The hasOtp criterion asks for "the message that carries a code", which avoids landing on an email that quotes an old code in its history.
The code lives in its own field
Extracted on arrival. Your test compares a value, it does not look for a pattern in HTML.

The code of an authenticator app: twenty lines of Node, no dependency

Nobody can send you this one: it is computed from the secret your activation screen shows. Facteur plays no part in it, and the phone stays in the drawer.

totp.ts TypeScript
import { createHmac } from 'node:crypto';

const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

/** The secret your activation screen shows, in base32. */
function decode(secret: string): Buffer {
  let bits = 0;
  let value = 0;
  const out: number[] = [];
  for (const c of secret.replace(/=/g, '').toUpperCase()) {
    value = (value << 5) | BASE32.indexOf(c);
    bits += 5;
    if (bits >= 8) {
      out.push((value >>> (bits - 8)) & 0xff);
      bits -= 8;
    }
  }
  return Buffer.from(out);
}

/** RFC 6238: SHA-1, six digits, a thirty-second step. */
export function totp(secret: string, at = Date.now()): string {
  const counter = Math.floor(at / 1000 / 30);
  const message = Buffer.alloc(8);
  message.writeUInt32BE(Math.floor(counter / 2 ** 32), 0);
  message.writeUInt32BE(counter % 2 ** 32, 4);

  const digest = createHmac('sha1', decode(secret)).update(message).digest();
  const offset = digest[digest.length - 1] & 0x0f;
  const binary =
    ((digest[offset] & 0x7f) << 24) |
    (digest[offset + 1] << 16) |
    (digest[offset + 2] << 8) |
    digest[offset + 3];

  return String(binary % 1_000_000).padStart(6, '0');
}

What it changes for a test suite

01

The whole journey can be tested

Turning on two-factor authentication, signing in, backup code: nothing depends on a physical device or a personal mailbox any more.

02

The test stays readable

A short function and an assertion. You do not extract the code, and the loop that waits fits in five lines.

03

Parallel runs do not step on each other

Each test receives at its own address, so the code it reads belongs to its own journey.

Install the Playwright plugin from npm

playwright-facteur can wait for a message that carries a code. It installs with npm i -D playwright-facteur. The test above expects nothing from it: it calls the API directly, and works as it is.

Unblock your two-factor tests

An inbox, a read-only key, and the whole journey becomes testable again. The free plan asks for no credit card.