Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(agents): implement Moltbook verification challenge auto-solver
Adam Eivye7cbaf6c3853
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.mdindex 4798706e11..378d1006e0 100644--- a/.changelog/v0.12.x.md+++ b/.changelog/v0.12.x.md@@ -180,14 +180,16 @@ This release adds branch management and automated release workflow capabilities- `server/routes/agentTools.js` — Check-posts endpoint detects suspension mid-loop, halts immediately, marks account suspended- `server/services/agentActionExecutor.js` — Monitor and engage actions detect suspension and break early-### Agents — Moltbook Challenge Detection & Response Framework-- **Challenge scanning**: Every API response body is scanned for embedded challenge fields (`challenge`, `nonce`, `verification`, `proof`, etc.)-- **HMAC-SHA256 response**: Detected challenges are automatically signed with the agent's API key and POSTed back to the challenge endpoint-- **Logging**: Challenge encounters, nonces, and response results are logged for diagnostics-- **Probe script**: New `server/scripts/moltbook-probe.mjs` polls a suspended account until it lifts, then exercises all API endpoints while logging full response bodies and headers to capture the exact challenge format+### Agents — Moltbook Verification Challenge Auto-Solver+- **Challenge detection**: API responses with `verification_required: true` are automatically intercepted and solved+- **AI-powered solver**: Uses the active AI provider to interpret obfuscated math word problems (e.g., `"LoOoBbSsTtEeR cLlAaW FoOrRcCeE"` = "lobster claw force") and compute the answer+- **Regex fallback**: Word-to-number parser handles simpler challenges when AI is unavailable+- **Auto-submission**: Solved answers are submitted to `POST /api/v1/verify` with the verification code, all within the 5-minute challenge window+- **Probe script**: `server/scripts/moltbook-probe.mjs` polls suspended accounts and exercises all API endpoints to capture challenge formats**Server changes**:-- `server/integrations/moltbook/api.js` — Added `handleChallenge()` with HMAC-SHA256 signing, scans every successful response+- `server/integrations/moltbook/challengeSolver.js` — New module with `solveChallenge()`, `cleanChallengeText()`, AI and regex solvers+- `server/integrations/moltbook/api.js` — Replaced speculative HMAC handler with `handleVerification()` that detects and auto-solves challenges- `server/scripts/moltbook-probe.mjs` — New standalone probe script for challenge format discovery### CoS — Quick Summary Widgetdiff --git a/server/integrations/moltbook/api.js b/server/integrations/moltbook/api.jsindex 89236452d0..ddeb84a3f2 100644--- a/server/integrations/moltbook/api.js+++ b/server/integrations/moltbook/api.js@@ -7,59 +7,49 @@* API Base: https://www.moltbook.com/api/v1*/-import crypto from 'crypto';import { checkRateLimit, recordAction } from './rateLimits.js';+import { solveChallenge } from './challengeSolver.js';const API_BASE = 'https://www.moltbook.com/api/v1';-// Known challenge field names to scan for in responses-const CHALLENGE_FIELDS = ['challenge', 'challenge_id', 'verification', 'verify', 'nonce', 'proof'];-/**- * Check a response body for embedded challenge data and handle it+ * Handle a Moltbook verification challenge embedded in a response+ * Challenges are obfuscated math word problems that must be solved within 5 minutes.*/-async function handleChallenge(data, apiKey) {- if (!data || typeof data !== 'object') return;-- // Detect challenge field in response body- const challengeKey = CHALLENGE_FIELDS.find(k => data[k] != null);- if (!challengeKey) return;-- const challenge = data[challengeKey];- console.log(`🔐 Moltbook challenge detected: ${challengeKey}=${JSON.stringify(challenge).substring(0, 120)}`);+async function handleVerification(data, apiKey) {+ if (!data?.verification_required || !data?.verification) return data;- // Solve the challenge: HMAC-SHA256 sign the challenge nonce with our API key- const nonce = typeof challenge === 'object' ? (challenge.nonce || challenge.id || challenge.challenge || JSON.stringify(challenge)) : String(challenge);- const signature = crypto.createHmac('sha256', apiKey).update(nonce).digest('hex');+ const { code, challenge, expires_at } = data.verification;+ console.log(`🔐 Moltbook verification required: code=${code}, expires=${expires_at}`);+ console.log(`🔐 Challenge: "${challenge.substring(0, 100)}..."`);- // Determine response endpoint- const challengeId = typeof challenge === 'object' ? (challenge.id || challenge.challenge_id) : null;- const respondUrl = typeof challenge === 'object' && challenge.respond_url- ? challenge.respond_url- : `${API_BASE}/agents/me/challenge`;+ const answer = await solveChallenge(challenge);+ if (!answer) {+ console.error(`❌ Could not solve Moltbook challenge — post will remain pending`);+ return data;+ }- console.log(`🔐 Moltbook challenge response: nonce=${nonce.substring(0, 40)} sig=${signature.substring(0, 16)}... -> ${respondUrl}`);+ console.log(`🔐 Submitting verification: code=${code} answer=${answer}`);- const resp = await fetch(respondUrl, {+ const resp = await fetch(`${API_BASE}/verify`, {method: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${apiKey}`},- body: JSON.stringify({- challenge_id: challengeId,- nonce,- signature,- response: signature- })+ body: JSON.stringify({ verification_code: code, answer })});const result = await resp.json().catch(() => ({}));- if (resp.ok) {- console.log(`✅ Moltbook challenge solved: ${result.message || 'accepted'}`);+ if (resp.ok && result.success !== false) {+ console.log(`✅ Moltbook verification passed: ${result.message || 'verified'}`);+ data.verification_solved = true;} else {- console.error(`❌ Moltbook challenge failed: ${resp.status} ${result.error || result.message || 'unknown'}`);+ console.error(`❌ Moltbook verification failed: ${resp.status} ${result.error || result.message || 'unknown'}`);+ data.verification_solved = false;}++ return data;}/**@@ -95,9 +85,9 @@ async function request(endpoint, options = {}) {const data = await response.json();- // Check for embedded challenges in every response+ // Auto-solve verification challenges embedded in responsesconst apiKey = config.headers?.['Authorization']?.replace('Bearer ', '');- if (apiKey) await handleChallenge(data, apiKey);+ if (apiKey) await handleVerification(data, apiKey);return data;}diff --git a/server/integrations/moltbook/challengeSolver.js b/server/integrations/moltbook/challengeSolver.jsnew file mode 100644index 0000000000..688e634c84--- /dev/null+++ b/server/integrations/moltbook/challengeSolver.js@@ -0,0 +1,212 @@+/**+ * Moltbook Challenge Solver+ *+ * Solves Moltbook's AI verification challenges — obfuscated math word problems+ * that agents must answer to publish posts.+ *+ * Challenge format:+ * - Text has random brackets/symbols injected and letters doubled with case-swapped duplicates+ * - Contains a simple arithmetic problem (addition, subtraction, etc.)+ * - Answer must be a number with 2 decimal places (e.g., "47.00")+ *+ * Uses AI for interpretation when available, with a regex fallback.+ */++import { executeApiRun, createRun } from '../../services/runner.js';+import { getActiveProvider } from '../../services/providers.js';++/**+ * Strip obfuscation noise from Moltbook challenge text+ * Removes: brackets, carets, braces, then collapses consecutive case-insensitive duplicate letters+ */+export function cleanChallengeText(text) {+ // Strip bracket/symbol noise+ let cleaned = text.replace(/[[\]{}^]/g, '');++ // Collapse consecutive case-insensitive duplicate letters+ // e.g., "LoOoBbSsTtEeR" -> "LoBSTER" (lobster)+ let result = '';+ for (let i = 0; i < cleaned.length; i++) {+ const char = cleaned[i];+ const prev = result[result.length - 1];+ if (prev && char.toLowerCase() === prev.toLowerCase()) continue;+ result += char;+ }++ // Normalize whitespace+ return result.replace(/\s+/g, ' ').trim();+}++// Word-to-number mapping for fallback solver+const WORD_NUMBERS = {+ zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9,+ ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16,+ seventeen: 17, eighteen: 18, nineteen: 19, twenty: 20, thirty: 30, forty: 40, fifty: 50,+ sixty: 60, seventy: 70, eighty: 80, ninety: 90, hundred: 100, thousand: 1000+};++/**+ * Parse a number from word representation (e.g., "thirty five" -> 35)+ */+function wordsToNumber(words) {+ const tokens = words.toLowerCase().split(/[\s-]+/);+ let total = 0;+ let current = 0;++ for (const token of tokens) {+ const val = WORD_NUMBERS[token];+ if (val === undefined) continue;+ if (val === 100) {+ current = (current || 1) * 100;+ } else if (val === 1000) {+ current = (current || 1) * 1000;+ total += current;+ current = 0;+ } else {+ current += val;+ }+ }++ return total + current;+}++/**+ * Attempt to solve the challenge using regex-based number extraction and arithmetic+ */+export function solveWithRegex(challengeText) {+ const cleaned = cleanChallengeText(challengeText);+ console.log(`🔐 Cleaned challenge: "${cleaned}"`);++ // Try to find numeric values (digit-based)+ const digitNumbers = cleaned.match(/\d+\.?\d*/g);+ if (digitNumbers?.length >= 2) {+ // Simple addition/subtraction with digit numbers+ const nums = digitNumbers.map(Number);+ if (cleaned.toLowerCase().includes('add') || cleaned.toLowerCase().includes('total') || cleaned.toLowerCase().includes('sum') || cleaned.toLowerCase().includes('plus')) {+ return nums.reduce((a, b) => a + b, 0);+ }+ if (cleaned.toLowerCase().includes('subtract') || cleaned.toLowerCase().includes('minus') || cleaned.toLowerCase().includes('difference')) {+ return nums[0] - nums.slice(1).reduce((a, b) => a + b, 0);+ }+ if (cleaned.toLowerCase().includes('multiply') || cleaned.toLowerCase().includes('times') || cleaned.toLowerCase().includes('product')) {+ return nums.reduce((a, b) => a * b, 1);+ }+ // Default: addition for "total" / "what is"+ return nums.reduce((a, b) => a + b, 0);+ }++ // Try word-based numbers+ const lc = cleaned.toLowerCase();++ // Extract patterns like "X is [number words] and ... adds/plus [number words]"+ const numberWordPattern = /(?:zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand)[\s-]*/gi;++ // Find number word sequences+ const numberSequences = [];+ let match;+ const wordRegex = /(?:(?:zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand)[\s-]*)+/gi;+ while ((match = wordRegex.exec(lc)) !== null) {+ const num = wordsToNumber(match[0]);+ if (num > 0) numberSequences.push(num);+ }++ if (numberSequences.length >= 2) {+ if (lc.includes('add') || lc.includes('total') || lc.includes('sum') || lc.includes('plus')) {+ return numberSequences.reduce((a, b) => a + b, 0);+ }+ if (lc.includes('subtract') || lc.includes('minus') || lc.includes('difference')) {+ return numberSequences[0] - numberSequences.slice(1).reduce((a, b) => a + b, 0);+ }+ if (lc.includes('multiply') || lc.includes('times') || lc.includes('product')) {+ return numberSequences.reduce((a, b) => a * b, 1);+ }+ // Default: addition+ return numberSequences.reduce((a, b) => a + b, 0);+ }++ return null;+}++/**+ * Solve using AI interpretation+ */+async function solveWithAI(challengeText) {+ const provider = await getActiveProvider();+ if (!provider) {+ console.log(`🔐 No AI provider available for challenge solving`);+ return null;+ }++ const model = provider.lightModel || provider.defaultModel || provider.models?.[0];+ const prompt = `You are solving a verification challenge. The text below is obfuscated with random brackets, symbols, and doubled letters. Decode it, solve the math problem, and respond with ONLY the numeric answer with 2 decimal places (e.g., "47.00"). No explanation.++Challenge text:+${challengeText}++Answer:`;++ const { runId } = await createRun({+ providerId: provider.id,+ model,+ prompt,+ source: 'moltbook-challenge'+ });++ let responseText = '';+ await new Promise((resolve, reject) => {+ executeApiRun(+ runId,+ provider,+ model,+ prompt,+ process.cwd(),+ [],+ (data) => { if (data?.text) responseText += data.text; },+ (result) => {+ if (result?.error) reject(new Error(result.error));+ else resolve(result);+ }+ );+ });++ // Extract number from response+ const numMatch = responseText.trim().match(/[\d]+\.?\d*/);+ if (numMatch) {+ return parseFloat(numMatch[0]);+ }++ console.log(`🔐 AI response didn't contain a number: "${responseText.substring(0, 100)}"`);+ return null;+}++/**+ * Solve a Moltbook verification challenge+ * Prefers AI (handles obfuscation reliably), falls back to regex if no AI provider+ * @returns {string|null} Answer formatted with 2 decimal places, or null if unsolvable+ */+export async function solveChallenge(challengeText) {+ console.log(`🔐 Solving challenge: "${challengeText.substring(0, 80)}..."`);++ // Try AI first — handles obfuscation much better than regex+ const aiAnswer = await solveWithAI(challengeText).catch(err => {+ console.log(`🔐 AI solver error: ${err.message}`);+ return null;+ });+ if (aiAnswer !== null) {+ const formatted = aiAnswer.toFixed(2);+ console.log(`🔐 AI solver: ${formatted}`);+ return formatted;+ }++ // Fall back to regex (works when numbers aren't heavily obfuscated)+ console.log(`🔐 AI unavailable, trying regex solver...`);+ const regexAnswer = solveWithRegex(challengeText);+ if (regexAnswer !== null) {+ const formatted = regexAnswer.toFixed(2);+ console.log(`🔐 Regex solver: ${formatted}`);+ return formatted;+ }++ console.error(`❌ Could not solve Moltbook challenge`);+ return null;+}diff --git a/server/scripts/moltbook-probe.mjs b/server/scripts/moltbook-probe.mjsindex fb836c9f7d..3e90d83c76 100644--- a/server/scripts/moltbook-probe.mjs+++ b/server/scripts/moltbook-probe.mjs@@ -78,12 +78,14 @@ async function rawRequest(apiKey, method, endpoint, body = null) {// Log raw bodyconst text = await response.text();- console.log(`📥 Body (raw): ${text}`);+ const isJson = (response.headers.get('content-type') || '').includes('application/json');+ console.log(`📥 Body (raw): ${isJson ? text : text.substring(0, 200) + (text.length > 200 ? '...[HTML/truncated]' : '')}`);// Parse JSON if possiblelet data = null;- if (text) {- data = JSON.parse(text);+ const parsed = isJson && text ? (() => { try { return JSON.parse(text); } catch { return null; } })() : null;+ if (parsed) {+ data = parsed;// Scan for anything that looks like a challengeif (data && typeof data === 'object') {const challengeKeys = ['challenge', 'challenge_id', 'verification', 'verify', 'nonce', 'proof', 'puzzle', 'captcha', 'token'];