@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.
Binary file
package/fishpi.js CHANGED
@@ -9,12 +9,26 @@
9
9
  */
10
10
 
11
11
  import { createHash } from 'node:crypto'
12
+ import { readFileSync } from 'node:fs'
12
13
 
13
14
  /** FishPi production origin. A deployment may override it in the service. */
14
15
  export const DEFAULT_SITE = 'https://fishpi.cn'
15
16
 
17
+ /** The version this package reports; read from the packaged manifest, never guessed. */
18
+ function readPackageVersion() {
19
+ try {
20
+ const manifest = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
21
+ return typeof manifest.version === 'string' && manifest.version !== '' ? manifest.version : '0.0.0'
22
+ } catch {
23
+ return '0.0.0'
24
+ }
25
+ }
26
+
27
+ /** The installed extension version, used by the client tag and update check. */
28
+ export const PLUGIN_VERSION = readPackageVersion()
29
+
16
30
  /** Client tag accepted by `/api/v3/chat/messages` (`brand/version`). */
17
- export const CLIENT_TAG = 'DSH/fishpi-chat-0.1.0'
31
+ export const CLIENT_TAG = `Extension/DSH ${PLUGIN_VERSION}`
18
32
 
19
33
  /** The largest body the public chat message endpoint accepts. */
20
34
  export const MAX_MESSAGE_LENGTH = 4096
@@ -42,6 +56,49 @@ export function md5Hex(value) {
42
56
  return createHash('md5').update(value, 'utf8').digest('hex')
43
57
  }
44
58
 
59
+ /**
60
+ * The HttpOnly refresh cookie the website login sets. The Host keeps its value
61
+ * in the DSH credential store and sends it back to `/api/v3/auth/refresh`, which
62
+ * rotates it on every successful refresh.
63
+ */
64
+ export const REFRESH_COOKIE_NAME = 'fp_v3_refresh'
65
+
66
+ /**
67
+ * Read every `Set-Cookie` line from a Fetch response without relying on a
68
+ * cookie jar. Node exposes `getSetCookie()`; a single joined header is the
69
+ * fallback for runtimes that do not.
70
+ * @param {Headers|undefined} headers - response headers.
71
+ * @returns {string[]} cookie lines.
72
+ */
73
+ function setCookieLines(headers) {
74
+ if (headers === undefined || headers === null) return []
75
+ if (typeof headers.getSetCookie === 'function') {
76
+ try {
77
+ const lines = headers.getSetCookie()
78
+ if (Array.isArray(lines)) return lines
79
+ } catch {
80
+ // Fall through to the single-header form.
81
+ }
82
+ }
83
+ const raw = typeof headers.get === 'function' ? headers.get('set-cookie') : null
84
+ return typeof raw === 'string' && raw !== '' ? [raw] : []
85
+ }
86
+
87
+ /**
88
+ * Extract the refresh cookie value from `Set-Cookie` lines.
89
+ * @param {string[]} lines - cookie lines.
90
+ * @returns {string} the token, or an empty string.
91
+ */
92
+ export function refreshCookieFrom(lines) {
93
+ const pattern = new RegExp(`(?:^|,\\s*)${REFRESH_COOKIE_NAME}=([^;,\\s]+)`)
94
+ for (const line of lines) {
95
+ if (typeof line !== 'string') continue
96
+ const match = pattern.exec(line)
97
+ if (match !== null) return match[1]
98
+ }
99
+ return ''
100
+ }
101
+
45
102
  /**
46
103
  * Remove the parts of a FishPi message the sidebar never renders and make the
47
104
  * shape predictable for the browser.
@@ -85,20 +142,26 @@ export function normalizeMessage(raw) {
85
142
  /**
86
143
  * A slim public user record for the Host state and message snapshots.
87
144
  * @param {unknown} raw - `/api/v3/me` data.
88
- * @returns {{ id: string, userName: string, userNickname: string, userAvatarURL: string, userPoint?: number }|undefined}
145
+ * @returns {{ id: string, userName: string, userNickname: string, userAvatarURL: string, userPoint?: number, capabilities?: { chatRevokeOthers: boolean }, userRole?: string }|undefined}
89
146
  */
