diff --git a/packages/onebot/src/actions/message.ts b/packages/onebot/src/actions/message.ts index da45e939..b2fbe754 100644 --- a/packages/onebot/src/actions/message.ts +++ b/packages/onebot/src/actions/message.ts @@ -3,6 +3,35 @@ import type { ApiHandler, ApiActionContext } from '../api-handler'; import { asNumber, asString, asBoolean, asMessage } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; +/** + * Re-sign image URLs in a stored message event at read time. `get_msg` + * returns a copy persisted when the message first arrived, and image rkeys + * expire — so walk the segment array and refresh each image URL through + * `ctx.getImageInfo`, which mints a current rkey. Best-effort and in-place; + * `findEvent` returns a fresh parse, so mutating the array is safe. + */ +async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext): Promise { + const segments = event.message; + if (!Array.isArray(segments)) return; + for (const seg of segments) { + if (!seg || typeof seg !== 'object') continue; + const segment = seg as { type?: unknown; data?: Record }; + if (segment.type !== 'image') continue; + const data = segment.data; + if (!data || typeof data !== 'object') continue; + const file = typeof data.file === 'string' ? data.file + : typeof data.file_id === 'string' ? data.file_id + : ''; + if (!file) continue; + try { + const info = await ctx.getImageInfo(file); + if (info && typeof info.url === 'string' && info.url) data.url = info.url; + } catch { + // Keep the stored URL when the refresh fails. + } + } +} + export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('send_msg', async (params) => { const messageType = asString(params.message_type); @@ -77,6 +106,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { delete result.post_type; delete result.self_id; result.real_id = (result.message_id ?? messageId) as JsonValue; + await refreshStoredImageUrls(result, ctx); return okResponse(result); }); diff --git a/packages/onebot/src/instance-context.ts b/packages/onebot/src/instance-context.ts index e32fecfc..50ccb3d3 100644 --- a/packages/onebot/src/instance-context.ts +++ b/packages/onebot/src/instance-context.ts @@ -114,7 +114,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { complete: cachedCount >= serverCount, }; }, - getImageInfo: (file) => getCachedImageInfo(mediaStore, file), + getImageInfo: (file) => getCachedImageInfo(mediaStore, file, ref.converterCtx.imageUrlResolver), getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file), }; } diff --git a/packages/onebot/src/modules/media-actions.ts b/packages/onebot/src/modules/media-actions.ts index 08ee1fe5..156885b2 100644 --- a/packages/onebot/src/modules/media-actions.ts +++ b/packages/onebot/src/modules/media-actions.ts @@ -1,5 +1,7 @@ import { createLogger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { MessageElement } from '@snowluma/protocol/events'; +import type { ImageUrlResolver } from '../event-converter'; import type { MediaStore } from '../media-store'; import type { JsonObject } from '../types'; @@ -8,10 +10,29 @@ const log = createLogger('OneBot'); export async function getImageInfo( mediaStore: MediaStore, file: string, + imageUrlResolver?: ImageUrlResolver | null, ): Promise { const cached = mediaStore.findImage(file); if (!cached) return null; - const url = cached.url || cached.imageUrl || ''; + + let url = cached.url || cached.imageUrl || ''; + + // Re-sign with a current rkey at lookup time. The stored `url` was signed + // when the message first arrived and its rkey may have since expired — the + // CDN then rejects the download with + // `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Resolving from the raw + // (unsigned) `imageUrl` mints a fresh rkey, mirroring NapCat which + // re-signs on every getImageUrl call instead of handing back a baked URL. + if (imageUrlResolver && cached.imageUrl) { + try { + const element: MessageElement = { type: 'image', imageUrl: cached.imageUrl, subType: cached.subType }; + const fresh = await imageUrlResolver(element, cached.isGroup); + if (fresh) url = fresh; + } catch { + // Best-effort: fall back to the stored URL on any resolver failure. + } + } + return { file: url || cached.file, url, diff --git a/packages/onebot/tests/media-actions.test.ts b/packages/onebot/tests/media-actions.test.ts new file mode 100644 index 00000000..d3a4cfa1 --- /dev/null +++ b/packages/onebot/tests/media-actions.test.ts @@ -0,0 +1,63 @@ +import { describe, it, expect, vi } from 'vitest'; +import type { MessageElement } from '@snowluma/protocol/events'; +import { getImageInfo } from '../src/modules/media-actions'; +import type { CachedImage, MediaStore } from '../src/media-store'; + +const RAW = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=ABC'; + +function fakeStore(image: CachedImage | null): MediaStore { + return { findImage: () => image } as unknown as MediaStore; +} + +function cachedImage(overrides: Partial = {}): CachedImage { + return { + file: 'ABC.jpg', + url: `${RAW}&rkey=STALE`, // signed when the message arrived; now expired + fileSize: 100, + fileName: 'ABC.jpg', + subType: 0, + summary: '', + isGroup: true, + sessionId: 123, + imageUrl: RAW, // raw, unsigned — the basis for re-signing + ...overrides, + }; +} + +describe('getImageInfo — rkey re-signing at lookup time', () => { + it('re-signs from the raw imageUrl via the resolver', async () => { + const resolver = vi.fn(async (el: MessageElement) => `${el.imageUrl}&rkey=FRESH`); + + const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg', resolver); + + expect(info?.url).toBe(`${RAW}&rkey=FRESH`); + expect(info?.file).toBe(`${RAW}&rkey=FRESH`); + expect(resolver).toHaveBeenCalledWith( + expect.objectContaining({ type: 'image', imageUrl: RAW }), + true, // isGroup carried through + ); + }); + + it('returns the stored URL when no resolver is wired', async () => { + const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg'); + expect(info?.url).toBe(`${RAW}&rkey=STALE`); + }); + + it('falls back to the stored URL when the resolver throws', async () => { + const resolver = vi.fn(async () => { throw new Error('rkey fetch failed'); }); + const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg', resolver); + expect(info?.url).toBe(`${RAW}&rkey=STALE`); + }); + + it('skips re-signing when no raw imageUrl is stored', async () => { + const resolver = vi.fn(async () => 'should-not-be-used'); + const info = await getImageInfo(fakeStore(cachedImage({ imageUrl: '' })), 'ABC.jpg', resolver); + expect(resolver).not.toHaveBeenCalled(); + expect(info?.url).toBe(`${RAW}&rkey=STALE`); + }); + + it('returns null when the image is not cached', async () => { + const info = await getImageInfo(fakeStore(null), 'missing.jpg'); + expect(info).toBeNull(); + }); +});