{"record":{"id":"3b7e1131c5a37e66","repo":"mastra-ai/mastra","slug":"auth-callback-rejected-invalid-state-token-400","errorCode":null,"errorMessage":"auth callback rejected (invalid state/token); 400 HTML failure page returned","messagePattern":"auth callback rejected \\(invalid state/token\\); 400 HTML failure page returned","errorType":"http","errorClass":null,"httpStatus":400,"severity":"error","filePath":"packages/cli/src/commands/auth/credentials.ts","lineNumber":304,"sourceCode":"      handleAbort();\n      return;\n    }\n    if (options.skipOnInput) {\n      stopListeningForSkip = listenForSkipInput(() => finish(() => reject(new LoginCancelledError())));\n    }\n\n    server.on('request', (req, res) => {\n      const url = new URL(req.url!, `http://localhost:${port}`);\n\n      if (url.pathname === '/callback') {\n        const callbackState = url.searchParams.get('state');\n        const token = url.searchParams.get('token');\n        const refreshToken = url.searchParams.get('refresh_token');\n        const userParam = url.searchParams.get('user');\n        const orgId = url.searchParams.get('org');\n\n        if (callbackState !== state || !token || !userParam || !orgId) {\n          res.writeHead(400, { 'Content-Type': 'text/html' });\n          res.end(callbackPage({ success: false }));\n          return;\n        }\n\n        const user = JSON.parse(decodeURIComponent(userParam));\n\n        res.writeHead(200, { 'Content-Type': 'text/html', Connection: 'close' });\n        res.end(callbackPage({ success: true }));\n\n        finish(() => resolve({ token, refreshToken, user, organizationId: orgId }));\n      }\n    });\n  });\n\n  const creds: Credentials = {\n    token: result.token,\n    ...(result.refreshToken ? { refreshToken: result.refreshToken } : {}),\n    user: result.user,","sourceCodeStart":286,"sourceCodeEnd":322,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/cli/src/commands/auth/credentials.ts#L286-L322","documentation":"During the interactive `mastra auth login` OAuth-style flow, the local HTTP callback validates the returned state parameter and required fields (token, user, org). If the state does not match the CSRF value the CLI generated, or token/user/org are missing, it responds with a 400 HTML failure page and throws this error, aborting login to prevent CSRF/token-injection attacks.","triggerScenarios":"The browser callback URL hit the local server with state != the generated state, or with missing token / user / org query params — e.g. user pasted a truncated URL, bookmarked a stale callback URL, the login page was opened twice, or a redirect dropped parameters.","commonSituations":"Re-opening an old login tab after the CLI restarted (state mismatch); copying only part of the callback URL; browser extensions stripping query params; concurrent `mastra auth login` runs clobbering each other's state; firewall/alternate port sending the callback to the wrong CLI instance.","solutions":["Abort the failed browser tab and restart cleanly with `mastra auth login`, completing the flow in the newly opened tab without reusing old URLs.","Ensure only one `mastra auth login` runs at a time.","Paste the full callback URL including all query parameters if completing manually.","Disable browser extensions that strip query strings, or try another browser."],"exampleFix":"// before (stale tab reused)\nhttp://localhost:PORT/callback?state=OLD_STATE...  # 400 failure page\n// after\nmastra auth login  # fresh state, use the newly opened tab only","handlingStrategy":"try-catch","validationCode":null,"typeGuard":"function isLoginStateError(err: unknown): boolean {\n  return err instanceof Error &&\n    err.message.includes('auth callback rejected');\n}","tryCatchPattern":"try {\n  await login(signal, options);\n} catch (err) {\n  if (isLoginStateError(err)) {\n    console.error('Login callback invalid — restart the flow: `mastra auth login`, and use only the newly opened browser tab.');\n    return login(signal, options); // single clean retry\n  }\n  throw err;\n}","preventionTips":["Never reuse or bookmark callback URLs from a previous login attempt.","Run only one `mastra auth login` at a time.","Complete login promptly in the tab the CLI opened; state expires with the CLI process.","Disable extensions that rewrite or strip URL query parameters."],"tags":["cli","auth","oauth","csrf","login-flow"],"backgroundTag":"oauth-state-mismatch","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}