90
147
  export function normalizeMe(raw) {
91
148
  if (raw === null || typeof raw !== 'object') return undefined
92
149
  const source = /** @type {Record<string, any>} */ (raw)
93
150
  const id = source.id === undefined || source.id === null ? '' : String(source.id)
94
151
  if (id === '') return undefined
95
- return {
152
+ /** @type {{ id: string, userName: string, userNickname: string, userAvatarURL: string, userPoint?: number, capabilities?: { chatRevokeOthers: boolean }, userRole?: string }} */
153
+ const user = {
96
154
  id,
97
155
  userName: typeof source.userName === 'string' ? source.userName : '',
98
156
  userNickname: typeof source.userNickname === 'string' ? source.userNickname : '',
99
157
  userAvatarURL: typeof source.userAvatarURL === 'string' ? source.userAvatarURL : '',
100
158
  userPoint: Number.isFinite(Number(source.userPoint)) ? Number(source.userPoint) : undefined,
101
159
  }
160
+ if (source.capabilities !== null && typeof source.capabilities === 'object') {
161
+ user.capabilities = { chatRevokeOthers: source.capabilities.chatRevokeOthers === true }
162
+ }
163
+ if (typeof source.userRole === 'string' && source.userRole !== '') user.userRole = source.userRole
164
+ return user
102
165
  }
103
166
 
104
167
  /**
@@ -137,8 +200,8 @@ export class FishPiApi {
137
200
  /**
138
201
  * One enveloped API request.
139
202
  * @param {string} path - absolute API path.
140
- * @param {{ method?: string, body?: unknown, signal?: AbortSignal, auth?: boolean, idempotencyKey?: string, raw?: boolean }} [options] - request shape.
141
- * @returns {Promise<any>} the envelope's `data`, or the raw JSON payload when `raw` is true.
203
+ * @param {{ method?: string, body?: unknown, signal?: AbortSignal, auth?: boolean, idempotencyKey?: string, raw?: boolean, headers?: Record<string, string>, captureCookies?: boolean }} [options] - request shape.
204
+ * @returns {Promise<any>} the envelope's `data`, or `{ data, setCookies }` when `captureCookies` is true.
142
205
  */
143
206
  async request(path, options = {}) {
144
207
  const method = options.method ?? 'GET'
@@ -152,6 +215,7 @@ export class FishPiApi {
152
215
  }
153
216
  if (options.auth !== false && this.token !== '') headers.authorization = `Bearer ${this.token}`
154
217
  if (options.idempotencyKey !== undefined) headers['idempotency-key'] = options.idempotencyKey
218
+ if (options.headers !== undefined && options.headers !== null) Object.assign(headers, options.headers)
155
219
  const timeout = AbortSignal.timeout(25_000)
156
220
  init.signal = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout])
157
221
 
@@ -183,19 +247,81 @@ export class FishPiApi {
183
247
  },
184
248
  )
185
249
  }
250
+ if (options.captureCookies === true) {
251
+ return {
252
+ data: options.raw === true ? payload : envelope.data,
253
+ setCookies: setCookieLines(response.headers),
254
+ }
255
+ }
186
256
  if (options.raw === true) return payload
187
257
  return envelope.data
188
258
  }
189
259
 
190
260
  /**
191
261
  * @param {{ nameOrEmail: string, userPassword: string, mfaCode?: string }} input - credentials; password is already MD5.
192
- * @returns {Promise<{ accessToken: string, tokenType?: string, expiresIn?: number, scope?: string }>} a login grant.
262
+ * @returns {Promise<{ accessToken: string, tokenType?: string, expiresIn?: number, refreshExpiresIn?: number, scope?: string, refreshCookie?: string }>} a login grant and the rotating refresh cookie.
193
263
  */
