fix(onebot): re-sign image rkey on get_image / get_msg lookups

get_image and get_msg returned the URL baked into the message store when
the message first arrived. That URL's rkey expires, so a client fetching
it later (or re-querying after the original push) got
`{"retcode":-5503010,"retmsg":"invalid rkey"}`.

Re-sign at lookup time from the raw unsigned `imageUrl` the media store
already keeps alongside the signed `url` (plus `isGroup`): getImageInfo
now takes the image rkey resolver and mints a current rkey, and get_msg
walks its segment array refreshing each image URL through it. Both are
best-effort — a resolver miss/throw or a non-array message body falls
back to the stored URL untouched. Mirrors NapCat re-signing on every
getImageUrl call instead of handing back a stale baked URL.

The resolver is reused from converterCtx (no new rkeyCache wiring); a
cache-hit re-sign is a string concat, only an expired rkey awaits the
already-deduped/cooled-down/timeout-bounded refresh.
This commit is contained in:
DrSmoothl committed 2026-05-29 20:14:21 +08:00
1 parent ba19cee07d
commit 4a0626f00b
4 files changed
+116 -2

No files matched your search

+30
View File
@@ -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<void> {
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<string, JsonValue> };
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);
});
+1 -1
View File
@@ -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),
};
}
+22 -1
View File
@@ -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<JsonObject | null> {
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,
@@ -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> = {}): 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();
});
});