internetdata-express 0.0.0-stage → 1.0.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mslm Dev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,163 @@
1
- # Temporary Holding Version
1
+ # [<img src="https://s3.internetdata.io/internetdata-public/brand/mark.svg" alt="InternetData" height="28"/>](https://internetdata.io/) InternetData Express Middleware
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/internetdata-express.svg)](https://www.npmjs.com/package/internetdata-express)
4
+ [![license](https://img.shields.io/npm/l/internetdata-express.svg)](LICENSE)
5
+
6
+ The official [Express](https://expressjs.com) middleware for the [InternetData](https://internetdata.io) API.
7
+
8
+ It looks up the visitor behind each request, where they are, which network they come from and whether it's a VPN, a proxy, Tor or a hosting server, and hands the answer to your handlers. Blocking is opt-in.
9
+
10
+ ## Getting Started
11
+
12
+ ```bash
13
+ npm install internetdata-express
14
+ ```
15
+
16
+ Requires Node.js 22 or newer and Express 4.18 or newer. TypeScript types are included.
17
+
18
+ Without an API key a lookup is on Unlimited, the free plan: the country, the network and the company behind the address, Tor, relay, anycast, carrier and satellite space and the service flags, with no daily or monthly cap. Every lookup your app makes comes from your server's one address, though, so a busy site will see bursts refused. A paid plan answers every field, VPN, the proxy flags, hosting, CDN and the city among them; create a key in the [console](https://app.internetdata.io). A free account tries every field, 100 lookups a day.
19
+
20
+ ```js
21
+ import express from 'express';
22
+ import { internetdata } from 'internetdata-express';
23
+
24
+ const app = express();
25
+
26
+ app.set('trust proxy', 'loopback'); // your proxy; see "Where the client address comes from" below
27
+ app.use(internetdata({ apiKey: process.env.INTERNETDATA_API_KEY }));
28
+
29
+ app.get('/', (req, res) => {
30
+ const { result } = req.internetdata;
31
+ res.send(`Hello, visitor from ${result?.location.country_name ?? 'somewhere'}`);
32
+ });
33
+ ```
34
+
35
+ By default nothing is blocked. Every request gets a `req.internetdata` and your own code decides what it means: a currency to show, a sign-up to review, a page to keep from some countries.
36
+
37
+ ## Blocking
38
+
39
+ Pass a `blockCondition` and a matching request is answered with `403` and never reaches your handlers.
40
+
41
+ ```js
42
+ app.use(internetdata({
43
+ apiKey: process.env.INTERNETDATA_API_KEY,
44
+ blockCondition: { location: { country: ['CU', 'IR', 'KP'] } },
45
+ }));
46
+ ```
47
+
48
+ A condition is written in the shape of a result, and only the members you name are considered, so it can refuse on anything in the answer. The country works on every plan, and so do the first two of these:
49
+
50
+ ```js
51
+ blockCondition: { asn: { type: 'hosting' } } // the network's type
52
+ blockCondition: [{ isAnycast: true }, { isSatellite: true }] // anycast and satellite space
53
+ blockCondition: [{ isHosting: true }, { isCdn: true }] // traffic from servers, not people
54
+ blockCondition: [{ isVpn: true }, { isTor: true }, { isResproxy: true }] // anonymity: a list is OR
55
+ blockCondition: { isVpn: true, vpn: { provider: 'nordvpn' } } // one provider
56
+ blockCondition: { resproxy: { hits: { gte: 5 } } } // a numeric threshold
57
+ ```
58
+
59
+ Values are matched by equality, strings without regard to case. An array means any-of. `{ gte, gt, lte, lt }` compares numbers, and every bound you give must hold, so two of them are a range. Members you set to `false` or `null` are ignored, so a condition states the signals you act on; one that constrains nothing would match every request, and is refused when the middleware is created rather than silently blocking all your traffic.
60
+
61
+ Replace the refusal with `onBlocked`:
62
+
63
+ ```js
64
+ app.use(internetdata({
65
+ apiKey: process.env.INTERNETDATA_API_KEY,
66
+ blockCondition: { location: { country: ['CU', 'IR', 'KP'] } },
67
+ onBlocked: (req, res) => res.status(451).render('unavailable'),
68
+ }));
69
+ ```
70
+
71
+ ## Where the client address comes from
72
+
73
+ This is the setting that decides whether any of the above works, and it is the one thing only you can get right.
74
+
75
+ By default the middleware uses `req.ip`, which is Express's own accessor. **Express resolves `req.ip` to the socket peer unless you set `trust proxy`.** So if your app sits behind nginx, a load balancer, or a CDN and you have not set it, every visitor arrives wearing your proxy's address, and that is the address that gets looked up: every visitor gets your proxy's country and network, and if it is a hosting address, a hosting rule blocks everyone. nginx on the same machine is `127.0.0.1` and a load balancer usually has a private address, which the middleware answers locally without a lookup, as an address with no country, and logs a warning.
76
+
77
+ If you are behind a proxy you control, setting Express's own option to that proxy's address is the right fix and everything else here follows from it:
78
+
79
+ ```js
80
+ app.set('trust proxy', 'loopback'); // a proxy on the same machine
81
+ app.set('trust proxy', '10.0.0.0/8'); // or your load balancer's subnet
82
+ ```
83
+
84
+ Name your proxies rather than setting `true`. With `true`, `req.ip` is the left-most `X-Forwarded-For` entry, and the visitor writes that one: nginx, AWS's Application Load Balancer and Cloudflare all append to the header rather than replace it, so a visitor who sends `X-Forwarded-For: 1.1.1.1` is looked up as `1.1.1.1`. A hop count such as `1` is no better, because it believes whoever connects to the app directly. Keep `true` only behind an edge you control that overwrites `X-Forwarded-For`.
85
+
86
+ For an edge that writes the address into its own header, name the header:
87
+
88
+ ```js
89
+ import { headerIpSelector } from 'internetdata-express';
90
+
91
+ app.use(internetdata({
92
+ apiKey: process.env.INTERNETDATA_API_KEY,
93
+ ipSelector: headerIpSelector('CF-Connecting-IP'), // or True-Client-IP, or your own
94
+ }));
95
+ ```
96
+
97
+ `xffIpSelector()` reads `X-Forwarded-For` directly. Be aware that the left-most entry is whatever the caller sent, because proxies append to that header, so it's only trustworthy when an edge you control overwrites it. If you know how many proxies sit in front, count from the right instead: `xffIpSelector({ depth: 1 })` is the address your nearest proxy saw.
98
+
99
+ Anything else, pass your own function. It receives the Express request and returns an address:
100
+
101
+ ```js
102
+ ipSelector: (req) => req.headers['x-real-ip'] ?? req.ip,
103
+ ```
104
+
105
+ If the address resolves to a private one, the middleware says so once on `console.warn`. That is expected on localhost and is the signal to fix your configuration anywhere else.
106
+
107
+ ## When a lookup fails
108
+
109
+ The request is let through, and the reason is recorded on `req.internetdata.error`. Our outage should not become yours, so a network failure, a rate limit or a rejected key all fail open.
110
+
111
+ ```js
112
+ app.get('/', (req, res) => {
113
+ const { result, error } = req.internetdata;
114
+ if (error) {
115
+ req.log.warn({ kind: error.kind }, 'internetdata unavailable');
116
+ }
117
+ res.send(`Hello, visitor from ${result?.location.country_name ?? 'somewhere'}`);
118
+ });
119
+ ```
120
+
121
+ Pass `failClosed: true` to block instead. Private addresses are answered locally and never fail, so this will not lock you out in development.
122
+
123
+ ## Cost and latency
124
+
125
+ Answers are cached per middleware for an hour, so a returning visitor costs nothing, and private addresses never leave the process. A cache miss is one request to our API, bounded at 2500 ms by default and not retried: on a request path, failing open quickly beats holding a visitor while we try again. Both are adjustable, along with the cache itself:
126
+
127
+ ```js
128
+ internetdata({ apiKey: KEY, timeoutMs: 1000, retries: 1, cache: { max: 50000, ttlMs: 600000 } })
129
+ ```
130
+
131
+ Mount it on the routes that matter rather than the whole app, or skip what you do not care about:
132
+
133
+ ```js
134
+ app.use(internetdata({ apiKey: KEY, skip: (req) => req.path.startsWith('/static') }));
135
+ ```
136
+
137
+ If you already hold an `InternetData` client, pass it as `client` and the middleware will share it rather than building a second cache.
138
+
139
+ Beyond a few million distinct visitors a day, stop calling the API per request: look addresses up locally in [our databases](https://internetdata.io/databases) instead.
140
+
141
+ ## Absent is not false
142
+
143
+ Unlimited, with a key or without one, leaves out `isVpn`, `isHosting`, `isCdn` and the four proxy flags, the detail behind them, and the paid members inside `location`, `asn`, `company` and `abuse`, such as `location.city`. A field your plan does not include is `undefined`, which means "not in your plan" rather than "checked, and no".
144
+
145
+ ```js
146
+ req.internetdata.result?.isVpn ?? false // when you only want the flag
147
+ ```
148
+
149
+ A `blockCondition` naming a member your plan does not serve, `location.city` on Unlimited included, can never match, so the middleware warns once instead of failing silently. Set `onMissingField: 'throw'` to make it an error.
150
+
151
+ ## Other Libraries
152
+
153
+ There are official InternetData client libraries available for many languages including PHP, Python, Go, Java, and Ruby. See our GitHub at https://github.com/internetdata for more.
154
+
155
+ ## About InternetData
156
+
157
+ Geolocation, anonymity, ownership and network data for IP addresses, AS numbers and domains, as an API and as databases you download and query yourself.
158
+
159
+ [<img src="https://s3.internetdata.io/internetdata-public/brand/mark.svg" alt="InternetData" height="64"/>](https://internetdata.io/)
160
+
161
+ ## License
162
+
163
+ This project is licensed under the [MIT License](LICENSE).
@@ -0,0 +1,57 @@
1
+ import type { IpSelector, Lookup, MiddlewareOptions } from '@internetdata/internetdata/middleware';
2
+ import type { Request, RequestHandler, Response } from 'express';
3
+ export type { BlockCondition, IpSelector, Lookup, NumericBound, } from '@internetdata/internetdata/middleware';
4
+ declare global {
5
+ namespace Express {
6
+ interface Request {
7
+ /**
8
+ * What the middleware found out about this visitor. Absent when the
9
+ * middleware has not run for this route, or when `skip` claimed it.
10
+ */
11
+ internetdata?: Lookup;
12
+ }
13
+ }
14
+ }
15
+ export interface Options extends MiddlewareOptions<Request> {
16
+ /**
17
+ * How a blocked request is answered. Defaults to `403` with a short JSON
18
+ * body. Whatever you pass must end the response.
19
+ */
20
+ onBlocked?: (req: Request, res: Response, lookup: Lookup) => void;
21
+ }
22
+ /**
23
+ * Look up the visitor and hang the answer off `req.internetdata`.
24
+ *
25
+ * Without a `blockCondition` this only enriches the request and never refuses
26
+ * one, leaving the decision to your own handlers. With one, a matching request
27
+ * is answered by `onBlocked` and never reaches them.
28
+ *
29
+ * A lookup that fails - network, rate limit, an outage of ours - lets the
30
+ * request through and records why on `req.internetdata.error`, unless you set
31
+ * `failClosed`.
32
+ */
33
+ export declare function internetdata(options?: Options): RequestHandler;
34
+ /**
35
+ * `req.ip`, which is the socket peer unless you have set Express's `trust
36
+ * proxy`. Behind a load balancer without it, every visitor looks like the load
37
+ * balancer - so if you are behind one, set it or pick another selector.
38
+ */
39
+ export declare const defaultIpSelector: IpSelector<Request>;
40
+ /**
41
+ * An address from `X-Forwarded-For`.
42
+ *
43
+ * **The left-most entry is whatever the caller sent**, since proxies append, so
44
+ * this is only trustworthy when an edge you control overwrites the header. When
45
+ * you know how many proxies sit in front, count from the right instead:
46
+ * `xffIpSelector({ depth: 1 })` is the address your nearest proxy saw.
47
+ */
48
+ export declare const xffIpSelector: (options?: {
49
+ depth?: number;
50
+ }) => IpSelector<Request>;
51
+ /**
52
+ * An address from a single-value header your edge writes -
53
+ * `headerIpSelector('CF-Connecting-IP')` behind Cloudflare,
54
+ * `headerIpSelector('True-Client-IP')` behind Akamai. Falls back to `req.ip`
55
+ * when the header is absent.
56
+ */
57
+ export declare const headerIpSelector: (name: string) => IpSelector<Request>;
package/dist/index.js ADDED
@@ -0,0 +1,67 @@
1
+ import { bindSelectors, createCore } from '@internetdata/internetdata/middleware';
2
+ /**
3
+ * Look up the visitor and hang the answer off `req.internetdata`.
4
+ *
5
+ * Without a `blockCondition` this only enriches the request and never refuses
6
+ * one, leaving the decision to your own handlers. With one, a matching request
7
+ * is answered by `onBlocked` and never reaches them.
8
+ *
9
+ * A lookup that fails - network, rate limit, an outage of ours - lets the
10
+ * request through and records why on `req.internetdata.error`, unless you set
11
+ * `failClosed`.
12
+ */
13
+ export function internetdata(options = {}) {
14
+ const core = createCore(options, defaultIpSelector);
15
+ const onBlocked = options.onBlocked ?? refuse;
16
+ return (req, res, next) => {
17
+ core.evaluate(req).then((lookup) => {
18
+ if (lookup === undefined) {
19
+ next();
20
+ return;
21
+ }
22
+ req.internetdata = lookup;
23
+ if (lookup.blocked) {
24
+ onBlocked(req, res, lookup);
25
+ return;
26
+ }
27
+ next();
28
+ }, next);
29
+ };
30
+ }
31
+ const view = (req) => ({
32
+ header: (name) => {
33
+ const value = req.headers[name.toLowerCase()];
34
+ return Array.isArray(value) ? value[0] : value;
35
+ },
36
+ frameworkIp: () => req.ip,
37
+ });
38
+ // Each of these is annotated rather than inferred: the inferred shape reaches
39
+ // through `@types/express` into its own transitive types, which TypeScript
40
+ // refuses to name in a declaration file a consumer would have to resolve.
41
+ const selectors = bindSelectors(view);
42
+ /**
43
+ * `req.ip`, which is the socket peer unless you have set Express's `trust
44
+ * proxy`. Behind a load balancer without it, every visitor looks like the load
45
+ * balancer - so if you are behind one, set it or pick another selector.
46
+ */
47
+ export const defaultIpSelector = selectors.defaultIpSelector;
48
+ /**
49
+ * An address from `X-Forwarded-For`.
50
+ *
51
+ * **The left-most entry is whatever the caller sent**, since proxies append, so
52
+ * this is only trustworthy when an edge you control overwrites the header. When
53
+ * you know how many proxies sit in front, count from the right instead:
54
+ * `xffIpSelector({ depth: 1 })` is the address your nearest proxy saw.
55
+ */
56
+ export const xffIpSelector = selectors.xffIpSelector;
57
+ /**
58
+ * An address from a single-value header your edge writes -
59
+ * `headerIpSelector('CF-Connecting-IP')` behind Cloudflare,
60
+ * `headerIpSelector('True-Client-IP')` behind Akamai. Falls back to `req.ip`
61
+ * when the header is absent.
62
+ */
63
+ export const headerIpSelector = selectors.headerIpSelector;
64
+ function refuse(_req, res) {
65
+ res.status(403).json({ error: 'access denied' });
66
+ }
67
+ //# sourceMappingURL=index.js.map
@@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AA8E;AAC9E,2EAA2E;AAC3E,0EAA0E;AAC1E,MAAM,SAAS,GAAG,aAAa,CAAU,IAAI,CAAC,CAAC;AAE/C;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAwB,SAAS,CAAC,iBAAiB,CAAC;AAElF;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,aAAa,GACpB,SAAS,CAAC,aAAa,CAAC;AAE9B;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gBAAgB,GACvB,SAAS,CAAC,gBAAgB,CAAC;AAEjC,SAAS,MAAM,CAAC,IAAa,EAAE,GAAa;IACxC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC,CAAC;AACrD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "internetdata-express",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.1",
4
+ "description": "Official Express middleware for the InternetData API. Look up the visitor behind every request: location, network, VPN, proxy, Tor and hosting.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "homepage": "https://internetdata.io",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/internetdata/sdk-nodejs-expressjs.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/internetdata/sdk-nodejs-expressjs/issues"
14
+ },
15
+ "keywords": [
16
+ "express",
17
+ "express-middleware",
18
+ "middleware",
19
+ "ip-geolocation",
20
+ "ip-intelligence",
21
+ "ip-lookup",
22
+ "geoblocking",
23
+ "vpn-detection",
24
+ "proxy-detection",
25
+ "tor",
26
+ "hosting",
27
+ "asn"
28
+ ],
29
+ "main": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ },
36
+ "./package.json": "./package.json"
37
+ },
38
+ "files": [
39
+ "dist",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "engines": {
44
+ "node": ">=22"
45
+ },
46
+ "dependencies": {
47
+ "@internetdata/internetdata": "^2.10.1"
48
+ },
49
+ "peerDependencies": {
50
+ "express": ">=4.18"
51
+ },
52
+ "devDependencies": {
53
+ "@mslmio/eslint-config": "^1.1.0",
54
+ "@types/express": "^5.0.0",
55
+ "@types/node": "^26.2.0",
56
+ "eslint": "^10.10.0",
57
+ "express": "^5.2.1",
58
+ "typescript": "^6.0.3"
59
+ },
60
+ "scripts": {
61
+ "build": "rm -rf dist && tsc",
62
+ "lint": "eslint",
63
+ "test": "pnpm run build && node --test test/*.test.mjs"
64
+ }
6
65
  }