194
- login(input) {
264
+ async login(input) {
195
265
  /** @type {Record<string, string>} */
196
266
  const body = { nameOrEmail: input.nameOrEmail, userPassword: input.userPassword }
197
267
  if (input.mfaCode !== undefined && input.mfaCode !== '') body.mfaCode = input.mfaCode
198
- return this.request('/api/v3/auth/login', { method: 'POST', body, auth: false })
268
+ const result = await this.request('/api/v3/auth/login', {
269
+ method: 'POST',
270
+ body,
271
+ auth: false,
272
+ captureCookies: true,
273
+ })
274
+ const grant = result.data !== null && typeof result.data === 'object' ? result.data : {}
275
+ return { ...grant, refreshCookie: refreshCookieFrom(result.setCookies) }
276
+ }
277
+
278
+ /**
279
+ * Rotate an expired access token with the website refresh cookie.
280
+ *
281
+ * The website refresh endpoint checks the request's Origin, so the Host sends
282
+ * the same origin the first-party page would; it does not need any other
283
+ * cookie because the refresh token itself is the credential.
284
+ * @param {string} refreshCookie - the `fp_v3_refresh` value.
285
+ * @returns {Promise<{ accessToken: string, expiresIn?: number, refreshExpiresIn?: number, scope?: string, refreshCookie?: string }>} the new access token and rotated cookie.
286
+ */
287
+ async refreshWebsite(refreshCookie) {
288
+ if (typeof refreshCookie !== 'string' || refreshCookie === '') {
289
+ throw new FishPiError('登录状态已失效,请重新登录', { code: 'unauthorized', status: 401 })
290
+ }
291
+ const origin = new URL(this.siteUrl).origin
292
+ const result = await this.request('/api/v3/auth/refresh', {
293
+ method: 'POST',
294
+ body: {},
295
+ auth: false,
296
+ captureCookies: true,
297
+ headers: {
298
+ origin,
299
+ referer: `${this.siteUrl}/`,
300
+ cookie: `${REFRESH_COOKIE_NAME}=${refreshCookie}`,
301
+ },
302
+ })
303
+ const grant = result.data !== null && typeof result.data === 'object' ? result.data : {}
304
+ return { ...grant, refreshCookie: refreshCookieFrom(result.setCookies) }
305
+ }
306
+
307
+ /**
308
+ * End the website session that owns the refresh cookie, when possible.
309
+ * @param {string} refreshCookie - the `fp_v3_refresh` value.
310
+ * @returns {Promise<void>}
311
+ */
312
+ async logoutWebsite(refreshCookie) {
313
+ if (typeof refreshCookie !== 'string' || refreshCookie === '') return
314
+ const origin = new URL(this.siteUrl).origin
315
+ await this.request('/api/v3/auth/logout', {
316
+ method: 'POST',
317
+ body: {},
318
+ auth: false,
319
+ headers: {
320
+ origin,
321
+ referer: `${this.siteUrl}/`,
322
+ cookie: `${REFRESH_COOKIE_NAME}=${refreshCookie}`,
323
+ },
324
+ })
199
325
  }
200
326
 
201
327
  /** @returns {Promise<any>} the current account profile. */
@@ -224,6 +350,19 @@ export class FishPiApi {
224
350
  return this.request(`/api/v3/chat/messages/${encodeURIComponent(id)}`)
225
351
  }
226
352
 
353
+ /**
354
+ * Recall (withdraw) one of the current account's messages.
355
+ * @param {string} id - message id.
356
+ * @param {string} idempotencyKey - stable key for this logical recall.
357
+ * @returns {Promise<{ removed?: boolean }>} the withdrawal receipt.
358
+ */
359
+ revokeMessage(id, idempotencyKey) {
360
+ return this.request(`/api/v3/chat/messages/${encodeURIComponent(id)}`, {
361
+ method: 'DELETE',
362
+ idempotencyKey,
363
+ })
364
+ }
365
+
227
366
  /**
228
367
  * @param {string} content - Markdown body, already trimmed by the caller.
229
368
  * @param {string} idempotencyKey - stable key for this logical send.