fix(onebot): sign forward-msg media + pick image rkey by appid (#74)

/get_forward_msg returned raw, rkey-less image/media URLs because
getForwardMessage converted forward nodes WITHOUT the URL resolvers the
normal receive path (to-message.ts) uses. Wire imageUrlResolver +
mediaUrlResolver into it so forwarded images/voice/video get signed
download URLs — exactly issue #74 (image url 缺少 rkey).

Also derive the image rkey scene from the appid baked into the URL
(1406 -> private, 1407 -> group) instead of the carrying message's
group/private context, falling back to isGroup only when the URL has no
recognised appid. A c2c image forwarded into a group keeps its original
c2c appid, so the old isGroup-based pick signed it with the group rkey ->
`invalid rkey` on download. Mirrors NapCat's getImageUrlFromParsedUrl;
Lagrange/NapCat both reuse one unified converter so this never drifts.

Fix the self-contradictory `c2c images` rkey test (its fixture used the
group appid 1407) and add cross-tests asserting appid outranks isGroup
both ways, plus the no-appid fallback.
This commit is contained in:
DrSmoothl committed 2026-05-31 23:50:08 +08:00
1 parent f9252fb26d
commit 0d63bf7415
3 files changed
+88 -13

No files matched your search

+29 -6
View File
@@ -43,7 +43,18 @@ export class RKeyCache {
const url = element.imageUrl ?? '';
if (!urlNeedsRKey(url)) return url;
const rkey = await this.findRKey(bridge, isGroup);
// The rkey scene must follow the IMAGE's own upload context, not the
// message currently carrying it. A c2c image forwarded into a group
// keeps its original c2c fileid/appid (1406); signing it with the
// group rkey just because the forward node looks like a group message
// yields `invalid rkey` on download. So derive the scene from the
// appid baked into the URL, and only fall back to `isGroup` when the
// URL carries no recognised appid (legacy gchat / unknown shapes).
// Mirrors NapCat's getImageUrlFromParsedUrl (appid 1406 → private,
// 1407 → group).
const primaryType = imageRKeyTypeFromUrl(url)
?? (isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE);
const rkey = await this.findRKeyForType(bridge, primaryType);
if (!rkey) return url;
const cleanRKey = stripRKeyPrefix(rkey);
@@ -90,11 +101,6 @@ export class RKeyCache {
}
}
private findRKey(bridge: BridgeInterface, isGroup: boolean): Promise<string | null> {
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
return this.findRKeyForType(bridge, primaryType);
}
/** Pull a still-valid rkey out of the cache, or null if missing/expiring. */
private findInCache(primaryType: number): string | null {
const now = Math.floor(Date.now() / 1000);
@@ -153,6 +159,23 @@ export class RKeyCache {
}
}
// QQ-NT download appids embedded in the image URL query string. The scene
// they encode is a property of the image (where it was uploaded), so they
// outrank the carrying message's group/private context — see resolveImageUrl.
const APPID_PRIVATE_IMAGE = '1406';
const APPID_GROUP_IMAGE = '1407';
/** Map the `appid` baked into an NT download URL to its rkey type. Returns
* null when the URL carries no recognised appid, leaving the caller to fall
* back to the message's group/private context. */
function imageRKeyTypeFromUrl(url: string): number | null {
const match = url.match(/[?&]appid=(\d+)/);
if (!match) return null;
if (match[1] === APPID_PRIVATE_IMAGE) return PRIVATE_IMAGE_RKEY_TYPE;
if (match[1] === APPID_GROUP_IMAGE) return GROUP_IMAGE_RKEY_TYPE;
return null;
}
function urlNeedsRKey(url: string): boolean {
if (!url || url.includes('rkey=')) return false;
if (url.includes('gchat.qpic.cn')) return false;
+10 -1
View File
@@ -675,7 +675,16 @@ export async function getForwardMessage(
for (const node of nodes) {
const isGroup = node.messageType === 'group' || (node.groupId !== undefined && node.groupId > 0);
const sessionId = isGroup ? (node.groupId ?? 0) : node.userUin;
const segments = await elementsToOneBotSegments(node.elements, isGroup, sessionId);
// Route forward nodes through the SAME resolver-equipped conversion the
// normal receive path uses (to-message.ts). Without the image/media URL
// resolvers the segments come back with raw, rkey-less download URLs —
// exactly issue #74 (`/get_forward_msg` image url 缺少 rkey). Image rkey
// re-signing is scene-aware via the appid in the URL (see instance-rkey).
const segments = await elementsToOneBotSegments(
node.elements, isGroup, sessionId,
ref.converterCtx.imageUrlResolver,
ref.converterCtx.mediaUrlResolver,
);
const sender: JsonObject = {
user_id: node.userUin,
+49 -6
View File
@@ -3,7 +3,9 @@ import { RKeyCache } from '../src/instance-rkey';
import type { MessageElement } from '@snowluma/protocol/events';
// The screenshot URL: a raw QQ-NT multimedia download link with no rkey yet.
// appid 1407 = group image, 1406 = private/c2c image (see instance-rkey).
const NT_IMAGE_URL = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=ABC';
const NT_PRIVATE_IMAGE_URL = 'https://multimedia.nt.qq.com.cn/download?appid=1406&fileid=XYZ';
const GROUP_IMAGE_TYPE = 20;
const PRIVATE_IMAGE_TYPE = 10;
@@ -20,10 +22,21 @@ function freshGroupRkey(value = 'GROUPKEY') {
return [{ rkey: value, type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 }];
}
function freshBothRkeys() {
return [
{ rkey: 'PRIVATEKEY', type: PRIVATE_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
{ rkey: 'GROUPKEY', type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
];
}
function imageEl(): MessageElement {
return { type: 'image', imageUrl: NT_IMAGE_URL };
}
function privateImageEl(): MessageElement {
return { type: 'image', imageUrl: NT_PRIVATE_IMAGE_URL };
}
describe('RKeyCache.resolveImageUrl', () => {
it('awaits a refresh on a cold cache and appends the rkey', async () => {
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
@@ -69,16 +82,46 @@ describe('RKeyCache.resolveImageUrl', () => {
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
});
it('uses the private rkey type for c2c images', async () => {
const { bridge } = makeBridge(async () => [
{ rkey: 'PRIVATEKEY', type: PRIVATE_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
{ rkey: 'GROUPKEY', type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
]);
it('uses the private rkey type for c2c images (appid 1406)', async () => {
const { bridge } = makeBridge(async () => freshBothRkeys());
const cache = new RKeyCache();
const url = await cache.resolveImageUrl(bridge as never, privateImageEl(), false);
expect(url).toBe(`${NT_PRIVATE_IMAGE_URL}&rkey=PRIVATEKEY`);
});
// The scene follows the image's own appid, not the carrying message — the
// crux of `/get_forward_msg` rkey correctness (issue #74): a c2c image
// forwarded into a group must still be signed with the private rkey.
it('signs an appid-1406 image with the private rkey even when isGroup is true', async () => {
const { bridge } = makeBridge(async () => freshBothRkeys());
const cache = new RKeyCache();
const url = await cache.resolveImageUrl(bridge as never, privateImageEl(), true);
expect(url).toBe(`${NT_PRIVATE_IMAGE_URL}&rkey=PRIVATEKEY`);
});
it('signs an appid-1407 image with the group rkey even when isGroup is false', async () => {
const { bridge } = makeBridge(async () => freshBothRkeys());
const cache = new RKeyCache();
const url = await cache.resolveImageUrl(bridge as never, imageEl(), false);
expect(url).toBe(`${NT_IMAGE_URL}&rkey=PRIVATEKEY`);
expect(url).toBe(`${NT_IMAGE_URL}&rkey=GROUPKEY`);
});
it('falls back to the isGroup scene when the URL carries no appid', async () => {
const noAppidUrl = 'https://multimedia.nt.qq.com.cn/download?fileid=NOAPPID';
const { bridge } = makeBridge(async () => freshBothRkeys());
const cache = new RKeyCache();
const url = await cache.resolveImageUrl(
bridge as never, { type: 'image', imageUrl: noAppidUrl }, true,
);
expect(url).toBe(`${noAppidUrl}&rkey=GROUPKEY`);
});
it('leaves non-NT URLs untouched and never fetches', async () => {