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.

πŸ› fix: add the lobehub cli oidc expreis should refresh aksk (#13925)

LiJianc37817e2d84a
diff --git a/apps/cli/src/auth/refresh.ts b/apps/cli/src/auth/refresh.ts
index 69439673d4b..882599d8d87 100644
--- a/apps/cli/src/auth/refresh.ts
+++ b/apps/cli/src/auth/refresh.ts
@@ -7,12 +7,14 @@ const CLIENT_ID = 'lobehub-cli';
* Get a valid access token, refreshing if expired.
* Returns null if no credentials or refresh fails.
*/
-export async function getValidToken(): Promise<{ credentials: StoredCredentials } | null> {
+export async function getValidToken(
+ bufferSeconds = 60,
+): Promise<{ credentials: StoredCredentials } | null> {
const credentials = loadCredentials();
if (!credentials) return null;
- // Check if token is still valid (with 60s buffer)
- if (credentials.expiresAt && Date.now() / 1000 < credentials.expiresAt - 60) {
+ // Check if token is still valid (with configurable buffer)
+ if (credentials.expiresAt && Date.now() / 1000 < credentials.expiresAt - bufferSeconds) {
return { credentials };
}
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.ts
index 9d47ee4ded5..0a6a50c2538 100644
--- a/apps/cli/src/commands/connect.test.ts
+++ b/apps/cli/src/commands/connect.test.ts
@@ -1,6 +1,11 @@
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+vi.mock('../auth/refresh', () => ({
+ getValidToken: vi.fn().mockResolvedValue({
+ credentials: { accessToken: 'test-token', expiresAt: undefined, refreshToken: 'test-refresh' },
+ }),
+}));
vi.mock('../auth/resolveToken', () => ({
resolveToken: vi.fn().mockResolvedValue({
serverUrl: 'https://app.lobehub.com',
@@ -83,16 +88,21 @@ vi.mock('@lobechat/device-gateway-client', () => ({
on: vi.fn().mockImplementation((event: string, handler: (...args: any[]) => any) => {
clientEventHandlers[event] = handler;
}),
+ reconnect: vi.fn().mockResolvedValue(undefined),
sendSystemInfoResponse: vi.fn().mockImplementation((data: any) => {
lastSentSystemInfoResponse = data;
}),
sendToolCallResponse: vi.fn().mockImplementation((data: any) => {
lastSentToolResponse = data;
}),
+ updateToken: vi.fn(),
};
}),
}));
+// eslint-disable-next-line import-x/first
+import { GatewayClient } from '@lobechat/device-gateway-client';
+
// eslint-disable-next-line import-x/first
import { resolveToken } from '../auth/resolveToken';
// eslint-disable-next-line import-x/first
@@ -242,13 +252,33 @@ describe('connect command', () => {
const program = createProgram();
await program.parseAsync(['node', 'test', 'connect']);
- clientEventHandlers['auth_failed']?.('invalid token');
+ await clientEventHandlers['auth_failed']?.('invalid token');
expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Authentication failed'));
expect(cleanupAllProcesses).toHaveBeenCalled();
expect(exitSpy).toHaveBeenCalledWith(1);
});
+ it('should retry auth_failed with token refresh when new token available', async () => {
+ vi.mocked(resolveToken).mockResolvedValueOnce({
+ serverUrl: 'https://app.lobehub.com',
+ token: 'refreshed-token',
+ tokenType: 'jwt',
+ userId: 'test-user',
+ });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'connect']);
+
+ const mockClient = vi.mocked(GatewayClient).mock.results[0].value;
+
+ await clientEventHandlers['auth_failed']?.('token expired');
+
+ expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Token refreshed'));
+ expect(mockClient.updateToken).toHaveBeenCalledWith('refreshed-token');
+ expect(exitSpy).not.toHaveBeenCalled();
+ });
+
it('should handle auth_expired', async () => {
vi.mocked(resolveToken).mockResolvedValueOnce({
serverUrl: 'https://app.lobehub.com',
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index cb38f361249..c8e30535516 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -10,6 +10,7 @@ import type {
import { GatewayClient } from '@lobechat/device-gateway-client';
import type { Command } from 'commander';
+import { getValidToken } from '../auth/refresh';
import { resolveToken } from '../auth/resolveToken';
import { CLI_API_KEY_ENV } from '../constants/auth';
import { OFFICIAL_GATEWAY_URL } from '../constants/urls';
@@ -284,8 +285,44 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
updateStatus('reconnecting');
});
- // Handle auth failed
- client.on('auth_failed', (reason) => {
+ // Proactive token refresh β€” schedule before JWT expires
+ const startProactiveRefresh = () =>
+ scheduleProactiveRefresh(
+ auth,
+ (refreshed) => {
+ client.updateToken(refreshed.token);
+ auth = refreshed;
+ // Schedule next refresh based on the new token
+ cancelRefreshTimer = startProactiveRefresh();
+ },
+ info,
+ error,
+ );
+ let cancelRefreshTimer = startProactiveRefresh();
+
+ // Handle auth failed β€” attempt token refresh once before giving up
+ // (e.g., auto-reconnect may send an expired JWT before proactive refresh fires)
+ let authFailedRefreshAttempted = false;
+ client.on('auth_failed', async (reason) => {
+ if (auth.tokenType === 'jwt' && !authFailedRefreshAttempted) {
+ authFailedRefreshAttempted = true;
+ info(`Authentication failed (${reason}). Attempting token refresh...`);
+ try {
+ const refreshed = await resolveToken({});
+ if (refreshed && refreshed.token !== auth.token) {
+ info('Token refreshed successfully. Reconnecting...');
+ client.updateToken(refreshed.token);
+ auth = refreshed;
+ authFailedRefreshAttempted = false;
+ cancelRefreshTimer = startProactiveRefresh();
+ await client.reconnect();
+ return;
+ }
+ } catch {
+ // fall through
+ }
+ }
+
error(`Authentication failed: ${reason}`);
error(
`Run 'lh login', or set ${CLI_API_KEY_ENV} and run 'lh login --server <url>' to configure API key authentication.`,
@@ -308,8 +345,8 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
if (refreshed) {
info('Token refreshed successfully. Reconnecting...');
client.updateToken(refreshed.token);
- // Update cached auth so subsequent refreshes use the latest token
auth = refreshed;
+ cancelRefreshTimer = startProactiveRefresh();
await client.reconnect();
return;
}
@@ -330,6 +367,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// Graceful shutdown
const cleanup = () => {
info('Shutting down...');
+ cancelRefreshTimer?.();
cleanupAllProcesses();
client.disconnect();
removeStatus();
@@ -374,6 +412,69 @@ function formatUptime(startedAt: Date): string {
return `${seconds}s`;
}
+// How far before expiry to proactively refresh (1 hour)
+const PROACTIVE_REFRESH_BUFFER = 60 * 60;
+
+/**
+ * Parse the `exp` claim from a JWT without verifying the signature.
+ */
+function parseJwtExp(token: string): number | undefined {
+ try {
+ const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());
+ return typeof payload.exp === 'number' ? payload.exp : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Schedule a proactive token refresh before the JWT expires.
+ * Returns a cleanup function that cancels the scheduled timer.
+ */
+function scheduleProactiveRefresh(
+ auth: { token: string; tokenType: string },
+ onRefreshed: (newAuth: Awaited<ReturnType<typeof resolveToken>>) => void,
+ info: (msg: string) => void,
+ error: (msg: string) => void,
+): (() => void) | null {
+ if (auth.tokenType !== 'jwt') return null;
+
+ const exp = parseJwtExp(auth.token);
+ if (!exp) return null;
+
+ const refreshAt = (exp - PROACTIVE_REFRESH_BUFFER) * 1000;
+ const delay = refreshAt - Date.now();
+
+ if (delay < 0) {
+ // Already past the refresh window β€” refresh immediately on next tick
+ void doRefresh();
+ return null;
+ }
+
+ const timer = setTimeout(() => void doRefresh(), delay);
+ return () => clearTimeout(timer);
+
+ async function doRefresh() {
+ try {
+ // Use the same buffer so getValidToken actually triggers a refresh
+ const result = await getValidToken(PROACTIVE_REFRESH_BUFFER);
+ if (!result) {
+ error('Proactive token refresh failed β€” no valid credentials.');
+ return;
+ }
+
+ const refreshed = await resolveToken({});
+ // Only notify if the token actually changed to avoid reschedule loops
+ if (refreshed.token !== auth.token) {
+ info('Proactively refreshed token.');
+ onRefreshed(refreshed);
+ }
+ } catch {
+ error('Proactive token refresh failed.');
+ }
+ }
+}
+
function collectSystemInfo(): DeviceSystemInfo {
const home = os.homedir();
const platform = process.platform;