fix(onebot): await a fresh rkey before signing media URLs
Image/video/record download URLs are signed at receive-time with an rkey
(OIDB 0x9067_202, TTL-bounded). RKeyCache resolved synchronously: on a
cache miss or inside the expiry skew it returned the URL *without* an
rkey and only kicked off a fire-and-forget refresh (plus a 30s cooldown).
So during the expire→refresh window — and whenever the OIDB hiccuped —
SnowLuma emitted unsigned URLs, which the CDN rejects with
`{"retcode":-5503010,"retmsg":"invalid rkey"}`. Intermittent by nature.
Mirror NapCat's getImageUrl (`if (isExpired()) await refreshRkey()`):
make resolveImageUrl/resolveMediaUrl async and block on one refresh when
the cache can't serve a still-valid rkey. The refresh coalesces
concurrent callers onto a single OIDB round-trip, backs off for 30s after
a failure, and is bounded by a 5s timeout so a stuck packet send never
wedges message conversion (it degrades to whatever the cache holds).
Widen ImageUrlResolver to `string | Promise<string>` and await it in
to-segment so the image path can resolve asynchronously like media.
This commit is contained in:
4 files changed
+156
-27
No files matched your search
@@ -25,7 +25,7 @@ import {
|
||||
} from './to-request';
|
||||
import { elementsToJson } from './to-segment';
|
||||
|
||||
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
|
||||
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string | Promise<string>;
|
||||
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
|
||||
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ async function elementToSegment(
|
||||
}
|
||||
|
||||
if (element.type === 'image') {
|
||||
const url = imageUrlResolver ? imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
|
||||
const url = imageUrlResolver ? await imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
|
||||
const data: JsonObject = {
|
||||
url,
|
||||
file: element.fileId ?? '',
|
||||
|
||||
@@ -15,6 +15,10 @@ interface CachedRKey {
|
||||
|
||||
const RKEY_REFRESH_SKEW = 60;
|
||||
const RKEY_REFRESH_COOLDOWN = 30;
|
||||
// Upper bound on how long URL resolution may block on a refresh round-trip.
|
||||
// A stuck packet send must never wedge message conversion — past this we
|
||||
// fall back to whatever the cache holds (possibly nothing).
|
||||
const RKEY_REFRESH_TIMEOUT_MS = 5000;
|
||||
const PRIVATE_IMAGE_RKEY_TYPE = 10;
|
||||
const GROUP_IMAGE_RKEY_TYPE = 20;
|
||||
const PRIVATE_VIDEO_RKEY_TYPE = 12;
|
||||
@@ -26,31 +30,28 @@ const FALLBACK_IMAGE_RKEY_TYPE = 2;
|
||||
export class RKeyCache {
|
||||
private cache = new Map<number, CachedRKey>();
|
||||
private lastRefreshAttempt = 0;
|
||||
private refreshInflight: Promise<void> | null = null;
|
||||
|
||||
warmUp(bridge: BridgeInterface, uin: string): void {
|
||||
bridge.apis.contacts.fetchDownloadRKeys().then(
|
||||
(rkeys) => {
|
||||
this.updateCache(rkeys);
|
||||
log.info('rkeys loaded: UIN=%s count=%d', uin, rkeys.length);
|
||||
},
|
||||
(err) => {
|
||||
log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err));
|
||||
},
|
||||
this.ensureFresh(bridge).then(
|
||||
() => log.info('rkeys loaded: UIN=%s count=%d', uin, this.cache.size),
|
||||
(err) => log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err)),
|
||||
);
|
||||
}
|
||||
|
||||
resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
|
||||
async resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): Promise<string> {
|
||||
const url = element.imageUrl ?? '';
|
||||
if (!urlNeedsRKey(url)) return url;
|
||||
|
||||
const rkey = this.findRKey(bridge, isGroup);
|
||||
const rkey = await this.findRKey(bridge, isGroup);
|
||||
if (!rkey) return url;
|
||||
|
||||
const cleanRKey = stripRKeyPrefix(rkey);
|
||||
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
|
||||
return url + separator + encodeURIComponent(cleanRKey);
|
||||
}
|
||||
resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
|
||||
|
||||
async resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): Promise<string> {
|
||||
const url = element.url ?? '';
|
||||
if (!url || !urlNeedsRKey(url)) return url;
|
||||
|
||||
@@ -65,7 +66,7 @@ export class RKeyCache {
|
||||
primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||
}
|
||||
|
||||
const rkey = this.findRKeyForType(bridge, primaryType);
|
||||
const rkey = await this.findRKeyForType(bridge, primaryType);
|
||||
if (!rkey) return url;
|
||||
|
||||
const cleanRKey = stripRKeyPrefix(rkey);
|
||||
@@ -89,32 +90,66 @@ export class RKeyCache {
|
||||
}
|
||||
}
|
||||
|
||||
private findRKey(bridge: BridgeInterface, isGroup: boolean): string | null {
|
||||
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);
|
||||
}
|
||||
|
||||
private findRKeyForType(bridge: BridgeInterface, primaryType: number): string | null {
|
||||
/** 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);
|
||||
|
||||
const tryFind = (type: number): string | null => {
|
||||
const cached = this.cache.get(type);
|
||||
if (!cached || !cached.value) return null;
|
||||
if (cached.expiresAt !== 0 && now + RKEY_REFRESH_SKEW >= cached.expiresAt) return null;
|
||||
return cached.value;
|
||||
};
|
||||
return tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||
}
|
||||
|
||||
let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||
if (result) return result;
|
||||
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null;
|
||||
this.lastRefreshAttempt = now;
|
||||
bridge.apis.contacts.fetchDownloadRKeys().then(
|
||||
(rkeys) => this.updateCache(rkeys),
|
||||
() => { /* ignore */ },
|
||||
);
|
||||
private async findRKeyForType(bridge: BridgeInterface, primaryType: number): Promise<string | null> {
|
||||
const cached = this.findInCache(primaryType);
|
||||
if (cached) return cached;
|
||||
|
||||
result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||
return result;
|
||||
// Cache miss or inside the expiry skew: block on a fresh fetch rather
|
||||
// than hand back a URL with a stale/absent rkey — the CDN rejects those
|
||||
// with `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Mirrors NapCat's
|
||||
// getImageUrl path, which does `if (isExpired()) await refreshRkey()`
|
||||
// before building the URL instead of refreshing in the background.
|
||||
await this.ensureFresh(bridge);
|
||||
return this.findInCache(primaryType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the rkey cache via OIDB 0x9067_202, coalescing concurrent
|
||||
* callers onto one in-flight request and backing off for
|
||||
* RKEY_REFRESH_COOLDOWN after a failed attempt so a persistently
|
||||
* unreachable server isn't hammered once per inbound image. The await is
|
||||
* bounded by RKEY_REFRESH_TIMEOUT_MS.
|
||||
*/
|
||||
private async ensureFresh(bridge: BridgeInterface): Promise<void> {
|
||||
if (!this.refreshInflight) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return;
|
||||
this.lastRefreshAttempt = now;
|
||||
this.refreshInflight = bridge.apis.contacts.fetchDownloadRKeys()
|
||||
.then((rkeys) => { this.updateCache(rkeys); })
|
||||
.catch((err) => {
|
||||
log.warn('rkey refresh failed: %s', err instanceof Error ? err.message : String(err));
|
||||
})
|
||||
.finally(() => { this.refreshInflight = null; });
|
||||
}
|
||||
|
||||
const inflight = this.refreshInflight;
|
||||
if (!inflight) return;
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<void>((resolve) => { timer = setTimeout(resolve, RKEY_REFRESH_TIMEOUT_MS); });
|
||||
try {
|
||||
await Promise.race([inflight, timeout]);
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
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.
|
||||
const NT_IMAGE_URL = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=ABC';
|
||||
const GROUP_IMAGE_TYPE = 20;
|
||||
const PRIVATE_IMAGE_TYPE = 10;
|
||||
|
||||
function nowSec(): number {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
function makeBridge(fetchImpl: () => Promise<unknown[]>) {
|
||||
const fetchDownloadRKeys = vi.fn(fetchImpl);
|
||||
return { bridge: { apis: { contacts: { fetchDownloadRKeys } } }, fetchDownloadRKeys };
|
||||
}
|
||||
|
||||
function freshGroupRkey(value = 'GROUPKEY') {
|
||||
return [{ rkey: value, type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 }];
|
||||
}
|
||||
|
||||
function imageEl(): MessageElement {
|
||||
return { type: 'image', imageUrl: NT_IMAGE_URL };
|
||||
}
|
||||
|
||||
describe('RKeyCache.resolveImageUrl', () => {
|
||||
it('awaits a refresh on a cold cache and appends the rkey', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
|
||||
|
||||
expect(url).toBe(`${NT_IMAGE_URL}&rkey=GROUPKEY`);
|
||||
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('coalesces concurrent cold-cache lookups into a single fetch', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const urls = await Promise.all([
|
||||
cache.resolveImageUrl(bridge as never, imageEl(), true),
|
||||
cache.resolveImageUrl(bridge as never, imageEl(), true),
|
||||
cache.resolveImageUrl(bridge as never, imageEl(), true),
|
||||
]);
|
||||
|
||||
expect(urls).toEqual(Array(3).fill(`${NT_IMAGE_URL}&rkey=GROUPKEY`));
|
||||
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('serves a still-valid rkey from cache without re-fetching', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
await cache.resolveImageUrl(bridge as never, imageEl(), true);
|
||||
await cache.resolveImageUrl(bridge as never, imageEl(), true);
|
||||
|
||||
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('falls back to the unsigned URL (no throw) when the refresh fails', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => { throw new Error('oidb down'); });
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
|
||||
|
||||
expect(url).toBe(NT_IMAGE_URL);
|
||||
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 },
|
||||
]);
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, imageEl(), false);
|
||||
|
||||
expect(url).toBe(`${NT_IMAGE_URL}&rkey=PRIVATEKEY`);
|
||||
});
|
||||
|
||||
it('leaves non-NT URLs untouched and never fetches', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
const el: MessageElement = { type: 'image', imageUrl: 'https://gchat.qpic.cn/foo.jpg' };
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, el, true);
|
||||
|
||||
expect(url).toBe('https://gchat.qpic.cn/foo.jpg');
|
||||
expect(fetchDownloadRKeys).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user