# TOTP Generator — 2FA Codes for Automation (`apivault_labs/totp-generator`) Actor

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.

- **URL**: https://apify.com/apivault_labs/totp-generator.md
- **Developed by:** [Apivault Labs](https://apify.com/apivault_labs) (community)
- **Categories:** Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.10 / 1,000 totp code delivereds

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## TOTP Generator — 2FA Codes for Automation

![TOTP Generator — 2FA codes for automation](https://api.apify.com/v2/key-value-stores/vvEf8RMIKG9MbOHuA/records/TOTP_README_COVER_V1)

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:

```json
{
  "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:

```json
{
  "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.

```json
{
  "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](https://docs.apify.com/api/v2), [Python client](https://docs.apify.com/api/client/python/), [JavaScript client](https://docs.apify.com/api/client/js/), 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](https://docs.apify.com/api/v2/actor-run-sync-post) 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.

```bash
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:

```python
import os
from datetime import datetime, timezone
from apify_client import ApifyClient

client = 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](https://apivault-labs.github.io/integrations/totp-generator/workflow.v1.json), follow the [short setup guide](https://apivault-labs.github.io/integrations/totp-generator/), or read the [full credential and error-handling instructions](https://github.com/apivault-labs/apivault-labs.github.io/blob/main/integrations/totp-generator/README.md). 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](https://apivault-labs.github.io/integrations/totp-generator/SHA256SUMS.txt) 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](https://apify.com/apivault_labs/totp-generator/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](https://www.rfc-editor.org/rfc/rfc6238#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](https://github.com/google/google-authenticator/wiki/Key-Uri-Format) and [Apify secret input documentation](https://docs.apify.com/actors/development/actor-definition/input-schema/secret-input).

# Actor input Schema

## `secret` (type: `string`):

Use a secret you own or are authorized to use. Apify encrypts this field. The Actor deletes its run input after reading; saved Tasks and external integrations retain their own copies. No real secret is included in examples.

## `algorithm` (type: `string`):

Auto uses the URI parameter or SHA1. Conflicting explicit URI and input settings fail.

## `digits` (type: `string`):

Auto uses the URI parameter or 6 digits. Codes are returned as strings to preserve leading zeros.

## `periodSeconds` (type: `integer`):

0 uses the URI period or 30 seconds. Explicit periods must be 15–120 seconds.

## `minValiditySeconds` (type: `integer`):

Wait for the next code when fewer seconds remain. Must be less than the selected period. Storage and delivery consume part of the remaining validity.

## Actor input object example

```json
{
  "algorithm": "auto",
  "digits": "auto",
  "periodSeconds": 0,
  "minValiditySeconds": 5
}
```

# Actor output Schema

## `result` (type: `string`):

No description

## `summary` (type: `string`):

No description

## `errors` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("apivault_labs/totp-generator").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("apivault_labs/totp-generator").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call apivault_labs/totp-generator --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,apivault_labs/totp-generator"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/fp4AgRswJ7BVjg7mz/builds/5Ltb4tA4h4Py7sgBz/openapi.json
