Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(auth): pass encrypted Device ID from Web to Desktop
Naiyuan Qingf13509e12a7d
diff --git a/apps/desktop/src/main/ipc/auth.ts b/apps/desktop/src/main/ipc/auth.tsindex 69f2df5e71..200e6eddc8 100644--- a/apps/desktop/src/main/ipc/auth.ts+++ b/apps/desktop/src/main/ipc/auth.ts@@ -178,10 +178,26 @@ function loadAuthData(): AuthData | null {}}-function saveAuthData(sid: string, user: AuthUser): boolean {+/**+ * Save auth data to disk.+ * @param sid Session ID+ * @param user User info+ * @param passedDeviceId Optional Device ID from Web browser (encrypted 40-char format).+ * If provided and valid, use it; otherwise fall back to local Device ID.+ */+function saveAuthData(sid: string, user: AuthUser, passedDeviceId?: string): boolean {try {- // Ensure we have a deviceId (get existing or create new)- const deviceId = getOrCreateDeviceId();+ // Use passed deviceId from Web if valid, otherwise use local one+ let deviceId: string;+ if (passedDeviceId && isValidDeviceId(passedDeviceId)) {+ deviceId = passedDeviceId;+ console.log("[Auth] Using Device ID from Web browser:", deviceId.slice(0, 8) + "...");+ } else {+ deviceId = getOrCreateDeviceId();+ if (passedDeviceId) {+ console.warn("[Auth] Invalid Device ID from Web, using local:", passedDeviceId);+ }+ }const data: AuthFileData = { sid, user, deviceId };@@ -309,6 +325,7 @@ async function createLocalServerSession(): Promise<number> {if (url.pathname === "/callback") {const sid = url.searchParams.get("sid");const userJson = url.searchParams.get("user");+ const deviceId = url.searchParams.get("deviceId");// 返回成功页面res.writeHead(200, {@@ -317,7 +334,7 @@ async function createLocalServerSession(): Promise<number> {});res.end(callbackHtml);- console.log("[Auth] Parsed params:", { sid, userJson });+ console.log("[Auth] Parsed params:", { sid, userJson, deviceId: deviceId?.slice(0, 8) + "..." });if (sid && userJson) {try {@@ -326,17 +343,15 @@ async function createLocalServerSession(): Promise<number> {console.log("[Auth] Received auth callback:", {sid: sid.substring(0, 8) + "...",user: user.name,+ deviceId: deviceId ? deviceId.slice(0, 8) + "..." : "not provided",});- // 保存认证数据- saveAuthData(sid, user);+ // 保存认证数据(使用 Web 传递的 deviceId)+ saveAuthData(sid, user, deviceId || undefined);// 通知渲染进程- console.log("[Auth] mainWindowRef:", mainWindowRef ? "exists" : "null");if (mainWindowRef && !mainWindowRef.isDestroyed()) {- console.log("[Auth] Sending auth:callback to renderer...");- mainWindowRef.webContents.send("auth:callback", { sid, user });- console.log("[Auth] auth:callback sent!");+ mainWindowRef.webContents.send("auth:callback", { sid, user, deviceId });// 聚焦窗口if (mainWindowRef.isMinimized()) mainWindowRef.restore();mainWindowRef.focus();@@ -434,7 +449,7 @@ export function handleAuthDeepLink(url: string): void {return;}- // multica://auth?sid=xxx&user=xxx+ // multica://auth?sid=xxx&user=xxx&deviceId=xxxif (parsedUrl.host === "auth" ||parsedUrl.pathname === "//auth" ||@@ -442,20 +457,22 @@ export function handleAuthDeepLink(url: string): void {) {const sid = parsedUrl.searchParams.get("sid");const userJson = parsedUrl.searchParams.get("user");+ const deviceId = parsedUrl.searchParams.get("deviceId");if (sid && userJson) {const user = JSON.parse(decodeURIComponent(userJson)) as AuthUser;console.log("[Auth] Deep link auth received:", {sid: sid.substring(0, 8) + "...",user: user.name,+ deviceId: deviceId ? deviceId.slice(0, 8) + "..." : "not provided",});- // 保存认证数据- saveAuthData(sid, user);+ // 保存认证数据(使用 Web 传递的 deviceId)+ saveAuthData(sid, user, deviceId || undefined);// 通知渲染进程if (mainWindowRef && !mainWindowRef.isDestroyed()) {- mainWindowRef.webContents.send("auth:callback", { sid, user });+ mainWindowRef.webContents.send("auth:callback", { sid, user, deviceId });if (mainWindowRef.isMinimized()) mainWindowRef.restore();mainWindowRef.focus();}@@ -476,9 +493,9 @@ export function registerAuthHandlers(): void {return loadAuthData();});- // 保存认证数据- ipcMain.handle("auth:save", (_, sid: string, user: AuthUser) => {- return saveAuthData(sid, user);+ // 保存认证数据(支持传入 deviceId)+ ipcMain.handle("auth:save", (_, sid: string, user: AuthUser, deviceId?: string) => {+ return saveAuthData(sid, user, deviceId);});// 清除认证数据(登出)diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex af3f7d471f..e317dc33d5 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -143,9 +143,9 @@ const electronAPI = {/** Load auth data from local file */load: (): Promise<{ sid: string; user: { uid: string; name: string; email?: string; icon?: string; vip?: number }; deviceId?: string } | null> =>ipcRenderer.invoke('auth:load'),- /** Save auth data to local file */- save: (sid: string, user: { uid: string; name: string; email?: string; icon?: string; vip?: number }): Promise<boolean> =>- ipcRenderer.invoke('auth:save', sid, user),+ /** Save auth data to local file (with optional deviceId from Web) */+ save: (sid: string, user: { uid: string; name: string; email?: string; icon?: string; vip?: number }, deviceId?: string): Promise<boolean> =>+ ipcRenderer.invoke('auth:save', sid, user, deviceId),/** Clear auth data (logout) */clear: (): Promise<boolean> => ipcRenderer.invoke('auth:clear'),/** Start login flow (opens browser) */@@ -154,8 +154,8 @@ const electronAPI = {getDeviceId: (): Promise<string> => ipcRenderer.invoke('auth:getDeviceId'),/** Get encrypted Device-Id header value for API requests */getDeviceIdHeader: (): Promise<string> => ipcRenderer.invoke('auth:getDeviceIdHeader'),- /** Listen for auth callback */- onAuthCallback: (callback: (data: { sid: string; user: { uid: string; name: string; email?: string; icon?: string; vip?: number } }) => void) => {+ /** Listen for auth callback (includes deviceId from Web browser) */+ onAuthCallback: (callback: (data: { sid: string; user: { uid: string; name: string; email?: string; icon?: string; vip?: number }; deviceId?: string }) => void) => {ipcRenderer.on('auth:callback', (_event, data) => callback(data))},/** Remove auth callback listener */diff --git a/apps/web/app/login/login-form.tsx b/apps/web/app/login/login-form.tsxindex 8b92830c72..e8a016f607 100644--- a/apps/web/app/login/login-form.tsx+++ b/apps/web/app/login/login-form.tsx@@ -10,6 +10,7 @@ import { MulticaIcon } from '@multica/ui/components/multica-icon'import { LoginAuthType, UserInfo } from '@/lib/interface'import { saveSession, isAuthenticated } from '@/lib/auth'import { userLogin } from '@/service/user'+import { getOrCreateDeviceId, generateDeviceIdHeader } from '@/lib/device'type LoginStep = 'email' | 'code'@@ -103,7 +104,7 @@ export function LoginForm() {}, [countdown])// Handle login success- const handleLoginSuccess = (sid: string, user: UserInfo) => {+ const handleLoginSuccess = async (sid: string, user: UserInfo) => {// Save session to cookie for web appsaveSession(sid, user)@@ -114,9 +115,14 @@ export function LoginForm() {const port = nextUrl.searchParams.get('port')const platform = nextUrl.searchParams.get('platform') || 'web'+ // Get Device ID and encrypt for Desktop+ const rawDeviceId = getOrCreateDeviceId()+ const deviceId = await generateDeviceIdHeader(rawDeviceId)+const params = new URLSearchParams({sid,user: JSON.stringify(user),+ deviceId,})if (platform === 'web' && port) {diff --git a/apps/web/lib/device.ts b/apps/web/lib/device.tsindex a19ceabcbd..299179a0a5 100644--- a/apps/web/lib/device.ts+++ b/apps/web/lib/device.ts@@ -1,36 +1,42 @@-const DEVICE_ID = 'MULTICA_DEVICE_ID';+/**+ * Device ID management for Multica Web+ * Consistent with copilot-search: stores raw UUID, encrypts when transmitting+ */++const DEVICE_ID_KEY = 'MULTICA_DEVICE_ID'// SHA-256 hash function (using Web Crypto API)async function sha256(text: string): Promise<string> {- const buffer = new TextEncoder().encode(text);- const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);- const hashArray = Array.from(new Uint8Array(hashBuffer));- return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');+ const buffer = new TextEncoder().encode(text)+ const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)+ const hashArray = Array.from(new Uint8Array(hashBuffer))+ return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')}-// Generate Device-Id header-export async function generateDeviceIdHeader(deviceId: string): Promise<string> {- // First hash, take first 32 chars- const hash1 = await sha256(deviceId);- const hashedDeviceId = hash1.slice(0, 32);-- // Second hash, take first 8 chars- const hash2 = await sha256(hashedDeviceId);- const finalDeviceId = hash2.slice(0, 8) + hashedDeviceId;-- return finalDeviceId;-}--// Get or create Device ID+/**+ * Get or create Device ID (raw UUID format)+ * Stored in localStorage, encrypted only when transmitting+ */export function getOrCreateDeviceId(): string {- if (typeof window === 'undefined') return '';+ if (typeof window === 'undefined') return ''- let deviceId = localStorage.getItem(DEVICE_ID);+ let deviceId = localStorage.getItem(DEVICE_ID_KEY)if (!deviceId) {- deviceId = crypto.randomUUID();- localStorage.setItem(DEVICE_ID, deviceId);+ deviceId = crypto.randomUUID()+ localStorage.setItem(DEVICE_ID_KEY, deviceId)}- return deviceId;+ return deviceId+}++/**+ * Generate encrypted Device-Id header value+ * Algorithm (consistent with copilot-search):+ * 1. sha256(uuid).slice(0, 32) = hashedDeviceId+ * 2. sha256(hashedDeviceId).slice(0, 8) + hashedDeviceId = 40 chars+ */+export async function generateDeviceIdHeader(deviceId: string): Promise<string> {+ const hashedDeviceId = (await sha256(deviceId)).slice(0, 32)+ return (await sha256(hashedDeviceId)).slice(0, 8) + hashedDeviceId}diff --git a/apps/web/service/request.ts b/apps/web/service/request.tsindex e4ac39217a..9c97b5c197 100644--- a/apps/web/service/request.ts+++ b/apps/web/service/request.ts@@ -1,10 +1,10 @@import { API_HOST } from '@/lib/constant';-import { generateDeviceIdHeader, getOrCreateDeviceId } from '@/lib/device';+import { getOrCreateDeviceId, generateDeviceIdHeader } from '@/lib/device';import { getSid } from '@/lib/auth';// Fetch request wrapperexport async function request<T = unknown>(url: string, options: RequestInit = {}): Promise<T> {- // Get or generate Device ID+ // Get or generate Device ID, encrypt for headerlet deviceIdHeader = '';let sid: string | null = null;if (typeof window !== 'undefined') {