Functional Weave
Code in Rust

auth.totp@1.0.0

README.md

4,065 bytes · view raw

# auth.totp

Two-factor sign-in with an authenticator app (Google Authenticator, Microsoft
Authenticator, 1Password, Authy): TOTP from RFC 6238, which is HOTP from
RFC 4226 counted in time steps. Everything is pure: the random bytes and the
time come from the caller.

## Setting it up for a user

```ts
const secret = totpSecret([...crypto.getRandomValues(new Uint8Array(20))]);
const settings = { algorithm: "SHA1", digits: 6, period: 30 };
const uri = totpUri("Acme", user.email, secret, settings); // render as a QR code
// store the secret (encrypted at rest) as pending; confirm it with one
// verifyTotp before switching two-factor on, so a mis-scan never locks them out
```

`totpSecret` takes at least 16 random bytes (RFC 4226 R6 asks for 128 bits,
recommends 160; 20 is what most services use) and returns unpadded base32,
the form the otpauth:// URI and manual entry both use. `totpUri` writes the
Google Authenticator Key Uri Format:
`otpauth://totp/Acme:ada%40example.com?secret=...&issuer=Acme&algorithm=SHA1&digits=6&period=30`.
The issuer and account are percent-encoded per RFC 3986 (unreserved
characters kept, the rest as UTF-8 `%XX`), and a colon in either is refused
because it would break the `Issuer:account` label.

**Use SHA1, 6 digits, 30 seconds** unless you control the authenticator: many
apps ignore `algorithm`, `digits` and `period` and silently show the wrong
codes. SHA1 here is HMAC-SHA1, which is still sound (see `crypto.sha1`).
SHA256 is offered for authenticators that honour it; SHA-512 is not offered,
because the registry has no SHA-512 yet.

## Checking a code

```ts
const check = verifyTotp(secret, typed, nowSeconds, settings, 1, user.totpDrift ?? 0, user.totpLastStep);
if (check.valid) save({ totpLastStep: check.step, totpDrift: check.drift });
```

- **Window.** Steps `drift - window` to `drift + window` around the expected
  step are accepted (`window` 0 to 10; 1 is RFC 6238's recommendation, which
  allows about 30 seconds of clock difference either way). They are tried
  closest first, the earlier step first on a tie, so the answer is
  deterministic.
- **Drift.** `drift` in the result is how many steps the user's device is off.
  Store it and pass it next time to centre the window on that device's clock
  (RFC 6238 section 6), keeping the window small.
- **Replay.** Pass the `step` of the user's last accepted code as
  `lastUsedStep`; a code for that step or an earlier one is refused with
  `replayed`, so a code seen over a shoulder or in a log cannot be used
  again (RFC 6238 section 5.2). Store the new `step` after every success.
- **Typed input.** Spaces are removed first (`123 456`); anything that is not
  then exactly `digits` ASCII digits is `malformed_code`, not `wrong_code`.
- Every step in the window is computed and compared with
  `crypto.constant-time-equal`, so timing does not say which step matched.

Rate-limit attempts (see `auth.login-throttle`): six digits are a million
codes, and a window of 1 accepts three of them.

A secret must decode to at least 10 bytes (80 bits, the size older services
issued) so existing secrets keep working; new ones are 16 or more. Base32
errors in a secret come straight from `encoding.base32`; strip spaces from a
secret shown in groups before passing it.

`hotpCode` is the counter-based RFC 4226 code on its own, for hardware tokens
or email/SMS codes keyed by a counter. Counters and times are 0 to 2^53 - 1,
the range all three languages share.

## Vectors

RFC 4226 Appendix D (all ten counters) and RFC 6238 Appendix B (SHA1 and
SHA256, all six times, 8 digits), with the test secrets
`12345678901234567890` (base32 `GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ`) and
`12345678901234567890123456789012`. Other expected codes were computed with
Python's `hmac` module as an independent reference, and the URIs with
`urllib.parse.quote`.

Sources: RFC 4226, HOTP (https://www.rfc-editor.org/rfc/rfc4226); RFC 6238,
TOTP (https://www.rfc-editor.org/rfc/rfc6238); Key Uri Format
(https://github.com/google/google-authenticator/wiki/Key-Uri-Format).