diag-mx-account.mjs 2.7 KB

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