auth.totp
Authenticator-app two-factor codes (TOTP RFC 6238, HOTP RFC 4226): secret, QR URI, codes, verify with window and drift.
1.0.0 · published 2026-10-10 by charlie · Anterra
Pinned by 80 tests, run in TypeScript, Python and Rust.totpSecret 8 · totpUri 11 · hotpCode 20 · totpCode 19 · verifyTotp 22
What it does
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
The functions
A group: 5 functions that work together, each in its own file, each pinned by its own tests in TypeScript, Python and Rust. A project can install only the ones it calls.
- totpSecret (randomBytes: int[]) -> string
- totpUri (issuer: string, account: string, secret: string, settings: TotpSettings) -> string
- hotpCode (secret: string, counter: int, digits: int, algorithm: TotpAlgorithm) -> string
- totpCode (secret: string, now: int, settings: TotpSettings) -> string
- verifyTotp (secret: string, code: string, now: int, settings: TotpSettings, window: int, drift: int, lastUsedStep: int?) -> TotpCheck
The types it declares, generated into your project
export type TotpAlgorithm = "SHA1" | "SHA256";
/** How codes are made. Authenticator apps expect SHA1, 6 digits, 30 seconds. */
export interface TotpSettings {
readonly algorithm: TotpAlgorithm;
/** 6, 7 or 8 */
readonly digits: number;
/** seconds per step, 1 or more; 30 is the default everywhere */
readonly period: number;
}
export type TotpReason = "wrong_code" | "malformed_code" | "replayed";
/** Whether a code was accepted, and what to store if it was. */
export interface TotpCheck {
readonly valid: boolean;
/** the time step that matched; store it as lastUsedStep */
readonly step: number | null;
/** matched step minus expected step; store it to centre the next window */
readonly drift: number | null;
/** why not, when not valid */
readonly reason: TotpReason | null;
}
Once installed, your code imports each one from the group's module.
totpSecret throws on bad input 8 tests
export function totpSecret(randomBytes: readonly number[]): string
| randomBytes | int[] | at least 16 bytes from a secure random source, read by the caller; 20 is usual |
| returns | string | the secret as unpadded base32, to store (encrypted) and to show in the QR code |
For example
totpSecret(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)→ AAAQEAYEAUDAOCAJBIFQYDIOB4IBCEQT 20 random bytes, the usual size, are 32 characterstotpSecret(255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240)→ 777P37H37L47R57W6X2PH4XR6A 16 bytes, the least accepted (RFC 4226 R6: 128 bits)totpSecret(49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48)→ GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ the RFC 4226 test secret
import { totpSecret } from "#fune/auth.totp@^1";
import { base32Encode } from "./encoding_base32_base32_encode.ts";
/**
* A new secret from the caller's random bytes, as unpadded base32. The bytes
* come from a secure source (crypto.getRandomValues, secrets.token_bytes),
* which a pure function cannot read for itself.
*/
export function totpSecret(randomBytes: readonly number[]): string {
if (!Array.isArray(randomBytes) && !(randomBytes instanceof Uint8Array)) {
throw new TypeError("randomBytes must be a list of integers from 0 to 255");
}
for (let i = 0; i < randomBytes.length; i++) {
const b = randomBytes[i];
if (typeof b !== "number" || !Number.isInteger(b) || b < 0 || b > 255) {
throw new RangeError("randomBytes must be a list of integers from 0 to 255");
}
}
if (randomBytes.length < 16) throw new RangeError("randomBytes must hold at least 16 bytes (128 bits)");
return base32Encode(randomBytes, false);
}totpUri throws on bad input 11 tests
export function totpUri(issuer: string, account: string, secret: string, settings: TotpSettings): string
| issuer | string | your app's name, shown in the authenticator; no colon |
| account | string | the user's email or username; no colon |
| secret | string | the base32 secret from totpSecret |
| settings | TotpSettings | the algorithm, digits and period; SHA1, 6 and 30 for every authenticator app |
| returns | string | the otpauth://totp/ URI to put in a QR code |
For example
totpUri(Acme, ada@example.com, JBSWY3DPEHPK3PXP, algorithm SHA1, digits 6, period 30)→ otpauth://totp/Acme:ada%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=Acme&algorithm=SHA1&digits=6&period=30 the usual QR code: SHA1, 6 digits, 30 secondstotpUri(Acme Corp, ada lovelace@example.com, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30)→ otpauth://totp/Acme%20Corp:ada%20lovelace%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme%20Corp&algorithm=SHA1&digits=6&period=30 spaces and an at sign are percent-encoded in the label and the issuertotpUri(Acme, ada, gezdgnbvgy3tqojqgezdgnbvgy3tqojq, algorithm SHA1, digits 6, period 30)→ otpauth://totp/Acme:ada?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme&algorithm=SHA1&digits=6&period=30 a lower-case, padded secret is written back canonical
import { totpUri } from "#fune/auth.totp@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { type TotpSettings } from "./auth_totp_types.ts";
import { checkTotpSettings, totpSecretKey } from "./auth_totp_hotp_code.ts"; ← hotpCode, another function of this group · built into the same file, even by a slim install
import { base32Encode } from "./encoding_base32_base32_encode.ts";
// RFC 3986 percent-encoding: everything but the unreserved characters.
function percentEncode(text: string): string {
return encodeURIComponent(text).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
}
function checkLabelPart(value: string, name: string): void {
if (typeof value !== "string") throw new TypeError(`${name} must be text`);
if (value.length === 0) throw new RangeError(`${name} must not be empty`);
if (value.includes(":")) throw new RangeError(`${name} must not contain a colon`);
}
/**
* The Key Uri Format authenticator apps scan from a QR code:
* otpauth://totp/Issuer:account?secret=...&issuer=...&algorithm=...&digits=...&period=...
* The secret is written back in canonical form (upper case, unpadded).
*/
export function totpUri(issuer: string, account: string, secret: string, settings: TotpSettings): string {
checkLabelPart(issuer, "issuer");
checkLabelPart(account, "account");
checkTotpSettings(settings);
const canonical = base32Encode(totpSecretKey(secret), false);
return (
`otpauth://totp/${percentEncode(issuer)}:${percentEncode(account)}` +
`?secret=${canonical}&issuer=${percentEncode(issuer)}` +
`&algorithm=${settings.algorithm}&digits=${settings.digits}&period=${settings.period}`
);
}hotpCode throws on bad input 20 tests
export function hotpCode(secret: string, counter: number, digits: number, algorithm: TotpAlgorithm): string
| secret | string | the base32 secret |
| counter | int | the moving factor, 0 to 2^53 - 1 |
| digits | int | 6, 7 or 8 |
| algorithm | TotpAlgorithm | |
| returns | string | the code, zero-padded to digits |
For example
hotpCode(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 6, SHA1)→ 755224 RFC 4226 Appendix D: counter 0hotpCode(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1, 6, SHA1)→ 287082 RFC 4226 Appendix D: counter 1hotpCode(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 2, 6, SHA1)→ 359152 RFC 4226 Appendix D: counter 2
import { hotpCode } from "#fune/auth.totp@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { type TotpAlgorithm, type TotpSettings } from "./auth_totp_types.ts";
import { hmacSha1 } from "./crypto_hmac_sha1.ts"; ← from crypto.hmac-sha1 ^1.0.0 · built alongside by fune
import { hmacSha256 } from "./crypto_hmac_sha256.ts"; ← from crypto.hmac-sha256 ^1.0.0 · built alongside by fune
import { base32Decode } from "./encoding_base32_base32_decode.ts";
const MAX_SAFE = 9007199254740991;
/** Whole number from 0 to 2^53 - 1: the range all three languages agree on. */
export function isTotpWhole(value: unknown): value is number {
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= MAX_SAFE;
}
export function checkTotpDigits(digits: number): void {
if (digits !== 6 && digits !== 7 && digits !== 8) throw new RangeError("digits must be 6, 7 or 8");
}
export function checkTotpAlgorithm(algorithm: string): void {
if (algorithm !== "SHA1" && algorithm !== "SHA256") throw new RangeError("algorithm must be SHA1 or SHA256");
}
export function checkTotpSettings(settings: TotpSettings): void {
if (typeof settings !== "object" || settings === null) throw new TypeError("settings must be a TotpSettings record");
checkTotpAlgorithm(settings.algorithm);
checkTotpDigits(settings.digits);
if (!isTotpWhole(settings.period) || settings.period < 1) {
throw new RangeError("period must be a whole number of seconds, 1 or more");
}
}
/**
* The secret's bytes. Old Google Authenticator secrets are 80 bits, so 10
* bytes is the least accepted here; new secrets from totpSecret are 16 or more.
*/
export function totpSecretKey(secret: string): readonly number[] {
const key = base32Decode(secret);
if (key.length < 10) throw new RangeError("secret must decode to at least 10 bytes");
return key;
}
/** RFC 4226 section 5.3: HMAC of the 8-byte big-endian counter, then dynamic truncation. */
export function hotpFromKey(key: readonly number[], counter: number, digits: number, algorithm: TotpAlgorithm): string {
const message: number[] = [];
const high = Math.floor(counter / 4294967296);
const low = counter % 4294967296;
for (const word of [high, low]) message.push(Math.floor(word / 16777216) % 256, Math.floor(word / 65536) % 256, Math.floor(word / 256) % 256, word % 256);
const mac = algorithm === "SHA1" ? hmacSha1(key, message) : hmacSha256(key, message);
const offset = mac[mac.length - 1] & 15;
const binary = (mac[offset] & 127) * 16777216 + mac[offset + 1] * 65536 + mac[offset + 2] * 256 + mac[offset + 3];
const code = String(binary % 10 ** digits);
return "0".repeat(digits - code.length) + code;
}
/** The RFC 4226 HOTP code for one counter value. */
export function hotpCode(secret: string, counter: number, digits: number, algorithm: TotpAlgorithm): string {
if (!isTotpWhole(counter)) throw new RangeError("counter must be a whole number from 0 to 2^53 - 1");
checkTotpDigits(digits);
checkTotpAlgorithm(algorithm);
return hotpFromKey(totpSecretKey(secret), counter, digits, algorithm);
}totpCode throws on bad input 19 tests
export function totpCode(secret: string, now: number, settings: TotpSettings): string
| secret | string | the base32 secret |
| now | int | the current time in Unix seconds, read by the caller |
| settings | TotpSettings | |
| returns | string | the code for the time step now falls in |
For example
totpCode(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59, algorithm SHA1, digits 8, period 30)→ 94287082 RFC 6238 Appendix B: SHA1 at 59totpCode(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 59, algorithm SHA256, digits 8, period 30)→ 46119246 RFC 6238 Appendix B: SHA256 at 59totpCode(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,111,111,109, algorithm SHA1, digits 8, period 30)→ 07081804 RFC 6238 Appendix B: SHA1 at 1111111109
import { totpCode } from "#fune/auth.totp@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { type TotpSettings } from "./auth_totp_types.ts";
import { checkTotpSettings, hotpFromKey, isTotpWhole, totpSecretKey } from "./auth_totp_hotp_code.ts"; ← hotpCode, another function of this group · built into the same file, even by a slim install
export function checkTotpNow(now: number): void {
if (!isTotpWhole(now)) throw new RangeError("now must be a whole number of seconds from 0 to 2^53 - 1");
}
/** The RFC 6238 code for the time step now falls in: HOTP at floor(now / period). */
export function totpCode(secret: string, now: number, settings: TotpSettings): string {
checkTotpNow(now);
checkTotpSettings(settings);
const key = totpSecretKey(secret);
return hotpFromKey(key, Math.floor(now / settings.period), settings.digits, settings.algorithm);
}verifyTotp throws on bad input 22 tests
export function verifyTotp(secret: string, code: string, now: number, settings: TotpSettings, window: number, drift: number, lastUsedStep: number | null): TotpCheck
| secret | string | the base32 secret |
| code | string | what the user typed; spaces are ignored |
| now | int | the current time in Unix seconds, read by the caller |
| settings | TotpSettings | |
| window | int | steps accepted either side of the expected one, 0 to 10; 1 is usual |
| drift | int | the user's known clock drift in steps, from an earlier check; 0 when none |
| lastUsedStep | int? | the step of the last code this user signed in with, or null; that step and earlier ones are refused |
| returns | TotpCheck | valid with the step and drift to store, or not valid with the reason |
For example
verifyTotp(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, —)→ valid true, step 37,037,037, drift 0, reason — the current code is valid, no driftverifyTotp(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 081804, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, —)→ valid true, step 37,037,036, drift -1, reason — the previous step's code inside a window of 1, drift -1verifyTotp(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 266759, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, —)→ valid true, step 37,037,038, drift 1, reason — the next step's code, drift +1
import { verifyTotp } from "#fune/auth.totp@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { type TotpCheck, type TotpSettings } from "./auth_totp_types.ts";
import { checkTotpSettings, hotpFromKey, totpSecretKey } from "./auth_totp_hotp_code.ts"; ← hotpCode, another function of this group · built into the same file, even by a slim install
import { checkTotpNow } from "./auth_totp_totp_code.ts"; ← totpCode, another function of this group · built into the same file, even by a slim install
import { constantTimeEqual } from "./crypto_constant_time_equal.ts"; ← from crypto.constant-time-equal ^1.0.0 · built alongside by fune
function ascii(text: string): number[] {
const out: number[] = [];
for (let i = 0; i < text.length; i++) out.push(text.charCodeAt(i) & 255);
return out;
}
/**
* Checks a typed code against the steps around now (centred on the user's
* known drift), closest first, earlier first on a tie. Every step in the
* window is computed and compared in constant time, so the time taken does
* not say which step matched. A step at or before lastUsedStep is refused as
* replayed: a code is good for one sign-in only.
*/
export function verifyTotp(
secret: string,
code: string,
now: number,
settings: TotpSettings,
window: number,
drift: number,
lastUsedStep: number | null,
): TotpCheck {
checkTotpNow(now);
checkTotpSettings(settings);
if (typeof window !== "number" || !Number.isInteger(window) || window < 0 || window > 10) {
throw new RangeError("window must be a whole number from 0 to 10");
}
if (typeof drift !== "number" || !Number.isInteger(drift) || drift < -1000 || drift > 1000) {
throw new RangeError("drift must be a whole number from -1000 to 1000");
}
if (lastUsedStep !== null && (typeof lastUsedStep !== "number" || !Number.isInteger(lastUsedStep))) {
throw new TypeError("lastUsedStep must be a whole number or null");
}
if (typeof code !== "string") throw new TypeError("code must be text");
const key = totpSecretKey(secret);
const typed = code.split(" ").join("");
if (typed.length !== settings.digits || !/^[0-9]+$/.test(typed)) {
return { valid: false, step: null, drift: null, reason: "malformed_code" };
}
const expected = Math.floor(now / settings.period);
const centre = expected + drift;
const typedBytes = ascii(typed);
let accepted: number | null = null;
let replayed = false;
for (let distance = 0; distance <= window; distance++) {
for (const step of distance === 0 ? [centre] : [centre - distance, centre + distance]) {
if (step < 0) continue;
const matches = constantTimeEqual(ascii(hotpFromKey(key, step, settings.digits, settings.algorithm)), typedBytes);
if (!matches) continue;
if (lastUsedStep !== null && step <= lastUsedStep) replayed = true;
else if (accepted === null) accepted = step;
}
}
if (accepted !== null) return { valid: true, step: accepted, drift: accepted - expected, reason: null };
return { valid: false, step: null, drift: null, reason: replayed ? "replayed" : "wrong_code" };
}Install
fune build
With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 4 dependencies, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add auth.totp
That builds the whole group. To build only what you call, and whatever it uses inside the group:
fune add auth.totp --only totpSecret
The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./auth.totp-1.0.0-typescript.fune, or fetch it from a terminal with fune pull auth.totp@1.0.0:typescript.
The whole function, every language, is one file too: auth.totp-1.0.0.fune, 62,297 bytes, sha256 92c28b8b0cdbe81f910af8b79eaf833d66b5aaf7d830e292e0668d19dfdf7e59. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
// fune: before auth.totp.totpSecret
// fune: before auth.totp.totpUri
// fune: before auth.totp.hotpCode
// fune: before auth.totp.totpCode
// fune: before auth.totp.verifyTotp
after — your function gets the result and the arguments, and returns the final result.
// fune: after auth.totp.totpSecret
// fune: after auth.totp.totpUri
// fune: after auth.totp.hotpCode
// fune: after auth.totp.totpCode
// fune: after auth.totp.verifyTotp
replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.
// fune: replace crypto.constant-time-equal in auth.totp
// fune: replace crypto.hmac-sha1 in auth.totp
// fune: replace crypto.hmac-sha256 in auth.totp
// fune: replace encoding.base32 in auth.totp
step — your function runs at a numbered point inside a function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show auth.totp --steps.
// fune: step auth.totp.<fn> after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
totpSecret 8 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| 20 random bytes, the usual size, are 32 characters | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 | → | AAAQEAYEAUDAOCAJBIFQYDIOB4IBCEQT |
| 16 bytes, the least accepted (RFC 4226 R6: 128 bits) | 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240 | → | 777P37H37L47R57W6X2PH4XR6A |
| the RFC 4226 test secret | 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48 | → | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ |
| 32 bytes need no padding character either way, 52 characters unpadded | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 | → | AAAQEAYEAUDAOCAJBIFQYDIOB4IBCEQTCQKRMFYYDENBWHA5DYPQ |
| 15 bytes are too few | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 | → | error: randomBytes must hold at least 16 bytes (128 bits) |
| no bytes at all | → | error: randomBytes must hold at least 16 bytes (128 bits) | |
| a value above 255 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 300 | → | error: randomBytes must be a list of integers from 0 to 255 |
| a fraction is not a byte | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1.5 | → | error: randomBytes must be a list of integers from 0 to 255 |
totpUri 11 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| the usual QR code: SHA1, 6 digits, 30 seconds | Acme, ada@example.com, JBSWY3DPEHPK3PXP, algorithm SHA1, digits 6, period 30 | → | otpauth://totp/Acme:ada%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=Acme&algorithm=SHA1&digits=6&period=30 |
| spaces and an at sign are percent-encoded in the label and the issuer | Acme Corp, ada lovelace@example.com, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 | → | otpauth://totp/Acme%20Corp:ada%20lovelace%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme%20Corp&algorithm=SHA1&digits=6&period=30 |
| a lower-case, padded secret is written back canonical | Acme, ada, gezdgnbvgy3tqojqgezdgnbvgy3tqojq, algorithm SHA1, digits 6, period 30 | → | otpauth://totp/Acme:ada?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme&algorithm=SHA1&digits=6&period=30 |
| SHA256, 8 digits, 60 seconds | Acme, ada, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, algorithm SHA256, digits 8, period 60 | → | otpauth://totp/Acme:ada?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&issuer=Acme&algorithm=SHA256&digits=8&period=60 |
| non-ASCII text is percent-encoded as UTF-8 | Café Ltd, zoë@example.com, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 | → | otpauth://totp/Caf%C3%A9%20Ltd:zo%C3%AB%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Caf%C3%A9%20Ltd&algorithm=SHA1&digits=6&period=30 |
| a colon in the issuer would break the label | Acme:Corp, ada, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 | → | error: issuer must not contain a colon |
| a colon in the account | Acme, ada:1, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 | → | error: account must not contain a colon |
| an empty issuer | , ada, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 | → | error: issuer must not be empty |
| an empty account | Acme, , GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 | → | error: account must not be empty |
| a secret that is not base32 | Acme, ada, JBSW Y3DP, algorithm SHA1, digits 6, period 30 | → | error: base32 text may only contain A-Z and 2-7 |
Show the other 1 test
| Case | Arguments | Expected | |
|---|---|---|---|
| 5 digits is not a code length authenticators show | Acme, ada, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 5, period 30 | → | error: digits must be 6, 7 or 8 |
hotpCode 20 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| RFC 4226 Appendix D: counter 0 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 6, SHA1 | → | 755224 |
| RFC 4226 Appendix D: counter 1 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1, 6, SHA1 | → | 287082 |
| RFC 4226 Appendix D: counter 2 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 2, 6, SHA1 | → | 359152 |
| RFC 4226 Appendix D: counter 3 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 3, 6, SHA1 | → | 969429 |
| RFC 4226 Appendix D: counter 4 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 4, 6, SHA1 | → | 338314 |
| RFC 4226 Appendix D: counter 5 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 5, 6, SHA1 | → | 254676 |
| RFC 4226 Appendix D: counter 6 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 6, 6, SHA1 | → | 287922 |
| RFC 4226 Appendix D: counter 7 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 7, 6, SHA1 | → | 162583 |
| RFC 4226 Appendix D: counter 8 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 8, 6, SHA1 | → | 399871 |
| RFC 4226 Appendix D: counter 9 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 9, 6, SHA1 | → | 520489 |
Show the other 10 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| 8 digits at counter 0 (reference: Python hmac) | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 8, SHA1 | → | 84755224 |
| SHA256 at counter 1 (reference: Python hmac) | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 1, 6, SHA256 | → | 119246 |
| a counter above 2^32 uses all eight counter bytes (reference: Python hmac) | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 4,294,967,297, 6, SHA1 | → | 108930 |
| the largest counter, 2^53 - 1 (reference: Python hmac) | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 9,007,199,254,740,991, 6, SHA1 | → | 891307 |
| a negative counter | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, -1, 6, SHA1 | → | error: counter must be a whole number from 0 to 2^53 - 1 |
| a fractional counter | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1.5, 6, SHA1 | → | error: counter must be a whole number from 0 to 2^53 - 1 |
| 9 digits | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 9, SHA1 | → | error: digits must be 6, 7 or 8 |
| SHA512 is not offered | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 6, SHA512 | → | error: algorithm must be SHA1 or SHA256 |
| a secret under 80 bits | AAAAAAAAAAAAAAA, 0, 6, SHA1 | → | error: secret must decode to at least 10 bytes |
| a secret with a trailing newline | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ , 0, 6, SHA1 | → | error: base32 text may only contain A-Z and 2-7 |
totpCode 19 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| RFC 6238 Appendix B: SHA1 at 59 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59, algorithm SHA1, digits 8, period 30 | → | 94287082 |
| RFC 6238 Appendix B: SHA256 at 59 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 59, algorithm SHA256, digits 8, period 30 | → | 46119246 |
| RFC 6238 Appendix B: SHA1 at 1111111109 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,111,111,109, algorithm SHA1, digits 8, period 30 | → | 07081804 |
| RFC 6238 Appendix B: SHA256 at 1111111109 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 1,111,111,109, algorithm SHA256, digits 8, period 30 | → | 68084774 |
| RFC 6238 Appendix B: SHA1 at 1111111111 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,111,111,111, algorithm SHA1, digits 8, period 30 | → | 14050471 |
| RFC 6238 Appendix B: SHA256 at 1111111111 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 1,111,111,111, algorithm SHA256, digits 8, period 30 | → | 67062674 |
| RFC 6238 Appendix B: SHA1 at 1234567890 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,234,567,890, algorithm SHA1, digits 8, period 30 | → | 89005924 |
| RFC 6238 Appendix B: SHA256 at 1234567890 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 1,234,567,890, algorithm SHA256, digits 8, period 30 | → | 91819424 |
| RFC 6238 Appendix B: SHA1 at 2000000000 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 2,000,000,000, algorithm SHA1, digits 8, period 30 | → | 69279037 |
| RFC 6238 Appendix B: SHA256 at 2000000000 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 2,000,000,000, algorithm SHA256, digits 8, period 30 | → | 90698825 |
Show the other 9 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| RFC 6238 Appendix B: SHA1 at 20000000000 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 20,000,000,000, algorithm SHA1, digits 8, period 30 | → | 65353130 |
| RFC 6238 Appendix B: SHA256 at 20000000000 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 20,000,000,000, algorithm SHA256, digits 8, period 30 | → | 77737706 |
| 6 digits, the last second of a step (59 is still step 1) | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59, algorithm SHA1, digits 6, period 30 | → | 287082 |
| the first second of the next step | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 60, algorithm SHA1, digits 6, period 30 | → | 359152 |
| time zero is step zero | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, algorithm SHA1, digits 6, period 30 | → | 755224 |
| a 60-second period halves the step (reference: Python hmac) | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,111,111,111, algorithm SHA1, digits 6, period 60 | → | 360094 |
| a time before 1970 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, -1, algorithm SHA1, digits 6, period 30 | → | error: now must be a whole number of seconds from 0 to 2^53 - 1 |
| a period of 0 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59, algorithm SHA1, digits 6, period 0 | → | error: period must be a whole number of seconds, 1 or more |
| a fractional time | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59.5, algorithm SHA1, digits 6, period 30 | → | error: now must be a whole number of seconds from 0 to 2^53 - 1 |
verifyTotp 22 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| the current code is valid, no drift | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid true, step 37,037,037, drift 0, reason — |
| the previous step's code inside a window of 1, drift -1 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 081804, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid true, step 37,037,036, drift -1, reason — |
| the next step's code, drift +1 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 266759, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid true, step 37,037,038, drift 1, reason — |
| two steps old is outside a window of 1 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 731029, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid false, step —, drift —, reason wrong_code |
| a stored drift of -2 centres the window: two steps old is now the middle | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 731029, 1,111,111,111, algorithm SHA1, digits 6, period 30, 0, -2, — | → | valid true, step 37,037,035, drift -2, reason — |
| window 0 accepts only the centre | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 266759, 1,111,111,111, algorithm SHA1, digits 6, period 30, 0, 0, — | → | valid false, step —, drift —, reason wrong_code |
| spaces in a typed code are ignored | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050 471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid true, step 37,037,037, drift 0, reason — |
| the code already used at this step is replayed | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, 37,037,037 | → | valid false, step —, drift —, reason replayed |
| a later step than the last one used is fine | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 266759, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, 37,037,037 | → | valid true, step 37,037,038, drift 1, reason — |
| an older code after a newer one was used is replayed | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 081804, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, 37,037,037 | → | valid false, step —, drift —, reason replayed |
Show the other 12 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| five digits is malformed, not wrong | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 05047, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid false, step —, drift —, reason malformed_code |
| letters are malformed | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 12a456, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid false, step —, drift —, reason malformed_code |
| full-width digits are malformed | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 123456, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid false, step —, drift —, reason malformed_code |
| a code that matches no step in the window | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 000000, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid false, step —, drift —, reason wrong_code |
| at time zero the window never reaches a negative step | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 755224, 0, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid true, step 0, drift 0, reason — |
| RFC 6238 SHA256, 8 digits, at 2000000000 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 90698825, 2,000,000,000, algorithm SHA256, digits 8, period 30, 1, 0, — | → | valid true, step 66,666,666, drift 0, reason — |
| a window of 11 is too wide | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 11, 0, — | → | error: window must be a whole number from 0 to 10 |
| a negative window | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, -1, 0, — | → | error: window must be a whole number from 0 to 10 |
| a drift beyond 1000 steps | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 1,001, — | → | error: drift must be a whole number from -1000 to 1000 |
| a fractional last used step | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, 1.5 | → | error: lastUsedStep must be a whole number or null |
| the code as a number rather than text | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 123,456, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | error: code must be text |
| a secret that is too short is an error, not a wrong code | AAAAAAAA, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | error: secret must decode to at least 10 bytes |
Verification
Verified by the operator, not the sandbox 80 test vectors declared; none run by the registry.
Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.
Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON
More from the author
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
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).