vpndetection-web 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +267 -2
  3. package/dist/bogon.d.ts +28 -0
  4. package/dist/bogon.js +164 -0
  5. package/dist/bogons.gen.d.ts +2 -0
  6. package/dist/bogons.gen.js +87 -0
  7. package/dist/client.d.ts +153 -0
  8. package/dist/client.js +384 -0
  9. package/dist/errors.d.ts +55 -0
  10. package/dist/errors.js +178 -0
  11. package/dist/generated/client/client.gen.d.ts +2 -0
  12. package/dist/generated/client/client.gen.js +216 -0
  13. package/dist/generated/client/index.d.ts +10 -0
  14. package/dist/generated/client/index.js +6 -0
  15. package/dist/generated/client/types.gen.d.ts +120 -0
  16. package/dist/generated/client/types.gen.js +2 -0
  17. package/dist/generated/client/utils.gen.d.ts +37 -0
  18. package/dist/generated/client/utils.gen.js +228 -0
  19. package/dist/generated/client.gen.d.ts +12 -0
  20. package/dist/generated/client.gen.js +3 -0
  21. package/dist/generated/core/auth.gen.d.ts +25 -0
  22. package/dist/generated/core/auth.gen.js +14 -0
  23. package/dist/generated/core/bodySerializer.gen.d.ts +25 -0
  24. package/dist/generated/core/bodySerializer.gen.js +57 -0
  25. package/dist/generated/core/params.gen.d.ts +43 -0
  26. package/dist/generated/core/params.gen.js +109 -0
  27. package/dist/generated/core/pathSerializer.gen.d.ts +33 -0
  28. package/dist/generated/core/pathSerializer.gen.js +106 -0
  29. package/dist/generated/core/queryKeySerializer.gen.d.ts +18 -0
  30. package/dist/generated/core/queryKeySerializer.gen.js +92 -0
  31. package/dist/generated/core/serverSentEvents.gen.d.ts +71 -0
  32. package/dist/generated/core/serverSentEvents.gen.js +132 -0
  33. package/dist/generated/core/types.gen.d.ts +83 -0
  34. package/dist/generated/core/types.gen.js +2 -0
  35. package/dist/generated/core/utils.gen.d.ts +19 -0
  36. package/dist/generated/core/utils.gen.js +87 -0
  37. package/dist/generated/index.d.ts +2 -0
  38. package/dist/generated/index.js +2 -0
  39. package/dist/generated/sdk.gen.d.ts +115 -0
  40. package/dist/generated/sdk.gen.js +171 -0
  41. package/dist/generated/types.gen.d.ts +787 -0
  42. package/dist/generated/types.gen.js +2 -0
  43. package/dist/index.d.ts +10 -0
  44. package/dist/index.js +4 -0
  45. package/dist/oauth.d.ts +114 -0
  46. package/dist/oauth.js +245 -0
  47. package/dist/shapes.d.ts +28 -0
  48. package/dist/shapes.js +133 -0
  49. package/dist/store.d.ts +39 -0
  50. package/dist/store.js +64 -0
  51. package/dist/transport.d.ts +47 -0
  52. package/dist/transport.js +140 -0
  53. package/dist/types.d.ts +48 -0
  54. package/dist/types.js +42 -0
  55. package/package.json +65 -3
