Open in a new tab

Enrol an account in time-based one-time codes: a random secret shown in base32 and as an otpauth:// URI, the current code with a countdown, and a check that accepts the code of the step before or after.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

When your sign-in adds a second factor that works with the authenticator apps people already have (Google Authenticator, Aegis, 1Password and the like), with no SMS and no third-party service: the server keeps one secret per account and checks six digits.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. In a real deployment, enrol and verify on the server: store the secret with the account, show it once, and refuse a code already used in its step. This page does both sides in the browser to show them together.

What it shows

  • totp.enroll({ issuer, account, secretLen: 20 }) returns secret (base32, without padding), secretBytes and uri. The URI is what a QR code would carry; render it with any QR library, or let the person type the secret.
  • The secret is shown in groups of four. base32.toBytes accepts lowercase and skips the spaces, so the typed form decodes to the same 20 bytes (base32.fromBytes pads with =; base32.test is the strict RFC 4648 check, for input you want to reject rather than repair).
  • totp.generate(secret, { t }) and totp.verify(code, secret, { t, window: 1 }); t is epoch seconds. verify returns { valid, delta }: delta 0 is the current step, -1 a code from the previous step (typed late), +1 one from the next step (a device clock running ahead).
  • A typed code is checked for exactly six digits before verify, so letters or a short code get a message, not a silent "invalid".
  • "Now" comes from fw's clock.now() (wall-clock time, which TOTP needs), and scheduler.interval refreshes the code and the countdown, stopped while the tab is hidden.
  • The defaults are RFC 6238's (SHA-1, 6 digits, 30 s), which every authenticator app reads; pass algorithm, digits or period to both enroll and verify to change them.

Code

main.js

javascriptApache-2.078 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { totp } from '@awacloud/fw/crypto/utils/totp.js';
import { base32 } from '@awacloud/fw/io/codec/base32.js';
import { clock } from '@awacloud/fw/io/timing/clock.js';
import { scheduler } from '@awacloud/fw/io/timing/scheduler.js';

fw.runtime.registerAllDeep([totp, base32, clock, scheduler]);
const TOTP = fw.runtime.resolve('totp');
const CLOCK = fw.runtime.resolve('clock');
const SCHEDULER = fw.runtime.resolve('scheduler');
export const BASE32 = fw.runtime.resolve('base32');

/** RFC 6238 defaults, which every authenticator app reads: SHA-1, 6 digits, 30 s steps. */
const PERIOD = 30;
/** Wall-clock epoch seconds, from fw's clock: TOTP needs real time, not a monotonic one. */
const now = () => Math.floor(CLOCK.now() / 1000);

/** @param {string} secret base32 @returns {string} groups of four, easier to read and type */
export const grouped = (secret) => (secret.match(/.{1,4}/g) ?? []).join(' ');
/** `toBytes` ignores spaces and accepts lowercase: what a person types from the grouped form. @param {string} typed */
export const secretBytes = (typed) => BASE32.toBytes(typed.replace(/\s/g, ''));
/** @param {string} secret base32 @param {number} t epoch seconds */
export const codeAt = (secret, t) => TOTP.generate(secret, { t });

/**
 * The server-side check: a window of one step each side absorbs clock drift and typing time.
 * @param {string} typed @param {string} secret base32 @param {number} [t] epoch seconds
 */
export function verdict(typed, secret, t = now()) {
    const code = typed.replace(/\s/g, '');
    if (!/^\d{6}$/.test(code)) return 'Refused: a code is exactly 6 digits.';
    const result = TOTP.verify(code, secret, { t, window: 1 });
    if (!result.valid) return 'Invalid: not the code of this step or the one on each side.';
    if (result.delta === 0) return 'Valid: the code of the current 30 s step.';
    // delta is the step that matched, relative to now: -1 an old code, +1 a device clock running ahead.
    return result.delta < 0 ? 'Valid, late: the code of the previous step.'
        : 'Valid, early: the code of the next step.';
}

const el = (/** @type {string} */ id) => /** @type {HTMLInputElement} */ (document.getElementById(id));
/** @param {string} id @param {string} value */
const show = (id, value) => { el(id).textContent = value; };
/** @type {{ secret: string } | null} */
let enrolled = null; // a server stores the secret with the account, and never shows it again

function tick() {
    if (!enrolled) return;
    const t = now();
    show('code', codeAt(enrolled.secret, t).replace(/^(\d{3})/, '$1 '));
    show('left', `${PERIOD - (t % PERIOD)} s`);
}
export const ticker = SCHEDULER.interval(tick, 250);
// A hidden tab needs no tick: stop it, and resume when the tab is shown again.
document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') ticker.stop();
    else ticker.start();
});

el('enrol').addEventListener('submit', (event) => {
    event.preventDefault();
    const { secret, secretBytes: bytes, uri } = TOTP.enroll({
        issuer: el('issuer').value, account: el('account').value, secretLen: 20,
    });
    enrolled = { secret };
    show('secret', grouped(secret));
    show('uri', uri); // the text a QR code would carry
    const typed = secretBytes(grouped(secret).toLowerCase());
    const same = typed.length === bytes.length && typed.every((b, i) => b === bytes[i]);
    show('same', same ? `yes, the same ${bytes.length} bytes` : 'no');
    tick();
    ticker.start();
});

el('check').addEventListener('click', () => {
    show('verdict', enrolled ? verdict(el('typed').value, enrolled.secret)
        : 'Enrol first: there is no secret to check against.');
});

index.html

htmlApache-2.043 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Set up two-factor codes (TOTP)</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Set up two-factor codes (TOTP)</h1>
    <h2>Enrol</h2>
    <form id="enrol">
      <label for="issuer">Issuer (the name the authenticator app shows)</label>
      <input id="issuer" type="text" value="Example App" autocomplete="off">
      <label for="account">Account</label>
      <input id="account" type="text" value="reader@example.org" autocomplete="off">
      <p><button type="submit">Enrol</button></p>
    </form>
    <dl>
      <dt>Secret (base32, in groups of four, to type by hand)</dt><dd><code id="secret"></code></dd>
      <dt>otpauth URI (what a QR code would carry)</dt><dd><code id="uri"></code></dd>
      <dt>Typed in lowercase with the spaces, it decodes to</dt><dd><output id="same"></output></dd>
    </dl>
    <h2>Current code</h2>
    <dl>
      <dt>Code</dt><dd><output id="code"></output></dd>
      <dt>Next code in</dt><dd><output id="left"></output></dd>
    </dl>
    <h2>Check a code</h2>
    <label for="typed">Code from the authenticator app</label>
    <input id="typed" type="text" inputmode="numeric" autocomplete="one-time-code">
    <p><button id="check" type="button">Check the code</button></p>
    <p><output id="verdict"></output></p>
  </main>
</body>
</html>