internetdata-web 0.0.0-stage → 1.1.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.
- package/LICENSE +21 -0
- package/README.md +282 -2
- package/dist/bogon.d.ts +31 -0
- package/dist/bogon.js +214 -0
- package/dist/bogons.gen.d.ts +2 -0
- package/dist/bogons.gen.js +87 -0
- package/dist/client.d.ts +183 -0
- package/dist/client.js +446 -0
- package/dist/errors.d.ts +66 -0
- package/dist/errors.js +185 -0
- package/dist/generated/client/client.gen.d.ts +2 -0
- package/dist/generated/client/client.gen.js +216 -0
- package/dist/generated/client/index.d.ts +10 -0
- package/dist/generated/client/index.js +6 -0
- package/dist/generated/client/types.gen.d.ts +120 -0
- package/dist/generated/client/types.gen.js +2 -0
- package/dist/generated/client/utils.gen.d.ts +37 -0
- package/dist/generated/client/utils.gen.js +228 -0
- package/dist/generated/client.gen.d.ts +12 -0
- package/dist/generated/client.gen.js +3 -0
- package/dist/generated/core/auth.gen.d.ts +25 -0
- package/dist/generated/core/auth.gen.js +14 -0
- package/dist/generated/core/bodySerializer.gen.d.ts +25 -0
- package/dist/generated/core/bodySerializer.gen.js +57 -0
- package/dist/generated/core/params.gen.d.ts +43 -0
- package/dist/generated/core/params.gen.js +109 -0
- package/dist/generated/core/pathSerializer.gen.d.ts +33 -0
- package/dist/generated/core/pathSerializer.gen.js +106 -0
- package/dist/generated/core/queryKeySerializer.gen.d.ts +18 -0
- package/dist/generated/core/queryKeySerializer.gen.js +92 -0
- package/dist/generated/core/serverSentEvents.gen.d.ts +71 -0
- package/dist/generated/core/serverSentEvents.gen.js +132 -0
- package/dist/generated/core/types.gen.d.ts +83 -0
- package/dist/generated/core/types.gen.js +2 -0
- package/dist/generated/core/utils.gen.d.ts +19 -0
- package/dist/generated/core/utils.gen.js +87 -0
- package/dist/generated/index.d.ts +2 -0
- package/dist/generated/index.js +2 -0
- package/dist/generated/sdk.gen.d.ts +117 -0
- package/dist/generated/sdk.gen.js +251 -0
- package/dist/generated/types.gen.d.ts +1527 -0
- package/dist/generated/types.gen.js +2 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +4 -0
- package/dist/oauth.d.ts +119 -0
- package/dist/oauth.js +247 -0
- package/dist/shapes.d.ts +68 -0
- package/dist/shapes.js +284 -0
- package/dist/store.d.ts +39 -0
- package/dist/store.js +64 -0
- package/dist/transport.d.ts +51 -0
- package/dist/transport.js +147 -0
- package/dist/types.d.ts +115 -0
- package/dist/types.js +46 -0
- package/package.json +65 -3
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import type { Entitlement } from './generated/types.gen.js';
|
|
2
|
+
import { InternetDataError } from './errors.js';
|
|
3
|
+
import { OauthApi } from './oauth.js';
|
|
4
|
+
import { type CacheStore } from './store.js';
|
|
5
|
+
import { type AsnResult, type DomainResult, type Result } from './types.js';
|
|
6
|
+
export declare const DEFAULT_BASE_URL = "https://api.internetdata.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. Without one a lookup is on Unlimited, the free plan, limited
|
|
22
|
+
* per address per minute, and no `Authorization` header is sent at all. A
|
|
23
|
+
* batch needs a key on a paid plan.
|
|
24
|
+
* A key in a web page is readable by anyone who opens the page.
|
|
25
|
+
*/
|
|
26
|
+
apiKey?: string;
|
|
27
|
+
/**
|
|
28
|
+
* Default `https://api.internetdata.io`. The `oauth` calls go to the apex
|
|
29
|
+
* this names: `api.` dropped, and `api-<env>.` read as `<env>.`.
|
|
30
|
+
*/
|
|
31
|
+
baseUrl?: string;
|
|
32
|
+
/** Pass `false` to disable caching. */
|
|
33
|
+
cache?: CacheOptions | false;
|
|
34
|
+
/** Concurrent batch requests - chunks of up to 1000 addresses - during a batch. Default 8. */
|
|
35
|
+
concurrency?: number;
|
|
36
|
+
/** Retry attempts for a transient failure, a whole number from 0. Default 2. */
|
|
37
|
+
retries?: number;
|
|
38
|
+
/**
|
|
39
|
+
* How long one request may take before it is abandoned, in milliseconds.
|
|
40
|
+
* Default 30000. Applies per attempt, so a retried call may take longer in
|
|
41
|
+
* total.
|
|
42
|
+
*/
|
|
43
|
+
timeoutMs?: number;
|
|
44
|
+
/** Override the HTTP implementation, mostly for tests. Defaults to the global `fetch`. */
|
|
45
|
+
fetch?: typeof globalThis.fetch;
|
|
46
|
+
}
|
|
47
|
+
/** Per-call overrides for a single lookup. Anything omitted falls back to the client's setting. */
|
|
48
|
+
export interface LookupOptions {
|
|
49
|
+
/** Retry attempts for a transient failure, a whole number from 0. */
|
|
50
|
+
retries?: number;
|
|
51
|
+
/** How long one attempt may take before it is abandoned, in milliseconds. */
|
|
52
|
+
timeoutMs?: number;
|
|
53
|
+
}
|
|
54
|
+
/** Per-call overrides for one batch. Anything omitted falls back to the client's setting. */
|
|
55
|
+
export interface BatchOptions extends LookupOptions {
|
|
56
|
+
/** Concurrent batch requests for THIS batch only. */
|
|
57
|
+
concurrency?: number;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* A client for the InternetData API, for a browser: a page's own scripts, a web
|
|
61
|
+
* worker or an extension.
|
|
62
|
+
*
|
|
63
|
+
* The cache is per instance, so an answer is never shared between two clients
|
|
64
|
+
* holding different API keys and therefore entitled to different fields.
|
|
65
|
+
*/
|
|
66
|
+
export declare class InternetData {
|
|
67
|
+
private readonly client;
|
|
68
|
+
private readonly cache;
|
|
69
|
+
private readonly store;
|
|
70
|
+
private readonly limit;
|
|
71
|
+
private readonly retries;
|
|
72
|
+
private readonly timeoutMs;
|
|
73
|
+
/**
|
|
74
|
+
* Sign a person in through their browser with the OAuth authorization code
|
|
75
|
+
* flow and PKCE, at the apex of the base URL. Needs no API key.
|
|
76
|
+
*/
|
|
77
|
+
readonly oauth: OauthApi;
|
|
78
|
+
constructor(options?: Options);
|
|
79
|
+
/**
|
|
80
|
+
* Whether an address is private, loopback, link-local, documentation,
|
|
81
|
+
* multicast or otherwise not routable, including the IPv6 equivalents and
|
|
82
|
+
* the 6to4 and Teredo ranges.
|
|
83
|
+
*
|
|
84
|
+
* These are the addresses `lookup` answers locally. Exposed here so the
|
|
85
|
+
* check is reachable from the client you already hold; the same function is
|
|
86
|
+
* also importable on its own.
|
|
87
|
+
*/
|
|
88
|
+
isBogon(ip: string): boolean;
|
|
89
|
+
/**
|
|
90
|
+
* What every database says about one address.
|
|
91
|
+
*
|
|
92
|
+
* A bogon is answered locally and never reaches the network. Everything
|
|
93
|
+
* else is served, then cached for this instance, and kept in the cache's
|
|
94
|
+
* `store` when it has one. Calls that miss the cache while a request for
|
|
95
|
+
* their address is in flight, a batch's included, await that request rather
|
|
96
|
+
* than sending their own, and take its answer, sent under the options of the
|
|
97
|
+
* call that led it. An IPv4-mapped address (`::ffff:8.8.8.8`) is the IPv4
|
|
98
|
+
* address it carries: judged, sent and cached as that, so the answer names
|
|
99
|
+
* `8.8.8.8`. Anything that is not an IP address is refused as `bad_request`
|
|
100
|
+
* before it is sent: an AS is `lookupAsn`'s, and a domain `lookupDomain`'s.
|
|
101
|
+
*/
|
|
102
|
+
lookup(ip: string, options?: LookupOptions): Promise<Result>;
|
|
103
|
+
private answer;
|
|
104
|
+
private serve;
|
|
105
|
+
/**
|
|
106
|
+
* What the databases say about the address this client is calling from: in a
|
|
107
|
+
* page, the visitor's own.
|
|
108
|
+
*
|
|
109
|
+
* The same answer `lookup` would give for that address, at the same cost
|
|
110
|
+
* against your allowance. The address is the one our edge observed, so a
|
|
111
|
+
* call made through a proxy or a VPN reports the exit it left through -
|
|
112
|
+
* usually the point of asking.
|
|
113
|
+
*
|
|
114
|
+
* Deliberately NOT cached. The cache is keyed by address, and which
|
|
115
|
+
* address this is IS the question: a device that moves between networks
|
|
116
|
+
* would otherwise be told where it used to be.
|
|
117
|
+
*/
|
|
118
|
+
myIp(options?: LookupOptions): Promise<Result>;
|
|
119
|
+
/**
|
|
120
|
+
* What InternetData knows about one autonomous system, by its number: its
|
|
121
|
+
* registration on every plan, and on a paid one its ASN Whois record and
|
|
122
|
+
* every prefix it announces.
|
|
123
|
+
*
|
|
124
|
+
* Sent as given and not cached. The API refuses a number it cannot read as
|
|
125
|
+
* `bad_request`.
|
|
126
|
+
*/
|
|
127
|
+
lookupAsn(asn: number, options?: LookupOptions): Promise<AsnResult>;
|
|
128
|
+
/**
|
|
129
|
+
* What InternetData knows about one domain: on every plan whether it is
|
|
130
|
+
* registered and which DNS record types it has, and on a paid one the
|
|
131
|
+
* records themselves, its organization's IP ranges and whether it is a
|
|
132
|
+
* disposable email domain.
|
|
133
|
+
*
|
|
134
|
+
* Sent as given and not cached. The API refuses a name it cannot read as
|
|
135
|
+
* `bad_request`.
|
|
136
|
+
*/
|
|
137
|
+
lookupDomain(domain: string, options?: LookupOptions): Promise<DomainResult>;
|
|
138
|
+
/**
|
|
139
|
+
* What this client's key is entitled to, and how much of it has been used.
|
|
140
|
+
*
|
|
141
|
+
* Named for what it answers rather than `me`, which sits one letter from
|
|
142
|
+
* `myIp` and means something quite different: one is which address you are
|
|
143
|
+
* calling FROM, the other is what the key you are calling WITH may spend.
|
|
144
|
+
*
|
|
145
|
+
* Unlike a lookup there is no useful unauthenticated answer, so a client
|
|
146
|
+
* built without a key gets an unauthorized error rather than a partial one.
|
|
147
|
+
*
|
|
148
|
+
* Usage counts against the ALLOWANCE WINDOW - on a paid plan the
|
|
149
|
+
* anniversary of the subscription, not the calendar month and not the
|
|
150
|
+
* billing period, and on the free plan the UTC day - and it is the same
|
|
151
|
+
* number a lookup is gated on. It can lag by a few seconds, because
|
|
152
|
+
* requests are counted in memory and flushed in aggregate.
|
|
153
|
+
*
|
|
154
|
+
* Deliberately NOT cached: the whole point is what has been spent, and a
|
|
155
|
+
* cached answer is a wrong one within seconds of the next request.
|
|
156
|
+
*/
|
|
157
|
+
myEntitlement(options?: LookupOptions): Promise<Entitlement>;
|
|
158
|
+
/**
|
|
159
|
+
* Look many addresses up in as few requests as possible.
|
|
160
|
+
*
|
|
161
|
+
* Bogons are answered locally, cached answers are reused, the cache's `store`
|
|
162
|
+
* is read for the rest, and an address with a request already in flight, a
|
|
163
|
+
* lookup's or another batch's, awaits that request; everything else goes to
|
|
164
|
+
* the batch endpoint in chunks of up to 1000 addresses, with at most
|
|
165
|
+
* `concurrency` chunks in flight, and a lookup arriving meanwhile awaits this
|
|
166
|
+
* batch's answer for its address. Keyed by address rather than positional, so
|
|
167
|
+
* duplicates in the input collapse to a single entry and the caller never has
|
|
168
|
+
* to line two lists up. An address that fails carries its error as its value,
|
|
169
|
+
* so one bad entry cannot lose the rest of the answers: the API reports a
|
|
170
|
+
* per-entry failure with the status the single lookup would have answered,
|
|
171
|
+
* and a chunk that fails as a whole marks every address in it. A per-call
|
|
172
|
+
* `concurrency` below 1 is refused as `bad_request` before anything is sent.
|
|
173
|
+
* An IPv4-mapped address is looked up as the IPv4 address it carries, and its
|
|
174
|
+
* answer keyed as you passed it. The batch endpoint needs a paid plan:
|
|
175
|
+
* without a key every address in a request of two or more carries an
|
|
176
|
+
* `unauthorized` error, and a free-plan key's request of two or more a
|
|
177
|
+
* `bad_request` (HTTP 402). A request of one address is answered as its
|
|
178
|
+
* lookup would be.
|
|
179
|
+
*/
|
|
180
|
+
lookupBatch(ips: Iterable<string>, options?: BatchOptions): Promise<Map<string, Result | InternetDataError>>;
|
|
181
|
+
private unstored;
|
|
182
|
+
private lookupChunk;
|
|
183
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
import { LRUCache } from 'lru-cache';
|
|
2
|
+
import pLimit from 'p-limit';
|
|
3
|
+
import { createClient, createConfig } from './generated/client/index.js';
|
|
4
|
+
import { lookupAsn, lookupBatch, lookupDomain, lookupIp, lookupMyIp, myEntitlement, } from './generated/sdk.gen.js';
|
|
5
|
+
import { bogonResult, isAddress, isBogon, unmapped } from './bogon.js';
|
|
6
|
+
import { errorFromEntry, InternetDataError } from './errors.js';
|
|
7
|
+
import { OauthApi } from './oauth.js';
|
|
8
|
+
import { isAsnLookup, isBatch, isBatchError, isDomainLookup, 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 { toAsnResult, toDomainResult, toResult, } from './types.js';
|
|
12
|
+
export const DEFAULT_BASE_URL = 'https://api.internetdata.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 InternetData 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 InternetData {
|
|
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, at the apex of the base URL. 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
|
+
// Looked up on each request rather than bound here, so a script that wraps
|
|
47
|
+
// the page's fetch after this client is built still sees its requests.
|
|
48
|
+
const fetchImpl = options.fetch
|
|
49
|
+
?? ((input, init) => globalThis.fetch(input, init));
|
|
50
|
+
this.client = createClient(createConfig({
|
|
51
|
+
baseUrl: baseUrl,
|
|
52
|
+
...(apiKey === undefined ? {} : { auth: bearerOnly(apiKey) }),
|
|
53
|
+
fetch: fetchImpl,
|
|
54
|
+
}));
|
|
55
|
+
this.retries = checkRetries(options.retries) ?? 2;
|
|
56
|
+
this.timeoutMs = checkTimeout(options.timeoutMs) ?? DEFAULT_TIMEOUT_MS;
|
|
57
|
+
this.limit = pLimit(checkConcurrency(options.concurrency) ?? 8);
|
|
58
|
+
const cache = options.cache === false ? null : (options.cache ?? {});
|
|
59
|
+
const ttlMs = cache?.ttlMs ?? 60 * 60 * 1000;
|
|
60
|
+
this.cache = cache === null ? null : new LRUCache({
|
|
61
|
+
max: cache.max ?? 10_000,
|
|
62
|
+
ttl: ttlMs,
|
|
63
|
+
// Concurrent misses for one address share one request: every
|
|
64
|
+
// `fetch()` while it is in flight gets the same promise, and a
|
|
65
|
+
// failure rejects them all and is cached for none.
|
|
66
|
+
fetchMethod: (_ip, _stale, { context }) => context(),
|
|
67
|
+
// An eviction must not fail the callers awaiting a request.
|
|
68
|
+
ignoreFetchAbort: true,
|
|
69
|
+
});
|
|
70
|
+
// `null` is no store, as it is no key.
|
|
71
|
+
const store = cache?.store ?? undefined;
|
|
72
|
+
if (store !== undefined && !isCacheStore(store)) {
|
|
73
|
+
throw new InternetDataError('bad_request', 'cache.store must have a get and a set function');
|
|
74
|
+
}
|
|
75
|
+
this.store = store === undefined ? null : new StoreTier(store, storeScope(baseUrl, apiKey), ttlMs);
|
|
76
|
+
// The authorization server is the apex, not the API host, and its
|
|
77
|
+
// requests carry no credential at all.
|
|
78
|
+
const authServer = createClient(createConfig({ baseUrl: apexOf(baseUrl), fetch: fetchImpl }));
|
|
79
|
+
this.oauth = new OauthApi(authServer, this.retries, this.timeoutMs);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Whether an address is private, loopback, link-local, documentation,
|
|
83
|
+
* multicast or otherwise not routable, including the IPv6 equivalents and
|
|
84
|
+
* the 6to4 and Teredo ranges.
|
|
85
|
+
*
|
|
86
|
+
* These are the addresses `lookup` answers locally. Exposed here so the
|
|
87
|
+
* check is reachable from the client you already hold; the same function is
|
|
88
|
+
* also importable on its own.
|
|
89
|
+
*/
|
|
90
|
+
isBogon(ip) {
|
|
91
|
+
return isBogon(ip);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* What every database says about one address.
|
|
95
|
+
*
|
|
96
|
+
* A bogon is answered locally and never reaches the network. Everything
|
|
97
|
+
* else is served, then cached for this instance, and kept in the cache's
|
|
98
|
+
* `store` when it has one. Calls that miss the cache while a request for
|
|
99
|
+
* their address is in flight, a batch's included, await that request rather
|
|
100
|
+
* than sending their own, and take its answer, sent under the options of the
|
|
101
|
+
* call that led it. An IPv4-mapped address (`::ffff:8.8.8.8`) is the IPv4
|
|
102
|
+
* address it carries: judged, sent and cached as that, so the answer names
|
|
103
|
+
* `8.8.8.8`. Anything that is not an IP address is refused as `bad_request`
|
|
104
|
+
* before it is sent: an AS is `lookupAsn`'s, and a domain `lookupDomain`'s.
|
|
105
|
+
*/
|
|
106
|
+
async lookup(ip, options = {}) {
|
|
107
|
+
// First, or a bogon and a cached address would answer any value.
|
|
108
|
+
checkTimeout(options.timeoutMs);
|
|
109
|
+
checkRetries(options.retries);
|
|
110
|
+
// The API answers an AS or a domain at this path too, in a shape this
|
|
111
|
+
// call cannot read, so one sent here would fail as three retried server errors.
|
|
112
|
+
if (typeof ip !== 'string' || !isAddress(unmapped(ip))) {
|
|
113
|
+
throw new InternetDataError('bad_request', `'${String(ip)}' is not an IP address: `
|
|
114
|
+
+ 'look up an AS with lookupAsn, and a domain with lookupDomain');
|
|
115
|
+
}
|
|
116
|
+
const addr = unmapped(ip);
|
|
117
|
+
if (isBogon(addr)) {
|
|
118
|
+
return bogonResult(addr);
|
|
119
|
+
}
|
|
120
|
+
if (this.cache === null) {
|
|
121
|
+
return this.serve(addr, options);
|
|
122
|
+
}
|
|
123
|
+
return (await this.cache.fetch(addr, { context: () => this.answer(addr, options) }));
|
|
124
|
+
}
|
|
125
|
+
// A miss in memory: the store's answer if it holds one, else the API's, kept.
|
|
126
|
+
async answer(ip, options) {
|
|
127
|
+
const stored = await this.store?.get(ip);
|
|
128
|
+
if (stored !== undefined) {
|
|
129
|
+
return stored;
|
|
130
|
+
}
|
|
131
|
+
const served = await this.serve(ip, options);
|
|
132
|
+
await this.store?.set(ip, served);
|
|
133
|
+
return served;
|
|
134
|
+
}
|
|
135
|
+
async serve(ip, options) {
|
|
136
|
+
const timeoutMs = options.timeoutMs ?? this.timeoutMs;
|
|
137
|
+
return withRetry(options.retries ?? this.retries, async () => {
|
|
138
|
+
const res = await deadline(timeoutMs, (signal) => lookupIp({
|
|
139
|
+
client: this.client, path: { ip: ip }, signal: signal,
|
|
140
|
+
}));
|
|
141
|
+
return toResult(readable(res, isLookup));
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* What the databases say about the address this client is calling from: in a
|
|
146
|
+
* page, the visitor's own.
|
|
147
|
+
*
|
|
148
|
+
* The same answer `lookup` would give for that address, at the same cost
|
|
149
|
+
* against your allowance. The address is the one our edge observed, so a
|
|
150
|
+
* call made through a proxy or a VPN reports the exit it left through -
|
|
151
|
+
* usually the point of asking.
|
|
152
|
+
*
|
|
153
|
+
* Deliberately NOT cached. The cache is keyed by address, and which
|
|
154
|
+
* address this is IS the question: a device that moves between networks
|
|
155
|
+
* would otherwise be told where it used to be.
|
|
156
|
+
*/
|
|
157
|
+
async myIp(options = {}) {
|
|
158
|
+
const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
|
|
159
|
+
return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
|
|
160
|
+
const res = await deadline(timeoutMs, (signal) => lookupMyIp({
|
|
161
|
+
client: this.client, signal: signal,
|
|
162
|
+
}));
|
|
163
|
+
return toResult(readable(res, isLookup));
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* What InternetData knows about one autonomous system, by its number: its
|
|
168
|
+
* registration on every plan, and on a paid one its ASN Whois record and
|
|
169
|
+
* every prefix it announces.
|
|
170
|
+
*
|
|
171
|
+
* Sent as given and not cached. The API refuses a number it cannot read as
|
|
172
|
+
* `bad_request`.
|
|
173
|
+
*/
|
|
174
|
+
async lookupAsn(asn, options = {}) {
|
|
175
|
+
const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
|
|
176
|
+
return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
|
|
177
|
+
const res = await deadline(timeoutMs, (signal) => lookupAsn({
|
|
178
|
+
client: this.client, path: { asn: String(asn) }, signal: signal,
|
|
179
|
+
}));
|
|
180
|
+
return toAsnResult(readable(res, isAsnLookup));
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* What InternetData knows about one domain: on every plan whether it is
|
|
185
|
+
* registered and which DNS record types it has, and on a paid one the
|
|
186
|
+
* records themselves, its organization's IP ranges and whether it is a
|
|
187
|
+
* disposable email domain.
|
|
188
|
+
*
|
|
189
|
+
* Sent as given and not cached. The API refuses a name it cannot read as
|
|
190
|
+
* `bad_request`.
|
|
191
|
+
*/
|
|
192
|
+
async lookupDomain(domain, options = {}) {
|
|
193
|
+
const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
|
|
194
|
+
return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
|
|
195
|
+
const res = await deadline(timeoutMs, (signal) => lookupDomain({
|
|
196
|
+
client: this.client, path: { domain: domain }, signal: signal,
|
|
197
|
+
}));
|
|
198
|
+
return toDomainResult(readable(res, isDomainLookup));
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* What this client's key is entitled to, and how much of it has been used.
|
|
203
|
+
*
|
|
204
|
+
* Named for what it answers rather than `me`, which sits one letter from
|
|
205
|
+
* `myIp` and means something quite different: one is which address you are
|
|
206
|
+
* calling FROM, the other is what the key you are calling WITH may spend.
|
|
207
|
+
*
|
|
208
|
+
* Unlike a lookup there is no useful unauthenticated answer, so a client
|
|
209
|
+
* built without a key gets an unauthorized error rather than a partial one.
|
|
210
|
+
*
|
|
211
|
+
* Usage counts against the ALLOWANCE WINDOW - on a paid plan the
|
|
212
|
+
* anniversary of the subscription, not the calendar month and not the
|
|
213
|
+
* billing period, and on the free plan the UTC day - and it is the same
|
|
214
|
+
* number a lookup is gated on. It can lag by a few seconds, because
|
|
215
|
+
* requests are counted in memory and flushed in aggregate.
|
|
216
|
+
*
|
|
217
|
+
* Deliberately NOT cached: the whole point is what has been spent, and a
|
|
218
|
+
* cached answer is a wrong one within seconds of the next request.
|
|
219
|
+
*/
|
|
220
|
+
async myEntitlement(options = {}) {
|
|
221
|
+
const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
|
|
222
|
+
return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
|
|
223
|
+
const res = await deadline(timeoutMs, (signal) => myEntitlement({
|
|
224
|
+
client: this.client, signal: signal,
|
|
225
|
+
}));
|
|
226
|
+
return readable(res, isEntitlement);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Look many addresses up in as few requests as possible.
|
|
231
|
+
*
|
|
232
|
+
* Bogons are answered locally, cached answers are reused, the cache's `store`
|
|
233
|
+
* is read for the rest, and an address with a request already in flight, a
|
|
234
|
+
* lookup's or another batch's, awaits that request; everything else goes to
|
|
235
|
+
* the batch endpoint in chunks of up to 1000 addresses, with at most
|
|
236
|
+
* `concurrency` chunks in flight, and a lookup arriving meanwhile awaits this
|
|
237
|
+
* batch's answer for its address. Keyed by address rather than positional, so
|
|
238
|
+
* duplicates in the input collapse to a single entry and the caller never has
|
|
239
|
+
* to line two lists up. An address that fails carries its error as its value,
|
|
240
|
+
* so one bad entry cannot lose the rest of the answers: the API reports a
|
|
241
|
+
* per-entry failure with the status the single lookup would have answered,
|
|
242
|
+
* and a chunk that fails as a whole marks every address in it. A per-call
|
|
243
|
+
* `concurrency` below 1 is refused as `bad_request` before anything is sent.
|
|
244
|
+
* An IPv4-mapped address is looked up as the IPv4 address it carries, and its
|
|
245
|
+
* answer keyed as you passed it. The batch endpoint needs a paid plan:
|
|
246
|
+
* without a key every address in a request of two or more carries an
|
|
247
|
+
* `unauthorized` error, and a free-plan key's request of two or more a
|
|
248
|
+
* `bad_request` (HTTP 402). A request of one address is answered as its
|
|
249
|
+
* lookup would be.
|
|
250
|
+
*/
|
|
251
|
+
async lookupBatch(ips, options = {}) {
|
|
252
|
+
const concurrency = checkConcurrency(options.concurrency);
|
|
253
|
+
checkTimeout(options.timeoutMs);
|
|
254
|
+
checkRetries(options.retries);
|
|
255
|
+
const asked = [...new Set(ips)];
|
|
256
|
+
const unique = [...new Set(asked.map(unmapped))];
|
|
257
|
+
const out = new Map();
|
|
258
|
+
const pending = [];
|
|
259
|
+
// Every address that is neither a bogon nor cached goes through
|
|
260
|
+
// `fetch()` in one synchronous pass: one with a request in flight joins
|
|
261
|
+
// it, and for the rest `fetchMethod` runs at once, which is how this
|
|
262
|
+
// batch learns the addresses it leads before building any chunk.
|
|
263
|
+
const shared = [];
|
|
264
|
+
const led = new Map();
|
|
265
|
+
for (const ip of unique) {
|
|
266
|
+
if (isBogon(ip)) {
|
|
267
|
+
out.set(ip, bogonResult(ip));
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
const hit = this.cache?.get(ip);
|
|
271
|
+
if (hit !== undefined) {
|
|
272
|
+
out.set(ip, hit);
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
if (this.cache === null) {
|
|
276
|
+
pending.push(ip);
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
shared.push([ip, this.cache.fetch(ip, {
|
|
280
|
+
context: () => {
|
|
281
|
+
const landing = deferred();
|
|
282
|
+
led.set(ip, landing);
|
|
283
|
+
pending.push(ip);
|
|
284
|
+
return landing.promise;
|
|
285
|
+
},
|
|
286
|
+
})]);
|
|
287
|
+
}
|
|
288
|
+
const sending = this.store === null ? pending : await this.unstored(pending, led);
|
|
289
|
+
// A per-call concurrency gets its own limiter; without one the call
|
|
290
|
+
// would share the instance's budget and silently ignore the override.
|
|
291
|
+
const limit = concurrency === undefined ? this.limit : pLimit(concurrency);
|
|
292
|
+
const chunks = [];
|
|
293
|
+
for (let i = 0; i < sending.length; i += BATCH_MAX) {
|
|
294
|
+
chunks.push(sending.slice(i, i + BATCH_MAX));
|
|
295
|
+
}
|
|
296
|
+
await Promise.all([
|
|
297
|
+
...chunks.map((chunk) => limit(async () => {
|
|
298
|
+
const kept = [];
|
|
299
|
+
for (const [ip, answer] of await this.lookupChunk(chunk, options)) {
|
|
300
|
+
const landing = led.get(ip);
|
|
301
|
+
if (landing === undefined) {
|
|
302
|
+
out.set(ip, answer);
|
|
303
|
+
}
|
|
304
|
+
else if (answer instanceof InternetDataError) {
|
|
305
|
+
landing.reject(answer);
|
|
306
|
+
}
|
|
307
|
+
else {
|
|
308
|
+
landing.resolve(answer);
|
|
309
|
+
}
|
|
310
|
+
if (this.store !== null && !(answer instanceof InternetDataError)) {
|
|
311
|
+
kept.push(this.store.set(ip, answer));
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
await Promise.all(kept);
|
|
315
|
+
})),
|
|
316
|
+
...shared.map(async ([ip, answer]) => {
|
|
317
|
+
try {
|
|
318
|
+
out.set(ip, (await answer));
|
|
319
|
+
}
|
|
320
|
+
catch (err) {
|
|
321
|
+
out.set(ip, asError(err));
|
|
322
|
+
}
|
|
323
|
+
}),
|
|
324
|
+
]);
|
|
325
|
+
// Reinstated in input order, under the addresses as passed: chunks
|
|
326
|
+
// settle in completion order, and a caller iterating the map should see
|
|
327
|
+
// what they passed in.
|
|
328
|
+
return new Map(asked.map((ip) => [ip, out.get(unmapped(ip))]));
|
|
329
|
+
}
|
|
330
|
+
// The addresses this batch leads that the store does not hold, in the order
|
|
331
|
+
// given. One the store holds lands at once, as a request's answer would.
|
|
332
|
+
async unstored(ips, led) {
|
|
333
|
+
const stored = await Promise.all(ips.map((ip) => this.store.get(ip)));
|
|
334
|
+
return ips.filter((ip, i) => {
|
|
335
|
+
const hit = stored[i];
|
|
336
|
+
if (hit === undefined) {
|
|
337
|
+
return true;
|
|
338
|
+
}
|
|
339
|
+
led.get(ip).resolve(hit);
|
|
340
|
+
return false;
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
// One POST /batch, mapped back onto the addresses it was asked about. A
|
|
344
|
+
// chunk-level failure - the call refused, the transport failing, the
|
|
345
|
+
// retries exhausted - becomes every address's error, exactly as it would
|
|
346
|
+
// have been had each been looked up alone.
|
|
347
|
+
async lookupChunk(chunk, options) {
|
|
348
|
+
const out = new Map();
|
|
349
|
+
const timeoutMs = options.timeoutMs ?? this.timeoutMs;
|
|
350
|
+
let body;
|
|
351
|
+
try {
|
|
352
|
+
body = await withRetry(options.retries ?? this.retries, async () => {
|
|
353
|
+
const res = await deadline(timeoutMs, (signal) => lookupBatch({
|
|
354
|
+
client: this.client, body: { ips: chunk }, signal: signal,
|
|
355
|
+
}));
|
|
356
|
+
return readable(res, isBatch);
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
catch (err) {
|
|
360
|
+
const failure = asError(err);
|
|
361
|
+
for (const ip of chunk) {
|
|
362
|
+
out.set(ip, failure);
|
|
363
|
+
}
|
|
364
|
+
return out;
|
|
365
|
+
}
|
|
366
|
+
// An entry is judged alone: one the client cannot read is that address's
|
|
367
|
+
// error, and the rest of the chunk keeps its answers. Each map is read by
|
|
368
|
+
// its own keys alone, so an address spelled `__proto__`, `constructor` or
|
|
369
|
+
// `toString` never reads the object's prototype as an answer.
|
|
370
|
+
for (const ip of chunk) {
|
|
371
|
+
const served = Object.hasOwn(body.results, ip) ? body.results[ip] : undefined;
|
|
372
|
+
if (served !== undefined) {
|
|
373
|
+
// The batch also answers ASes and domains, which this call never sends.
|
|
374
|
+
out.set(ip, isLookup(served) ? toResult(served) : unreadableEntry(ip));
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
const failed = Object.hasOwn(body.errors, ip) ? body.errors[ip] : undefined;
|
|
378
|
+
if (failed !== undefined) {
|
|
379
|
+
out.set(ip, isBatchError(failed) ? errorFromEntry(failed) : unreadableEntry(ip));
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
out.set(ip, new InternetDataError('server_error', `the batch answer did not include ${ip}`, 200));
|
|
383
|
+
}
|
|
384
|
+
return out;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
// Promise.withResolvers by hand: it is newer than the browsers this library supports.
|
|
388
|
+
function deferred() {
|
|
389
|
+
let resolve;
|
|
390
|
+
let reject;
|
|
391
|
+
const promise = new Promise((res, rej) => {
|
|
392
|
+
resolve = res;
|
|
393
|
+
reject = rej;
|
|
394
|
+
});
|
|
395
|
+
return { promise: promise, resolve: resolve, reject: reject };
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* The key without the blanks around it, and no key at all for blanks alone,
|
|
399
|
+
* which would go out as `Authorization: Bearer`. A control character inside it
|
|
400
|
+
* is refused here, since fetch refuses such a header and every call would fail
|
|
401
|
+
* with nothing sent. `null` is no key.
|
|
402
|
+
*/
|
|
403
|
+
function checkApiKey(apiKey) {
|
|
404
|
+
if (apiKey === undefined || apiKey === null) {
|
|
405
|
+
return undefined;
|
|
406
|
+
}
|
|
407
|
+
if (typeof apiKey !== 'string') {
|
|
408
|
+
throw new InternetDataError('bad_request', `apiKey must be a string, got ${typeof apiKey}`);
|
|
409
|
+
}
|
|
410
|
+
const key = apiKey.trim();
|
|
411
|
+
if (/[\u0000-\u001f\u007f]/.test(key)) {
|
|
412
|
+
throw new InternetDataError('bad_request', 'apiKey must not contain a control character');
|
|
413
|
+
}
|
|
414
|
+
// fetch sends a header as Latin-1 and refuses anything past it.
|
|
415
|
+
if (/[^\u0000-\u00ff]/.test(key)) {
|
|
416
|
+
throw new InternetDataError('bad_request', 'apiKey must not contain a character past U+00FF');
|
|
417
|
+
}
|
|
418
|
+
return key === '' ? undefined : key;
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* The host the `oauth` calls go to: the apex, since the authorization server is
|
|
422
|
+
* mounted there and not on the API host. `https://api.internetdata.io` is
|
|
423
|
+
* `https://internetdata.io` and `https://api-<env>.internetdata.io` is
|
|
424
|
+
* `https://<env>.internetdata.io`; any other base URL is used as given.
|
|
425
|
+
*/
|
|
426
|
+
function apexOf(baseUrl) {
|
|
427
|
+
return baseUrl.replace(/^(https?:\/\/)api(?:-([^./:@]+))?\./i, (_, scheme, env) => (env === undefined ? scheme : `${scheme}${env}.`));
|
|
428
|
+
}
|
|
429
|
+
function unreadableEntry(ip) {
|
|
430
|
+
return new InternetDataError('server_error', `unreadable batch answer for ${ip}, status 200`, 200);
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Sends the key in the `Authorization` header and nowhere else.
|
|
434
|
+
*
|
|
435
|
+
* The API accepts three credential forms and the spec documents all three, so
|
|
436
|
+
* the generator applies EVERY one of them - putting the key in the query string
|
|
437
|
+
* of every request alongside the headers. A query string is the one place a
|
|
438
|
+
* secret should never be: it lands in access logs, proxy logs and browser
|
|
439
|
+
* history, none of which we control.
|
|
440
|
+
*
|
|
441
|
+
* Returning undefined for the other schemes is what suppresses them; the
|
|
442
|
+
* generated `getAuthToken` drops a scheme whose callback yields nothing.
|
|
443
|
+
*/
|
|
444
|
+
function bearerOnly(apiKey) {
|
|
445
|
+
return (auth) => (auth.scheme === 'bearer' ? apiKey : undefined);
|
|
446
|
+
}
|