feat(onebot): opt-in remote rkey fallback server (#156)

On accounts where the native OIDB 0x9067_202 rkey fetch persistently returns
nothing, every image was served as a bare multimedia.nt.qq.com.cn URL the CDN
rejects with invalid rkey — SnowLuma had no fallback, unlike NapCat.

Add config.rkey.fallbackServers (default []: OFF; no third-party server is
contacted unless the operator configures one). When the native fetch leaves the
cache without a usable image rkey, each configured HTTP endpoint is tried in
turn for { group_rkey, private_rkey, expired_time } (NapCat rkey-server format;
an OneBot { retcode, data } wrapper is also accepted), populating the group/
private image rkey types. Values keep any leading &rkey=/?rkey= since
resolveImageUrl strips before re-appending.

WebUI has no form yet but round-trips rkey.fallbackServers verbatim so a hand-
edited value survives an unrelated config save. Part B of #156 (cooldown is A).
This commit is contained in:
DrSmoothl committed 2026-06-28 01:37:58 +08:00
1 parent 219d60410a
commit 12b01907bc
8 files changed
+265 -7

No files matched your search

+24
View File
@@ -63,6 +63,30 @@ describe('loadOneBotConfig', () => {
expect(onDisk.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5, trigger: '#sl' });
});
it('defaults rkey.fallbackServers to empty (feature off)', () => {
const config = loadOneBotConfig('10055');
expect(config.rkey).toEqual({ fallbackServers: [] });
});
it('parses, validates (http only), dedupes and round-trips rkey.fallbackServers', () => {
const uin = '10056';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, `onebot_${uin}.json`),
JSON.stringify({ rkey: { fallbackServers: ['https://a.example/r', 'not-a-url', 'https://a.example/r', 'http://b.example/r', 42] } }),
'utf8',
);
const config = loadOneBotConfig(uin);
expect(config.rkey.fallbackServers).toEqual(['https://a.example/r', 'http://b.example/r']);
saveOneBotConfig(uin, config);
const onDisk = JSON.parse(fs.readFileSync(path.join(dir, `onebot_${uin}.json`), 'utf8'));
expect(onDisk.rkey).toEqual({ fallbackServers: ['https://a.example/r', 'http://b.example/r'] });
expect(loadOneBotConfig(uin).rkey.fallbackServers).toEqual(['https://a.example/r', 'http://b.example/r']);
});
it('fills statusCommand defaults and clamps a negative cooldown', () => {
const uin = '10042';
const dir = path.join(tempDir, 'config');
+93 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { RKeyCache } from '../src/instance-rkey';
import type { MessageElement } from '@snowluma/protocol/events';
@@ -178,3 +178,95 @@ describe('RKeyCache.resolveImageUrl', () => {
expect(fetchDownloadRKeys).not.toHaveBeenCalled();
});
});
describe('RKeyCache remote fallback (#156)', () => {
const SERVER = 'https://rkey.example/r';
function stubFetch(payload: unknown, status = 200) {
return vi.spyOn(globalThis, 'fetch').mockResolvedValue(
new Response(JSON.stringify(payload), { status }),
);
}
afterEach(() => {
vi.restoreAllMocks();
});
it('is off by default: never contacts a server, leaves the URL bare', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch');
const { bridge } = makeBridge(async () => []); // native yields nothing
const cache = new RKeyCache(); // no config → fallback off
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(NT_IMAGE_URL);
expect(fetchSpy).not.toHaveBeenCalled();
});
it('falls back to the configured server when the native fetch is empty', async () => {
const fetchSpy = stubFetch({
group_rkey: '&rkey=FBGROUP', private_rkey: '&rkey=FBPRIV', expired_time: nowSec() + 3600,
});
const { bridge } = makeBridge(async () => []);
const cache = new RKeyCache({ fallbackServers: [SERVER] });
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(`${NT_IMAGE_URL}&rkey=FBGROUP`);
expect(fetchSpy).toHaveBeenCalledWith(SERVER, expect.anything());
});
it('signs c2c images with the fallback private rkey', async () => {
stubFetch({ group_rkey: '&rkey=FBGROUP', private_rkey: '&rkey=FBPRIV', expired_time: nowSec() + 3600 });
const { bridge } = makeBridge(async () => []);
const cache = new RKeyCache({ fallbackServers: [SERVER] });
const url = await cache.resolveImageUrl(bridge as never, privateImageEl(), false);
expect(url).toBe(`${NT_PRIVATE_IMAGE_URL}&rkey=FBPRIV`);
});
it('accepts an OneBot { retcode, data } wrapper and bare (unprefixed) tokens', async () => {
stubFetch({ retcode: 0, data: { group_rkey: 'BAREKEY', private_rkey: '', expired_time: nowSec() + 3600 } });
const { bridge } = makeBridge(async () => []);
const cache = new RKeyCache({ fallbackServers: [SERVER] });
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(`${NT_IMAGE_URL}&rkey=BAREKEY`);
});
it('does not hit any server when the native fetch already returned a rkey', async () => {
const fetchSpy = stubFetch({ group_rkey: '&rkey=FBGROUP', expired_time: nowSec() + 3600 });
const { bridge } = makeBridge(async () => freshGroupRkey());
const cache = new RKeyCache({ fallbackServers: [SERVER] });
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(`${NT_IMAGE_URL}&rkey=GROUPKEY`); // native rkey, not fallback
expect(fetchSpy).not.toHaveBeenCalled();
});
it('tries the next server when the first one fails', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch')
.mockRejectedValueOnce(new Error('down'))
.mockResolvedValueOnce(new Response(JSON.stringify({ group_rkey: '&rkey=SECOND', expired_time: nowSec() + 3600 }), { status: 200 }));
const { bridge } = makeBridge(async () => []);
const cache = new RKeyCache({ fallbackServers: ['https://a.example/r', 'https://b.example/r'] });
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(`${NT_IMAGE_URL}&rkey=SECOND`);
expect(fetchSpy).toHaveBeenCalledTimes(2);
});
it('leaves the URL bare when every fallback server fails', async () => {
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('down'));
const { bridge } = makeBridge(async () => []);
const cache = new RKeyCache({ fallbackServers: [SERVER] });
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(NT_IMAGE_URL);
});
});