magpie-plugin-loomy-auth 0.1.26 → 0.1.36
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/AGENTS.md +11 -1
- package/CHANGELOG.md +75 -0
- package/CHECKLIST.md +11 -5
- package/README.md +61 -97
- package/docs/internals.md +140 -374
- package/docs/security.md +67 -0
- package/index.mjs +31 -78
- package/package.json +2 -2
- package/src/api.mjs +44 -0
- package/src/chat.mjs +43 -8
- package/src/constants.mjs +18 -2
- package/src/hardening.mjs +59 -0
- package/src/invite-store.mjs +141 -0
- package/src/models.mjs +63 -19
- package/src/prompt.mjs +69 -0
- package/src/team-mode.mjs +70 -0
- package/src/team.mjs +74 -0
- package/src/tracing.mjs +113 -0
- package/src/usage.mjs +15 -3
- package/src/desktop.mjs +0 -173
package/index.mjs
CHANGED
|
@@ -69,14 +69,18 @@ import {
|
|
|
69
69
|
INTEGRATION_BASE,
|
|
70
70
|
} from "./src/constants.mjs"
|
|
71
71
|
import { claimDailyQuota, loginBySmsCode, fetchBalances, sendSmsCode, fetchOnboarding, claimAllTasks, fetchInviteCodes, bindInviteCode, fetchActivation } from "./src/api.mjs"
|
|
72
|
-
import { readDesktopSession, readAllLoomySessions, readAllLoomyAccounts } from "./src/desktop.mjs"
|
|
73
72
|
import { staticModels, liveModels } from "./src/models.mjs"
|
|
74
73
|
import { readUsage, publicUsage, quotaToRemember, clearUsageCache } from "./src/usage.mjs"
|
|
75
74
|
import { chatFetch } from "./src/chat.mjs"
|
|
75
|
+
import { inviteCandidates, ownerTag, rememberInviteCodes } from "./src/invite-store.mjs"
|
|
76
|
+
import { createTeamModeController } from "./src/team-mode.mjs"
|
|
76
77
|
|
|
77
78
|
const API_URL = `${INTEGRATION_BASE}/api/v1`
|
|
78
79
|
|
|
79
|
-
export const LoomyAuthPlugin = async ({ client } = {}) => {
|
|
80
|
+
export const LoomyAuthPlugin = async ({ client, magpie } = {}) => {
|
|
81
|
+
const teamMode = magpie?.option ? createTeamModeController({
|
|
82
|
+
readOption: () => magpie.option(PROVIDER, "team_mode") === true,
|
|
83
|
+
}) : null
|
|
80
84
|
const log = (message, level = "info") => {
|
|
81
85
|
try {
|
|
82
86
|
client?.app?.log?.({ service: "loomy", level, message })
|
|
@@ -129,27 +133,11 @@ export const LoomyAuthPlugin = async ({ client } = {}) => {
|
|
|
129
133
|
* ⚠ 结果按分钟缓存:登录是低频操作,但三个 provider id 会各扫一遍,
|
|
130
134
|
* 没必要每次都打 N 个只读请求。
|
|
131
135
|
*/
|
|
132
|
-
const inviteCodeCache = new Map() // session -> { at, codes }
|
|
133
|
-
const INVITE_CACHE_TTL_MS = 60_000
|
|
134
136
|
|
|
135
137
|
const collectInviteCandidates = async (excludeSession) => {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
const hit = inviteCodeCache.get(session)
|
|
140
|
-
if (hit && Date.now() - hit.at < INVITE_CACHE_TTL_MS) {
|
|
141
|
-
out.push(...hit.codes)
|
|
142
|
-
continue
|
|
143
|
-
}
|
|
144
|
-
try {
|
|
145
|
-
const codes = await fetchInviteCodes(session)
|
|
146
|
-
inviteCodeCache.set(session, { at: Date.now(), codes })
|
|
147
|
-
out.push(...codes)
|
|
148
|
-
} catch {
|
|
149
|
-
// 这个号查不到就跳过,不影响其它号
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
return out
|
|
138
|
+
// 来源是**插件自己攒的**邀请码库(src/invite-store.mjs),不读官方客户端:
|
|
139
|
+
// 哪个号登录过,就把它的邀请码记下来,后面的新号从这里挑。
|
|
140
|
+
return inviteCandidates(excludeSession)
|
|
153
141
|
}
|
|
154
142
|
|
|
155
143
|
/**
|
|
@@ -188,6 +176,12 @@ export const LoomyAuthPlugin = async ({ client } = {}) => {
|
|
|
188
176
|
try {
|
|
189
177
|
const mine = await fetchInviteCodes(session)
|
|
190
178
|
selfCode = mine[0]?.code
|
|
179
|
+
// 顺手把自己的码记进本地库:下一个新号登录时就有候选可挑
|
|
180
|
+
try {
|
|
181
|
+
rememberInviteCodes(mine, { owner: ownerTag(session) })
|
|
182
|
+
} catch {
|
|
183
|
+
// 记不住不影响本次
|
|
184
|
+
}
|
|
191
185
|
} catch {
|
|
192
186
|
selfCode = undefined
|
|
193
187
|
}
|
|
@@ -251,66 +245,13 @@ export const LoomyAuthPlugin = async ({ client } = {}) => {
|
|
|
251
245
|
provider: PROVIDER,
|
|
252
246
|
icon: ICON,
|
|
253
247
|
maxConcurrency: 4,
|
|
248
|
+
get options() { return teamMode?.options() ?? [] },
|
|
254
249
|
// Loomy 没有续期接口;这个值只影响 magpie 何时「尝试」续期,
|
|
255
250
|
// 而 refresh 恒返回 undefined,所以不会真的去续。
|
|
256
251
|
refreshLead: 60_000,
|
|
257
252
|
|
|
258
253
|
// ═══ ② 登录 ═══════════════════════════════════════════════════
|
|
259
254
|
methods: [
|
|
260
|
-
{
|
|
261
|
-
type: "oauth",
|
|
262
|
-
label: "Loomy 桌面端登录态(自动读取本机客户端)",
|
|
263
|
-
/**
|
|
264
|
-
* ⚠ 立刻返回:真正的等待在 callback 里。这里只做一次同步读盘 + 校验。
|
|
265
|
-
* (读盘是毫秒级的,但校验要发一次请求 —— 也放在 callback 里做,
|
|
266
|
-
* 免得 authorize 卡住导致 magpie 拿不到 url 而死锁。)
|
|
267
|
-
*/
|
|
268
|
-
authorize: async () => {
|
|
269
|
-
const desktop = readDesktopSession()
|
|
270
|
-
if (!desktop) {
|
|
271
|
-
return {
|
|
272
|
-
type: "failed",
|
|
273
|
-
error:
|
|
274
|
-
"没有读到本机 Loomy 桌面端的登录态:请先打开 Loomy 客户端并登录,或改用手机号 / 粘贴 session 的方式。",
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
const session = String(desktop.session).trim()
|
|
278
|
-
return {
|
|
279
|
-
url: "",
|
|
280
|
-
method: "auto",
|
|
281
|
-
instructions: `将从本机 Loomy 客户端导入登录态(${
|
|
282
|
-
desktop.maskedPhone || (desktop.phone ? _pure.maskPhone(String(desktop.phone)) : "Loomy")
|
|
283
|
-
})。`,
|
|
284
|
-
callback: async () => {
|
|
285
|
-
// 一次校验:目录能拉通才算这个 session 是活的
|
|
286
|
-
try {
|
|
287
|
-
await liveModels(session, {})
|
|
288
|
-
} catch (error) {
|
|
289
|
-
return {
|
|
290
|
-
type: "failed",
|
|
291
|
-
error: `桌面端登录态已失效(${error?.message ?? error}):请在 Loomy 客户端重新登录后重试。`,
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
const label =
|
|
295
|
-
desktop.maskedPhone ||
|
|
296
|
-
(desktop.phone ? _pure.maskPhone(String(desktop.phone)) : `Loomy ${session.slice(-6)}`)
|
|
297
|
-
// 登录后立刻初始化当天额度(官方客户端同款行为)并把上限记进凭据;
|
|
298
|
-
// 顺便带上已有账号的邀请码(每个账号只能兑换一次,失败不影响登录)
|
|
299
|
-
const patch = await settleNewAccount(session)
|
|
300
|
-
return {
|
|
301
|
-
type: "success",
|
|
302
|
-
access: session,
|
|
303
|
-
refresh: "",
|
|
304
|
-
expires: Date.now() + SESSION_TTL_MS,
|
|
305
|
-
accountId: label,
|
|
306
|
-
...(desktop.userid ? { uid: String(desktop.userid) } : {}),
|
|
307
|
-
...(desktop.phone ? { phone: String(desktop.phone) } : {}),
|
|
308
|
-
...patch,
|
|
309
|
-
}
|
|
310
|
-
},
|
|
311
|
-
}
|
|
312
|
-
},
|
|
313
|
-
},
|
|
314
255
|
{
|
|
315
256
|
type: "oauth",
|
|
316
257
|
label: "手机号 + 短信验证码",
|
|
@@ -449,7 +390,7 @@ export const LoomyAuthPlugin = async ({ client } = {}) => {
|
|
|
449
390
|
const usage = publicUsage(value)
|
|
450
391
|
// 新手任务:一次性可领的 1 万分,只做 aside 展示(不参与路由)。
|
|
451
392
|
// ⚠ 单独缓存 10 分钟 —— 它是另一个端点,而 usage 会被频繁刷新。
|
|
452
|
-
const extra = await onboardingWindowFor(credential)
|
|
393
|
+
const extra = value._team ? undefined : await onboardingWindowFor(credential)
|
|
453
394
|
if (extra) usage.windows = [...(usage.windows ?? []), extra]
|
|
454
395
|
return usage
|
|
455
396
|
},
|
|
@@ -545,6 +486,20 @@ export const LoomyAuthPlugin = async ({ client } = {}) => {
|
|
|
545
486
|
const credential = _pure.credentialOf(auth)
|
|
546
487
|
if (!credential) return fallback
|
|
547
488
|
|
|
489
|
+
// Magpie 拨动 provider 开关只会调用 models;不要在 usage 里切换身份。
|
|
490
|
+
if (teamMode) {
|
|
491
|
+
try {
|
|
492
|
+
if (await teamMode.sync(credential)) {
|
|
493
|
+
clearUsageCache()
|
|
494
|
+
catalog.delete(credential.session)
|
|
495
|
+
}
|
|
496
|
+
} catch (error) {
|
|
497
|
+
clearUsageCache()
|
|
498
|
+
catalog.delete(credential.session)
|
|
499
|
+
throw error
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
548
503
|
const hit = catalog.get(credential.session)
|
|
549
504
|
if (hit && Date.now() - hit.at < CATALOG_TTL_MS) return hit.models
|
|
550
505
|
|
|
@@ -597,7 +552,6 @@ export const _internal = {
|
|
|
597
552
|
publicUsage,
|
|
598
553
|
quotaToRemember,
|
|
599
554
|
quotaPatch,
|
|
600
|
-
readDesktopSession,
|
|
601
555
|
claimDailyQuota,
|
|
602
556
|
fetchBalances,
|
|
603
557
|
fetchOnboarding,
|
|
@@ -605,7 +559,6 @@ export const _internal = {
|
|
|
605
559
|
fetchInviteCodes,
|
|
606
560
|
bindInviteCode,
|
|
607
561
|
fetchActivation,
|
|
608
|
-
readAllLoomyAccounts,
|
|
609
562
|
pickInviteFor: (session) => pickInviteFor(session),
|
|
610
563
|
collectInviteCandidates: (s) => collectInviteCandidates(s),
|
|
611
564
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "magpie-plugin-loomy-auth",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "讯飞 Loomy (iFlytek) for magpie:
|
|
3
|
+
"version": "0.1.36",
|
|
4
|
+
"description": "讯飞 Loomy (iFlytek) for magpie: network-only sign-in (SMS / pasted session, no official client required), the official chat request reproduced header-for-header (including opencode's x-session-affinity), no injected system prompt, hardened credential handling, and the daily/permanent/team credit pools reported the way the host routes them.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.mjs",
|
|
7
7
|
"exports": "./index.mjs",
|
package/src/api.mjs
CHANGED
|
@@ -161,6 +161,30 @@ export async function fetchBalances(session, fetcher = fetch) {
|
|
|
161
161
|
return { permanent, daily, total }
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
+
/** 当前团队由服务端的账号上下文决定,不能从个人钱包或 isInternal 猜。 */
|
|
165
|
+
export async function fetchTeamIdentity(session, fetcher = fetch) {
|
|
166
|
+
const data = await fetchTeamContext(session, fetcher)
|
|
167
|
+
const id = typeof data.currentTeamId === "string" ? data.currentTeamId.trim() : ""
|
|
168
|
+
if (!id) return null
|
|
169
|
+
const team = Array.isArray(data.teams) ? data.teams.find((row) => row?.teamId === id) : undefined
|
|
170
|
+
return { id, name: typeof team?.name === "string" ? team.name.trim() : "" }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** 成员资格与当前身份分开读取;个人模式下仍可有已加入的团队。 */
|
|
174
|
+
export async function fetchTeamContext(session, fetcher = fetch) {
|
|
175
|
+
return tokenRequest("GET", "/api/v1/user/identity", session, undefined, "团队身份查询", fetcher)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** 团队共享余额与当前成员的每日额度;只读,不切换团队。 */
|
|
179
|
+
export async function fetchTeamBalances(session, fetcher = fetch) {
|
|
180
|
+
return tokenRequest("GET", "/api/v1/team-points/balance", session, undefined, "团队积分查询", fetcher)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** 只用于用户选择身份时;空 teamId 切个人,非空选择已加入的团队。 */
|
|
184
|
+
export async function setCurrentTeam(session, teamId, fetcher = fetch) {
|
|
185
|
+
return tokenRequest("POST", "/api/v1/user/current-team", session, teamId ? { teamId } : {}, "切换积分身份", fetcher)
|
|
186
|
+
}
|
|
187
|
+
|
|
164
188
|
/**
|
|
165
189
|
* 从流水推今天的 daily 消耗(降级路径,只在凭据里没有当天 quota 时用)。
|
|
166
190
|
*
|
|
@@ -169,6 +193,9 @@ export async function fetchBalances(session, fetcher = fetch) {
|
|
|
169
193
|
* 上限 LEDGER_MAX_PAGES 页;翻不满就如实标 partial 并放弃推导(宁缺毋谎)。
|
|
170
194
|
*/
|
|
171
195
|
export async function fetchDailyLedger(session, cycleDate, fetcher = fetch) {
|
|
196
|
+
const dateOf = (r) => (typeof r?.dailyCycleDate === "string" ? r.dailyCycleDate.trim() : "")
|
|
197
|
+
// 只有 debit + daily 的扣分行才算「今天的消耗」,credit / permanent 行不参与停页判据。
|
|
198
|
+
const isDailyDebit = (r) => r?.direction === "debit" && r?.consumeSource === "daily"
|
|
172
199
|
let rows = []
|
|
173
200
|
let total = 0
|
|
174
201
|
let complete = false
|
|
@@ -188,6 +215,23 @@ export async function fetchDailyLedger(session, cycleDate, fetcher = fetch) {
|
|
|
188
215
|
complete = true
|
|
189
216
|
break
|
|
190
217
|
}
|
|
218
|
+
// 流水按时间倒序返回,所以「本页出现早于本业务日的 daily 扣分」就等于今天的分已经收全。
|
|
219
|
+
// 不加这一条,4387 条流水的账号要翻 88 页才 complete,而这里最多 6 页 —— 永远 partial,
|
|
220
|
+
// 推导永远不发生,卡片就永远写「今日上限未知」(上限因此既不给占比、也让 cap 闸门拒号)。
|
|
221
|
+
//
|
|
222
|
+
// ⚠ 但「本页没有今天的行」≠「今天没花分」:旧快照、或跨日时厂商还没滚业务日时,
|
|
223
|
+
// 首页可能整页都是昨天的行。那种情况直接收尾就会把「未知」写成「今日消耗 0」,
|
|
224
|
+
// 上限于是被当成当前余额、amount 归零,还会被写回凭据固化一整天。
|
|
225
|
+
// 所以日期规则收尾必须两边同时成立:
|
|
226
|
+
// (a) 已累积的 rows 里真的出现过本业务日的 daily 扣分(证明确实看到了今天);
|
|
227
|
+
// (b) 本页确实出现了早于本业务日的 daily 扣分(倒序证据,证明今天已收全)。
|
|
228
|
+
// credit / permanent 行不参与这两个判据 —— 它们既不算今日消耗,也不能替今天作证。
|
|
229
|
+
const sawToday = rows.some((r) => isDailyDebit(r) && dateOf(r) === cycleDate)
|
|
230
|
+
const sawOlder = list.some((r) => isDailyDebit(r) && dateOf(r) !== "" && dateOf(r) < cycleDate)
|
|
231
|
+
if (sawToday && sawOlder) {
|
|
232
|
+
complete = true
|
|
233
|
+
break
|
|
234
|
+
}
|
|
191
235
|
}
|
|
192
236
|
if (!complete) return { partial: true, consumed: 0, latestCycle: undefined }
|
|
193
237
|
|
package/src/chat.mjs
CHANGED
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
|
|
22
22
|
import { _pure } from "./pure.mjs"
|
|
23
23
|
import { CHAT_TIMEOUT_MS, CLIENT_UA, ERROR_CODES } from "./constants.mjs"
|
|
24
|
+
import { stripOfficialSoulPrompt } from "./prompt.mjs"
|
|
25
|
+
import { chatTracingHeaders } from "./tracing.mjs"
|
|
24
26
|
import { exhausted } from "./usage.mjs"
|
|
25
27
|
|
|
26
28
|
const { businessCode, isAuthErrorCode, prefersTagFormat, rewriteImagesToTags } = _pure
|
|
@@ -42,7 +44,9 @@ export async function chatFetch({ input, init, credential, session, usageValue }
|
|
|
42
44
|
if (usageValue && exhausted(usageValue)) {
|
|
43
45
|
return jsonResponse(429, {
|
|
44
46
|
error: {
|
|
45
|
-
message:
|
|
47
|
+
message: usageValue._team
|
|
48
|
+
? "Loomy 团队积分或今日团队额度已耗尽,请等待额度恢复或切换账号"
|
|
49
|
+
: "Loomy 积分已耗尽(今日额度与永久积分均为 0),请签到或更换账号",
|
|
46
50
|
type: "rate_limit_error",
|
|
47
51
|
code: ERROR_CODES.rateLimited,
|
|
48
52
|
status: 429,
|
|
@@ -57,6 +61,13 @@ export async function chatFetch({ input, init, credential, session, usageValue }
|
|
|
57
61
|
// 非 JSON body:原样透传
|
|
58
62
|
}
|
|
59
63
|
|
|
64
|
+
// ①.5 剥掉官方 soul prompt(若有人把客户端那整段抄进了请求)。
|
|
65
|
+
// ⚠ 快路径:没命中特征串就直接返回,热路径只多一次子串查找。
|
|
66
|
+
if (bodyText) {
|
|
67
|
+
const stripped = stripOfficialSoulPrompt(bodyText)
|
|
68
|
+
if (stripped) bodyText = stripped.body
|
|
69
|
+
}
|
|
70
|
+
|
|
60
71
|
// ② 发送前预改写:已知不吃 `image_url` 的模型直接按标记形态发(省掉一次 400)
|
|
61
72
|
let alreadyTagged = false
|
|
62
73
|
if (model && prefersTagFormat(model) && bodyText) {
|
|
@@ -67,22 +78,46 @@ export async function chatFetch({ input, init, credential, session, usageValue }
|
|
|
67
78
|
}
|
|
68
79
|
}
|
|
69
80
|
|
|
81
|
+
// 重发与首发必须用**完全相同**的 headers / method / signal —— 只换 body。
|
|
82
|
+
// signal 在这里先定下来(不留在 fetch 参数里),否则重发会各自造一个新的超时。
|
|
83
|
+
const method = init?.method ?? request?.method ?? "POST"
|
|
84
|
+
const callerSignal = init?.signal ?? request?.signal ?? null
|
|
85
|
+
const signal = callerSignal ?? AbortSignal.timeout(CHAT_TIMEOUT_MS)
|
|
86
|
+
const target = request ? request.url : url
|
|
87
|
+
|
|
70
88
|
const incoming = new Headers(request ? request.headers : init?.headers)
|
|
71
89
|
// `user-agent` 必须进跳过名单:magpie 递给插件的是它自己的 `magpie/<version>`,
|
|
72
90
|
// 原样转发就是这个插件在替「第三方客户端」投标(上游网关按 `<product>/<version>` 认人,
|
|
73
91
|
// 命中即 403 TM.00000001)。下面统一换成官方 Loomy 客户端的 UA。
|
|
74
|
-
|
|
92
|
+
//
|
|
93
|
+
// `x-loomy-session` 是本插件**自己**在 `chat.headers` 钩子里加的会话关联头,
|
|
94
|
+
// 官方客户端没有这个头 —— 不上游,只借它推 `ChatId`(同一会话同一个值)。
|
|
95
|
+
const magpieSession = incoming.get("x-loomy-session") ?? ""
|
|
96
|
+
for (const key of [
|
|
97
|
+
"authorization",
|
|
98
|
+
"x-api-key",
|
|
99
|
+
"token",
|
|
100
|
+
"content-length",
|
|
101
|
+
"host",
|
|
102
|
+
"user-agent",
|
|
103
|
+
"x-loomy-session",
|
|
104
|
+
]) {
|
|
105
|
+
incoming.delete(key)
|
|
106
|
+
}
|
|
75
107
|
incoming.set("token", session)
|
|
76
108
|
incoming.set("Authorization", `Bearer ${session}`)
|
|
77
109
|
incoming.set("user-agent", CLIENT_UA)
|
|
78
110
|
if (bodyText) incoming.set("Content-Type", "application/json")
|
|
79
111
|
|
|
80
|
-
//
|
|
81
|
-
//
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
112
|
+
// 官方客户端 0.9.39 的追踪头(逆向见 `src/tracing.mjs` 顶部):
|
|
113
|
+
// traceparent **必带**,缺了上游会挂住直到超时;ChatId/MsgId/TurnId/InvokeOrigin/
|
|
114
|
+
// X-Loomy-Request-Purpose/loomy-version 同属一条请求的协议面。
|
|
115
|
+
// 只给 `/chat/completions` 加 —— 生图/embedding 不是这套契约。
|
|
116
|
+
if (/\/chat\/completions\/?$/.test(target)) {
|
|
117
|
+
for (const [key, value] of Object.entries(chatTracingHeaders({ sessionId: magpieSession }))) {
|
|
118
|
+
incoming.set(key, value)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
86
121
|
const sendOnce = (body) =>
|
|
87
122
|
fetch(target, { ...(init ?? {}), method, headers: incoming, body: body || undefined, signal })
|
|
88
123
|
|
package/src/constants.mjs
CHANGED
|
@@ -41,8 +41,14 @@ export const USAGE_FAIL_TTL_MS = 5_000
|
|
|
41
41
|
*/
|
|
42
42
|
export const USAGE_LEAD_POINTS = 1
|
|
43
43
|
|
|
44
|
-
/**
|
|
45
|
-
|
|
44
|
+
/**
|
|
45
|
+
* 推导每日池上限时翻流水的上限(条/页)。
|
|
46
|
+
* ⚠ 不能是 100:实测上游 `pageSize=100` 返回的是一份**不含当天记录**的旧快照
|
|
47
|
+
* (total 比 pageSize≤80 时少掉当天的条数,首页直接跳到昨天),
|
|
48
|
+
* 于是推导永远看不到今天的扣分、`partial` 也永远为真。
|
|
49
|
+
* 50 已实测能拿到当天记录。
|
|
50
|
+
*/
|
|
51
|
+
export const LEDGER_PAGE_SIZE = 50
|
|
46
52
|
export const LEDGER_MAX_PAGES = 6
|
|
47
53
|
|
|
48
54
|
export const SUCCESS_CODE = "000000"
|
|
@@ -92,6 +98,16 @@ export const CLIENT_DEVICE_ID = "web"
|
|
|
92
98
|
export const CLIENT_UA = "Loomy|Desktop|Electron|macOS"
|
|
93
99
|
export const CLIENT_VERSION = "1.0.0"
|
|
94
100
|
|
|
101
|
+
/**
|
|
102
|
+
* 聊天请求的 `loomy-version` —— 逆向自**官方客户端 0.9.39**(2026-10-10 发布)。
|
|
103
|
+
*
|
|
104
|
+
* ⚠ 与 `CLIENT_VERSION` 分开:那个是账号签名体里的 `base.version`(业务接口),
|
|
105
|
+
* 这个只出现在 `/chat/completions` 的 `loomy-version` 头里,官方填的是
|
|
106
|
+
* Electron `app.getVersion()`(= 客户端版本号)。
|
|
107
|
+
* 客户端升级后这里要跟着改;改错不会报错,只会让上游看到的客户端版本对不上。
|
|
108
|
+
*/
|
|
109
|
+
export const LOOMY_CHAT_VERSION = "0.9.39"
|
|
110
|
+
|
|
95
111
|
function trim(v) {
|
|
96
112
|
return typeof v === "string" ? v.trim().replace(/\/+$/, "") : ""
|
|
97
113
|
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// 安全加固的公共件:凭据脱敏 + 上游白名单。
|
|
2
|
+
//
|
|
3
|
+
// 这两件事都在**热路径**上(每个错误消息、每个出站 URL),所以只做纯函数、
|
|
4
|
+
// 不做 IO、不缓存全局状态。
|
|
5
|
+
|
|
6
|
+
/** 官方上游主机白名单 —— 硬编码,不受环境变量影响。 */
|
|
7
|
+
export const ALLOWED_HOSTS = Object.freeze(["loomyad.xunfei.cn", "account.xfinfr.com"])
|
|
8
|
+
|
|
9
|
+
/** session 是 32 位十六进制串;签名密钥是 16/32 位字母数字。别的一律不猜。 */
|
|
10
|
+
const SECRET_PATTERNS = [
|
|
11
|
+
/\b[0-9a-f]{32}\b/gi, // session / token
|
|
12
|
+
/\b(?:csk|sk)[-_][A-Za-z0-9_-]{6,}\b/g, // 形如 csk_ / sk- 的 key
|
|
13
|
+
/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi, // 任何落到文本里的 Bearer
|
|
14
|
+
/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, // JWT
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 把一段文本里的凭据换成 `***`。
|
|
19
|
+
*
|
|
20
|
+
* ⚠ 只在**要给别人看的字符串**上调用(错误消息、日志、响应头、诊断信息),
|
|
21
|
+
* 不要拿它处理请求体 —— 那会把用户正常内容改坏。
|
|
22
|
+
*/
|
|
23
|
+
export function redact(text, extra = []) {
|
|
24
|
+
if (typeof text !== "string" || !text) return text ?? ""
|
|
25
|
+
let out = text
|
|
26
|
+
for (const pattern of SECRET_PATTERNS) out = out.replace(pattern, "***")
|
|
27
|
+
for (const secret of extra) {
|
|
28
|
+
const value = String(secret ?? "").trim()
|
|
29
|
+
if (value.length >= 8) out = out.split(value).join("***")
|
|
30
|
+
}
|
|
31
|
+
// 手机号:只留前 3 后 4
|
|
32
|
+
out = out.replace(/\b(1[3-9]\d)\d{4}(\d{4})\b/g, "$1****$2")
|
|
33
|
+
return out
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 造一个 `Error`,message 已脱敏,原文放 `cause`(不参与序列化)。 */
|
|
37
|
+
export function safeError(message, extra = []) {
|
|
38
|
+
const error = new Error(redact(message, extra))
|
|
39
|
+
return error
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 只允许打官方上游。
|
|
44
|
+
*
|
|
45
|
+
* 抛错而不是返回 false:调用方忘了判断就是安全漏洞,所以这里 fail-closed。
|
|
46
|
+
*/
|
|
47
|
+
export function assertUpstream(url) {
|
|
48
|
+
let parsed
|
|
49
|
+
try {
|
|
50
|
+
parsed = new URL(String(url))
|
|
51
|
+
} catch {
|
|
52
|
+
throw safeError(`上游地址不合法:${String(url).slice(0, 80)}`)
|
|
53
|
+
}
|
|
54
|
+
if (parsed.protocol !== "https:") throw safeError(`上游必须是 https:${parsed.protocol}`)
|
|
55
|
+
if (!ALLOWED_HOSTS.includes(parsed.hostname)) {
|
|
56
|
+
throw safeError(`上游主机不在白名单:${parsed.hostname}`)
|
|
57
|
+
}
|
|
58
|
+
return parsed
|
|
59
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// 邀请码本地库:**自己攒的码**,不读官方客户端。
|
|
2
|
+
//
|
|
3
|
+
// 背景:官方客户端时代,插件的「自动邀请」是靠扫本机其它 Loomy 登录态、现查它们的
|
|
4
|
+
// 邀请码来实现的。这一版不碰官方客户端的任何文件(见 docs/security.md),所以改成
|
|
5
|
+
// 「谁登录过、就把谁的邀请码记进插件自己的小库」——下次有新号登录时从这里挑。
|
|
6
|
+
//
|
|
7
|
+
// ⚠ 只存**邀请码**(半公开的兑换码 + 首尾各 4 位归属指纹),**绝不存 session**。
|
|
8
|
+
// ⚠ 目录不可写时静默降级为空库:自动邀请是锦上添花,不能挡住登录。
|
|
9
|
+
|
|
10
|
+
import { createHash } from "node:crypto"
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
|
|
12
|
+
import { homedir } from "node:os"
|
|
13
|
+
import { dirname, join } from "node:path"
|
|
14
|
+
|
|
15
|
+
import { _pure } from "./pure.mjs"
|
|
16
|
+
|
|
17
|
+
const { INVITE_REWARD_POINTS } = _pure
|
|
18
|
+
|
|
19
|
+
const STORE_VERSION = 1
|
|
20
|
+
const MAX_ENTRIES = 200
|
|
21
|
+
const STORE_TTL_MS = 90 * 24 * 3600_000
|
|
22
|
+
|
|
23
|
+
/** 账号归属指纹:只用于「别自己邀请自己」,不可逆推 session。 */
|
|
24
|
+
export function ownerTag(session) {
|
|
25
|
+
const value = String(session ?? "").trim()
|
|
26
|
+
if (!value) return ""
|
|
27
|
+
return createHash("sha256").update(value).digest("hex").slice(0, 12)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function storePath() {
|
|
31
|
+
const explicit = String(process.env.LOOMY_INVITE_STORE ?? "").trim()
|
|
32
|
+
if (explicit) return explicit
|
|
33
|
+
const base = process.platform === "win32"
|
|
34
|
+
? (process.env.APPDATA || join(homedir(), "AppData", "Roaming"))
|
|
35
|
+
: join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"))
|
|
36
|
+
return join(base, "magpie-plugin-loomy-auth", "invites.json")
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function loadInviteStore(path = storePath(), now = Date.now()) {
|
|
40
|
+
try {
|
|
41
|
+
if (!existsSync(path)) return []
|
|
42
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"))
|
|
43
|
+
if (parsed?.version !== STORE_VERSION || !Array.isArray(parsed.entries)) return []
|
|
44
|
+
return parsed.entries
|
|
45
|
+
.filter((row) => row && typeof row.code === "string" && row.code)
|
|
46
|
+
.filter((row) => !row.at || now - row.at < STORE_TTL_MS)
|
|
47
|
+
.slice(0, MAX_ENTRIES)
|
|
48
|
+
} catch {
|
|
49
|
+
return [] // 损坏就重来,不抛
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 记住一组邀请码(同一个 code 只留一条,owner 取最新)。返回写入后的条目数。 */
|
|
54
|
+
export function rememberInviteCodes(codes, { owner = "", path = storePath(), now = Date.now() } = {}) {
|
|
55
|
+
const incoming = (Array.isArray(codes) ? codes : [])
|
|
56
|
+
.map((row) => (typeof row === "string" ? { code: row } : row))
|
|
57
|
+
.map((row) => ({
|
|
58
|
+
code: String(row?.code ?? "").trim(),
|
|
59
|
+
// ⚠ 必须连 status / usedCount / maxUses 一起存:
|
|
60
|
+
// `pickInviteCode()` 会把 status 不是 ""/"active"、或已用满的码过滤掉。
|
|
61
|
+
// 只存 code 的话,候选会被它全部滤空 —— 自动邀请看起来「开着但永远不生效」。
|
|
62
|
+
status: typeof row?.status === "string" ? row.status : "",
|
|
63
|
+
usedCount: Number.isFinite(row?.usedCount) ? row.usedCount : undefined,
|
|
64
|
+
maxUses: Number.isFinite(row?.maxUses) ? row.maxUses : undefined,
|
|
65
|
+
}))
|
|
66
|
+
.filter((row) => row.code)
|
|
67
|
+
if (!incoming.length) return loadInviteStore(path, now).length
|
|
68
|
+
|
|
69
|
+
const byCode = new Map()
|
|
70
|
+
for (const row of loadInviteStore(path, now)) byCode.set(row.code, row)
|
|
71
|
+
for (const row of incoming) {
|
|
72
|
+
const prev = byCode.get(row.code)
|
|
73
|
+
byCode.set(row.code, {
|
|
74
|
+
code: row.code,
|
|
75
|
+
owner: owner || prev?.owner || "",
|
|
76
|
+
status: row.status || prev?.status || "",
|
|
77
|
+
...(row.usedCount === undefined ? (prev?.usedCount === undefined ? {} : { usedCount: prev.usedCount }) : { usedCount: row.usedCount }),
|
|
78
|
+
...(row.maxUses === undefined ? (prev?.maxUses === undefined ? {} : { maxUses: prev.maxUses }) : { maxUses: row.maxUses }),
|
|
79
|
+
at: now,
|
|
80
|
+
reward: INVITE_REWARD_POINTS,
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
const entries = [...byCode.values()].sort((a, b) => (b.at ?? 0) - (a.at ?? 0)).slice(0, MAX_ENTRIES)
|
|
84
|
+
|
|
85
|
+
try {
|
|
86
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
87
|
+
writeFileSync(path, JSON.stringify({ version: STORE_VERSION, entries }, null, 2), "utf8")
|
|
88
|
+
} catch {
|
|
89
|
+
// 目录不可写就只活在内存里(本次进程内仍能用)
|
|
90
|
+
}
|
|
91
|
+
return entries.length
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 兜底邀请码:码库为空(第一次装、或者从没登录过第二个号)时也要有候选。
|
|
96
|
+
*
|
|
97
|
+
* 取值原则:**只放当前 active 的码**。已用尽(`exhausted` / `usedCount === maxUses`)
|
|
98
|
+
* 的码不要放进来 —— `pickInviteCode()` 会把它挑出来又白跑一次绑定请求。
|
|
99
|
+
* 顺序即优先级:靠前的先被挑中。
|
|
100
|
+
*
|
|
101
|
+
* 换码:改这里,或直接用环境变量 `LOOMY_INVITE_CODE=CODE1,CODE2`(逗号分隔,覆盖本表)。
|
|
102
|
+
*/
|
|
103
|
+
export const FALLBACK_INVITE_CODES = Object.freeze(
|
|
104
|
+
String(process.env.LOOMY_INVITE_CODE ?? "").trim()
|
|
105
|
+
? String(process.env.LOOMY_INVITE_CODE).split(",").map((x) => x.trim().toUpperCase()).filter(Boolean)
|
|
106
|
+
: ["J2QC44", "V5Y8JE"],
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 候选邀请码:排除本号自己那份。
|
|
111
|
+
*
|
|
112
|
+
* @param {string} selfSession 当前账号的 session(只用来算归属指纹,不落盘)
|
|
113
|
+
* @param {{ path?: string, now?: number }} [opts]
|
|
114
|
+
* @returns {Array<{ code: string }>}
|
|
115
|
+
*/
|
|
116
|
+
export function inviteCandidates(selfSession, { path = storePath(), now = Date.now(), fallback = FALLBACK_INVITE_CODES } = {}) {
|
|
117
|
+
const self = ownerTag(selfSession)
|
|
118
|
+
const all = loadInviteStore(path, now)
|
|
119
|
+
const stored = all.filter((row) => !row.owner || row.owner !== self)
|
|
120
|
+
// 本号自己的码:既要排除,也不能在兜底那一步被加回来
|
|
121
|
+
// (否则「自己邀请自己」的候选还在,只是靠 pickInviteFor 的第二道 selfCode 拦着)
|
|
122
|
+
const selfCodes = new Set(all.filter((row) => row.owner && row.owner === self).map((row) => row.code))
|
|
123
|
+
|
|
124
|
+
const out = stored.map((row) => ({
|
|
125
|
+
code: row.code,
|
|
126
|
+
status: typeof row.status === "string" ? row.status : "",
|
|
127
|
+
usedCount: Number.isFinite(row.usedCount) ? row.usedCount : 0,
|
|
128
|
+
maxUses: Number.isFinite(row.maxUses) ? row.maxUses : 0,
|
|
129
|
+
}))
|
|
130
|
+
|
|
131
|
+
// 兜底排在最后:自己攒到的码优先,兜底只在没有可用码时被挑中。
|
|
132
|
+
// 同一个 code 已经在库里就以库里的状态为准(那份是最近一次查到的真实状态)。
|
|
133
|
+
const known = new Set(out.map((row) => row.code))
|
|
134
|
+
for (const code of fallback || []) {
|
|
135
|
+
const value = String(code ?? "").trim().toUpperCase()
|
|
136
|
+
if (!value || known.has(value) || selfCodes.has(value)) continue
|
|
137
|
+
known.add(value)
|
|
138
|
+
out.push({ code: value, status: "active", usedCount: 0, maxUses: 0 })
|
|
139
|
+
}
|
|
140
|
+
return out
|
|
141
|
+
}
|