{"record":{"id":"164c9ccdd3ca1290","repo":"decolua/9router","slug":"xai-token-refresh-failed-err","errorCode":null,"errorMessage":"xAI token refresh failed: ${err}","messagePattern":"xAI token refresh failed: (.+?)","errorType":"http","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/lib/oauth/services/xai.js","lineNumber":171,"sourceCode":"   * Refresh an access token using a refresh_token.\n   */\n  async refreshAccessToken(refreshToken) {\n    const { tokenUrl } = await discoverEndpoints();\n    const res = await fetch(tokenUrl, {\n      method: \"POST\",\n      headers: {\n        \"Content-Type\": \"application/x-www-form-urlencoded\",\n        Accept: \"application/json\",\n      },\n      body: new URLSearchParams({\n        grant_type: \"refresh_token\",\n        client_id: XAI_CONFIG.clientId,\n        refresh_token: refreshToken,\n      }),\n    });\n    if (!res.ok) {\n      const err = await res.text();\n      throw new Error(`xAI token refresh failed: ${err}`);\n    }\n    return await res.json();\n  }\n\n  /**\n   * Complete xAI OAuth flow end-to-end (CLI entrypoint).\n   * Returns the raw token response plus extracted email.\n   */\n  async connect() {\n    const spinner = createSpinner(\"Starting xAI OAuth...\").start();\n    try {\n      spinner.text = \"Discovering xAI endpoints...\";\n      const { authorizeUrl, tokenUrl } = await discoverEndpoints();\n\n      spinner.text = `Starting local server on port ${XAI_CONFIG.loopbackPort}...`;\n      let callbackParams = null;\n      const { port, close } = await startLocalServer((params) => {\n        callbackParams = params;","sourceCodeStart":153,"sourceCodeEnd":189,"githubUrl":"https://github.com/decolua/9router/blob/90b52e06ffd666b7929554211474d01588f6b1f8/src/lib/oauth/services/xai.js#L153-L189","documentation":"refreshAccessToken posts a refresh_token grant to xAI's token endpoint to obtain a new access token. On a non-ok response it throws 'xAI token refresh failed: <body>' with the upstream body text. A failure here usually means the refresh token is invalid, expired, or has been rotated/revoked.","triggerScenarios":"Refresh POST returns 400 (invalid_grant — refresh token expired or revoked, or already used after rotation), 401 (invalid_client), or 5xx from xAI.","commonSituations":"Long-lived stored credentials finally expiring; xAI rotating refresh tokens on each use and the app reusing an old one after a concurrent refresh; user revoking the app in their xAI account settings.","solutions":["Inspect the thrown body: invalid_grant means re-authentication is required — the refresh token cannot be recovered.","Persist the NEW refresh token immediately after each successful refresh if xAI rotates them.","Guard against concurrent refreshes of the same account (single-flight/lock) to avoid burning rotated tokens.","If 5xx, retry with backoff — the token may still be valid."],"exampleFix":"// before\nconst t = await refreshAccessToken(stored.refreshToken); // throws when expired\n// after\ntry {\n  const t = await refreshAccessToken(stored.refreshToken);\n  saveNewRefreshToken(t.refresh_token ?? stored.refreshToken);\n} catch (e) {\n  if (e.message.includes('invalid_grant')) return requireReauthorization(account);\n  throw e;\n}","handlingStrategy":"try-catch","validationCode":"if (typeof refreshToken !== 'string' || !refreshToken) {\n  return requireReauthorization(account); // nothing to refresh with\n}","typeGuard":null,"tryCatchPattern":"try {\n  const tokens = await refreshAccessToken(refreshToken);\n  if (tokens.refresh_token && tokens.refresh_token !== refreshToken) {\n    await persistRotatedToken(account, tokens.refresh_token); // rotation: save immediately\n  }\n} catch (e) {\n  if (!e.message.startsWith('xAI token refresh failed:')) throw e;\n  if (e.message.includes('invalid_grant')) return requireReauthorization(account); // expired/revoked\n  if (/HTTP 5\\d\\d|fetch failed/.test(e.message)) return retryWithBackoff();\n  throw e;\n}","preventionTips":["Persist rotated refresh tokens immediately after every successful refresh.","Serialize refreshes per account (single-flight) so concurrent calls can't consume a rotated token twice.","Detect invalid_grant and route the user to re-authorization rather than retrying forever.","Proactively refresh before expiry using expires_in, reducing reliance on the refresh path."],"tags":["oauth","xai","refresh-token","http"],"backgroundTag":"oauth-token-refresh-failed","analyzedSha":"90b52e06ffd666b7929554211474d01588f6b1f8","analyzedAt":"2026-08-30T21:05:45.952Z","schemaVersion":2},"datasetVersion":"2026-08-30T23:17:21.991Z"}