/** * 用户中心:cocoflow / cococlass 共用的"当前登录老师是谁"。 * ---------------------------------------------------------- * 为什么单独抽一个模块: * 1. 登录回调(cocorobo://auth/callback)不一定带回 organizeid,而 cocoflow 建智能体 * 必须要有它;cococlass 也要靠 userid / schoolName 定位老师。 * 2. 平台有按 userid 补全账号的接口,但**只有 selectUser 是安全的**: * GET https://pbl.cocorobo.cn/api/pbl/selectUser?userid= * 它校验网页会话 cookie,没会话只返回 [](201)。所以调用时必须带上登录窗口所在 * Cookie 域(.cocorobo.cn)的会话,Electron 侧会把它物化进 authFile 的 platformCookie。 * selectUser2 是同域下的测试接口:不带任何凭据就直出 apikey —— 任何人遍历 userid * 就能拿到老师的密钥,线上不能当常规通路。这里默认**不调用**它,只有显式 * 打开 pblTestApi(本机调试)才会作为兜底。 * * 设计约束: * · 只读 authFile(由 Electron 进程物化),不碰密钥存储。 * · 补全失败不抛错:身份是"尽力补全",业务工具自己判断缺哪个字段再给老师可执行的提示。 * · 绝不把 apiKey 明文交给模型,对外只给掩码 + hasApiKey。 */ import fs from 'node:fs' const DEFAULT_PBL_BASE = 'https://pbl.cocorobo.cn/api/pbl/' /** 补全结果的复用时长:老师换账号 / 平台换发 key 后最多这么久就能自愈。 */ const CACHE_TTL_MS = 10 * 60 * 1000 /** 平台取不到时别每次都重试:60 秒内直接用上次的结论,避免每个业务调用都白等两条请求。 */ const NEGATIVE_TTL_MS = 60 * 1000 /** 平台补全接口是外网请求,失败不该把一次对话卡住。 */ const PBL_TIMEOUT_MS = 8000 /** * selectUser2 的返回不是固定形状,线上见过两种: * [[{ userid, apikey, … }], { fieldCount: 0, … }] ← 裸数组(mysql 直出) * { value: [[{ … }], { … }] } ← 包了一层 value * 这里做一次宽松下钻,只认"带 userid 或 apikey 的那个对象"。 */ function findUserRow (input, depth = 0) { if (!input || depth > 4) return null if (Array.isArray(input)) { for (const item of input) { const hit = findUserRow(item, depth + 1) if (hit) return hit } return null } if (typeof input !== 'object') return null if (input.userid || input.apikey) return input for (const key of ['value', 'data', 'result', 'rows']) { if (key in input) { const hit = findUserRow(input[key], depth + 1) if (hit) return hit } } return null } /** 模型能看到的东西里不能有完整密钥。 */ function maskKey (key) { const k = String(key || '') if (!k) return '' if (k.length <= 14) return `${k.slice(0, 4)}***` return `${k.slice(0, 8)}***${k.slice(-6)}` } function str (v) { return v === null || v === undefined ? '' : String(v).trim() } /** * @param {{ authFile: string, apiBase?: string, pblBase?: string, mock?: boolean, allowTestApi?: boolean }} options * apiBase —— 业务接口根地址(用它调 /agent/v1/auth/me 补身份) * allowTestApi —— 是否允许用 selectUser2(测试接口,无鉴权直出 apikey)。默认 false。 */ export function createUserCenter (options = {}) { const authFile = options.authFile const pblBase = String(options.pblBase || DEFAULT_PBL_BASE).replace(/\/*$/, '/') const apiBase = String(options.apiBase || '').replace(/\/+$/, '') const forceMock = options.mock === true // 安全开关:默认只走判 cookie 的 selectUser;本机调试才把测试接口放进来 const allowTestApi = options.allowTestApi === true let cached = null // { identity, syncedAt } let inflight = null // 并发调用只打一次平台接口 let lastFail = null // { at, warning } —— 补不到时的短暂记忆,避免每个工具调用都白等 function readAuthFile () { try { return JSON.parse(fs.readFileSync(authFile, 'utf8')) || {} } catch { return {} } } /** * 把 authFile 里现有的身份摊平成一个统一结构。 * 兼容两种写法:顶层 userid/username/schoolName,以及 user:{id,name,orgName,orgId}。 */ function fromFile (auth) { const u = auth.user || {} const userid = str(auth.userid || auth.userId || u.id || u.userid) const mock = forceMock || !!auth.mock || userid.startsWith('mock') return { userid, username: str(auth.username || u.name || u.nickname), schoolName: str(auth.schoolName || u.orgName || u.schoolName), organizeId: str(auth.organizeId || auth.organizeid || u.orgId || u.organizeId), accountNumber: str(auth.accountNumber), phone: str(auth.phonenumber || u.phone), apiKey: str(auth.apiKey || auth.token), mock, syncedAt: str(auth.userSyncedAt) } } /** 缺哪个字段,业务工具就靠它决定要不要继续。 */ function missingOf (id, { needKey = true } = {}) { const missing = [] if (!id.userid) missing.push('userid') if (needKey && !id.apiKey) missing.push('apiKey') if (!id.organizeId) missing.push('organizeId') return missing } async function fetchFromPbl (userid) { const controller = new AbortController() const timer = setTimeout(() => controller.abort(), PBL_TIMEOUT_MS) // selectUser 靠网页会话 cookie 认人:没带就是空数组,带错了也拿不到数据。 // 这个 cookie 串由 Electron 从登录窗口分区取出后写进 authFile,插件不自己读 cookie 库。 const cookie = str(readAuthFile().platformCookie) const apis = allowTestApi ? ['selectUser', 'selectUser2'] : ['selectUser'] try { for (const api of apis) { try { const res = await fetch(`${pblBase}${api}?userid=${encodeURIComponent(userid)}`, { headers: { accept: 'application/json', ...(cookie ? { cookie } : {}) }, signal: controller.signal }) if (!res.ok) continue const row = findUserRow(await res.json()) if (!row) continue // selectUser 正常返回里带着 apikey;万一平台收紧成"只回身份不回 key", // 身份字段照样有用,key 沿用 authFile 里登录回调那把。 return { ...(row.apikey ? { apiKey: str(row.apikey) } : {}), userid: str(row.userid) || userid, username: str(row.username || row.name), schoolName: str(row.schoolName || row.schoolname || row.orgName), organizeId: str(row.organizeid || row.organize_id || row.orgId || row.org), accountNumber: str(row.accountNumber), phone: str(row.phonenumber || row.phone) } } catch (err) { if (err && err.name === 'AbortError') throw err /* 换下一个接口 */ } } return null } finally { clearTimeout(timer) } } /** * 另一条同样安全的补全通路:用登录拿到的 apiKey 调业务接口 /agent/v1/auth/me。 * 它用 Bearer 鉴权,不依赖网页 cookie,也不碰任何无鉴权接口; * 平台还没实现这个接口时就是 404,静默跳过,不影响业务调用。 */ async function fetchFromAccountApi (apiKey) { if (!apiBase || !apiKey) return null const controller = new AbortController() const timer = setTimeout(() => controller.abort(), PBL_TIMEOUT_MS) try { const res = await fetch(`${apiBase}/agent/v1/auth/me`, { headers: { accept: 'application/json', authorization: `Bearer ${apiKey}` }, signal: controller.signal }) if (!res.ok) return null // 网关未部署时 nginx 会 301 到首页 HTML,别把它当 JSON 解析 const ct = res.headers.get('content-type') || '' if (!ct.includes('json')) return null const json = await res.json() const u = (json && (json.user || (json.data && json.data.user))) || json || {} const userid = str(u.id || u.userid || u.userId) if (!userid) return null return { userid, username: str(u.name || u.username || u.nickname), schoolName: str(u.orgName || u.schoolName || u.org_name), organizeId: str(u.orgId || u.organizeId || u.organize_id), accountNumber: str(u.account || u.accountNumber), phone: str(u.phone || u.phonenumber) } } catch { return null } finally { clearTimeout(timer) } } /** * 补全结果写回 authFile,让"这次登录没带回 organizeid"变成一次性问题: * 下一次启动(以及同进程里的其他工具)直接读文件就有。 * 写失败不影响本次调用。 */ function persist (id) { try { const auth = readAuthFile() const user = { ...(auth.user || {}) } if (id.userid) { auth.userid = id.userid; user.id = id.userid } if (id.username) { auth.username = id.username; user.name = id.username } if (id.schoolName) { auth.schoolName = id.schoolName; user.orgName = id.schoolName } if (id.organizeId) { auth.organizeId = id.organizeId; user.orgId = id.organizeId } if (id.accountNumber) { auth.accountNumber = id.accountNumber; user.accountNumber = id.accountNumber } if (id.apiKey) { auth.apiKey = id.apiKey; auth.token = id.apiKey } auth.user = user auth.userSyncedAt = new Date().toISOString() fs.writeFileSync(authFile, JSON.stringify(auth, null, 2), 'utf8') } catch { /* 写不进去只是下次还要再补一遍 */ } } /** * 取身份。 * @param {{ force?: boolean, needKey?: boolean }} opts * force —— 忽略缓存,重新问一次平台(老师换了账号、或怀疑 key 被平台换了) * needKey —— 业务是否需要 apiKey(cocoflow 走 cookie 时不需要,可传 false) */ async function resolve (opts = {}) { const { force = false, needKey = true } = opts const fromFileId = fromFile(readAuthFile()) if (fromFileId.mock) { return { ...fromFileId, source: 'mock', missing: [], warning: '' } } // 缓存命中:内存缓存或文件里的同步时间还在有效期内,且字段齐 const now = Date.now() const cacheFresh = cached && now - cached.at < CACHE_TTL_MS && cached.identity.userid === fromFileId.userid && cached.identity.apiKey === fromFileId.apiKey // 进程重启后内存缓存是空的,但文件里刚同步过就不用再打一次平台 const fileSyncedAt = Date.parse(fromFileId.syncedAt) || 0 const fileFresh = fileSyncedAt > 0 && now - fileSyncedAt < CACHE_TTL_MS const fileMissing = missingOf(fromFileId, { needKey }) if (!force && fileMissing.length === 0 && (cacheFresh || fileFresh)) { return { ...fromFileId, source: 'cache', missing: [], warning: '' } } // 没有 userid 就补不了 —— 只有老师重新登录这条路 if (!fromFileId.userid) { return { ...fromFileId, source: 'file', missing: missingOf(fromFileId, { needKey }), warning: '还没有登录授权过,读不到 userid' } } // 走到这里就是要问平台了(force / 字段缺 / 已过期) // 刚失败过就先用上次的结论,60 秒后再试(force 例外) if (!force && lastFail && Date.now() - lastFail.at < NEGATIVE_TTL_MS) { return { ...fromFileId, source: 'file', missing: fileMissing, warning: lastFail.warning } } // 两条都是安全通路:先 selectUser(判 cookie),再 apiKey 调 /agent/v1/auth/me。 if (!inflight) { inflight = (async () => { const viaSession = await fetchFromPbl(fromFileId.userid) if (viaSession) return viaSession return await fetchFromAccountApi(fromFileId.apiKey) })().finally(() => { inflight = null }) } let remote = null let warning = '' try { remote = await inflight } catch (err) { warning = (err && err.name === 'AbortError') ? '读取账号信息超时' : String((err && err.message) || err) } const merged = remote ? { ...fromFileId, ...Object.fromEntries(Object.entries(remote).filter(([, v]) => v)), // 平台返回空字段不能把文件里的好数据冲掉 userid: remote.userid || fromFileId.userid, // 与写进文件的时间保持一致,工具返回里看到的才是真的同步时间 syncedAt: new Date().toISOString(), mock: false } : fromFileId if (remote) { persist(merged) cached = { at: Date.now(), identity: merged } } // 补不到时把原因说清楚:两条通路都不通,只能靠老师重新登录让回调把身份带回来 const noRemote = str(readAuthFile().platformCookie) ? '平台会话已失效(selectUser 与 /agent/v1/auth/me 都没返回账号),请老师在客户端重新登录一次' : '缺少平台登录会话(selectUser 需要网页 cookie,/agent/v1/auth/me 也未返回账号),请老师在客户端重新登录一次' if (remote) { persist(merged) cached = { at: Date.now(), identity: merged } lastFail = null } else { // 60 秒内不再重复问平台,直接复用这个结论 lastFail = { at: Date.now(), warning: warning || noRemote } } return { ...merged, source: remote ? 'pbl' : 'file', missing: missingOf(merged, { needKey }), warning: remote ? '' : (warning || noRemote) } } /** * 给工具用的安全视图:密钥只给掩码。 * 老师问"我现在是哪个账号"时直接返回这个。 */ async function describe (opts = {}) { const id = await resolve(opts) return { loggedIn: !!id.userid, mock: !!id.mock, userid: id.userid, username: id.username, schoolName: id.schoolName, organizeId: id.organizeId, accountNumber: id.accountNumber, phone: id.phone, hasApiKey: !!id.apiKey, apiKeyMasked: maskKey(id.apiKey), source: id.source, syncedAt: id.syncedAt || '', missing: id.missing, ...(id.warning ? { warning: id.warning } : {}) } } return { resolve, describe, maskKey } }