feat(desktop): implement client token rotation and session management enhancements
This commit is contained in:
@@ -1,7 +1,11 @@
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
import type { DesktopAccountInfo, DesktopRuntimeSessionSyncRequest } from '@geo/shared-types'
|
||||
import type {
|
||||
DesktopAccountInfo,
|
||||
DesktopClientRotateResponse,
|
||||
DesktopRuntimeSessionSyncRequest,
|
||||
} from '@geo/shared-types'
|
||||
import { isAIPlatformId } from '@geo/shared-types'
|
||||
import { shell } from 'electron'
|
||||
import type {
|
||||
@@ -38,12 +42,13 @@ import { registerRendererDevtoolsProxyTarget } from './renderer-devtools-proxy'
|
||||
import {
|
||||
noteRuntimeAccountBound,
|
||||
refreshRuntimeAccounts,
|
||||
getRuntimeControllerSnapshot,
|
||||
releaseRuntimeSession,
|
||||
requestRuntimeAccountProbe,
|
||||
syncRuntimeSession,
|
||||
unbindRuntimeAccount,
|
||||
} from './runtime-controller'
|
||||
import { onRuntimeInvalidated } from './runtime-events'
|
||||
import { onRuntimeAuthExpired, onRuntimeInvalidated } from './runtime-events'
|
||||
import { createRuntimeAccountSnapshot, createRuntimeSnapshot } from './runtime-snapshot'
|
||||
import { initScheduler } from './scheduler'
|
||||
import { initSessionRegistry } from './session-registry'
|
||||
@@ -52,6 +57,7 @@ import {
|
||||
initTransport,
|
||||
listDesktopPublishTasks,
|
||||
retryDesktopPublishTask,
|
||||
rotateDesktopClient,
|
||||
} from './transport/api-client'
|
||||
import { initTray, showTrayBalloon } from './tray'
|
||||
import { STANDARD_USER_AGENT } from './user-agent'
|
||||
@@ -120,6 +126,7 @@ let mainWindowCreatePromise: Promise<ElectronBrowserWindow> | null = null
|
||||
let loginWindowCreatePromise: Promise<ElectronBrowserWindow> | null = null
|
||||
let settingsWindowCreatePromise: Promise<ElectronBrowserWindow> | null = null
|
||||
let windowModeSwitchQueue: Promise<void> = Promise.resolve()
|
||||
let clientTokenRotatePromise: Promise<DesktopClientRotateResponse> | null = null
|
||||
let canHandleDesktopDeepLinks = false
|
||||
const pendingDesktopDeepLinks: string[] = []
|
||||
const forceCloseWindows = new WeakSet<ElectronBrowserWindow>()
|
||||
@@ -358,6 +365,32 @@ function captureRuntimeAccountSnapshot(accountId: string) {
|
||||
return createRuntimeAccountSnapshot(accountId)
|
||||
}
|
||||
|
||||
async function clearRendererDesktopSession(window: ElectronBrowserWindow | null): Promise<void> {
|
||||
if (!window || window.isDestroyed()) {
|
||||
return
|
||||
}
|
||||
|
||||
await window.webContents
|
||||
.executeJavaScript("window.localStorage.removeItem('geo.desktop.session.v1')", true)
|
||||
.catch((error) => {
|
||||
console.warn('[desktop-main] clear renderer desktop session failed', {
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function clearRendererDesktopSessions(): Promise<void> {
|
||||
await Promise.all(
|
||||
BrowserWindow.getAllWindows().map((window) =>
|
||||
clearRendererDesktopSession(window).catch((error) => {
|
||||
console.warn('[desktop-main] clear window desktop session failed', {
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async function ensureMainWindow(): Promise<ElectronBrowserWindow> {
|
||||
const existing = currentMainWindow()
|
||||
if (existing) {
|
||||
@@ -491,6 +524,13 @@ function queueWindowModeSwitch(
|
||||
return nextSwitch
|
||||
}
|
||||
|
||||
async function forceLoginWindowForAuthExpired(message: string): Promise<void> {
|
||||
console.warn('[desktop-main] runtime auth expired; switching to login window', { message })
|
||||
syncRuntimeSession(null)
|
||||
await clearRendererDesktopSessions()
|
||||
await queueWindowModeSwitch('login', { source: 'logout', animate: true }, currentMainWindow())
|
||||
}
|
||||
|
||||
async function openSettingsWindow(): Promise<void> {
|
||||
const window = await ensureSettingsWindow()
|
||||
const parent = settingsWindowParent()
|
||||
@@ -890,7 +930,35 @@ function registerBridgeHandlers(): void {
|
||||
return null
|
||||
},
|
||||
)
|
||||
safeHandle('desktop:runtime-session-rotate-client-token', async () => {
|
||||
if (!clientTokenRotatePromise) {
|
||||
clientTokenRotatePromise = rotateDesktopClient()
|
||||
.then((rotated) => {
|
||||
const currentSession = getRuntimeControllerSnapshot().session
|
||||
if (
|
||||
currentSession?.mode === 'authenticated' &&
|
||||
currentSession.desktop_client?.id === rotated.client.id
|
||||
) {
|
||||
syncRuntimeSession({
|
||||
...currentSession,
|
||||
client_token: rotated.client_token,
|
||||
desktop_client: rotated.client,
|
||||
})
|
||||
}
|
||||
return rotated
|
||||
})
|
||||
.finally(() => {
|
||||
clientTokenRotatePromise = null
|
||||
})
|
||||
}
|
||||
return clientTokenRotatePromise
|
||||
})
|
||||
safeHandle('desktop:runtime-session-release', async (_event, revoke?: boolean) => {
|
||||
if (revoke) {
|
||||
currentWindowMode = 'login'
|
||||
persistWindowMode('login')
|
||||
await clearRendererDesktopSessions()
|
||||
}
|
||||
await releaseRuntimeSession({ revoke: Boolean(revoke) })
|
||||
return null
|
||||
})
|
||||
@@ -920,7 +988,8 @@ if (!hasSingleInstanceLock) {
|
||||
.then(async () => {
|
||||
suppressNativeWindowMenu()
|
||||
registerDesktopProtocolClient()
|
||||
currentWindowMode = readPersistedWindowMode()
|
||||
currentWindowMode = 'login'
|
||||
persistWindowMode('login')
|
||||
initDesktopAppSettings()
|
||||
registerBridgeHandlers()
|
||||
await initSessionRegistry()
|
||||
@@ -937,6 +1006,11 @@ if (!hasSingleInstanceLock) {
|
||||
}
|
||||
mainRendererContents.send('desktop:runtime-invalidated', event)
|
||||
})
|
||||
onRuntimeAuthExpired((event) => {
|
||||
void forceLoginWindowForAuthExpired(event.message).catch((error) => {
|
||||
console.error('[desktop-main] auth-expired window transition failed', error)
|
||||
})
|
||||
})
|
||||
await queueWindowModeSwitch(currentWindowMode)
|
||||
initTray(() => {
|
||||
revealActiveWindowSafely('tray')
|
||||
@@ -976,8 +1050,14 @@ if (!hasSingleInstanceLock) {
|
||||
quitReleaseInFlight = true
|
||||
event.preventDefault()
|
||||
|
||||
currentWindowMode = 'login'
|
||||
persistWindowMode('login')
|
||||
|
||||
void Promise.race([
|
||||
releaseRuntimeSession(),
|
||||
(async () => {
|
||||
await clearRendererDesktopSessions()
|
||||
await releaseRuntimeSession()
|
||||
})(),
|
||||
new Promise<void>((resolve) => setTimeout(resolve, 1500)),
|
||||
]).finally(() => {
|
||||
app.quit()
|
||||
|
||||
@@ -84,7 +84,11 @@ import {
|
||||
notePublishTaskLeaseMiss,
|
||||
selectNextPublishTask,
|
||||
} from './publish-scheduler'
|
||||
import { emitRuntimeInvalidated, onRuntimeInvalidated } from './runtime-events'
|
||||
import {
|
||||
emitRuntimeAuthExpired,
|
||||
emitRuntimeInvalidated,
|
||||
onRuntimeInvalidated,
|
||||
} from './runtime-events'
|
||||
import {
|
||||
initScheduler,
|
||||
noteSchedulerAccountsSync,
|
||||
@@ -3277,6 +3281,7 @@ function handleAuthExpired(error: unknown): void {
|
||||
setTransportAuthState('expired')
|
||||
recordActivity('danger', '客户端令牌已过期', message)
|
||||
stopRuntime()
|
||||
emitRuntimeAuthExpired(message)
|
||||
}
|
||||
|
||||
function selectPublishAdapter(platform: string): PublishAdapter | null {
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
type RuntimeInvalidationReason = 'account-health' | 'publish-task-lease'
|
||||
|
||||
type RuntimeAuthExpiredListener = (event: {
|
||||
reason: 'client-auth-expired'
|
||||
at: number
|
||||
message: string
|
||||
}) => void
|
||||
|
||||
type RuntimeInvalidationListener = (event: {
|
||||
reason: RuntimeInvalidationReason
|
||||
at: number
|
||||
@@ -8,6 +14,7 @@ type RuntimeInvalidationListener = (event: {
|
||||
}) => void
|
||||
|
||||
const listeners = new Set<RuntimeInvalidationListener>()
|
||||
const authExpiredListeners = new Set<RuntimeAuthExpiredListener>()
|
||||
|
||||
export function emitRuntimeInvalidated(
|
||||
reason: RuntimeInvalidationReason,
|
||||
@@ -37,3 +44,28 @@ export function onRuntimeInvalidated(listener: RuntimeInvalidationListener): ()
|
||||
listeners.delete(listener)
|
||||
}
|
||||
}
|
||||
|
||||
export function emitRuntimeAuthExpired(message: string): void {
|
||||
const event = {
|
||||
reason: 'client-auth-expired',
|
||||
at: Date.now(),
|
||||
message,
|
||||
} as const
|
||||
|
||||
for (const listener of authExpiredListeners) {
|
||||
try {
|
||||
listener(event)
|
||||
} catch (error) {
|
||||
console.warn('[desktop-runtime] auth-expired listener failed', {
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function onRuntimeAuthExpired(listener: RuntimeAuthExpiredListener): () => void {
|
||||
authExpiredListeners.add(listener)
|
||||
return () => {
|
||||
authExpiredListeners.delete(listener)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
DesktopArticleContent,
|
||||
DesktopClientHeartbeatRequest,
|
||||
DesktopClientHeartbeatResponse,
|
||||
DesktopClientRotateResponse,
|
||||
DesktopPublishTaskListResponse,
|
||||
DesktopRuntimeSessionSyncRequest,
|
||||
DesktopTaskInfo,
|
||||
@@ -430,6 +431,13 @@ export async function heartbeatDesktopClient(
|
||||
)
|
||||
}
|
||||
|
||||
export async function rotateDesktopClient(): Promise<DesktopClientRotateResponse> {
|
||||
return desktopPost<DesktopClientRotateResponse, Record<string, never>>(
|
||||
'/api/desktop/clients/rotate',
|
||||
{},
|
||||
)
|
||||
}
|
||||
|
||||
export async function offlineDesktopClient(): Promise<void> {
|
||||
await desktopPost<{ server_time: string }, Record<string, never>>(
|
||||
'/api/desktop/clients/offline',
|
||||
|
||||
Reference in New Issue
Block a user