/** * 诊断专用 Matrix 账号 * * 为什么需要:provision 云函数返回的 accessToken 属于 **App 登录用户本人** * (userId 与 App 相同)。诊断脚本若拿它开 /sync 并推进 since token, * 会把 App 端的同步流截断 —— App 表现为「丢消息 / 卡片不刷新」。 * 所以诊断另起一个独立 Matrix 账号,只进自己建的房间。 * * 注册策略(按顺序尝试,任一成功即用): * 1) 缓存文件命中(~/.fmode/config/diag-mx.json,含 homeserver) * 2) /register 开放注册(无 captcha、无 token 要求) * 3) /register 带注册令牌(环境变量 MATRIX_REGISTRATION_TOKEN) * * 注册失败时抛错并要求人工提供账号 —— 绝不回退去用 App 主账号。 */ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { homedir } from 'node:os'; import { join, dirname } from 'node:path'; const CACHE = join(homedir(), '.fmode', 'config', 'diag-mx.json'); function readCache(hs) { try { const j = JSON.parse(readFileSync(CACHE, 'utf8')); if (j.homeserver === hs && j.accessToken && j.userId) return j; } catch { /* 无缓存 */ } return null; } async function register(hs) { const username = `diag${Date.now().toString(36)}`; const bodies = [ { username, password: `p-${Math.random().toString(36).slice(2)}`, auth: { type: 'm.login.dummy' } }, ]; const regToken = process.env.MATRIX_REGISTRATION_TOKEN; if (regToken) bodies.push({ username, password: `p-${Math.random().toString(36).slice(2)}`, auth: { type: 'm.login.registration_token', token: regToken } }); else bodies.push({ username, password: `p-${Math.random().toString(36).slice(2)}` }); let lastErr = ''; for (const body of bodies) { const r = await fetch(`${hs}/_matrix/client/v3/register?kind=user`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); const j = await r.json().catch(() => ({})); if (r.ok && j.access_token) return { homeserver: hs, userId: j.user_id, accessToken: j.access_token }; lastErr = `${r.status} ${j.errcode ?? ''} ${j.error ?? ''}`.trim(); } throw new Error( `诊断账号注册失败(${lastErr})。请提供一台注册账号,或在 ~/.fmode/config/diag-mx.json 写入 ` + `{"homeserver":"${hs}","userId":"@diag:...","accessToken":"syt_..."}。` + `**不要**用 App 主账号跑诊断(会截断 App 的 /sync 流)。`, ); } export async function getOrCreateDiagAccount(hs) { const cached = readCache(hs); if (cached) return cached; const acct = await register(hs); mkdirSync(dirname(CACHE), { recursive: true }); writeFileSync(CACHE, JSON.stringify(acct, null, 2)); return acct; }