user.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /**
  2. * 用户中心:cocoflow / cococlass 共用的"当前登录老师是谁"。
  3. * ----------------------------------------------------------
  4. * 为什么单独抽一个模块:
  5. * 1. 登录回调(cocorobo://auth/callback)不一定带回 organizeid,而 cocoflow 建智能体
  6. * 必须要有它;cococlass 也要靠 userid / schoolName 定位老师。
  7. * 2. 平台有按 userid 补全账号的接口,但**只有 selectUser 是安全的**:
  8. * GET https://pbl.cocorobo.cn/api/pbl/selectUser?userid=<uid>
  9. * 它校验网页会话 cookie,没会话只返回 [](201)。所以调用时必须带上登录窗口所在
  10. * Cookie 域(.cocorobo.cn)的会话,Electron 侧会把它物化进 authFile 的 platformCookie。
  11. * selectUser2 是同域下的测试接口:不带任何凭据就直出 apikey —— 任何人遍历 userid
  12. * 就能拿到老师的密钥,线上不能当常规通路。这里默认**不调用**它,只有显式
  13. * 打开 pblTestApi(本机调试)才会作为兜底。
  14. *
  15. * 设计约束:
  16. * · 只读 authFile(由 Electron 进程物化),不碰密钥存储。
  17. * · 补全失败不抛错:身份是"尽力补全",业务工具自己判断缺哪个字段再给老师可执行的提示。
  18. * · 绝不把 apiKey 明文交给模型,对外只给掩码 + hasApiKey。
  19. */
  20. import fs from 'node:fs'
  21. const DEFAULT_PBL_BASE = 'https://pbl.cocorobo.cn/api/pbl/'
  22. /** 补全结果的复用时长:老师换账号 / 平台换发 key 后最多这么久就能自愈。 */
  23. const CACHE_TTL_MS = 10 * 60 * 1000
  24. /** 平台取不到时别每次都重试:60 秒内直接用上次的结论,避免每个业务调用都白等两条请求。 */
  25. const NEGATIVE_TTL_MS = 60 * 1000
  26. /** 平台补全接口是外网请求,失败不该把一次对话卡住。 */
  27. const PBL_TIMEOUT_MS = 8000
  28. /**
  29. * selectUser2 的返回不是固定形状,线上见过两种:
  30. * [[{ userid, apikey, … }], { fieldCount: 0, … }] ← 裸数组(mysql 直出)
  31. * { value: [[{ … }], { … }] } ← 包了一层 value
  32. * 这里做一次宽松下钻,只认"带 userid 或 apikey 的那个对象"。
  33. */
  34. function findUserRow (input, depth = 0) {
  35. if (!input || depth > 4) return null
  36. if (Array.isArray(input)) {
  37. for (const item of input) {
  38. const hit = findUserRow(item, depth + 1)
  39. if (hit) return hit
  40. }
  41. return null
  42. }
  43. if (typeof input !== 'object') return null
  44. if (input.userid || input.apikey) return input
  45. for (const key of ['value', 'data', 'result', 'rows']) {
  46. if (key in input) {
  47. const hit = findUserRow(input[key], depth + 1)
  48. if (hit) return hit
  49. }
  50. }
  51. return null
  52. }
  53. /** 模型能看到的东西里不能有完整密钥。 */
  54. function maskKey (key) {
  55. const k = String(key || '')
  56. if (!k) return ''
  57. if (k.length <= 14) return `${k.slice(0, 4)}***`
  58. return `${k.slice(0, 8)}***${k.slice(-6)}`
  59. }
  60. function str (v) {
  61. return v === null || v === undefined ? '' : String(v).trim()
  62. }
  63. /**
  64. * @param {{ authFile: string, apiBase?: string, pblBase?: string, mock?: boolean, allowTestApi?: boolean }} options
  65. * apiBase —— 业务接口根地址(用它调 /agent/v1/auth/me 补身份)
  66. * allowTestApi —— 是否允许用 selectUser2(测试接口,无鉴权直出 apikey)。默认 false。
  67. */
  68. export function createUserCenter (options = {}) {
  69. const authFile = options.authFile
  70. const pblBase = String(options.pblBase || DEFAULT_PBL_BASE).replace(/\/*$/, '/')
  71. const apiBase = String(options.apiBase || '').replace(/\/+$/, '')
  72. const forceMock = options.mock === true
  73. // 安全开关:默认只走判 cookie 的 selectUser;本机调试才把测试接口放进来
  74. const allowTestApi = options.allowTestApi === true
  75. let cached = null // { identity, syncedAt }
  76. let inflight = null // 并发调用只打一次平台接口
  77. let lastFail = null // { at, warning } —— 补不到时的短暂记忆,避免每个工具调用都白等
  78. function readAuthFile () {
  79. try {
  80. return JSON.parse(fs.readFileSync(authFile, 'utf8')) || {}
  81. } catch {
  82. return {}
  83. }
  84. }
  85. /**
  86. * 把 authFile 里现有的身份摊平成一个统一结构。
  87. * 兼容两种写法:顶层 userid/username/schoolName,以及 user:{id,name,orgName,orgId}。
  88. */
  89. function fromFile (auth) {
  90. const u = auth.user || {}
  91. const userid = str(auth.userid || auth.userId || u.id || u.userid)
  92. const mock = forceMock || !!auth.mock || userid.startsWith('mock')
  93. return {
  94. userid,
  95. username: str(auth.username || u.name || u.nickname),
  96. schoolName: str(auth.schoolName || u.orgName || u.schoolName),
  97. organizeId: str(auth.organizeId || auth.organizeid || u.orgId || u.organizeId),
  98. accountNumber: str(auth.accountNumber),
  99. phone: str(auth.phonenumber || u.phone),
  100. apiKey: str(auth.apiKey || auth.token),
  101. mock,
  102. syncedAt: str(auth.userSyncedAt)
  103. }
  104. }
  105. /** 缺哪个字段,业务工具就靠它决定要不要继续。 */
  106. function missingOf (id, { needKey = true } = {}) {
  107. const missing = []
  108. if (!id.userid) missing.push('userid')
  109. if (needKey && !id.apiKey) missing.push('apiKey')
  110. if (!id.organizeId) missing.push('organizeId')
  111. return missing
  112. }
  113. async function fetchFromPbl (userid) {
  114. const controller = new AbortController()
  115. const timer = setTimeout(() => controller.abort(), PBL_TIMEOUT_MS)
  116. // selectUser 靠网页会话 cookie 认人:没带就是空数组,带错了也拿不到数据。
  117. // 这个 cookie 串由 Electron 从登录窗口分区取出后写进 authFile,插件不自己读 cookie 库。
  118. const cookie = str(readAuthFile().platformCookie)
  119. const apis = allowTestApi ? ['selectUser', 'selectUser2'] : ['selectUser']
  120. try {
  121. for (const api of apis) {
  122. try {
  123. const res = await fetch(`${pblBase}${api}?userid=${encodeURIComponent(userid)}`, {
  124. headers: {
  125. accept: 'application/json',
  126. ...(cookie ? { cookie } : {})
  127. },
  128. signal: controller.signal
  129. })
  130. if (!res.ok) continue
  131. const row = findUserRow(await res.json())
  132. if (!row) continue
  133. // selectUser 正常返回里带着 apikey;万一平台收紧成"只回身份不回 key",
  134. // 身份字段照样有用,key 沿用 authFile 里登录回调那把。
  135. return {
  136. ...(row.apikey ? { apiKey: str(row.apikey) } : {}),
  137. userid: str(row.userid) || userid,
  138. username: str(row.username || row.name),
  139. schoolName: str(row.schoolName || row.schoolname || row.orgName),
  140. organizeId: str(row.organizeid || row.organize_id || row.orgId || row.org),
  141. accountNumber: str(row.accountNumber),
  142. phone: str(row.phonenumber || row.phone)
  143. }
  144. } catch (err) {
  145. if (err && err.name === 'AbortError') throw err
  146. /* 换下一个接口 */
  147. }
  148. }
  149. return null
  150. } finally {
  151. clearTimeout(timer)
  152. }
  153. }
  154. /**
  155. * 另一条同样安全的补全通路:用登录拿到的 apiKey 调业务接口 /agent/v1/auth/me。
  156. * 它用 Bearer 鉴权,不依赖网页 cookie,也不碰任何无鉴权接口;
  157. * 平台还没实现这个接口时就是 404,静默跳过,不影响业务调用。
  158. */
  159. async function fetchFromAccountApi (apiKey) {
  160. if (!apiBase || !apiKey) return null
  161. const controller = new AbortController()
  162. const timer = setTimeout(() => controller.abort(), PBL_TIMEOUT_MS)
  163. try {
  164. const res = await fetch(`${apiBase}/agent/v1/auth/me`, {
  165. headers: { accept: 'application/json', authorization: `Bearer ${apiKey}` },
  166. signal: controller.signal
  167. })
  168. if (!res.ok) return null
  169. // 网关未部署时 nginx 会 301 到首页 HTML,别把它当 JSON 解析
  170. const ct = res.headers.get('content-type') || ''
  171. if (!ct.includes('json')) return null
  172. const json = await res.json()
  173. const u = (json && (json.user || (json.data && json.data.user))) || json || {}
  174. const userid = str(u.id || u.userid || u.userId)
  175. if (!userid) return null
  176. return {
  177. userid,
  178. username: str(u.name || u.username || u.nickname),
  179. schoolName: str(u.orgName || u.schoolName || u.org_name),
  180. organizeId: str(u.orgId || u.organizeId || u.organize_id),
  181. accountNumber: str(u.account || u.accountNumber),
  182. phone: str(u.phone || u.phonenumber)
  183. }
  184. } catch {
  185. return null
  186. } finally {
  187. clearTimeout(timer)
  188. }
  189. }
  190. /**
  191. * 补全结果写回 authFile,让"这次登录没带回 organizeid"变成一次性问题:
  192. * 下一次启动(以及同进程里的其他工具)直接读文件就有。
  193. * 写失败不影响本次调用。
  194. */
  195. function persist (id) {
  196. try {
  197. const auth = readAuthFile()
  198. const user = { ...(auth.user || {}) }
  199. if (id.userid) { auth.userid = id.userid; user.id = id.userid }
  200. if (id.username) { auth.username = id.username; user.name = id.username }
  201. if (id.schoolName) { auth.schoolName = id.schoolName; user.orgName = id.schoolName }
  202. if (id.organizeId) { auth.organizeId = id.organizeId; user.orgId = id.organizeId }
  203. if (id.accountNumber) { auth.accountNumber = id.accountNumber; user.accountNumber = id.accountNumber }
  204. if (id.apiKey) { auth.apiKey = id.apiKey; auth.token = id.apiKey }
  205. auth.user = user
  206. auth.userSyncedAt = new Date().toISOString()
  207. fs.writeFileSync(authFile, JSON.stringify(auth, null, 2), 'utf8')
  208. } catch { /* 写不进去只是下次还要再补一遍 */ }
  209. }
  210. /**
  211. * 取身份。
  212. * @param {{ force?: boolean, needKey?: boolean }} opts
  213. * force —— 忽略缓存,重新问一次平台(老师换了账号、或怀疑 key 被平台换了)
  214. * needKey —— 业务是否需要 apiKey(cocoflow 走 cookie 时不需要,可传 false)
  215. */
  216. async function resolve (opts = {}) {
  217. const { force = false, needKey = true } = opts
  218. const fromFileId = fromFile(readAuthFile())
  219. if (fromFileId.mock) {
  220. return { ...fromFileId, source: 'mock', missing: [], warning: '' }
  221. }
  222. // 缓存命中:内存缓存或文件里的同步时间还在有效期内,且字段齐
  223. const now = Date.now()
  224. const cacheFresh = cached && now - cached.at < CACHE_TTL_MS &&
  225. cached.identity.userid === fromFileId.userid &&
  226. cached.identity.apiKey === fromFileId.apiKey
  227. // 进程重启后内存缓存是空的,但文件里刚同步过就不用再打一次平台
  228. const fileSyncedAt = Date.parse(fromFileId.syncedAt) || 0
  229. const fileFresh = fileSyncedAt > 0 && now - fileSyncedAt < CACHE_TTL_MS
  230. const fileMissing = missingOf(fromFileId, { needKey })
  231. if (!force && fileMissing.length === 0 && (cacheFresh || fileFresh)) {
  232. return { ...fromFileId, source: 'cache', missing: [], warning: '' }
  233. }
  234. // 没有 userid 就补不了 —— 只有老师重新登录这条路
  235. if (!fromFileId.userid) {
  236. return {
  237. ...fromFileId,
  238. source: 'file',
  239. missing: missingOf(fromFileId, { needKey }),
  240. warning: '还没有登录授权过,读不到 userid'
  241. }
  242. }
  243. // 走到这里就是要问平台了(force / 字段缺 / 已过期)
  244. // 刚失败过就先用上次的结论,60 秒后再试(force 例外)
  245. if (!force && lastFail && Date.now() - lastFail.at < NEGATIVE_TTL_MS) {
  246. return { ...fromFileId, source: 'file', missing: fileMissing, warning: lastFail.warning }
  247. }
  248. // 两条都是安全通路:先 selectUser(判 cookie),再 apiKey 调 /agent/v1/auth/me。
  249. if (!inflight) {
  250. inflight = (async () => {
  251. const viaSession = await fetchFromPbl(fromFileId.userid)
  252. if (viaSession) return viaSession
  253. return await fetchFromAccountApi(fromFileId.apiKey)
  254. })().finally(() => { inflight = null })
  255. }
  256. let remote = null
  257. let warning = ''
  258. try {
  259. remote = await inflight
  260. } catch (err) {
  261. warning = (err && err.name === 'AbortError')
  262. ? '读取账号信息超时'
  263. : String((err && err.message) || err)
  264. }
  265. const merged = remote
  266. ? {
  267. ...fromFileId,
  268. ...Object.fromEntries(Object.entries(remote).filter(([, v]) => v)),
  269. // 平台返回空字段不能把文件里的好数据冲掉
  270. userid: remote.userid || fromFileId.userid,
  271. // 与写进文件的时间保持一致,工具返回里看到的才是真的同步时间
  272. syncedAt: new Date().toISOString(),
  273. mock: false
  274. }
  275. : fromFileId
  276. if (remote) {
  277. persist(merged)
  278. cached = { at: Date.now(), identity: merged }
  279. }
  280. // 补不到时把原因说清楚:两条通路都不通,只能靠老师重新登录让回调把身份带回来
  281. const noRemote = str(readAuthFile().platformCookie)
  282. ? '平台会话已失效(selectUser 与 /agent/v1/auth/me 都没返回账号),请老师在客户端重新登录一次'
  283. : '缺少平台登录会话(selectUser 需要网页 cookie,/agent/v1/auth/me 也未返回账号),请老师在客户端重新登录一次'
  284. if (remote) {
  285. persist(merged)
  286. cached = { at: Date.now(), identity: merged }
  287. lastFail = null
  288. } else {
  289. // 60 秒内不再重复问平台,直接复用这个结论
  290. lastFail = { at: Date.now(), warning: warning || noRemote }
  291. }
  292. return {
  293. ...merged,
  294. source: remote ? 'pbl' : 'file',
  295. missing: missingOf(merged, { needKey }),
  296. warning: remote ? '' : (warning || noRemote)
  297. }
  298. }
  299. /**
  300. * 给工具用的安全视图:密钥只给掩码。
  301. * 老师问"我现在是哪个账号"时直接返回这个。
  302. */
  303. async function describe (opts = {}) {
  304. const id = await resolve(opts)
  305. return {
  306. loggedIn: !!id.userid,
  307. mock: !!id.mock,
  308. userid: id.userid,
  309. username: id.username,
  310. schoolName: id.schoolName,
  311. organizeId: id.organizeId,
  312. accountNumber: id.accountNumber,
  313. phone: id.phone,
  314. hasApiKey: !!id.apiKey,
  315. apiKeyMasked: maskKey(id.apiKey),
  316. source: id.source,
  317. syncedAt: id.syncedAt || '',
  318. missing: id.missing,
  319. ...(id.warning ? { warning: id.warning } : {})
  320. }
  321. }
  322. return { resolve, describe, maskKey }
  323. }