@@ -0,0 +1,153 @@
1
+ import type { Entitlement } from './generated/types.gen.js';
2
+ import { VPNDetectionError } from './errors.js';
3
+ import { OauthApi } from './oauth.js';
4
+ import { type CacheStore } from './store.js';
5
+ import { type Result } from './types.js';
6
+ export declare const DEFAULT_BASE_URL = "https://api.vpndetection.io";
7
+ export interface CacheOptions {
8
+ /** Maximum number of addresses held in memory. Default 10000. */
9
+ max?: number;
10
+ /** How long an answer stays fresh, in milliseconds. Default 1 hour. */
11
+ ttlMs?: number;
12
+ /**
13
+ * Where answers outlive this client: read after the in-memory cache misses and
14
+ * before the network, and written after each answer the API serves. Bogons,
15
+ * errors, `myIp` and `myEntitlement` are never stored.
16
+ */
17
+ store?: CacheStore;
18
+ }
19
+ export interface Options {
20
+ /**
21
+ * Your API key. Omit it entirely to use the free tier, which answers
22
+ * `ip` and `is_vpn` and allows 1000 requests per day per source address.
23
+ * A key in a web page is readable by anyone who opens the page.
24
+ */
25
+ apiKey?: string;
26
+ baseUrl?: string;
27
+ /** Pass `false` to disable caching. */
28
+ cache?: CacheOptions | false;
29
+ /** Concurrent batch requests - chunks of up to 1000 addresses - during a batch. Default 8. */
30
+ concurrency?: number;
31
+ /** Retry attempts for a transient failure, a whole number from 0. Default 2. */
32
+ retries?: number;
33
+ /**
34
+ * How long one request may take before it is abandoned, in milliseconds.
35
+ * Default 30000. Applies per attempt, so a retried call may take longer in
36
+ * total.
37
+ */
38
+ timeoutMs?: number;
39
+ /** Override the HTTP implementation, mostly for tests. Defaults to the global `fetch`. */
40
+ fetch?: typeof globalThis.fetch;
41
+ }
42
+ /** Per-call overrides for a single lookup. Anything omitted falls back to the client's setting. */
43
+ export interface LookupOptions {
44
+ /** Retry attempts for a transient failure, a whole number from 0. */
45
+ retries?: number;
46
+ /** How long one attempt may take before it is abandoned, in milliseconds. */
47
+ timeoutMs?: number;
48
+ }
49
+ /** Per-call overrides for one batch. Anything omitted falls back to the client's setting. */
50
+ export interface BatchOptions extends LookupOptions {
51
+ /** Concurrent batch requests for THIS batch only. */
52
+ concurrency?: number;
53
+ }
54
+ /**
55
+ * A client for the VPNDetection API, for a browser: a page's own scripts, a web
56
+ * worker or an extension.
57
+ *
58
+ * The cache is per instance, so an answer is never shared between two clients
59
+ * holding different API keys and therefore entitled to different fields.
60
+ */
61
+ export declare class VPNDetection {
62
+ private readonly client;
63
+ private readonly cache;
64
+ private readonly store;
65
+ private readonly limit;
66
+ private readonly retries;
67
+ private readonly timeoutMs;
68
+ /**
69
+ * Sign a person in through their browser with the OAuth authorization code
70
+ * flow and PKCE. Needs no API key.
71
+ */
72
+ readonly oauth: OauthApi;
73
+ constructor(options?: Options);
74
+ /**
75
+ * Whether an address is private, loopback, link-local, documentation,
76
+ * multicast or otherwise not routable, including the IPv6 equivalents and
77
+ * the 6to4 and Teredo ranges.
78
+ *
79
+ * These are the addresses `lookup` answers locally. Exposed here so the
80
+ * check is reachable from the client you already hold; the same function is
81
+ * also importable on its own.
82
+ */
83
+ isBogon(ip: string): boolean;
84
+ /**
85
+ * Classify one address.
86
+ *
87
+ * A bogon is answered locally and never reaches the network. Everything
88
+ * else is served, then cached for this instance, and kept in the cache's
89
+ * `store` when it has one. Calls that miss the cache while a request for
90
+ * their address is in flight, a batch's included, await that request rather
91
+ * than sending their own, and take its answer, sent under the options of the
92
+ * call that led it. An IPv4-mapped address (`::ffff:8.8.8.8`) is the IPv4
93
+ * address it carries: judged, sent and cached as that, so the answer names
94
+ * `8.8.8.8`.
95
+ */
96
+ lookup(ip: string, options?: LookupOptions): Promise<Result>;
97
+ private answer;
98
+ private serve;
99
+ /**
100
+ * Classify the address this client is calling from: in a page, the visitor's
101
+ * own.
102
+ *
103
+ * The same answer `lookup` would give for that address, at the same cost
104
+ * against your allowance. The address is the one our edge observed, so a
105
+ * call made through a proxy or a VPN reports the exit it left through -
106
+ * usually the point of asking.
107
+ *
108
+ * Deliberately NOT cached. The cache is keyed by address, and which
109
+ * address this is IS the question: a device that moves between networks
110
+ * would otherwise be told where it used to be.
111
+ */
112
+ myIp(options?: LookupOptions): Promise<Result>;
113
+ /**
114
+ * What this client's key is entitled to, and how much of it has been used.
115
+ *
116
+ * Named for what it answers rather than `me`, which sits one letter from
117
+ * `myIp` and means something quite different: one is which address you are
118
+ * calling FROM, the other is what the key you are calling WITH may spend.
119
+ *
120
+ * Unlike a lookup there is no useful unauthenticated answer, so a client
121
+ * built without a key gets an unauthorized error rather than a partial one.
122
+ *
123
+ * Usage counts against the ALLOWANCE WINDOW - the anniversary of the
124
+ * subscription, not the calendar month and not the billing period - and it
125
+ * is the same number a lookup is gated on. It can lag by a few seconds,
126
+ * because requests are counted in memory and flushed in aggregate.
127
+ *
128
+ * Deliberately NOT cached: the whole point is what has been spent, and a
129
+ * cached answer is a wrong one within seconds of the next request.
130
+ */
131
+ myEntitlement(options?: LookupOptions): Promise<Entitlement>;
132
+ /**
133
+ * Classify many addresses in as few requests as possible.
134
+ *
135
+ * Bogons are answered locally, cached answers are reused, the cache's `store`
136
+ * is read for the rest, and an address with a request already in flight, a
137
+ * lookup's or another batch's, awaits that request; everything else goes to
138
+ * the batch endpoint in chunks of up to 1000 addresses, with at most
139
+ * `concurrency` chunks in flight, and a lookup arriving meanwhile awaits this
140
+ * batch's answer for its address. Keyed by address rather than positional, so
141
+ * duplicates in the input collapse to a single entry and the caller never has
142
+ * to line two lists up. An address that fails carries its error as its value,
143
+ * so one bad entry cannot lose the rest of the answers: the API reports a
144
+ * per-entry failure with the status the single lookup would have answered,
145
+ * and a chunk that fails as a whole marks every address in it. A per-call
146
+ * `concurrency` below 1 is refused as `bad_request` before anything is sent.
147
+ * An IPv4-mapped address is looked up as the IPv4 address it carries, and its
148
+ * answer keyed as you passed it.
149
+ */
150
+ lookupBatch(ips: Iterable<string>, options?: BatchOptions): Promise<Map<string, Result | VPNDetectionError>>;
151
+ private unstored;
152
+ private lookupChunk;
153
+ }
package/dist/client.js ADDED
@@ -0,0 +1,384 @@
1
+ import { LRUCache } from 'lru-cache';
2
+ import pLimit from 'p-limit';
3
+ import { createClient, createConfig } from './generated/client/index.js';
4
+ import { lookupBatch, lookupIp, lookupMyIp, myEntitlement } from './generated/sdk.gen.js';
5
+ import { bogonResult, isBogon, unmapped } from './bogon.js';
6
+ import { errorFromEntry, VPNDetectionError } from './errors.js';
7
+ import { OauthApi } from './oauth.js';
8
+ import { isBatch, isBatchError, isEntitlement, isLookup } from './shapes.js';
9
+ import { isCacheStore, storeScope, StoreTier } from './store.js';
10
+ import { asError, checkConcurrency, checkRetries, checkTimeout, deadline, readable, withRetry, } from './transport.js';
11
+ import { toResult } from './types.js';
12
+ export const DEFAULT_BASE_URL = 'https://api.vpndetection.io';
13
+ // fetch has no whole-request limit of its own, so without this a hung API would
14
+ // hold a caller for as long as the browser keeps the connection open.
15
+ const DEFAULT_TIMEOUT_MS = 30_000;
16
+ // The most addresses POST /batch takes in one call; a larger batch is sent in
17
+ // chunks of this size.
18
+ const BATCH_MAX = 1000;
19
+ /**
20
+ * A client for the VPNDetection API, for a browser: a page's own scripts, a web
21
+ * worker or an extension.
22
+ *
23
+ * The cache is per instance, so an answer is never shared between two clients
24
+ * holding different API keys and therefore entitled to different fields.
25
+ */
26
+ export class VPNDetection {
27
+ client;
28
+ // Keyed by address. The context is how a call sends the request when the
29
+ // address has none in flight: `fetch()` runs it synchronously, so a batch
30
+ // knows which addresses it leads before it builds a chunk.
31
+ cache;
32
+ store;
33
+ limit;
34
+ retries;
35
+ timeoutMs;
36
+ /**
37
+ * Sign a person in through their browser with the OAuth authorization code
38
+ * flow and PKCE. Needs no API key.
39
+ */
40
+ oauth;
41
+ constructor(options = {}) {
42
+ const apiKey = checkApiKey(options.apiKey);
43
+ // Every path appended starts with a slash, and a second one is another
44
+ // path, which the API answers with a redirect.
45
+ const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
46
+ this.client = createClient(createConfig({
47
+ baseUrl: baseUrl,
48
+ ...(apiKey === undefined ? {} : { auth: bearerOnly(apiKey) }),
49
+ // Looked up on each request rather than bound here, so a script that wraps
50
+ // the page's fetch after this client is built still sees its requests.
51
+ fetch: options.fetch ?? ((input, init) => globalThis.fetch(input, init)),
52
+ }));
53
+ this.retries = checkRetries(options.retries) ?? 2;
54
+ this.timeoutMs = checkTimeout(options.timeoutMs) ?? DEFAULT_TIMEOUT_MS;
55
+ this.limit = pLimit(checkConcurrency(options.concurrency) ?? 8);
56
+ const cache = options.cache === false ? null : (options.cache ?? {});
57
+ const ttlMs = cache?.ttlMs ?? 60 * 60 * 1000;
58
+ this.cache = cache === null ? null : new LRUCache({
59
+ max: cache.max ?? 10_000,
60
+ ttl: ttlMs,
61
+ // Concurrent misses for one address share one request: every
62
+ // `fetch()` while it is in flight gets the same promise, and a
63
+ // failure rejects them all and is cached for none.
64
+ fetchMethod: (_ip, _stale, { context }) => context(),
65
+ // An eviction must not fail the callers awaiting a request.
66
+ ignoreFetchAbort: true,
67
+ });
68
+ // `null` is no store, as it is no key.
69
+ const store = cache?.store ?? undefined;
70
+ if (store !== undefined && !isCacheStore(store)) {
71
+ throw new VPNDetectionError('bad_request', 'cache.store must have a get and a set function');
72
+ }
73
+ this.store = store === undefined ? null : new StoreTier(store, storeScope(baseUrl, apiKey), ttlMs);
74
+ this.oauth = new OauthApi(this.client, this.retries, this.timeoutMs);
75
+ }
76
+ /**
77
+ * Whether an address is private, loopback, link-local, documentation,
78
+ * multicast or otherwise not routable, including the IPv6 equivalents and
79
+ * the 6to4 and Teredo ranges.
80
+ *
81
+ * These are the addresses `lookup` answers locally. Exposed here so the
82
+ * check is reachable from the client you already hold; the same function is
83
+ * also importable on its own.
84
+ */
85
+ isBogon(ip) {
86
+ return isBogon(ip);
87
+ }
88
+ /**
89
+ * Classify one address.
90
+ *
91
+ * A bogon is answered locally and never reaches the network. Everything
92
+ * else is served, then cached for this instance, and kept in the cache's
93
+ * `store` when it has one. Calls that miss the cache while a request for
94
+ * their address is in flight, a batch's included, await that request rather
95
+ * than sending their own, and take its answer, sent under the options of the
96
+ * call that led it. An IPv4-mapped address (`::ffff:8.8.8.8`) is the IPv4
97
+ * address it carries: judged, sent and cached as that, so the answer names
98
+ * `8.8.8.8`.
99
+ */
100
+ async lookup(ip, options = {}) {
101
+ // First, or a bogon and a cached address would answer any value.
102
+ checkTimeout(options.timeoutMs);
103
+ checkRetries(options.retries);
104
+ const addr = unmapped(ip);
105
+ if (isBogon(addr)) {
106
+ return bogonResult(addr);
107
+ }
108
+ if (this.cache === null) {
109
+ return this.serve(addr, options);
110
+ }
111
+ return (await this.cache.fetch(addr, { context: () => this.answer(addr, options) }));
112
+ }
113
+ // A miss in memory: the store's answer if it holds one, else the API's, kept.
114
+ async answer(ip, options) {
115
+ const stored = await this.store?.get(ip);
116
+ if (stored !== undefined) {
117
+ return stored;
118
+ }
119
+ const served = await this.serve(ip, options);
120
+ await this.store?.set(ip, served);
121
+ return served;
122
+ }
123
+ async serve(ip, options) {
124
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
125
+ return withRetry(options.retries ?? this.retries, async () => {
126
+ const res = await deadline(timeoutMs, (signal) => lookupIp({
127
+ client: this.client, path: { ip: ip }, signal: signal,
128
+ }));
129
+ return toResult(readable(res, isLookup));
130
+ });
131
+ }
132
+ /**
133
+ * Classify the address this client is calling from: in a page, the visitor's
134
+ * own.
135
+ *
136
+ * The same answer `lookup` would give for that address, at the same cost
137
+ * against your allowance. The address is the one our edge observed, so a
138
+ * call made through a proxy or a VPN reports the exit it left through -
139
+ * usually the point of asking.
140
+ *
141
+ * Deliberately NOT cached. The cache is keyed by address, and which
142
+ * address this is IS the question: a device that moves between networks
143
+ * would otherwise be told where it used to be.
144
+ */
145
+ async myIp(options = {}) {
146
+ const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
147
+ return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
148
+ const res = await deadline(timeoutMs, (signal) => lookupMyIp({
149
+ client: this.client, signal: signal,
150
+ }));
151
+ return toResult(readable(res, isLookup));
152
+ });
153
+ }
154
+ /**
155
+ * What this client's key is entitled to, and how much of it has been used.
156
+ *
157
+ * Named for what it answers rather than `me`, which sits one letter from
158
+ * `myIp` and means something quite different: one is which address you are
159
+ * calling FROM, the other is what the key you are calling WITH may spend.
160
+ *
161
+ * Unlike a lookup there is no useful unauthenticated answer, so a client
162
+ * built without a key gets an unauthorized error rather than a partial one.
163
+ *
164
+ * Usage counts against the ALLOWANCE WINDOW - the anniversary of the
165
+ * subscription, not the calendar month and not the billing period - and it
166
+ * is the same number a lookup is gated on. It can lag by a few seconds,
167
+ * because requests are counted in memory and flushed in aggregate.
168
+ *
169
+ * Deliberately NOT cached: the whole point is what has been spent, and a
170
+ * cached answer is a wrong one within seconds of the next request.
171
+ */
172
+ async myEntitlement(options = {}) {
173
+ const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
174
+ return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
175
+ const res = await deadline(timeoutMs, (signal) => myEntitlement({
176
+ client: this.client, signal: signal,
177
+ }));
178
+ return readable(res, isEntitlement);
179
+ });
180
+ }
181
+ /**
182
+ * Classify many addresses in as few requests as possible.
183
+ *
184
+ * Bogons are answered locally, cached answers are reused, the cache's `store`
185
+ * is read for the rest, and an address with a request already in flight, a
186
+ * lookup's or another batch's, awaits that request; everything else goes to
187
+ * the batch endpoint in chunks of up to 1000 addresses, with at most
188
+ * `concurrency` chunks in flight, and a lookup arriving meanwhile awaits this
189
+ * batch's answer for its address. Keyed by address rather than positional, so
190
+ * duplicates in the input collapse to a single entry and the caller never has
191
+ * to line two lists up. An address that fails carries its error as its value,
192
+ * so one bad entry cannot lose the rest of the answers: the API reports a
193
+ * per-entry failure with the status the single lookup would have answered,
194
+ * and a chunk that fails as a whole marks every address in it. A per-call
195
+ * `concurrency` below 1 is refused as `bad_request` before anything is sent.
196
+ * An IPv4-mapped address is looked up as the IPv4 address it carries, and its
197
+ * answer keyed as you passed it.
198
+ */
199
+ async lookupBatch(ips, options = {}) {
200
+ const concurrency = checkConcurrency(options.concurrency);
201
+ checkTimeout(options.timeoutMs);
202
+ checkRetries(options.retries);
203
+ const asked = [...new Set(ips)];
204
+ const unique = [...new Set(asked.map(unmapped))];
205
+ const out = new Map();
206
+ const pending = [];
207
+ // Every address that is neither a bogon nor cached goes through
208
+ // `fetch()` in one synchronous pass: one with a request in flight joins
209
+ // it, and for the rest `fetchMethod` runs at once, which is how this
210
+ // batch learns the addresses it leads before building any chunk.
211
+ const shared = [];
212
+ const led = new Map();
213
+ for (const ip of unique) {
214
+ if (isBogon(ip)) {
215
+ out.set(ip, bogonResult(ip));
216
+ continue;
217
+ }
218
+ const hit = this.cache?.get(ip);
219
+ if (hit !== undefined) {
220
+ out.set(ip, hit);
221
+ continue;
222
+ }
223
+ if (this.cache === null) {
224
+ pending.push(ip);
225
+ continue;
226
+ }
227
+ shared.push([ip, this.cache.fetch(ip, {
228
+ context: () => {
229
+ const landing = deferred();
230
+ led.set(ip, landing);
231
+ pending.push(ip);
232
+ return landing.promise;
233
+ },
234
+ })]);
235
+ }
236
+ const sending = this.store === null ? pending : await this.unstored(pending, led);
237
+ // A per-call concurrency gets its own limiter; without one the call
238
+ // would share the instance's budget and silently ignore the override.
239
+ const limit = concurrency === undefined ? this.limit : pLimit(concurrency);
240
+ const chunks = [];
241
+ for (let i = 0; i < sending.length; i += BATCH_MAX) {
242
+ chunks.push(sending.slice(i, i + BATCH_MAX));
243
+ }
244
+ await Promise.all([
245
+ ...chunks.map((chunk) => limit(async () => {
246
+ const kept = [];
247
+ for (const [ip, answer] of await this.lookupChunk(chunk, options)) {
248
+ const landing = led.get(ip);
249
+ if (landing === undefined) {
250
+ out.set(ip, answer);
251
+ }
252
+ else if (answer instanceof VPNDetectionError) {
253
+ landing.reject(answer);
254
+ }
255
+ else {
256
+ landing.resolve(answer);
257
+ }
258
+ if (this.store !== null && !(answer instanceof VPNDetectionError)) {
259
+ kept.push(this.store.set(ip, answer));
260
+ }
261
+ }
262
+ await Promise.all(kept);
263
+ })),
264
+ ...shared.map(async ([ip, answer]) => {
265
+ try {
266
+ out.set(ip, (await answer));
267
+ }
268
+ catch (err) {
269
+ out.set(ip, asError(err));
270
+ }
271
+ }),
272
+ ]);
273
+ // Reinstated in input order, under the addresses as passed: chunks
274
+ // settle in completion order, and a caller iterating the map should see
275
+ // what they passed in.
276
+ return new Map(asked.map((ip) => [ip, out.get(unmapped(ip))]));
277
+ }
278
+ // The addresses this batch leads that the store does not hold, in the order
279
+ // given. One the store holds lands at once, as a request's answer would.
280
+ async unstored(ips, led) {
281
+ const stored = await Promise.all(ips.map((ip) => this.store.get(ip)));
282
+ return ips.filter((ip, i) => {
283
+ const hit = stored[i];
284
+ if (hit === undefined) {
285
+ return true;
286
+ }
287
+ led.get(ip).resolve(hit);
288
+ return false;
289
+ });
290
+ }
291
+ // One POST /batch, mapped back onto the addresses it was asked about. A
292
+ // chunk-level failure - the call refused, the transport failing, the
293
+ // retries exhausted - becomes every address's error, exactly as it would
294
+ // have been had each been looked up alone.
295
+ async lookupChunk(chunk, options) {
296
+ const out = new Map();
297
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
298
+ let body;
299
+ try {
300
+ body = await withRetry(options.retries ?? this.retries, async () => {
301
+ const res = await deadline(timeoutMs, (signal) => lookupBatch({
302
+ client: this.client, body: { ips: chunk }, signal: signal,
303
+ }));
304
+ return readable(res, isBatch);
305
+ });
306
+ }
307
+ catch (err) {
308
+ const failure = asError(err);
309
+ for (const ip of chunk) {
310
+ out.set(ip, failure);
311
+ }
312
+ return out;
313
+ }
314
+ // An entry is judged alone: one the client cannot read is that address's
315
+ // error, and the rest of the chunk keeps its answers. Each map is read by
316
+ // its own keys alone, so an address spelled `__proto__`, `constructor` or
317
+ // `toString` never reads the object's prototype as an answer.
318
+ for (const ip of chunk) {
319
+ const served = Object.hasOwn(body.results, ip) ? body.results[ip] : undefined;
320
+ if (served !== undefined) {
321
+ out.set(ip, isLookup(served) ? toResult(served) : unreadableEntry(ip));
322
+ continue;
323
+ }
324
+ const failed = Object.hasOwn(body.errors, ip) ? body.errors[ip] : undefined;
325
+ if (failed !== undefined) {
326
+ out.set(ip, isBatchError(failed) ? errorFromEntry(failed) : unreadableEntry(ip));
327
+ continue;
328
+ }
329
+ out.set(ip, new VPNDetectionError('server_error', `the batch answer did not include ${ip}`, 200));
330
+ }
331
+ return out;
332
+ }
333
+ }
334
+ // Promise.withResolvers by hand: it is newer than the browsers this library supports.
335
+ function deferred() {
336
+ let resolve;
337
+ let reject;
338
+ const promise = new Promise((res, rej) => {
339
+ resolve = res;
340
+ reject = rej;
341
+ });
342
+ return { promise: promise, resolve: resolve, reject: reject };
343
+ }
344
+ /**
345
+ * The key without the blanks around it, and no key at all for blanks alone,
346
+ * which would go out as `Authorization: Bearer`. A control character inside it
347
+ * is refused here, since fetch refuses such a header and every call would fail
348
+ * with nothing sent. `null` is no key.
349
+ */
350
+ function checkApiKey(apiKey) {
351
+ if (apiKey === undefined || apiKey === null) {
352
+ return undefined;
353
+ }
354
+ if (typeof apiKey !== 'string') {
355
+ throw new VPNDetectionError('bad_request', `apiKey must be a string, got ${typeof apiKey}`);
356
+ }
357
+ const key = apiKey.trim();
358
+ if (/[\u0000-\u001f\u007f]/.test(key)) {
359
+ throw new VPNDetectionError('bad_request', 'apiKey must not contain a control character');
360
+ }
361
+ // fetch sends a header as Latin-1 and refuses anything past it.
362
+ if (/[^\u0000-\u00ff]/.test(key)) {
363
+ throw new VPNDetectionError('bad_request', 'apiKey must not contain a character past U+00FF');
364
+ }
365
+ return key === '' ? undefined : key;
366
+ }
367
+ function unreadableEntry(ip) {
368
+ return new VPNDetectionError('server_error', `unreadable batch answer for ${ip}, status 200`, 200);
369
+ }
370
+ /**
371
+ * Sends the key in the `Authorization` header and nowhere else.
372
+ *
373
+ * The API accepts three credential forms and the spec documents all three, so
374
+ * the generator applies EVERY one of them - putting the key in the query string
375
+ * of every request alongside the headers. A query string is the one place a
376
+ * secret should never be: it lands in access logs, proxy logs and browser
377
+ * history, none of which we control.
378
+ *
379
+ * Returning undefined for the other schemes is what suppresses them; the
380
+ * generated `getAuthToken` drops a scheme whose callback yields nothing.
381
+ */
382
+ function bearerOnly(apiKey) {
383
+ return (auth) => (auth.scheme === 'bearer' ? apiKey : undefined);
384
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Why a request failed.
3
+ *
4
+ * `rate_limited` and `quota_exceeded` both arrive as HTTP 429 and are NOT the
5
+ * same thing. A rate limit is the API protecting itself and carries
6
+ * `Retry-After`; retrying works. A spent quota carries no such header and
7
+ * retrying will not help until the window rolls over or the limit is raised.
8
+ * The header is the only thing that distinguishes them.
9
+ */
10
+ export type ErrorKind = 'bad_request' | 'unauthorized' | 'forbidden' | 'rate_limited' | 'quota_exceeded' | 'server_error' | 'network';
11
+ export declare class VPNDetectionError extends Error {
12
+ readonly kind: ErrorKind;
13
+ readonly status?: number;
14
+ readonly retryAfterSeconds?: number;
15
+ constructor(kind: ErrorKind, message: string, status?: number, retryAfterSeconds?: number);
16
+ /** Whether retrying this exact request could succeed. */
17
+ get retryable(): boolean;
18
+ }
19
+ /**
20
+ * The authorization server refusing an OAuth request: a 4xx whose body names an
21
+ * OAuth error code. Never retryable as it stands.
22
+ *
23
+ * `kind` follows the status like any other failure's. A 401 here means the
24
+ * client ID is not registered, never the API key, which OAuth requests do not
25
+ * carry. The two codes a sign-in ends on have their own subclasses.
26
+ */
27
+ export declare class OauthError extends VPNDetectionError {
28
+ /** The server's code, such as `invalid_grant` or `invalid_client`, kept as sent. */
29
+ readonly errorCode: string;
30
+ /** The server's explanation, when it sent one. */
31
+ readonly errorDescription?: string;
32
+ constructor(errorCode: string, errorDescription?: string, status?: number);
33
+ get retryable(): boolean;
34
+ }
35
+ /** The person refused the sign-in, so a new attempt starts over. */
36
+ export declare class OauthAccessDeniedError extends OauthError {
37
+ constructor(errorDescription?: string, status?: number);
38
+ }
39
+ /** What was presented is no longer valid: it expired, or was already used or refused. */
40
+ export declare class OauthExpiredTokenError extends OauthError {
41
+ constructor(errorDescription?: string, status?: number);
42
+ }
43
+ export declare function oauthErrorFrom(errorCode: string, errorDescription: string | undefined, status: number): OauthError;
44
+ export declare function errorFromResponse(status: number, headers: {
45
+ get(name: string): string | null;
46
+ }, body: unknown): VPNDetectionError;
47
+ /**
48
+ * A per-entry failure inside a successful batch: the status the single lookup
49
+ * would have answered, and its message, with no headers at all - so a 429 here
50
+ * is a spent allowance, which is the only kind the API puts in an entry.
51
+ */
52
+ export declare function errorFromEntry(entry: {
53
+ status: number;
54
+ error: string;
55
+ }): VPNDetectionError;