// VirginProxy – minimal official client for Node.js 18+ (one file, no dependencies). // Docs: https://docs.virginproxy.com/sdks/ API: https://docs.virginproxy.com/openapi.json // // import { VirginProxy } from './virginproxy.mjs'; // const vp = new VirginProxy(); // key from VP_KEY // const page = await vp.scrape('https://example.com/'); // console.log(page.body); // // Errors are thrown as VirginProxyError with the API's stable `code`. Calls that failed because of a short-lived // limit (rate_limited, concurrency_limited, busy, …) are retried automatically after the time the API asks for. import { createHmac, timingSafeEqual } from 'node:crypto'; export const VERSION = '1.2.0'; const RETRY_CODES = new Set(['rate_limited', 'concurrency_limited', 'busy', 'executor_unavailable', 'idempotency_in_progress', 'render_unavailable']); export class VirginProxyError extends Error { constructor(status, body, headers) { const e = body?.error || {}; super(`${e.code || `http_${status}`}: ${e.message || 'The API answered with an error.'}`); this.name = 'VirginProxyError'; this.status = status; this.code = e.code || `http_${status}`; this.charged = e.charged; this.credits = e.credits; this.retryAfterMs = e.retry_after_ms ?? (headers?.get?.('retry-after') ? Number(headers.get('retry-after')) * 1000 : undefined); this.requestId = body?.request_id || headers?.get?.('x-request-id') || undefined; this.details = e; } } const qs = (query = {}) => { const p = new URLSearchParams(); for (const [k, v] of Object.entries(query)) if (v !== undefined && v !== null) p.append(k, typeof v === 'boolean' ? String(v) : String(v)); const s = p.toString(); return s ? `?${s}` : ''; }; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); export class VirginProxy { /** * @param {object} [o] * @param {string} [o.apiKey] defaults to process.env.VP_KEY ("vp_live_…" or a test key "vp_test_…") * @param {string} [o.baseUrl] defaults to https://api.virginproxy.com * @param {number} [o.timeoutMs] per call, default 180000 * @param {number} [o.maxRetries] automatic retries of short-lived limits, default 2 * @param {typeof fetch} [o.fetch] */ constructor({ apiKey = globalThis.process?.env?.VP_KEY, baseUrl = 'https://api.virginproxy.com', timeoutMs = 180000, maxRetries = 2, fetch: f } = {}) { if (!apiKey) throw new Error('VirginProxy: no API key. Pass { apiKey } or set VP_KEY.'); this.apiKey = apiKey; this.baseUrl = baseUrl.replace(/\/+$/, ''); this.timeoutMs = timeoutMs; this.maxRetries = maxRetries; this.fetch = f || globalThis.fetch; } /** One call; JSON in and out unless `raw` (then the Response). */ async call(method, path, { body, rawBody, query, headers = {}, raw = false, timeoutMs = this.timeoutMs } = {}) { for (let attempt = 0; ; attempt++) { const res = await this.fetch(`${this.baseUrl}${path}${qs(query)}`, { method, headers: { Authorization: `Bearer ${this.apiKey}`, 'User-Agent': `virginproxy-node/${VERSION}`, ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...headers }, body: rawBody !== undefined ? rawBody : body !== undefined ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(timeoutMs), }); if (res.ok) { if (raw) return res; return res.status === 204 ? null : res.json(); } let data = null; try { data = await res.json(); } catch { /* not JSON */ } const err = new VirginProxyError(res.status, data, res.headers); if (RETRY_CODES.has(err.code) && attempt < this.maxRetries) { await sleep(Math.min(30000, Math.max(250, err.retryAfterMs ?? 1000))); continue; } throw err; } } // ---- requests ----------------------------------------------------------------------------------- /** POST /v1/requests with any options. */ request(body, { idempotencyKey } = {}) { return this.call('POST', '/v1/requests', { body, headers: idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {} }); } /** One page as Markdown of its main content (override with options, e.g. { render: true }). */ scrape(url, options = {}, opts) { return this.request({ format: 'markdown', main_content: true, ...options, url }, opts); } /** GET /v1/raw: the target's answer itself. Returns { status, headers, body (Buffer), credits, requestId }. */ async raw(url, query = {}, { headers = {} } = {}) { const h = Object.fromEntries(Object.entries(headers).map(([k, v]) => [`X-VP-Header-${k}`, v])); const res = await this.call('GET', '/v1/raw', { query: { ...query, url }, headers: h, raw: true }); return { status: Number(res.headers.get('x-vp-status') || res.status), headers: res.headers, body: Buffer.from(await res.arrayBuffer()), credits: Number(res.headers.get('x-vp-credits') || 0), requestId: res.headers.get('x-vp-request-id') }; } /** GET /v1/screenshot: { image (Buffer), type, credits, requestId, status }. */ async screenshot(url, query = {}) { return this.#file('/v1/screenshot', url, query, 'image'); } /** GET /v1/pdf: { pdf (Buffer), credits, requestId, status }. */ async pdf(url, query = {}) { return this.#file('/v1/pdf', url, query, 'pdf'); } async #file(path, url, query, field) { const res = await this.call('GET', path, { query: { ...query, url }, raw: true }); return { [field]: Buffer.from(await res.arrayBuffer()), type: res.headers.get('content-type'), credits: Number(res.headers.get('x-vp-credits') || 0), requestId: res.headers.get('x-vp-request-id'), status: Number(res.headers.get('x-vp-status') || 0), test: res.headers.get('x-vp-test') === 'true' }; } /** POST /v1/batch: { requests: [...] } or { urls: [...], request: {...} }. */ batch(body) { return this.call('POST', '/v1/batch', { body, timeoutMs: Math.max(this.timeoutMs, 120000) }); } /** Several pages with the same options, answered together. */ batchUrls(urls, request = { format: 'markdown', main_content: true }, { maxCredits, tag } = {}) { return this.batch({ urls, request, ...(maxCredits ? { max_credits: maxCredits } : {}), ...(tag ? { tag } : {}) }); } map(body) { return this.call('POST', '/v1/map', { body: typeof body === 'string' ? { url: body } : body }); } /** POST /v1/search: results as JSON; options as in the docs (engine, limit, language, country, time_range, scrape …). */ search(query, options = {}) { return this.call('POST', '/v1/search', { body: { ...options, query }, timeoutMs: Math.max(this.timeoutMs, 180000) }); } estimate(body) { return this.call('POST', '/v1/estimate', { body }); } solveCaptcha(body) { return this.call('POST', '/v1/captcha', { body }); } // ---- jobs and crawls ---------------------------------------------------------------------------- createJob(body, { idempotencyKey } = {}) { return this.call('POST', '/v1/jobs', { body, headers: idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {} }); } crawl(body, { idempotencyKey } = {}) { return this.call('POST', '/v1/crawl', { body: typeof body === 'string' ? { url: body } : body, headers: idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {} }); } listJobs(query) { return this.call('GET', '/v1/jobs', { query }); } /** With { wait: 1…30 } the answer waits until the job moves on (or the seconds pass). */ getJob(id, { wait } = {}) { return this.call('GET', `/v1/jobs/${encodeURIComponent(id)}`, { query: wait ? { wait } : undefined, timeoutMs: wait ? Math.max(this.timeoutMs, (wait + 15) * 1000) : this.timeoutMs }); } jobResults(id, query) { return this.call('GET', `/v1/jobs/${encodeURIComponent(id)}/results`, { query }); } cancelJob(id) { return this.call('DELETE', `/v1/jobs/${encodeURIComponent(id)}`); } retryJob(id) { return this.call('POST', `/v1/jobs/${encodeURIComponent(id)}/retry`); } /** Every result of a job, page by page. */ async *iterJobResults(id, { status } = {}) { let offset = 0; for (;;) { const page = await this.jobResults(id, { offset, limit: 100, status }); for (const it of page.items) yield it; if (page.next_offset === null || page.next_offset === undefined) return; offset = page.next_offset; } } /** * GET /v1/jobs/{id}/stream: every finished item as it comes ({ type: 'item', … }), then { type: 'end', job }. * Reconnects by itself after the server's 15-minute limit; pings are skipped. */ async *streamJob(id, { includeBody } = {}) { let after; for (;;) { const res = await this.call('GET', `/v1/jobs/${encodeURIComponent(id)}/stream`, { query: { after, include_body: includeBody }, raw: true, timeoutMs: 16 * 60000 }); const reader = res.body.getReader(); const dec = new TextDecoder(); let buf = ''; let again = false; for (;;) { const { done, value } = await reader.read(); if (done) break; buf += dec.decode(value, { stream: true }); let nl; while ((nl = buf.indexOf('\n')) >= 0) { const line = buf.slice(0, nl).trim(); buf = buf.slice(nl + 1); if (!line) continue; const msg = JSON.parse(line); if (msg.type === 'item') { after = msg.index; yield msg; } else if (msg.type === 'end') { yield msg; return; } else if (msg.type === 'reconnect') { after = msg.after; again = true; } } } if (!again) return; } } /** POST /v1/jobs with an NDJSON body: one request per line (strings are taken as URLs), optional job options. */ createJobNdjson(requests, jobOptions) { const lines = [...(jobOptions ? [JSON.stringify({ job: jobOptions })] : []), ...requests.map((r) => JSON.stringify(typeof r === 'string' ? { url: r } : r))]; return this.call('POST', '/v1/jobs', { rawBody: `${lines.join('\n')}\n`, headers: { 'Content-Type': 'application/x-ndjson' } }); } /** GET /v1/jobs/{id}/export as text (ndjson, csv or json). */ async exportJob(id, { format = 'ndjson', status, includeBody } = {}) { const res = await this.call('GET', `/v1/jobs/${encodeURIComponent(id)}/export`, { query: { format, status, include_body: includeBody }, raw: true }); return res.text(); } /** Waits until the job is done or canceled (the API holds each call up to 25 s while nothing changes; at most 30 min). */ async waitForJob(id, { intervalMs = 500, timeoutMs = 30 * 60000 } = {}) { const end = Date.now() + timeoutMs; for (;;) { const job = await this.getJob(id, { wait: 25 }); if (!['queued', 'running'].includes(job.status)) return job; if (Date.now() > end) throw new Error(`VirginProxy: job ${id} still ${job.status} after ${timeoutMs} ms`); await sleep(intervalMs); } } // ---- presets and schedules ---------------------------------------------------------------------- listPresets() { return this.call('GET', '/v1/presets'); } getPreset(name) { return this.call('GET', `/v1/presets/${encodeURIComponent(name)}`); } createPreset(name, request, { description } = {}) { return this.call('POST', '/v1/presets', { body: { name, request, ...(description ? { description } : {}) } }); } updatePreset(name, changes) { return this.call('PATCH', `/v1/presets/${encodeURIComponent(name)}`, { body: changes }); } deletePreset(name) { return this.call('DELETE', `/v1/presets/${encodeURIComponent(name)}`); } listSchedules() { return this.call('GET', '/v1/schedules'); } getSchedule(id) { return this.call('GET', `/v1/schedules/${encodeURIComponent(id)}`); } createSchedule(body) { return this.call('POST', '/v1/schedules', { body }); } updateSchedule(id, changes) { return this.call('PATCH', `/v1/schedules/${encodeURIComponent(id)}`, { body: changes }); } pauseSchedule(id) { return this.updateSchedule(id, { status: 'paused' }); } resumeSchedule(id) { return this.updateSchedule(id, { status: 'active' }); } deleteSchedule(id) { return this.call('DELETE', `/v1/schedules/${encodeURIComponent(id)}`); } runSchedule(id) { return this.call('POST', `/v1/schedules/${encodeURIComponent(id)}/run`); } /** A rhythm checked ("weekdays at 09:30") and its next three runs; nothing is saved. */ previewSchedule(every) { return this.call('POST', '/v1/schedules/preview', { body: { every } }); } /** Monitors (track: "pages"): what each run found – new, removed and changed pages. */ scheduleReports(id, query) { return this.call('GET', `/v1/schedules/${encodeURIComponent(id)}/reports`, { query }); } // ---- storage destinations (delivery to your own S3-compatible bucket) ---- listDestinations() { return this.call('GET', '/v1/destinations'); } createDestination(body) { return this.call('POST', '/v1/destinations', { body }); } deleteDestination(id) { return this.call('DELETE', `/v1/destinations/${encodeURIComponent(id)}`); } testDestination(id) { return this.call('POST', `/v1/destinations/${encodeURIComponent(id)}/test`); } // ---- account ------------------------------------------------------------------------------------ account() { return this.call('GET', '/v1/account'); } usage(query) { return this.call('GET', '/v1/usage', { query }); } usageBreakdown(query) { return this.call('GET', '/v1/usage/breakdown', { query }); } listRequests(query) { return this.call('GET', '/v1/requests', { query }); } getRequest(id) { return this.call('GET', `/v1/requests/${encodeURIComponent(id)}`); } /** The kept answer of a request (sent with an Idempotency-Key, or cached). */ getAnswer(id) { return this.call('GET', `/v1/requests/${encodeURIComponent(id)}/answer`); } /** What you may still do right now: parallel requests, rate, CAPTCHAs today, daily caps. */ limits() { return this.call('GET', '/v1/limits'); } /** Daily cap, credit alert thresholds, alert webhook (a key with the manage scope). */ updateSettings(changes) { return this.call('PATCH', '/v1/account/settings', { body: changes }); } status() { return this.call('GET', '/v1/status'); } /** Every error code with its HTTP status, meaning and whether to retry. */ errors() { return this.call('GET', '/v1/errors'); } // ---- keys and webhooks (a live key without its own credit limit) --------------------------------- listKeys() { return this.call('GET', '/v1/keys'); } createKey(body) { return this.call('POST', '/v1/keys', { body }); } updateKey(id, body) { return this.call('PATCH', `/v1/keys/${encodeURIComponent(id)}`, { body }); } revokeKey(id, { confirmCurrent = false } = {}) { return this.call('DELETE', `/v1/keys/${encodeURIComponent(id)}`, { query: confirmCurrent ? { confirm: 'revoke_current_key' } : {} }); } getWebhooks(query) { return this.call('GET', '/v1/webhooks', { query }); } rotateWebhookSecret() { return this.call('POST', '/v1/webhooks/secret'); } testWebhook(url, event = 'webhook.test') { return this.call('POST', '/v1/webhooks/test', { body: { url, event } }); } rollKey(id, body = {}) { return this.call('POST', `/v1/keys/${encodeURIComponent(id)}/roll`, { body }); } listDeliveries(query) { return this.call('GET', '/v1/webhooks/deliveries', { query }); } getDelivery(id) { return this.call('GET', `/v1/webhooks/deliveries/${encodeURIComponent(id)}`); } redeliver(id) { return this.call('POST', `/v1/webhooks/deliveries/${encodeURIComponent(id)}/redeliver`); } /** * Checks the X-VP-Signature header of a webhook ("t=…,v1=…") against the raw body. Returns true or false. * Use the bytes you received, not re-serialised JSON. */ /** * Checks X-VP-Signature ("t=…,v1=…") against the raw body. During a secret rotation with a grace period the header * carries two signatures ("t=…,v1=,v1="): the call is genuine when any of them matches your secret. */ static verifyWebhook(secret, rawBody, signatureHeader, { toleranceSec = 300, now = Date.now() } = {}) { const m = /^t=(\d+)((?:,v1=[0-9a-f]{64}){1,2})$/.exec(String(signatureHeader || '').trim()); if (!m) return false; if (Math.abs(now / 1000 - Number(m[1])) > toleranceSec) return false; const want = createHmac('sha256', secret).update(`${m[1]}.`).update(typeof rawBody === 'string' ? Buffer.from(rawBody) : rawBody).digest(); let ok = false; for (const sig of m[2].slice(4).split(',v1=')) { const got = Buffer.from(sig, 'hex'); if (got.length === want.length && timingSafeEqual(got, want)) ok = true; } return ok; } } export default VirginProxy;