Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
230 lines (209 loc) · 12.7 KB
/
Copy pathindex.js
File metadata and controls
230 lines (209 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// Vardic: one client for every Vardic UK data API (vehicle, business, sanctions, monitoring, location).
// Docs: https://vardic.dev/docs . No dependencies; needs global fetch (Node 18+, Deno, Bun, edge runtimes).
export const VERSION = '1.0.0';
/** Thrown for every failed call: an error response from the API, a timeout (code "timeout") or a network failure (code "network_error"). */
export class VardicApiError extends Error {
/**
* @param {number} status HTTP status, or 0 when no response arrived
* @param {string} code Stable machine-readable code, for example "quota_exceeded"
* @param {string} message
* @param {{ requestId?: string|null, body?: any, retryAfter?: number|null }} [extra]
*/
constructor(status, code, message, extra = {}) {
super(message);
this.name = 'VardicApiError';
this.status = status;
this.code = code;
this.requestId = extra.requestId ?? null;
this.body = extra.body;
this.retryAfter = extra.retryAfter ?? null;
}
}
const NO_RETRY_CODES = new Set(['quota_exceeded', 'coming_soon']);
const MAX_RETRY_WAIT_SECS = 30;
function query(params) {
const q = new URLSearchParams();
for (const [k, v] of Object.entries(params ?? {})) {
if (v === undefined || v === null || v === '') continue;
q.set(k, Array.isArray(v) ? v.join(',') : String(v));
}
const s = q.toString();
return s ? `?${s}` : '';
}
const seg = (v) => encodeURIComponent(String(v));
function parseRetryAfter(value) {
if (value === null || value === undefined || value === '') return null;
const n = Number(value);
if (Number.isFinite(n)) return Math.max(0, n);
const t = Date.parse(value);
return Number.isNaN(t) ? null : Math.max(0, (t - Date.now()) / 1000);
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
class Product {
constructor(client) { this._c = client; }
}
class Vehicle extends Product {
/** Look up a vehicle by registration: DVLA record, MOT history, mileage checks and ULEZ estimate. Returns { data, meta }. */
get(registration) { return this._c._request('GET', `/v1/vehicles/${seg(registration)}`); }
/** Look up up to 25 registrations. Each entry has its own data or error. */
bulk(registrations) { return this._c._request('POST', '/v1/vehicles/bulk', { body: { registrations } }); }
}
class Business extends Product {
/** Check a company. Options: vat, eori, include (array or comma string, for example ['officers', 'psc']). */
check(number, { vat, eori, include } = {}) { return this._c._request('GET', `/v1/companies/${seg(number)}${query({ vat, eori, include })}`); }
/** Company officers (one check). Options: page, size. */
officers(number, { page, size } = {}) { return this._c._request('GET', `/v1/companies/${seg(number)}/officers${query({ page, size })}`); }
/** Persons with significant control (one check). Options: page, size. */
psc(number, { page, size } = {}) { return this._c._request('GET', `/v1/companies/${seg(number)}/persons-with-significant-control${query({ page, size })}`); }
/** Registered charges (one check). Options: page, size. */
charges(number, { page, size } = {}) { return this._c._request('GET', `/v1/companies/${seg(number)}/charges${query({ page, size })}`); }
/** Filing history (one check). Options: page, size, category. */
filings(number, { page, size, category } = {}) { return this._c._request('GET', `/v1/companies/${seg(number)}/filing-history${query({ page, size, category })}`); }
/** UK ownership check: owners at 50% or more, screened against sanctions lists. Options: depth, threshold. A screening aid, not legal advice. */
ownership(number, { depth, threshold } = {}) { return this._c._request('GET', `/v1/companies/${seg(number)}/ownership${query({ depth, threshold })}`); }
/** Search companies by name (at least 2 characters). */
search(q) { return this._c._request('GET', `/v1/companies/search${query({ q })}`); }
/** Check a UK (GB) EORI number with HMRC. */
eori(eori) { return this._c._request('GET', `/v1/eori/${seg(eori)}`); }
/** Validate a UK VAT number with HMRC. Not open yet: throws a 503 (not counted) until it is. */
vat(vatNumber) { return this._c._request('GET', `/v1/vat/${seg(vatNumber)}`); }
}
class Sanctions extends Product {
/** Screen a name: { name, type?, dob?, country?, lists?, threshold?, limit?, record?, reference? }. */
screen(q) { return this._c._request('POST', '/v1/sanctions/screen', { body: q }); }
/** Screen up to 25 queries. One result per query, in order. */
screenBulk(queries) { return this._c._request('POST', '/v1/sanctions/screen/bulk', { body: { queries } }); }
/**
* Screen a CSV file of names (a string or bytes). Options: record, format ('json' or 'csv'), threshold, lists, type.
* With format 'csv' the result is the CSV text; otherwise the parsed JSON summary.
*/
screenCsv(csv, { record, format, threshold, lists, type } = {}) {
return this._c._request('POST', `/v1/sanctions/screen/csv${query({ record, format, threshold, lists, type })}`, {
rawBody: csv, contentType: 'text/csv', as: format === 'csv' ? 'text' : 'json',
});
}
/** Your screening records, newest first (not counted). Options: limit, before (ISO timestamp). */
listChecks({ limit, before } = {}) { return this._c._request('GET', `/v1/sanctions/checks${query({ limit, before })}`); }
/** One screening record with its results. */
getCheck(id) { return this._c._request('GET', `/v1/sanctions/checks/${seg(id)}`); }
/** Delete a screening record. */
deleteCheck(id) { return this._c._request('DELETE', `/v1/sanctions/checks/${seg(id)}`); }
/** PDF screening certificate as a Uint8Array. Option: row (1-based, one row of a batch). */
certificate(id, { row } = {}) { return this._c._request('GET', `/v1/sanctions/checks/${seg(id)}/certificate${query({ row })}`, { as: 'bytes' }); }
/** Results file of a recorded CSV batch, as text. */
checkCsv(id) { return this._c._request('GET', `/v1/sanctions/checks/${seg(id)}/results.csv`, { as: 'text' }); }
/** List versions and publication dates (not counted). */
lists() { return this._c._request('GET', '/v1/sanctions/lists'); }
}
class Monitoring extends Product {
/** List your watches. */
list() { return this._c._request('GET', '/v1/watches'); }
/**
* Create a watch. Send one of registration, companyNumber or sanctions ({ name, ... }) with a url.
* Options: daysBefore (vehicles), events, emailDigest.
*/
create(watch) { return this._c._request('POST', '/v1/watches', { body: watch }); }
/** Watch up to 500 companies: { companyNumbers, url, events?, emailDigest? }. Returns { data: { created, errors } }. */
createMany(watches) { return this._c._request('POST', '/v1/watches/bulk', { body: watches }); }
/** Delete a watch. Resolves to null. */
delete(id) { return this._c._request('DELETE', `/v1/watches/${seg(id)}`); }
/** Send a sample signed event to a URL: { url, type? }. Needs your own key; sandbox keys work. */
testEvent(opts) { return this._c._request('POST', '/v1/watches/test-event', { body: opts }); }
}
class Location extends Product {
/** Check a postcode in Great Britain: area codes, flood risk, crime and schools. Options: include, schools, phase. */
postcode(postcode, { include, schools, phase } = {}) { return this._c._request('GET', `/v1/postcodes/${seg(postcode)}${query({ include, schools, phase })}`); }
/** Nearest or cheapest forecourts. Options: postcode or lat and lng, fuel, radius (km), sort, limit. */
fuelNearest({ postcode, lat, lng, fuel, radius, sort, limit } = {}) { return this._c._request('GET', `/v1/fuel/nearest${query({ postcode, lat, lng, fuel, radius, sort, limit })}`); }
/** Every price at one forecourt. */
fuelStation(id) { return this._c._request('GET', `/v1/fuel/stations/${seg(id)}`); }
/** Price history for a forecourt. Option: days (1 to 90). */
fuelHistory(id, { days } = {}) { return this._c._request('GET', `/v1/fuel/stations/${seg(id)}/history${query({ days })}`); }
}
export class Vardic {
/** @param {{ apiKey?: string, baseUrl?: string, timeoutMs?: number, maxRetries?: number, fetch?: typeof fetch }} [opts] */
constructor(opts = {}) {
this.apiKey = opts.apiKey ?? (typeof process !== 'undefined' ? process.env.VARDIC_API_KEY : undefined);
if (!this.apiKey) throw new Error('Pass apiKey or set VARDIC_API_KEY. Free key: https://vardic.dev/signup');
this.baseUrl = (opts.baseUrl ?? 'https://api.vardic.dev').replace(/\/+$/, '');
this.timeoutMs = opts.timeoutMs ?? 15000;
this.maxRetries = opts.maxRetries ?? 2;
this._fetch = opts.fetch ?? globalThis.fetch;
this.vehicle = new Vehicle(this);
this.business = new Business(this);
this.sanctions = new Sanctions(this);
this.monitoring = new Monitoring(this);
this.location = new Location(this);
}
/** Your plans, usage this month and webhook secret. */
account() { return this._request('GET', '/v1/account'); }
/** Public service status with uptime per source. Not counted. */
status() { return this._request('GET', '/v1/status'); }
async _request(method, path, { body, rawBody, contentType, as = 'json' } = {}) {
const headers = { 'x-api-key': this.apiKey, 'user-agent': `vardic-node/${VERSION}`, accept: as === 'json' ? 'application/json' : '*/*' };
let payload;
if (rawBody !== undefined) { payload = rawBody; headers['content-type'] = contentType; }
else if (body !== undefined) { payload = JSON.stringify(body); headers['content-type'] = 'application/json'; }
for (let attempt = 0; ; attempt++) {
const ctrl = new AbortController();
let timedOut = false;
const timer = setTimeout(() => { timedOut = true; ctrl.abort(); }, this.timeoutMs);
let res; let out;
try {
res = await this._fetch(this.baseUrl + path, { method, headers, body: payload, signal: ctrl.signal });
if (res.status === 204) out = null;
else if (as === 'bytes' && res.ok) out = new Uint8Array(await res.arrayBuffer());
else out = await res.text();
} catch (e) {
if (timedOut) throw new VardicApiError(0, 'timeout', `No response within ${this.timeoutMs} ms`);
throw new VardicApiError(0, 'network_error', e?.message ?? 'Network error');
} finally { clearTimeout(timer); }
if (res.ok) {
if (out === null || as !== 'json') return out;
try { return out ? JSON.parse(out) : null; } catch {
throw new VardicApiError(res.status, 'invalid_response', 'The response was not valid JSON', { requestId: res.headers?.get?.('x-request-id') ?? null });
}
}
let json = {};
try { json = JSON.parse(out) ?? {}; } catch { /* not JSON */ }
const err = json?.error ?? {};
const retryAfter = parseRetryAfter(res.headers?.get?.('retry-after'));
const apiError = new VardicApiError(res.status, err.code ?? 'http_error', err.message ?? `HTTP ${res.status}`, {
requestId: res.headers?.get?.('x-request-id') ?? json?.meta?.requestId ?? null, body: json, retryAfter,
});
const retryable = (res.status === 429 || res.status === 503) && !NO_RETRY_CODES.has(apiError.code);
if (!retryable || attempt >= this.maxRetries) throw apiError;
const waitSecs = retryAfter ?? 0.5 * 2 ** attempt;
if (waitSecs > MAX_RETRY_WAIT_SECS) throw apiError;
await sleep(waitSecs * 1000);
}
}
/** Same as the exported verifyWebhook. */
static verifyWebhook(rawBody, header, secret, toleranceSecs) { return verifyWebhook(rawBody, header, secret, toleranceSecs); }
}
/**
* Verify a webhook's vardic-signature header. rawBody must be the exact request body (string or bytes).
* Resolves to true only for a valid signature made within toleranceSecs (default 300).
*/
export async function verifyWebhook(rawBody, header, secret, toleranceSecs = 300) {
const parts = {};
for (const p of String(header ?? '').split(',')) {
const i = p.indexOf('=');
if (i > 0) parts[p.slice(0, i).trim()] = p.slice(i + 1).trim();
}
const t = Number(parts.t);
if (!parts.t || !parts.v1 || !Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > toleranceSecs) return false;
const subtle = (globalThis.crypto ?? (await import('node:crypto')).webcrypto).subtle; // Node 18 has no global crypto
const enc = new TextEncoder();
const body = typeof rawBody === 'string' ? enc.encode(rawBody) : new Uint8Array(rawBody);
const prefix = enc.encode(`${parts.t}.`);
const data = new Uint8Array(prefix.length + body.length);
data.set(prefix); data.set(body, prefix.length);
const key = await subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
const hex = [...new Uint8Array(await subtle.sign('HMAC', key, data))].map((b) => b.toString(16).padStart(2, '0')).join('');
if (hex.length !== parts.v1.length) return false;
let diff = 0;
for (let i = 0; i < hex.length; i++) diff |= hex.charCodeAt(i) ^ parts.v1.charCodeAt(i);
return diff === 0;
}
export default Vardic;