Generating 2FA (TOTP) codes in scripts: pyotp, otplib, and when an API is a bad idea
Sooner or later an automation needs a 2FA code: a test account in CI, a login script for your own accounts, a bulk check of accounts you manage. There are two ways to get one: compute it yourself, or ask an API. Here's h
Sooner or later an automation needs a 2FA code: a test account in CI, a login script for your own accounts, a bulk check of accounts you manage. There are two ways to get one: compute it yourself, or ask an API. Here's how both work and why the first is almost always better.
TOTP in one paragraph
A TOTP code is HMAC-SHA1(secret, floor(unix_time / 30)), dynamically truncated to 6 digits (RFC 6238). The secret is the Base32 string behind the QR code you scan when enabling 2FA. If two machines share the secret and agree on the time, they produce the same code.
Option 1: compute locally (recommended)
# pip install pyotp
import pyotp
print(pyotp.TOTP("JBSWY3DPEHPK3PXP").now())
// npm i otplib
import { authenticator } from "otplib";
console.log(authenticator.generate("JBSWY3DPEHPK3PXP"));
The key never leaves your machine. Keep the clock synced (NTP): a drift of about 30 seconds is the number one cause of "invalid code".
Option 2: an HTTP API
Services like 2fa.live and Code2FA expose GET /tok/{KEY} returning {"token":"123456"}:
curl https://api.code2fa.co/tok/JBSWY3DPEHPK3PXP
Convenient from no-code tools, but the key now travels in a URL and can land in proxy logs, server logs and shell history. That's true for every such API, including the one I run. Use it only for low-value keys.
Rules of thumb
- Prefer official API tokens (GitHub personal access tokens, cloud service keys) over automating 2FA entry.
- Never paste real keys into a site you haven't checked: open DevTools β Network and look for requests carrying the key, or try the page offline.
- Rotate the key if it ever touched a log.
- Only automate 2FA for accounts you own or are allowed to manage.
Longer version with Steam Guard, bulk mode and clock-drift debugging: Get 2FA codes with an API or code.
The zero-dependency engine behind Code2FA (TOTP/HOTP, Steam Guard, Google Authenticator export parser, MIT): github.com/nguyennoben-a11y/code2fa-totp
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.