TOTP Generator — 2FA Codes for Automation
Pricing
from $0.10 / 1,000 totp code delivereds
TOTP Generator — 2FA Codes for Automation
Generate current 2FA TOTP codes from a Base32 secret or otpauth URI. Get 6/8-digit codes, expiration times and fresh-code waiting via API, Python or n8n.
Pricing
from $0.10 / 1,000 totp code delivereds
Rating
0.0
(0)
Developer
Apivault Labs
Maintained by CommunityActor stats
0
Bookmarked
1
Total users
0
Monthly active users
9 days ago
Last modified
Categories
Features
Share

Generate a current time-based one-time password from a Base32 secret or an otpauth://totp/ provisioning URI. Use it in an authorized browser test, an internal workflow, or an API integration that already has access to its own authenticator secret. The result includes the code as a string and its expiration time.
One key → one current 2FA code → an exact expiration time. Supports SHA1, SHA256 and SHA512, six or eight digits, configurable periods, and waiting for a fresh code. No proxy or third-party generator account is required.
The Actor computes RFC 6238 TOTP locally inside its run. It does not contact 2fa.cn or another code-generation website. You must already have the shared authenticator secret; an account password, QR image, or previous six-digit code is insufficient.
Quick start
Run with your own authorized key in the encrypted Secret field. For a disposable demonstration, use this public RFC test key, which must never protect an account:
{"secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ","minValiditySeconds": 5}
After the run succeeds, open Code and expiration in the Output tab, or read its default Key-value store record OUTPUT. SUMMARY gives the run status and settings without duplicating the secret or code. There are no Dataset rows. Check validUntil before using the code: startup, storage requests, and delivery introduce latency. A successful run does not mean the code is still valid when your next workflow step starts. The secret field is deliberately not prefilled: supplying no key fails rather than silently generating a demonstration code.
Supported inputs
| Setting | Behavior |
|---|---|
secret | Required encrypted string: Base32 key or full otpauth://totp/... URI, up to 4,096 characters |
algorithm | auto (default), SHA1, SHA256, or SHA512 |
digits | String auto (default), 6, or 8 |
periodSeconds | 0 (default) uses URI value or 30; explicit periods 15–120 seconds |
minValiditySeconds | Default 5; integer 0–119, strictly less than the selected period |
Automatic settings honor URI parameters. For a raw key they select SHA1, six digits, and 30 seconds. An explicit setting that conflicts with an explicit URI parameter fails, rather than silently returning a different code. Base32 is case-insensitive; ASCII whitespace and hyphens are accepted. The decoded key must contain 10–128 bytes; malformed padding and noncanonical trailing bits are rejected.
URI example, again using a public test key:
{"secret": "otpauth://totp/Demo:public-test?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Demo&algorithm=SHA1&digits=8&period=30","digits": "auto"}
Supported URI parameters are secret, issuer, algorithm, digits, and period. Duplicate or unknown parameters, fragments, and HOTP URIs fail. Labels and issuers are not returned or logged.
Output and expiration
This deterministic illustration uses the public RFC key at Unix time 59 with eight digits. A live run uses the current server clock and returns a different code.
{"code": "94287082","algorithm": "SHA1","digits": 8,"periodSeconds": 30,"generatedAt": "1970-01-01T00:00:59.000Z","validFrom": "1970-01-01T00:00:30.000Z","validUntil": "1970-01-01T00:01:00.000Z","remainingSeconds": 1.0,"waitedSeconds": 0}
| Field | Meaning |
|---|---|
code | Six or eight characters, preserving leading zeros |
algorithm, digits, periodSeconds | Effective settings used for this result |
generatedAt | UTC time at computation |
validFrom, validUntil | Start inclusive and end exclusive of this TOTP window |
remainingSeconds | Seconds remaining at computation, not at client receipt |
waitedSeconds | Time spent waiting inside the generation step |
If the current code is close to expiration, the Actor waits for the next period. Setting minValiditySeconds to 0 disables that wait. Waiting is bounded to 125 seconds and does not retry indefinitely on a broken clock. There is one result per run; pagination and deduplication do not apply. Repeated runs within one period normally return the same code.
Practical workflows and integrations
| Scenario | Suggested input |
|---|---|
| Authorized browser automation | Raw key, default settings; obtain the code immediately before the login step |
| Import from a provisioning URI | URI with automatic settings |
| Eight-digit authenticator | digits: "8", matching the account configuration |
| SHA256 or SHA512 authenticator | Matching algorithm and period, or the provisioning URI |
| Avoid an almost expired code | Set a minimum validity that fits inside the selected period |
Use the standard Apify API, Python client, JavaScript client, or the generic Apify integration in n8n. Submit the secret in a JSON request body and keep the API token in your integration's credential store. Avoid putting secrets or codes in URL query strings. Start a run, wait for SUCCEEDED, then retrieve OUTPUT from the returned defaultKeyValueStoreId and inspect the expiration. Retrieve ERRORS for failed runs.
Return a code in one HTTP response
Apify's synchronous Key-value store endpoint returns this Actor's OUTPUT directly. Create a local input.json with your secret in a trusted environment. This shell example reads that file and writes the response to output.json; both files can contain sensitive material and should be removed when your workflow is done.
curl --fail-with-body --max-time 210 \-X POST 'https://api.apify.com/v2/acts/apivault_labs~totp-generator/run-sync?timeout=180&memory=256&maxTotalChargeUsd=0.03' \-H "Authorization: Bearer $APIFY_TOKEN" \-H 'Content-Type: application/json' \--data-binary @input.json \--output output.json
The synchronous HTTP connection can fail even when a run was started; do not blindly retry. For production workflows that must track completion, use asynchronous runs and save the run ID before polling. maxTotalChargeUsd caps a run; the example is not a price quote or a required fee.
Python client
Install the official apify-client package and keep APIFY_TOKEN and TOTP_SECRET in your environment or secret manager:
import osfrom datetime import datetime, timezonefrom apify_client import ApifyClientclient = ApifyClient(os.environ["APIFY_TOKEN"])run = client.actor("apivault_labs/totp-generator").call(run_input={"secret": os.environ["TOTP_SECRET"], "minValiditySeconds": 10},memory_mbytes=256, timeout_secs=180, max_total_charge_usd=0.03,)if not run or run["status"] != "SUCCEEDED":raise RuntimeError("TOTP run failed; inspect ERRORS.")record = client.key_value_store(run["defaultKeyValueStoreId"]).get_record("OUTPUT")if not record:raise RuntimeError("TOTP output is missing.")result = record["value"]expiry = datetime.fromisoformat(result["validUntil"].replace("Z", "+00:00"))if (expiry - datetime.now(timezone.utc)).total_seconds() < 3:raise RuntimeError("Code is too close to expiration.")# Pass result["code"] directly to your authorized next step. Do not log it.
n8n
Download the ready-to-import n8n workflow, follow the short setup guide, or read the full credential and error-handling instructions. The public JSON uses 17 standard nodes: start one run, track its ID, poll for completion, read OUTPUT/ERRORS, and reject a code with fewer than three seconds remaining on receipt. It contains no credentials or pinned data.
Import the file into n8n, then configure Custom Auth on Start TOTP run with the API token in the Authorization header and your key in the credential's JSON body. Use a separate, token-only Header Auth credential on the three GET nodes. Put keys in the credential editor, outside exported node parameters. Connect Result to an IF node checking ok: true; handled failures return ok: false without a code, even when n8n marks the execution green. Recheck validUntil immediately before the next step.
The example disables saving execution history and automatic HTTP retries. It does not guarantee zero retention across your instance, backups or downstream nodes. A lost start/billing response requires inspecting the existing Apify run before another request. A code rejected for expiry may already have incurred its Actor result event. Run IDs are carried in memory and are not durable recovery checkpoints after an n8n crash.
The exact downloadable JSON was tested on n8n 2.47.7 / Node 24 / Linux, with 12 fixture scenarios and three real runs against Actor 0.3.1. The download and checksum are public. Compatibility with older n8n releases and the n8n Cloud UI has not been verified.
For a minimal alternative, use HTTP Request with POST to the synchronous URL above, a stored Bearer credential, and a JSON body containing secret and minValiditySeconds. Set the HTTP timeout to at least 210 seconds and inspect code plus validUntil. With the generic Run Actor integration, retrieve Key-value store OUTPUT; Get Dataset Items returns an empty list for this Actor.
No dedicated n8n community node, Python wrapper package, MCP tool, or public saved Task is provided for this Actor. Generic integrations may keep workflow inputs and execution history; configure their retention separately.
Secret handling and storage
Apify encrypts the input field marked isSecret, including input submitted through the API. The SDK decrypts it inside the Actor. After reading, this Actor deletes the run's configured input record before validating or calculating a code. Cleanup failure stops generation. It does not log keys, provisioning URIs, labels, or generated codes, and does not write Dataset rows.
This is not a zero-retention service. The key exists in process memory during the run. Deletion through the storage API does not guarantee erasure from platform backups or infrastructure. If the run never starts or cannot reach storage, input deletion may not complete. Secrets saved in an Apify Task or external workflow are separate records and must be removed there. OUTPUT contains a usable code until expiry and remains stored according to platform retention or until you delete it. Keep run and storage access private. Do not share run/storage links containing access credentials.
Cost and runtime
The Actor uses pay-per-event pricing: $0.10 per 1,000 delivered codes ($0.0001 per code), plus Apify platform usage. There is no subscription or separate Actor start fee. One successful run delivers one code, even if the same code is returned by another run within its time window. Check the Actor's Pricing tab for the currently effective rate and any future activation date.
The totp-code-generated event is requested once, after OUTPUT and SUMMARY have been stored. Invalid input, cleanup/storage failures before billing, and an insufficient result budget do not trigger the result event. Failed runs can still consume platform resources. A billing response can be lost after a result was stored: BILLING_UNCERTAIN preserves that OUTPUT, fails the run, and does not retry the charge. Inspect that run and its event counts before trying again. No atomic transaction across storage and billing is promised.
The recommended settings are 256 MB memory, a 180-second run timeout, and automatic restart disabled. It only needs Apify's Limited permissions to read/delete run INPUT, write its own result records, and charge its own configured event. This is a short Python run without proxies, browsers, external API keys, or external code-generation services. Cold startup and waiting can dominate its small computation cost. This is not an always-on or low-latency authenticator endpoint; use a local authenticator library when you require immediate codes without a cloud round trip.
Limits, errors, and FAQ
Can it recover an unknown secret or bypass 2FA? No. It computes a code only from a supplied shared secret. It does not retrieve SMS/email codes, log into accounts, or derive keys from old codes.
Why does the target reject the code? Confirm the key, algorithm, digit count, period, and the target's clock. The Actor uses the current server time and does not offer arbitrary timestamp overrides or search adjacent windows. A used code can also be rejected by replay protection.
Can I upload a QR code? No. Decode it using your trusted authenticator tooling and supply the resulting TOTP URI. HOTP/counter-based tokens and proprietary authenticator formats are unsupported.
Why did a run fail? Invalid input, conflicting URI settings, input cleanup failure, a clock problem, output storage failure, or a billing/budget problem leads to a failed run with a fixed, non-sensitive message. Most failures produce no confirmed OUTPUT. BILLING_UNCERTAIN is the exception: OUTPUT was already stored, and billing needs inspection. Platform usage may still be charged. Do not blindly retry failed requests.
The ERRORS record includes a stable errorCode for routing workflow failures:
| Error code | Action |
|---|---|
INVALID_INPUT | Check the key format and effective URI settings; do not retry unchanged input |
INPUT_READ_FAILED | Check encrypted-input/runtime configuration and inspect the run status |
INPUT_CLEANUP_FAILED | Generation stopped because INPUT could not be removed; check storage permissions/access |
CLOCK_ERROR | Check run/platform timing; no usable result was confirmed |
OUTPUT_STORAGE_FAILED | Inspect the run and storage before retrying; no successful result was confirmed |
SUMMARY contains status, resultCount, inputDeleted, and effective settings on success or errorCode on failure. It excludes the key, URI label, issuer, code, and customer data. When storage itself fails, ERRORS or SUMMARY may also be unavailable; the run status remains the primary completion signal.
Is a browser-based generator cheaper? Free browser tools and local libraries already exist. This Actor adds Apify workflow execution, encrypted input, expiration metadata, and run input deletion. Its value is convenient integration, not a new cryptographic algorithm.
Verification and standards
The implementation is checked against all 18 official eight-digit vectors in RFC 6238 Appendix B, including timestamps beyond 2038. Additional tests cover six-digit codes, period rollover, URI settings, input deletion, short-validity waits, and sanitized failures. Only public test keys are used for QA. See also the Key URI format and Apify secret input documentation.