π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(oidc): stop a grant's deadline from ending an active session (#19806)
Arvin Xu5357476bcf7b
diff --git a/apps/cli/src/api/client.test.ts b/apps/cli/src/api/client.test.tsindex 541006f21e4..f9d789c0728 100644--- a/apps/cli/src/api/client.test.ts+++ b/apps/cli/src/api/client.test.ts@@ -1,5 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type * as RefreshModule from '../auth/refresh';+const mockCreateTRPCClient = vi.hoisted(() => vi.fn(() => ({ marker: 'client' })));const mockHttpLink = vi.hoisted(() => vi.fn((opts: unknown) => opts));@@ -8,7 +10,8 @@ vi.mock('@trpc/client', () => ({httpLink: mockHttpLink,}));-vi.mock('../auth/refresh', () => ({+vi.mock('../auth/refresh', async (importOriginal) => ({+ ...(await importOriginal<typeof RefreshModule>()),getValidToken: vi.fn(),}));diff --git a/apps/cli/src/api/client.ts b/apps/cli/src/api/client.tsindex f7214e8b96a..cfe4b8021ca 100644--- a/apps/cli/src/api/client.ts+++ b/apps/cli/src/api/client.ts@@ -4,7 +4,7 @@ import superjson from 'superjson';import type { LambdaRouter } from '@/server/routers/lambda';import type { ToolsRouter } from '@/server/routers/tools';-import { getValidToken } from '../auth/refresh';+import { describeTokenLookup, getValidToken } from '../auth/refresh';import { pickAuthSource } from '../auth/source';import { CLI_API_KEY_ENV } from '../constants/auth';import { CLI_PRIMARY_BIN } from '../constants/identity';@@ -50,9 +50,12 @@ async function getAuthAndServer(): Promise<{}const result = await getValidToken();- if (!result) {+ if (result.status !== 'ok') {+ const report = describeTokenLookup(result);log.error(- `No authentication found. Run '${CLI_PRIMARY_BIN} login' (or 'npx -y ${cliPackageName} login') first, or set ${CLI_API_KEY_ENV}.`,+ report+ ? `${report.detail} ${report.fix}`+ : `No authentication found. Run '${CLI_PRIMARY_BIN} login' (or 'npx -y ${cliPackageName} login') first, or set ${CLI_API_KEY_ENV}.`,);process.exit(1);}diff --git a/apps/cli/src/api/http.test.ts b/apps/cli/src/api/http.test.tsindex 51603fea3f0..48ad0f93a8e 100644--- a/apps/cli/src/api/http.test.ts+++ b/apps/cli/src/api/http.test.ts@@ -1,9 +1,12 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type * as RefreshModule from '../auth/refresh';+const mockGetValidToken = vi.hoisted(() => vi.fn());const mockResolveServerUrl = vi.hoisted(() => vi.fn(() => 'https://app.lobehub.com'));-vi.mock('../auth/refresh', () => ({+vi.mock('../auth/refresh', async (importOriginal) => ({+ ...(await importOriginal<typeof RefreshModule>()),getValidToken: mockGetValidToken,}));@@ -53,6 +56,7 @@ describe('api/http auth helpers', () => {process.env.LOBEHUB_WORKSPACE_ID = 'workspace-1';mockGetValidToken.mockResolvedValue({credentials: { accessToken: 'stored-jwt' },+ status: 'ok',});const { getAuthInfo } = await import('./http');diff --git a/apps/cli/src/api/http.ts b/apps/cli/src/api/http.tsindex 538536ea74b..f9677af45ab 100644--- a/apps/cli/src/api/http.ts+++ b/apps/cli/src/api/http.ts@@ -1,4 +1,4 @@-import { getValidToken } from '../auth/refresh';+import { describeTokenLookup, getValidToken } from '../auth/refresh';import { CLI_API_KEY_ENV, readCliApiKeyEnv } from '../constants/auth';import { CLI_PRIMARY_BIN } from '../constants/identity';import { resolveServerUrl } from '../settings';@@ -30,7 +30,7 @@ export async function getAuthInfo(workspaceId?: string): Promise<AuthInfo> {}const result = await getValidToken();- if (!result) {+ if (result.status !== 'ok') {if (readCliApiKeyEnv()) {log.error(`API key auth from ${CLI_API_KEY_ENV} is not supported for /webapi/* routes. Run OIDC login instead.`,@@ -38,11 +38,16 @@ export async function getAuthInfo(workspaceId?: string): Promise<AuthInfo> {process.exit(1);}- log.error(`No authentication found. Run '${CLI_PRIMARY_BIN} login' first.`);+ const report = describeTokenLookup(result);+ log.error(+ report+ ? `${report.detail} ${report.fix}`+ : `No authentication found. Run '${CLI_PRIMARY_BIN} login' first.`,+ );process.exit(1);}- const accessToken = result!.credentials.accessToken;+ const accessToken = result.credentials.accessToken;return {accessToken,@@ -99,9 +104,12 @@ export async function getAgentStreamAuthInfo(workspaceId?: string): Promise<Agen}const result = await getValidToken();- if (!result) {+ if (result.status !== 'ok') {+ const report = describeTokenLookup(result);log.error(- `No authentication found. Run '${CLI_PRIMARY_BIN} login' first, or set ${CLI_API_KEY_ENV}.`,+ report+ ? `${report.detail} ${report.fix}`+ : `No authentication found. Run '${CLI_PRIMARY_BIN} login' first, or set ${CLI_API_KEY_ENV}.`,);process.exit(1);diff --git a/apps/cli/src/auth/refresh.test.ts b/apps/cli/src/auth/refresh.test.tsindex 02c0d60c4d1..4572d8e7081 100644--- a/apps/cli/src/auth/refresh.test.ts+++ b/apps/cli/src/auth/refresh.test.ts@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { resolveServerUrl } from '../settings';import type { StoredCredentials } from './credentials';import { loadCredentials, saveCredentials } from './credentials';-import { getValidToken } from './refresh';+import { describeTokenLookup, getValidToken } from './refresh';vi.mock('./credentials', () => ({loadCredentials: vi.fn(),@@ -13,6 +13,12 @@ vi.mock('../settings', () => ({resolveServerUrl: vi.fn().mockReturnValue('https://app.lobehub.com'),}));+const expiredCredentials = (refreshToken?: string): StoredCredentials => ({+ accessToken: 'expired-token',+ expiresAt: Math.floor(Date.now() / 1000) - 100,+ refreshToken,+});+describe('getValidToken', () => {beforeEach(() => {vi.mocked(loadCredentials).mockClear();@@ -26,12 +32,10 @@ describe('getValidToken', () => {vi.unstubAllGlobals();});- it('should return null when no credentials stored', async () => {+ it('should report no login when no credentials stored', async () => {vi.mocked(loadCredentials).mockReturnValue(null);- const result = await getValidToken();-- expect(result).toBeNull();+ await expect(getValidToken()).resolves.toEqual({ status: 'no-login' });});it('should return credentials when token is still valid', async () => {@@ -44,42 +48,26 @@ describe('getValidToken', () => {const result = await getValidToken();- expect(result).toEqual({ credentials: creds });+ expect(result).toEqual({ credentials: creds, status: 'ok' });expect(fetch).not.toHaveBeenCalled();});- it('should return credentials when no expiresAt is set', async () => {- const creds: StoredCredentials = {- accessToken: 'valid-token',- };- vi.mocked(loadCredentials).mockReturnValue(creds);-- const result = await getValidToken();+ it('should report no login when no expiresAt and nothing to refresh with', async () => {+ vi.mocked(loadCredentials).mockReturnValue({ accessToken: 'valid-token' });- // expiresAt is undefined, so Date.now()/1000 < undefined - 60 is false (NaN comparison)- // This means it will try to refresh, but there's no refreshToken- expect(result).toBeNull();+ // expiresAt is undefined, so the validity check cannot pass and a refresh is attempted,+ // but there is no refresh token to attempt it with.+ await expect(getValidToken()).resolves.toEqual({ status: 'no-login' });});- it('should return null when token expired and no refresh token', async () => {- const creds: StoredCredentials = {- accessToken: 'expired-token',- expiresAt: Math.floor(Date.now() / 1000) - 100, // expired- };- vi.mocked(loadCredentials).mockReturnValue(creds);-- const result = await getValidToken();+ it('should report no login when token expired and no refresh token', async () => {+ vi.mocked(loadCredentials).mockReturnValue(expiredCredentials());- expect(result).toBeNull();+ await expect(getValidToken()).resolves.toEqual({ status: 'no-login' });});it('should refresh and save updated credentials when token is expired', async () => {- const creds: StoredCredentials = {- accessToken: 'expired-token',- expiresAt: Math.floor(Date.now() / 1000) - 100,- refreshToken: 'valid-refresh-token',- };- vi.mocked(loadCredentials).mockReturnValue(creds);+ vi.mocked(loadCredentials).mockReturnValue(expiredCredentials('valid-refresh-token'));vi.mocked(fetch).mockResolvedValue({json: vi.fn().mockResolvedValue({@@ -93,21 +81,17 @@ describe('getValidToken', () => {const result = await getValidToken();- expect(result).not.toBeNull();- expect(result!.credentials.accessToken).toBe('new-access-token');- expect(result!.credentials.refreshToken).toBe('new-refresh-token');+ expect(result.status).toBe('ok');+ expect(result).toMatchObject({+ credentials: { accessToken: 'new-access-token', refreshToken: 'new-refresh-token' },+ });expect(saveCredentials).toHaveBeenCalledWith(expect.objectContaining({ accessToken: 'new-access-token' }),);});it('should keep old refresh token if new one is not returned', async () => {- const creds: StoredCredentials = {- accessToken: 'expired-token',- expiresAt: Math.floor(Date.now() / 1000) - 100,- refreshToken: 'old-refresh-token',- };- vi.mocked(loadCredentials).mockReturnValue(creds);+ vi.mocked(loadCredentials).mockReturnValue(expiredCredentials('old-refresh-token'));vi.mocked(fetch).mockResolvedValue({json: vi.fn().mockResolvedValue({@@ -119,87 +103,135 @@ describe('getValidToken', () => {const result = await getValidToken();- expect(result!.credentials.refreshToken).toBe('old-refresh-token');- expect(result!.credentials.expiresAt).toBeUndefined();- });-- it('should return null when refresh request fails (non-ok)', async () => {- const creds: StoredCredentials = {- accessToken: 'expired-token',- expiresAt: Math.floor(Date.now() / 1000) - 100,- refreshToken: 'valid-refresh-token',- };- vi.mocked(loadCredentials).mockReturnValue(creds);-- vi.mocked(fetch).mockResolvedValue({- json: vi.fn().mockResolvedValue({}),- ok: false,- status: 401,- } as any);-- const result = await getValidToken();-- expect(result).toBeNull();- });-- it('should return null when refresh response has error field', async () => {- const creds: StoredCredentials = {- accessToken: 'expired-token',- expiresAt: Math.floor(Date.now() / 1000) - 100,- refreshToken: 'valid-refresh-token',- };- vi.mocked(loadCredentials).mockReturnValue(creds);-- vi.mocked(fetch).mockResolvedValue({- json: vi.fn().mockResolvedValue({ error: 'invalid_grant' }),- ok: true,- } as any);-- const result = await getValidToken();-- expect(result).toBeNull();+ expect(result).toMatchObject({+ credentials: { expiresAt: undefined, refreshToken: 'old-refresh-token' },+ });});- it('should return null when refresh response has no access_token', async () => {- const creds: StoredCredentials = {- accessToken: 'expired-token',- expiresAt: Math.floor(Date.now() / 1000) - 100,- refreshToken: 'valid-refresh-token',- };- vi.mocked(loadCredentials).mockReturnValue(creds);-- vi.mocked(fetch).mockResolvedValue({- json: vi.fn().mockResolvedValue({ token_type: 'Bearer' }),- ok: true,- } as any);-- const result = await getValidToken();-- expect(result).toBeNull();- });-- it('should return null when network error occurs during refresh', async () => {- const creds: StoredCredentials = {- accessToken: 'expired-token',- expiresAt: Math.floor(Date.now() / 1000) - 100,- refreshToken: 'valid-refresh-token',- };- vi.mocked(loadCredentials).mockReturnValue(creds);-- vi.mocked(fetch).mockRejectedValue(new Error('network error'));-- const result = await getValidToken();-- expect(result).toBeNull();+ /**+ * The regression this classification exists for: a refresh that never got an answer used to be+ * indistinguishable from having no login at all, so every caller told the user to run `login`+ * and re-authenticate over what was usually a passing blip.+ */+ describe('separates a refused token from an unanswered request', () => {+ beforeEach(() => {+ vi.mocked(loadCredentials).mockReturnValue(expiredCredentials('stored-refresh-token'));+ });++ it('treats invalid_grant as a spent login', async () => {+ vi.mocked(fetch).mockResolvedValue({+ json: vi.fn().mockResolvedValue({+ error: 'invalid_grant',+ error_description: 'grant request is invalid',+ }),+ ok: false,+ status: 400,+ } as any);++ await expect(getValidToken()).resolves.toEqual({+ detail: 'invalid_grant: grant request is invalid',+ status: 'spent',+ });+ expect(saveCredentials).not.toHaveBeenCalled();+ });++ it('treats a gateway failure as unavailable', async () => {+ vi.mocked(fetch).mockResolvedValue({+ json: vi.fn().mockRejectedValue(new SyntaxError('Unexpected token <')),+ ok: false,+ status: 502,+ } as any);++ await expect(getValidToken()).resolves.toEqual({+ detail: 'HTTP 502',+ status: 'unavailable',+ });+ });++ it('treats a request timeout as unavailable', async () => {+ vi.mocked(fetch).mockResolvedValue({+ json: vi.fn().mockResolvedValue({}),+ ok: false,+ status: 408,+ } as any);++ await expect(getValidToken()).resolves.toMatchObject({ status: 'unavailable' });+ });++ it('treats a network error as unavailable and keeps the reason', async () => {+ vi.mocked(fetch).mockRejectedValue(new Error('fetch failed'));++ await expect(getValidToken()).resolves.toEqual({+ detail: 'fetch failed',+ status: 'unavailable',+ });+ });++ it('treats an OAuth error in a 2xx body as a spent login', async () => {+ vi.mocked(fetch).mockResolvedValue({+ json: vi.fn().mockResolvedValue({ error: 'invalid_grant' }),+ ok: true,+ } as any);++ await expect(getValidToken()).resolves.toEqual({+ detail: 'invalid_grant',+ status: 'spent',+ });+ });++ it('treats a 2xx without an access token as unavailable', async () => {+ vi.mocked(fetch).mockResolvedValue({+ json: vi.fn().mockResolvedValue({ token_type: 'Bearer' }),+ ok: true,+ } as any);++ await expect(getValidToken()).resolves.toMatchObject({ status: 'unavailable' });+ });++ it('treats client-auth failure as a refusal, not a spent login', async () => {+ vi.mocked(fetch).mockResolvedValue({+ json: vi.fn().mockResolvedValue({ error: 'invalid_client' }),+ ok: false,+ status: 401,+ } as any);++ await expect(getValidToken()).resolves.toEqual({+ detail: 'invalid_client',+ status: 'refused',+ });+ });++ /**+ * The shape that made this distinction worth having: a WAF in front of the token endpoint+ * answers 403 with no OAuth body at all. Calling that a spent login walks the user through a+ * pointless re-authentication straight back into the same wall.+ */+ it('treats a proxy 403 as a refusal, not a spent login', async () => {+ vi.mocked(fetch).mockResolvedValue({+ json: vi.fn().mockRejectedValue(new SyntaxError('Unexpected token F')),+ ok: false,+ status: 403,+ } as any);++ await expect(getValidToken()).resolves.toEqual({+ detail: 'HTTP 403',+ status: 'refused',+ });+ });++ it('treats a wrong server URL (404) as a refusal', async () => {+ vi.mocked(fetch).mockResolvedValue({+ json: vi.fn().mockRejectedValue(new SyntaxError('Unexpected token <')),+ ok: false,+ status: 404,+ } as any);++ await expect(getValidToken()).resolves.toMatchObject({ status: 'refused' });+ });});it('should send correct request to refresh endpoint', async () => {- const creds: StoredCredentials = {- accessToken: 'expired-token',- expiresAt: Math.floor(Date.now() / 1000) - 100,- refreshToken: 'my-refresh-token',- };- vi.mocked(loadCredentials).mockReturnValue(creds);+ vi.mocked(loadCredentials).mockReturnValue(expiredCredentials('my-refresh-token'));vi.mocked(resolveServerUrl).mockReturnValueOnce('https://my-server.com');vi.mocked(fetch).mockResolvedValue({@@ -226,3 +258,34 @@ describe('getValidToken', () => {expect(body.get('client_id')).toBe('lobehub-cli');});});++describe('describeTokenLookup', () => {+ it('says the stored login survived when the server never answered', () => {+ const report = describeTokenLookup({ detail: 'fetch failed', status: 'unavailable' });++ expect(report?.detail).toContain('fetch failed');+ expect(report?.detail).toContain('untouched');+ // The whole point: it must not send the user off to re-authenticate.+ expect(report?.fix).not.toMatch(/run .*login/i);+ expect(report?.fix).toMatch(/retry/i);+ });++ /** Spent is the one status where signing in again is the remedy, so it has to say so. */+ it('tells the user to sign in again when the stored login is spent', () => {+ const report = describeTokenLookup({ detail: 'invalid_grant', status: 'spent' });++ expect(report?.detail).toContain('invalid_grant');+ expect(report?.fix).toContain('login');+ });++ it('does not send the user to sign in again over a refusal the credential did not cause', () => {+ const report = describeTokenLookup({ detail: 'HTTP 403', status: 'refused' });++ expect(report?.detail).toContain('HTTP 403');+ expect(report?.fix).toContain('signing in again will not change the answer');+ });++ it('leaves the caller its own wording when there is nothing to diagnose', () => {+ expect(describeTokenLookup({ status: 'no-login' })).toBeUndefined();+ });+});diff --git a/apps/cli/src/auth/refresh.ts b/apps/cli/src/auth/refresh.tsindex 882599d8d87..5621371cdf9 100644--- a/apps/cli/src/auth/refresh.ts+++ b/apps/cli/src/auth/refresh.ts@@ -1,40 +1,117 @@+import { CLI_PRIMARY_BIN } from '../constants/identity';import { resolveServerUrl } from '../settings';import { loadCredentials, saveCredentials, type StoredCredentials } from './credentials';const CLIENT_ID = 'lobehub-cli';+/**+ * Why a refresh did not produce a token.+ *+ * Every failure used to be the same `null`, so a timeout or a 502 on the way to the token endpoint+ * was reported as "No authentication found. Run `lh login`" β sending the user to re-authenticate+ * over a network blip with a perfectly good refresh token still on disk. The three failure shapes+ * below each have a different remedy, and telling them apart is the whole point: only `spent`+ * means signing in again achieves anything.+ */+export type TokenLookup =+ | { credentials: StoredCredentials; status: 'ok' }+ /** Nothing on disk to work with: no credentials file, or no refresh token to spend. */+ | { status: 'no-login' }+ /** The server proved the stored refresh token is done. Signing in again is the fix. */+ | { detail: string; status: 'spent' }+ /**+ * The server said no for a reason the stored credential is not responsible for β a client+ * misconfiguration, a wrong server URL, a proxy or WAF in front of the endpoint. Neither+ * retrying nor signing in again changes the answer.+ */+ | { detail: string; status: 'refused' }+ /** No usable answer came back. The stored credentials are untouched, so retrying is the fix. */+ | { detail: string; status: 'unavailable' };++/** HTTP statuses that say "ask again later" rather than "this token is dead". */+const TRANSIENT_STATUSES = new Set([408, 425, 429]);++/**+ * The one OAuth error that proves the stored refresh token itself is finished (RFC 6749 Β§5.2).+ * Its neighbours β `invalid_client`, `invalid_request`, `unauthorized_client` β describe how the+ * request was built, not whether the credential still lives, so re-authenticating over them just+ * walks the user into the same wall.+ */+const CREDENTIAL_SPENT_ERROR = 'invalid_grant';+/*** Get a valid access token, refreshing if expired.- * Returns null if no credentials or refresh fails.*/-export async function getValidToken(- bufferSeconds = 60,-): Promise<{ credentials: StoredCredentials } | null> {+export async function getValidToken(bufferSeconds = 60): Promise<TokenLookup> {const credentials = loadCredentials();- if (!credentials) return null;+ if (!credentials) return { status: 'no-login' };// Check if token is still valid (with configurable buffer)if (credentials.expiresAt && Date.now() / 1000 < credentials.expiresAt - bufferSeconds) {- return { credentials };+ return { credentials, status: 'ok' };}// Token expired β try refresh- if (!credentials.refreshToken) return null;+ if (!credentials.refreshToken) return { status: 'no-login' };const serverUrl = resolveServerUrl();const refreshed = await refreshAccessToken(serverUrl, credentials.refreshToken);- if (!refreshed) return null;+ if (refreshed.status !== 'ok') return refreshed;const updated: StoredCredentials = {- accessToken: refreshed.access_token,- expiresAt: refreshed.expires_in- ? Math.floor(Date.now() / 1000) + refreshed.expires_in+ accessToken: refreshed.token.access_token,+ expiresAt: refreshed.token.expires_in+ ? Math.floor(Date.now() / 1000) + refreshed.token.expires_in: undefined,- refreshToken: refreshed.refresh_token || credentials.refreshToken,+ refreshToken: refreshed.token.refresh_token || credentials.refreshToken,};saveCredentials(updated);- return { credentials: updated };+ return { credentials: updated, status: 'ok' };+}++/**+ * What went wrong, and what the user can do about it.+ *+ * The two are separate fields because they render in different places: a command prints them as+ * one line, while `lh doctor` has its own `fix` slot and would otherwise repeat the remedy right+ * next to itself β or worse, print its own generic one contradicting the diagnosis above it.+ */+export interface TokenLookupReport {+ /** What the server said, in the user's terms. */+ detail: string;+ /** The action that actually changes the outcome. */+ fix: string;+}++/**+ * How to explain a lookup that produced no token, or `undefined` when there is nothing to+ * diagnose and the caller's own "log in first" message fits.+ */+export function describeTokenLookup(lookup: TokenLookup): TokenLookupReport | undefined {+ switch (lookup.status) {+ case 'spent': {+ return {+ detail: `The stored login is no longer valid (${lookup.detail}).`,+ fix: `Run '${CLI_PRIMARY_BIN} login' again.`,+ };+ }+ case 'refused': {+ return {+ detail: `The server refused the refresh request: ${lookup.detail}. The stored login is intact, so the credential is not what it is objecting to.`,+ fix: 'Check the server URL and anything sitting in front of it β signing in again will not change the answer.',+ };+ }+ case 'unavailable': {+ return {+ detail: `Could not reach the server to refresh the access token: ${lookup.detail}. The stored login is untouched, so this is the network or the server rather than a signed-out session.`,+ fix: 'Retry in a moment; the stored login does not need renewing.',+ };+ }+ default: {+ return undefined;+ }+ }}interface TokenResponse {@@ -44,12 +121,17 @@ interface TokenResponse {token_type: string;}-async function refreshAccessToken(- serverUrl: string,- refreshToken: string,-): Promise<TokenResponse | null> {+type RefreshResult =+ | { status: 'ok'; token: TokenResponse }+ | { detail: string; status: 'refused' }+ | { detail: string; status: 'spent' }+ | { detail: string; status: 'unavailable' };++async function refreshAccessToken(serverUrl: string, refreshToken: string): Promise<RefreshResult> {+ let res: Response;+try {- const res = await fetch(`${serverUrl}/oidc/token`, {+ res = await fetch(`${serverUrl}/oidc/token`, {body: new URLSearchParams({client_id: CLIENT_ID,grant_type: 'refresh_token',@@ -58,13 +140,44 @@ async function refreshAccessToken(headers: { 'Content-Type': 'application/x-www-form-urlencoded' },method: 'POST',});+ } catch (error) {+ return {+ detail: error instanceof Error ? error.message : String(error),+ status: 'unavailable',+ };+ }- const body = (await res.json()) as TokenResponse & { error?: string };+ // A proxy or gateway in front of the token endpoint answers with HTML, not JSON.+ const body = (await res.json().catch(() => undefined)) as+ (TokenResponse & { error?: string; error_description?: string }) | undefined;- if (!res.ok || body.error || !body.access_token) return null;+ if (!res.ok) {+ const detail = body?.error+ ? `${body.error}${body.error_description ? `: ${body.error_description}` : ''}`+ : `HTTP ${res.status}`;- return body;- } catch {- return null;+ if (res.status >= 500 || TRANSIENT_STATUSES.has(res.status)) {+ return { detail, status: 'unavailable' };+ }++ // The status code alone cannot tell these apart: a 400 carrying `invalid_grant` is a spent+ // token, while a 400 carrying `invalid_request`, a 401 from client auth, a WAF's 403 or a+ // 404 from the wrong server URL all leave the stored credential untouched.+ return body?.error === CREDENTIAL_SPENT_ERROR+ ? { detail, status: 'spent' }+ : { detail, status: 'refused' };+ }++ if (body?.error) {+ return body.error === CREDENTIAL_SPENT_ERROR+ ? { detail: body.error, status: 'spent' }+ : { detail: body.error, status: 'refused' };}++ // A 2xx with nothing usable in it is the server misbehaving, so it may well answer next time.+ if (!body?.access_token) {+ return { detail: 'the response carried no access token', status: 'unavailable' };+ }++ return { status: 'ok', token: body };}diff --git a/apps/cli/src/auth/resolveToken.test.ts b/apps/cli/src/auth/resolveToken.test.tsindex bd637109bc2..d178058f637 100644--- a/apps/cli/src/auth/resolveToken.test.ts+++ b/apps/cli/src/auth/resolveToken.test.ts@@ -1,13 +1,16 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { log } from '../utils/logger';import { getUserIdFromApiKey } from './apiKey';+import type * as RefreshModule from './refresh';import { getValidToken } from './refresh';import { resolveToken } from './resolveToken';vi.mock('./apiKey', () => ({getUserIdFromApiKey: vi.fn(),}));-vi.mock('./refresh', () => ({+vi.mock('./refresh', async (importOriginal) => ({+ ...(await importOriginal<typeof RefreshModule>()),getValidToken: vi.fn(),}));vi.mock('../settings', () => ({@@ -133,6 +136,7 @@ describe('resolveToken', () => {credentials: {accessToken: token,},+ status: 'ok',});const result = await resolveToken({});@@ -154,6 +158,7 @@ describe('resolveToken', () => {credentials: {accessToken: token,},+ status: 'ok',});await expect(resolveToken({})).rejects.toThrow('process.exit');@@ -161,10 +166,30 @@ describe('resolveToken', () => {});it('should exit when no stored credentials', async () => {- vi.mocked(getValidToken).mockResolvedValue(null);+ vi.mocked(getValidToken).mockResolvedValue({ status: 'no-login' });await expect(resolveToken({})).rejects.toThrow('process.exit');expect(exitSpy).toHaveBeenCalledWith(1);});++ /**+ * An unanswered refresh must not be dressed up as a missing login: the stored credentials are+ * still good, and telling the user to authenticate again is how a network blip turned into a+ * re-login.+ */+ it('should say the login survived when the refresh went unanswered', async () => {+ vi.mocked(getValidToken).mockResolvedValue({+ detail: 'fetch failed',+ status: 'unavailable',+ });+ const logError = vi.spyOn(log, 'error').mockImplementation(() => {});++ await expect(resolveToken({})).rejects.toThrow('process.exit');+ expect(logError).toHaveBeenCalledWith(expect.stringContaining('fetch failed'));+ expect(logError).toHaveBeenCalledWith(expect.stringContaining('Retry in a moment'));+ expect(logError).not.toHaveBeenCalledWith(expect.stringContaining('No authentication found'));++ logError.mockRestore();+ });});});diff --git a/apps/cli/src/auth/resolveToken.ts b/apps/cli/src/auth/resolveToken.tsindex a105f380e28..22bcce58962 100644--- a/apps/cli/src/auth/resolveToken.ts+++ b/apps/cli/src/auth/resolveToken.ts@@ -3,7 +3,7 @@ import { CLI_PRIMARY_BIN } from '../constants/identity';import { resolveServerUrl } from '../settings';import { log } from '../utils/logger';import { getUserIdFromApiKey } from './apiKey';-import { getValidToken } from './refresh';+import { describeTokenLookup, getValidToken } from './refresh';import { pickAuthSource } from './source';interface ResolveTokenOptions {@@ -92,7 +92,7 @@ export async function resolveToken(options: ResolveTokenOptions): Promise<Resolv// Stored credentials, refreshed when the access token is close to expiry.const result = await getValidToken();- if (result) {+ if (result.status === 'ok') {log.debug('Using stored credentials');const { credentials } = result;const serverUrl = resolveServerUrl();@@ -106,8 +106,11 @@ export async function resolveToken(options: ResolveTokenOptions): Promise<Resolvreturn { serverUrl, token: credentials.accessToken, tokenType: 'jwt', userId };}+ const report = describeTokenLookup(result);log.error(- `No authentication found. Run '${CLI_PRIMARY_BIN} login' first, or set ${CLI_API_KEY_ENV}, or provide --token.`,+ report+ ? `${report.detail} ${report.fix}`+ : `No authentication found. Run '${CLI_PRIMARY_BIN} login' first, or set ${CLI_API_KEY_ENV}, or provide --token.`,);process.exit(1);}diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.tsindex e8419111051..09b574cb720 100644--- a/apps/cli/src/commands/connect.test.ts+++ b/apps/cli/src/commands/connect.test.ts@@ -2,6 +2,7 @@ import { GatewayClient } from '@lobechat/device-gateway-client';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type * as RefreshModule from '../auth/refresh';import { resolveToken } from '../auth/resolveToken';import { removeStatus, spawnDaemon, stopDaemon, writeStatus } from '../daemon/manager';import type * as DeviceRegister from '../device/register';@@ -18,9 +19,11 @@ vi.mock('../device/register', async (importOriginal) => {return { ...actual, registerDevice: registerDeviceMock };});-vi.mock('../auth/refresh', () => ({+vi.mock('../auth/refresh', async (importOriginal) => ({+ ...(await importOriginal<typeof RefreshModule>()),getValidToken: vi.fn().mockResolvedValue({credentials: { accessToken: 'test-token', expiresAt: undefined, refreshToken: 'test-refresh' },+ status: 'ok',}),}));vi.mock('../auth/resolveToken', () => ({diff --git a/apps/cli/src/doctor/checks/credentials.test.ts b/apps/cli/src/doctor/checks/credentials.test.tsindex b3862c622f2..84a6f0dd183 100644--- a/apps/cli/src/doctor/checks/credentials.test.ts+++ b/apps/cli/src/doctor/checks/credentials.test.ts@@ -63,6 +63,27 @@ describe('credentials.validity', () => {expect(outcome.fix).toContain('LOBEHUB_CLI_API_KEY');});+ /**+ * The probe knows a refresh timed out and says so; the check used to print its own generic+ * "log in again" underneath, so doctor gave two contradictory instructions at once.+ */+ it("keeps the probe's own remedy instead of prescribing a fresh login", async () => {+ credential.value = {+ error:+ 'Could not reach the server to refresh the access token: fetch failed. The stored login is untouched, so this is the network or the server rather than a signed-out session.',+ fix: 'Retry in a moment; the stored login does not need renewing.',+ kind: 'stored',+ origin: 'stored login',+ tokenType: 'jwt',+ };++ const outcome = await runCheck(credentialChecks, 'credentials.validity');++ expect(outcome.status).toBe('fail');+ expect(outcome.fix).toContain('Retry in a moment');+ expect(outcome.fix).not.toMatch(/run .*login/i);+ });+it('fails an expired token that could not refresh', async () => {credential.value = {expiresAt: Math.floor(Date.now() / 1000) - 600,diff --git a/apps/cli/src/doctor/checks/credentials.ts b/apps/cli/src/doctor/checks/credentials.tsindex 8695f09dd38..3057a0b4af2 100644--- a/apps/cli/src/doctor/checks/credentials.ts+++ b/apps/cli/src/doctor/checks/credentials.ts@@ -71,12 +71,17 @@ const credentialValidity: DoctorCheck = {if (credential.error)return {- detail: `${credential.origin} cannot be used: ${credential.error}.`,+ // The probe's reasons are whole sentences, so the trailing period has to give way rather+ // than double up behind them.+ detail: `${credential.origin} cannot be used: ${credential.error.replace(/\.$/, '')}.`,evidence,+ // The probe's own remedy wins: a refresh that never got an answer needs a retry, and+ // printing the generic "log in again" under that diagnosis contradicts it.fix:- credential.kind === 'env-api-key'+ credential.fix ??+ (credential.kind === 'env-api-key'? `Issue a fresh key and re-export ${CLI_API_KEY_ENV}.`- : `Run '${CLI_PRIMARY_BIN} login' again.`,+ : `Run '${CLI_PRIMARY_BIN} login' again.`),status: 'fail',};diff --git a/apps/cli/src/doctor/probes.ts b/apps/cli/src/doctor/probes.tsindex 4b178d054b9..8c904bfe655 100644--- a/apps/cli/src/doctor/probes.ts+++ b/apps/cli/src/doctor/probes.ts@@ -1,7 +1,7 @@import { createLambdaClient, type TrpcClient } from '../api/client';import { resolveWorkspaceScope } from '../api/workspace';import { getUserIdFromApiKey } from '../auth/apiKey';-import { getValidToken } from '../auth/refresh';+import { describeTokenLookup, getValidToken } from '../auth/refresh';import type { AuthSourceKind } from '../auth/source';import { parseJwtPayload, pickAuthSource } from '../auth/source';import { resolveServerUrl } from '../settings';@@ -55,6 +55,11 @@ export interface CredentialProbe {error?: string;/** `exp` claim, for JWTs. */expiresAt?: number;+ /**+ * The remedy for that failure, when the probe knows one more specific than "log in again" β+ * a refresh that timed out needs a retry, not a re-authentication.+ */+ fix?: string;kind: AuthSourceKind;origin: string;serverUrl: string;@@ -91,13 +96,19 @@ export async function probeCredential(ctx: DoctorContext): Promise<CredentialProif (source.kind === 'stored') {const refreshed = await getValidToken();- if (!refreshed)+ if (refreshed.status !== 'ok') {+ const report = describeTokenLookup(refreshed);+return {...base,- error: source.token- ? 'the stored token has expired and could not be refreshed'- : 'no stored login on this machine',+ error:+ report?.detail ??+ (source.token+ ? 'the stored token has expired and could not be refreshed'+ : 'no stored login on this machine'),+ fix: report?.fix,};+ }const payload = parseJwtPayload(refreshed.credentials.accessToken);return {...base,diff --git a/src/libs/oidc-provider/provider.test.ts b/src/libs/oidc-provider/provider.test.tsindex f658de3247c..701520a556a 100644--- a/src/libs/oidc-provider/provider.test.ts+++ b/src/libs/oidc-provider/provider.test.ts@@ -114,7 +114,7 @@ describe('OIDC Provider - Market Client Integration', () => {BackchannelAuthenticationRequest: 600,ClientCredentials: 600,DeviceCode: 600,- Grant: 365 * 24 * 60 * 60,+ Grant: 100 * 365 * 24 * 60 * 60,IdToken: 3600,Interaction: 3600,RefreshToken: 30 * 24 * 60 * 60,@@ -130,7 +130,7 @@ describe('OIDC Provider - Market Client Integration', () => {vi.doUnmock('@/envs/app');}, 10000);- it('keeps the grant alive longer than a rotating refresh token', async () => {+ it('never lets the grant be what ends an active session', async () => {vi.doMock('@/envs/app', () => ({appEnv: {APP_URL: 'https://example.com',@@ -139,10 +139,16 @@ describe('OIDC Provider - Market Client Integration', () => {}));const { oidcArtifactTTL } = await import('./provider');- const dayFifteen = 15 * 24 * 60 * 60;-- expect(oidcArtifactTTL.Grant).toBeGreaterThan(dayFifteen);- expect(oidcArtifactTTL.Grant).toBeGreaterThanOrEqual(oidcArtifactTTL.RefreshToken);+ const fiftyYears = 50 * 365 * 24 * 60 * 60;++ /**+ * oidc-provider never extends `Grant.exp` on refresh, so a grant TTL anywhere near a+ * realistic account lifetime is a hard logout deadline for every client of that account+ * β a refresh that lands after it fails with `invalid_grant` even though the refresh+ * token itself is unused and unexpired. Only `RefreshToken` may bound a session.+ */+ expect(oidcArtifactTTL.Grant).toBeGreaterThan(fiftyYears);+ expect(oidcArtifactTTL.Grant).toBeGreaterThan(oidcArtifactTTL.RefreshToken);vi.doUnmock('@/envs/app');}, 10000);diff --git a/src/libs/oidc-provider/provider.ts b/src/libs/oidc-provider/provider.tsindex 97b2e350f57..4f8e6e5dc92 100644--- a/src/libs/oidc-provider/provider.ts+++ b/src/libs/oidc-provider/provider.ts@@ -30,9 +30,17 @@ export const oidcArtifactTTL = {BackchannelAuthenticationRequest: 10 * MINUTE_SECONDS,ClientCredentials: 10 * MINUTE_SECONDS,DeviceCode: 10 * MINUTE_SECONDS,- // oidc-provider never extends Grant.exp on refresh, so this is the absolute cap on a- // signed-in session no matter how often the refresh token rotates.- Grant: 365 * DAY_SECONDS,+ /**+ * A grant is the standing record of "this account authorised this client". oidc-provider+ * checks `grant.isExpired` on every refresh but never extends `Grant.exp`, so any finite+ * value here caps a signed-in session however active it is: the library's 14-day default+ * logged every client out a fortnight after login while its refresh token still sat unused+ * and unexpired. Inactivity is already expressed by `RefreshToken`, whose TTL restarts on+ * each rotation, so a grant carries no deadline of its own. `ttl` entries do accept+ * `undefined`, but the configuration merge drops undefined values, so "never" has to be+ * spelled as a century.+ */+ Grant: 100 * 365 * DAY_SECONDS,IdToken: HOUR_SECONDS,Interaction: HOUR_SECONDS,RefreshToken: 30 * DAY_SECONDS,@@ -333,6 +341,44 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<ProviderlogProvider('Authorization successful for client: %s', ctx.oidc.client?.clientId); // Use logProvider});+ /**+ * A rejected token request is the moment a client loses its session, and until this listener+ * existed it left no trace on the server: oidc-provider answers the client and nothing else,+ * so the platform logs showed a bare `POST /oidc/token 400` with no client, no grant type and+ * no reason. `error_detail` is the field worth having β it separates "grant not found" from+ * "refresh token already used" from "client mismatch", and the spec keeps it out of the+ * response body, so the server is the only place it can be read.+ *+ * Logged at warn, not error: a client presenting a dead token is its own fault, not an+ * incident, and drowning the error feed in it would bury the failures that are ours.+ */+ provider.on('grant.error', (ctx, err) => {+ const error = err as { error?: string; error_description?: string; error_detail?: string };++ console.warn(+ '[OIDC] grant rejected',+ JSON.stringify({+ clientId: ctx.oidc?.client?.clientId,+ error: error.error,+ errorDescription: error.error_description,+ errorDetail: error.error_detail,+ grantType: ctx.oidc?.params?.grant_type,+ status: ctx.status,+ }),+ );+ });++ provider.on('grant.revoked', (ctx, grantId) => {+ console.warn(+ '[OIDC] grant revoked',+ JSON.stringify({+ clientId: ctx.oidc?.client?.clientId,+ grantId,+ grantType: ctx.oidc?.params?.grant_type,+ }),+ );+ });+return provider;};