@idevconn/allowlist-guard 0.0.0-stage → 0.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 +201 -0
- package/README.md +229 -2
- package/dist/chunk-POEP4ARO.js +63 -0
- package/dist/chunk-POEP4ARO.js.map +1 -0
- package/dist/fastify.cjs +94 -0
- package/dist/fastify.cjs.map +1 -0
- package/dist/fastify.d.cts +44 -0
- package/dist/fastify.d.ts +44 -0
- package/dist/fastify.js +25 -0
- package/dist/fastify.js.map +1 -0
- package/dist/index.cjs +189 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +70 -0
- package/dist/index.d.ts +70 -0
- package/dist/index.js +115 -0
- package/dist/index.js.map +1 -0
- package/dist/ip-matcher-D4MA1kIq.d.cts +22 -0
- package/dist/ip-matcher-D4MA1kIq.d.ts +22 -0
- package/package.json +95 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by interface) to the interfaces
|
|
46
|
+
of, the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 iDEVconn
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,230 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @idevconn/allowlist-guard
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Global NestJS guard that restricts routes by **source IP / CIDR**. Two independent allowlists: one for protected (authenticated) routes, one for public ("open") routes. Works on Fastify and Express. No runtime dependencies (uses `node:net` `BlockList`).
|
|
4
|
+
|
|
5
|
+
> [!IMPORTANT]
|
|
6
|
+
> **What this guard does NOT protect against.**
|
|
7
|
+
> It decides by the caller's **IP address only**. It does **not** stop Postman, curl, scripts or Playwright/Puppeteer **coming from an allowed IP** — to the server those requests look exactly like your own front end:
|
|
8
|
+
>
|
|
9
|
+
> - `Origin`, `Referer`, `User-Agent` and `Sec-Fetch-*` headers are trivially forged by Postman/curl, so header checks give no protection.
|
|
10
|
+
> - Playwright/Puppeteer drive a real Chromium; headers and fingerprint are indistinguishable from a human's browser.
|
|
11
|
+
> - A secret embedded in a front-end bundle (API key, HMAC) is extractable in a minute.
|
|
12
|
+
> - Anyone with a valid login can replay requests from a script.
|
|
13
|
+
>
|
|
14
|
+
> The allowlist only helps when your legitimate clients have **known, stable IPs** (office, VPN, your own servers): a request from anywhere else gets `403`. For an **open** API (any user from the internet) an IP list is the wrong tool — use authentication, per-account rate limits and quotas, CAPTCHA / bot protection at the edge (e.g. Cloudflare Turnstile / Bot Management), and registration controls. Treat this guard as an outer perimeter, not as bot protection.
|
|
15
|
+
|
|
16
|
+
## Features
|
|
17
|
+
|
|
18
|
+
- IPv4 + IPv6, single addresses and CIDR ranges; IPv4-mapped IPv6 (`::ffff:1.2.3.4`) is normalised.
|
|
19
|
+
- Separate lists for `protected` and `public` routes. A list that is unset/blank is **not enforced**, so adopting the guard is non-breaking.
|
|
20
|
+
- Loopback (`127.0.0.0/8`, `::1`) is allowed once a list is set (local dev, health probes) — disable with `allowLoopback: false` (see below).
|
|
21
|
+
- `@SkipIpAllowlist()` exempts a route or controller (e.g. HMAC-signed provider webhooks whose IPs you cannot pin).
|
|
22
|
+
- A malformed entry throws at boot naming the option — a typo never silently becomes "everyone allowed" or "everyone blocked".
|
|
23
|
+
- Rejects with `403 ip_not_allowed`. Default log line is rate-limited per IP (1/min, bounded memory, never echoes malformed input); `onBlocked` is called on **every** blocked request for metrics/alerting.
|
|
24
|
+
- Fails closed: only microservice (`rpc`) contexts are exempt; other non-HTTP contexts (GraphQL, WebSocket) have no resolvable `req.ip` and are denied while a list is enforced.
|
|
25
|
+
- `/fastify` subpath: `buildTrustProxy` and `restrictRoutesToAllowlist` (for routes outside Nest's guard pipeline, e.g. Swagger UI).
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npm install @idevconn/allowlist-guard
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Peer dependencies: `@nestjs/common`, `@nestjs/core` (10 or 11), `reflect-metadata`, `rxjs`. The `/fastify` subpath has no `fastify` dependency (it is typed structurally).
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
### Minimal (NestJS on Express, the default adapter)
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
// app.module.ts
|
|
41
|
+
import { Module } from "@nestjs/common";
|
|
42
|
+
import { IpAllowlistModule } from "@idevconn/allowlist-guard";
|
|
43
|
+
import { AuthModule } from "./auth/auth.module";
|
|
44
|
+
|
|
45
|
+
@Module({
|
|
46
|
+
imports: [
|
|
47
|
+
// Import BEFORE the module that registers your auth guard, so a blocked IP
|
|
48
|
+
// is rejected before any authentication work.
|
|
49
|
+
IpAllowlistModule.forRoot({
|
|
50
|
+
protected: "203.0.113.5, 10.0.0.0/8, 2001:db8::/32", // authenticated routes
|
|
51
|
+
public: "198.51.100.0/24", // @Public routes: login, lead capture, ...
|
|
52
|
+
}),
|
|
53
|
+
AuthModule,
|
|
54
|
+
],
|
|
55
|
+
})
|
|
56
|
+
export class AppModule {}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
// main.ts
|
|
61
|
+
import { NestFactory } from "@nestjs/core";
|
|
62
|
+
import type { NestExpressApplication } from "@nestjs/platform-express";
|
|
63
|
+
import { AppModule } from "./app.module";
|
|
64
|
+
|
|
65
|
+
async function bootstrap() {
|
|
66
|
+
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
|
67
|
+
app.set("trust proxy", 1); // behind ONE reverse proxy; see "Getting the real client IP"
|
|
68
|
+
await app.listen(3000);
|
|
69
|
+
}
|
|
70
|
+
bootstrap();
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Options
|
|
74
|
+
|
|
75
|
+
| Option | Meaning |
|
|
76
|
+
| ------------------- | ---------------------------------------------------------------------------------------------------- |
|
|
77
|
+
| `protected` | Comma-separated string or array of IPs/CIDRs for non-public routes. Unset/blank = not enforced. |
|
|
78
|
+
| `public` | Same, for public routes. |
|
|
79
|
+
| `publicMetadataKey` | Metadata key marking a route public. Default `'isPublic'` (the common `@Public()` decorator's key). |
|
|
80
|
+
| `allowLoopback` | Default `true`. Set `false` if a reverse proxy runs on the same host (see below). |
|
|
81
|
+
| `onBlocked` | `(ip) => void`, called on every blocked request. Default: a rate-limited Nest `Logger.warn`. |
|
|
82
|
+
|
|
83
|
+
**The two lists are independent.** Setting only `protected` leaves `@Public` routes (login, lead capture, ...) open to everyone, and vice versa. Set both if you want the whole surface restricted; exempt individual routes with `@SkipIpAllowlist()`.
|
|
84
|
+
|
|
85
|
+
### Configuration from the environment (`@nestjs/config`)
|
|
86
|
+
|
|
87
|
+
`forRoot()` takes plain values, so read them from `process.env`. `ConfigModule.forRoot()` loads `.env` synchronously, so list it **before** the allowlist module:
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
@Module({
|
|
91
|
+
imports: [
|
|
92
|
+
ConfigModule.forRoot({ isGlobal: true }),
|
|
93
|
+
IpAllowlistModule.forRoot({
|
|
94
|
+
protected: process.env.API_IP_ALLOWLIST, // unset/blank => not enforced
|
|
95
|
+
public: process.env.API_PUBLIC_IP_ALLOWLIST,
|
|
96
|
+
allowLoopback: process.env.API_IP_ALLOWLIST_ALLOW_LOOPBACK !== "false",
|
|
97
|
+
}),
|
|
98
|
+
AuthModule,
|
|
99
|
+
],
|
|
100
|
+
})
|
|
101
|
+
export class AppModule {}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
# .env
|
|
106
|
+
API_IP_ALLOWLIST=203.0.113.5,10.0.0.0/8
|
|
107
|
+
API_PUBLIC_IP_ALLOWLIST=198.51.100.0/24
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
A malformed entry (`API_IP_ALLOWLIST=203.0.113.5,banana`) throws at boot naming the option, so a typo never silently opens or closes the API.
|
|
111
|
+
|
|
112
|
+
### NestJS on Fastify
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
// main.ts
|
|
116
|
+
import { NestFactory } from "@nestjs/core";
|
|
117
|
+
import { FastifyAdapter, type NestFastifyApplication } from "@nestjs/platform-fastify";
|
|
118
|
+
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
|
|
119
|
+
import { buildTrustProxy, parseIpAllowlist, restrictRoutesToAllowlist } from "@idevconn/allowlist-guard/fastify";
|
|
120
|
+
import { AppModule } from "./app.module";
|
|
121
|
+
|
|
122
|
+
async function bootstrap() {
|
|
123
|
+
const app = await NestFactory.create<NestFastifyApplication>(
|
|
124
|
+
AppModule,
|
|
125
|
+
new FastifyAdapter({
|
|
126
|
+
// One trusted hop, and only when the socket peer is one of YOUR proxies.
|
|
127
|
+
trustProxy: buildTrustProxy(process.env.TRUSTED_PROXIES),
|
|
128
|
+
}),
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
// Swagger UI is a Fastify route outside Nest's guard pipeline: restrict it too,
|
|
132
|
+
// BEFORE SwaggerModule.setup registers it.
|
|
133
|
+
const allowed = parseIpAllowlist(process.env.API_IP_ALLOWLIST);
|
|
134
|
+
if (allowed) {
|
|
135
|
+
restrictRoutesToAllowlist(app.getHttpAdapter().getInstance(), allowed, "/api/docs");
|
|
136
|
+
}
|
|
137
|
+
const document = SwaggerModule.createDocument(app, new DocumentBuilder().build());
|
|
138
|
+
SwaggerModule.setup("api/docs", app, document);
|
|
139
|
+
|
|
140
|
+
await app.listen(3000, "0.0.0.0");
|
|
141
|
+
}
|
|
142
|
+
bootstrap();
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### Exempting routes
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
import { Controller, Post, SetMetadata } from "@nestjs/common";
|
|
149
|
+
import { SkipIpAllowlist } from "@idevconn/allowlist-guard";
|
|
150
|
+
|
|
151
|
+
const Public = () => SetMetadata("isPublic", true); // your existing @Public()
|
|
152
|
+
|
|
153
|
+
@Controller("webhooks")
|
|
154
|
+
export class WebhooksController {
|
|
155
|
+
// Providers call from IPs you cannot pin; authenticate by HMAC signature instead.
|
|
156
|
+
@Public()
|
|
157
|
+
@SkipIpAllowlist()
|
|
158
|
+
@Post(":provider")
|
|
159
|
+
receive() {}
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`@SkipIpAllowlist()` also works on a whole controller class (e.g. a health check controller).
|
|
164
|
+
|
|
165
|
+
### Using your own "public" decorator
|
|
166
|
+
|
|
167
|
+
If your project marks open routes with a different metadata key, tell the guard:
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
export const OPEN_ROUTE = "openRoute";
|
|
171
|
+
export const Open = () => SetMetadata(OPEN_ROUTE, true);
|
|
172
|
+
|
|
173
|
+
IpAllowlistModule.forRoot({ public: "198.51.100.0/24", publicMetadataKey: OPEN_ROUTE });
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### Alerting on blocked requests
|
|
177
|
+
|
|
178
|
+
`onBlocked` runs on **every** blocked request (the default log line is rate-limited to one per IP per minute), so feed metrics from it:
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
IpAllowlistModule.forRoot({
|
|
182
|
+
protected: process.env.API_IP_ALLOWLIST,
|
|
183
|
+
onBlocked: (ip) => metrics.increment("ip_allowlist.blocked", { ip: ip ?? "unknown" }),
|
|
184
|
+
});
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Using the matcher on its own
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
import { parseIpAllowlist } from "@idevconn/allowlist-guard";
|
|
191
|
+
|
|
192
|
+
const isAllowed = parseIpAllowlist("203.0.113.5, 10.0.0.0/8", "myList");
|
|
193
|
+
isAllowed?.("10.4.5.6"); // true (returns null when the list is blank = not enforced)
|
|
194
|
+
isAllowed?.("::ffff:203.0.113.5"); // true (IPv4-mapped IPv6 is normalised)
|
|
195
|
+
isAllowed?.("8.8.8.8"); // false
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
### Local development and tests
|
|
199
|
+
|
|
200
|
+
Leave the lists unset: nothing is enforced, so `localhost`, Postman and e2e tests work as usual. With a list set, loopback (`127.0.0.1`, `::1`) is still allowed unless `allowLoopback: false`. In e2e tests either leave the lists unset or set `protected` to a test IP and send requests from it (Fastify `app.inject({ remoteAddress })`; Express with `trust proxy` + `X-Forwarded-For`).
|
|
201
|
+
|
|
202
|
+
## Getting the real client IP (read this)
|
|
203
|
+
|
|
204
|
+
The guard reads `request.ip` and **never** parses `X-Forwarded-For` itself. Behind a reverse proxy/load balancer, configure your framework's trust-proxy setting so `req.ip` is the real client:
|
|
205
|
+
|
|
206
|
+
- **Express:** `app.set("trust proxy", 1)` (one proxy in front).
|
|
207
|
+
- **Fastify:** `buildTrustProxy(...)` from `@idevconn/allowlist-guard/fastify` (see the Fastify example above). It trusts one hop. Hop 0 is the socket peer, so **if the app port is reachable directly, any client can forge `X-Forwarded-For` and pass the allowlist**. Either make the port reachable only via your proxy, or pass `trustedProxies` (the proxy's IP/CIDR) so a direct client's header is ignored.
|
|
208
|
+
|
|
209
|
+
Make the proxy **overwrite** the header with the address it saw, not append to a client-supplied one. nginx:
|
|
210
|
+
|
|
211
|
+
```nginx
|
|
212
|
+
location /api/ {
|
|
213
|
+
proxy_pass http://127.0.0.1:3000;
|
|
214
|
+
proxy_set_header X-Forwarded-For $remote_addr; # overwrite, do not use $proxy_add_x_forwarded_for
|
|
215
|
+
}
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
Without any trust-proxy setting `req.ip` is the proxy's own address for every client. If that proxy runs on the **same host**, that address is loopback — which is allowed by default, so the allowlist would be wide open. Set `allowLoopback: false` in that setup (and keep trust-proxy configured). Behind a CDN (e.g. Cloudflare) the proxy chain has two hops; configure the trusted hop count/CIDRs of your CDN accordingly rather than trusting arbitrary headers.
|
|
219
|
+
|
|
220
|
+
## Routes outside Nest (Swagger UI)
|
|
221
|
+
|
|
222
|
+
Fastify-native routes never reach Nest guards; `restrictRoutesToAllowlist` (see the Fastify example) applies the same list to them. It matches on the resolved route (`routeOptions.url`), not the raw URL, so percent-encoded paths such as `/api/%64ocs` cannot slip past.
|
|
223
|
+
|
|
224
|
+
## Limits
|
|
225
|
+
|
|
226
|
+
See the notice at the top: an IP allowlist is a network perimeter, not bot protection. It cannot tell a browser from Postman or Playwright on the same IP.
|
|
227
|
+
|
|
228
|
+
## License
|
|
229
|
+
|
|
230
|
+
Apache-2.0
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __decorateClass = (decorators, target, key, kind) => {
|
|
4
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
5
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
6
|
+
if (decorator = decorators[i])
|
|
7
|
+
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
8
|
+
if (kind && result) __defProp(target, key, result);
|
|
9
|
+
return result;
|
|
10
|
+
};
|
|
11
|
+
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
12
|
+
|
|
13
|
+
// src/ip-matcher.ts
|
|
14
|
+
import { BlockList, isIP } from "net";
|
|
15
|
+
var LOOPBACK = ["127.0.0.0/8", "::1"];
|
|
16
|
+
function normalizeIp(ip) {
|
|
17
|
+
const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(ip);
|
|
18
|
+
return mapped?.[1] ?? ip;
|
|
19
|
+
}
|
|
20
|
+
function addEntry(list, raw) {
|
|
21
|
+
const [addr = "", prefix, ...rest] = raw.split("/");
|
|
22
|
+
const family = isIP(addr);
|
|
23
|
+
if (!family || addr.includes("%") || rest.length > 0) {
|
|
24
|
+
throw new Error(`invalid IP/CIDR "${raw}"`);
|
|
25
|
+
}
|
|
26
|
+
const type = family === 4 ? "ipv4" : "ipv6";
|
|
27
|
+
if (prefix === void 0) {
|
|
28
|
+
list.addAddress(addr, type);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
const bits = Number(prefix);
|
|
32
|
+
const max = family === 4 ? 32 : 128;
|
|
33
|
+
if (!/^\d+$/.test(prefix) || bits > max) throw new Error(`invalid IP/CIDR "${raw}"`);
|
|
34
|
+
list.addSubnet(addr, bits, type);
|
|
35
|
+
}
|
|
36
|
+
function parseIpAllowlist(value, label = "allowlist", { allowLoopback = true } = {}) {
|
|
37
|
+
const raw = typeof value === "string" ? value.split(",") : value ?? [];
|
|
38
|
+
const entries = raw.map((s) => s.trim()).filter(Boolean);
|
|
39
|
+
if (entries.length === 0) return null;
|
|
40
|
+
const list = new BlockList();
|
|
41
|
+
for (const entry of [...allowLoopback ? LOOPBACK : [], ...entries]) {
|
|
42
|
+
try {
|
|
43
|
+
addEntry(list, entry);
|
|
44
|
+
} catch (err) {
|
|
45
|
+
throw new Error(`${label}: ${err.message}`, { cause: err });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return (ip) => {
|
|
49
|
+
if (!ip || ip.includes("%")) return false;
|
|
50
|
+
const addr = normalizeIp(ip);
|
|
51
|
+
const family = isIP(addr);
|
|
52
|
+
if (!family) return false;
|
|
53
|
+
return list.check(addr, family === 4 ? "ipv4" : "ipv6");
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export {
|
|
58
|
+
__decorateClass,
|
|
59
|
+
__decorateParam,
|
|
60
|
+
normalizeIp,
|
|
61
|
+
parseIpAllowlist
|
|
62
|
+
};
|
|
63
|
+
//# sourceMappingURL=chunk-POEP4ARO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ip-matcher.ts"],"sourcesContent":["import { BlockList, isIP } from \"node:net\";\n\nexport type IpMatcher = (ip: string | undefined) => boolean;\n\nexport interface ParseOptions {\n /**\n * Always allow loopback (`127.0.0.0/8`, `::1`) once a list is set. Default `true`\n * (local dev, health probes). Set `false` when a reverse proxy runs on the SAME\n * host and `req.ip` may fall back to its loopback address — otherwise a proxy\n * without trust-proxy configured makes every client look like 127.0.0.1.\n */\n allowLoopback?: boolean;\n}\n\nconst LOOPBACK = [\"127.0.0.0/8\", \"::1\"] as const;\n\n/** `::ffff:1.2.3.4` (what a dual-stack socket reports for IPv4 peers) → `1.2.3.4`. */\nexport function normalizeIp(ip: string): string {\n const mapped = /^::ffff:(\\d{1,3}(?:\\.\\d{1,3}){3})$/i.exec(ip);\n return mapped?.[1] ?? ip;\n}\n\nfunction addEntry(list: BlockList, raw: string): void {\n const [addr = \"\", prefix, ...rest] = raw.split(\"/\");\n const family = isIP(addr);\n // A zone id (`fe80::1%eth0`) is accepted by isIP but ignored by BlockList.check,\n // so `::1%x` would match loopback — never allow one in a list or as a client IP.\n if (!family || addr.includes(\"%\") || rest.length > 0) {\n throw new Error(`invalid IP/CIDR \"${raw}\"`);\n }\n const type = family === 4 ? \"ipv4\" : \"ipv6\";\n if (prefix === undefined) {\n list.addAddress(addr, type);\n return;\n }\n const bits = Number(prefix);\n const max = family === 4 ? 32 : 128;\n if (!/^\\d+$/.test(prefix) || bits > max) throw new Error(`invalid IP/CIDR \"${raw}\"`);\n list.addSubnet(addr, bits, type);\n}\n\n/**\n * Builds a matcher from a comma-separated string or an array of IPs/CIDRs\n * (IPv4 + IPv6). Returns `null` when the list is unset/blank (= not enforced).\n * Loopback is part of an enforced list by default (see `allowLoopback`). Throws on a malformed entry — a typo must not silently turn\n * into \"everyone allowed\" or \"everyone blocked\". `label` names the option in\n * the error message.\n */\nexport function parseIpAllowlist(\n value: string | readonly string[] | undefined,\n label = \"allowlist\",\n { allowLoopback = true }: ParseOptions = {},\n): IpMatcher | null {\n const raw = typeof value === \"string\" ? value.split(\",\") : (value ?? []);\n const entries = raw.map((s) => s.trim()).filter(Boolean);\n if (entries.length === 0) return null;\n\n const list = new BlockList();\n for (const entry of [...(allowLoopback ? LOOPBACK : []), ...entries]) {\n try {\n addEntry(list, entry);\n } catch (err) {\n throw new Error(`${label}: ${(err as Error).message}`, { cause: err });\n }\n }\n return (ip) => {\n if (!ip || ip.includes(\"%\")) return false;\n const addr = normalizeIp(ip);\n const family = isIP(addr);\n if (!family) return false;\n return list.check(addr, family === 4 ? \"ipv4\" : \"ipv6\");\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,WAAW,YAAY;AAchC,IAAM,WAAW,CAAC,eAAe,KAAK;AAG/B,SAAS,YAAY,IAAoB;AAC9C,QAAM,SAAS,sCAAsC,KAAK,EAAE;AAC5D,SAAO,SAAS,CAAC,KAAK;AACxB;AAEA,SAAS,SAAS,MAAiB,KAAmB;AACpD,QAAM,CAAC,OAAO,IAAI,QAAQ,GAAG,IAAI,IAAI,IAAI,MAAM,GAAG;AAClD,QAAM,SAAS,KAAK,IAAI;AAGxB,MAAI,CAAC,UAAU,KAAK,SAAS,GAAG,KAAK,KAAK,SAAS,GAAG;AACpD,UAAM,IAAI,MAAM,oBAAoB,GAAG,GAAG;AAAA,EAC5C;AACA,QAAM,OAAO,WAAW,IAAI,SAAS;AACrC,MAAI,WAAW,QAAW;AACxB,SAAK,WAAW,MAAM,IAAI;AAC1B;AAAA,EACF;AACA,QAAM,OAAO,OAAO,MAAM;AAC1B,QAAM,MAAM,WAAW,IAAI,KAAK;AAChC,MAAI,CAAC,QAAQ,KAAK,MAAM,KAAK,OAAO,IAAK,OAAM,IAAI,MAAM,oBAAoB,GAAG,GAAG;AACnF,OAAK,UAAU,MAAM,MAAM,IAAI;AACjC;AASO,SAAS,iBACd,OACA,QAAQ,aACR,EAAE,gBAAgB,KAAK,IAAkB,CAAC,GACxB;AAClB,QAAM,MAAM,OAAO,UAAU,WAAW,MAAM,MAAM,GAAG,IAAK,SAAS,CAAC;AACtE,QAAM,UAAU,IAAI,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,OAAO;AACvD,MAAI,QAAQ,WAAW,EAAG,QAAO;AAEjC,QAAM,OAAO,IAAI,UAAU;AAC3B,aAAW,SAAS,CAAC,GAAI,gBAAgB,WAAW,CAAC,GAAI,GAAG,OAAO,GAAG;AACpE,QAAI;AACF,eAAS,MAAM,KAAK;AAAA,IACtB,SAAS,KAAK;AACZ,YAAM,IAAI,MAAM,GAAG,KAAK,KAAM,IAAc,OAAO,IAAI,EAAE,OAAO,IAAI,CAAC;AAAA,IACvE;AAAA,EACF;AACA,SAAO,CAAC,OAAO;AACb,QAAI,CAAC,MAAM,GAAG,SAAS,GAAG,EAAG,QAAO;AACpC,UAAM,OAAO,YAAY,EAAE;AAC3B,UAAM,SAAS,KAAK,IAAI;AACxB,QAAI,CAAC,OAAQ,QAAO;AACpB,WAAO,KAAK,MAAM,MAAM,WAAW,IAAI,SAAS,MAAM;AAAA,EACxD;AACF;","names":[]}
|
package/dist/fastify.cjs
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/fastify/index.ts
|
|
21
|
+
var fastify_exports = {};
|
|
22
|
+
__export(fastify_exports, {
|
|
23
|
+
buildTrustProxy: () => buildTrustProxy,
|
|
24
|
+
parseIpAllowlist: () => parseIpAllowlist,
|
|
25
|
+
restrictRoutesToAllowlist: () => restrictRoutesToAllowlist
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(fastify_exports);
|
|
28
|
+
|
|
29
|
+
// src/ip-matcher.ts
|
|
30
|
+
var import_node_net = require("net");
|
|
31
|
+
var LOOPBACK = ["127.0.0.0/8", "::1"];
|
|
32
|
+
function normalizeIp(ip) {
|
|
33
|
+
const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(ip);
|
|
34
|
+
return mapped?.[1] ?? ip;
|
|
35
|
+
}
|
|
36
|
+
function addEntry(list, raw) {
|
|
37
|
+
const [addr = "", prefix, ...rest] = raw.split("/");
|
|
38
|
+
const family = (0, import_node_net.isIP)(addr);
|
|
39
|
+
if (!family || addr.includes("%") || rest.length > 0) {
|
|
40
|
+
throw new Error(`invalid IP/CIDR "${raw}"`);
|
|
41
|
+
}
|
|
42
|
+
const type = family === 4 ? "ipv4" : "ipv6";
|
|
43
|
+
if (prefix === void 0) {
|
|
44
|
+
list.addAddress(addr, type);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const bits = Number(prefix);
|
|
48
|
+
const max = family === 4 ? 32 : 128;
|
|
49
|
+
if (!/^\d+$/.test(prefix) || bits > max) throw new Error(`invalid IP/CIDR "${raw}"`);
|
|
50
|
+
list.addSubnet(addr, bits, type);
|
|
51
|
+
}
|
|
52
|
+
function parseIpAllowlist(value, label = "allowlist", { allowLoopback = true } = {}) {
|
|
53
|
+
const raw = typeof value === "string" ? value.split(",") : value ?? [];
|
|
54
|
+
const entries = raw.map((s) => s.trim()).filter(Boolean);
|
|
55
|
+
if (entries.length === 0) return null;
|
|
56
|
+
const list = new import_node_net.BlockList();
|
|
57
|
+
for (const entry of [...allowLoopback ? LOOPBACK : [], ...entries]) {
|
|
58
|
+
try {
|
|
59
|
+
addEntry(list, entry);
|
|
60
|
+
} catch (err) {
|
|
61
|
+
throw new Error(`${label}: ${err.message}`, { cause: err });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return (ip) => {
|
|
65
|
+
if (!ip || ip.includes("%")) return false;
|
|
66
|
+
const addr = normalizeIp(ip);
|
|
67
|
+
const family = (0, import_node_net.isIP)(addr);
|
|
68
|
+
if (!family) return false;
|
|
69
|
+
return list.check(addr, family === 4 ? "ipv4" : "ipv6");
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// src/fastify/index.ts
|
|
74
|
+
function buildTrustProxy(trustedProxies) {
|
|
75
|
+
const matcher = parseIpAllowlist(trustedProxies, "trustedProxies");
|
|
76
|
+
return (address, hop) => hop === 0 && (!matcher || matcher(address));
|
|
77
|
+
}
|
|
78
|
+
function restrictRoutesToAllowlist(instance, allowed, routePrefix) {
|
|
79
|
+
instance.addHook("onRequest", (req, reply, done) => {
|
|
80
|
+
const route = req.routeOptions?.url ?? "";
|
|
81
|
+
if (route.startsWith(routePrefix) && !allowed(req.ip)) {
|
|
82
|
+
void reply.code(403).send({ statusCode: 403, message: "ip_not_allowed" });
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
done();
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
89
|
+
0 && (module.exports = {
|
|
90
|
+
buildTrustProxy,
|
|
91
|
+
parseIpAllowlist,
|
|
92
|
+
restrictRoutesToAllowlist
|
|
93
|
+
});
|
|
94
|
+
//# sourceMappingURL=fastify.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/fastify/index.ts","../src/ip-matcher.ts"],"sourcesContent":["import { parseIpAllowlist, type IpMatcher } from \"../ip-matcher.js\";\n\n/**\n * Fastify `trustProxy` function equal to Express's `trust proxy = 1`: trusts\n * only hop 0 (the socket peer, i.e. your reverse proxy), so a client cannot\n * walk past it with extra X-Forwarded-For entries.\n *\n * Hop 0 is the socket peer itself: if the app port is reachable directly (not\n * only through the proxy), ANY client is hop 0 and can forge X-Forwarded-For,\n * defeating the allowlist. Pass `trustedProxies` (IPs/CIDRs of your proxy) to\n * trust hop 0 only when the peer is one of them; a direct client's header is\n * then ignored. Loopback is always included.\n */\nexport function buildTrustProxy(\n trustedProxies?: string | readonly string[],\n): (address: string, hop: number) => boolean {\n const matcher = parseIpAllowlist(trustedProxies, \"trustedProxies\");\n return (address, hop) => hop === 0 && (!matcher || matcher(address));\n}\n\n/**\n * Structural slice of a Fastify instance — deliberately not `FastifyInstance`, so\n * it type-checks even when the app and `@nestjs/platform-fastify` resolve two\n * different copies of `fastify`.\n */\nexport interface FastifyHookHost {\n addHook(\n name: \"onRequest\",\n hook: (\n req: { ip: string; routeOptions?: { url?: string } },\n reply: { code(statusCode: number): { send(payload: unknown): unknown } },\n done: () => void,\n ) => void,\n ): unknown;\n}\n\n/**\n * Restricts Fastify-native routes that live outside Nest's guard pipeline\n * (e.g. Swagger UI under `/api/docs`) with the same allowlist. Register BEFORE\n * those routes are added.\n *\n * Matches on the ROUTE Fastify resolved (`routeOptions.url`), not the raw\n * `req.url`: Fastify percent-decodes the path before routing, so `/api/%64ocs`\n * reaches the docs handler while `req.url.startsWith('/api/docs')` is false.\n */\nexport function restrictRoutesToAllowlist(\n instance: FastifyHookHost,\n allowed: IpMatcher,\n routePrefix: string,\n): void {\n instance.addHook(\"onRequest\", (req, reply, done) => {\n const route = req.routeOptions?.url ?? \"\";\n if (route.startsWith(routePrefix) && !allowed(req.ip)) {\n void reply.code(403).send({ statusCode: 403, message: \"ip_not_allowed\" });\n return;\n }\n done();\n });\n}\n\nexport { parseIpAllowlist, type IpMatcher } from \"../ip-matcher.js\";\n","import { BlockList, isIP } from \"node:net\";\n\nexport type IpMatcher = (ip: string | undefined) => boolean;\n\nexport interface ParseOptions {\n /**\n * Always allow loopback (`127.0.0.0/8`, `::1`) once a list is set. Default `true`\n * (local dev, health probes). Set `false` when a reverse proxy runs on the SAME\n * host and `req.ip` may fall back to its loopback address — otherwise a proxy\n * without trust-proxy configured makes every client look like 127.0.0.1.\n */\n allowLoopback?: boolean;\n}\n\nconst LOOPBACK = [\"127.0.0.0/8\", \"::1\"] as const;\n\n/** `::ffff:1.2.3.4` (what a dual-stack socket reports for IPv4 peers) → `1.2.3.4`. */\nexport function normalizeIp(ip: string): string {\n const mapped = /^::ffff:(\\d{1,3}(?:\\.\\d{1,3}){3})$/i.exec(ip);\n return mapped?.[1] ?? ip;\n}\n\nfunction addEntry(list: BlockList, raw: string): void {\n const [addr = \"\", prefix, ...rest] = raw.split(\"/\");\n const family = isIP(addr);\n // A zone id (`fe80::1%eth0`) is accepted by isIP but ignored by BlockList.check,\n // so `::1%x` would match loopback — never allow one in a list or as a client IP.\n if (!family || addr.includes(\"%\") || rest.length > 0) {\n throw new Error(`invalid IP/CIDR \"${raw}\"`);\n }\n const type = family === 4 ? \"ipv4\" : \"ipv6\";\n if (prefix === undefined) {\n list.addAddress(addr, type);\n return;\n }\n const bits = Number(prefix);\n const max = family === 4 ? 32 : 128;\n if (!/^\\d+$/.test(prefix) || bits > max) throw new Error(`invalid IP/CIDR \"${raw}\"`);\n list.addSubnet(addr, bits, type);\n}\n\n/**\n * Builds a matcher from a comma-separated string or an array of IPs/CIDRs\n * (IPv4 + IPv6). Returns `null` when the list is unset/blank (= not enforced).\n * Loopback is part of an enforced list by default (see `allowLoopback`). Throws on a malformed entry — a typo must not silently turn\n * into \"everyone allowed\" or \"everyone blocked\". `label` names the option in\n * the error message.\n */\nexport function parseIpAllowlist(\n value: string | readonly string[] | undefined,\n label = \"allowlist\",\n { allowLoopback = true }: ParseOptions = {},\n): IpMatcher | null {\n const raw = typeof value === \"string\" ? value.split(\",\") : (value ?? []);\n const entries = raw.map((s) => s.trim()).filter(Boolean);\n if (entries.length === 0) return null;\n\n const list = new BlockList();\n for (const entry of [...(allowLoopback ? LOOPBACK : []), ...entries]) {\n try {\n addEntry(list, entry);\n } catch (err) {\n throw new Error(`${label}: ${(err as Error).message}`, { cause: err });\n }\n }\n return (ip) => {\n if (!ip || ip.includes(\"%\")) return false;\n const addr = normalizeIp(ip);\n const family = isIP(addr);\n if (!family) return false;\n return list.check(addr, family === 4 ? \"ipv4\" : \"ipv6\");\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,sBAAgC;AAchC,IAAM,WAAW,CAAC,eAAe,KAAK;AAG/B,SAAS,YAAY,IAAoB;AAC9C,QAAM,SAAS,sCAAsC,KAAK,EAAE;AAC5D,SAAO,SAAS,CAAC,KAAK;AACxB;AAEA,SAAS,SAAS,MAAiB,KAAmB;AACpD,QAAM,CAAC,OAAO,IAAI,QAAQ,GAAG,IAAI,IAAI,IAAI,MAAM,GAAG;AAClD,QAAM,aAAS,sBAAK,IAAI;AAGxB,MAAI,CAAC,UAAU,KAAK,SAAS,GAAG,KAAK,KAAK,SAAS,GAAG;AACpD,UAAM,IAAI,MAAM,oBAAoB,GAAG,GAAG;AAAA,EAC5C;AACA,QAAM,OAAO,WAAW,IAAI,SAAS;AACrC,MAAI,WAAW,QAAW;AACxB,SAAK,WAAW,MAAM,IAAI;AAC1B;AAAA,EACF;AACA,QAAM,OAAO,OAAO,MAAM;AAC1B,QAAM,MAAM,WAAW,IAAI,KAAK;AAChC,MAAI,CAAC,QAAQ,KAAK,MAAM,KAAK,OAAO,IAAK,OAAM,IAAI,MAAM,oBAAoB,GAAG,GAAG;AACnF,OAAK,UAAU,MAAM,MAAM,IAAI;AACjC;AASO,SAAS,iBACd,OACA,QAAQ,aACR,EAAE,gBAAgB,KAAK,IAAkB,CAAC,GACxB;AAClB,QAAM,MAAM,OAAO,UAAU,WAAW,MAAM,MAAM,GAAG,IAAK,SAAS,CAAC;AACtE,QAAM,UAAU,IAAI,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,OAAO;AACvD,MAAI,QAAQ,WAAW,EAAG,QAAO;AAEjC,QAAM,OAAO,IAAI,0BAAU;AAC3B,aAAW,SAAS,CAAC,GAAI,gBAAgB,WAAW,CAAC,GAAI,GAAG,OAAO,GAAG;AACpE,QAAI;AACF,eAAS,MAAM,KAAK;AAAA,IACtB,SAAS,KAAK;AACZ,YAAM,IAAI,MAAM,GAAG,KAAK,KAAM,IAAc,OAAO,IAAI,EAAE,OAAO,IAAI,CAAC;AAAA,IACvE;AAAA,EACF;AACA,SAAO,CAAC,OAAO;AACb,QAAI,CAAC,MAAM,GAAG,SAAS,GAAG,EAAG,QAAO;AACpC,UAAM,OAAO,YAAY,EAAE;AAC3B,UAAM,aAAS,sBAAK,IAAI;AACxB,QAAI,CAAC,OAAQ,QAAO;AACpB,WAAO,KAAK,MAAM,MAAM,WAAW,IAAI,SAAS,MAAM;AAAA,EACxD;AACF;;;AD3DO,SAAS,gBACd,gBAC2C;AAC3C,QAAM,UAAU,iBAAiB,gBAAgB,gBAAgB;AACjE,SAAO,CAAC,SAAS,QAAQ,QAAQ,MAAM,CAAC,WAAW,QAAQ,OAAO;AACpE;AA2BO,SAAS,0BACd,UACA,SACA,aACM;AACN,WAAS,QAAQ,aAAa,CAAC,KAAK,OAAO,SAAS;AAClD,UAAM,QAAQ,IAAI,cAAc,OAAO;AACvC,QAAI,MAAM,WAAW,WAAW,KAAK,CAAC,QAAQ,IAAI,EAAE,GAAG;AACrD,WAAK,MAAM,KAAK,GAAG,EAAE,KAAK,EAAE,YAAY,KAAK,SAAS,iBAAiB,CAAC;AACxE;AAAA,IACF;AACA,SAAK;AAAA,EACP,CAAC;AACH;","names":[]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { I as IpMatcher } from './ip-matcher-D4MA1kIq.cjs';
|
|
2
|
+
export { p as parseIpAllowlist } from './ip-matcher-D4MA1kIq.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Fastify `trustProxy` function equal to Express's `trust proxy = 1`: trusts
|
|
6
|
+
* only hop 0 (the socket peer, i.e. your reverse proxy), so a client cannot
|
|
7
|
+
* walk past it with extra X-Forwarded-For entries.
|
|
8
|
+
*
|
|
9
|
+
* Hop 0 is the socket peer itself: if the app port is reachable directly (not
|
|
10
|
+
* only through the proxy), ANY client is hop 0 and can forge X-Forwarded-For,
|
|
11
|
+
* defeating the allowlist. Pass `trustedProxies` (IPs/CIDRs of your proxy) to
|
|
12
|
+
* trust hop 0 only when the peer is one of them; a direct client's header is
|
|
13
|
+
* then ignored. Loopback is always included.
|
|
14
|
+
*/
|
|
15
|
+
declare function buildTrustProxy(trustedProxies?: string | readonly string[]): (address: string, hop: number) => boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Structural slice of a Fastify instance — deliberately not `FastifyInstance`, so
|
|
18
|
+
* it type-checks even when the app and `@nestjs/platform-fastify` resolve two
|
|
19
|
+
* different copies of `fastify`.
|
|
20
|
+
*/
|
|
21
|
+
interface FastifyHookHost {
|
|
22
|
+
addHook(name: "onRequest", hook: (req: {
|
|
23
|
+
ip: string;
|
|
24
|
+
routeOptions?: {
|
|
25
|
+
url?: string;
|
|
26
|
+
};
|
|
27
|
+
}, reply: {
|
|
28
|
+
code(statusCode: number): {
|
|
29
|
+
send(payload: unknown): unknown;
|
|
30
|
+
};
|
|
31
|
+
}, done: () => void) => void): unknown;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Restricts Fastify-native routes that live outside Nest's guard pipeline
|
|
35
|
+
* (e.g. Swagger UI under `/api/docs`) with the same allowlist. Register BEFORE
|
|
36
|
+
* those routes are added.
|
|
37
|
+
*
|
|
38
|
+
* Matches on the ROUTE Fastify resolved (`routeOptions.url`), not the raw
|
|
39
|
+
* `req.url`: Fastify percent-decodes the path before routing, so `/api/%64ocs`
|
|
40
|
+
* reaches the docs handler while `req.url.startsWith('/api/docs')` is false.
|
|
41
|
+
*/
|
|
42
|
+
declare function restrictRoutesToAllowlist(instance: FastifyHookHost, allowed: IpMatcher, routePrefix: string): void;
|
|
43
|
+
|
|
44
|
+
export { type FastifyHookHost, IpMatcher, buildTrustProxy, restrictRoutesToAllowlist };
|