magpie-plugin-loomy-auth 0.1.18 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/chat.mjs CHANGED
@@ -1,12 +1,14 @@
1
1
  // Loomy · 请求接管(loader 的 fetch)
2
2
  //
3
- // 只做四件事,其余原样转发(上游本来就是 OpenAI 协议,不做协议转换):
3
+ // 只做五件事,其余原样转发(上游本来就是 OpenAI 协议,不做协议转换):
4
4
  //
5
5
  // ① 换成 Loomy 的 token 双头(AI SDK 发的 Bearer 是占位值,必须覆盖)
6
6
  // ② deepseek 系模型:把 `image_url` data URI 改写成 `<image_base64>` 标记
7
7
  // ③ HTTP 200 + 信封 `{code:"100002"}` 的失效响应 → 打上
8
8
  // `X-Magpie-Sign-In: expired`(magpie 据此标记账号)
9
9
  // ④ 本地额度闸:**已知**两池皆空时直接回 429,不白撞上游
10
+ // ⑤ 「内容太长了」的 400/413/422 → 把文案换成 magpie `tooLongRe` 认得的中文写法,
11
+ // 否则整轮会话会以 400 失败(详见 `rewriteTooLongRefusal` 的注释)
10
12
  //
11
13
  // ⚠ SSE 一律原样透传:解析 clone 会把整条流缓冲住,用户看到的是「一直不出字」。
12
14
  // 所以只有 `content-type: application/json` 才 clone 来判业务码。
@@ -91,9 +93,68 @@ export async function chatFetch({ input, init, credential, session, usageValue }
91
93
  }
92
94
  }
93
95
 
96
+ // ⑤ 上游用 400 说「内容太长了」,但**它并不总是真的超长**(实测 2026-10-30):
97
+ // 同一天里 838,400 token 的请求成功,373,924 token 的却被这样拒绝;
98
+ // 同一时段还有 `429 模型服务当前繁忙` —— 这条 400 更像过载时的通用文案。
99
+ //
100
+ // 所以按**请求体大小**分流,而不是一律当长度问题:
101
+ // · 请求体远小于模型声明上限 ⇒ 不是长度问题 ⇒ 502(magpie 换号重试,几秒钟)
102
+ // · 请求体确实很大 ⇒ 真是长度问题 ⇒ 改写成 `tooLongRe` 认得的中文写法
103
+ // (magpie 据此让 agent 压缩上下文,而不是整轮失败)
104
+ const tooLong = await rewriteTooLongRefusal(response, bodyText.length)
105
+ if (tooLong) return tooLong
106
+
94
107
  return response
95
108
  }
96
109
 
