Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(desktop): surface server 401 reason and add auth log analyzer (#19240)

Innei8933f373167d
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 628e73e21a1..74cebdad35a 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -31,6 +31,7 @@
"lint:md": "remark . --silent --output",
"lint:style": "stylelint \"{src,tests}/**/*.{js,jsx,ts,tsx}\" --fix",
"lint:ts": "eslint \"{src,tests}/**/*.{js,jsx,ts,tsx}\" --fix",
+ "log:auth": "node scripts/analyzeAuthLog.mjs",
"package:linux": "npm run build:main && electron-builder --linux --config electron-builder.mjs --publish never",
"package:local": "npm run build:main && electron-builder --dir --config electron-builder.mjs --c.mac.notarize=false -c.mac.identity=null --c.asar=false",
"package:local:reuse": "electron-builder --dir --config electron-builder.mjs --c.mac.notarize=false -c.mac.identity=null --c.asar=false",
diff --git a/apps/desktop/scripts/__tests__/analyzeAuthLog.test.mjs b/apps/desktop/scripts/__tests__/analyzeAuthLog.test.mjs
new file mode 100644
index 00000000000..d7d3b3e4e78
--- /dev/null
+++ b/apps/desktop/scripts/__tests__/analyzeAuthLog.test.mjs
@@ -0,0 +1,158 @@
+import { describe, expect, it } from 'vitest';
+
+import { analyzeAuthLog, parseAuthEvents } from '../analyzeAuthLog.mjs';
+
+const line = (ts, level, ns, msg) => `[${ts}] [${level}] [${ns}] ${msg}`;
+const codes = (text) => analyzeAuthLog(text).verdicts.map((v) => v.code);
+
+describe('parseAuthEvents', () => {
+ it('parses reason fields and ignores unrelated or continuation lines', () => {
+ const text = [
+ line('2026-09-06 19:01:00.000', 'info', 'core:App', ' OS: darwin (arm64)'),
+ line(
+ '2026-09-06 19:01:01.000',
+ 'info',
+ 'services:GatewayConnectionSrv',
+ 'Connection status: connected',
+ ),
+ ' at Yd.getAccessToken (main-app.js:54:20945)',
+ line(
+ '2026-09-06 19:01:02.000',
+ 'info',
+ 'core:BackendProxyProtocolManager',
+ '[main] BackendProxy auth response proxy:main:status=401 POST /trpc/lambda/me hadToken=true authRequired=true token{sub=user_123 exp=2026-09-06T10:00:00.000Z expiredBy=3600s} authFailure=jwt_expired body={"error":{}}',
+ ),
+ ].join('\n');
+
+ const events = parseAuthEvents(text);
+ expect(events.map((e) => e.kind)).toEqual(['appStart', 'authResponse']);
+ expect(events[1].fields).toMatchObject({
+ authFailure: 'jwt_expired',
+ authRequired: true,
+ expiredBySeconds: 3600,
+ hadToken: true,
+ route: 'POST /trpc/lambda/me',
+ status: 401,
+ });
+ });
+});
+
+describe('analyzeAuthLog verdicts', () => {
+ it('flags safeStorage decrypt failure when a tokenless 401 follows it', () => {
+ expect(
+ codes(
+ [
+ line(
+ '2026-09-06 19:01:25.167',
+ 'error',
+ 'controllers:RemoteServerConfigCtr',
+ 'Failed to decrypt access token: Error: Error while decrypting the ciphertext provided to safeStorage.decryptString.',
+ ),
+ line(
+ '2026-09-06 19:01:26.000',
+ 'info',
+ 'core:BackendProxyProtocolManager',
+ 'Broadcasting authorizationRequired (reason=proxy:status=401 GET /trpc/lambda/me hadToken=false body=x)',
+ ),
+ ].join('\n'),
+ ),
+ ).toEqual(['SAFE_STORAGE_DECRYPT_FAILED']);
+ });
+
+ it('flags a revoked refresh token from the real 400 grant error', () => {
+ expect(
+ codes(
+ [
+ line(
+ '2026-08-11 02:02:26.151',
+ 'info',
+ 'controllers:AuthCtr',
+ 'Token is expiring soon, triggering auto-refresh. Expires at: 2026-08-10T18:10:30.800Z',
+ ),
+ line(
+ '2026-08-11 02:02:26.564',
+ 'error',
+ 'controllers:RemoteServerConfigCtr',
+ 'Token refresh failed: 400 grant request is invalid {',
+ ),
+ line(
+ '2026-08-11 02:02:26.566',
+ 'error',
+ 'controllers:AuthCtr',
+ 'Auto-refresh failed after retries: Token refresh failed: 400 grant request is invalid',
+ ),
+ line(
+ '2026-08-11 02:02:26.600',
+ 'info',
+ 'controllers:AuthCtr',
+ 'Broadcasting authorizationRequired event (reason=auto-refresh:non_retryable Token refresh failed: 400)',
+ ),
+ ].join('\n'),
+ ),
+ ).toEqual(['REFRESH_TOKEN_REVOKED']);
+ });
+
+ it('separates expired-not-refreshed, signature mismatch, header dropped and inactive user', () => {
+ const at = (s, reason) =>
+ line(
+ `2026-09-07 10:00:0${s}.000`,
+ 'info',
+ 'core:BackendProxyProtocolManager',
+ `[main] BackendProxy auth response ${reason}`,
+ );
+ expect(
+ codes(
+ [
+ at(
+ 1,
+ 'proxy:status=401 POST /trpc/a hadToken=true authRequired=true token{expiredBy=5s} authFailure=jwt_expired',
+ ),
+ at(
+ 2,
+ 'proxy:status=401 POST /trpc/b hadToken=true authRequired=true token{expiresIn=500s} authFailure=jwt_signature',
+ ),
+ at(
+ 3,
+ 'proxy:status=401 POST /trpc/c hadToken=true authRequired=true token{expiresIn=500s} authFailure=no_token',
+ ),
+ at(
+ 4,
+ 'proxy:status=401 POST /trpc/d hadToken=true authRequired=true token{expiresIn=500s} authFailure=user_inactive',
+ ),
+ ].join('\n'),
+ ),
+ ).toEqual([
+ 'TOKEN_EXPIRED_NOT_REFRESHED',
+ 'SERVER_KEY_MISMATCH',
+ 'HEADER_DROPPED_IN_TRANSIT',
+ 'USER_INACTIVE',
+ ]);
+ });
+
+ it('flags non-session 401s and old-build unknown rejections', () => {
+ expect(
+ codes(
+ [
+ line(
+ '2026-09-07 10:00:01.000',
+ 'info',
+ 'core:BackendProxyProtocolManager',
+ '[main] BackendProxy auth response proxy:status=401 POST /webapi/chat hadToken=true authRequired=false token=opaque body={"errorType":"InvalidProviderAPIKey"}',
+ ),
+ line(
+ '2026-09-07 10:00:02.000',
+ 'info',
+ 'core:BackendProxyProtocolManager',
+ 'Broadcasting authorizationRequired (reason=proxy:status=401 POST /trpc/lambda/me hadToken=true body={"error":"UNAUTHORIZED"})',
+ ),
+ ].join('\n'),
+ ),
+ ).toEqual(['NON_SESSION_401', 'SERVER_REJECTED_UNKNOWN']);
+ });
+
+ it('reports NO_AUTH_EVENTS for a log with nothing relevant', () => {
+ expect(
+ codes(line('2026-09-07 10:00:01.000', 'info', 'core:App', 'PATH: /Applications')),
+ ).toEqual(['NO_AUTH_EVENTS']);
+ });
+});
diff --git a/apps/desktop/scripts/analyzeAuthLog.mjs b/apps/desktop/scripts/analyzeAuthLog.mjs
new file mode 100644
index 00000000000..5de95cf18c0
--- /dev/null
+++ b/apps/desktop/scripts/analyzeAuthLog.mjs
@@ -0,0 +1,267 @@
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const LINE_RE = /^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})\] \[(\w+)\]\s+\[([^\]]+)\] (.*)$/;
+
+const MATCHERS = [
+ { kind: 'appStart', re: /^\s*OS: (.+)$/, summary: (m) => `app started (${m[1]})` },
+ {
+ kind: 'authResponse',
+ re: /auth response (proxy:.*)$/,
+ summary: (m) => m[1],
+ fields: (m) => parseReason(m[1]),
+ },
+ {
+ kind: 'authRequired',
+ re: /Broadcasting authorizationRequired(?: event)? \(reason=(.*)\)$/,
+ summary: (m) => m[1],
+ fields: (m) => parseReason(m[1]),
+ },
+ {
+ kind: 'streamAuthResponse',
+ re: /\[(?:ForwardStream|StreamProxy) [^\]]+\]\[[^\]]+\] auth response (status=.*)$/,
+ summary: (m) => m[1],
+ fields: (m) => parseReason(m[1]),
+ },
+ {
+ kind: 'decryptFailed',
+ re: /Failed to decrypt (access|refresh) token/,
+ summary: (m) => `${m[1]} token decrypt failed`,
+ },
+ {
+ kind: 'safeStorageUnavailable',
+ re: /Safe storage not available/,
+ summary: () => 'safeStorage unavailable',
+ },
+ {
+ kind: 'refreshFailed',
+ re: /(?:Token refresh failed|Auto-refresh failed after retries|Proactive token refresh failed|Token refresh failed via AuthCtr call|Exception during token refresh operation): (.*)$/,
+ summary: (m) => m[1].trim(),
+ },
+ {
+ kind: 'refreshFailed',
+ re: /No refresh token available/,
+ summary: () => 'no refresh token in storage',
+ },
+ {
+ kind: 'refreshOk',
+ re: /(Token refresh successful|Auto-refresh successful|Proactive token refresh successful)/,
+ summary: (m) => m[1],
+ },
+ {
+ kind: 'refreshTriggered',
+ re: /(Token is expiring soon.*|Token is expired or expiring soon.*|Initiating new token refresh operation)/,
+ summary: (m) => m[1],
+ },
+ {
+ kind: 'timerStarted',
+ re: /Token is valid, starting auto-refresh timer\. Token expires at: (.*)$/,
+ summary: (m) => `auto-refresh timer armed, exp ${m[1]}`,
+ },
+ {
+ kind: 'tokensSaved',
+ re: /(Successfully saved exchanged tokens|Authorization successful)/,
+ summary: (m) => m[1],
+ },
+ {
+ kind: 'tokensCleared',
+ re: /Clearing (access and refresh tokens|remote server configuration)/,
+ summary: (m) => `cleared ${m[1]}`,
+ },
+ {
+ kind: 'loginStarted',
+ re: /Requesting OAuth authorization, storageMode:(\S+) server URL: (\S+)/,
+ summary: (m) => `login started (${m[1]} ${m[2]})`,
+ },
+];
+
+function parseReason(reason) {
+ const fields = {};
+ const status = reason.match(/status=(\d+)/);
+ if (status) fields.status = Number(status[1]);
+ const hadToken = reason.match(/hadToken=(true|false)/);
+ if (hadToken) fields.hadToken = hadToken[1] === 'true';
+ const authRequired = reason.match(/authRequired=(true|false)/);
+ if (authRequired) fields.authRequired = authRequired[1] === 'true';
+ const authFailure = reason.match(/authFailure=(\S+)/);
+ if (authFailure) fields.authFailure = authFailure[1];
+ const route = reason.match(/\b(GET|POST|PUT|DELETE|PATCH) (\S+)/);
+ if (route) fields.route = `${route[1]} ${route[2]}`;
+ const expiredBy = reason.match(/expiredBy=(\d+)s/);
+ if (expiredBy) fields.expiredBySeconds = Number(expiredBy[1]);
+ const expiresIn = reason.match(/expiresIn=(\d+)s/);
+ if (expiresIn) fields.expiresInSeconds = Number(expiresIn[1]);
+ const tag = reason.match(/^((?:refresh|auto-refresh|startup|activate)\S*)/);
+ if (tag) fields.tag = tag[1];
+ const body = reason.match(/body=(.*)$/);
+ if (body) fields.body = body[1];
+ return fields;
+}
+
+export function parseAuthEvents(text) {
+ const events = [];
+ for (const rawLine of text.split(/\r?\n/)) {
+ const line = rawLine.match(LINE_RE);
+ if (!line) continue;
+ const [, timestamp, level, namespace, message] = line;
+ for (const matcher of MATCHERS) {
+ const m = message.match(matcher.re);
+ if (!m) continue;
+ events.push({
+ fields: matcher.fields ? matcher.fields(m) : {},
+ kind: matcher.kind,
+ level,
+ namespace,
+ summary: matcher.summary(m),
+ timestamp,
+ });
+ break;
+ }
+ }
+ return events.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
+}
+
+const VERDICTS = {
+ HEADER_DROPPED_IN_TRANSIT: {
+ next: 'Desktop injected Oidc-Auth but the server saw none. Check the user’s proxy / VPN / corporate gateway stripping custom headers, or a remote URL that redirects (headers are dropped on cross-origin redirect).',
+ title: 'Token sent, server received no token',
+ },
+ NON_SESSION_401: {
+ next: 'Not a login problem. Read the body: provider API key, market OAuth, or a workspace permission. Route the ticket to that feature.',
+ title: '401 without X-Auth-Required',
+ },
+ NO_AUTH_EVENTS: {
+ next: 'Ask for both main.log and main.old.log from the logs directory (Help > Open Logs Directory), and confirm the 401 happened in the desktop app rather than a browser tab.',
+ title: 'No auth events in this log',
+ },
+ NO_TOKEN_STORED: {
+ next: 'No token was ever saved in this session and no decrypt error. Check whether login completed (look for "Successfully saved exchanged tokens") or whether the store file was removed.',
+ title: 'Request went out without a token',
+ },
+ REFRESH_TOKEN_REVOKED: {
+ next: 'The refresh token was rotated away or revoked (another device, crash between rotation and save, or server-side revoke). Re-login is the only fix; check for a second device/session if it recurs.',
+ title: 'Refresh rejected by server',
+ },
+ SAFE_STORAGE_DECRYPT_FAILED: {
+ next: 'macOS Keychain / Windows DPAPI could not decrypt the stored token (new signing identity, keychain reset, or profile migration). Re-login is required; if it recurs on every launch, the keychain entry for the app is denied.',
+ title: 'Stored token could not be decrypted',
+ },
+ SERVER_KEY_MISMATCH: {
+ next: 'The token signature does not match the server JWKS. Either the server rotated its key or the desktop is pointed at a different server than it logged in to. Compare the login server URL against the current remote URL.',
+ title: 'Server rejected token signature',
+ },
+ SERVER_REJECTED_UNKNOWN: {
+ next: 'This build predates X-Auth-Failure so the server reason is unknown. Ask the user to update and reproduce, or search server logs for "OIDC authentication failed" near this timestamp.',
+ title: 'Server rejected a token, reason not logged',
+ },
+ TOKEN_EXPIRED_NOT_REFRESHED: {
+ next: 'Access token expired before the auto-refresh ran (sleep/wake, timer lost, or app not running). Check the gap between the last "timer armed" and this 401; the refresh cycle should recover on next launch.',
+ title: 'Expired token used, refresh did not run',
+ },
+ USER_INACTIVE: {
+ next: 'The account is banned or deleted on the server. Nothing to fix client-side.',
+ title: 'Account inactive on server',
+ },
+};
+
+const lastBefore = (events, index, kinds) => {
+ for (let i = index - 1; i >= 0; i -= 1) {
+ if (kinds.includes(events[i].kind)) return events[i];
+ }
+ return undefined;
+};
+
+function classify(events, index) {
+ const event = events[index];
+ const { authFailure, authRequired, hadToken, expiredBySeconds } = event.fields;
+
+ if (hadToken === false) {
+ if (lastBefore(events, index, ['decryptFailed'])) return 'SAFE_STORAGE_DECRYPT_FAILED';
+ const cleared = lastBefore(events, index, ['tokensCleared', 'tokensSaved']);
+ if (cleared?.kind === 'tokensCleared') {
+ const refreshFailed = lastBefore(events, index, ['refreshFailed']);
+ return refreshFailed ? 'REFRESH_TOKEN_REVOKED' : 'NO_TOKEN_STORED';
+ }
+ return 'NO_TOKEN_STORED';
+ }
+
+ if (authRequired === false) return 'NON_SESSION_401';
+ if (authFailure === 'jwt_expired' || (!authFailure && expiredBySeconds !== undefined))
+ return 'TOKEN_EXPIRED_NOT_REFRESHED';
+ if (authFailure === 'jwt_signature' || authFailure === 'jwks_error') return 'SERVER_KEY_MISMATCH';
+ if (authFailure === 'user_inactive') return 'USER_INACTIVE';
+ if (authFailure === 'no_token') return 'HEADER_DROPPED_IN_TRANSIT';
+ if (hadToken === true) return 'SERVER_REJECTED_UNKNOWN';
+ return undefined;
+}
+
+export function analyzeAuthLog(text) {
+ const events = parseAuthEvents(text);
+ const verdicts = new Map();
+ const record = (code, event) => {
+ if (!verdicts.has(code))
+ verdicts.set(code, { code, count: 0, first: event, ...VERDICTS[code] });
+ const verdict = verdicts.get(code);
+ verdict.count += 1;
+ verdict.last = event;
+ };
+
+ events.forEach((event, index) => {
+ if (['authResponse', 'authRequired', 'streamAuthResponse'].includes(event.kind)) {
+ if (event.fields.tag) return;
+ const code = classify(events, index);
+ if (code) record(code, event);
+ return;
+ }
+ if (
+ event.kind === 'refreshFailed' &&
+ /invalid_grant|grant request is invalid|400/.test(event.summary)
+ ) {
+ record('REFRESH_TOKEN_REVOKED', event);
+ }
+ if (event.kind === 'decryptFailed') record('SAFE_STORAGE_DECRYPT_FAILED', event);
+ });
+
+ if (verdicts.size === 0) {
+ record('NO_AUTH_EVENTS', events[0]);
+ }
+
+ return { events, verdicts: [...verdicts.values()] };
+}
+
+export function formatReport({ events, verdicts }, { limit = 80 } = {}) {
+ const lines = ['== Verdicts =='];
+ for (const v of verdicts) {
+ lines.push(
+ `* ${v.code} (${v.count}x)${v.first ? ` first at ${v.first.timestamp}` : ''}: ${v.title}`,
+ );
+ lines.push(` next: ${v.next}`);
+ }
+ const shown = limit > 0 ? events.slice(-limit) : events;
+ lines.push(
+ '',
+ `== Auth timeline (last ${shown.length} of ${events.length} events; --all for everything) ==`,
+ );
+ for (const e of shown) {
+ lines.push(`${e.timestamp} [${e.level}] ${e.kind.padEnd(22)} ${e.summary}`);
+ }
+ return lines.join('\n');
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ const args = process.argv.slice(2);
+ const json = args.includes('--json');
+ const all = args.includes('--all');
+ const files = args.filter((a) => !a.startsWith('--'));
+ if (files.length === 0) {
+ console.error(
+ 'usage: node scripts/analyzeAuthLog.mjs [--json] [--all] <main.log> [main.old.log ...]',
+ );
+ process.exit(1);
+ }
+ const text = files.map((f) => readFileSync(f, 'utf8')).join('\n');
+ const result = analyzeAuthLog(text);
+ console.log(
+ json ? JSON.stringify(result, null, 2) : formatReport(result, { limit: all ? 0 : 80 }),
+ );
+}
diff --git a/apps/desktop/src/main/controllers/RemoteServerSyncCtr.ts b/apps/desktop/src/main/controllers/RemoteServerSyncCtr.ts
index 103c483cf6b..00706fd88b0 100644
--- a/apps/desktop/src/main/controllers/RemoteServerSyncCtr.ts
+++ b/apps/desktop/src/main/controllers/RemoteServerSyncCtr.ts
@@ -12,6 +12,7 @@ import { HttpsProxyAgent } from 'https-proxy-agent';
import { defaultProxySettings } from '@/const/store';
import { appendVercelCookie } from '@/utils/http-headers';
+import { describeJwtClaims } from '@/utils/jwt-claims';
import { createLogger } from '@/utils/logger';
import { setDesktopUserAgentHeader } from '@/utils/user-agent';
@@ -126,6 +127,11 @@ export default class RemoteServerSyncCtr extends ControllerModule {
const clientReq = requester.request(requestOptions, (clientRes: IncomingMessage) => {
logger.debug(`${logPrefix} Received response with status ${clientRes.statusCode}`);
+ if (clientRes.statusCode === 401 || clientRes.statusCode === 403) {
+ logger.info(
+ `${logPrefix} auth response status=${clientRes.statusCode} authRequired=${clientRes.headers['x-auth-required'] === 'true'} authFailure=${clientRes.headers['x-auth-failure'] ?? ''} ${describeJwtClaims(accessToken)}`,
+ );
+ }
// Add debug information
logger.debug(`${logPrefix} Response details:`, {
diff --git a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
index f2d131337d5..c1e18af3d70 100644
--- a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
@@ -1,10 +1,11 @@
-import { AUTH_REQUIRED_HEADER } from '@lobechat/desktop-bridge';
+import { AUTH_FAILURE_HEADER, AUTH_REQUIRED_HEADER } from '@lobechat/desktop-bridge';
import { BrowserWindow, type Session, session as electronSession } from 'electron';
import { isDev } from '@/const/env';
import { isBackendPath } from '@/const/protocol';
import { getDesktopEnv } from '@/env';
import { appendVercelCookie } from '@/utils/http-headers';
+import { describeJwtClaims } from '@/utils/jwt-claims';
import { createLogger } from '@/utils/logger';
import { netFetch } from '@/utils/net-fetch';
import { classifyProxyNetworkError } from '@/utils/proxy-network-error';
@@ -348,7 +349,8 @@ export class BackendProxyProtocolManager {
// checking only status === 401 misses that case and the login modal never opens.
// Other failures keep 401 without this header (e.g., invalid API keys) and must not notify here.
const authRequired = upstreamResponse.headers.get(AUTH_REQUIRED_HEADER) === 'true';
- if (authRequired) {
+ const isAuthStatus = upstreamResponse.status === 401 || upstreamResponse.status === 403;
+ if (authRequired || isAuthStatus) {
const pathTag = (() => {
try {
return new URL(rewrittenUrl).pathname;
@@ -358,6 +360,7 @@ export class BackendProxyProtocolManager {
})();
const sourceTag = context.source ? `${context.source}:` : '';
const wwwAuth = upstreamResponse.headers.get('www-authenticate') ?? '';
+ const authFailure = upstreamResponse.headers.get(AUTH_FAILURE_HEADER) ?? '';
// Clone before forwarding the body downstream — the original stream stays
// intact for the renderer. Body snippet is truncated to keep logs small
// and to avoid leaking large payloads if the server ever returns one.
@@ -371,10 +374,18 @@ export class BackendProxyProtocolManager {
`proxy:${sourceTag}status=${upstreamResponse.status}`,
`${request.method} ${pathTag}`,
`hadToken=${Boolean(token)}`,
+ `authRequired=${authRequired}`,
+ describeJwtClaims(token),
];
+ if (authFailure) parts.push(`authFailure=${authFailure}`);
if (wwwAuth) parts.push(`wwwAuth=${wwwAuth}`);
if (bodySnippet) parts.push(`body=${bodySnippet}`);
- this.notifyAuthorizationRequired(parts.join(' '));
+ const reason = parts.join(' ');
+ // Every auth-status response lands in the production log file, not only
+ // the ones that open the re-login modal: a 401 without X-Auth-Required is
+ // exactly the case that was previously invisible in user-supplied logs.
+ this.logger.info(`${logPrefix} auth response ${reason}`);
+ if (authRequired) this.notifyAuthorizationRequired(reason);
}
return new Response(
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
index 03cb0fabc63..b0537b80a30 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
@@ -1,4 +1,4 @@
-import { AUTH_REQUIRED_HEADER } from '@lobechat/desktop-bridge';
+import { AUTH_FAILURE_HEADER, AUTH_REQUIRED_HEADER } from '@lobechat/desktop-bridge';
import { BrowserWindow, session as electronSession } from 'electron';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -10,6 +10,18 @@ interface RequestInitWithDuplex extends RequestInit {
type FetchMock = (input: RequestInfo | URL, init?: RequestInitWithDuplex) => Promise<Response>;
+const loggerMock = vi.hoisted(() => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ verbose: vi.fn(),
+ warn: vi.fn(),
+}));
+
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => loggerMock,
+}));
+
vi.mock('@/utils/platform', () => ({
dev: vi.fn(() => false),
macOS: vi.fn(() => false),
@@ -374,6 +386,85 @@ describe('BackendProxyProtocolManager', () => {
expect(payload.reason).toContain('token expired');
});
+ it('logs X-Auth-Failure and decoded token claims on a session 401', async () => {
+ vi.useFakeTimers();
+ const send = vi.fn();
+ vi.mocked(BrowserWindow.getAllWindows).mockReturnValue([
+ { isDestroyed: () => false, webContents: { send } },
+ ] as any);
+
+ const manager = new BackendProxyProtocolManager();
+ const session = {} as any;
+ const token = `h.${Buffer.from(JSON.stringify({ client_id: 'desktop', exp: 1, sub: 'user_12345678' })).toString('base64url')}.s`;
+ const headers = new Headers({
+ [AUTH_FAILURE_HEADER]: 'jwt_expired',
+ [AUTH_REQUIRED_HEADER]: 'true',
+ });
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn<FetchMock>(async () => new Response('{}', { headers, status: 401 })) as any,
+ );
+
+ manager.registerWithRemoteBaseUrl(session, {
+ getAccessToken: async () => token,
+ getRemoteBaseUrl: async () => 'https://remote.example.com',
+ });
+
+ await manager.proxy(
+ { headers: new Headers(), method: 'POST', url: 'app://renderer/trpc/lambda/me' } as any,
+ session,
+ );
+
+ const infoLine = loggerMock.info.mock.calls
+ .map((c) => String(c[0]))
+ .find((line) => line.includes('auth response'));
+ expect(infoLine).toContain('authFailure=jwt_expired');
+ expect(infoLine).toContain(
+ 'token{sub=user_123 client=desktop exp=1970-01-01T00:00:01.000Z expiredBy=',
+ );
+ expect(infoLine).toContain('authRequired=true');
+
+ await vi.advanceTimersByTimeAsync(1000);
+ const [, payload] = send.mock.calls[0];
+ expect(payload.reason).toContain('authFailure=jwt_expired');
+ });
+
+ it('logs a 401 without X-Auth-Required at info but does not broadcast', async () => {
+ vi.useFakeTimers();
+ const send = vi.fn();
+ vi.mocked(BrowserWindow.getAllWindows).mockReturnValue([
+ { isDestroyed: () => false, webContents: { send } },
+ ] as any);
+
+ const manager = new BackendProxyProtocolManager();
+ const session = {} as any;
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn<FetchMock>(
+ async () => new Response('{"errorType":"InvalidProviderAPIKey"}', { status: 401 }),
+ ) as any,
+ );
+
+ manager.registerWithRemoteBaseUrl(session, {
+ getAccessToken: async () => 'opaque',
+ getRemoteBaseUrl: async () => 'https://remote.example.com',
+ });
+
+ await manager.proxy(
+ { headers: new Headers(), method: 'POST', url: 'app://renderer/webapi/chat' } as any,
+ session,
+ );
+
+ const infoLine = loggerMock.info.mock.calls
+ .map((c) => String(c[0]))
+ .find((line) => line.includes('auth response'));
+ expect(infoLine).toContain('status=401 POST /webapi/chat hadToken=true authRequired=false');
+ expect(infoLine).toContain('InvalidProviderAPIKey');
+
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(send).not.toHaveBeenCalled();
+ });
+
describe('createAppRequestInterceptor', () => {
it('returns null for non-backend paths', async () => {
const manager = new BackendProxyProtocolManager();
diff --git a/apps/desktop/src/main/utils/__tests__/jwt-claims.test.ts b/apps/desktop/src/main/utils/__tests__/jwt-claims.test.ts
new file mode 100644
index 00000000000..b0b6a04fe6c
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/jwt-claims.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { describeJwtClaims, readJwtClaims } from '../jwt-claims';
+
+const makeJwt = (payload: Record<string, unknown>) =>
+ `${Buffer.from('{"alg":"RS256"}').toString('base64url')}.${Buffer.from(
+ JSON.stringify(payload),
+ ).toString('base64url')}.sig`;
+
+describe('jwt-claims', () => {
+ it('reads sub/exp/iat/client_id without verifying', () => {
+ expect(
+ readJwtClaims(makeJwt({ client_id: 'desktop', exp: 200, iat: 100, sub: 'user_abc' })),
+ ).toEqual({ clientId: 'desktop', exp: 200, iat: 100, sub: 'user_abc' });
+ });
+
+ it('returns null for non-JWT tokens', () => {
+ expect(readJwtClaims('opaque-token')).toBeNull();
+ expect(readJwtClaims('a.!!!.c')).toBeNull();
+ });
+
+ it('describes an expired token with how long ago it expired', () => {
+ const now = 1_000_000_000_000;
+ const description = describeJwtClaims(
+ makeJwt({ client_id: 'desktop', exp: now / 1000 - 90, sub: 'user_abcdefghijk' }),
+ now,
+ );
+ expect(description).toBe(
+ 'token{sub=user_abc client=desktop exp=2001-09-09T01:45:10.000Z expiredBy=90s}',
+ );
+ });
+
+ it('describes a live token with remaining seconds', () => {
+ const now = 1_000_000_000_000;
+ expect(describeJwtClaims(makeJwt({ exp: now / 1000 + 30 }), now)).toContain('expiresIn=30s');
+ });
+
+ it('labels missing and opaque tokens', () => {
+ expect(describeJwtClaims(null)).toBe('token=none');
+ expect(describeJwtClaims('opaque')).toBe('token=opaque');
+ });
+});
diff --git a/apps/desktop/src/main/utils/jwt-claims.ts b/apps/desktop/src/main/utils/jwt-claims.ts
new file mode 100644
index 00000000000..c5d7962d50e
--- /dev/null
+++ b/apps/desktop/src/main/utils/jwt-claims.ts
@@ -0,0 +1,48 @@
+import { Buffer } from 'node:buffer';
+
+interface JwtClaimSummary {
+ clientId?: string;
+ exp?: number;
+ iat?: number;
+ sub?: string;
+}
+
+const decodeSegment = (segment: string): Record<string, unknown> | null => {
+ try {
+ const json = Buffer.from(segment, 'base64url').toString('utf8');
+ const parsed = JSON.parse(json);
+ return parsed && typeof parsed === 'object' ? parsed : null;
+ } catch {
+ return null;
+ }
+};
+
+export const readJwtClaims = (token: string): JwtClaimSummary | null => {
+ const parts = token.split('.');
+ if (parts.length !== 3) return null;
+ const payload = decodeSegment(parts[1]);
+ if (!payload) return null;
+ return {
+ clientId: typeof payload.client_id === 'string' ? payload.client_id : undefined,
+ exp: typeof payload.exp === 'number' ? payload.exp : undefined,
+ iat: typeof payload.iat === 'number' ? payload.iat : undefined,
+ sub: typeof payload.sub === 'string' ? payload.sub : undefined,
+ };
+};
+
+export const describeJwtClaims = (token: string | null | undefined, now = Date.now()) => {
+ if (!token) return 'token=none';
+ const claims = readJwtClaims(token);
+ if (!claims) return 'token=opaque';
+
+ const parts: string[] = [];
+ if (claims.sub) parts.push(`sub=${claims.sub.slice(0, 8)}`);
+ if (claims.clientId) parts.push(`client=${claims.clientId}`);
+ if (claims.iat) parts.push(`iat=${new Date(claims.iat * 1000).toISOString()}`);
+ if (claims.exp) {
+ const remaining = Math.round(claims.exp - now / 1000);
+ parts.push(`exp=${new Date(claims.exp * 1000).toISOString()}`);
+ parts.push(remaining < 0 ? `expiredBy=${-remaining}s` : `expiresIn=${remaining}s`);
+ }
+ return parts.length ? `token{${parts.join(' ')}}` : 'token=no-claims';
+};
diff --git a/packages/desktop-bridge/src/index.ts b/packages/desktop-bridge/src/index.ts
index 7134a8169cf..6ed9551f8a6 100644
--- a/packages/desktop-bridge/src/index.ts
+++ b/packages/desktop-bridge/src/index.ts
@@ -37,6 +37,14 @@ export const APP_WINDOW_MIN_SIZE = {
*/
export const AUTH_REQUIRED_HEADER = 'X-Auth-Required';
+/**
+ * Companion to X-Auth-Required: a short machine-readable reason for the 401
+ * (e.g. `jwt_expired`, `jwt_signature`, `user_inactive`, `no_token`) so the
+ * desktop main-process log can record WHY the server rejected the session
+ * without access to server logs.
+ */
+export const AUTH_FAILURE_HEADER = 'X-Auth-Failure';
+
// TRPC error codes (mirrors @trpc/server internal codes)
/**
* TRPC error code for unauthorized requests.
diff --git a/packages/trpc/src/lambda/context.test.ts b/packages/trpc/src/lambda/context.test.ts
index ea85b3e7b83..c649ff84b47 100644
--- a/packages/trpc/src/lambda/context.test.ts
+++ b/packages/trpc/src/lambda/context.test.ts
@@ -1,3 +1,4 @@
+import { AUTH_FAILURE_HEADER } from '@lobechat/desktop-bridge';
import { API_KEY_PREFIX } from '@lobechat/utils/apiKey';
import { NextRequest } from 'next/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -463,4 +464,58 @@ describe('createLambdaContext', () => {
expect(mockValidateOIDCJWT).toHaveBeenCalledWith('oidc-token');
expect(mockGetSession).not.toHaveBeenCalled();
});
+
+ it('records jwt_expired in resHeaders when the OIDC JWT is expired and no session exists', async () => {
+ const cause = Object.assign(new Error('"exp" claim timestamp check failed'), {
+ code: 'ERR_JWT_EXPIRED',
+ });
+ mockValidateOIDCJWT.mockRejectedValueOnce(
+ Object.assign(new Error('JWT token validation failed'), { cause }),
+ );
+ mockGetSession.mockResolvedValueOnce(null);
+
+ const request = new NextRequest('https://example.com/trpc/lambda', {
+ headers: { 'Oidc-Auth': 'stale-token' },
+ });
+
+ const context = await createLambdaContext(request);
+
+ expect(context.userId).toBeUndefined();
+ expect(context.resHeaders?.get(AUTH_FAILURE_HEADER)).toBe('jwt_expired');
+ });
+
+ it('does not record a failure when the session fallback authenticates the user', async () => {
+ mockValidateOIDCJWT.mockRejectedValueOnce(new Error('JWT token validation failed'));
+
+ const request = new NextRequest('https://example.com/trpc/lambda', {
+ headers: { 'Oidc-Auth': 'stale-token' },
+ });
+
+ const context = await createLambdaContext(request);
+
+ expect(context.userId).toBe('session-user');
+ expect(context.resHeaders?.get(AUTH_FAILURE_HEADER)).toBeNull();
+ });
+
+ it('records user_inactive for a banned OIDC user', async () => {
+ mockAssertOIDCUserActive.mockRejectedValueOnce(new Error('OIDC user is no longer active'));
+ mockIsOIDCUserInactiveError.mockReturnValueOnce(true);
+
+ const request = new NextRequest('https://example.com/trpc/lambda', {
+ headers: { 'Oidc-Auth': 'oidc-token' },
+ });
+
+ const context = await createLambdaContext(request);
+
+ expect(context.resHeaders?.get(AUTH_FAILURE_HEADER)).toBe('user_inactive');
+ });
+
+ it('records no_token when neither Oidc-Auth nor a session is present', async () => {
+ mockGetSession.mockResolvedValueOnce(null);
+
+ const context = await createLambdaContext(new NextRequest('https://example.com/trpc/lambda'));
+
+ expect(context.userId).toBeUndefined();
+ expect(context.resHeaders?.get(AUTH_FAILURE_HEADER)).toBe('no_token');
+ });
});
diff --git a/packages/trpc/src/lambda/context.ts b/packages/trpc/src/lambda/context.ts
index 375054d6715..5e52179823b 100644
--- a/packages/trpc/src/lambda/context.ts
+++ b/packages/trpc/src/lambda/context.ts
@@ -17,6 +17,7 @@ import { assertOIDCUserActive, isOIDCUserInactiveError } from '@/libs/oidc-provi
import { validateOIDCJWT } from '@/libs/oidc-provider/jwt';
import { isApiKeyExpired, validateApiKeyFormat } from '@/utils/apiKey';
+import { describeOIDCAuthFailure, setAuthFailureHeader } from '../utils/authFailure';
import { HETERO_OPERATION_JWT_PURPOSE } from '../utils/internalJwt';
// Create context logger namespace
@@ -122,6 +123,7 @@ export interface AuthContext {
*/
export const createContextInner = async (params?: {
apiKeyScopes?: string[] | null;
+ authFailure?: string;
clientMetadata?: ClientMetadata;
clientIp?: string | null;
marketAccessToken?: string;
@@ -136,6 +138,9 @@ export const createContextInner = async (params?: {
}): Promise<AuthContext> => {
log('createContextInner called with params: %O', params);
const responseHeaders = new Headers();
+ if (params?.authFailure && !params.userId) {
+ setAuthFailureHeader(responseHeaders, params.authFailure);
+ }
return {
apiKeyScopes: params?.apiKeyScopes,
@@ -287,12 +292,14 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaC
let userId;
let oidcAuth;
+ let authFailure: string | undefined;
// Prioritize checking for OIDC authentication (both standard Authorization and custom Oidc-Auth headers)
if (authEnv.ENABLE_OIDC) {
log('OIDC enabled, attempting OIDC authentication');
const oidcAuthToken = request.headers.get(LOBE_CHAT_OIDC_AUTH_HEADER);
log('Oidc-Auth header: %s', oidcAuthToken ? 'exists' : 'not found');
+ if (!oidcAuthToken) authFailure = 'no_token';
try {
if (oidcAuthToken) {
@@ -341,6 +348,7 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaC
console.error('OIDC authentication failed for inactive user:', error);
return createContextInner({
...commonContext,
+ authFailure: 'user_inactive',
traceContext,
userId: null,
});
@@ -348,7 +356,8 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaC
// If OIDC authentication fails, log error and continue with other authentication methods
if (oidcAuthToken) {
- log('OIDC authentication failed, error: %O', error);
+ authFailure = describeOIDCAuthFailure(error);
+ log('OIDC authentication failed (%s), error: %O', authFailure, error);
console.error('OIDC authentication failed, trying other methods:', error);
}
}
@@ -370,6 +379,7 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaC
return createContextInner({
...commonContext,
+ authFailure,
traceContext,
userId,
});
@@ -383,5 +393,5 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaC
'All authentication methods attempted, returning final context, userId: %s',
userId || 'not authenticated',
);
- return createContextInner({ ...commonContext, traceContext, userId });
+ return createContextInner({ ...commonContext, authFailure, traceContext, userId });
};
diff --git a/packages/trpc/src/utils/authFailure.test.ts b/packages/trpc/src/utils/authFailure.test.ts
new file mode 100644
index 00000000000..fdb5f8d9431
--- /dev/null
+++ b/packages/trpc/src/utils/authFailure.test.ts
@@ -0,0 +1,47 @@
+import { AUTH_FAILURE_HEADER } from '@lobechat/desktop-bridge';
+import { TRPCError } from '@trpc/server';
+import { describe, expect, it } from 'vitest';
+
+import { describeOIDCAuthFailure, setAuthFailureHeader } from './authFailure';
+
+const joseError = (code: string) => Object.assign(new Error(code), { code });
+
+describe('describeOIDCAuthFailure', () => {
+ it('maps jose codes carried on TRPCError.cause', () => {
+ const wrap = (code: string) =>
+ new TRPCError({ cause: joseError(code), code: 'UNAUTHORIZED', message: 'x' });
+ expect(describeOIDCAuthFailure(wrap('ERR_JWT_EXPIRED'))).toBe('jwt_expired');
+ expect(describeOIDCAuthFailure(wrap('ERR_JWS_SIGNATURE_VERIFICATION_FAILED'))).toBe(
+ 'jwt_signature',
+ );
+ expect(describeOIDCAuthFailure(wrap('ERR_JWS_INVALID'))).toBe('jwt_malformed');
+ });
+
+ it('maps jose codes on a bare error', () => {
+ expect(describeOIDCAuthFailure(joseError('ERR_JWT_EXPIRED'))).toBe('jwt_expired');
+ });
+
+ it('classifies JWKS infrastructure errors and missing sub', () => {
+ expect(describeOIDCAuthFailure(new Error('JWKS_KEY environment variable is not set'))).toBe(
+ 'jwks_error',
+ );
+ expect(
+ describeOIDCAuthFailure(
+ new TRPCError({ code: 'UNAUTHORIZED', message: 'JWT token is missing user ID (sub)' }),
+ ),
+ ).toBe('jwt_no_sub');
+ });
+
+ it('falls back to jwt_invalid', () => {
+ expect(describeOIDCAuthFailure(new Error('boom'))).toBe('jwt_invalid');
+ expect(describeOIDCAuthFailure('string')).toBe('jwt_invalid');
+ });
+});
+
+describe('setAuthFailureHeader', () => {
+ it('writes the header', () => {
+ const headers = new Headers();
+ setAuthFailureHeader(headers, 'jwt_expired');
+ expect(headers.get(AUTH_FAILURE_HEADER)).toBe('jwt_expired');
+ });
+});
diff --git a/packages/trpc/src/utils/authFailure.ts b/packages/trpc/src/utils/authFailure.ts
new file mode 100644
index 00000000000..7f56339d41c
--- /dev/null
+++ b/packages/trpc/src/utils/authFailure.ts
@@ -0,0 +1,31 @@
+import { AUTH_FAILURE_HEADER } from '@lobechat/desktop-bridge';
+
+const JOSE_CODE_TO_FAILURE: Record<string, string> = {
+ ERR_JWKS_NO_MATCHING_KEY: 'jwt_signature',
+ ERR_JWS_INVALID: 'jwt_malformed',
+ ERR_JWS_SIGNATURE_VERIFICATION_FAILED: 'jwt_signature',
+ ERR_JWT_CLAIM_VALIDATION_FAILED: 'jwt_claims',
+ ERR_JWT_EXPIRED: 'jwt_expired',
+ ERR_JWT_INVALID: 'jwt_malformed',
+};
+
+const readCode = (value: unknown): string | undefined => {
+ if (!value || typeof value !== 'object') return undefined;
+ const code = (value as { code?: unknown }).code;
+ return typeof code === 'string' ? code : undefined;
+};
+
+export const describeOIDCAuthFailure = (error: unknown): string => {
+ const cause = (error as { cause?: unknown } | undefined)?.cause;
+ const code = readCode(cause) ?? readCode(error);
+ if (code && JOSE_CODE_TO_FAILURE[code]) return JOSE_CODE_TO_FAILURE[code];
+
+ const message = error instanceof Error ? error.message : String(error);
+ if (/JWKS/i.test(message)) return 'jwks_error';
+ if (/missing user ID/i.test(message)) return 'jwt_no_sub';
+ return 'jwt_invalid';
+};
+
+export const setAuthFailureHeader = (headers: Headers, failure: string) => {
+ headers.set(AUTH_FAILURE_HEADER, failure);
+};
diff --git a/packages/trpc/src/utils/responseMeta.test.ts b/packages/trpc/src/utils/responseMeta.test.ts
index 67634e87f53..9db7d1512c6 100644
--- a/packages/trpc/src/utils/responseMeta.test.ts
+++ b/packages/trpc/src/utils/responseMeta.test.ts
@@ -1,4 +1,5 @@
import {
+ AUTH_FAILURE_HEADER,
AUTH_REQUIRED_HEADER,
MARKET_AUTH_REQUIRED_MESSAGE,
TRPC_ERROR_CODE_UNAUTHORIZED,
@@ -111,4 +112,23 @@ describe('createResponseMeta', () => {
expect(result.headers).toBeInstanceOf(Headers);
expect(result.headers?.get(AUTH_REQUIRED_HEADER)).toBe('true');
});
+
+ it('keeps AUTH_FAILURE_HEADER next to an UNAUTHORIZED error', () => {
+ const resHeaders = new Headers({ [AUTH_FAILURE_HEADER]: 'jwt_expired' });
+ const result = createResponseMeta({
+ ctx: { resHeaders },
+ errors: [new TRPCError({ code: TRPC_ERROR_CODE_UNAUTHORIZED })],
+ });
+
+ expect(result.headers?.get(AUTH_REQUIRED_HEADER)).toBe('true');
+ expect(result.headers?.get(AUTH_FAILURE_HEADER)).toBe('jwt_expired');
+ });
+
+ it('drops AUTH_FAILURE_HEADER when the response is not an UNAUTHORIZED error', () => {
+ const resHeaders = new Headers({ [AUTH_FAILURE_HEADER]: 'no_token', 'X-Custom': 'v' });
+ const result = createResponseMeta({ ctx: { resHeaders }, errors: [] });
+
+ expect(result.headers?.get(AUTH_FAILURE_HEADER)).toBeNull();
+ expect(result.headers?.get('X-Custom')).toBe('v');
+ });
});
diff --git a/packages/trpc/src/utils/responseMeta.ts b/packages/trpc/src/utils/responseMeta.ts
index 7b8d4d60bb6..b016dfc449c 100644
--- a/packages/trpc/src/utils/responseMeta.ts
+++ b/packages/trpc/src/utils/responseMeta.ts
@@ -1,4 +1,5 @@
import {
+ AUTH_FAILURE_HEADER,
AUTH_REQUIRED_HEADER,
MARKET_AUTH_REQUIRED_MESSAGE,
TRPC_ERROR_CODE_UNAUTHORIZED,
@@ -48,6 +49,10 @@ export function createResponseMeta({ ctx, errors }: ResponseMetaParams): {
);
if (hasUnauthorizedError) {
headers.set(AUTH_REQUIRED_HEADER, 'true');
+ } else {
+ // The failure reason is only meaningful next to a session 401; a public
+ // procedure served without a user must not carry it.
+ headers.delete(AUTH_FAILURE_HEADER);
}
// Only return headers if there's content or auth error