{"record":{"id":"6344f5febc395881","repo":"JuliusBrussee/caveman","slug":"device-login-failed-errorcode","errorCode":null,"errorMessage":"device login failed: ${errorCode}","messagePattern":"device login failed: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/cli/src/index.ts","lineNumber":9789,"sourceCode":"      // effort: login never fails for seats or a down entitlement service.\n      await fetchAndStoreWrapEntitlement(baseURL, credentials.access_token);\n      if (gateway && wrapMode(gateway) === \"managed\") {\n        console.error(`  ${mark(\"ok\")} wrap now routes through the managed gateway (${gateway}) — governed reporting; verified stays zero without qualifying provider evidence`);\n      } else if (gateway) {\n        console.error(`  ${mark(\"ok\")} connected; wrap routes through ${gateway}`);\n      }\n      console.error(SYNC_DISCLOSURE);\n      print({ authenticated: true, baseURL, gateway_url: gateway || null, organization_id: organizationId ?? null, token_store: tokenStore });\n      // The funnel bridge: pull the spans the local proxy already measured into\n      // the dashboard, once, right now (always labeled inferred; best-effort).\n      await syncAfterLogin();\n      return;\n    }\n    const errorCode = typeof tok.error === \"string\" ? tok.error : \"\";\n    if (errorCode === \"slow_down\") {\n      intervalMs = nextDevicePollIntervalMs(intervalMs, errorCode);\n    } else if (errorCode && errorCode !== \"authorization_pending\") {\n      throw new Error(`device login failed: ${errorCode}`);\n    }\n    await sleep(Math.max(intervalMs, 200));\n  }\n  throw new Error(\"device login timed out before approval\");\n}\n\nasync function logout() {\n\tconst cfg = await config();\n\tconst externalToken = Boolean(process.env.CAVE_TOKEN);\n\tif (cfg.token && (!cfg.logoutPendingLocalCleanup || externalToken)) {\n\t  if (cfg.projectId && cfg.gatewayKeyId) {\n\t    let response: Response;\n\t    try {\n\t      response = await fetch(`${cfg.baseURL}/api/v1/projects/${encodeURIComponent(cfg.projectId)}/keys/${encodeURIComponent(cfg.gatewayKeyId)}/revoke`, {\n\t        method: \"POST\",\n\t        headers: { authorization: `Bearer ${cfg.token}`, \"content-type\": \"application/json\", \"x-cave-csrf\": \"cli\" },\n\t        body: \"{}\",\n\t        signal: AbortSignal.timeout(5000),","sourceCodeStart":9771,"sourceCodeEnd":9807,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/cli/src/index.ts#L9771-L9807","documentation":"During RFC 8628 token polling the server may return an `error` field. `authorization_pending` and `slow_down` are expected and handled; any other error code (e.g. expired_token, access_denied, invalid_grant) is fatal and thrown with the code included. The flow then ends without credentials.","triggerScenarios":"The token endpoint returns a payload whose `error` is any value other than \"authorization_pending\" or \"slow_down\" — most commonly \"expired_token\" (user never approved in time), \"access_denied\" (user rejected the request), or \"invalid_grant\".","commonSituations":"User waited too long to approve, so the device code expired; user clicked 'deny' in the browser; someone else consumed the code; server revoked the pending grant.","solutions":["Read the error code in the message: expired_token → re-run login and approve faster; access_denied → re-run and approve the request","Re-run `login` to get a fresh device code","If codes expire too quickly, increase the device-code lifetime on the authorization server","Check that the correct user account is used when approving in the browser"],"exampleFix":"// before\n// user lets the code expire: server returns { \"error\": \"expired_token\" }\n// after\n// re-run promptly\ncaveman login --instance=https://your-instance  // then approve within the code lifetime","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try { await login({ instance }) } catch (e) {\n  const m = e.message.match(/device login failed: (\\S+)/);\n  if (m?.[1] === \"expired_token\") await promptReLoginQuickly();\n  else if (m?.[1] === \"access_denied\") await promptUserToApprove();\n}","preventionTips":["Approve the device code in the browser promptly after login starts","Never reuse an already-consumed user code","Increase device-code lifetime on the authorization server if approvals are slow","Ensure the approving user matches the intended account"],"tags":["oauth","device-flow","token-exchange"],"backgroundTag":"oauth-token-exchange-failed","analyzedSha":"3ee70a102609e550bd2e68004bf5990a9341c851","analyzedAt":"2026-09-20T15:53:39.229Z","contentChangedAt":"2026-09-20T15:53:39.229Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}