110
+ /** 「内容太长」的几种中文说法 —— 上游只说了长度,没说「上下文」 */
111
+ const TOO_LONG_SAID = /内容太长(了)?|内容过长/
112
+ /** 换成 magpie `tooLongRe` 认得的中文写法(`上下文…超` 命中) */
113
+ const TOO_LONG_REWORDED = "上下文超出长度限制"
114
+
115
+ /**
116
+ * 请求体小于这个字符数,就不可能是「超过模型上限」。
117
+ *
118
+ * 判据(2026-10-30 实测):Loomy 的 DeepSeek-V4.1-Flash 声明 1,048,576 token,
119
+ * 而 **838,400 token 的请求是成功的**;按 2~4 字符/token 折算约 200~330 万字符。
120
+ * 取 200 万字符作界,落在它下面的一律当「上游瞬时错误」而不是长度问题。
121
+ */
122
+ const NOT_TOO_LONG_MAX_CHARS = 2_000_000
123
+
124
+ /**
125
+ * 处理「内容太长了」的 400/413/422:
126
+ * · 请求体不大 → 502(让 magpie 换号重试)
127
+ * · 请求体确实大 → 改写成 `tooLongRe` 认得的中文写法,状态码不变
128
+ *
129
+ * ⚠ 只读 400/413/422 的响应体(错误响应很小),其它状态码连 clone 都不做。
130
+ * ⚠ 只换那一句文案;JSON 结构、其它字段、状态码保留。解析/读取失败一律原样返回。
131
+ */
132
+ async function rewriteTooLongRefusal(response, requestChars = 0) {
133
+ const status = response?.status
134
+ if (status !== 400 && status !== 413 && status !== 422) return null
135
+ let text
136
+ try {
137
+ // clone 之后再读:不改写时把原 Response 原样交回去
138
+ text = await response.clone().text()
139
+ } catch {
140
+ return null
141
+ }
142
+ if (!TOO_LONG_SAID.test(text)) return null
143
+
144
+ // 请求体远小于上限 ⇒ 这不是长度问题,是上游的瞬时错误(过载时它就这么说)
145
+ const momentary = requestChars > 0 && requestChars < NOT_TOO_LONG_MAX_CHARS
146
+ const rewritten = momentary ? text : text.replace(TOO_LONG_SAID, TOO_LONG_REWORDED)
147
+ const outStatus = momentary ? 502 : status
148
+ const headers = new Headers(response.headers)
149
+ // body 长度变了,原来的长度/编码头不再成立
150
+ headers.delete("content-length")
151
+ headers.delete("content-encoding")
152
+ // 排障用:上游原本是几、我们判成了什么
153
+ headers.set("x-loomy-vendor-status", String(status))
154
+ if (momentary) headers.set("x-loomy-classified", "momentary")
155
+ return new Response(rewritten, { status: outStatus, statusText: response.statusText, headers })
156
+ }
157
+
97
158
  function jsonResponse(status, payload) {
98
159
  return new Response(JSON.stringify(payload), {
99
160
  status,
@@ -101,4 +162,4 @@ function jsonResponse(status, payload) {
101
162
  })
102
163
  }
103
164
 
104
- export { businessCode, isAuthErrorCode }
165
+ export { businessCode, isAuthErrorCode, rewriteTooLongRefusal }
package/src/constants.mjs CHANGED
@@ -1,72 +1,72 @@
1
- // Loomy(讯飞)供应商插件 · 常量
2
- //
3
- // 两个网关(实测,2026-10-26):
4
- // 业务/积分/模型目录 https://loomyad.xunfei.cn 鉴权 = token 双头(session)
5
- // 账号/短信登录 https://account.xfinfr.com 鉴权 = HMAC-SHA1 签名(公开客户端常量)
6
-
7
- export { ICON } from "./icon.mjs"
8
-
9
- export const PROVIDER = "loomy"
10
- export const PROVIDER_NAME = "Loomy"
11
-
12
- export const INTEGRATION_BASE = trim(process.env.LOOMY_POINTS_BASE_URL) || "https://loomyad.xunfei.cn"
13
- export const XFYUN_ACCOUNT_BASE =
14
- trim(process.env.LOOMY_ACCOUNT_BASE_URL) || "https://account.xfinfr.com"
15
-
16
- export const NPM = "@ai-sdk/openai-compatible"
17
-
18
- /** Loomy 无续期接口:会话固定 14 天(上游 expire=14d),到期只能重登。 */
19
- export const SESSION_TTL_MS = 14 * 24 * 3600_000
20
-
21
- /** 模型目录进程内缓存 */
22
- export const CATALOG_TTL_MS = 10 * 60_000
23
-
24
- /**
25
- * 额度进程内缓存(成功)。
26
- *
27
- * ⚠ 这个 TTL 同时也是**请求热路径上的额度闸**(chat 前读同一份缓存判耗尽),
28
- * 所以不能长:耗尽后最多再漏 60 秒的请求。
29
- * ⚠ 成功与失败分别存:失败短 TTL,否则一次网络抖动会让界面 60 秒都显示
30
- * 「查询失败」,用户重试也没用。
31
- */
32
- export const USAGE_CACHE_TTL_MS = 60_000
33
- export const USAGE_FAIL_TTL_MS = 5_000
34
-
35
- /**
36
- * 耗尽闸的提前量:剩余额度低于这个值就**按已耗尽处理**。
37
- *
38
- * 为什么:每日池耗尽时上游的报错形态是 HTTP 400「积分余额不足」,
39
- * 会白烧一次请求还可能被 harness 归类重试;而本地余额读数最多旧 60 秒。
40
- * 留 1 分的提前量,宁可早停 1 分也不要撞上游报错。
41
- */
42
- export const USAGE_LEAD_POINTS = 1
43
-
44
- /** 推导每日池上限时翻流水的上限(条/页)。 */
45
- export const LEDGER_PAGE_SIZE = 100
46
- export const LEDGER_MAX_PAGES = 6
47
-
48
- export const SUCCESS_CODE = "000000"
49
- /** 登录态失效的业务码(上游部分错误是 HTTP 200 + 信封 code)。 */
50
- export const AUTH_ERROR_CODES = ["020002", "100002"]
51
-
52
- export const REQUEST_TIMEOUT_MS = 20_000
53
- export const CHAT_TIMEOUT_MS = 300_000
54
-
55
- /** 上游业务日按东八区计(实测 dailyCycleDate 与北京时间一致)。 */
56
- export const BEIJING_UTC_OFFSET_MS = 8 * 3600_000
57
-
58
- // ── 账号接口的公开客户端常量(随 Loomy 客户端分发,不是用户凭据)──
59
- // 配了环境变量就用用户的(常量被厂商旋转时自救)。
60
- export const SIGN_ACCESS_KEY_ID = trim(process.env.LOOMY_XFYUN_ACCESS_KEY_ID) || "2thryby66wxi53sk"
61
- export const SIGN_ACCESS_KEY_SECRET =
62
- trim(process.env.LOOMY_XFYUN_ACCESS_KEY_SECRET) || "zsak6eadrbawz683wf5r3m2snrwj868r"
63
- export const APP_ID = trim(process.env.LOOMY_XFYUN_APP_ID) || "GM3LOOMY"
64
-
65
- export const CLIENT_MODEL_ID = "Web"
66
- export const CLIENT_DEVICE_ID = "web"
67
- export const CLIENT_UA = "Loomy|Desktop|Electron|macOS"
68
- export const CLIENT_VERSION = "1.0.0"
69
-
70
- function trim(v) {
71
- return typeof v === "string" ? v.trim().replace(/\/+$/, "") : ""
72
- }
1
+ // Loomy(讯飞)供应商插件 · 常量
2
+ //
3
+ // 两个网关(实测,2026-10-26):
4
+ // 业务/积分/模型目录 https://loomyad.xunfei.cn 鉴权 = token 双头(session)
5
+ // 账号/短信登录 https://account.xfinfr.com 鉴权 = HMAC-SHA1 签名(公开客户端常量)
6
+
7
+ export { ICON } from "./icon.mjs"
8
+
9
+ export const PROVIDER = "loomy"
10
+ export const PROVIDER_NAME = "讯飞 Loomy"
11
+
12
+ export const INTEGRATION_BASE = trim(process.env.LOOMY_POINTS_BASE_URL) || "https://loomyad.xunfei.cn"
13
+ export const XFYUN_ACCOUNT_BASE =
14
+ trim(process.env.LOOMY_ACCOUNT_BASE_URL) || "https://account.xfinfr.com"
15
+
16
+ export const NPM = "@ai-sdk/openai-compatible"
17
+
18
+ /** Loomy 无续期接口:会话固定 14 天(上游 expire=14d),到期只能重登。 */
19
+ export const SESSION_TTL_MS = 14 * 24 * 3600_000
20
+
21
+ /** 模型目录进程内缓存 */
22
+ export const CATALOG_TTL_MS = 10 * 60_000
23
+
24
+ /**
25
+ * 额度进程内缓存(成功)。
26
+ *
27
+ * ⚠ 这个 TTL 同时也是**请求热路径上的额度闸**(chat 前读同一份缓存判耗尽),
28
+ * 所以不能长:耗尽后最多再漏 60 秒的请求。
29
+ * ⚠ 成功与失败分别存:失败短 TTL,否则一次网络抖动会让界面 60 秒都显示
30
+ * 「查询失败」,用户重试也没用。
31
+ */
32
+ export const USAGE_CACHE_TTL_MS = 60_000
33
+ export const USAGE_FAIL_TTL_MS = 5_000
34
+
35
+ /**
36
+ * 耗尽闸的提前量:剩余额度低于这个值就**按已耗尽处理**。
37
+ *
38
+ * 为什么:每日池耗尽时上游的报错形态是 HTTP 400「积分余额不足」,
39
+ * 会白烧一次请求还可能被 harness 归类重试;而本地余额读数最多旧 60 秒。
40
+ * 留 1 分的提前量,宁可早停 1 分也不要撞上游报错。
41
+ */
42
+ export const USAGE_LEAD_POINTS = 1
43
+
44
+ /** 推导每日池上限时翻流水的上限(条/页)。 */
45
+ export const LEDGER_PAGE_SIZE = 100
46
+ export const LEDGER_MAX_PAGES = 6
47
+
48
+ export const SUCCESS_CODE = "000000"
49
+ /** 登录态失效的业务码(上游部分错误是 HTTP 200 + 信封 code)。 */
50
+ export const AUTH_ERROR_CODES = ["020002", "100002"]
51
+
52
+ export const REQUEST_TIMEOUT_MS = 20_000
53
+ export const CHAT_TIMEOUT_MS = 300_000
54
+
55
+ /** 上游业务日按东八区计(实测 dailyCycleDate 与北京时间一致)。 */
56
+ export const BEIJING_UTC_OFFSET_MS = 8 * 3600_000
57
+
58
+ // ── 账号接口的公开客户端常量(随 Loomy 客户端分发,不是用户凭据)──
59
+ // 配了环境变量就用用户的(常量被厂商旋转时自救)。
60
+ export const SIGN_ACCESS_KEY_ID = trim(process.env.LOOMY_XFYUN_ACCESS_KEY_ID) || "2thryby66wxi53sk"
61
+ export const SIGN_ACCESS_KEY_SECRET =
62
+ trim(process.env.LOOMY_XFYUN_ACCESS_KEY_SECRET) || "zsak6eadrbawz683wf5r3m2snrwj868r"
63
+ export const APP_ID = trim(process.env.LOOMY_XFYUN_APP_ID) || "GM3LOOMY"
64
+
65
+ export const CLIENT_MODEL_ID = "Web"
66
+ export const CLIENT_DEVICE_ID = "web"
67
+ export const CLIENT_UA = "Loomy|Desktop|Electron|macOS"
68
+ export const CLIENT_VERSION = "1.0.0"
69
+
70
+ function trim(v) {
71
+ return typeof v === "string" ? v.trim().replace(/\/+$/, "") : ""
72
+ }
package/src/desktop.mjs CHANGED
@@ -1,173 +1,173 @@
1
- // Loomy · 桌面端登录态导入
2
- //
3
- // Loomy 是 Electron 应用,登录态以**明文 JSON** 存在 Chromium 的 Local Storage
4
- // (leveldb)里,键名 `loomy-auth-session`:
5
- // {"phone":…, "maskedPhone":…, "session":…, "userid":…, "loggedInAt":…}
6
- // 无加密、无 DPAPI —— 实测(Loomy 0.9.39,Windows)`000003.log` 里可直接读出
7
- // session,且该 session 能打通 `/api/v1/models` 与积分接口。
8
- //
9
- // ⚠ leveldb 的 log 是**追加写**的:同一个键可能有多份,新的在后。
10
- // 所以从后往前找,拿到的才是当前登录态。
11
- // ⚠ 只读取本机自己的客户端存储,不碰任何别的用户数据;读不到就返回 null,
12
- // 由上层提示「请先打开 Loomy 客户端登录」而不是报错。
13
-
14
- import { readFileSync, readdirSync } from "node:fs"
15
- import path from "node:path"
16
- import os from "node:os"
17
-
18
- const DESKTOP_SESSION_KEY = "loomy-auth-session"
19
-
20
- export function desktopStorageDirs() {
21
- const home = os.homedir()
22
- const dirs = []
23
- if (process.platform === "win32") {
24
- const appData = process.env.APPDATA || path.join(home, "AppData", "Roaming")
25
- dirs.push(path.join(appData, "Loomy", "Local Storage", "leveldb"))
26
- } else if (process.platform === "darwin") {
27
- dirs.push(path.join(home, "Library", "Application Support", "Loomy", "Local Storage", "leveldb"))
28
- } else {
29
- const cfg = process.env.XDG_CONFIG_HOME || path.join(home, ".config")
30
- dirs.push(path.join(cfg, "Loomy", "Local Storage", "leveldb"))
31
- }
32
- return dirs
33
- }
34
-
35
- /** 读本机 Loomy 桌面端登录态;没有返回 null。 */
36
- export function readDesktopSession() {
37
- for (const dir of desktopStorageDirs()) {
38
- const value = readSessionFrom(dir)
39
- if (value) return value
40
- }
41
- return null
42
- }
43
-
44
- export function readSessionFrom(dir) {
45
- let entries
46
- try {
47
- entries = readdirSync(dir, { withFileTypes: true })
48
- } catch {
49
- return null
50
- }
51
- const logs = entries
52
- .filter((e) => e.isFile() && e.name.endsWith(".log"))
53
- .map((e) => e.name)
54
- .sort()
55
- .reverse() // 新的在后 ⇒ 从后往前
56
-
57
- for (const name of logs) {
58
- let bytes
59
- try {
60
- bytes = readFileSync(path.join(dir, name))
61
- } catch {
62
- continue
63
- }
64
- const key = new TextEncoder().encode(DESKTOP_SESSION_KEY)
65
- let at = bytes.lastIndexOf(key)
66
- while (at >= 0) {
67
- const value = jsonAfter(bytes, at + key.length)
68
- if (value && typeof value.session === "string" && value.session.trim()) return value
69
- at = bytes.lastIndexOf(key, at - 1)
70
- }
71
- }
72
- return null
73
- }
74
-
75
- /**
76
- * 从字节串里取 key 之后那个完整的 JSON 对象(括号配对,跳过字符串里的括号)。
77
- * 容错:截断的写入解析失败就返回 null,由调用方继续往前找。
78
- */
79
- export function jsonAfter(bytes, from) {
80
- const open = bytes.indexOf(0x7b, from) // "{"
81
- if (open < 0) return null
82
- let depth = 0
83
- for (let i = open; i < bytes.length; i++) {
84
- const byte = bytes[i]
85
- if (byte === 0x22) {
86
- // 跳过字符串字面量,括号配对不受其内容干扰
87
- i++
88
- while (i < bytes.length && bytes[i] !== 0x22) {
89
- if (bytes[i] === 0x5c) i++ // 反斜杠转义
90
- i++
91
- }
92
- continue
93
- }
94
- if (byte === 0x7b) depth++
95
- else if (byte === 0x7d && --depth === 0) {
96
- try {
97
- return JSON.parse(bytes.subarray(open, i + 1).toString("utf8"))
98
- } catch {
99
- return null
100
- }
101
- }
102
- }
103
- return null
104
- }
105
-
106
- // ════════════════════════════════════════════════════════════════════
107
- // 本机已有的 Loomy 账号(读 magpie 的凭据文件)
108
- // ════════════════════════════════════════════════════════════════════
109
- //
110
- // 为什么要读文件:`getAuth()` 只在**当前账号作用域**里可见(magpie 的 inScope),
111
- // 拿不到同一 provider 下的**其它**账号。而「用已有账号的邀请码邀请新账号」
112
- // 这件事,恰恰需要知道别的账号是什么 —— 只能直接读 `plugin-auth.json`。
113
- //
114
- // ⚠ 只读、只取 `access`(session),不打印、不外传。
115
- // ⚠ 只认 `loomy` 与 `loomy#xxxxxx` 两种键(magpie 的多账号命名)。
116
- // ⚠ 读不到就当没有:登录流程不能因为读凭据失败而失败。
117
-
118
- /** magpie 的凭据文件位置(与 `~/.config/magpie` 一致;DSH/MAGPIE 目录可用环境变量覆盖)。 */
119
- export function authFilePath() {
120
- if (process.env.MAGPIE_AUTH_FILE) return process.env.MAGPIE_AUTH_FILE
121
- const home = os.homedir()
122
- const cfg = process.env.XDG_CONFIG_HOME || path.join(home, ".config")
123
- return path.join(cfg, "magpie", "plugin-auth.json")
124
- }
125
-
126
- /**
127
- * 本机所有 Loomy 账号的 session(**排除** excludeSession)。
128
- *
129
- * 顺序稳定(`loomy` 在前,其余按名排序),方便「优先用主账号的邀请码」。
130
- */
131
- export function readAllLoomySessions(excludeSession) {
132
- let raw
133
- try {
134
- raw = JSON.parse(readFileSync(authFilePath(), "utf8"))
135
- } catch {
136
- return []
137
- }
138
- if (!raw || typeof raw !== "object") return []
139
-
140
- const keys = Object.keys(raw)
141
- .filter((k) => k === "loomy" || k.startsWith("loomy#"))
142
- .sort((a, b) => (a === "loomy" ? -1 : b === "loomy" ? 1 : a.localeCompare(b)))
143
-
144
- const out = []
145
- for (const key of keys) {
146
- const rec = raw[key]
147
- const session = typeof rec?.access === "string" ? rec.access.trim() : ""
148
- if (!session) continue
149
- if (excludeSession && session === excludeSession) continue
150
- if (!out.includes(session)) out.push(session)
151
- }
152
- return out
153
- }
154
-
155
- /** 本机所有 Loomy 账号的 `{key, session, phone}`(供挑选邀请码时排除自己)。 */
156
- export function readAllLoomyAccounts() {
157
- let raw
158
- try {
159
- raw = JSON.parse(readFileSync(authFilePath(), "utf8"))
160
- } catch {
161
- return []
162
- }
163
- if (!raw || typeof raw !== "object") return []
164
- return Object.keys(raw)
165
- .filter((k) => k === "loomy" || k.startsWith("loomy#"))
166
- .sort((a, b) => (a === "loomy" ? -1 : b === "loomy" ? 1 : a.localeCompare(b)))
167
- .map((key) => ({
168
- key,
169
- session: typeof raw[key]?.access === "string" ? raw[key].access.trim() : "",
170
- phone: typeof raw[key]?.phone === "string" ? raw[key].phone : "",
171
- }))
172
- .filter((x) => x.session)
173
- }
1
+ // Loomy · 桌面端登录态导入
2
+ //
3
+ // Loomy 是 Electron 应用,登录态以**明文 JSON** 存在 Chromium 的 Local Storage
4
+ // (leveldb)里,键名 `loomy-auth-session`:
5
+ // {"phone":…, "maskedPhone":…, "session":…, "userid":…, "loggedInAt":…}
6
+ // 无加密、无 DPAPI —— 实测(Loomy 0.9.39,Windows)`000003.log` 里可直接读出
7
+ // session,且该 session 能打通 `/api/v1/models` 与积分接口。
8
+ //
9
+ // ⚠ leveldb 的 log 是**追加写**的:同一个键可能有多份,新的在后。
10
+ // 所以从后往前找,拿到的才是当前登录态。
11
+ // ⚠ 只读取本机自己的客户端存储,不碰任何别的用户数据;读不到就返回 null,
12
+ // 由上层提示「请先打开 Loomy 客户端登录」而不是报错。
13
+
14
+ import { readFileSync, readdirSync } from "node:fs"
15
+ import path from "node:path"
16
+ import os from "node:os"
17
+
18
+ const DESKTOP_SESSION_KEY = "loomy-auth-session"
19
+
20
+ export function desktopStorageDirs() {
21
+ const home = os.homedir()
22
+ const dirs = []
23
+ if (process.platform === "win32") {
24
+ const appData = process.env.APPDATA || path.join(home, "AppData", "Roaming")
25
+ dirs.push(path.join(appData, "Loomy", "Local Storage", "leveldb"))
26
+ } else if (process.platform === "darwin") {
27
+ dirs.push(path.join(home, "Library", "Application Support", "Loomy", "Local Storage", "leveldb"))
28
+ } else {
29
+ const cfg = process.env.XDG_CONFIG_HOME || path.join(home, ".config")
30
+ dirs.push(path.join(cfg, "Loomy", "Local Storage", "leveldb"))
31
+ }
32
+ return dirs
33
+ }
34
+
35
+ /** 读本机 Loomy 桌面端登录态;没有返回 null。 */
36
+ export function readDesktopSession() {
37
+ for (const dir of desktopStorageDirs()) {
38
+ const value = readSessionFrom(dir)
39
+ if (value) return value
40
+ }
41
+ return null
42
+ }
43
+
44
+ export function readSessionFrom(dir) {
45
+ let entries
46
+ try {
47
+ entries = readdirSync(dir, { withFileTypes: true })
48
+ } catch {
49
+ return null
50
+ }
51
+ const logs = entries
52
+ .filter((e) => e.isFile() && e.name.endsWith(".log"))
53
+ .map((e) => e.name)
54
+ .sort()
55
+ .reverse() // 新的在后 ⇒ 从后往前
56
+
57
+ for (const name of logs) {
58
+ let bytes
59
+ try {
60
+ bytes = readFileSync(path.join(dir, name))
61
+ } catch {
62
+ continue
63
+ }
64
+ const key = new TextEncoder().encode(DESKTOP_SESSION_KEY)
65
+ let at = bytes.lastIndexOf(key)
66
+ while (at >= 0) {
67
+ const value = jsonAfter(bytes, at + key.length)
68
+ if (value && typeof value.session === "string" && value.session.trim()) return value
69
+ at = bytes.lastIndexOf(key, at - 1)
70
+ }
71
+ }
72
+ return null
73
+ }
74
+
75
+ /**
76
+ * 从字节串里取 key 之后那个完整的 JSON 对象(括号配对,跳过字符串里的括号)。
77
+ * 容错:截断的写入解析失败就返回 null,由调用方继续往前找。
78
+ */
79
+ export function jsonAfter(bytes, from) {
80
+ const open = bytes.indexOf(0x7b, from) // "{"
81
+ if (open < 0) return null
82
+ let depth = 0
83
+ for (let i = open; i < bytes.length; i++) {
84
+ const byte = bytes[i]
85
+ if (byte === 0x22) {
86
+ // 跳过字符串字面量,括号配对不受其内容干扰
87
+ i++
88
+ while (i < bytes.length && bytes[i] !== 0x22) {
89
+ if (bytes[i] === 0x5c) i++ // 反斜杠转义
90
+ i++
91
+ }
92
+ continue
93
+ }
94
+ if (byte === 0x7b) depth++
95
+ else if (byte === 0x7d && --depth === 0) {
96
+ try {
97
+ return JSON.parse(bytes.subarray(open, i + 1).toString("utf8"))
98
+ } catch {
99
+ return null
100
+ }
101
+ }
102
+ }
103
+ return null
104
+ }
105
+
106
+ // ════════════════════════════════════════════════════════════════════
107
+ // 本机已有的 Loomy 账号(读 magpie 的凭据文件)
108
+ // ════════════════════════════════════════════════════════════════════
109
+ //
110
+ // 为什么要读文件:`getAuth()` 只在**当前账号作用域**里可见(magpie 的 inScope),
111
+ // 拿不到同一 provider 下的**其它**账号。而「用已有账号的邀请码邀请新账号」
112
+ // 这件事,恰恰需要知道别的账号是什么 —— 只能直接读 `plugin-auth.json`。
113
+ //
114
+ // ⚠ 只读、只取 `access`(session),不打印、不外传。
115
+ // ⚠ 只认 `loomy` 与 `loomy#xxxxxx` 两种键(magpie 的多账号命名)。
116
+ // ⚠ 读不到就当没有:登录流程不能因为读凭据失败而失败。
117
+
118
+ /** magpie 的凭据文件位置(与 `~/.config/magpie` 一致;DSH/MAGPIE 目录可用环境变量覆盖)。 */
119
+ export function authFilePath() {
120
+ if (process.env.MAGPIE_AUTH_FILE) return process.env.MAGPIE_AUTH_FILE
121
+ const home = os.homedir()
122
+ const cfg = process.env.XDG_CONFIG_HOME || path.join(home, ".config")
123
+ return path.join(cfg, "magpie", "plugin-auth.json")
124
+ }
125
+
126
+ /**
127
+ * 本机所有 Loomy 账号的 session(**排除** excludeSession)。
128
+ *
129
+ * 顺序稳定(`loomy` 在前,其余按名排序),方便「优先用主账号的邀请码」。
130
+ */
131
+ export function readAllLoomySessions(excludeSession) {
132
+ let raw
133
+ try {
134
+ raw = JSON.parse(readFileSync(authFilePath(), "utf8"))
135
+ } catch {
136
+ return []
137
+ }
138
+ if (!raw || typeof raw !== "object") return []
139
+
140
+ const keys = Object.keys(raw)
141
+ .filter((k) => k === "loomy" || k.startsWith("loomy#"))
142
+ .sort((a, b) => (a === "loomy" ? -1 : b === "loomy" ? 1 : a.localeCompare(b)))
143
+
144
+ const out = []
145
+ for (const key of keys) {
146
+ const rec = raw[key]
147
+ const session = typeof rec?.access === "string" ? rec.access.trim() : ""
148
+ if (!session) continue
149
+ if (excludeSession && session === excludeSession) continue
150
+ if (!out.includes(session)) out.push(session)
151
+ }
152
+ return out
153
+ }
154
+
155
+ /** 本机所有 Loomy 账号的 `{key, session, phone}`(供挑选邀请码时排除自己)。 */
156
+ export function readAllLoomyAccounts() {
157
+ let raw
158
+ try {
159
+ raw = JSON.parse(readFileSync(authFilePath(), "utf8"))
160
+ } catch {
161
+ return []
162
+ }
163
+ if (!raw || typeof raw !== "object") return []
164
+ return Object.keys(raw)
165
+ .filter((k) => k === "loomy" || k.startsWith("loomy#"))
166
+ .sort((a, b) => (a === "loomy" ? -1 : b === "loomy" ? 1 : a.localeCompare(b)))
167
+ .map((key) => ({
168
+ key,
169
+ session: typeof raw[key]?.access === "string" ? raw[key].access.trim() : "",
170
+ phone: typeof raw[key]?.phone === "string" ? raw[key].phone : "",
171
+ }))
172
+ .filter((x) => x.session)
173
+ }