{"record":{"id":"c7eeee2ab502182b","repo":"JuliusBrussee/caveman","slug":"device-authorization-failed-json-stringify-rawc","errorCode":null,"errorMessage":"device authorization failed: ${JSON.stringify(rawCode)}","messagePattern":"device authorization failed: (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/device-auth/src/index.ts","lineNumber":107,"sourceCode":"  signal?: AbortSignal;\n  sleep?: (ms: number) => Promise<void>;\n  onCode?: (code: DeviceCode) => void | Promise<void>;\n}): Promise<DeviceGrant> {\n  const fetcher = options.fetch ?? globalThis.fetch;\n  const wait = options.sleep ?? defaultSleep;\n  const baseURL = options.baseURL.replace(/\\/$/, \"\");\n  const codeResponse = await fetcher(`${baseURL}/api/v1/auth/device/code`, {\n    method: \"POST\",\n    headers: { \"content-type\": \"application/json\", \"x-cave-client\": options.client },\n    body: \"{}\",\n    signal: requestSignal(options.signal, 5000),\n  });\n  if (!codeResponse.ok) throw new Error(`device authorization failed: HTTP ${codeResponse.status}`);\n  const rawCode = await codeResponse.json().catch(() => null) as Partial<DeviceCode> | null;\n  if (rawCode === null || typeof rawCode.device_code !== \"string\" || rawCode.device_code === \"\" ||\n    typeof rawCode.user_code !== \"string\" || typeof rawCode.verification_uri !== \"string\" ||\n    typeof rawCode.expires_in !== \"number\" || !Number.isFinite(rawCode.expires_in) || rawCode.expires_in <= 0) {\n    throw new Error(`device authorization failed: ${JSON.stringify(rawCode)}`);\n  }\n  const code = rawCode as DeviceCode;\n  await options.onCode?.(structuredClone(code));\n  let intervalMs = Math.max(0, Number(code.interval ?? 5)) * 1000;\n  const deadline = Date.now() + code.expires_in * 1000;\n  while (Date.now() < deadline) {\n    let payload: Record<string, unknown>;\n    let status = 0;\n    let retryAfterMs = 0;\n    try {\n      const response = await fetcher(`${baseURL}/api/v1/auth/device/token`, {\n        method: \"POST\",\n        headers: { \"content-type\": \"application/json\", \"x-cave-client\": options.client },\n        body: JSON.stringify({ device_code: code.device_code }),\n        signal: requestSignal(options.signal, 5000),\n      });\n      status = response.status;\n      const retryAfter = response.headers.get(\"retry-after\");","sourceCodeStart":89,"sourceCodeEnd":125,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/device-auth/src/index.ts#L89-L125","documentation":"Thrown by runCavemanDeviceFlow when the device-code endpoint responds 2xx but its JSON body fails DeviceCode validation: missing/empty device_code, user_code, verification_uri, or a non-positive/non-finite expires_in (a JSON parse failure yields null and also triggers this). The library refuses to proceed with malformed authorization data.","triggerScenarios":"codeResponse.ok is true but `await codeResponse.json()` returns null (unparseable body) or a Partial<DeviceCode> failing any of: device_code/user_code/verification_uri must be non-empty strings, expires_in must be a finite number > 0.","commonSituations":"Server behind a gateway returning an HTML error page with 200, an API version mismatch returning a different schema, a mock/stub server returning an empty body, or an incompatible server release.","solutions":["Log/capture the JSON.stringify(rawCode) payload from the message to see exactly which field is missing or malformed.","Verify server and client versions are compatible (the server must return device_code, user_code, verification_uri, expires_in).","Check that no proxy or middleware is rewriting the response body (HTML challenge pages, WAF interstitials).","Retry; if transient (e.g. an edge node served a bad body), a fresh request often succeeds."],"exampleFix":"// server returning wrong shape\n{ \"device_code\": \"abc\" }  // missing user_code, verification_uri, expires_in\n// after (correct DeviceCode shape)\n{ \"device_code\": \"abc\", \"user_code\": \"ABCD-EFGH\", \"verification_uri\": \"https://example.com/activate\", \"expires_in\": 900 }","handlingStrategy":"validation","validationCode":"function isValidDeviceCode(v: unknown): v is { device_code: string; user_code: string; verification_uri: string; expires_in: number } {\n  const d = v as any;\n  return !!d && typeof d.device_code === 'string' && d.device_code !== '' &&\n    typeof d.user_code === 'string' && typeof d.verification_uri === 'string' &&\n    typeof d.expires_in === 'number' && Number.isFinite(d.expires_in) && d.expires_in > 0;\n}","typeGuard":"const isDeviceCode = (v: unknown): v is DeviceCode =>\n  typeof v === 'object' && v !== null &&\n  typeof (v as DeviceCode).device_code === 'string' && (v as DeviceCode).device_code !== '' &&\n  typeof (v as DeviceCode).user_code === 'string' &&\n  typeof (v as DeviceCode).verification_uri === 'string' &&\n  typeof (v as DeviceCode).expires_in === 'number' && (v as DeviceCode).expires_in > 0;","tryCatchPattern":"try {\n  await runCavemanDeviceFlow(opts);\n} catch (e) {\n  if (e instanceof Error && e.message.startsWith('device authorization failed: {')) {\n    console.error('Malformed device-code response:', e.message);\n  } else throw e;\n}","preventionTips":["Keep server and client package versions aligned","Test the flow against staging to catch schema drift","Check for proxies/WAFs that rewrite JSON bodies","Log raw responses on failure for support tickets"],"tags":["validation","device-auth","response-shape","json"],"backgroundTag":"unexpected-api-response-shape","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"}