identity.mjs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (c) 未来飞马
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
  6. //
  7. // Trademark Notice:
  8. // The MPL-2.0 license grants copyright permissions for source code only.
  9. // It does NOT grant any rights to use trademarks including "未来飞马",
  10. // "Harness Loop", "RSI", and associated slogan "让AI进化提前发生,让AI落地快人一步".
  11. // Any use of these trademarks requires separate written permission.
  12. import { readFileSync, existsSync } from 'node:fs';
  13. import { hostname, homedir } from 'node:os';
  14. // 读取 JSON 文件,自动剥 BOM,失败返回 null
  15. function readJson(p) {
  16. if (!existsSync(p)) return null;
  17. try {
  18. const raw = readFileSync(p, 'utf-8').replace(/^/, '');
  19. return JSON.parse(raw);
  20. } catch {
  21. return null;
  22. }
  23. }
  24. /**
  25. * 身份解析高兼容链:
  26. * userid: FMODE_USERID → FMODE_AGENT_USERID → /opt/data/fmode-identity.json → $HOME/.fmode/config.json → ./.fmode/config.json
  27. * sessionToken: FMODE_SESSION_TOKEN → $HOME/.fmode/config/user.json → $HOME/.fmode/config.json → ./.fmode/config.json
  28. * agentId: FMODE_AGENT_ID → AGENT_ID → $HOME/.fmode/config.json → hostname()
  29. *
  30. * $HOME 容器 hermes 用户 = /opt/data;root 用户 = /root;两处都能命中。
  31. */
  32. export function resolveIdentity() {
  33. const home = process.env.HOME || homedir();
  34. const userid =
  35. process.env.FMODE_USERID ||
  36. process.env.FMODE_AGENT_USERID ||
  37. readJson('/opt/data/fmode-identity.json')?.userid ||
  38. readJson(`${home}/.fmode/config.json`)?.userid ||
  39. readJson('./.fmode/config.json')?.userid ||
  40. null;
  41. const sessionToken =
  42. process.env.FMODE_SESSION_TOKEN ||
  43. readJson(`${home}/.fmode/config/user.json`)?.sessionToken ||
  44. readJson(`${home}/.fmode/config.json`)?.sessionToken ||
  45. readJson('./.fmode/config.json')?.sessionToken ||
  46. null;
  47. const agentId =
  48. process.env.FMODE_AGENT_ID ||
  49. process.env.AGENT_ID ||
  50. readJson(`${home}/.fmode/config.json`)?.agentId ||
  51. hostname();
  52. return { userid, sessionToken, agentId };
  53. }
  54. /** 仅打印身份摘要(不暴露密钥本体)*/
  55. export function identitySummary(identity) {
  56. const { userid, sessionToken, agentId } = identity;
  57. return {
  58. userid: userid || '(未找到)',
  59. sessionToken: sessionToken
  60. ? `${sessionToken.slice(0, 8)}... (${sessionToken.length} 字符)`
  61. : '(未找到)',
  62. agentId,
  63. };
  64. }