{ "name": "TOTP Generator — checked code with budget and expiry", "nodes": [ { "id": "run-manually", "name": "Run manually", "type": "n8n-nodes-base.manualTrigger", "typeVersion": 1, "position": [ 0, 120 ], "parameters": {} }, { "id": "settings", "name": "Settings", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 220, 120 ], "parameters": { "mode": "runOnceForAllItems", "jsCode": "// Public settings only. Put tokens and the TOTP key in encrypted Credentials.\nreturn [{ json: {\n maxTotalChargeUsd: 0.03,\n minValidityAtGeneration: 10,\n minValidityAtReceipt: 3,\n maxPolls: 65,\n} }];\n" } }, { "id": "start-totp-run", "name": "Start TOTP run", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.4, "position": [ 440, 120 ], "parameters": { "method": "POST", "url": "https://api.apify.com/v2/acts/apivault_labs~totp-generator/runs", "authentication": "genericCredentialType", "genericAuthType": "httpCustomAuth", "options": { "timeout": 15000, "redirect": { "redirect": { "followRedirects": false } }, "response": { "response": { "fullResponse": true, "neverError": true, "responseFormat": "json" } } }, "sendQuery": true, "queryParameters": { "parameters": [ { "name": "build", "value": "latest" }, { "name": "memory", "value": "256" }, { "name": "timeout", "value": "180" }, { "name": "waitForFinish", "value": "0" }, { "name": "restartOnError", "value": "false" }, { "name": "forcePermissionLevel", "value": "LIMITED_PERMISSIONS" }, { "name": "maxTotalChargeUsd", "value": "={{ $json.maxTotalChargeUsd }}" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={{ { minValiditySeconds: $json.minValidityAtGeneration } }}" }, "retryOnFail": false, "onError": "continueRegularOutput", "notes": "Select the encrypted credential described in the setup note. No automatic retry.", "notesInFlow": false }, { "id": "track-run", "name": "Track run", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 660, 120 ], "parameters": { "mode": "runOnceForAllItems", "jsCode": "const response = $input.first().json;\nconst run = response.body?.data;\nconst validId = (id) => typeof id === 'string' && /^[A-Za-z0-9]{17}$/.test(id);\nif (![200, 201].includes(response.statusCode) || !validId(run?.id)) {\n return [{ json: { ok: false, route: 'done', errorCode: 'START_NOT_CONFIRMED',\n message: 'Run start was not confirmed. Inspect Apify runs before submitting again.', retryAutomatically: false } }];\n}\nreturn [{ json: { route: 'poll', runId: run.id, pollCount: 0,\n runUrl: 'https://console.apify.com/view/runs/' + run.id } }];\n" } }, { "id": "run-tracked", "name": "Run tracked", "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [ 880, 120 ], "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 2 }, "conditions": [ { "id": "run-tracked", "leftValue": "={{ $json.route }}", "rightValue": "poll", "operator": { "type": "string", "operation": "equals" } } ], "combinator": "and" }, "options": {} } }, { "id": "wait-for-status", "name": "Wait for status", "type": "n8n-nodes-base.wait", "typeVersion": 1.1, "position": [ 1100, 0 ], "parameters": { "resume": "timeInterval", "amount": 3, "unit": "seconds" } }, { "id": "read-run-status", "name": "Read run status", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.4, "position": [ 1320, 0 ], "parameters": { "method": "GET", "url": "={{ 'https://api.apify.com/v2/actor-runs/' + $json.runId }}", "authentication": "genericCredentialType", "genericAuthType": "httpHeaderAuth", "options": { "timeout": 15000, "redirect": { "redirect": { "followRedirects": false } }, "response": { "response": { "fullResponse": true, "neverError": true, "responseFormat": "json" } } } }, "retryOnFail": false, "onError": "continueRegularOutput", "notes": "Select the encrypted credential described in the setup note. No automatic retry.", "notesInFlow": false }, { "id": "inspect-status", "name": "Inspect status", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1540, 0 ], "parameters": { "mode": "runOnceForAllItems", "jsCode": "const response = $input.first().json;\nconst previous = $('Wait for status').item.json;\nconst settings = $('Settings').first().json;\nconst context = { runId: previous.runId, runUrl: previous.runUrl,\n pollCount: previous.pollCount + 1, retryAutomatically: false };\nconst fail = (errorCode, message) => [{ json: { ...context, ok: false, route: 'done', errorCode, message } }];\nconst run = response.body?.data;\nif (response.statusCode !== 200 || run?.id !== previous.runId) {\n return fail('STATUS_UNAVAILABLE', 'Run status could not be confirmed. Inspect the saved run ID; do not start another run automatically.');\n}\ncontext.status = run.status;\nif (['READY', 'RUNNING', 'TIMING-OUT', 'ABORTING'].includes(run.status)) {\n if (context.pollCount >= settings.maxPolls) return fail('POLL_LIMIT_REACHED', 'Polling limit reached. The Actor may still be running; inspect this run.');\n return [{ json: { ...context, route: 'poll' } }];\n}\nif (!['SUCCEEDED', 'FAILED', 'TIMED-OUT', 'ABORTED'].includes(run.status)) {\n return fail('UNKNOWN_RUN_STATUS', 'Unrecognized run status; inspect the run before continuing.');\n}\nif (typeof run.defaultKeyValueStoreId !== 'string' || !/^[A-Za-z0-9]{17}$/.test(run.defaultKeyValueStoreId)) {\n return fail('RESULT_STORE_UNAVAILABLE', 'Run has no usable result store ID.');\n}\nreturn [{ json: { ...context, storeId: run.defaultKeyValueStoreId,\n route: run.status === 'SUCCEEDED' ? 'output' : 'errorRecord' } }];\n" } }, { "id": "still-running", "name": "Still running", "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [ 1760, 0 ], "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 2 }, "conditions": [ { "id": "still-running", "leftValue": "={{ $json.route }}", "rightValue": "poll", "operator": { "type": "string", "operation": "equals" } } ], "combinator": "and" }, "options": {} } }, { "id": "run-succeeded", "name": "Run succeeded", "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [ 1980, 120 ], "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 2 }, "conditions": [ { "id": "run-succeeded", "leftValue": "={{ $json.route }}", "rightValue": "output", "operator": { "type": "string", "operation": "equals" } } ], "combinator": "and" }, "options": {} } }, { "id": "read-output", "name": "Read OUTPUT", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.4, "position": [ 2200, 0 ], "parameters": { "method": "GET", "url": "={{ 'https://api.apify.com/v2/key-value-stores/' + $json.storeId + '/records/OUTPUT' }}", "authentication": "genericCredentialType", "genericAuthType": "httpHeaderAuth", "options": { "timeout": 15000, "redirect": { "redirect": { "followRedirects": false } }, "response": { "response": { "fullResponse": true, "neverError": true, "responseFormat": "json" } } } }, "retryOnFail": false, "onError": "continueRegularOutput", "notes": "Select the encrypted credential described in the setup note. No automatic retry.", "notesInFlow": false }, { "id": "check-expiry", "name": "Check expiry", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 2420, 0 ], "parameters": { "mode": "runOnceForAllItems", "jsCode": "const response = $input.first().json;\nconst run = $('Run succeeded').item.json;\nconst settings = $('Settings').first().json;\nconst context = { runId: run.runId, runUrl: run.runUrl, status: run.status, retryAutomatically: false };\nconst fail = (errorCode, message) => [{ json: { ...context, ok: false, errorCode, message } }];\nconst output = response.body;\nif (response.statusCode !== 200 || !output || typeof output.code !== 'string' ||\n ![6, 8].includes(output.digits) || !new RegExp('^[0-9]{' + output.digits + '}$').test(output.code) ||\n !['SHA1', 'SHA256', 'SHA512'].includes(output.algorithm) || !Number.isInteger(output.periodSeconds) ||\n output.periodSeconds < 15 || output.periodSeconds > 120) {\n return fail('OUTPUT_UNAVAILABLE', 'Result is missing or malformed. Inspect the existing run before trying again.');\n}\nconst generated = Date.parse(output.generatedAt);\nconst expiry = Date.parse(output.validUntil);\nconst now = Date.now();\nconst remaining = (expiry - now) / 1000;\nif (!Number.isFinite(generated) || !Number.isFinite(expiry) || expiry <= generated ||\n expiry - generated > output.periodSeconds * 1000 + 1 || generated > now + 2000 ||\n remaining > output.periodSeconds + 2) {\n return fail('INVALID_EXPIRY', 'Invalid expiration metadata or clock mismatch.');\n}\nif (remaining < settings.minValidityAtReceipt) {\n return fail('CODE_TOO_OLD', 'Delivered code is expired or too close to expiry. No automatic paid regeneration was attempted.');\n}\nreturn [{ json: { ...context, ok: true, code: output.code, validUntil: output.validUntil,\n remainingSecondsAtReceipt: Math.floor(remaining * 1000) / 1000,\n algorithm: output.algorithm, digits: output.digits, periodSeconds: output.periodSeconds } }];\n" } }, { "id": "read-actor-error", "name": "Read Actor error", "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [ 2200, 240 ], "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 2 }, "conditions": [ { "id": "read-actor-error", "leftValue": "={{ $json.route }}", "rightValue": "errorRecord", "operator": { "type": "string", "operation": "equals" } } ], "combinator": "and" }, "options": {} } }, { "id": "read-errors", "name": "Read ERRORS", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.4, "position": [ 2420, 180 ], "parameters": { "method": "GET", "url": "={{ 'https://api.apify.com/v2/key-value-stores/' + $json.storeId + '/records/ERRORS' }}", "authentication": "genericCredentialType", "genericAuthType": "httpHeaderAuth", "options": { "timeout": 15000, "redirect": { "redirect": { "followRedirects": false } }, "response": { "response": { "fullResponse": true, "neverError": true, "responseFormat": "json" } } } }, "retryOnFail": false, "onError": "continueRegularOutput", "notes": "Select the encrypted credential described in the setup note. No automatic retry.", "notesInFlow": false }, { "id": "safe-failure", "name": "Safe failure", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 2640, 180 ], "parameters": { "mode": "runOnceForAllItems", "jsCode": "const response = $input.first().json;\nconst run = $('Read Actor error').item.json;\nconst messages = {\n INVALID_INPUT: 'Check the key and authenticator settings; do not retry unchanged input.',\n INPUT_READ_FAILED: 'The Actor could not read its input.',\n INPUT_CLEANUP_FAILED: 'Generation stopped because INPUT could not be deleted.',\n OUTPUT_STORAGE_FAILED: 'Result storage could not be confirmed.',\n CLOCK_ERROR: 'No usable current code window was confirmed.',\n BILLING_CONFIGURATION_ERROR: 'Result pricing could not be verified.',\n BUDGET_EXCEEDED: 'Budget does not allow one result event. No usable code was delivered.',\n BILLING_UNCERTAIN: 'OUTPUT may exist and billing may have succeeded. Inspect this run and its events before trying again.',\n};\nconst received = response.statusCode === 200 ? response.body?.errorCode : null;\nconst known = Object.prototype.hasOwnProperty.call(messages, received);\nreturn [{ json: { ok: false, runId: run.runId, runUrl: run.runUrl, status: run.status,\n errorCode: known ? received : 'ACTOR_RUN_FAILED',\n message: known ? messages[received] : 'Actor did not succeed; inspect the saved run. Error details could not be verified.',\n retryAutomatically: false } }];\n" } }, { "id": "result", "name": "Result", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 2880, 120 ], "parameters": { "mode": "runOnceForAllItems", "jsCode": "// Continue to your next step ONLY when ok === true. Never log a successful item.\nconst value = $input.first().json;\nconst allowed = value.ok === true\n ? ['ok', 'code', 'validUntil', 'remainingSecondsAtReceipt', 'algorithm', 'digits', 'periodSeconds', 'runId', 'runUrl', 'status', 'retryAutomatically']\n : ['ok', 'errorCode', 'message', 'runId', 'runUrl', 'status', 'retryAutomatically'];\nreturn [{ json: Object.fromEntries(allowed.filter((key) => value[key] !== undefined).map((key) => [key, value[key]])) }];\n" } }, { "id": "setup-and-privacy", "name": "Setup and privacy", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ 0, -460 ], "parameters": { "width": 1040, "height": 460, "content": "## TOTP Generator → checked code\n1. Start TOTP run: select Custom Auth with JSON headers.Authorization=Bearer YOUR_TOKEN and body.secret=YOUR_TOTP_SECRET.\n2. Read run status / Read OUTPUT / Read ERRORS: select Header Auth with Name=Authorization and Value=Bearer YOUR_TOKEN. Never use the secret-bearing Custom Auth on GET nodes.\n3. Adjust Settings, execute, then connect Result to your next step. Continue ONLY when ok=true; check expiry again immediately before use. No automatic regeneration/retry.\nSecrets stay in encrypted Credentials, outside this JSON. Do not pin execution data or export credentials. Execution saving is disabled here; your instance logs/retention still need review.\n$0.10/1,000 delivered codes + Apify resources, no subscription/start fee. Budget is not a platform-cost guarantee.\nActor: https://apify.com/apivault_labs/totp-generator\nSetup, failure codes and tested versions: accompanying README.md." } } ], "connections": { "Run manually": { "main": [ [ { "node": "Settings", "type": "main", "index": 0 } ] ] }, "Settings": { "main": [ [ { "node": "Start TOTP run", "type": "main", "index": 0 } ] ] }, "Start TOTP run": { "main": [ [ { "node": "Track run", "type": "main", "index": 0 } ] ] }, "Track run": { "main": [ [ { "node": "Run tracked", "type": "main", "index": 0 } ] ] }, "Run tracked": { "main": [ [ { "node": "Wait for status", "type": "main", "index": 0 } ], [ { "node": "Result", "type": "main", "index": 0 } ] ] }, "Wait for status": { "main": [ [ { "node": "Read run status", "type": "main", "index": 0 } ] ] }, "Read run status": { "main": [ [ { "node": "Inspect status", "type": "main", "index": 0 } ] ] }, "Inspect status": { "main": [ [ { "node": "Still running", "type": "main", "index": 0 } ] ] }, "Still running": { "main": [ [ { "node": "Wait for status", "type": "main", "index": 0 } ], [ { "node": "Run succeeded", "type": "main", "index": 0 } ] ] }, "Run succeeded": { "main": [ [ { "node": "Read OUTPUT", "type": "main", "index": 0 } ], [ { "node": "Read Actor error", "type": "main", "index": 0 } ] ] }, "Read OUTPUT": { "main": [ [ { "node": "Check expiry", "type": "main", "index": 0 } ] ] }, "Check expiry": { "main": [ [ { "node": "Result", "type": "main", "index": 0 } ] ] }, "Read Actor error": { "main": [ [ { "node": "Read ERRORS", "type": "main", "index": 0 } ], [ { "node": "Result", "type": "main", "index": 0 } ] ] }, "Read ERRORS": { "main": [ [ { "node": "Safe failure", "type": "main", "index": 0 } ] ] }, "Safe failure": { "main": [ [ { "node": "Result", "type": "main", "index": 0 } ] ] } }, "active": false, "pinData": {}, "tags": [], "settings": { "executionOrder": "v1", "executionTimeout": 420, "saveDataErrorExecution": "none", "saveDataSuccessExecution": "none", "saveManualExecutions": false, "saveExecutionProgress": false } }