Files
webshare-api/__tests__/torrent.test.js
Michal Pemcak ac97862edb Fix bdecode busy-loop on truncated torrent payloads.
Malformed bencode could set pos.i to NaN and hang Jest forever;
guard the decoder and align the no-url-list fixture with current qbt behavior.
2026-10-19 19:14:15 +02:00

67 lines
2.6 KiB
JavaScript

const { makeTorrent, extractWebseed } = require('../src/torrent');
describe('makeTorrent + extractWebseed round-trip', () => {
it('extracts the webseed URL back from a generated torrent', () => {
const url = 'http://example.com/stream/abc123';
const buf = makeTorrent({ name: 'test.mkv', size: 1024 * 1024, webseedUrl: url });
expect(extractWebseed(buf)).toBe(url);
});
it('works with size 0', () => {
const url = 'http://example.com/stream/xyz';
const buf = makeTorrent({ name: 'empty.mkv', size: 0, webseedUrl: url });
expect(extractWebseed(buf)).toBe(url);
});
it('produces a Buffer', () => {
const buf = makeTorrent({ name: 'f.mkv', size: 100, webseedUrl: 'http://x.com/s/y' });
expect(Buffer.isBuffer(buf)).toBe(true);
expect(buf.length).toBeGreaterThan(0);
});
it('encodes name into the torrent', () => {
const buf = makeTorrent({ name: 'movie.mkv', size: 500, webseedUrl: 'http://x.com/s/z' });
expect(buf.toString()).toContain('movie.mkv');
});
});
describe('extractWebseed', () => {
it('returns null for empty buffer', () => {
expect(extractWebseed(Buffer.alloc(0))).toBeNull();
});
it('returns null for non-torrent data', () => {
expect(extractWebseed(Buffer.from('not a torrent'))).toBeNull();
});
it('returns null for truncated dict (no busy-loop)', () => {
// Previously: dict key "pieces" without value → bdecode infinite loop
const truncated = Buffer.from(
'd4:infod6:lengthi0e4:name4:teste12:piece lengthi524288e6:piecese',
'utf8',
);
const t0 = Date.now();
expect(extractWebseed(truncated)).toBeNull();
expect(Date.now() - t0).toBeLessThan(100);
});
it('returns null when url-list is missing', () => {
// Bencode a dict without url-list
const buf = makeTorrent({ name: 'f.mkv', size: 0, webseedUrl: 'http://x.com/s/a' });
// Corrupt the url-list key to make it missing
const str = buf.toString('binary').replace('url-list', 'url-xxxx');
const corrupted = Buffer.from(str, 'binary');
expect(extractWebseed(corrupted)).toBeNull();
});
it('handles url-list as array', () => {
// Manually build a torrent-like bencode with url-list as list
const { makeTorrent: mt } = require('../src/torrent');
// We test via the actual makeTorrent which uses a string — round-trip test above covers it.
// Here just verify the array branch: if url-list is a Buffer (string) it still returns a string.
const url = 'http://cdn.example.com/stream/abcdef';
const buf = mt({ name: 't.mkv', size: 50, webseedUrl: url });
expect(typeof extractWebseed(buf)).toBe('string');
});
});