// The Node-specific API surface, as distinct from the shared conformance // corpus in conformance.test.mjs. import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { test } from 'node:test'; import { VPNDetection, VPNDetectionError, isBogon } from '../dist/index.js'; const data = JSON.parse(readFileSync(new URL('../testdata/testdata.json', import.meta.url), 'utf8')); // Answers slowly enough that concurrent calls overlap, and records the peak // number in flight. Asserting the PEAK is the only way to tell a real limit // from an option that was accepted and ignored. A batch arrives as one POST per // chunk, so it is answered from the addresses in the body. function concurrencyTrackingFetch(delayMs = 20) { const state = { inFlight: 0, peak: 0, calls: 0 }; const fn = async (input, init) => { const body = typeof input === 'string' ? (init?.body ?? '') : await input.text(); state.calls++; state.inFlight++; state.peak = Math.max(state.peak, state.inFlight); await new Promise((r) => setTimeout(r, delayMs)); state.inFlight--; const results = {}; for (const ip of JSON.parse(body || '{}').ips ?? []) { results[ip] = { ip: ip, is_vpn: false }; } return new Response(JSON.stringify({ results: results, errors: {} }), { status: 200, headers: { 'content-type': 'application/json' }, }); }; return { fetch: fn, state: state }; } // Enough addresses for seven chunks of the batch endpoint's 1000, so a // concurrency bound has something to bound: one request per chunk, and only the // chunks overlap. const addrs = Array.from( { length: 6001 }, (_, i) => `9.${1 + Math.floor(i / 65536)}.${Math.floor(i / 256) % 256}.${i % 256}`, ); test('isBogon is on the client and agrees with the standalone export', () => { const client = new VPNDetection(); for (const c of data.isBogon) { assert.equal(client.isBogon(c.ip), c.expect, `${c.ip} (${c.why})`); assert.equal(client.isBogon(c.ip), isBogon(c.ip), `${c.ip}: client and export disagree`); } }); test('batch concurrency is configurable per call', async () => { const t = concurrencyTrackingFetch(); const client = new VPNDetection({ fetch: t.fetch, cache: false }); await client.lookupBatch(addrs, { concurrency: 3 }); assert.equal(t.state.calls, 7, 'one request per chunk of 1000'); assert.ok(t.state.peak <= 3, `peak in flight was ${t.state.peak}, expected at most 3`); assert.ok(t.state.peak > 1, 'requests should still overlap'); }); test('a per-call concurrency overrides the client default', async () => { const t = concurrencyTrackingFetch(); // Instance default of 2, raised to 6 for this one batch. const client = new VPNDetection({ fetch: t.fetch, cache: false, concurrency: 2 }); await client.lookupBatch(addrs, { concurrency: 6 }); assert.ok(t.state.peak > 2, `override ignored: peak was ${t.state.peak}, expected above 2`); assert.ok(t.state.peak <= 6, `peak in flight was ${t.state.peak}, expected at most 6`); }); test('without an override the client concurrency still applies', async () => { const t = concurrencyTrackingFetch(); const client = new VPNDetection({ fetch: t.fetch, cache: false, concurrency: 2 }); await client.lookupBatch(addrs); assert.ok(t.state.peak <= 2, `peak in flight was ${t.state.peak}, expected at most 2`); }); // p-limit would throw a bare TypeError for these; they are the caller's mistake. test('a per-call concurrency below 1 is refused before any request', async () => { let calls = 0; const client = new VPNDetection({ fetch: async () => { calls++; throw new Error('the network must not be reached'); }, }); for (const concurrency of [0, -1, 0.5, 1.5, NaN]) { const call = () => client.lookupBatch(['45.83.91.1', '10.0.0.1'], { concurrency: concurrency }); await assert.rejects(call, (err) => { assert.ok(err instanceof VPNDetectionError, `${concurrency}: wrong error type`); assert.equal(err.kind, 'bad_request', `${concurrency}`); assert.equal(err.retryable, false, `${concurrency}`); assert.match(err.message, /concurrency/, `${concurrency}`); return true; }); } assert.equal(calls, 0); }); // Through 5.10.3 the constructor handed any value to p-limit, which threw its own // bare TypeError for each of these (measured 2026-11-07). test('a client concurrency that is not a whole number from 1 is refused where it is set', () => { for (const concurrency of [0, -1, 0.5, 1.5, NaN, 'x', '', '2', {}, [2]]) { assert.throws(() => new VPNDetection({ concurrency: concurrency }), (err) => { assert.ok(err instanceof VPNDetectionError, `${String(concurrency)}: wrong error type`); assert.equal(err.kind, 'bad_request', `${String(concurrency)}`); assert.match(err.message, /concurrency/, `${String(concurrency)}`); return true; }); } }); test('a null concurrency reads as unset, on the client and per call', async () => { const t = concurrencyTrackingFetch(); const client = new VPNDetection({ fetch: t.fetch, cache: false, concurrency: null }); await client.lookupBatch(addrs, { concurrency: null }); // Seven chunks, all in flight under the default of 8. assert.equal(t.state.calls, 7); assert.equal(t.state.peak, 7); }); test('retries are configurable per call', async () => { let calls = 0; const fetchFn = async () => { calls++; return new Response(JSON.stringify({ error: 'lookup failed' }), { status: 500, headers: { 'content-type': 'application/json' }, }); }; const client = new VPNDetection({ fetch: fetchFn, cache: false, retries: 0 }); await assert.rejects(() => client.lookup('9.9.9.9', { retries: 2 })); // 1 initial attempt plus 2 retries, rather than the instance's 0. assert.equal(calls, 3); }); // Two ways a response stalls: nothing arrives, or the headers do and the body // never finishes. The deadline has to bound the whole call, not just the first. const STALLS = { 'no response': () => new Promise(() => {}), 'a body that never ends': async () => new Response(new ReadableStream({ start() {} }), { status: 200, headers: { 'content-type': 'application/json' }, }), }; // Every call that takes per-call options, each surfacing its failure as a // rejection. A batch reports a failed chunk as every address's value instead of // throwing, so that one rethrows what it was given. const PER_CALL = { 'lookup': (c, o) => c.lookup('45.83.91.1', o), 'myIp': (c, o) => c.myIp(o), 'myEntitlement': (c, o) => c.myEntitlement(o), 'lookupBatch': async (c, o) => { const answers = [...(await c.lookupBatch(['45.83.91.1', '9.9.9.9'], o)).values()]; assert.ok(answers.every((a) => a instanceof VPNDetectionError), 'the chunk should fail as a whole'); throw answers[0]; }, 'database.downloads': (c, o) => c.database.downloads({ limit: 5, ...o }), 'oauth.metadata': (c, o) => c.oauth.metadata(o), 'oauth.deviceAuthorization': (c, o) => c.oauth.deviceAuthorization('your-client-id', o), 'oauth.exchangeDeviceCode': (c, o) => c.oauth.exchangeDeviceCode('your-client-id', 'mo_dc_x', o), 'oauth.exchangeRefreshToken': (c, o) => c.oauth.exchangeRefreshToken('your-client-id', 'mo_rt_x', o), 'oauth.revoke': (c, o) => c.oauth.revoke('your-client-id', 'mo_rt_x', o), // Waits nothing, and parks rather than spinning if the poll never ends. 'oauth.pollDeviceToken': (c, o) => { let waits = 0; c.oauth.clock = { now: () => 0, sleep: () => (++waits > 16 ? new Promise(() => {}) : Promise.resolve()), }; const device = { device_code: 'mo_dc_x', user_code: 'x', verification_uri: 'x', expires_in: 900, interval: 5, }; return c.oauth.pollDeviceToken('your-client-id', device, o); }, }; // Set BELOW the client's, so the only deadline that can fire in time is the // per-call one, and its message names which one it was. test('a per-call timeoutMs bounds every call below the client default', async () => { for (const [stallName, stall] of Object.entries(STALLS)) { for (const [call, invoke] of Object.entries(PER_CALL)) { const client = new VPNDetection({ retries: 0, timeoutMs: 10_000, cache: false, fetch: stall }); const label = `${call}, ${stallName}`; const started = Date.now(); await assert.rejects(() => invoke(client, { timeoutMs: 80 }), (err) => { assert.ok(err instanceof VPNDetectionError, `${label}: wrong error type`); assert.equal(err.kind, 'network', label); assert.equal(err.retryable, true, label); assert.match(err.message, /timed out after 80ms/, label); return true; }); assert.ok(Date.now() - started < 2000, `${label}: the per-call deadline did not hold`); } } }); // Per ATTEMPT, like the client-level one: a retried call gets a fresh budget. test('a per-call timeoutMs applies to each attempt', async () => { let calls = 0; const client = new VPNDetection({ retries: 0, timeoutMs: 10_000, cache: false, fetch: () => { calls++; return new Promise(() => {}); }, }); await assert.rejects( () => client.lookup('45.83.91.1', { retries: 1, timeoutMs: 80 }), (err) => err instanceof VPNDetectionError && /timed out after 80ms/.test(err.message), ); assert.equal(calls, 2, 'one attempt plus one retry, each abandoned at its own deadline'); }); // The database responses nest their payload, and a hand-written unwrap shape is // a claim the compiler cannot check. `checksums` shipped broken in 1.0.x for // exactly that reason: it read a top-level `sha256` that is not there, and // returned undefined against a perfectly healthy API. const DATABASE = { base: 'vpn_ip_extended', name: 'n', summary: 's', license_type: null, starts: null, expires: null, renews_at: null, notice_due_at: null, in_term: false, standing: 'available', open: false, versions: [{ id: 'vpn_ip_extended_v1', version: 1, formats: [{ format: 'mmdb', bytes: null }] }], }; const DOWNLOAD = { dataset_id: 'vpn_ip_extended_v1', format: 'mmdb', outcome: 'ok', sample: false, open: false, bytes: null, http_status: null, apikey_id: null, client_ip: null, user_agent: null, created: '2026-09-04T10:00:00Z', }; test('database responses are unwrapped at the right depth', async () => { const routes = { '/api/v1/database/checksum': { id: 'vpn_ip_extended_v1', format: 'mmdb', checksums: { md5: 'm', sha1: 's1', sha256: 's256', sha512: 's512' }, }, '/api/v1/database/list': { databases: [DATABASE] }, '/api/v1/database/downloads': { downloads: [DOWNLOAD] }, '/api/v1/database/metadata': { id: 'vpn_ip_extended_v1', updated: '2026-09-04', entries: 1, schema: {} }, }; const fetchFn = async (input) => { const url = new URL(typeof input === 'string' ? input : input.url); return new Response(JSON.stringify(routes[url.pathname]), { status: 200, headers: { 'content-type': 'application/json' }, }); }; const client = new VPNDetection({ fetch: fetchFn, apiKey: 'k' }); const sums = await client.database.checksums('vpn_ip_extended_v1', 'mmdb'); assert.deepEqual(sums, { md5: 'm', sha1: 's1', sha256: 's256', sha512: 's512' }); assert.equal(sums.sha256, 's256', 'the digest a caller actually wants must not be undefined'); assert.deepEqual(await client.database.list(), [DATABASE]); assert.deepEqual(await client.database.downloads(), [DOWNLOAD]); assert.equal((await client.database.metadata('vpn_ip_extended_v1')).id, 'vpn_ip_extended_v1'); }); // The spec documents three credential forms because the API accepts three, and // the generator will happily apply all of them - putting the key in the query // string of every request. A query string is the one place a secret must not // be: access logs, proxy logs and browser history all keep it, and none of // those are ours. Asserted on what leaves the client, because the request still // succeeds either way. test('the key is sent in the Authorization header and nowhere else', async () => { let seen = null; const fetchFn = async (input, init) => { const url = new URL(typeof input === 'string' ? input : input.url); const headers = new Headers(input?.headers ?? init?.headers ?? {}); seen = { query: url.searchParams.get('apikey'), authorization: headers.get('authorization'), xApiKey: headers.get('x-api-key'), }; return new Response(JSON.stringify({ databases: [] }), { status: 200, headers: { 'content-type': 'application/json' }, }); }; await new VPNDetection({ fetch: fetchFn, apiKey: 'SECRET' }).database.list(); assert.equal(seen.authorization, 'Bearer SECRET'); assert.equal(seen.query, null, 'the key must never reach a URL'); assert.equal(seen.xApiKey, null, 'one credential form, not three'); }); // The API bounds the history at 200 and defaults to 50. An option that is // accepted and silently dropped passes any test that only reads the result, so // this asserts the query string that actually left. test('the downloads limit reaches the wire, and is omitted when not given', async () => { const seen = []; const fetchFn = async (input) => { const url = new URL(typeof input === 'string' ? input : input.url); seen.push(url.searchParams.get('limit')); return new Response(JSON.stringify({ downloads: [] }), { status: 200, headers: { 'content-type': 'application/json' }, }); }; const client = new VPNDetection({ fetch: fetchFn, apiKey: 'k' }); await client.database.downloads(); await client.database.downloads({ limit: 200 }); assert.equal(seen[0], null, 'no limit means no query parameter, so the API default applies'); assert.equal(seen[1], '200'); }); test('a per-call timeoutMs never reaches the wire', async () => { const seen = []; const fetchFn = async (input) => { seen.push([...new URL(typeof input === 'string' ? input : input.url).searchParams.keys()]); return new Response(JSON.stringify({ downloads: [] }), { status: 200, headers: { 'content-type': 'application/json' }, }); }; const client = new VPNDetection({ fetch: fetchFn, apiKey: 'k' }); await client.database.downloads({ limit: 5, timeoutMs: 5000 }); assert.deepEqual(seen[0], ['limit']); }); // A fetch that answers one fixed body and counts calls, for the two endpoints // that take no argument. function countingFetch(body) { const state = { calls: 0, urls: [] }; const fn = async (input) => { const url = typeof input === 'string' ? input : input.url; state.calls++; state.urls.push(new URL(url).pathname); return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' }, }); }; return { fetch: fn, state: state }; } test('myIp asks the server which address you are', async () => { const t = countingFetch({ ip: '203.0.113.9', is_vpn: true }); const client = new VPNDetection({ fetch: t.fetch }); const result = await client.myIp(); assert.equal(result.ip, '203.0.113.9'); assert.equal(result.isVpn, true); assert.equal(t.state.urls[0], '/myip'); }); // The cache is keyed by address, and which address this is IS the question, so // a second call has to ask again. test('myIp is not cached', async () => { const t = countingFetch({ ip: '203.0.113.9', is_vpn: false }); const client = new VPNDetection({ fetch: t.fetch }); await client.myIp(); await client.myIp(); await client.myIp(); assert.equal(t.state.calls, 3); }); test('myEntitlement reports the plan and the usage', async () => { const t = countingFetch({ org_id: '85bb51e4-2eb6-4a31-8e4d-02ba8b98fe61', apikey: { id: '0ab424cc-7619-4dad-b027-afacdc2cedb0', expires: null, allowed_cidrs: [] }, plan: { key: 'max', name: 'Max', tier: 'max' }, usage: { requests: 580, quota: 5000000, hard_limit: null, window_start: '2026-09-04T07:00:00Z', window_end: '2026-10-04T07:00:00Z', }, }); const client = new VPNDetection({ fetch: t.fetch, apiKey: 'k' }); const ent = await client.myEntitlement(); assert.equal(ent.plan.key, 'max'); assert.equal(ent.plan.name, 'Max'); assert.equal(ent.usage.requests, 580); // An uncapped plan reports null, which is not zero: zero would read as // "stop serving immediately". assert.equal(ent.usage.hard_limit, null); assert.equal(t.state.urls[0], '/api/v1/entitlement'); }); // Usage is the whole point, so a cached answer is a wrong one within seconds. test('myEntitlement is not cached', async () => { const t = countingFetch({ org_id: 'f32191d0-ef02-450e-a505-eb5814c35cab', apikey: { id: '10c2b437-3aa2-4a63-bd17-8e7c8c7f0def', expires: null, allowed_cidrs: [] }, plan: { key: 'free', name: 'Free', tier: 'free' }, usage: { requests: 1, quota: 2, hard_limit: 2, window_start: '2026-09-01T00:00:00Z', window_end: '2026-10-01T00:00:00Z', }, }); const client = new VPNDetection({ fetch: t.fetch, apiKey: 'k' }); await client.myEntitlement(); await client.myEntitlement(); assert.equal(t.state.calls, 2); }); // Answers after a delay and counts what it was asked, a batch by the addresses in // its body, so a request shared or sent twice shows in the count. function sharingFetch(delayMs, refuse = new Set()) { const state = { paths: [], batched: [] }; const fn = async (input, init) => { const request = typeof input === 'string' ? new Request(input, init) : input; const path = new URL(request.url).pathname; state.paths.push(path); await new Promise((r) => setTimeout(r, delayMs)); if (path === '/batch') { const ips = JSON.parse(await request.text()).ips; state.batched.push(ips); const results = {}; const errors = {}; for (const ip of ips) { if (refuse.has(ip)) { errors[ip] = { status: 403, error: 'forbidden' }; } else { results[ip] = { ip: ip, is_vpn: false }; } } return Response.json({ results: results, errors: errors }); } const ip = decodeURIComponent(path.slice(1)); if (refuse.has(ip)) { return Response.json({ error: 'forbidden' }, { status: 403 }); } return Response.json({ ip: ip, is_vpn: false }); }; return { fetch: fn, state: state }; } const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); // Long enough that a call started a quarter of it later is still concurrent. const STAGGER = 400; test('concurrent misses for one address share one request', async () => { const t = sharingFetch(200); const client = new VPNDetection({ fetch: t.fetch }); const answers = await Promise.all(Array.from({ length: 20 }, () => client.lookup('45.83.91.1'))); assert.deepEqual(t.state.paths, ['/45.83.91.1'], `20 callers sent ${t.state.paths.length} requests`); for (const answer of answers) { assert.equal(answer.ip, '45.83.91.1'); } }); test('a shared failure reaches every waiter and is not cached', async () => { const refuse = new Set(['45.83.91.1']); const t = sharingFetch(200, refuse); const client = new VPNDetection({ fetch: t.fetch, retries: 0 }); const settled = await Promise.allSettled(Array.from({ length: 5 }, () => client.lookup('45.83.91.1'))); assert.equal(t.state.paths.length, 1); for (const s of settled) { assert.equal(s.status, 'rejected'); assert.equal(s.reason.kind, 'forbidden'); } refuse.clear(); assert.equal((await client.lookup('45.83.91.1')).ip, '45.83.91.1'); assert.equal(t.state.paths.length, 2, 'the failure was cached'); }); test('a batch awaits a lookup in flight', async () => { const t = sharingFetch(STAGGER); const client = new VPNDetection({ fetch: t.fetch }); const single = client.lookup('45.83.91.1'); await sleep(STAGGER / 4); const batch = await client.lookupBatch(['45.83.91.1', '45.83.91.2']); await single; assert.equal(batch.get('45.83.91.1').ip, '45.83.91.1'); assert.equal(batch.get('45.83.91.2').ip, '45.83.91.2'); assert.deepEqual(t.state.batched, [['45.83.91.2']], 'the batch sent the address in flight again'); assert.equal(t.state.paths.length, 2); }); test('a lookup awaits a batch in flight', async () => { const t = sharingFetch(STAGGER); const client = new VPNDetection({ fetch: t.fetch }); const batch = client.lookupBatch(['45.83.91.1', '45.83.91.2']); await sleep(STAGGER / 4); const single = await client.lookup('45.83.91.2'); await batch; assert.equal(single.ip, '45.83.91.2'); assert.deepEqual(t.state.paths, ['/batch']); }); test('a lookup takes the failure of the batch it joined', async () => { const t = sharingFetch(STAGGER, new Set(['45.83.91.2'])); const client = new VPNDetection({ fetch: t.fetch }); const batch = client.lookupBatch(['45.83.91.1', '45.83.91.2']); await sleep(STAGGER / 4); await assert.rejects(client.lookup('45.83.91.2'), (err) => err.kind === 'forbidden'); const answers = await batch; assert.equal(answers.get('45.83.91.2').kind, 'forbidden'); assert.deepEqual(t.state.paths, ['/batch']); }); test('a client without a cache shares nothing', async () => { const t = sharingFetch(100); const client = new VPNDetection({ fetch: t.fetch, cache: false }); await Promise.all([ ...Array.from({ length: 3 }, () => client.lookup('45.83.91.1')), client.lookupBatch(['45.83.91.1']), client.lookupBatch(['45.83.91.1']), ]); assert.equal(t.state.paths.length, 5); }); // Answers every call the way its path expects and records the paths, so a // doubled slash shows up as a path rather than as whatever a server makes of it. function pathRecordingFetch() { const paths = []; const fn = async (input, init) => { const request = input instanceof Request ? input : new Request(input, init); const path = new URL(request.url).pathname; paths.push(path); const body = path.endsWith('batch') ? { results: { '9.9.9.9': { ip: '9.9.9.9', is_vpn: false } }, errors: {} } : path.endsWith('oauth-authorization-server') ? { issuer: 'x', authorization_endpoint: 'x', token_endpoint: 'x' } : path.endsWith('list') ? { databases: [] } : { ip: '8.8.8.8', is_vpn: false }; return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' }, }); }; return { fetch: fn, paths: paths }; } // Every path the client appends starts with a slash. One trailing slash on the // base URL was dropped, but through 5.3.0 a second doubled into every path // (//8.8.8.8, //batch), which the API answers with a redirect. test('every trailing slash on the base URL is dropped', async (t) => { for (const suffix of ['/', '//', '///']) { await t.test(JSON.stringify(suffix), async () => { const stub = pathRecordingFetch(); const client = new VPNDetection({ baseUrl: `https://api.example.test${suffix}`, apiKey: 'k', fetch: stub.fetch, retries: 0, }); await client.lookup('8.8.8.8'); await client.lookupBatch(['9.9.9.9']); await client.myIp(); await client.database.list(); await client.oauth.metadata(); assert.deepEqual(stub.paths, [ '/8.8.8.8', '/batch', '/myip', '/api/v1/database/list', '/.well-known/oauth-authorization-server', ]); }); } }); // setTimeout runs 0, a negative, NaN, Infinity and anything past 2^31 - 1 ms as // 1 ms, so through 5.3.0 each failed every call as a timeout 1 ms in. Refused // where set instead, per call before a bogon or a cached address can answer. const IMPOSSIBLE_TIMEOUTS = [0, -1, NaN, Infinity, 2 ** 31, '5000']; test('a timeout no attempt can meet is refused on the client', () => { for (const timeoutMs of IMPOSSIBLE_TIMEOUTS) { assert.throws(() => new VPNDetection({ timeoutMs: timeoutMs }), (err) => err instanceof VPNDetectionError && err.kind === 'bad_request', String(timeoutMs)); } for (const timeoutMs of [1, 2 ** 31 - 1]) { assert.doesNotThrow(() => new VPNDetection({ timeoutMs: timeoutMs }), String(timeoutMs)); } }); test('a timeout no attempt can meet is refused per call, before anything answers', async () => { const stub = pathRecordingFetch(); const client = new VPNDetection({ apiKey: 'k', fetch: stub.fetch, retries: 0 }); await client.lookup('8.8.8.8'); const asked = stub.paths.length; const calls = { 'a bogon': (o) => client.lookup('10.0.0.1', o), 'a cached address': (o) => client.lookup('8.8.8.8', o), 'a batch': (o) => client.lookupBatch(['10.0.0.1', '8.8.8.8'], o), 'myIp': (o) => client.myIp(o), 'myEntitlement': (o) => client.myEntitlement(o), 'downloads': (o) => client.database.downloads(o), 'metadata': (o) => client.oauth.metadata(o), 'revoke': (o) => client.oauth.revoke('vpndetection-cli', 'mo_rt_x', o), 'pollDeviceToken': (o) => client.oauth.pollDeviceToken('vpndetection-cli', { device_code: 'mo_dc_x', user_code: 'x', verification_uri: 'x', expires_in: 900, interval: 2, }, o), }; // Before its first wait, not after sitting out the interval. const started = performance.now(); await assert.rejects(calls.pollDeviceToken({ timeoutMs: 0 }), VPNDetectionError); assert.ok(performance.now() - started < 1000, 'the poll waited before refusing'); for (const timeoutMs of IMPOSSIBLE_TIMEOUTS) { for (const [name, call] of Object.entries(calls)) { await assert.rejects(call({ timeoutMs: timeoutMs }), (err) => err instanceof VPNDetectionError && err.kind === 'bad_request', `${name}: ${timeoutMs}`); } } assert.equal(stub.paths.length, asked, 'a refused timeout sent a request'); }); // setTimeout runs a delay past 2^31 - 1 ms as 1 ms and prints a // TimeoutOverflowWarning, which through 5.3.1 is how a Retry-After of 2147484 s // or more was waited: on the caller's stderr, once per retry, from the API and // object storage alike. The backoff alone waits it now, still a throttle. test('a Retry-After past what setTimeout holds waits the backoff, with no warning', async (t) => { const warnings = timeoutWarnings(t); const paths = []; const fetch = async (input) => { const url = new URL(typeof input === 'string' ? input : input.url); paths.push(url.pathname); if (url.pathname === '/api/v1/database/download') { return new Response(null, { status: 302, headers: { location: 'https://storage.invalid/blob' } }); } if (paths.filter((p) => p === url.pathname).length === 1) { return new Response(JSON.stringify({ error: 'rate limit exceeded' }), { status: 429, headers: { 'content-type': 'application/json', 'retry-after': '2147484' }, }); } if (url.pathname === '/blob') { return new Response(new Uint8Array([1, 2, 3]), { status: 200 }); } return new Response(JSON.stringify({ ip: '9.9.9.9', is_vpn: false }), { status: 200, headers: { 'content-type': 'application/json' }, }); }; const client = new VPNDetection({ fetch: fetch, retries: 1, cache: false }); assert.equal((await client.lookup('9.9.9.9')).ip, '9.9.9.9'); assert.deepEqual(await client.database.downloadBytes('cdn_ip_v1', 'csvgz'), new Uint8Array([1, 2, 3])); assert.deepEqual(paths, ['/9.9.9.9', '/9.9.9.9', '/api/v1/database/download', '/blob', '/blob']); assert.deepEqual(warnings, []); }); // p-retry calls onFailedAttempt before it checks retriesLeft, so through 5.4.0 // a 429's Retry-After was waited out even after the last attempt, and only // then did the call fail. test('a Retry-After is not waited out when no retry follows', async () => { const fetch = async () => new Response(JSON.stringify({ error: 'rate limit exceeded' }), { status: 429, headers: { 'content-type': 'application/json', 'retry-after': '3' }, }); // One retry waits the header once, then p-retry's own 1 s backoff. for (const [retries, least, most] of [[0, 0, 1000], [1, 3000, 6000]]) { const client = new VPNDetection({ fetch: fetch, cache: false, retries: retries }); const started = Date.now(); await assert.rejects(client.lookup('9.9.9.9'), (err) => err.kind === 'rate_limited'); const elapsed = Date.now() - started; assert.ok(elapsed >= least && elapsed < most, `retries ${retries} failed after ${elapsed} ms, want ${least} to ${most} ms`); } }); function timeoutWarnings(t) { const seen = []; const listener = (warning) => { if (warning.name === 'TimeoutOverflowWarning') { seen.push(warning.message); } }; process.on('warning', listener); t.after(() => process.off('warning', listener)); return seen; }