vpndetection-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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +268 -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 +156 -0
  8. package/dist/client.js +386 -0
  9. package/dist/errors.d.ts +56 -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 +118 -0
  40. package/dist/generated/sdk.gen.js +174 -0
  41. package/dist/generated/types.gen.d.ts +790 -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,2 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export {};
@@ -0,0 +1,10 @@
1
+ export { VPNDetection, DEFAULT_BASE_URL } from './client.js';
2
+ export type { Options, CacheOptions, LookupOptions, BatchOptions } from './client.js';
3
+ export type { CacheStore } from './store.js';
4
+ export { OauthApi } from './oauth.js';
5
+ export type { OauthOptions, AuthorizationUrlOptions, OauthMetadata, TokenResponse, Pkce } from './oauth.js';
6
+ export { isBogon } from './bogon.js';
7
+ export { VPNDetectionError, OauthError, OauthAccessDeniedError, OauthExpiredTokenError, } from './errors.js';
8
+ export type { ErrorKind } from './errors.js';
9
+ export type { Result, VpnDetail, ClassDetail, ProxyDetail, PubproxyDetail, Location, Asn, LookupResponse, } from './types.js';
10
+ export type { Entitlement, EntitlementApikey, EntitlementPlan, EntitlementUsage, } from './generated/types.gen.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { VPNDetection, DEFAULT_BASE_URL } from './client.js';
2
+ export { OauthApi } from './oauth.js';
3
+ export { isBogon } from './bogon.js';
4
+ export { VPNDetectionError, OauthError, OauthAccessDeniedError, OauthExpiredTokenError, } from './errors.js';
@@ -0,0 +1,114 @@
1
+ import type { Client } from './generated/client/index.js';
2
+ /** Per-call overrides for one OAuth request. Anything omitted falls back to the client's setting. */
3
+ export interface OauthOptions {
4
+ /** How long one attempt may take before it is abandoned, in milliseconds. */
5
+ timeoutMs?: number;
6
+ }
7
+ /** What an authorization URL asks for beyond what every one carries. A member left out is left out. */
8
+ export interface AuthorizationUrlOptions {
9
+ /** Space-delimited scopes, sent as given. The server narrows them to what the client may ask for. */
10
+ scope?: string;
11
+ /** Comes back on the redirect unchanged, so the caller can tell the answer is to its own request. */
12
+ state?: string;
13
+ /** The API the tokens are meant for. */
14
+ resource?: string;
15
+ }
16
+ /** One sign-in's PKCE pair: `challenge` goes in the authorization URL, `verifier` to the exchange. */
17
+ export interface Pkce {
18
+ /** 32 random bytes as 43 characters of unpadded base64url, sent only to the exchange. */
19
+ verifier: string;
20
+ /** The verifier's SHA-256, as unpadded base64url. */
21
+ challenge: string;
22
+ /** `S256`, the only method the server accepts. */
23
+ method: 'S256';
24
+ }
25
+ /** The authorization server's discovery document. No call here needs it: each builds on the base URL. */
26
+ export interface OauthMetadata {
27
+ issuer: string;
28
+ authorization_endpoint: string;
29
+ token_endpoint: string;
30
+ device_authorization_endpoint?: string;
31
+ revocation_endpoint?: string;
32
+ scopes_supported?: string[];
33
+ response_types_supported?: string[];
34
+ grant_types_supported?: string[];
35
+ code_challenge_methods_supported?: string[];
36
+ token_endpoint_auth_methods_supported?: string[];
37
+ authorization_response_iss_parameter_supported?: boolean;
38
+ client_id_metadata_document_supported?: boolean;
39
+ registration_endpoint?: string;
40
+ service_documentation?: string;
41
+ }
42
+ /**
43
+ * What a completed sign-in or a refresh hands back.
44
+ *
45
+ * `apikey_id` is set when the person picked one of their API keys and may still
46
+ * read it back. `apikey`, the key itself, also needs a sign-in rather than a
47
+ * refresh and a key whose secret can be shown again, so `apikey_id` without
48
+ * `apikey` is normal. An app signing in with a client metadata document is never
49
+ * handed a key. An empty `scope` is present.
50
+ */
51
+ export interface TokenResponse {
52
+ access_token: string;
53
+ token_type: string;
54
+ expires_in: number;
55
+ /** Spent by the refresh that presents it, so keep the one each refresh returns. */
56
+ refresh_token?: string;
57
+ scope?: string;
58
+ apikey_id?: string;
59
+ apikey?: string;
60
+ }
61
+ /**
62
+ * Signs a person in through their browser with the OAuth authorization code flow
63
+ * and PKCE, so an app or an extension can act for them. Reached through
64
+ * `client.oauth`.
65
+ *
66
+ * Every call takes a client ID: one issued on request from
67
+ * support@vpndetection.io, or the https URL of a client metadata document the app
68
+ * serves. None of these requests carries the client's API key, and none needs one.
69
+ */
70
+ export declare class OauthApi {
71
+ private readonly client;
72
+ private readonly retries;
73
+ private readonly timeoutMs;
74
+ constructor(client: Client, retries: number, timeoutMs: number);
75
+ metadata(options?: OauthOptions): Promise<OauthMetadata>;
76
+ /**
77
+ * The URL to send the person's browser to. Makes no request. Once they
78
+ * decide, the server redirects to `redirectUri` with a `code` for
79
+ * `exchangeAuthorizationCode` (and `state`, when one was given), or with an
80
+ * `error`.
81
+ */
82
+ authorizationUrl(clientId: string, redirectUri: string, codeChallenge: string, options?: AuthorizationUrlOptions): string;
83
+ /**
84
+ * Trade the `code` a sign-in's redirect brought back for tokens.
85
+ * `codeVerifier` is the PKCE verifier whose challenge went into the
86
+ * authorization URL, and `redirectUri` that URL's, exactly.
87
+ *
88
+ * Never retried: the server spends the code on first read, before it checks
89
+ * the verifier, so a retry could only be refused.
90
+ */
91
+ exchangeAuthorizationCode(clientId: string, code: string, codeVerifier: string, redirectUri: string, options?: OauthOptions): Promise<TokenResponse>;
92
+ /**
93
+ * Trade a refresh token for a new pair. The old one is spent whatever happens
94
+ * next, so this is never retried. A refresh names the key the person picked
95
+ * (`apikey_id`) but never reveals it again (`apikey`).
96
+ */
97
+ exchangeRefreshToken(clientId: string, refreshToken: string, options?: OauthOptions): Promise<TokenResponse>;
98
+ /**
99
+ * A fresh PKCE pair for one sign-in, from the browser's secure random source.
100
+ *
101
+ * Async, as Web Crypto's digest is. A page served over plain http has no Web
102
+ * Crypto digest at all, so there it rejects as `bad_request`.
103
+ */
104
+ createPkce(): Promise<Pkce>;
105
+ /** The `S256` challenge for a PKCE verifier: its SHA-256, as unpadded base64url. */
106
+ pkceChallenge(verifier: string): Promise<string>;
107
+ /**
108
+ * End a token. A refresh token ends the whole sign-in and every token it
109
+ * issued, which is how an app signs the person out; an access token ends
110
+ * only itself. The server answers the same for any token, known or not.
111
+ */
112
+ revoke(clientId: string, token: string, options?: OauthOptions): Promise<void>;
113
+ private exchange;
114
+ }
package/dist/oauth.js ADDED
@@ -0,0 +1,245 @@
1
+ import { oauthMetadata, oauthRevoke, oauthToken } from './generated/sdk.gen.js';
2
+ import { errorFromResponse, oauthErrorFrom, VPNDetectionError } from './errors.js';
3
+ import { checkTimeout, deadline, noResponse, withRetry } from './transport.js';
4
+ /**
5
+ * Signs a person in through their browser with the OAuth authorization code flow
6
+ * and PKCE, so an app or an extension can act for them. Reached through
7
+ * `client.oauth`.
8
+ *
9
+ * Every call takes a client ID: one issued on request from
10
+ * support@vpndetection.io, or the https URL of a client metadata document the app
11
+ * serves. None of these requests carries the client's API key, and none needs one.
12
+ */
13
+ export class OauthApi {
14
+ client;
15
+ retries;
16
+ timeoutMs;
17
+ constructor(client, retries, timeoutMs) {
18
+ this.client = client;
19
+ this.retries = retries;
20
+ this.timeoutMs = timeoutMs;
21
+ }
22
+ async metadata(options = {}) {
23
+ checkTimeout(options.timeoutMs);
24
+ return withRetry(this.retries, async () => {
25
+ const res = await deadline(options.timeoutMs ?? this.timeoutMs, (signal) => oauthMetadata({
26
+ client: this.client, signal: signal,
27
+ }));
28
+ return decode(res, METADATA);
29
+ });
30
+ }
31
+ /**
32
+ * The URL to send the person's browser to. Makes no request. Once they
33
+ * decide, the server redirects to `redirectUri` with a `code` for
34
+ * `exchangeAuthorizationCode` (and `state`, when one was given), or with an
35
+ * `error`.
36
+ */
37
+ authorizationUrl(clientId, redirectUri, codeChallenge, options = {}) {
38
+ const params = [
39
+ ['response_type', 'code'],
40
+ ['client_id', clientId],
41
+ ['redirect_uri', redirectUri],
42
+ ['code_challenge', codeChallenge],
43
+ ['code_challenge_method', 'S256'],
44
+ ['scope', options.scope || undefined],
45
+ ['state', options.state || undefined],
46
+ ['resource', options.resource || undefined],
47
+ ];
48
+ const query = params
49
+ .filter((param) => param[1] !== undefined)
50
+ .map(([name, value]) => `${name}=${percentEncode(name, value)}`)
51
+ .join('&');
52
+ return `${this.client.getConfig().baseUrl ?? ''}/oauth/authorize?${query}`;
53
+ }
54
+ /**
55
+ * Trade the `code` a sign-in's redirect brought back for tokens.
56
+ * `codeVerifier` is the PKCE verifier whose challenge went into the
57
+ * authorization URL, and `redirectUri` that URL's, exactly.
58
+ *
59
+ * Never retried: the server spends the code on first read, before it checks
60
+ * the verifier, so a retry could only be refused.
61
+ */
62
+ async exchangeAuthorizationCode(clientId, code, codeVerifier, redirectUri, options = {}) {
63
+ return this.exchange({
64
+ grant_type: 'authorization_code', code: code, redirect_uri: redirectUri,
65
+ client_id: clientId, code_verifier: codeVerifier,
66
+ }, options.timeoutMs);
67
+ }
68
+ /**
69
+ * Trade a refresh token for a new pair. The old one is spent whatever happens
70
+ * next, so this is never retried. A refresh names the key the person picked
71
+ * (`apikey_id`) but never reveals it again (`apikey`).
72
+ */
73
+ async exchangeRefreshToken(clientId, refreshToken, options = {}) {
74
+ return this.exchange({
75
+ grant_type: 'refresh_token', refresh_token: refreshToken, client_id: clientId,
76
+ }, options.timeoutMs);
77
+ }
78
+ /**
79
+ * A fresh PKCE pair for one sign-in, from the browser's secure random source.
80
+ *
81
+ * Async, as Web Crypto's digest is. A page served over plain http has no Web
82
+ * Crypto digest at all, so there it rejects as `bad_request`.
83
+ */
84
+ async createPkce() {
85
+ const verifier = base64url(webCrypto().getRandomValues(new Uint8Array(32)));
86
+ return { verifier: verifier, challenge: await challengeFor(verifier), method: 'S256' };
87
+ }
88
+ /** The `S256` challenge for a PKCE verifier: its SHA-256, as unpadded base64url. */
89
+ async pkceChallenge(verifier) {
90
+ return challengeFor(verifier);
91
+ }
92
+ /**
93
+ * End a token. A refresh token ends the whole sign-in and every token it
94
+ * issued, which is how an app signs the person out; an access token ends
95
+ * only itself. The server answers the same for any token, known or not.
96
+ */
97
+ async revoke(clientId, token, options = {}) {
98
+ checkTimeout(options.timeoutMs);
99
+ await withRetry(this.retries, async () => {
100
+ const res = await deadline(options.timeoutMs ?? this.timeoutMs, (signal) => oauthRevoke({
101
+ client: this.client,
102
+ body: { token: token, client_id: clientId },
103
+ // The answer says nothing, so it is read as text and dropped rather than parsed.
104
+ parseAs: 'text',
105
+ signal: signal,
106
+ }));
107
+ throwIfFailed(res);
108
+ });
109
+ }
110
+ async exchange(form, timeoutMs) {
111
+ checkTimeout(timeoutMs);
112
+ const res = await deadline(timeoutMs ?? this.timeoutMs, (signal) => oauthToken({
113
+ client: this.client, body: form, signal: signal,
114
+ }));
115
+ return decode(res, TOKEN_RESPONSE);
116
+ }
117
+ }
118
+ async function challengeFor(verifier) {
119
+ if (typeof verifier !== 'string') {
120
+ throw new VPNDetectionError('bad_request', `verifier must be a string, got ${typeof verifier}`);
121
+ }
122
+ const digest = await webCrypto().subtle.digest('SHA-256', new TextEncoder().encode(verifier));
123
+ return base64url(new Uint8Array(digest));
124
+ }
125
+ // A browser offers Web Crypto's digest only to a secure context: https, or a
126
+ // page on the loopback address. Refused by name here rather than failing as a
127
+ // TypeError on `undefined`.
128
+ function webCrypto() {
129
+ const crypto = globalThis.crypto;
130
+ if (crypto?.subtle === undefined || typeof crypto.getRandomValues !== 'function') {
131
+ throw new VPNDetectionError('bad_request', 'PKCE needs Web Crypto, which this context lacks: serve the page over https');
132
+ }
133
+ return crypto;
134
+ }
135
+ function base64url(bytes) {
136
+ let binary = '';
137
+ for (const byte of bytes) {
138
+ binary += String.fromCharCode(byte);
139
+ }
140
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
141
+ }
142
+ // Every byte of the value's UTF-8 as %XX but A-Z a-z 0-9 - . _ ~, so a space is
143
+ // %20 and never +. encodeURIComponent alone leaves ! ' ( ) * as they are, and
144
+ // throws a URIError on a lone surrogate, which has no UTF-8 at all.
145
+ function percentEncode(name, value) {
146
+ if (typeof value !== 'string' || value === '') {
147
+ throw new VPNDetectionError('bad_request', `${name} must be a non-empty string`);
148
+ }
149
+ try {
150
+ return encodeURIComponent(value)
151
+ .replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
152
+ }
153
+ catch {
154
+ throw new VPNDetectionError('bad_request', `${name} is not valid UTF-16, so it has no UTF-8 to send`);
155
+ }
156
+ }
157
+ const METADATA = {
158
+ issuer: { type: 'string', required: true },
159
+ authorization_endpoint: { type: 'string', required: true },
160
+ token_endpoint: { type: 'string', required: true },
161
+ device_authorization_endpoint: { type: 'string' },
162
+ revocation_endpoint: { type: 'string' },
163
+ scopes_supported: { type: 'string[]' },
164
+ response_types_supported: { type: 'string[]' },
165
+ grant_types_supported: { type: 'string[]' },
166
+ code_challenge_methods_supported: { type: 'string[]' },
167
+ token_endpoint_auth_methods_supported: { type: 'string[]' },
168
+ authorization_response_iss_parameter_supported: { type: 'boolean' },
169
+ client_id_metadata_document_supported: { type: 'boolean' },
170
+ registration_endpoint: { type: 'string' },
171
+ service_documentation: { type: 'string' },
172
+ };
173
+ const TOKEN_RESPONSE = {
174
+ access_token: { type: 'string', required: true },
175
+ token_type: { type: 'string', required: true },
176
+ expires_in: { type: 'integer', required: true },
177
+ refresh_token: { type: 'string' },
178
+ scope: { type: 'string' },
179
+ apikey_id: { type: 'string', wire: 'mslm:apikey_id' },
180
+ apikey: { type: 'string', wire: 'mslm:apikey' },
181
+ };
182
+ // Only the declared members are copied, on PRESENCE, so an absent one stays
183
+ // absent and an empty `scope` stays present. Anything else the server sends is
184
+ // dropped rather than surfaced untyped.
185
+ function decode(res, members) {
186
+ const status = throwIfFailed(res).status;
187
+ if (res.error !== undefined) {
188
+ // A 2xx the generated client could not parse, which reports it here: as
189
+ // unreadable as an object missing a member, so the same retried error.
190
+ throw new VPNDetectionError('server_error', 'the answer was not JSON', status);
191
+ }
192
+ const body = res.data;
193
+ if (!isObject(body)) {
194
+ throw new VPNDetectionError('server_error', 'the answer was not a JSON object', status);
195
+ }
196
+ const out = {};
197
+ for (const [name, member] of Object.entries(members)) {
198
+ const wire = member.wire ?? name;
199
+ const value = body[wire];
200
+ if (value === undefined || value === null) {
201
+ if (member.required) {
202
+ throw new VPNDetectionError('server_error', `the answer carried no ${wire}`, status);
203
+ }
204
+ continue;
205
+ }
206
+ if (!hasType(value, member.type)) {
207
+ throw new VPNDetectionError('server_error', `the answer's ${wire} is not ${TYPE_NAMES[member.type]}`, status);
208
+ }
209
+ out[name] = value;
210
+ }
211
+ return out;
212
+ }
213
+ // Only a 4xx whose body is a JSON object with a STRING `error` is an OAuth
214
+ // refusal. Every 5xx, whatever it says, is the server failing, and is retried
215
+ // wherever the operation retries.
216
+ function throwIfFailed(res) {
217
+ if (res.response === undefined) {
218
+ throw noResponse(res.error);
219
+ }
220
+ const { status, ok, headers } = res.response;
221
+ if (ok) {
222
+ return res.response;
223
+ }
224
+ const body = res.error;
225
+ if (status >= 400 && status < 500 && isObject(body) && typeof body.error === 'string') {
226
+ const description = typeof body.error_description === 'string' ? body.error_description : undefined;
227
+ throw oauthErrorFrom(body.error, description, status);
228
+ }
229
+ throw errorFromResponse(status, headers, body);
230
+ }
231
+ function isObject(value) {
232
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
233
+ }
234
+ const TYPE_NAMES = {
235
+ 'string': 'a string', 'integer': 'an integer', 'boolean': 'a boolean', 'string[]': 'a list of strings',
236
+ };
237
+ function hasType(value, type) {
238
+ if (type === 'string[]') {
239
+ return Array.isArray(value) && value.every((item) => typeof item === 'string');
240
+ }
241
+ if (type === 'integer') {
242
+ return Number.isInteger(value);
243
+ }
244
+ return typeof value === type;
245
+ }
@@ -0,0 +1,28 @@
1
+ export declare const LOOKUP_MEMBERS: readonly ["ip", "is_vpn"];
2
+ export declare const LOCATION_MEMBERS: readonly ["continent", "continent_name", "country", "country_name", "timezone", "currency_code", "currency_name", "currency_symbol", "flag_emoji", "flag_unicode"];
3
+ export declare const ASN_MEMBERS: readonly ["asn", "name", "domain", "type", "prefix"];
4
+ export declare const BATCH_MEMBERS: readonly ["results", "errors"];
5
+ export declare const BATCH_ERROR_MEMBERS: readonly ["status", "error"];
6
+ export declare const ENTITLEMENT_MEMBERS: readonly ["org_id", "apikey", "plan", "usage"];
7
+ export declare const ENTITLEMENT_APIKEY_MEMBERS: readonly ["id", "allowed_cidrs"];
8
+ export declare const ENTITLEMENT_PLAN_MEMBERS: readonly ["key", "tier"];
9
+ export declare const ENTITLEMENT_USAGE_MEMBERS: readonly ["requests", "quota", "window_start", "window_end"];
10
+ type Kind = 'string' | 'integer' | 'boolean' | 'object' | 'array' | 'date' | 'date-time';
11
+ export declare const LOOKUP_TYPES: Record<string, Kind>;
12
+ export declare const VPN_DETAIL_TYPES: Record<string, Kind>;
13
+ export declare const CLASS_DETAIL_TYPES: Record<string, Kind>;
14
+ export declare const PROXY_DETAIL_TYPES: Record<string, Kind>;
15
+ export declare const PUBPROXY_DETAIL_TYPES: Record<string, Kind>;
16
+ export declare const LOCATION_TYPES: Record<string, Kind>;
17
+ export declare const ASN_TYPES: Record<string, Kind>;
18
+ export declare const BATCH_ERROR_TYPES: Record<string, Kind>;
19
+ export declare const ENTITLEMENT_TYPES: Record<string, Kind>;
20
+ export declare const ENTITLEMENT_APIKEY_TYPES: Record<string, Kind>;
21
+ export declare const ENTITLEMENT_PLAN_TYPES: Record<string, Kind>;
22
+ export declare const ENTITLEMENT_USAGE_TYPES: Record<string, Kind>;
23
+ export declare function isLookup(data: unknown): boolean;
24
+ /** Both maps present. An entry in either is judged on its own, as that address's answer. */
25
+ export declare function isBatch(data: unknown): boolean;
26
+ export declare function isBatchError(entry: unknown): boolean;
27
+ export declare function isEntitlement(data: unknown): boolean;
28
+ export {};
package/dist/shapes.js ADDED
@@ -0,0 +1,133 @@
1
+ // The members each answer must carry before the client hands it back: every one
2
+ // the spec requires and never sends as null. The tests read them against the
3
+ // generated types, so a member the spec adds fails the suite until it is here.
4
+ import { hasMembers } from './transport.js';
5
+ export const LOOKUP_MEMBERS = ['ip', 'is_vpn'];
6
+ export const LOCATION_MEMBERS = [
7
+ 'continent', 'continent_name', 'country', 'country_name', 'timezone', 'currency_code', 'currency_name',
8
+ 'currency_symbol', 'flag_emoji', 'flag_unicode',
9
+ ];
10
+ export const ASN_MEMBERS = ['asn', 'name', 'domain', 'type', 'prefix'];
11
+ export const BATCH_MEMBERS = ['results', 'errors'];
12
+ export const BATCH_ERROR_MEMBERS = ['status', 'error'];
13
+ export const ENTITLEMENT_MEMBERS = ['org_id', 'apikey', 'plan', 'usage'];
14
+ export const ENTITLEMENT_APIKEY_MEMBERS = ['id', 'allowed_cidrs'];
15
+ export const ENTITLEMENT_PLAN_MEMBERS = ['key', 'tier'];
16
+ export const ENTITLEMENT_USAGE_MEMBERS = ['requests', 'quota', 'window_start', 'window_end'];
17
+ export const LOOKUP_TYPES = {
18
+ ip: 'string', is_vpn: 'boolean', is_hosting: 'boolean', is_relay: 'boolean', is_tor: 'boolean',
19
+ is_cdn: 'boolean', is_resproxy: 'boolean', is_dcproxy: 'boolean', is_mobproxy: 'boolean',
20
+ is_pubproxy: 'boolean', vpn: 'object', hosting: 'object', relay: 'object', tor: 'object', cdn: 'object',
21
+ resproxy: 'object', dcproxy: 'object', mobproxy: 'object', pubproxy: 'object', location: 'object',
22
+ asn: 'object',
23
+ };
24
+ export const VPN_DETAIL_TYPES = {
25
+ provider: 'string', last_seen: 'date', confidence: 'string', method: 'string',
26
+ };
27
+ export const CLASS_DETAIL_TYPES = {
28
+ provider: 'string', confidence: 'string', last_seen: 'date',
29
+ };
30
+ export const PROXY_DETAIL_TYPES = {
31
+ provider: 'string', first_seen: 'date', last_seen: 'date', hits: 'integer', hits_days_pct: 'integer',
32
+ providers_num: 'integer',
33
+ };
34
+ export const PUBPROXY_DETAIL_TYPES = {
35
+ entry: 'boolean', exit: 'boolean', protocols: 'array', num_ports: 'integer', num_proxies: 'integer',
36
+ last_seen: 'date', last_usable: 'string',
37
+ };
38
+ export const LOCATION_TYPES = Object.fromEntries(LOCATION_MEMBERS.map((m) => [m, 'string']));
39
+ export const ASN_TYPES = {
40
+ asn: 'integer', name: 'string', domain: 'string', type: 'string', prefix: 'string',
41
+ };
42
+ export const BATCH_ERROR_TYPES = { status: 'integer', error: 'string' };
43
+ export const ENTITLEMENT_TYPES = {
44
+ org_id: 'string', apikey: 'object', plan: 'object', usage: 'object',
45
+ };
46
+ export const ENTITLEMENT_APIKEY_TYPES = {
47
+ id: 'string', expires: 'date-time', allowed_cidrs: 'array',
48
+ };
49
+ export const ENTITLEMENT_PLAN_TYPES = { key: 'string', tier: 'string' };
50
+ export const ENTITLEMENT_USAGE_TYPES = {
51
+ requests: 'integer', quota: 'integer', hard_limit: 'integer', window_start: 'date-time',
52
+ window_end: 'date-time',
53
+ };
54
+ function isObject(value) {
55
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
56
+ }
57
+ function isKind(value, kind) {
58
+ switch (kind) {
59
+ case 'string': return typeof value === 'string';
60
+ case 'integer': return Number.isInteger(value);
61
+ case 'boolean': return typeof value === 'boolean';
62
+ case 'object': return isObject(value);
63
+ case 'array': return Array.isArray(value);
64
+ case 'date': return typeof value === 'string' && isFullDate(value);
65
+ case 'date-time': return typeof value === 'string' && isDateTime(value);
66
+ }
67
+ }
68
+ const FULL_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
69
+ const DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))$/;
70
+ /** RFC 3339's `full-date`, naming a day its month has. */
71
+ function isFullDate(value) {
72
+ const m = FULL_DATE.exec(value);
73
+ return m !== null && isDay(m[1], m[2], m[3]);
74
+ }
75
+ /**
76
+ * RFC 3339's `date-time`, its lowercase `t` and `z` included, with an hour below 24,
77
+ * a minute and a second below 60 and an offset of at most 23:59.
78
+ */
79
+ function isDateTime(value) {
80
+ const m = DATE_TIME.exec(value);
81
+ return m !== null && isDay(m[1], m[2], m[3])
82
+ && Number(m[4]) < 24 && Number(m[5]) < 60 && Number(m[6]) < 60
83
+ && (m[7] === undefined || (Number(m[7]) < 24 && Number(m[8]) < 60));
84
+ }
85
+ // setUTCFullYear rather than Date.UTC, which reads a year below 100 as 19xx.
86
+ function isDay(year, month, day) {
87
+ const date = new Date(0);
88
+ date.setUTCFullYear(Number(year), Number(month) - 1, Number(day));
89
+ return date.getUTCFullYear() === Number(year) && date.getUTCMonth() === Number(month) - 1
90
+ && date.getUTCDate() === Number(day);
91
+ }
92
+ function typed(value, required, types) {
93
+ return hasMembers(value, required) && Object.entries(types).every(([member, kind]) => {
94
+ const v = value[member];
95
+ return v === undefined || v === null ? !required.includes(member) : isKind(v, kind);
96
+ });
97
+ }
98
+ function every(value, valid) {
99
+ return Array.isArray(value) && value.every(valid);
100
+ }
101
+ function isString(value) {
102
+ return typeof value === 'string';
103
+ }
104
+ /** An optional member: absent or null, or valid. */
105
+ function optional(value, valid) {
106
+ return value === undefined || value === null || valid(value);
107
+ }
108
+ const DETAILS = [
109
+ ['vpn', VPN_DETAIL_TYPES], ['hosting', CLASS_DETAIL_TYPES], ['relay', CLASS_DETAIL_TYPES],
110
+ ['tor', CLASS_DETAIL_TYPES], ['cdn', CLASS_DETAIL_TYPES], ['resproxy', PROXY_DETAIL_TYPES],
111
+ ['dcproxy', PROXY_DETAIL_TYPES], ['mobproxy', PROXY_DETAIL_TYPES], ['pubproxy', PUBPROXY_DETAIL_TYPES],
112
+ ];
113
+ export function isLookup(data) {
114
+ return typed(data, LOOKUP_MEMBERS, LOOKUP_TYPES)
115
+ && DETAILS.every(([member, types]) => optional(data[member], (detail) => typed(detail, [], types)))
116
+ && optional(data['pubproxy']?.['protocols'], (protocols) => every(protocols, isString))
117
+ && optional(data['location'], (location) => typed(location, LOCATION_MEMBERS, LOCATION_TYPES))
118
+ && optional(data['asn'], (asn) => typed(asn, ASN_MEMBERS, ASN_TYPES));
119
+ }
120
+ /** Both maps present. An entry in either is judged on its own, as that address's answer. */
121
+ export function isBatch(data) {
122
+ return hasMembers(data, BATCH_MEMBERS) && isObject(data['results']) && isObject(data['errors']);
123
+ }
124
+ export function isBatchError(entry) {
125
+ return typed(entry, BATCH_ERROR_MEMBERS, BATCH_ERROR_TYPES);
126
+ }
127
+ export function isEntitlement(data) {
128
+ return typed(data, ENTITLEMENT_MEMBERS, ENTITLEMENT_TYPES)
129
+ && typed(data['apikey'], ENTITLEMENT_APIKEY_MEMBERS, ENTITLEMENT_APIKEY_TYPES)
130
+ && every(data['apikey']['allowed_cidrs'], isString)
131
+ && typed(data['plan'], ENTITLEMENT_PLAN_MEMBERS, ENTITLEMENT_PLAN_TYPES)
132
+ && typed(data['usage'], ENTITLEMENT_USAGE_MEMBERS, ENTITLEMENT_USAGE_TYPES);
133
+ }
@@ -0,0 +1,39 @@
1
+ import { type Result } from './types.js';
2
+ /**
3
+ * A persistent tier behind the client's in-memory cache, for answers that should
4
+ * outlive the client: a page reload, or an extension's service worker, which the
5
+ * browser stops once it sits idle and starts again on the next event.
6
+ *
7
+ * `key` is the address with a hash of the client's API key and base URL in front of
8
+ * it, so clients holding different keys, and so entitled to different fields, can
9
+ * share one store without ever reading each other's answers. `set` is handed how long
10
+ * the answer stays fresh; dropping it once that has passed is the store's job.
11
+ */
12
+ export interface CacheStore {
13
+ get(key: string): Promise<Result | undefined> | Result | undefined;
14
+ set(key: string, result: Result, ttlMs: number): Promise<void> | void;
15
+ }
16
+ /**
17
+ * The client's side of a `CacheStore`. A store is a cache, never a source of
18
+ * errors: one that throws or rejects reads as a miss and a write that fails is
19
+ * dropped, so either costs a request and never an answer. An entry it hands back
20
+ * is read the way an answer off the wire is, so one that is not a lookup answer
21
+ * is a miss too.
22
+ */
23
+ export declare class StoreTier {
24
+ private readonly store;
25
+ private readonly scope;
26
+ private readonly ttlMs;
27
+ constructor(store: CacheStore, scope: string, ttlMs: number);
28
+ get(ip: string): Promise<Result | undefined>;
29
+ set(ip: string, result: Result): Promise<void>;
30
+ private keyFor;
31
+ }
32
+ /**
33
+ * What tells one client's entries from another's: FNV-1a over the base URL and the
34
+ * key, as 16 hex digits. It tells keys apart and keeps the key itself out of the
35
+ * store; it is not a way to keep a key secret.
36
+ */
37
+ export declare function storeScope(baseUrl: string, apiKey: string | undefined): string;
38
+ /** A store is two functions; anything else is refused where the client is built. */
39
+ export declare function isCacheStore(store: unknown): store is CacheStore;
package/dist/store.js ADDED
@@ -0,0 +1,64 @@
1
+ import { isLookup } from './shapes.js';
2
+ import { toResult } from './types.js';
3
+ /**
4
+ * The client's side of a `CacheStore`. A store is a cache, never a source of
5
+ * errors: one that throws or rejects reads as a miss and a write that fails is
6
+ * dropped, so either costs a request and never an answer. An entry it hands back
7
+ * is read the way an answer off the wire is, so one that is not a lookup answer
8
+ * is a miss too.
9
+ */
10
+ export class StoreTier {
11
+ store;
12
+ scope;
13
+ ttlMs;
14
+ constructor(store, scope, ttlMs) {
15
+ this.store = store;
16
+ this.scope = scope;
17
+ this.ttlMs = ttlMs;
18
+ }
19
+ async get(ip) {
20
+ let stored;
21
+ try {
22
+ stored = await this.store.get(this.keyFor(ip));
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ if (typeof stored !== 'object' || stored === null) {
28
+ return undefined;
29
+ }
30
+ const raw = stored.raw;
31
+ return isLookup(raw) ? toResult(raw) : undefined;
32
+ }
33
+ async set(ip, result) {
34
+ try {
35
+ await this.store.set(this.keyFor(ip), result, this.ttlMs);
36
+ }
37
+ catch {
38
+ // Costs a request on the next miss, nothing more.
39
+ }
40
+ }
41
+ keyFor(ip) {
42
+ return `${this.scope}:${ip}`;
43
+ }
44
+ }
45
+ const FNV_OFFSET = 0xcbf29ce484222325n;
46
+ const FNV_PRIME = 0x100000001b3n;
47
+ const MASK_64 = (1n << 64n) - 1n;
48
+ /**
49
+ * What tells one client's entries from another's: FNV-1a over the base URL and the
50
+ * key, as 16 hex digits. It tells keys apart and keeps the key itself out of the
51
+ * store; it is not a way to keep a key secret.
52
+ */
53
+ export function storeScope(baseUrl, apiKey) {
54
+ let hash = FNV_OFFSET;
55
+ for (const byte of new TextEncoder().encode(`${baseUrl}\n${apiKey ?? ''}`)) {
56
+ hash = ((hash ^ BigInt(byte)) * FNV_PRIME) & MASK_64;
57
+ }
58
+ return hash.toString(16).padStart(16, '0');
59
+ }
60
+ /** A store is two functions; anything else is refused where the client is built. */
61
+ export function isCacheStore(store) {
62
+ return typeof store === 'object' && store !== null
63
+ && typeof store.get === 'function' && typeof store.set === 'function';
64
+ }