@iwpz/fishpi-dsh 0.1.0 → 0.1.2
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/README.md +195 -94
- package/client.js +581 -69
- package/docs/screenshot.jpg +0 -0
- package/fishpi.js +147 -8
- package/index.js +436 -22
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -22,8 +22,18 @@ import {
|
|
|
22
22
|
md5Hex,
|
|
23
23
|
normalizeMe,
|
|
24
24
|
normalizeMessage,
|
|
25
|
+
PLUGIN_VERSION,
|
|
25
26
|
} from './fishpi.js'
|
|
26
27
|
|
|
28
|
+
/** This package's npm identity and the cadence of its update reminder. */
|
|
29
|
+
const PACKAGE_NAME = '@iwpz/fishpi-dsh'
|
|
30
|
+
const UPDATE_CHECK_INTERVAL_MS = 60 * 60 * 1000
|
|
31
|
+
const UPDATE_REQUEST_TIMEOUT_MS = 8_000
|
|
32
|
+
const UPDATE_SOURCES = [
|
|
33
|
+
{ source: 'npm', url: `https://registry.npmjs.org/${encodeURIComponent(PACKAGE_NAME)}/latest` },
|
|
34
|
+
{ source: 'npmmirror', url: `https://registry.npmmirror.com/${encodeURIComponent(PACKAGE_NAME)}/latest` },
|
|
35
|
+
]
|
|
36
|
+
|
|
27
37
|
/** Credential record address: `<scope>/<id>`, both lowercase hyphenated. */
|
|
28
38
|
const CREDENTIAL_KEY = 'fishpi-chat/account'
|
|
29
39
|
|
|
@@ -36,6 +46,56 @@ const EVENT_WAIT_MS = 20_000
|
|
|
36
46
|
/** Retained realtime events; the browser reloads its window on a gap. */
|
|
37
47
|
const EVENT_LOG_LIMIT = 500
|
|
38
48
|
|
|
49
|
+
/**
|
|
50
|
+
* Parse a semver-like version, including an optional prerelease.
|
|
51
|
+
* @param {unknown} value - candidate version.
|
|
52
|
+
* @returns {{ major: number, minor: number, patch: number, pre: string }|undefined}
|
|
53
|
+
*/
|
|
54
|
+
function parseVersion(value) {
|
|
55
|
+
if (typeof value !== 'string') return undefined
|
|
56
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/u.exec(value.trim())
|
|
57
|
+
if (match === null) return undefined
|
|
58
|
+
return {
|
|
59
|
+
major: Number(match[1]),
|
|
60
|
+
minor: Number(match[2]),
|
|
61
|
+
patch: Number(match[3]),
|
|
62
|
+
pre: match[4] ?? '',
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Compare two semver-like versions. A prerelease sorts below its release.
|
|
68
|
+
* @param {unknown} left - first version.
|
|
69
|
+
* @param {unknown} right - second version.
|
|
70
|
+
* @returns {-1|0|1} negative when `left` is older.
|
|
71
|
+
*/
|
|
72
|
+
export function compareVersions(left, right) {
|
|
73
|
+
const first = parseVersion(left)
|
|
74
|
+
const second = parseVersion(right)
|
|
75
|
+
if (first === undefined || second === undefined) return 0
|
|
76
|
+
for (const part of ['major', 'minor', 'patch']) {
|
|
77
|
+
if (first[part] !== second[part]) return first[part] < second[part] ? -1 : 1
|
|
78
|
+
}
|
|
79
|
+
if (first.pre === second.pre) return 0
|
|
80
|
+
if (first.pre === '') return 1
|
|
81
|
+
if (second.pre === '') return -1
|
|
82
|
+
const leftParts = first.pre.split('.')
|
|
83
|
+
const rightParts = second.pre.split('.')
|
|
84
|
+
for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
|
|
85
|
+
const a = leftParts[index]
|
|
86
|
+
const b = rightParts[index]
|
|
87
|
+
if (a === undefined) return -1
|
|
88
|
+
if (b === undefined) return 1
|
|
89
|
+
if (a === b) continue
|
|
90
|
+
const aNumeric = /^\d+$/u.test(a)
|
|
91
|
+
const bNumeric = /^\d+$/u.test(b)
|
|
92
|
+
if (aNumeric && bNumeric) return Number(a) < Number(b) ? -1 : 1
|
|
93
|
+
if (aNumeric !== bNumeric) return aNumeric ? -1 : 1
|
|
94
|
+
return a < b ? -1 : 1
|
|
95
|
+
}
|
|
96
|
+
return 0
|
|
97
|
+
}
|
|
98
|
+
|
|
39
99
|
/** Cordis Host services this plugin needs. */
|
|
40
100
|
export const inject = ['connection', 'credentials']
|
|
41
101
|
|
|
@@ -162,6 +222,7 @@ class FishPiChat {
|
|
|
162
222
|
this.ctx = options.ctx
|
|
163
223
|
this.hub = options.hub
|
|
164
224
|
this.api = new FishPiApi({ siteUrl: DEFAULT_SITE })
|
|
225
|
+
this.updateCheckEnabled = options.updateCheck !== false
|
|
165
226
|
this.stopped = false
|
|
166
227
|
this.initialized = false
|
|
167
228
|
this.loggedIn = false
|
|
@@ -169,6 +230,9 @@ class FishPiChat {
|
|
|
169
230
|
/** @type {Record<string, any>|undefined} */
|
|
170
231
|
this.record = undefined
|
|
171
232
|
this.tokenExpiresAt = 0
|
|
233
|
+
/** @type {string} */
|
|
234
|
+
this.refreshCookie = ''
|
|
235
|
+
this.refreshExpiresAt = 0
|
|
172
236
|
/** @type {'connecting'|'connected'|'disconnected'} */
|
|
173
237
|
this.connectionState = 'disconnected'
|
|
174
238
|
/** @type {FishPiError|undefined} */
|
|
@@ -177,11 +241,27 @@ class FishPiChat {
|
|
|
177
241
|
this.realtime = undefined
|
|
178
242
|
/** @type {Promise<void>|undefined} */
|
|
179
243
|
this.loginTask = undefined
|
|
244
|
+
/** @type {Promise<void>|undefined} */
|
|
245
|
+
this.refreshTask = undefined
|
|
180
246
|
/** @type {Map<string, { at: number, medals: object[] }>} */
|
|
181
247
|
this.medalCache = new Map()
|
|
248
|
+
this.updateInfo = {
|
|
249
|
+
current: PLUGIN_VERSION,
|
|
250
|
+
latest: '',
|
|
251
|
+
available: false,
|
|
252
|
+
localAhead: false,
|
|
253
|
+
url: '',
|
|
254
|
+
source: '',
|
|
255
|
+
checkedAt: 0,
|
|
256
|
+
error: null,
|
|
257
|
+
}
|
|
258
|
+
/** @type {Promise<object>|undefined} */
|
|
259
|
+
this.updateTask = undefined
|
|
260
|
+
this.updateTimer = undefined
|
|
261
|
+
this.lastUpdateCheckAt = 0
|
|
182
262
|
}
|
|
183
263
|
|
|
184
|
-
/** Load stored credentials, validate the token, and start the socket. */
|
|
264
|
+
/** Load stored credentials, validate or renew the token, and start the socket. */
|
|
185
265
|
async initialize() {
|
|
186
266
|
try {
|
|
187
267
|
const stored = await this.ctx.credentials.readRecord(CREDENTIAL_KEY)
|
|
@@ -195,21 +275,34 @@ class FishPiChat {
|
|
|
195
275
|
if (this.record?.accessToken) {
|
|
196
276
|
this.api.setToken(String(this.record.accessToken))
|
|
197
277
|
this.tokenExpiresAt = Number(this.record.tokenExpiresAt) || 0
|
|
278
|
+
this.refreshExpiresAt = Number(this.record.refreshExpiresAt) || 0
|
|
279
|
+
this.refreshCookie = typeof this.record.refreshCookie === 'string' ? this.record.refreshCookie : ''
|
|
198
280
|
try {
|
|
199
|
-
|
|
200
|
-
this.user = normalizeMe(me)
|
|
201
|
-
this.loggedIn = this.user !== undefined
|
|
281
|
+
await this.#loadMe()
|
|
202
282
|
} catch (error) {
|
|
203
283
|
const authFailure = error instanceof FishPiError
|
|
204
284
|
&& (error.status === 401 || error.status === 403 || error.code === 'unauthorized')
|
|
205
285
|
if (authFailure) {
|
|
206
286
|
this.api.setToken('')
|
|
287
|
+
this.tokenExpiresAt = 0
|
|
207
288
|
this.user = undefined
|
|
208
289
|
this.loggedIn = false
|
|
209
290
|
} else {
|
|
210
291
|
this.#rememberFailure(error)
|
|
211
292
|
}
|
|
212
293
|
}
|
|
294
|
+
} else if (this.record?.refreshCookie) {
|
|
295
|
+
this.refreshCookie = String(this.record.refreshCookie)
|
|
296
|
+
this.refreshExpiresAt = Number(this.record.refreshExpiresAt) || 0
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
if (!this.loggedIn && this.refreshCookie !== '') {
|
|
300
|
+
try {
|
|
301
|
+
await this.#refreshSession()
|
|
302
|
+
await this.#loadMe()
|
|
303
|
+
} catch (error) {
|
|
304
|
+
this.#rememberFailure(error)
|
|
305
|
+
}
|
|
213
306
|
}
|
|
214
307
|
|
|
215
308
|
if (!this.loggedIn && this.record?.passwordMd5) {
|
|
@@ -222,12 +315,15 @@ class FishPiChat {
|
|
|
222
315
|
|
|
223
316
|
this.initialized = true
|
|
224
317
|
if (this.loggedIn && this.realtime === undefined) this.#startRealtime()
|
|
318
|
+
this.#startUpdateWatch()
|
|
225
319
|
this.#emitState()
|
|
226
320
|
}
|
|
227
321
|
|
|
228
322
|
/** Release the socket and every held event request. */
|
|
229
323
|
dispose() {
|
|
230
324
|
this.stopped = true
|
|
325
|
+
clearInterval(this.updateTimer)
|
|
326
|
+
this.updateTimer = undefined
|
|
231
327
|
this.realtime?.stop()
|
|
232
328
|
this.realtime = undefined
|
|
233
329
|
this.hub.dispose()
|
|
@@ -246,10 +342,160 @@ class FishPiChat {
|
|
|
246
342
|
cursor: this.hub.seq,
|
|
247
343
|
mfaRequired: this.lastError?.code === 'mfa_required',
|
|
248
344
|
error: this.lastError === undefined ? null : { code: this.lastError.code, message: this.lastError.message },
|
|
345
|
+
persistent: this.record?.refreshCookie !== undefined && this.record.refreshCookie !== '',
|
|
346
|
+
refreshExpiresAt: this.refreshExpiresAt || null,
|
|
347
|
+
update: this.updateState(),
|
|
348
|
+
hostVersion: PLUGIN_VERSION,
|
|
249
349
|
siteUrl: DEFAULT_SITE,
|
|
250
350
|
}
|
|
251
351
|
}
|
|
252
352
|
|
|
353
|
+
/** @returns {Record<string, unknown>} the latest npm version check, safe for the browser. */
|
|
354
|
+
updateState() {
|
|
355
|
+
return {
|
|
356
|
+
current: this.updateInfo.current,
|
|
357
|
+
latest: this.updateInfo.latest,
|
|
358
|
+
available: this.updateInfo.available,
|
|
359
|
+
localAhead: this.updateInfo.localAhead === true,
|
|
360
|
+
url: this.updateInfo.url,
|
|
361
|
+
source: this.updateInfo.source,
|
|
362
|
+
checkedAt: this.updateInfo.checkedAt,
|
|
363
|
+
error: this.updateInfo.error === null || this.updateInfo.error === undefined
|
|
364
|
+
? null
|
|
365
|
+
: { code: this.updateInfo.error.code, message: this.updateInfo.error.message },
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Ask the npm registry for the latest published version and publish the result.
|
|
371
|
+
* Failures are returned as state rather than thrown, so a reminder never blocks
|
|
372
|
+
* chat operations.
|
|
373
|
+
* @returns {Promise<Record<string, unknown>>} the browser-safe update state.
|
|
374
|
+
*/
|
|
375
|
+
async checkForUpdate() {
|
|
376
|
+
return this.#runUpdateCheck()
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* One shared registry check. Concurrent callers await the same request.
|
|
381
|
+
* @returns {Promise<Record<string, unknown>>} the browser-safe update state.
|
|
382
|
+
*/
|
|
383
|
+
async #runUpdateCheck() {
|
|
384
|
+
if (this.updateTask !== undefined) return this.updateTask
|
|
385
|
+
this.updateTask = (async () => {
|
|
386
|
+
const checkedAt = Date.now()
|
|
387
|
+
try {
|
|
388
|
+
const latest = await this.#fetchLatestVersion()
|
|
389
|
+
this.updateInfo = {
|
|
390
|
+
current: PLUGIN_VERSION,
|
|
391
|
+
latest: latest.version,
|
|
392
|
+
available: compareVersions(PLUGIN_VERSION, latest.version) < 0,
|
|
393
|
+
localAhead: compareVersions(PLUGIN_VERSION, latest.version) > 0,
|
|
394
|
+
url: `https://www.npmjs.com/package/${PACKAGE_NAME}/v/${encodeURIComponent(latest.version)}`,
|
|
395
|
+
source: latest.source,
|
|
396
|
+
checkedAt,
|
|
397
|
+
error: null,
|
|
398
|
+
}
|
|
399
|
+
} catch (error) {
|
|
400
|
+
this.updateInfo = {
|
|
401
|
+
...this.updateInfo,
|
|
402
|
+
checkedAt,
|
|
403
|
+
error: {
|
|
404
|
+
code: 'update_check_failed',
|
|
405
|
+
message: error instanceof Error && error.message !== '' ? error.message : '检查更新失败',
|
|
406
|
+
},
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
this.lastUpdateCheckAt = checkedAt
|
|
410
|
+
this.#emitState()
|
|
411
|
+
return this.updateState()
|
|
412
|
+
})()
|
|
413
|
+
try {
|
|
414
|
+
return await this.updateTask
|
|
415
|
+
} finally {
|
|
416
|
+
this.updateTask = undefined
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Install the newest published version through the DSH plugin manager.
|
|
422
|
+
* Returns a clear refusal for development links and Git installs, which the
|
|
423
|
+
* manager does not update from a registry version.
|
|
424
|
+
* @returns {Promise<Record<string, unknown>>}
|
|
425
|
+
*/
|
|
426
|
+
async installUpdate() {
|
|
427
|
+
const version = this.updateInfo.available === true ? this.updateInfo.latest : ''
|
|
428
|
+
if (version === '') throw new FishPiError('当前没有可安装的新版本', { code: 'no_update', status: 409 })
|
|
429
|
+
const manager = this.ctx.get('pluginManager')
|
|
430
|
+
if (manager === undefined || typeof manager.listBundles !== 'function' || typeof manager.updateBundle !== 'function') {
|
|
431
|
+
throw new FishPiError('当前 DSH 没有可用的插件管理器', { code: 'update_unavailable', status: 503 })
|
|
432
|
+
}
|
|
433
|
+
let bundle
|
|
434
|
+
try {
|
|
435
|
+
const bundles = await manager.listBundles()
|
|
436
|
+
bundle = Array.isArray(bundles) ? bundles.find(item => item?.name === PACKAGE_NAME) : undefined
|
|
437
|
+
} catch (error) {
|
|
438
|
+
throw new FishPiError('无法读取插件安装状态', { code: 'update_failed', cause: error })
|
|
439
|
+
}
|
|
440
|
+
if (bundle === undefined) throw new FishPiError('找不到已安装的插件', { code: 'update_unavailable', status: 503 })
|
|
441
|
+
if (bundle.update !== 'registry') {
|
|
442
|
+
throw new FishPiError('当前是本地开发或 Git 安装,请在 Plugins 页面手动更新', { code: 'not_updatable', status: 409 })
|
|
443
|
+
}
|
|
444
|
+
const result = await manager.updateBundle(PACKAGE_NAME, version)
|
|
445
|
+
this.updateInfo = { ...this.updateInfo, available: false }
|
|
446
|
+
this.#emitState()
|
|
447
|
+
return { ok: true, version, result }
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** @returns {Promise<{ version: string, source: string }>} the newest published version. */
|
|
451
|
+
async #fetchLatestVersion() {
|
|
452
|
+
if (typeof globalThis.fetch !== 'function') throw new Error('当前运行环境不支持网络请求')
|
|
453
|
+
let lastError
|
|
454
|
+
for (const endpoint of UPDATE_SOURCES) {
|
|
455
|
+
try {
|
|
456
|
+
const signal = typeof AbortSignal.timeout === 'function'
|
|
457
|
+
? AbortSignal.timeout(UPDATE_REQUEST_TIMEOUT_MS)
|
|
458
|
+
: undefined
|
|
459
|
+
const response = await globalThis.fetch(endpoint.url, {
|
|
460
|
+
headers: { accept: 'application/json' },
|
|
461
|
+
credentials: 'omit',
|
|
462
|
+
signal,
|
|
463
|
+
})
|
|
464
|
+
if (!response.ok) {
|
|
465
|
+
lastError = new Error(`HTTP ${response.status}`)
|
|
466
|
+
continue
|
|
467
|
+
}
|
|
468
|
+
let payload
|
|
469
|
+
try {
|
|
470
|
+
payload = await response.json()
|
|
471
|
+
} catch {
|
|
472
|
+
lastError = new Error('npm 返回了无法解析的响应')
|
|
473
|
+
continue
|
|
474
|
+
}
|
|
475
|
+
const version = typeof payload?.version === 'string' ? payload.version.trim() : ''
|
|
476
|
+
if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(version)) {
|
|
477
|
+
lastError = new Error('npm 返回了无法识别的版本')
|
|
478
|
+
continue
|
|
479
|
+
}
|
|
480
|
+
return { version, source: endpoint.source }
|
|
481
|
+
} catch (error) {
|
|
482
|
+
lastError = error
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
throw lastError instanceof Error ? lastError : new Error('无法连接 npm registry')
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** Start the periodic npm reminder; one check per process interval. */
|
|
489
|
+
#startUpdateWatch() {
|
|
490
|
+
if (!this.updateCheckEnabled || this.updateTimer !== undefined) return
|
|
491
|
+
void this.checkForUpdate()
|
|
492
|
+
this.updateTimer = setInterval(() => {
|
|
493
|
+
if (Date.now() - this.lastUpdateCheckAt < UPDATE_CHECK_INTERVAL_MS) return
|
|
494
|
+
void this.checkForUpdate()
|
|
495
|
+
}, UPDATE_CHECK_INTERVAL_MS)
|
|
496
|
+
this.updateTimer.unref?.()
|
|
497
|
+
}
|
|
498
|
+
|
|
253
499
|
/**
|
|
254
500
|
* @param {{ nameOrEmail?: unknown, password?: unknown, mfaCode?: unknown, remember?: unknown }} body - login form.
|
|
255
501
|
* @returns {Promise<Record<string, unknown>>}
|
|
@@ -269,7 +515,7 @@ class FishPiChat {
|
|
|
269
515
|
if (grant?.mfaRequired === true || grant?.mfa_required === true) {
|
|
270
516
|
return { ok: false, code: 'mfa_required', message: '该账号启用了两步验证,请输入验证码', mfaRequired: true }
|
|
271
517
|
}
|
|
272
|
-
await this.#applyLogin(grant, {
|
|
518
|
+
await this.#applyLogin(grant, { remember })
|
|
273
519
|
return { ok: true, user: this.user }
|
|
274
520
|
} catch (error) {
|
|
275
521
|
if (error instanceof FishPiError && error.code === 'mfa_required') {
|
|
@@ -288,15 +534,25 @@ class FishPiChat {
|
|
|
288
534
|
|
|
289
535
|
/** Forget the account and its stored credentials. */
|
|
290
536
|
async logout() {
|
|
537
|
+
const cookie = this.refreshCookie !== ''
|
|
538
|
+
? this.refreshCookie
|
|
539
|
+
: (typeof this.record?.refreshCookie === 'string' ? this.record.refreshCookie : '')
|
|
291
540
|
this.loggedIn = false
|
|
292
541
|
this.user = undefined
|
|
293
542
|
this.record = undefined
|
|
294
543
|
this.api.setToken('')
|
|
295
544
|
this.tokenExpiresAt = 0
|
|
545
|
+
this.refreshCookie = ''
|
|
546
|
+
this.refreshExpiresAt = 0
|
|
296
547
|
this.lastError = undefined
|
|
297
548
|
this.realtime?.stop()
|
|
298
549
|
this.realtime = undefined
|
|
299
550
|
this.connectionState = 'disconnected'
|
|
551
|
+
if (cookie !== '') {
|
|
552
|
+
void this.api.logoutWebsite(cookie).catch(error => {
|
|
553
|
+
warn(this.ctx, 'could not end the remote session', error)
|
|
554
|
+
})
|
|
555
|
+
}
|
|
300
556
|
try {
|
|
301
557
|
await this.ctx.credentials.deleteRecord(CREDENTIAL_KEY)
|
|
302
558
|
} catch (error) {
|
|
@@ -551,6 +807,22 @@ class FishPiChat {
|
|
|
551
807
|
return { ok: true, total: Number(data?.pagination?.total) || list.length, list }
|
|
552
808
|
}
|
|
553
809
|
|
|
810
|
+
/**
|
|
811
|
+
* Recall one of the current account's messages.
|
|
812
|
+
* @param {{ id?: unknown, requestId?: unknown }} body - recall request.
|
|
813
|
+
* @returns {Promise<Record<string, unknown>>}
|
|
814
|
+
*/
|
|
815
|
+
async recall(body) {
|
|
816
|
+
const id = typeof body.id === 'string' && /^\d+$/u.test(body.id) ? body.id : ''
|
|
817
|
+
if (id === '') throw new FishPiError('消息 ID 不正确', { code: 'invalid_input', status: 400 })
|
|
818
|
+
const rawId = typeof body.requestId === 'string' ? body.requestId.replace(/[^A-Za-z0-9_-]/gu, '').slice(0, 64) : ''
|
|
819
|
+
const requestId = rawId === '' ? crypto.randomUUID() : rawId
|
|
820
|
+
const result = await this.#withAuth(() => this.api.revokeMessage(id, `fishpi-chat-revoke-${requestId}`))
|
|
821
|
+
if (result?.removed === false) throw new FishPiError('消息未能撤回', { code: 'recall_failed' })
|
|
822
|
+
this.hub.emit('message.deleted', { messageId: id })
|
|
823
|
+
return { ok: true, id, removed: true }
|
|
824
|
+
}
|
|
825
|
+
|
|
554
826
|
/**
|
|
555
827
|
* Send one message with a caller-stable request id.
|
|
556
828
|
* @param {{ content?: unknown, requestId?: unknown }} body - composer payload.
|
|
@@ -605,38 +877,64 @@ class FishPiChat {
|
|
|
605
877
|
}
|
|
606
878
|
|
|
607
879
|
/**
|
|
608
|
-
* @param {{ accessToken?: string, expiresIn?: number }} grant - a successful login response.
|
|
609
|
-
* @param {{
|
|
880
|
+
* @param {{ accessToken?: string, expiresIn?: number, refreshExpiresIn?: number, refreshCookie?: string }} grant - a successful login or refresh response.
|
|
881
|
+
* @param {{ remember: boolean }} account - whether to persist the refresh cookie.
|
|
610
882
|
*/
|
|
611
883
|
async #applyLogin(grant, account) {
|
|
612
884
|
const token = typeof grant?.accessToken === 'string' ? grant.accessToken : ''
|
|
613
885
|
if (token === '') throw new FishPiError('登录响应缺少访问令牌', { code: 'invalid_response' })
|
|
614
886
|
this.api.setToken(token)
|
|
615
887
|
this.tokenExpiresAt = Number(grant?.expiresIn) > 0 ? Date.now() + Number(grant.expiresIn) * 1000 : 0
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
if (
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
this.lastError = undefined
|
|
888
|
+
this.refreshCookie = typeof grant?.refreshCookie === 'string' ? grant.refreshCookie : ''
|
|
889
|
+
this.refreshExpiresAt = Number(grant?.refreshExpiresIn) > 0 ? Date.now() + Number(grant.refreshExpiresIn) * 1000 : 0
|
|
890
|
+
if (this.refreshCookie === '') {
|
|
891
|
+
warn(this.ctx, 'login response did not include the refresh cookie; the session will expire with the access token', new Error('missing fp_v3_refresh'))
|
|
892
|
+
}
|
|
622
893
|
this.record = {
|
|
623
|
-
version:
|
|
624
|
-
nameOrEmail: account.nameOrEmail,
|
|
625
|
-
passwordMd5: account.remember ? account.passwordMd5 : undefined,
|
|
626
|
-
remember: account.remember,
|
|
894
|
+
version: 2,
|
|
627
895
|
accessToken: token,
|
|
628
896
|
tokenExpiresAt: this.tokenExpiresAt,
|
|
629
|
-
|
|
897
|
+
refreshExpiresAt: this.refreshExpiresAt,
|
|
898
|
+
refreshCookie: account.remember && this.refreshCookie !== '' ? this.refreshCookie : undefined,
|
|
899
|
+
remember: account.remember,
|
|
630
900
|
}
|
|
901
|
+
// Keep the fresh refresh credential even if the profile read fails; the
|
|
902
|
+
// next Host start can recover the session without another sign-in.
|
|
631
903
|
await this.#persist()
|
|
904
|
+
try {
|
|
905
|
+
await this.#loadMe()
|
|
906
|
+
} catch (error) {
|
|
907
|
+
if (error instanceof FishPiError && (error.status === 401 || error.code === 'unauthorized')) {
|
|
908
|
+
await this.#clearSession()
|
|
909
|
+
}
|
|
910
|
+
throw error
|
|
911
|
+
}
|
|
912
|
+
if (this.record !== undefined) {
|
|
913
|
+
this.record.user = this.user
|
|
914
|
+
await this.#persist()
|
|
915
|
+
}
|
|
632
916
|
this.#startRealtime()
|
|
633
917
|
this.#emitState()
|
|
634
918
|
}
|
|
635
919
|
|
|
920
|
+
/** Read `/api/v3/me` and publish the signed-in identity. */
|
|
921
|
+
async #loadMe() {
|
|
922
|
+
const me = await this.api.me()
|
|
923
|
+
const user = normalizeMe(me)
|
|
924
|
+
if (user === undefined) throw new FishPiError('无法读取账号资料', { code: 'invalid_response' })
|
|
925
|
+
this.user = user
|
|
926
|
+
this.loggedIn = true
|
|
927
|
+
this.lastError = undefined
|
|
928
|
+
if (this.record !== undefined) {
|
|
929
|
+
this.record.user = user
|
|
930
|
+
await this.#persist()
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
|
|
636
934
|
/**
|
|
637
935
|
* @param {string} nameOrEmail - stored account name.
|
|
638
936
|
* @param {string} passwordMd5 - stored digest.
|
|
639
|
-
* @param {boolean} remember - whether to keep the
|
|
937
|
+
* @param {boolean} remember - whether to keep the new refresh cookie.
|
|
640
938
|
*/
|
|
641
939
|
async #loginWithDigest(nameOrEmail, passwordMd5, remember) {
|
|
642
940
|
if (this.loginTask !== undefined) {
|
|
@@ -645,7 +943,7 @@ class FishPiChat {
|
|
|
645
943
|
}
|
|
646
944
|
this.loginTask = (async () => {
|
|
647
945
|
const grant = await this.api.login({ nameOrEmail, userPassword: passwordMd5 })
|
|
648
|
-
await this.#applyLogin(grant, {
|
|
946
|
+
await this.#applyLogin(grant, { remember })
|
|
649
947
|
})()
|
|
650
948
|
try {
|
|
651
949
|
await this.loginTask
|
|
@@ -654,11 +952,106 @@ class FishPiChat {
|
|
|
654
952
|
}
|
|
655
953
|
}
|
|
656
954
|
|
|
955
|
+
/**
|
|
956
|
+
* Rotate the access token with the stored refresh cookie.
|
|
957
|
+
*
|
|
958
|
+
* Refreshes are serialized because fishpi rotates the cookie and invalidates
|
|
959
|
+
* the previous value; two concurrent refreshes would revoke the session.
|
|
960
|
+
*/
|
|
961
|
+
async #refreshSession() {
|
|
962
|
+
if (this.refreshTask !== undefined) {
|
|
963
|
+
await this.refreshTask
|
|
964
|
+
return
|
|
965
|
+
}
|
|
966
|
+
const cookie = this.refreshCookie !== ''
|
|
967
|
+
? this.refreshCookie
|
|
968
|
+
: (typeof this.record?.refreshCookie === 'string' ? this.record.refreshCookie : '')
|
|
969
|
+
if (cookie === '') {
|
|
970
|
+
throw new FishPiError('登录状态已失效,请重新登录', { code: 'unauthorized', status: 401 })
|
|
971
|
+
}
|
|
972
|
+
if (this.refreshExpiresAt > 0 && this.refreshExpiresAt <= Date.now()) {
|
|
973
|
+
await this.#clearSession()
|
|
974
|
+
throw new FishPiError('登录状态已过期,请重新登录', { code: 'unauthorized', status: 401 })
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
this.refreshTask = (async () => {
|
|
978
|
+
let grant
|
|
979
|
+
try {
|
|
980
|
+
grant = await this.api.refreshWebsite(cookie)
|
|
981
|
+
} catch (error) {
|
|
982
|
+
if (error instanceof FishPiError && (error.status === 401 || error.code === 'unauthorized')) {
|
|
983
|
+
await this.#clearSession()
|
|
984
|
+
}
|
|
985
|
+
throw error
|
|
986
|
+
}
|
|
987
|
+
const token = typeof grant?.accessToken === 'string' ? grant.accessToken : ''
|
|
988
|
+
if (token === '') {
|
|
989
|
+
await this.#clearSession()
|
|
990
|
+
throw new FishPiError('刷新响应缺少访问令牌', { code: 'invalid_response' })
|
|
991
|
+
}
|
|
992
|
+
this.api.setToken(token)
|
|
993
|
+
this.tokenExpiresAt = Number(grant.expiresIn) > 0 ? Date.now() + Number(grant.expiresIn) * 1000 : 0
|
|
994
|
+
if (typeof grant.refreshCookie === 'string' && grant.refreshCookie !== '') {
|
|
995
|
+
this.refreshCookie = grant.refreshCookie
|
|
996
|
+
}
|
|
997
|
+
if (Number(grant.refreshExpiresIn) > 0) {
|
|
998
|
+
this.refreshExpiresAt = Date.now() + Number(grant.refreshExpiresIn) * 1000
|
|
999
|
+
}
|
|
1000
|
+
this.loggedIn = true
|
|
1001
|
+
this.lastError = undefined
|
|
1002
|
+
if (this.record !== undefined) {
|
|
1003
|
+
this.record.version = 2
|
|
1004
|
+
this.record.accessToken = token
|
|
1005
|
+
this.record.tokenExpiresAt = this.tokenExpiresAt
|
|
1006
|
+
this.record.refreshExpiresAt = this.refreshExpiresAt
|
|
1007
|
+
if (this.record.remember !== false && this.refreshCookie !== '') {
|
|
1008
|
+
this.record.refreshCookie = this.refreshCookie
|
|
1009
|
+
}
|
|
1010
|
+
await this.#persist()
|
|
1011
|
+
}
|
|
1012
|
+
this.#emitState()
|
|
1013
|
+
})()
|
|
1014
|
+
try {
|
|
1015
|
+
await this.refreshTask
|
|
1016
|
+
} finally {
|
|
1017
|
+
this.refreshTask = undefined
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
/** Drop the local session and its credential record. */
|
|
1022
|
+
async #clearSession() {
|
|
1023
|
+
this.loggedIn = false
|
|
1024
|
+
this.user = undefined
|
|
1025
|
+
this.record = undefined
|
|
1026
|
+
this.api.setToken('')
|
|
1027
|
+
this.tokenExpiresAt = 0
|
|
1028
|
+
this.refreshCookie = ''
|
|
1029
|
+
this.refreshExpiresAt = 0
|
|
1030
|
+
this.realtime?.stop()
|
|
1031
|
+
this.realtime = undefined
|
|
1032
|
+
this.connectionState = 'disconnected'
|
|
1033
|
+
try {
|
|
1034
|
+
await this.ctx.credentials.deleteRecord(CREDENTIAL_KEY)
|
|
1035
|
+
} catch (error) {
|
|
1036
|
+
warn(this.ctx, 'could not delete expired credentials', error)
|
|
1037
|
+
}
|
|
1038
|
+
this.#emitState()
|
|
1039
|
+
}
|
|
1040
|
+
|
|
657
1041
|
/**
|
|
658
1042
|
* @param {boolean} force - renew even when the current token looks fresh.
|
|
659
1043
|
*/
|
|
660
1044
|
async #ensureAuth(force) {
|
|
661
1045
|
if (this.loggedIn && !force && (this.tokenExpiresAt === 0 || this.tokenExpiresAt > Date.now() + 60_000)) return
|
|
1046
|
+
if (this.refreshCookie !== '' || typeof this.record?.refreshCookie === 'string') {
|
|
1047
|
+
try {
|
|
1048
|
+
await this.#refreshSession()
|
|
1049
|
+
return
|
|
1050
|
+
} catch (error) {
|
|
1051
|
+
this.#rememberFailure(error)
|
|
1052
|
+
throw error
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
662
1055
|
if (this.record?.passwordMd5) {
|
|
663
1056
|
try {
|
|
664
1057
|
await this.#loginWithDigest(String(this.record.nameOrEmail ?? ''), String(this.record.passwordMd5), this.record.remember !== false)
|
|
@@ -865,9 +1258,9 @@ class FishPiChat {
|
|
|
865
1258
|
* Host plugin body.
|
|
866
1259
|
* @param {import('@deepseek-ai/cordis').Context} ctx - loader context with `connection` and `credentials`.
|
|
867
1260
|
*/
|
|
868
|
-
export function apply(ctx) {
|
|
1261
|
+
export function apply(ctx, config = {}) {
|
|
869
1262
|
const hub = new EventHub({ limit: EVENT_LOG_LIMIT })
|
|
870
|
-
const chat = new FishPiChat({ ctx, hub })
|
|
1263
|
+
const chat = new FishPiChat({ ctx, hub, updateCheck: config?.updateCheck !== false })
|
|
871
1264
|
|
|
872
1265
|
/**
|
|
873
1266
|
* @param {string} path - exact path below `/api`.
|
|
@@ -915,6 +1308,13 @@ export function apply(ctx) {
|
|
|
915
1308
|
return failure(error)
|
|
916
1309
|
}
|
|
917
1310
|
})
|
|
1311
|
+
route('/recall', ['POST'], async request => {
|
|
1312
|
+
try {
|
|
1313
|
+
return json(await chat.recall(await readJson(request)))
|
|
1314
|
+
} catch (error) {
|
|
1315
|
+
return failure(error)
|
|
1316
|
+
}
|
|
1317
|
+
})
|
|
918
1318
|
route('/medals', ['GET'], async request => {
|
|
919
1319
|
try {
|
|
920
1320
|
const url = new URL(request.url)
|
|
@@ -976,6 +1376,20 @@ export function apply(ctx) {
|
|
|
976
1376
|
return failure(error)
|
|
977
1377
|
}
|
|
978
1378
|
})
|
|
1379
|
+
route('/update/install', ['POST'], async () => {
|
|
1380
|
+
try {
|
|
1381
|
+
return json(await chat.installUpdate())
|
|
1382
|
+
} catch (error) {
|
|
1383
|
+
return failure(error)
|
|
1384
|
+
}
|
|
1385
|
+
})
|
|
1386
|
+
route('/update/check', ['POST'], async () => {
|
|
1387
|
+
try {
|
|
1388
|
+
return json({ ok: true, update: await chat.checkForUpdate() })
|
|
1389
|
+
} catch (error) {
|
|
1390
|
+
return failure(error)
|
|
1391
|
+
}
|
|
1392
|
+
})
|
|
979
1393
|
route('/events', ['GET'], async request => {
|
|
980
1394
|
try {
|
|
981
1395
|
const url = new URL(request.url)
|