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:
DrSmoothl committed 2026-05-29 17:56:39 +08:00
1 parent 0110b71dd3
commit 624959f099
4 files changed
+156 -27

No files matched your search

+60 -25
View File
@@ -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);
}
}
}