@iwpz/fishpi-dsh 0.0.0-stage → 0.1.1

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/index.js ADDED
@@ -0,0 +1,990 @@
1
+ /**
2
+ * Host half of the FishPi chat plugin.
3
+ *
4
+ * Responsibilities:
5
+ * - Log in on the Host (the FishPi login endpoint refuses browser CORS), keep
6
+ * the access token and an optional password digest in the DSH credential
7
+ * store, and renew the session when it expires.
8
+ * - Keep one chat WebSocket open per DSH process and fan its events out as a
9
+ * replayable, cursor-based event log.
10
+ * - Serve the browser through authenticated same-origin Fetch routes, so no
11
+ * secret and no cross-origin request ever reaches the page.
12
+ */
13
+
14
+ import {
15
+ ChatRealtime,
16
+ DEFAULT_SITE,
17
+ delay,
18
+ EventHub,
19
+ FishPiApi,
20
+ FishPiError,
21
+ MAX_MESSAGE_LENGTH,
22
+ md5Hex,
23
+ normalizeMe,
24
+ normalizeMessage,
25
+ } from './fishpi.js'
26
+
27
+ /** Credential record address: `<scope>/<id>`, both lowercase hyphenated. */
28
+ const CREDENTIAL_KEY = 'fishpi-chat/account'
29
+
30
+ /** Route prefix on DSH's authenticated API channel. */
31
+ const API_PREFIX = '/api/fishpi'
32
+
33
+ /** Longest a browser event request is held before an empty answer. */
34
+ const EVENT_WAIT_MS = 20_000
35
+
36
+ /** Retained realtime events; the browser reloads its window on a gap. */
37
+ const EVENT_LOG_LIMIT = 500
38
+
39
+ /** Cordis Host services this plugin needs. */
40
+ export const inject = ['connection', 'credentials']
41
+
42
+ /**
43
+ * @param {unknown} value - candidate integer.
44
+ * @param {number} fallback - used when the value is absent or unusable.
45
+ * @param {number} min - lower bound.
46
+ * @param {number} max - upper bound.
47
+ * @returns {number}
48
+ */
49
+ function integer(value, fallback, min, max) {
50
+ const parsed = Number(value)
51
+ if (!Number.isSafeInteger(parsed)) return fallback
52
+ return Math.min(max, Math.max(min, parsed))
53
+ }
54
+
55
+ /**
56
+ * @param {unknown} value - candidate string.
57
+ * @param {number} max - maximum accepted UTF-16 length.
58
+ * @returns {string}
59
+ */
60
+ function text(value, max) {
61
+ if (typeof value !== 'string') return ''
62
+ return value.trim().slice(0, max)
63
+ }
64
+
65
+ /**
66
+ * @param {Request} request - a buffered Fetch request.
67
+ * @returns {Promise<Record<string, unknown>>} its JSON object body.
68
+ */
69
+ async function readJson(request) {
70
+ const body = await request.text()
71
+ if (body.length > 16_384) throw new FishPiError('请求内容过大', { code: 'bad_request', status: 413 })
72
+ if (body.trim() === '') return {}
73
+ let parsed
74
+ try {
75
+ parsed = JSON.parse(body)
76
+ } catch {
77
+ throw new FishPiError('请求格式不正确', { code: 'bad_request', status: 400 })
78
+ }
79
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
80
+ throw new FishPiError('请求格式不正确', { code: 'bad_request', status: 400 })
81
+ }
82
+ return parsed
83
+ }
84
+
85
+ /**
86
+ * @param {import('@deepseek-ai/cordis').Context} ctx - host context; its logger is optional.
87
+ * @param {string} message - diagnostic text.
88
+ * @param {unknown} error - the contained failure.
89
+ */
90
+ function warn(ctx, message, error) {
91
+ const line = `[fishpi-chat] ${message}`
92
+ if (typeof ctx.logger?.warn === 'function') ctx.logger.warn(line, error)
93
+ else console.warn(line, error)
94
+ }
95
+
96
+ /**
97
+ * Normalize the legacy medal list into icon-bearing records.
98
+ * @param {unknown} data - medal envelope data or a list.
99
+ * @returns {Array<{id: string, name: string, type: string, description: string, url: string, order: number}>}
100
+ */
101
+ function normalizeMedals(data) {
102
+ const list = Array.isArray(data) ? data : Array.isArray(data?.list) ? data.list : []
103
+ return list
104
+ .filter(medal => medal !== null && typeof medal === 'object' && medal.enabled !== false)
105
+ .map(medal => {
106
+ const attr = typeof medal.attr === 'string' ? medal.attr : ''
107
+ let url = ''
108
+ try {
109
+ url = new URLSearchParams(attr).get('url') ?? ''
110
+ } catch {
111
+ url = ''
112
+ }
113
+ if (url === '') return null
114
+ return {
115
+ id: medal.id === undefined ? '' : String(medal.id),
116
+ name: typeof medal.name === 'string' ? medal.name : '',
117
+ type: typeof medal.type === 'string' ? medal.type : '',
118
+ description: typeof medal.description === 'string' ? medal.description : '',
119
+ url,
120
+ order: Number(medal.order) || 0,
121
+ }
122
+ })
123
+ .filter(Boolean)
124
+ .sort((left, right) => left.order - right.order)
125
+ }
126
+
127
+ /**
128
+ * @param {unknown} data - JSON-safe body.
129
+ * @param {number} [status] - HTTP status.
130
+ * @returns {Response}
131
+ */
132
+ function json(data, status = 200) {
133
+ return new Response(JSON.stringify(data), {
134
+ status,
135
+ headers: {
136
+ 'content-type': 'application/json; charset=utf-8',
137
+ 'cache-control': 'no-store',
138
+ },
139
+ })
140
+ }
141
+
142
+ /**
143
+ * @param {unknown} error - a thrown operation failure.
144
+ * @returns {Response}
145
+ */
146
+ function failure(error) {
147
+ const known = error instanceof FishPiError
148
+ ? error
149
+ : new FishPiError(error instanceof Error ? error.message : '操作失败', { code: 'internal' })
150
+ const status = known.status >= 400 && known.status < 600 ? known.status : 500
151
+ return json({ ok: false, code: known.code, message: known.message }, status)
152
+ }
153
+
154
+ /**
155
+ * Owns the FishPi session and translates browser requests into API calls.
156
+ */
157
+ class FishPiChat {
158
+ /**
159
+ * @param {{ ctx: import('@deepseek-ai/cordis').Context, hub: EventHub }} options - Host context and event log.
160
+ */
161
+ constructor(options) {
162
+ this.ctx = options.ctx
163
+ this.hub = options.hub
164
+ this.api = new FishPiApi({ siteUrl: DEFAULT_SITE })
165
+ this.stopped = false
166
+ this.initialized = false
167
+ this.loggedIn = false
168
+ this.user = undefined
169
+ /** @type {Record<string, any>|undefined} */
170
+ this.record = undefined
171
+ this.tokenExpiresAt = 0
172
+ /** @type {'connecting'|'connected'|'disconnected'} */
173
+ this.connectionState = 'disconnected'
174
+ /** @type {FishPiError|undefined} */
175
+ this.lastError = undefined
176
+ /** @type {ChatRealtime|undefined} */
177
+ this.realtime = undefined
178
+ /** @type {Promise<void>|undefined} */
179
+ this.loginTask = undefined
180
+ /** @type {Map<string, { at: number, medals: object[] }>} */
181
+ this.medalCache = new Map()
182
+ }
183
+
184
+ /** Load stored credentials, validate the token, and start the socket. */
185
+ async initialize() {
186
+ try {
187
+ const stored = await this.ctx.credentials.readRecord(CREDENTIAL_KEY)
188
+ if (stored?.kind === 'grant' && stored.payload !== null && typeof stored.payload === 'object') {
189
+ this.record = /** @type {Record<string, any>} */ (stored.payload)
190
+ }
191
+ } catch (error) {
192
+ warn(this.ctx, 'could not read stored credentials', error)
193
+ }
194
+
195
+ if (this.record?.accessToken) {
196
+ this.api.setToken(String(this.record.accessToken))
197
+ this.tokenExpiresAt = Number(this.record.tokenExpiresAt) || 0
198
+ try {
199
+ const me = await this.api.me()
200
+ this.user = normalizeMe(me)
201
+ this.loggedIn = this.user !== undefined
202
+ } catch (error) {
203
+ const authFailure = error instanceof FishPiError
204
+ && (error.status === 401 || error.status === 403 || error.code === 'unauthorized')
205
+ if (authFailure) {
206
+ this.api.setToken('')
207
+ this.user = undefined
208
+ this.loggedIn = false
209
+ } else {
210
+ this.#rememberFailure(error)
211
+ }
212
+ }
213
+ }
214
+
215
+ if (!this.loggedIn && this.record?.passwordMd5) {
216
+ try {
217
+ await this.#loginWithDigest(String(this.record.nameOrEmail ?? ''), String(this.record.passwordMd5), this.record.remember !== false)
218
+ } catch (error) {
219
+ this.#rememberFailure(error)
220
+ }
221
+ }
222
+
223
+ this.initialized = true
224
+ if (this.loggedIn && this.realtime === undefined) this.#startRealtime()
225
+ this.#emitState()
226
+ }
227
+
228
+ /** Release the socket and every held event request. */
229
+ dispose() {
230
+ this.stopped = true
231
+ this.realtime?.stop()
232
+ this.realtime = undefined
233
+ this.hub.dispose()
234
+ }
235
+
236
+ /**
237
+ * @returns {Record<string, unknown>} the browser-visible session state.
238
+ */
239
+ state() {
240
+ return {
241
+ ok: true,
242
+ ready: this.initialized,
243
+ loggedIn: this.loggedIn,
244
+ user: this.user ?? null,
245
+ connection: this.connectionState,
246
+ cursor: this.hub.seq,
247
+ mfaRequired: this.lastError?.code === 'mfa_required',
248
+ error: this.lastError === undefined ? null : { code: this.lastError.code, message: this.lastError.message },
249
+ siteUrl: DEFAULT_SITE,
250
+ }
251
+ }
252
+
253
+ /**
254
+ * @param {{ nameOrEmail?: unknown, password?: unknown, mfaCode?: unknown, remember?: unknown }} body - login form.
255
+ * @returns {Promise<Record<string, unknown>>}
256
+ */
257
+ async login(body) {
258
+ const nameOrEmail = text(body.nameOrEmail, 200)
259
+ const password = typeof body.password === 'string' ? body.password : ''
260
+ const mfaCode = text(body.mfaCode, 16)
261
+ const remember = body.remember !== false
262
+ if (nameOrEmail === '' || password === '') {
263
+ return { ok: false, code: 'invalid_input', message: '请输入账号和密码' }
264
+ }
265
+
266
+ const passwordMd5 = md5Hex(password)
267
+ try {
268
+ const grant = await this.api.login({ nameOrEmail, userPassword: passwordMd5, mfaCode })
269
+ if (grant?.mfaRequired === true || grant?.mfa_required === true) {
270
+ return { ok: false, code: 'mfa_required', message: '该账号启用了两步验证,请输入验证码', mfaRequired: true }
271
+ }
272
+ await this.#applyLogin(grant, { nameOrEmail, passwordMd5, remember })
273
+ return { ok: true, user: this.user }
274
+ } catch (error) {
275
+ if (error instanceof FishPiError && error.code === 'mfa_required') {
276
+ this.lastError = error
277
+ this.#emitState()
278
+ return { ok: false, code: error.code, message: '该账号启用了两步验证,请输入验证码', mfaRequired: true }
279
+ }
280
+ this.#rememberFailure(error)
281
+ return {
282
+ ok: false,
283
+ code: error instanceof FishPiError ? error.code : 'internal',
284
+ message: error instanceof Error ? error.message : '登录失败',
285
+ }
286
+ }
287
+ }
288
+
289
+ /** Forget the account and its stored credentials. */
290
+ async logout() {
291
+ this.loggedIn = false
292
+ this.user = undefined
293
+ this.record = undefined
294
+ this.api.setToken('')
295
+ this.tokenExpiresAt = 0
296
+ this.lastError = undefined
297
+ this.realtime?.stop()
298
+ this.realtime = undefined
299
+ this.connectionState = 'disconnected'
300
+ try {
301
+ await this.ctx.credentials.deleteRecord(CREDENTIAL_KEY)
302
+ } catch (error) {
303
+ warn(this.ctx, 'could not delete stored credentials', error)
304
+ }
305
+ this.#emitState()
306
+ return { ok: true }
307
+ }
308
+
309
+ /**
310
+ * @param {{ size?: unknown, before?: unknown, after?: unknown }} query - one window.
311
+ * @returns {Promise<Record<string, unknown>>}
312
+ */
313
+ async messages(query) {
314
+ const size = integer(query.size, 30, 1, 50)
315
+ const before = typeof query.before === 'string' && /^\d+$/u.test(query.before) ? query.before : undefined
316
+ const after = typeof query.after === 'string' && /^\d+$/u.test(query.after) ? query.after : undefined
317
+ const data = await this.#withAuth(() => this.api.messages({ size, before, after }))
318
+ const list = Array.isArray(data?.list) ? data.list.map(normalizeMessage).filter(Boolean) : []
319
+ return {
320
+ ok: true,
321
+ list,
322
+ hasMore: data?.hasMore === true,
323
+ nextBefore: data?.nextBefore === undefined ? '' : String(data.nextBefore),
324
+ nextAfter: data?.nextAfter === undefined ? '' : String(data.nextAfter),
325
+ }
326
+ }
327
+
328
+ /**
329
+ * Resolve medal icons for message authors, cached per user.
330
+ * @param {string[]} names - public usernames.
331
+ * @returns {Promise<Record<string, unknown>>} medal lists keyed by username.
332
+ */
333
+ async medals(names) {
334
+ const clean = [...new Set(names
335
+ .filter(name => typeof name === 'string' && name !== '' && /^[A-Za-z0-9_-]{1,64}$/u.test(name))
336
+ .slice(0, 30))]
337
+ const output = {}
338
+ await Promise.all(clean.map(async name => {
339
+ const cached = this.medalCache.get(name)
340
+ if (cached !== undefined && Date.now() - cached.at < 10 * 60 * 1000) {
341
+ output[name] = cached.medals
342
+ return
343
+ }
344
+ try {
345
+ const medals = normalizeMedals(await this.api.userMedals(name))
346
+ this.medalCache.set(name, { at: Date.now(), medals })
347
+ output[name] = medals
348
+ } catch {
349
+ output[name] = []
350
+ }
351
+ }))
352
+ return { ok: true, medals: output }
353
+ }
354
+
355
+ /**
356
+ * @param {{ name?: unknown }} query - public username.
357
+ * @returns {Promise<Record<string, unknown>>} public profile and medal icons.
358
+ */
359
+ async userInfo(query) {
360
+ const userName = typeof query.name === 'string' ? query.name.trim().slice(0, 64) : ''
361
+ if (userName === '' || !/^[A-Za-z0-9_-]+$/u.test(userName)) {
362
+ throw new FishPiError('用户名不正确', { code: 'invalid_input', status: 400 })
363
+ }
364
+ let source
365
+ try {
366
+ source = await this.#withAuth(() => this.api.legacyUser(userName))
367
+ } catch {
368
+ source = await this.#withAuth(() => this.api.userProfile(userName))
369
+ }
370
+ const raw = source !== null && typeof source === 'object' ? source : {}
371
+ const profile = {
372
+ id: raw.oId === undefined && raw.id === undefined ? '' : String(raw.oId ?? raw.id),
373
+ userNo: raw.userNo === undefined || raw.userNo === null ? '' : String(raw.userNo),
374
+ userName: typeof raw.userName === 'string' ? raw.userName : userName,
375
+ userNickname: typeof raw.userNickname === 'string' ? raw.userNickname : '',
376
+ userAvatarURL: typeof raw.userAvatarURL === 'string' ? raw.userAvatarURL : '',
377
+ userIntro: typeof raw.userIntro === 'string' ? raw.userIntro : '',
378
+ userURL: typeof raw.userURL === 'string' ? raw.userURL : '',
379
+ userRole: typeof raw.userRole === 'string' ? raw.userRole : '',
380
+ userCity: typeof raw.userCity === 'string' ? raw.userCity : '',
381
+ cardBg: typeof raw.cardBg === 'string' ? raw.cardBg : '',
382
+ userPoint: Number.isFinite(Number(raw.userPoint)) ? Number(raw.userPoint) : undefined,
383
+ onlineMinute: Number.isFinite(Number(raw.onlineMinute)) ? Number(raw.onlineMinute) : undefined,
384
+ }
385
+ let medals = []
386
+ try {
387
+ medals = normalizeMedals(await this.api.userMedals(userName))
388
+ } catch {
389
+ medals = []
390
+ }
391
+ return { ok: true, profile, medals }
392
+ }
393
+
394
+ /**
395
+ * @param {{ prefix?: unknown }} query - username prefix typed after `@`.
396
+ * @returns {Promise<Record<string, unknown>>} matching users.
397
+ */
398
+ async suggestUsers(query) {
399
+ const prefix = typeof query.prefix === 'string' ? query.prefix.slice(0, 64) : ''
400
+ if (prefix === '' || !/^[A-Za-z0-9_-]+$/u.test(prefix)) return { ok: true, list: [] }
401
+ const data = await this.#withAuth(() => this.api.suggestUsers(prefix))
402
+ const list = Array.isArray(data?.list)
403
+ ? data.list
404
+ .filter(user => user !== null && typeof user === 'object')
405
+ .map(user => ({
406
+ id: user.id === undefined ? '' : String(user.id),
407
+ userName: typeof user.userName === 'string' ? user.userName : '',
408
+ userNickname: typeof user.userNickname === 'string' ? user.userNickname : '',
409
+ userAvatarURL: typeof user.userAvatarURL === 'string' ? user.userAvatarURL : '',
410
+ }))
411
+ : []
412
+ return { ok: true, list }
413
+ }
414
+
415
+ /**
416
+ * Upload image files through a FishPi upload ticket and return their URLs.
417
+ * @param {FormData} form - multipart body with one or more `file` entries.
418
+ * @returns {Promise<Record<string, unknown>>} uploaded file names and URLs.
419
+ */
420
+ async upload(form) {
421
+ const files = form.getAll('file').filter(value => value !== null && typeof value === 'object' && typeof value.arrayBuffer === 'function')
422
+ if (files.length === 0) throw new FishPiError('请选择要上传的图片', { code: 'invalid_input', status: 400 })
423
+ if (files.length > 9) throw new FishPiError('一次最多上传 9 张图片', { code: 'invalid_input', status: 400 })
424
+ let total = 0
425
+ for (const file of files) {
426
+ const size = Number(file.size) || 0
427
+ if (size === 0) throw new FishPiError('图片内容为空', { code: 'invalid_input', status: 400 })
428
+ if (size > 10 * 1024 * 1024) throw new FishPiError('单张图片不能超过 10MB', { code: 'invalid_input', status: 413 })
429
+ total += size
430
+ }
431
+ if (total > 30 * 1024 * 1024) throw new FishPiError('图片总大小不能超过 30MB', { code: 'invalid_input', status: 413 })
432
+
433
+ const ticket = await this.#withAuth(() => this.api.uploadTicket())
434
+ if (ticket === null || typeof ticket !== 'object' || typeof ticket.uploadURL !== 'string') {
435
+ throw new FishPiError('上传票据无效', { code: 'invalid_response' })
436
+ }
437
+ const fieldName = typeof ticket.fieldName === 'string' && ticket.fieldName !== '' ? ticket.fieldName : 'file'
438
+ const upload = new FormData()
439
+ const names = new Map()
440
+ files.forEach((file, index) => {
441
+ const original = typeof file.name === 'string' && file.name !== '' ? file.name : `image-${index + 1}.png`
442
+ let name = original
443
+ if (names.has(name)) {
444
+ const dot = original.lastIndexOf('.')
445
+ const stem = dot > 0 ? original.slice(0, dot) : original
446
+ const ext = dot > 0 ? original.slice(dot) : ''
447
+ name = `${stem}-${index + 1}${ext}`
448
+ }
449
+ names.set(name, original)
450
+ upload.append(fieldName, file, name)
451
+ })
452
+
453
+ let response
454
+ try {
455
+ response = await fetch(ticket.uploadURL, {
456
+ method: 'POST',
457
+ headers: { authorization: `Bearer ${ticket.ticket}` },
458
+ body: upload,
459
+ signal: AbortSignal.timeout(60_000),
460
+ })
461
+ } catch (error) {
462
+ throw new FishPiError('图片上传失败,请检查网络后重试', { code: 'network', cause: error })
463
+ }
464
+ let payload = null
465
+ try {
466
+ payload = await response.json()
467
+ } catch {
468
+ // The status and upload response carry the failure.
469
+ }
470
+ if (!response.ok || payload?.code !== 0 && payload?.code !== '0') {
471
+ throw new FishPiError(
472
+ typeof payload?.msg === 'string' && payload.msg !== '' ? payload.msg : `图片上传失败(HTTP ${response.status})`,
473
+ { code: 'upload_failed', status: response.status },
474
+ )
475
+ }
476
+ const succMap = payload?.data?.succMap !== null && typeof payload?.data?.succMap === 'object' ? payload.data.succMap : {}
477
+ const uploaded = []
478
+ for (const [name, original] of names) {
479
+ const url = succMap[name]
480
+ if (typeof url === 'string' && url !== '') uploaded.push({ name: original, url })
481
+ }
482
+ if (uploaded.length === 0) {
483
+ throw new FishPiError('图片上传失败,请稍后重试', { code: 'upload_failed', status: 502 })
484
+ }
485
+ return { ok: true, files: uploaded }
486
+ }
487
+
488
+ /**
489
+ * @param {{ id?: unknown }} query - red-packet message id.
490
+ * @returns {Promise<Record<string, unknown>>} the red-packet detail.
491
+ */
492
+ async redPacket(query) {
493
+ const id = typeof query.id === 'string' && /^\d+$/u.test(query.id) ? query.id : ''
494
+ if (id === '') throw new FishPiError('红包 ID 不正确', { code: 'invalid_input', status: 400 })
495
+ const detail = await this.#withAuth(() => this.api.redPacket(id))
496
+ return { ok: true, detail }
497
+ }
498
+
499
+ /**
500
+ * @param {{ id?: unknown, gesture?: unknown, riskAccepted?: unknown, requestId?: unknown }} body - claim form.
501
+ * @returns {Promise<Record<string, unknown>>} the claim and refreshed detail.
502
+ */
503
+ async claimRedPacket(body) {
504
+ const id = typeof body.id === 'string' && /^\d+$/u.test(body.id) ? body.id : ''
505
+ if (id === '') throw new FishPiError('红包 ID 不正确', { code: 'invalid_input', status: 400 })
506
+ const gesture = Number.isInteger(body.gesture) && body.gesture >= 0 && body.gesture <= 2 ? body.gesture : undefined
507
+ const riskAccepted = body.riskAccepted === true
508
+ const rawId = typeof body.requestId === 'string' ? body.requestId.replace(/[^A-Za-z0-9_-]/gu, '').slice(0, 64) : ''
509
+ const requestId = rawId === '' ? crypto.randomUUID() : rawId
510
+ const idempotencyKey = `fishpi-chat-claim-${requestId}`
511
+ const claim = await this.#withAuth(async () => {
512
+ for (let attempt = 0; ; attempt += 1) {
513
+ try {
514
+ return await this.api.claimRedPacket(id, { gesture, riskAccepted }, idempotencyKey)
515
+ } catch (error) {
516
+ const retryable = error instanceof FishPiError
517
+ && attempt === 0
518
+ && (error.code === 'confirmation_required' || error.code === 'network')
519
+ if (!retryable) throw error
520
+ if (error.code === 'network') await delay(400)
521
+ }
522
+ }
523
+ })
524
+ let detail
525
+ try {
526
+ detail = await this.#withAuth(() => this.api.redPacket(id))
527
+ } catch {
528
+ detail = undefined
529
+ }
530
+ return { ok: true, claim, detail: detail ?? null }
531
+ }
532
+
533
+ /** @returns {Promise<Record<string, unknown>>} the current topic. */
534
+ async topic() {
535
+ const data = await this.#withAuth(() => this.api.topic())
536
+ return { ok: true, text: typeof data?.text === 'string' ? data.text : '' }
537
+ }
538
+
539
+ /** @returns {Promise<Record<string, unknown>>} visible online users. */
540
+ async online() {
541
+ const data = await this.#withAuth(() => this.api.onlineUsers({ size: 50 }))
542
+ const list = Array.isArray(data?.list)
543
+ ? data.list
544
+ .filter(user => user !== null && typeof user === 'object')
545
+ .map(user => ({
546
+ id: user.id === undefined ? '' : String(user.id),
547
+ userName: typeof user.userName === 'string' ? user.userName : '',
548
+ userAvatarURL: typeof user.userAvatarURL === 'string' ? user.userAvatarURL : '',
549
+ }))
550
+ : []
551
+ return { ok: true, total: Number(data?.pagination?.total) || list.length, list }
552
+ }
553
+
554
+ /**
555
+ * Send one message with a caller-stable request id.
556
+ * @param {{ content?: unknown, requestId?: unknown }} body - composer payload.
557
+ * @returns {Promise<Record<string, unknown>>}
558
+ */
559
+ async send(body) {
560
+ const content = text(body.content, MAX_MESSAGE_LENGTH + 1)
561
+ if (content === '') throw new FishPiError('消息不能为空', { code: 'invalid_input', status: 400 })
562
+ if (content.length > MAX_MESSAGE_LENGTH) throw new FishPiError('消息超过 4096 个字符', { code: 'invalid_input', status: 400 })
563
+ const rawId = typeof body.requestId === 'string' ? body.requestId.replace(/[^A-Za-z0-9_-]/gu, '').slice(0, 64) : ''
564
+ const requestId = rawId === '' ? crypto.randomUUID() : rawId
565
+ const idempotencyKey = `fishpi-chat-${requestId}`
566
+
567
+ const accepted = await this.#withAuth(async () => {
568
+ for (let attempt = 0; ; attempt += 1) {
569
+ try {
570
+ return await this.api.send(content, idempotencyKey)
571
+ } catch (error) {
572
+ const retryable = error instanceof FishPiError
573
+ && attempt === 0
574
+ && (error.code === 'confirmation_required' || error.code === 'network')
575
+ if (!retryable) throw error
576
+ if (error.code === 'network') await delay(400)
577
+ }
578
+ }
579
+ })
580
+
581
+ let message
582
+ try {
583
+ const raw = await this.#withAuth(() => this.api.message(String(accepted?.id ?? '')))
584
+ message = normalizeMessage(raw)
585
+ } catch {
586
+ message = undefined
587
+ }
588
+ if (message !== undefined) this.hub.emit('message.created', { message })
589
+ return {
590
+ ok: true,
591
+ id: accepted?.id === undefined ? '' : String(accepted.id),
592
+ createdAt: Number(accepted?.createdAt) || Date.now(),
593
+ message: message ?? null,
594
+ }
595
+ }
596
+
597
+ /**
598
+ * @param {{ since?: unknown }} query - browser cursor.
599
+ * @param {AbortSignal} signal - request lifetime.
600
+ * @returns {Promise<Record<string, unknown>>}
601
+ */
602
+ async events(query, signal) {
603
+ const since = integer(query.since, 0, 0, Number.MAX_SAFE_INTEGER)
604
+ return this.hub.wait(since, signal, EVENT_WAIT_MS)
605
+ }
606
+
607
+ /**
608
+ * @param {{ accessToken?: string, expiresIn?: number }} grant - a successful login response.
609
+ * @param {{ nameOrEmail: string, passwordMd5: string, remember: boolean }} account - the credentials to keep.
610
+ */
611
+ async #applyLogin(grant, account) {
612
+ const token = typeof grant?.accessToken === 'string' ? grant.accessToken : ''
613
+ if (token === '') throw new FishPiError('登录响应缺少访问令牌', { code: 'invalid_response' })
614
+ this.api.setToken(token)
615
+ this.tokenExpiresAt = Number(grant?.expiresIn) > 0 ? Date.now() + Number(grant.expiresIn) * 1000 : 0
616
+ const me = await this.api.me()
617
+ const user = normalizeMe(me)
618
+ if (user === undefined) throw new FishPiError('无法读取账号资料', { code: 'invalid_response' })
619
+ this.user = user
620
+ this.loggedIn = true
621
+ this.lastError = undefined
622
+ this.record = {
623
+ version: 1,
624
+ nameOrEmail: account.nameOrEmail,
625
+ passwordMd5: account.remember ? account.passwordMd5 : undefined,
626
+ remember: account.remember,
627
+ accessToken: token,
628
+ tokenExpiresAt: this.tokenExpiresAt,
629
+ user,
630
+ }
631
+ await this.#persist()
632
+ this.#startRealtime()
633
+ this.#emitState()
634
+ }
635
+
636
+ /**
637
+ * @param {string} nameOrEmail - stored account name.
638
+ * @param {string} passwordMd5 - stored digest.
639
+ * @param {boolean} remember - whether to keep the digest.
640
+ */
641
+ async #loginWithDigest(nameOrEmail, passwordMd5, remember) {
642
+ if (this.loginTask !== undefined) {
643
+ await this.loginTask
644
+ return
645
+ }
646
+ this.loginTask = (async () => {
647
+ const grant = await this.api.login({ nameOrEmail, userPassword: passwordMd5 })
648
+ await this.#applyLogin(grant, { nameOrEmail, passwordMd5, remember })
649
+ })()
650
+ try {
651
+ await this.loginTask
652
+ } finally {
653
+ this.loginTask = undefined
654
+ }
655
+ }
656
+
657
+ /**
658
+ * @param {boolean} force - renew even when the current token looks fresh.
659
+ */
660
+ async #ensureAuth(force) {
661
+ if (this.loggedIn && !force && (this.tokenExpiresAt === 0 || this.tokenExpiresAt > Date.now() + 60_000)) return
662
+ if (this.record?.passwordMd5) {
663
+ try {
664
+ await this.#loginWithDigest(String(this.record.nameOrEmail ?? ''), String(this.record.passwordMd5), this.record.remember !== false)
665
+ return
666
+ } catch (error) {
667
+ this.#rememberFailure(error)
668
+ throw error
669
+ }
670
+ }
671
+ this.loggedIn = false
672
+ this.api.setToken('')
673
+ const error = new FishPiError('登录已失效,请在设置中重新登录', { code: 'unauthorized', status: 401 })
674
+ this.lastError = error
675
+ this.#emitState()
676
+ throw error
677
+ }
678
+
679
+ /**
680
+ * Run an authenticated operation, renewing once after a 401.
681
+ * @template T
682
+ * @param {() => Promise<T>} operation - the API call.
683
+ * @returns {Promise<T>}
684
+ */
685
+ async #withAuth(operation) {
686
+ await this.#ensureAuth(false)
687
+ try {
688
+ const result = await operation()
689
+ this.lastError = undefined
690
+ return result
691
+ } catch (error) {
692
+ if (error instanceof FishPiError && (error.status === 401 || error.code === 'unauthorized')) {
693
+ this.loggedIn = false
694
+ this.api.setToken('')
695
+ await this.#ensureAuth(true)
696
+ const result = await operation()
697
+ this.lastError = undefined
698
+ return result
699
+ }
700
+ throw error
701
+ }
702
+ }
703
+
704
+ /** Persist the current account record without failing the caller. */
705
+ async #persist() {
706
+ if (this.record === undefined) return
707
+ try {
708
+ await this.ctx.credentials.modifyRecord(CREDENTIAL_KEY, () => ({ kind: 'grant', payload: this.record }))
709
+ } catch (error) {
710
+ warn(this.ctx, 'could not store credentials', error)
711
+ }
712
+ }
713
+
714
+ /** Start a fresh socket for the current token. */
715
+ #startRealtime() {
716
+ if (this.stopped) return
717
+ this.realtime?.stop()
718
+ this.connectionState = 'connecting'
719
+ this.realtime = new ChatRealtime({
720
+ siteUrl: DEFAULT_SITE,
721
+ getTicket: async () => {
722
+ try {
723
+ await this.#ensureAuth(false)
724
+ return await this.api.realtimeTicket()
725
+ } catch (error) {
726
+ if (error instanceof FishPiError && (error.status === 401 || error.code === 'unauthorized')) {
727
+ await this.#ensureAuth(true)
728
+ return await this.api.realtimeTicket()
729
+ }
730
+ throw error
731
+ }
732
+ },
733
+ onState: state => {
734
+ this.connectionState = state
735
+ this.hub.emit('connection', { state })
736
+ this.#emitState()
737
+ },
738
+ onEvent: event => { void this.#onRealtime(event) },
739
+ onError: error => {
740
+ if (error instanceof FishPiError && (error.status === 401 || error.code === 'unauthorized')) {
741
+ this.loggedIn = false
742
+ this.api.setToken('')
743
+ this.#emitState()
744
+ }
745
+ },
746
+ })
747
+ this.realtime.start()
748
+ }
749
+
750
+ /**
751
+ * @param {{ type: string, data: any }} event - one socket event.
752
+ */
753
+ async #onRealtime(event) {
754
+ if (this.stopped) return
755
+ if (event.type === 'ready') {
756
+ this.hub.emit('sync', { reason: 'ready' })
757
+ return
758
+ }
759
+ const message = event.data
760
+ if (message === null || typeof message !== 'object') return
761
+ switch (message.type) {
762
+ case 'chat.message.created':
763
+ case 'chat.message.updated': {
764
+ const snapshot = normalizeMessage(message.data?.message)
765
+ if (snapshot !== undefined) {
766
+ this.hub.emit(message.type === 'chat.message.created' ? 'message.created' : 'message.updated', { message: snapshot })
767
+ return
768
+ }
769
+ const id = message.data?.messageId === undefined ? '' : String(message.data.messageId)
770
+ if (id !== '') await this.#fetchAndEmitMessage(id, message.type === 'chat.message.updated')
771
+ return
772
+ }
773
+ case 'chat.message.deleted': {
774
+ const id = message.data?.messageId === undefined ? '' : String(message.data.messageId)
775
+ if (id !== '') this.hub.emit('message.deleted', { messageId: id })
776
+ return
777
+ }
778
+ case 'chat.message.reactions':
779
+ return
780
+ case 'chat.topic_changed': {
781
+ void this.#refreshTopic()
782
+ return
783
+ }
784
+ case 'chat.sync_required': {
785
+ this.hub.emit('sync', { reason: 'server' })
786
+ return
787
+ }
788
+ case 'chat.presence.changed': {
789
+ const data = message.data ?? {}
790
+ this.hub.emit('presence', {
791
+ id: data.id === undefined ? '' : String(data.id),
792
+ kind: data.kind === 'leave' ? 'leave' : 'join',
793
+ text: typeof data.text === 'string' ? data.text : '',
794
+ actor: data.actor ?? null,
795
+ mount: data.mount ?? null,
796
+ avatarURL: typeof data.avatarURL === 'string' ? data.avatarURL : '',
797
+ createdAt: Number(data.createdAt) || Date.now(),
798
+ })
799
+ return
800
+ }
801
+ case 'chat.red_packet.claimed': {
802
+ const data = message.data ?? {}
803
+ this.hub.emit('redPacket.claimed', {
804
+ id: data.id === undefined ? '' : String(data.id),
805
+ sender: data.sender ?? null,
806
+ actor: data.actor ?? null,
807
+ got: Number(data.got) || 0,
808
+ count: Number(data.count) || 0,
809
+ createdAt: Number(data.createdAt) || Date.now(),
810
+ })
811
+ return
812
+ }
813
+ default:
814
+ return
815
+ }
816
+ }
817
+
818
+ /** Re-read the topic and publish it. */
819
+ async #refreshTopic() {
820
+ try {
821
+ const data = await this.#withAuth(() => this.api.topic())
822
+ this.hub.emit('topic', { text: typeof data?.text === 'string' ? data.text : '' })
823
+ } catch {
824
+ // A topic refresh is best-effort; the next sync retries it.
825
+ }
826
+ }
827
+
828
+ /**
829
+ * @param {string} id - message id from a revision-only event.
830
+ * @param {boolean} updated - whether the message already existed.
831
+ */
832
+ async #fetchAndEmitMessage(id, updated) {
833
+ try {
834
+ const raw = await this.#withAuth(() => this.api.message(id))
835
+ const message = normalizeMessage(raw)
836
+ if (message !== undefined) {
837
+ this.hub.emit(updated ? 'message.updated' : 'message.created', { message })
838
+ }
839
+ } catch {
840
+ // The next sync reads the window again, so a missed snapshot is recoverable.
841
+ }
842
+ }
843
+
844
+ /** Publish the whole session state to every browser. */
845
+ #emitState() {
846
+ this.hub.emit('state', this.state())
847
+ }
848
+
849
+ /**
850
+ * @param {unknown} error - the last failed operation.
851
+ */
852
+ #rememberFailure(error) {
853
+ this.lastError = error instanceof FishPiError
854
+ ? error
855
+ : new FishPiError(error instanceof Error ? error.message : '操作失败', { code: 'internal' })
856
+ if (this.lastError.code === 'unauthorized' || this.lastError.status === 401) {
857
+ this.loggedIn = false
858
+ this.api.setToken('')
859
+ }
860
+ this.#emitState()
861
+ }
862
+ }
863
+
864
+ /**
865
+ * Host plugin body.
866
+ * @param {import('@deepseek-ai/cordis').Context} ctx - loader context with `connection` and `credentials`.
867
+ */
868
+ export function apply(ctx) {
869
+ const hub = new EventHub({ limit: EVENT_LOG_LIMIT })
870
+ const chat = new FishPiChat({ ctx, hub })
871
+
872
+ /**
873
+ * @param {string} path - exact path below `/api`.
874
+ * @param {('GET'|'POST')[]} methods - methods this route owns.
875
+ * @param {(request: Request) => Promise<Response>} fetch - authenticated handler.
876
+ */
877
+ const route = (path, methods, fetch) => {
878
+ ctx.effect(
879
+ () => ctx.connection.fetch.register({ path: `${API_PREFIX}${path}`, methods, requestBody: 'buffered', fetch }),
880
+ `fishpi-chat route ${path}`,
881
+ )
882
+ }
883
+
884
+ route('/state', ['GET'], async () => json(chat.state()))
885
+ route('/login', ['POST'], async request => {
886
+ try {
887
+ return json(await chat.login(await readJson(request)))
888
+ } catch (error) {
889
+ return failure(error)
890
+ }
891
+ })
892
+ route('/logout', ['POST'], async () => {
893
+ try {
894
+ return json(await chat.logout())
895
+ } catch (error) {
896
+ return failure(error)
897
+ }
898
+ })
899
+ route('/messages', ['GET'], async request => {
900
+ try {
901
+ const url = new URL(request.url)
902
+ return json(await chat.messages({
903
+ size: url.searchParams.get('size'),
904
+ before: url.searchParams.get('before'),
905
+ after: url.searchParams.get('after'),
906
+ }))
907
+ } catch (error) {
908
+ return failure(error)
909
+ }
910
+ })
911
+ route('/send', ['POST'], async request => {
912
+ try {
913
+ return json(await chat.send(await readJson(request)))
914
+ } catch (error) {
915
+ return failure(error)
916
+ }
917
+ })
918
+ route('/medals', ['GET'], async request => {
919
+ try {
920
+ const url = new URL(request.url)
921
+ const names = (url.searchParams.get('names') ?? '').split(',').filter(Boolean)
922
+ return json(await chat.medals(names))
923
+ } catch (error) {
924
+ return failure(error)
925
+ }
926
+ })
927
+ route('/user', ['GET'], async request => {
928
+ try {
929
+ const url = new URL(request.url)
930
+ return json(await chat.userInfo({ name: url.searchParams.get('name') }))
931
+ } catch (error) {
932
+ return failure(error)
933
+ }
934
+ })
935
+ route('/users', ['GET'], async request => {
936
+ try {
937
+ const url = new URL(request.url)
938
+ return json(await chat.suggestUsers({ prefix: url.searchParams.get('prefix') }))
939
+ } catch (error) {
940
+ return failure(error)
941
+ }
942
+ })
943
+ route('/upload', ['POST'], async request => {
944
+ try {
945
+ return json(await chat.upload(await request.formData()))
946
+ } catch (error) {
947
+ return failure(error)
948
+ }
949
+ })
950
+ route('/red-packet', ['GET'], async request => {
951
+ try {
952
+ const url = new URL(request.url)
953
+ return json(await chat.redPacket({ id: url.searchParams.get('id') }))
954
+ } catch (error) {
955
+ return failure(error)
956
+ }
957
+ })
958
+ route('/red-packet/claim', ['POST'], async request => {
959
+ try {
960
+ return json(await chat.claimRedPacket(await readJson(request)))
961
+ } catch (error) {
962
+ return failure(error)
963
+ }
964
+ })
965
+ route('/topic', ['GET'], async () => {
966
+ try {
967
+ return json(await chat.topic())
968
+ } catch (error) {
969
+ return failure(error)
970
+ }
971
+ })
972
+ route('/online', ['GET'], async () => {
973
+ try {
974
+ return json(await chat.online())
975
+ } catch (error) {
976
+ return failure(error)
977
+ }
978
+ })
979
+ route('/events', ['GET'], async request => {
980
+ try {
981
+ const url = new URL(request.url)
982
+ return json(await chat.events({ since: url.searchParams.get('since') }, request.signal))
983
+ } catch (error) {
984
+ return failure(error)
985
+ }
986
+ })
987
+
988
+ ctx.effect(() => () => { chat.dispose() }, 'fishpi-chat lifetime')
989
+ void chat.initialize()
990
+ }