@idevconn/allowlist-guard 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,102 @@
1
- # Temporary Holding Version
1
+ # @idevconn/allowlist-guard
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
+ 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
+ ## Features
6
+
7
+ - IPv4 + IPv6, single addresses and CIDR ranges; IPv4-mapped IPv6 (`::ffff:1.2.3.4`) is normalised.
8
+ - Separate lists for `protected` and `public` routes. A list that is unset/blank is **not enforced**, so adopting the guard is non-breaking.
9
+ - Loopback (`127.0.0.0/8`, `::1`) is allowed once a list is set (local dev, health probes) — disable with `allowLoopback: false` (see below).
10
+ - `@SkipIpAllowlist()` exempts a route or controller (e.g. HMAC-signed provider webhooks whose IPs you cannot pin).
11
+ - A malformed entry throws at boot naming the option — a typo never silently becomes "everyone allowed" or "everyone blocked".
12
+ - 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.
13
+ - 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.
14
+ - `/fastify` subpath: `buildTrustProxy` and `restrictRoutesToAllowlist` (for routes outside Nest's guard pipeline, e.g. Swagger UI).
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ npm install @idevconn/allowlist-guard
20
+ ```
21
+
22
+ Peer dependencies: `@nestjs/common`, `@nestjs/core` (10 or 11), `reflect-metadata`, `rxjs`; `fastify` only if you use the `/fastify` subpath.
23
+
24
+ ## Usage
25
+
26
+ ```ts
27
+ import { Module } from "@nestjs/common";
28
+ import { IpAllowlistModule } from "@idevconn/allowlist-guard";
29
+
30
+ @Module({
31
+ imports: [
32
+ // Import BEFORE the module that registers your auth guard, so a blocked IP
33
+ // is rejected before any authentication work.
34
+ IpAllowlistModule.forRoot({
35
+ protected: process.env.API_IP_ALLOWLIST, // "203.0.113.5, 10.0.0.0/8"
36
+ public: process.env.API_PUBLIC_IP_ALLOWLIST, // login, lead capture, ...
37
+ }),
38
+ AuthModule,
39
+ ],
40
+ })
41
+ export class AppModule {}
42
+ ```
43
+
44
+ | Option | Meaning |
45
+ | ------------------- | ---------------------------------------------------------------------------------------------------- |
46
+ | `protected` | Comma-separated string or array of IPs/CIDRs for non-public routes. Unset/blank = not enforced. |
47
+ | `public` | Same, for public routes. |
48
+ | `publicMetadataKey` | Metadata key marking a route public. Default `'isPublic'` (the common `@Public()` decorator's key). |
49
+ | `allowLoopback` | Default `true`. Set `false` if a reverse proxy runs on the same host (see below). |
50
+ | `onBlocked` | `(ip) => void`, called on every blocked request. Default: a rate-limited Nest `Logger.warn`. |
51
+
52
+ **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()`.
53
+
54
+ Exempt a route:
55
+
56
+ ```ts
57
+ import { SkipIpAllowlist } from "@idevconn/allowlist-guard";
58
+
59
+ @Public()
60
+ @SkipIpAllowlist() // authenticated by an HMAC signature instead
61
+ @Post("webhooks/:provider")
62
+ receive() {}
63
+ ```
64
+
65
+ ## Getting the real client IP (read this)
66
+
67
+ 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:
68
+
69
+ - **Express:** `app.set("trust proxy", 1)`.
70
+ - **Fastify:**
71
+
72
+ ```ts
73
+ import { buildTrustProxy } from "@idevconn/allowlist-guard/fastify";
74
+
75
+ new FastifyAdapter({ trustProxy: buildTrustProxy(process.env.TRUSTED_PROXIES) });
76
+ ```
77
+
78
+ `buildTrustProxy()` 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.
79
+
80
+ 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).
81
+
82
+ ## Routes outside Nest (Swagger UI)
83
+
84
+ Fastify-native routes never reach Nest guards. Restrict them with the same list, **before** registering them:
85
+
86
+ ```ts
87
+ import { parseIpAllowlist, restrictRoutesToAllowlist } from "@idevconn/allowlist-guard/fastify";
88
+
89
+ const allowed = parseIpAllowlist(process.env.API_IP_ALLOWLIST);
90
+ if (allowed) restrictRoutesToAllowlist(app.getHttpAdapter().getInstance(), allowed, "/api/docs");
91
+ SwaggerModule.setup("api/docs", app, document);
92
+ ```
93
+
94
+ It matches on the resolved route (`routeOptions.url`), not the raw URL, so percent-encoded paths such as `/api/%64ocs` cannot slip past.
95
+
96
+ ## Limits
97
+
98
+ An IP allowlist only helps when your legitimate clients have known IPs. It cannot tell a browser from Postman/Playwright on the same IP — use authentication, rate limiting and bot protection for open APIs.
99
+
100
+ ## License
101
+
102
+ 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":[]}
@@ -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 type { FastifyInstance } from \"fastify\";\nimport { 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 * 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: FastifyInstance,\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;;;AD1DO,SAAS,gBACd,gBAC2C;AAC3C,QAAM,UAAU,iBAAiB,gBAAgB,gBAAgB;AACjE,SAAO,CAAC,SAAS,QAAQ,QAAQ,MAAM,CAAC,WAAW,QAAQ,OAAO;AACpE;AAWO,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,28 @@
1
+ import { FastifyInstance } from 'fastify';
2
+ import { I as IpMatcher } from './ip-matcher-D4MA1kIq.cjs';
3
+ export { p as parseIpAllowlist } from './ip-matcher-D4MA1kIq.cjs';
4
+
5
+ /**
6
+ * Fastify `trustProxy` function equal to Express's `trust proxy = 1`: trusts
7
+ * only hop 0 (the socket peer, i.e. your reverse proxy), so a client cannot
8
+ * walk past it with extra X-Forwarded-For entries.
9
+ *
10
+ * Hop 0 is the socket peer itself: if the app port is reachable directly (not
11
+ * only through the proxy), ANY client is hop 0 and can forge X-Forwarded-For,
12
+ * defeating the allowlist. Pass `trustedProxies` (IPs/CIDRs of your proxy) to
13
+ * trust hop 0 only when the peer is one of them; a direct client's header is
14
+ * then ignored. Loopback is always included.
15
+ */
16
+ declare function buildTrustProxy(trustedProxies?: string | readonly string[]): (address: string, hop: number) => boolean;
17
+ /**
18
+ * Restricts Fastify-native routes that live outside Nest's guard pipeline
19
+ * (e.g. Swagger UI under `/api/docs`) with the same allowlist. Register BEFORE
20
+ * those routes are added.
21
+ *
22
+ * Matches on the ROUTE Fastify resolved (`routeOptions.url`), not the raw
23
+ * `req.url`: Fastify percent-decodes the path before routing, so `/api/%64ocs`
24
+ * reaches the docs handler while `req.url.startsWith('/api/docs')` is false.
25
+ */
26
+ declare function restrictRoutesToAllowlist(instance: FastifyInstance, allowed: IpMatcher, routePrefix: string): void;
27
+
28
+ export { IpMatcher, buildTrustProxy, restrictRoutesToAllowlist };
@@ -0,0 +1,28 @@
1
+ import { FastifyInstance } from 'fastify';
2
+ import { I as IpMatcher } from './ip-matcher-D4MA1kIq.js';
3
+ export { p as parseIpAllowlist } from './ip-matcher-D4MA1kIq.js';
4
+
5
+ /**
6
+ * Fastify `trustProxy` function equal to Express's `trust proxy = 1`: trusts
7
+ * only hop 0 (the socket peer, i.e. your reverse proxy), so a client cannot
8
+ * walk past it with extra X-Forwarded-For entries.
9
+ *
10
+ * Hop 0 is the socket peer itself: if the app port is reachable directly (not
11
+ * only through the proxy), ANY client is hop 0 and can forge X-Forwarded-For,
12
+ * defeating the allowlist. Pass `trustedProxies` (IPs/CIDRs of your proxy) to
13
+ * trust hop 0 only when the peer is one of them; a direct client's header is
14
+ * then ignored. Loopback is always included.
15
+ */
16
+ declare function buildTrustProxy(trustedProxies?: string | readonly string[]): (address: string, hop: number) => boolean;
17
+ /**
18
+ * Restricts Fastify-native routes that live outside Nest's guard pipeline
19
+ * (e.g. Swagger UI under `/api/docs`) with the same allowlist. Register BEFORE
20
+ * those routes are added.
21
+ *
22
+ * Matches on the ROUTE Fastify resolved (`routeOptions.url`), not the raw
23
+ * `req.url`: Fastify percent-decodes the path before routing, so `/api/%64ocs`
24
+ * reaches the docs handler while `req.url.startsWith('/api/docs')` is false.
25
+ */
26
+ declare function restrictRoutesToAllowlist(instance: FastifyInstance, allowed: IpMatcher, routePrefix: string): void;
27
+
28
+ export { IpMatcher, buildTrustProxy, restrictRoutesToAllowlist };
@@ -0,0 +1,25 @@
1
+ import {
2
+ parseIpAllowlist
3
+ } from "./chunk-POEP4ARO.js";
4
+
5
+ // src/fastify/index.ts
6
+ function buildTrustProxy(trustedProxies) {
7
+ const matcher = parseIpAllowlist(trustedProxies, "trustedProxies");
8
+ return (address, hop) => hop === 0 && (!matcher || matcher(address));
9
+ }
10
+ function restrictRoutesToAllowlist(instance, allowed, routePrefix) {
11
+ instance.addHook("onRequest", (req, reply, done) => {
12
+ const route = req.routeOptions?.url ?? "";
13
+ if (route.startsWith(routePrefix) && !allowed(req.ip)) {
14
+ void reply.code(403).send({ statusCode: 403, message: "ip_not_allowed" });
15
+ return;
16
+ }
17
+ done();
18
+ });
19
+ }
20
+ export {
21
+ buildTrustProxy,
22
+ parseIpAllowlist,
23
+ restrictRoutesToAllowlist
24
+ };
25
+ //# sourceMappingURL=fastify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fastify/index.ts"],"sourcesContent":["import type { FastifyInstance } from \"fastify\";\nimport { 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 * 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: FastifyInstance,\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"],"mappings":";;;;;AAcO,SAAS,gBACd,gBAC2C;AAC3C,QAAM,UAAU,iBAAiB,gBAAgB,gBAAgB;AACjE,SAAO,CAAC,SAAS,QAAQ,QAAQ,MAAM,CAAC,WAAW,QAAQ,OAAO;AACpE;AAWO,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":[]}
package/dist/index.cjs ADDED
@@ -0,0 +1,189 @@
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
+ var __decorateClass = (decorators, target, key, kind) => {
20
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
21
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
22
+ if (decorator = decorators[i])
23
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
24
+ if (kind && result) __defProp(target, key, result);
25
+ return result;
26
+ };
27
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
28
+
29
+ // src/index.ts
30
+ var src_exports = {};
31
+ __export(src_exports, {
32
+ IP_ALLOWLIST_OPTIONS: () => IP_ALLOWLIST_OPTIONS,
33
+ IpAllowlistGuard: () => IpAllowlistGuard,
34
+ IpAllowlistModule: () => IpAllowlistModule,
35
+ SKIP_IP_ALLOWLIST_KEY: () => SKIP_IP_ALLOWLIST_KEY,
36
+ SkipIpAllowlist: () => SkipIpAllowlist,
37
+ normalizeIp: () => normalizeIp,
38
+ parseIpAllowlist: () => parseIpAllowlist
39
+ });
40
+ module.exports = __toCommonJS(src_exports);
41
+
42
+ // src/ip-allowlist.module.ts
43
+ var import_common3 = require("@nestjs/common");
44
+ var import_core2 = require("@nestjs/core");
45
+
46
+ // src/ip-allowlist.guard.ts
47
+ var import_common2 = require("@nestjs/common");
48
+ var import_core = require("@nestjs/core");
49
+ var import_node_net2 = require("net");
50
+
51
+ // src/options.ts
52
+ var IP_ALLOWLIST_OPTIONS = /* @__PURE__ */ Symbol("IP_ALLOWLIST_OPTIONS");
53
+
54
+ // src/ip-matcher.ts
55
+ var import_node_net = require("net");
56
+ var LOOPBACK = ["127.0.0.0/8", "::1"];
57
+ function normalizeIp(ip) {
58
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(ip);
59
+ return mapped?.[1] ?? ip;
60
+ }
61
+ function addEntry(list, raw) {
62
+ const [addr = "", prefix, ...rest] = raw.split("/");
63
+ const family = (0, import_node_net.isIP)(addr);
64
+ if (!family || addr.includes("%") || rest.length > 0) {
65
+ throw new Error(`invalid IP/CIDR "${raw}"`);
66
+ }
67
+ const type = family === 4 ? "ipv4" : "ipv6";
68
+ if (prefix === void 0) {
69
+ list.addAddress(addr, type);
70
+ return;
71
+ }
72
+ const bits = Number(prefix);
73
+ const max = family === 4 ? 32 : 128;
74
+ if (!/^\d+$/.test(prefix) || bits > max) throw new Error(`invalid IP/CIDR "${raw}"`);
75
+ list.addSubnet(addr, bits, type);
76
+ }
77
+ function parseIpAllowlist(value, label = "allowlist", { allowLoopback = true } = {}) {
78
+ const raw = typeof value === "string" ? value.split(",") : value ?? [];
79
+ const entries = raw.map((s) => s.trim()).filter(Boolean);
80
+ if (entries.length === 0) return null;
81
+ const list = new import_node_net.BlockList();
82
+ for (const entry of [...allowLoopback ? LOOPBACK : [], ...entries]) {
83
+ try {
84
+ addEntry(list, entry);
85
+ } catch (err) {
86
+ throw new Error(`${label}: ${err.message}`, { cause: err });
87
+ }
88
+ }
89
+ return (ip) => {
90
+ if (!ip || ip.includes("%")) return false;
91
+ const addr = normalizeIp(ip);
92
+ const family = (0, import_node_net.isIP)(addr);
93
+ if (!family) return false;
94
+ return list.check(addr, family === 4 ? "ipv4" : "ipv6");
95
+ };
96
+ }
97
+
98
+ // src/skip-ip-allowlist.decorator.ts
99
+ var import_common = require("@nestjs/common");
100
+ var SKIP_IP_ALLOWLIST_KEY = "skipIpAllowlist";
101
+ var SkipIpAllowlist = () => (0, import_common.SetMetadata)(SKIP_IP_ALLOWLIST_KEY, true);
102
+
103
+ // src/ip-allowlist.guard.ts
104
+ var LOG_INTERVAL_MS = 6e4;
105
+ var MAX_TRACKED_IPS = 1e3;
106
+ var IpAllowlistGuard = class {
107
+ constructor(reflector, options) {
108
+ this.reflector = reflector;
109
+ this.options = options;
110
+ const parse = { allowLoopback: options.allowLoopback ?? true };
111
+ this.protectedMatcher = parseIpAllowlist(options.protected, "protected", parse);
112
+ this.publicMatcher = parseIpAllowlist(options.public, "public", parse);
113
+ this.publicKey = options.publicMetadataKey ?? "isPublic";
114
+ }
115
+ reflector;
116
+ options;
117
+ logger = new import_common2.Logger(IpAllowlistGuard.name);
118
+ protectedMatcher;
119
+ publicMatcher;
120
+ publicKey;
121
+ lastLogged = /* @__PURE__ */ new Map();
122
+ canActivate(ctx) {
123
+ const type = ctx.getType();
124
+ if (type === "rpc") return true;
125
+ if (!this.protectedMatcher && !this.publicMatcher) return true;
126
+ const targets = [ctx.getHandler(), ctx.getClass()];
127
+ if (this.reflector.getAllAndOverride(SKIP_IP_ALLOWLIST_KEY, targets)) return true;
128
+ const isPublic = this.reflector.getAllAndOverride(this.publicKey, targets);
129
+ const matcher = isPublic ? this.publicMatcher : this.protectedMatcher;
130
+ if (!matcher) return true;
131
+ const ip = type === "http" ? ctx.switchToHttp().getRequest().ip : void 0;
132
+ if (matcher(ip)) return true;
133
+ this.notifyBlocked(ip);
134
+ throw new import_common2.ForbiddenException("ip_not_allowed");
135
+ }
136
+ notifyBlocked(ip) {
137
+ this.options.onBlocked?.(ip);
138
+ const key = ip && (0, import_node_net2.isIP)(ip) ? ip : "invalid";
139
+ const now = Date.now();
140
+ const last = this.lastLogged.get(key);
141
+ if (last !== void 0 && now - last < LOG_INTERVAL_MS) return;
142
+ this.lastLogged.delete(key);
143
+ this.lastLogged.set(key, now);
144
+ if (this.lastLogged.size > MAX_TRACKED_IPS) {
145
+ const oldest = this.lastLogged.keys().next().value;
146
+ if (oldest !== void 0) this.lastLogged.delete(oldest);
147
+ }
148
+ if (!this.options.onBlocked) {
149
+ this.logger.warn(`Blocked request from non-allowlisted IP ${key}`);
150
+ }
151
+ }
152
+ };
153
+ IpAllowlistGuard = __decorateClass([
154
+ (0, import_common2.Injectable)(),
155
+ __decorateParam(0, (0, import_common2.Inject)(import_core.Reflector)),
156
+ __decorateParam(1, (0, import_common2.Inject)(IP_ALLOWLIST_OPTIONS))
157
+ ], IpAllowlistGuard);
158
+
159
+ // src/ip-allowlist.module.ts
160
+ var IpAllowlistModule = class {
161
+ /**
162
+ * Registers the guard globally (APP_GUARD). Import this module BEFORE the
163
+ * module that registers your auth guard so a blocked IP is rejected before
164
+ * any authentication work.
165
+ */
166
+ static forRoot(options = {}) {
167
+ return {
168
+ module: IpAllowlistModule,
169
+ providers: [
170
+ { provide: IP_ALLOWLIST_OPTIONS, useValue: options },
171
+ { provide: import_core2.APP_GUARD, useClass: IpAllowlistGuard }
172
+ ]
173
+ };
174
+ }
175
+ };
176
+ IpAllowlistModule = __decorateClass([
177
+ (0, import_common3.Module)({})
178
+ ], IpAllowlistModule);
179
+ // Annotate the CommonJS export names for ESM import in node:
180
+ 0 && (module.exports = {
181
+ IP_ALLOWLIST_OPTIONS,
182
+ IpAllowlistGuard,
183
+ IpAllowlistModule,
184
+ SKIP_IP_ALLOWLIST_KEY,
185
+ SkipIpAllowlist,
186
+ normalizeIp,
187
+ parseIpAllowlist
188
+ });
189
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/ip-allowlist.module.ts","../src/ip-allowlist.guard.ts","../src/options.ts","../src/ip-matcher.ts","../src/skip-ip-allowlist.decorator.ts"],"sourcesContent":["export { IpAllowlistModule } from \"./ip-allowlist.module.js\";\nexport { IpAllowlistGuard } from \"./ip-allowlist.guard.js\";\nexport { SkipIpAllowlist, SKIP_IP_ALLOWLIST_KEY } from \"./skip-ip-allowlist.decorator.js\";\nexport { IP_ALLOWLIST_OPTIONS, type IpAllowlistOptions } from \"./options.js\";\nexport { parseIpAllowlist, normalizeIp, type IpMatcher } from \"./ip-matcher.js\";\n","import { Module, type DynamicModule } from \"@nestjs/common\";\nimport { APP_GUARD } from \"@nestjs/core\";\nimport { IpAllowlistGuard } from \"./ip-allowlist.guard.js\";\nimport { IP_ALLOWLIST_OPTIONS, type IpAllowlistOptions } from \"./options.js\";\n\n@Module({})\nexport class IpAllowlistModule {\n /**\n * Registers the guard globally (APP_GUARD). Import this module BEFORE the\n * module that registers your auth guard so a blocked IP is rejected before\n * any authentication work.\n */\n static forRoot(options: IpAllowlistOptions = {}): DynamicModule {\n return {\n module: IpAllowlistModule,\n providers: [\n { provide: IP_ALLOWLIST_OPTIONS, useValue: options },\n { provide: APP_GUARD, useClass: IpAllowlistGuard },\n ],\n };\n }\n}\n","import {\n ForbiddenException,\n Inject,\n Injectable,\n Logger,\n type CanActivate,\n type ExecutionContext,\n} from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\nimport { isIP } from \"node:net\";\nimport { IP_ALLOWLIST_OPTIONS, type IpAllowlistOptions } from \"./options.js\";\nimport { parseIpAllowlist, type IpMatcher } from \"./ip-matcher.js\";\nimport { SKIP_IP_ALLOWLIST_KEY } from \"./skip-ip-allowlist.decorator.js\";\n\n// Default log line is rate-limited per IP; the map is bounded by evicting the OLDEST\n// entry, so rotating through many IPs can never switch logging off.\nconst LOG_INTERVAL_MS = 60_000;\nconst MAX_TRACKED_IPS = 1000;\n\n/**\n * Restricts routes by source IP. Reads `request.ip`, which Express/Fastify\n * resolve through their own `trust proxy` setting — configure it so `req.ip`\n * is the real client behind your proxy (see `buildTrustProxy` in the\n * `/fastify` entry). `X-Forwarded-For` is never read here.\n */\n@Injectable()\nexport class IpAllowlistGuard implements CanActivate {\n private readonly logger = new Logger(IpAllowlistGuard.name);\n private readonly protectedMatcher: IpMatcher | null;\n private readonly publicMatcher: IpMatcher | null;\n private readonly publicKey: string;\n private readonly lastLogged = new Map<string, number>();\n\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(IP_ALLOWLIST_OPTIONS) private readonly options: IpAllowlistOptions,\n ) {\n const parse = { allowLoopback: options.allowLoopback ?? true };\n this.protectedMatcher = parseIpAllowlist(options.protected, \"protected\", parse);\n this.publicMatcher = parseIpAllowlist(options.public, \"public\", parse);\n this.publicKey = options.publicMetadataKey ?? \"isPublic\";\n }\n\n canActivate(ctx: ExecutionContext): boolean {\n // Only microservice (RPC) traffic is exempt: it has no client IP and is internal\n // transport. Any other context type (graphql, ws, ...) is NOT skipped — it has no\n // resolvable `req.ip` here, so it is denied when a list is enforced (fail closed).\n const type = ctx.getType<string>();\n if (type === \"rpc\") return true;\n if (!this.protectedMatcher && !this.publicMatcher) return true;\n\n const targets = [ctx.getHandler(), ctx.getClass()];\n if (this.reflector.getAllAndOverride<boolean>(SKIP_IP_ALLOWLIST_KEY, targets)) return true;\n\n const isPublic = this.reflector.getAllAndOverride<boolean>(this.publicKey, targets);\n const matcher = isPublic ? this.publicMatcher : this.protectedMatcher;\n if (!matcher) return true;\n\n const ip = type === \"http\" ? ctx.switchToHttp().getRequest<{ ip?: string }>().ip : undefined;\n if (matcher(ip)) return true;\n\n this.notifyBlocked(ip);\n throw new ForbiddenException(\"ip_not_allowed\");\n }\n\n private notifyBlocked(ip: string | undefined): void {\n this.options.onBlocked?.(ip);\n\n // Never log attacker-controlled text: only a well-formed IP is echoed.\n const key = ip && isIP(ip) ? ip : \"invalid\";\n const now = Date.now();\n const last = this.lastLogged.get(key);\n if (last !== undefined && now - last < LOG_INTERVAL_MS) return;\n this.lastLogged.delete(key);\n this.lastLogged.set(key, now);\n if (this.lastLogged.size > MAX_TRACKED_IPS) {\n const oldest = this.lastLogged.keys().next().value;\n if (oldest !== undefined) this.lastLogged.delete(oldest);\n }\n if (!this.options.onBlocked) {\n this.logger.warn(`Blocked request from non-allowlisted IP ${key}`);\n }\n }\n}\n","export const IP_ALLOWLIST_OPTIONS = Symbol(\"IP_ALLOWLIST_OPTIONS\");\n\nexport interface IpAllowlistOptions {\n /**\n * Allowlist for protected (non-public) routes: comma-separated string or\n * array of IPs/CIDRs. Unset/blank = not enforced.\n */\n protected?: string | readonly string[];\n /**\n * Allowlist for public (\"open\") routes, i.e. routes carrying the metadata key\n * below. Unset/blank = not enforced.\n */\n public?: string | readonly string[];\n /**\n * Metadata key that marks a route as public. Defaults to `'isPublic'`, the\n * key used by the common `@Public()` decorator (`SetMetadata('isPublic', true)`).\n */\n publicMetadataKey?: string;\n /**\n * Always allow loopback once a list is set. Default `true`. Set `false` if a\n * reverse proxy runs on the same host and `req.ip` could be its loopback address.\n */\n allowLoopback?: boolean;\n /**\n * Called on EVERY blocked request (feed your metrics/alerting from here).\n * The default Nest Logger warning is rate-limited per IP; this hook is not.\n */\n onBlocked?: (ip: string | undefined) => void;\n}\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","import { SetMetadata } from \"@nestjs/common\";\n\nexport const SKIP_IP_ALLOWLIST_KEY = \"skipIpAllowlist\";\n\n/**\n * Exempts a route (or controller) from the guard. For callers whose IPs cannot\n * be pinned down and that authenticate by other means (e.g. provider webhooks\n * verified by an HMAC signature).\n */\nexport const SkipIpAllowlist = (): MethodDecorator & ClassDecorator =>\n SetMetadata(SKIP_IP_ALLOWLIST_KEY, true);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAA2C;AAC3C,IAAAC,eAA0B;;;ACD1B,IAAAC,iBAOO;AACP,kBAA0B;AAC1B,IAAAC,mBAAqB;;;ACTd,IAAM,uBAAuB,uBAAO,sBAAsB;;;ACAjE,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;;;ACxEA,oBAA4B;AAErB,IAAM,wBAAwB;AAO9B,IAAM,kBAAkB,UAC7B,2BAAY,uBAAuB,IAAI;;;AHMzC,IAAM,kBAAkB;AACxB,IAAM,kBAAkB;AASjB,IAAM,mBAAN,MAA8C;AAAA,EAOnD,YACsC,WACW,SAC/C;AAFoC;AACW;AAE/C,UAAM,QAAQ,EAAE,eAAe,QAAQ,iBAAiB,KAAK;AAC7D,SAAK,mBAAmB,iBAAiB,QAAQ,WAAW,aAAa,KAAK;AAC9E,SAAK,gBAAgB,iBAAiB,QAAQ,QAAQ,UAAU,KAAK;AACrE,SAAK,YAAY,QAAQ,qBAAqB;AAAA,EAChD;AAAA,EAPsC;AAAA,EACW;AAAA,EARhC,SAAS,IAAI,sBAAO,iBAAiB,IAAI;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa,oBAAI,IAAoB;AAAA,EAYtD,YAAY,KAAgC;AAI1C,UAAM,OAAO,IAAI,QAAgB;AACjC,QAAI,SAAS,MAAO,QAAO;AAC3B,QAAI,CAAC,KAAK,oBAAoB,CAAC,KAAK,cAAe,QAAO;AAE1D,UAAM,UAAU,CAAC,IAAI,WAAW,GAAG,IAAI,SAAS,CAAC;AACjD,QAAI,KAAK,UAAU,kBAA2B,uBAAuB,OAAO,EAAG,QAAO;AAEtF,UAAM,WAAW,KAAK,UAAU,kBAA2B,KAAK,WAAW,OAAO;AAClF,UAAM,UAAU,WAAW,KAAK,gBAAgB,KAAK;AACrD,QAAI,CAAC,QAAS,QAAO;AAErB,UAAM,KAAK,SAAS,SAAS,IAAI,aAAa,EAAE,WAA4B,EAAE,KAAK;AACnF,QAAI,QAAQ,EAAE,EAAG,QAAO;AAExB,SAAK,cAAc,EAAE;AACrB,UAAM,IAAI,kCAAmB,gBAAgB;AAAA,EAC/C;AAAA,EAEQ,cAAc,IAA8B;AAClD,SAAK,QAAQ,YAAY,EAAE;AAG3B,UAAM,MAAM,UAAM,uBAAK,EAAE,IAAI,KAAK;AAClC,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,OAAO,KAAK,WAAW,IAAI,GAAG;AACpC,QAAI,SAAS,UAAa,MAAM,OAAO,gBAAiB;AACxD,SAAK,WAAW,OAAO,GAAG;AAC1B,SAAK,WAAW,IAAI,KAAK,GAAG;AAC5B,QAAI,KAAK,WAAW,OAAO,iBAAiB;AAC1C,YAAM,SAAS,KAAK,WAAW,KAAK,EAAE,KAAK,EAAE;AAC7C,UAAI,WAAW,OAAW,MAAK,WAAW,OAAO,MAAM;AAAA,IACzD;AACA,QAAI,CAAC,KAAK,QAAQ,WAAW;AAC3B,WAAK,OAAO,KAAK,2CAA2C,GAAG,EAAE;AAAA,IACnE;AAAA,EACF;AACF;AAzDa,mBAAN;AAAA,MADN,2BAAW;AAAA,EASP,8CAAO,qBAAS;AAAA,EAChB,8CAAO,oBAAoB;AAAA,GATnB;;;ADpBN,IAAM,oBAAN,MAAwB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM7B,OAAO,QAAQ,UAA8B,CAAC,GAAkB;AAC9D,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,WAAW;AAAA,QACT,EAAE,SAAS,sBAAsB,UAAU,QAAQ;AAAA,QACnD,EAAE,SAAS,wBAAW,UAAU,iBAAiB;AAAA,MACnD;AAAA,IACF;AAAA,EACF;AACF;AAfa,oBAAN;AAAA,MADN,uBAAO,CAAC,CAAC;AAAA,GACG;","names":["import_common","import_core","import_common","import_node_net"]}
@@ -0,0 +1,70 @@
1
+ import { DynamicModule, CanActivate, ExecutionContext } from '@nestjs/common';
2
+ import { Reflector } from '@nestjs/core';
3
+ export { I as IpMatcher, n as normalizeIp, p as parseIpAllowlist } from './ip-matcher-D4MA1kIq.cjs';
4
+
5
+ declare const IP_ALLOWLIST_OPTIONS: unique symbol;
6
+ interface IpAllowlistOptions {
7
+ /**
8
+ * Allowlist for protected (non-public) routes: comma-separated string or
9
+ * array of IPs/CIDRs. Unset/blank = not enforced.
10
+ */
11
+ protected?: string | readonly string[];
12
+ /**
13
+ * Allowlist for public ("open") routes, i.e. routes carrying the metadata key
14
+ * below. Unset/blank = not enforced.
15
+ */
16
+ public?: string | readonly string[];
17
+ /**
18
+ * Metadata key that marks a route as public. Defaults to `'isPublic'`, the
19
+ * key used by the common `@Public()` decorator (`SetMetadata('isPublic', true)`).
20
+ */
21
+ publicMetadataKey?: string;
22
+ /**
23
+ * Always allow loopback once a list is set. Default `true`. Set `false` if a
24
+ * reverse proxy runs on the same host and `req.ip` could be its loopback address.
25
+ */
26
+ allowLoopback?: boolean;
27
+ /**
28
+ * Called on EVERY blocked request (feed your metrics/alerting from here).
29
+ * The default Nest Logger warning is rate-limited per IP; this hook is not.
30
+ */
31
+ onBlocked?: (ip: string | undefined) => void;
32
+ }
33
+
34
+ declare class IpAllowlistModule {
35
+ /**
36
+ * Registers the guard globally (APP_GUARD). Import this module BEFORE the
37
+ * module that registers your auth guard so a blocked IP is rejected before
38
+ * any authentication work.
39
+ */
40
+ static forRoot(options?: IpAllowlistOptions): DynamicModule;
41
+ }
42
+
43
+ /**
44
+ * Restricts routes by source IP. Reads `request.ip`, which Express/Fastify
45
+ * resolve through their own `trust proxy` setting — configure it so `req.ip`
46
+ * is the real client behind your proxy (see `buildTrustProxy` in the
47
+ * `/fastify` entry). `X-Forwarded-For` is never read here.
48
+ */
49
+ declare class IpAllowlistGuard implements CanActivate {
50
+ private readonly reflector;
51
+ private readonly options;
52
+ private readonly logger;
53
+ private readonly protectedMatcher;
54
+ private readonly publicMatcher;
55
+ private readonly publicKey;
56
+ private readonly lastLogged;
57
+ constructor(reflector: Reflector, options: IpAllowlistOptions);
58
+ canActivate(ctx: ExecutionContext): boolean;
59
+ private notifyBlocked;
60
+ }
61
+
62
+ declare const SKIP_IP_ALLOWLIST_KEY = "skipIpAllowlist";
63
+ /**
64
+ * Exempts a route (or controller) from the guard. For callers whose IPs cannot
65
+ * be pinned down and that authenticate by other means (e.g. provider webhooks
66
+ * verified by an HMAC signature).
67
+ */
68
+ declare const SkipIpAllowlist: () => MethodDecorator & ClassDecorator;
69
+
70
+ export { IP_ALLOWLIST_OPTIONS, IpAllowlistGuard, IpAllowlistModule, type IpAllowlistOptions, SKIP_IP_ALLOWLIST_KEY, SkipIpAllowlist };
@@ -0,0 +1,70 @@
1
+ import { DynamicModule, CanActivate, ExecutionContext } from '@nestjs/common';
2
+ import { Reflector } from '@nestjs/core';
3
+ export { I as IpMatcher, n as normalizeIp, p as parseIpAllowlist } from './ip-matcher-D4MA1kIq.js';
4
+
5
+ declare const IP_ALLOWLIST_OPTIONS: unique symbol;
6
+ interface IpAllowlistOptions {
7
+ /**
8
+ * Allowlist for protected (non-public) routes: comma-separated string or
9
+ * array of IPs/CIDRs. Unset/blank = not enforced.
10
+ */
11
+ protected?: string | readonly string[];
12
+ /**
13
+ * Allowlist for public ("open") routes, i.e. routes carrying the metadata key
14
+ * below. Unset/blank = not enforced.
15
+ */
16
+ public?: string | readonly string[];
17
+ /**
18
+ * Metadata key that marks a route as public. Defaults to `'isPublic'`, the
19
+ * key used by the common `@Public()` decorator (`SetMetadata('isPublic', true)`).
20
+ */
21
+ publicMetadataKey?: string;
22
+ /**
23
+ * Always allow loopback once a list is set. Default `true`. Set `false` if a
24
+ * reverse proxy runs on the same host and `req.ip` could be its loopback address.
25
+ */
26
+ allowLoopback?: boolean;
27
+ /**
28
+ * Called on EVERY blocked request (feed your metrics/alerting from here).
29
+ * The default Nest Logger warning is rate-limited per IP; this hook is not.
30
+ */
31
+ onBlocked?: (ip: string | undefined) => void;
32
+ }
33
+
34
+ declare class IpAllowlistModule {
35
+ /**
36
+ * Registers the guard globally (APP_GUARD). Import this module BEFORE the
37
+ * module that registers your auth guard so a blocked IP is rejected before
38
+ * any authentication work.
39
+ */
40
+ static forRoot(options?: IpAllowlistOptions): DynamicModule;
41
+ }
42
+
43
+ /**
44
+ * Restricts routes by source IP. Reads `request.ip`, which Express/Fastify
45
+ * resolve through their own `trust proxy` setting — configure it so `req.ip`
46
+ * is the real client behind your proxy (see `buildTrustProxy` in the
47
+ * `/fastify` entry). `X-Forwarded-For` is never read here.
48
+ */
49
+ declare class IpAllowlistGuard implements CanActivate {
50
+ private readonly reflector;
51
+ private readonly options;
52
+ private readonly logger;
53
+ private readonly protectedMatcher;
54
+ private readonly publicMatcher;
55
+ private readonly publicKey;
56
+ private readonly lastLogged;
57
+ constructor(reflector: Reflector, options: IpAllowlistOptions);
58
+ canActivate(ctx: ExecutionContext): boolean;
59
+ private notifyBlocked;
60
+ }
61
+
62
+ declare const SKIP_IP_ALLOWLIST_KEY = "skipIpAllowlist";
63
+ /**
64
+ * Exempts a route (or controller) from the guard. For callers whose IPs cannot
65
+ * be pinned down and that authenticate by other means (e.g. provider webhooks
66
+ * verified by an HMAC signature).
67
+ */
68
+ declare const SkipIpAllowlist: () => MethodDecorator & ClassDecorator;
69
+
70
+ export { IP_ALLOWLIST_OPTIONS, IpAllowlistGuard, IpAllowlistModule, type IpAllowlistOptions, SKIP_IP_ALLOWLIST_KEY, SkipIpAllowlist };
package/dist/index.js ADDED
@@ -0,0 +1,115 @@
1
+ import {
2
+ __decorateClass,
3
+ __decorateParam,
4
+ normalizeIp,
5
+ parseIpAllowlist
6
+ } from "./chunk-POEP4ARO.js";
7
+
8
+ // src/ip-allowlist.module.ts
9
+ import { Module } from "@nestjs/common";
10
+ import { APP_GUARD } from "@nestjs/core";
11
+
12
+ // src/ip-allowlist.guard.ts
13
+ import {
14
+ ForbiddenException,
15
+ Inject,
16
+ Injectable,
17
+ Logger
18
+ } from "@nestjs/common";
19
+ import { Reflector } from "@nestjs/core";
20
+ import { isIP } from "net";
21
+
22
+ // src/options.ts
23
+ var IP_ALLOWLIST_OPTIONS = /* @__PURE__ */ Symbol("IP_ALLOWLIST_OPTIONS");
24
+
25
+ // src/skip-ip-allowlist.decorator.ts
26
+ import { SetMetadata } from "@nestjs/common";
27
+ var SKIP_IP_ALLOWLIST_KEY = "skipIpAllowlist";
28
+ var SkipIpAllowlist = () => SetMetadata(SKIP_IP_ALLOWLIST_KEY, true);
29
+
30
+ // src/ip-allowlist.guard.ts
31
+ var LOG_INTERVAL_MS = 6e4;
32
+ var MAX_TRACKED_IPS = 1e3;
33
+ var IpAllowlistGuard = class {
34
+ constructor(reflector, options) {
35
+ this.reflector = reflector;
36
+ this.options = options;
37
+ const parse = { allowLoopback: options.allowLoopback ?? true };
38
+ this.protectedMatcher = parseIpAllowlist(options.protected, "protected", parse);
39
+ this.publicMatcher = parseIpAllowlist(options.public, "public", parse);
40
+ this.publicKey = options.publicMetadataKey ?? "isPublic";
41
+ }
42
+ reflector;
43
+ options;
44
+ logger = new Logger(IpAllowlistGuard.name);
45
+ protectedMatcher;
46
+ publicMatcher;
47
+ publicKey;
48
+ lastLogged = /* @__PURE__ */ new Map();
49
+ canActivate(ctx) {
50
+ const type = ctx.getType();
51
+ if (type === "rpc") return true;
52
+ if (!this.protectedMatcher && !this.publicMatcher) return true;
53
+ const targets = [ctx.getHandler(), ctx.getClass()];
54
+ if (this.reflector.getAllAndOverride(SKIP_IP_ALLOWLIST_KEY, targets)) return true;
55
+ const isPublic = this.reflector.getAllAndOverride(this.publicKey, targets);
56
+ const matcher = isPublic ? this.publicMatcher : this.protectedMatcher;
57
+ if (!matcher) return true;
58
+ const ip = type === "http" ? ctx.switchToHttp().getRequest().ip : void 0;
59
+ if (matcher(ip)) return true;
60
+ this.notifyBlocked(ip);
61
+ throw new ForbiddenException("ip_not_allowed");
62
+ }
63
+ notifyBlocked(ip) {
64
+ this.options.onBlocked?.(ip);
65
+ const key = ip && isIP(ip) ? ip : "invalid";
66
+ const now = Date.now();
67
+ const last = this.lastLogged.get(key);
68
+ if (last !== void 0 && now - last < LOG_INTERVAL_MS) return;
69
+ this.lastLogged.delete(key);
70
+ this.lastLogged.set(key, now);
71
+ if (this.lastLogged.size > MAX_TRACKED_IPS) {
72
+ const oldest = this.lastLogged.keys().next().value;
73
+ if (oldest !== void 0) this.lastLogged.delete(oldest);
74
+ }
75
+ if (!this.options.onBlocked) {
76
+ this.logger.warn(`Blocked request from non-allowlisted IP ${key}`);
77
+ }
78
+ }
79
+ };
80
+ IpAllowlistGuard = __decorateClass([
81
+ Injectable(),
82
+ __decorateParam(0, Inject(Reflector)),
83
+ __decorateParam(1, Inject(IP_ALLOWLIST_OPTIONS))
84
+ ], IpAllowlistGuard);
85
+
86
+ // src/ip-allowlist.module.ts
87
+ var IpAllowlistModule = class {
88
+ /**
89
+ * Registers the guard globally (APP_GUARD). Import this module BEFORE the
90
+ * module that registers your auth guard so a blocked IP is rejected before
91
+ * any authentication work.
92
+ */
93
+ static forRoot(options = {}) {
94
+ return {
95
+ module: IpAllowlistModule,
96
+ providers: [
97
+ { provide: IP_ALLOWLIST_OPTIONS, useValue: options },
98
+ { provide: APP_GUARD, useClass: IpAllowlistGuard }
99
+ ]
100
+ };
101
+ }
102
+ };
103
+ IpAllowlistModule = __decorateClass([
104
+ Module({})
105
+ ], IpAllowlistModule);
106
+ export {
107
+ IP_ALLOWLIST_OPTIONS,
108
+ IpAllowlistGuard,
109
+ IpAllowlistModule,
110
+ SKIP_IP_ALLOWLIST_KEY,
111
+ SkipIpAllowlist,
112
+ normalizeIp,
113
+ parseIpAllowlist
114
+ };
115
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ip-allowlist.module.ts","../src/ip-allowlist.guard.ts","../src/options.ts","../src/skip-ip-allowlist.decorator.ts"],"sourcesContent":["import { Module, type DynamicModule } from \"@nestjs/common\";\nimport { APP_GUARD } from \"@nestjs/core\";\nimport { IpAllowlistGuard } from \"./ip-allowlist.guard.js\";\nimport { IP_ALLOWLIST_OPTIONS, type IpAllowlistOptions } from \"./options.js\";\n\n@Module({})\nexport class IpAllowlistModule {\n /**\n * Registers the guard globally (APP_GUARD). Import this module BEFORE the\n * module that registers your auth guard so a blocked IP is rejected before\n * any authentication work.\n */\n static forRoot(options: IpAllowlistOptions = {}): DynamicModule {\n return {\n module: IpAllowlistModule,\n providers: [\n { provide: IP_ALLOWLIST_OPTIONS, useValue: options },\n { provide: APP_GUARD, useClass: IpAllowlistGuard },\n ],\n };\n }\n}\n","import {\n ForbiddenException,\n Inject,\n Injectable,\n Logger,\n type CanActivate,\n type ExecutionContext,\n} from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\nimport { isIP } from \"node:net\";\nimport { IP_ALLOWLIST_OPTIONS, type IpAllowlistOptions } from \"./options.js\";\nimport { parseIpAllowlist, type IpMatcher } from \"./ip-matcher.js\";\nimport { SKIP_IP_ALLOWLIST_KEY } from \"./skip-ip-allowlist.decorator.js\";\n\n// Default log line is rate-limited per IP; the map is bounded by evicting the OLDEST\n// entry, so rotating through many IPs can never switch logging off.\nconst LOG_INTERVAL_MS = 60_000;\nconst MAX_TRACKED_IPS = 1000;\n\n/**\n * Restricts routes by source IP. Reads `request.ip`, which Express/Fastify\n * resolve through their own `trust proxy` setting — configure it so `req.ip`\n * is the real client behind your proxy (see `buildTrustProxy` in the\n * `/fastify` entry). `X-Forwarded-For` is never read here.\n */\n@Injectable()\nexport class IpAllowlistGuard implements CanActivate {\n private readonly logger = new Logger(IpAllowlistGuard.name);\n private readonly protectedMatcher: IpMatcher | null;\n private readonly publicMatcher: IpMatcher | null;\n private readonly publicKey: string;\n private readonly lastLogged = new Map<string, number>();\n\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(IP_ALLOWLIST_OPTIONS) private readonly options: IpAllowlistOptions,\n ) {\n const parse = { allowLoopback: options.allowLoopback ?? true };\n this.protectedMatcher = parseIpAllowlist(options.protected, \"protected\", parse);\n this.publicMatcher = parseIpAllowlist(options.public, \"public\", parse);\n this.publicKey = options.publicMetadataKey ?? \"isPublic\";\n }\n\n canActivate(ctx: ExecutionContext): boolean {\n // Only microservice (RPC) traffic is exempt: it has no client IP and is internal\n // transport. Any other context type (graphql, ws, ...) is NOT skipped — it has no\n // resolvable `req.ip` here, so it is denied when a list is enforced (fail closed).\n const type = ctx.getType<string>();\n if (type === \"rpc\") return true;\n if (!this.protectedMatcher && !this.publicMatcher) return true;\n\n const targets = [ctx.getHandler(), ctx.getClass()];\n if (this.reflector.getAllAndOverride<boolean>(SKIP_IP_ALLOWLIST_KEY, targets)) return true;\n\n const isPublic = this.reflector.getAllAndOverride<boolean>(this.publicKey, targets);\n const matcher = isPublic ? this.publicMatcher : this.protectedMatcher;\n if (!matcher) return true;\n\n const ip = type === \"http\" ? ctx.switchToHttp().getRequest<{ ip?: string }>().ip : undefined;\n if (matcher(ip)) return true;\n\n this.notifyBlocked(ip);\n throw new ForbiddenException(\"ip_not_allowed\");\n }\n\n private notifyBlocked(ip: string | undefined): void {\n this.options.onBlocked?.(ip);\n\n // Never log attacker-controlled text: only a well-formed IP is echoed.\n const key = ip && isIP(ip) ? ip : \"invalid\";\n const now = Date.now();\n const last = this.lastLogged.get(key);\n if (last !== undefined && now - last < LOG_INTERVAL_MS) return;\n this.lastLogged.delete(key);\n this.lastLogged.set(key, now);\n if (this.lastLogged.size > MAX_TRACKED_IPS) {\n const oldest = this.lastLogged.keys().next().value;\n if (oldest !== undefined) this.lastLogged.delete(oldest);\n }\n if (!this.options.onBlocked) {\n this.logger.warn(`Blocked request from non-allowlisted IP ${key}`);\n }\n }\n}\n","export const IP_ALLOWLIST_OPTIONS = Symbol(\"IP_ALLOWLIST_OPTIONS\");\n\nexport interface IpAllowlistOptions {\n /**\n * Allowlist for protected (non-public) routes: comma-separated string or\n * array of IPs/CIDRs. Unset/blank = not enforced.\n */\n protected?: string | readonly string[];\n /**\n * Allowlist for public (\"open\") routes, i.e. routes carrying the metadata key\n * below. Unset/blank = not enforced.\n */\n public?: string | readonly string[];\n /**\n * Metadata key that marks a route as public. Defaults to `'isPublic'`, the\n * key used by the common `@Public()` decorator (`SetMetadata('isPublic', true)`).\n */\n publicMetadataKey?: string;\n /**\n * Always allow loopback once a list is set. Default `true`. Set `false` if a\n * reverse proxy runs on the same host and `req.ip` could be its loopback address.\n */\n allowLoopback?: boolean;\n /**\n * Called on EVERY blocked request (feed your metrics/alerting from here).\n * The default Nest Logger warning is rate-limited per IP; this hook is not.\n */\n onBlocked?: (ip: string | undefined) => void;\n}\n","import { SetMetadata } from \"@nestjs/common\";\n\nexport const SKIP_IP_ALLOWLIST_KEY = \"skipIpAllowlist\";\n\n/**\n * Exempts a route (or controller) from the guard. For callers whose IPs cannot\n * be pinned down and that authenticate by other means (e.g. provider webhooks\n * verified by an HMAC signature).\n */\nexport const SkipIpAllowlist = (): MethodDecorator & ClassDecorator =>\n SetMetadata(SKIP_IP_ALLOWLIST_KEY, true);\n"],"mappings":";;;;;;;;AAAA,SAAS,cAAkC;AAC3C,SAAS,iBAAiB;;;ACD1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,iBAAiB;AAC1B,SAAS,YAAY;;;ACTd,IAAM,uBAAuB,uBAAO,sBAAsB;;;ACAjE,SAAS,mBAAmB;AAErB,IAAM,wBAAwB;AAO9B,IAAM,kBAAkB,MAC7B,YAAY,uBAAuB,IAAI;;;AFMzC,IAAM,kBAAkB;AACxB,IAAM,kBAAkB;AASjB,IAAM,mBAAN,MAA8C;AAAA,EAOnD,YACsC,WACW,SAC/C;AAFoC;AACW;AAE/C,UAAM,QAAQ,EAAE,eAAe,QAAQ,iBAAiB,KAAK;AAC7D,SAAK,mBAAmB,iBAAiB,QAAQ,WAAW,aAAa,KAAK;AAC9E,SAAK,gBAAgB,iBAAiB,QAAQ,QAAQ,UAAU,KAAK;AACrE,SAAK,YAAY,QAAQ,qBAAqB;AAAA,EAChD;AAAA,EAPsC;AAAA,EACW;AAAA,EARhC,SAAS,IAAI,OAAO,iBAAiB,IAAI;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa,oBAAI,IAAoB;AAAA,EAYtD,YAAY,KAAgC;AAI1C,UAAM,OAAO,IAAI,QAAgB;AACjC,QAAI,SAAS,MAAO,QAAO;AAC3B,QAAI,CAAC,KAAK,oBAAoB,CAAC,KAAK,cAAe,QAAO;AAE1D,UAAM,UAAU,CAAC,IAAI,WAAW,GAAG,IAAI,SAAS,CAAC;AACjD,QAAI,KAAK,UAAU,kBAA2B,uBAAuB,OAAO,EAAG,QAAO;AAEtF,UAAM,WAAW,KAAK,UAAU,kBAA2B,KAAK,WAAW,OAAO;AAClF,UAAM,UAAU,WAAW,KAAK,gBAAgB,KAAK;AACrD,QAAI,CAAC,QAAS,QAAO;AAErB,UAAM,KAAK,SAAS,SAAS,IAAI,aAAa,EAAE,WAA4B,EAAE,KAAK;AACnF,QAAI,QAAQ,EAAE,EAAG,QAAO;AAExB,SAAK,cAAc,EAAE;AACrB,UAAM,IAAI,mBAAmB,gBAAgB;AAAA,EAC/C;AAAA,EAEQ,cAAc,IAA8B;AAClD,SAAK,QAAQ,YAAY,EAAE;AAG3B,UAAM,MAAM,MAAM,KAAK,EAAE,IAAI,KAAK;AAClC,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,OAAO,KAAK,WAAW,IAAI,GAAG;AACpC,QAAI,SAAS,UAAa,MAAM,OAAO,gBAAiB;AACxD,SAAK,WAAW,OAAO,GAAG;AAC1B,SAAK,WAAW,IAAI,KAAK,GAAG;AAC5B,QAAI,KAAK,WAAW,OAAO,iBAAiB;AAC1C,YAAM,SAAS,KAAK,WAAW,KAAK,EAAE,KAAK,EAAE;AAC7C,UAAI,WAAW,OAAW,MAAK,WAAW,OAAO,MAAM;AAAA,IACzD;AACA,QAAI,CAAC,KAAK,QAAQ,WAAW;AAC3B,WAAK,OAAO,KAAK,2CAA2C,GAAG,EAAE;AAAA,IACnE;AAAA,EACF;AACF;AAzDa,mBAAN;AAAA,EADN,WAAW;AAAA,EASP,0BAAO,SAAS;AAAA,EAChB,0BAAO,oBAAoB;AAAA,GATnB;;;ADpBN,IAAM,oBAAN,MAAwB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM7B,OAAO,QAAQ,UAA8B,CAAC,GAAkB;AAC9D,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,WAAW;AAAA,QACT,EAAE,SAAS,sBAAsB,UAAU,QAAQ;AAAA,QACnD,EAAE,SAAS,WAAW,UAAU,iBAAiB;AAAA,MACnD;AAAA,IACF;AAAA,EACF;AACF;AAfa,oBAAN;AAAA,EADN,OAAO,CAAC,CAAC;AAAA,GACG;","names":[]}
@@ -0,0 +1,22 @@
1
+ type IpMatcher = (ip: string | undefined) => boolean;
2
+ interface ParseOptions {
3
+ /**
4
+ * Always allow loopback (`127.0.0.0/8`, `::1`) once a list is set. Default `true`
5
+ * (local dev, health probes). Set `false` when a reverse proxy runs on the SAME
6
+ * host and `req.ip` may fall back to its loopback address — otherwise a proxy
7
+ * without trust-proxy configured makes every client look like 127.0.0.1.
8
+ */
9
+ allowLoopback?: boolean;
10
+ }
11
+ /** `::ffff:1.2.3.4` (what a dual-stack socket reports for IPv4 peers) → `1.2.3.4`. */
12
+ declare function normalizeIp(ip: string): string;
13
+ /**
14
+ * Builds a matcher from a comma-separated string or an array of IPs/CIDRs
15
+ * (IPv4 + IPv6). Returns `null` when the list is unset/blank (= not enforced).
16
+ * Loopback is part of an enforced list by default (see `allowLoopback`). Throws on a malformed entry — a typo must not silently turn
17
+ * into "everyone allowed" or "everyone blocked". `label` names the option in
18
+ * the error message.
19
+ */
20
+ declare function parseIpAllowlist(value: string | readonly string[] | undefined, label?: string, { allowLoopback }?: ParseOptions): IpMatcher | null;
21
+
22
+ export { type IpMatcher as I, normalizeIp as n, parseIpAllowlist as p };
@@ -0,0 +1,22 @@
1
+ type IpMatcher = (ip: string | undefined) => boolean;
2
+ interface ParseOptions {
3
+ /**
4
+ * Always allow loopback (`127.0.0.0/8`, `::1`) once a list is set. Default `true`
5
+ * (local dev, health probes). Set `false` when a reverse proxy runs on the SAME
6
+ * host and `req.ip` may fall back to its loopback address — otherwise a proxy
7
+ * without trust-proxy configured makes every client look like 127.0.0.1.
8
+ */
9
+ allowLoopback?: boolean;
10
+ }
11
+ /** `::ffff:1.2.3.4` (what a dual-stack socket reports for IPv4 peers) → `1.2.3.4`. */
12
+ declare function normalizeIp(ip: string): string;
13
+ /**
14
+ * Builds a matcher from a comma-separated string or an array of IPs/CIDRs
15
+ * (IPv4 + IPv6). Returns `null` when the list is unset/blank (= not enforced).
16
+ * Loopback is part of an enforced list by default (see `allowLoopback`). Throws on a malformed entry — a typo must not silently turn
17
+ * into "everyone allowed" or "everyone blocked". `label` names the option in
18
+ * the error message.
19
+ */
20
+ declare function parseIpAllowlist(value: string | readonly string[] | undefined, label?: string, { allowLoopback }?: ParseOptions): IpMatcher | null;
21
+
22
+ export { type IpMatcher as I, normalizeIp as n, parseIpAllowlist as p };
package/package.json CHANGED
@@ -1,6 +1,103 @@
1
1
  {
2
2
  "name": "@idevconn/allowlist-guard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "description": "Global NestJS guard that restricts routes by source IP/CIDR, with separate allowlists for protected and public routes. Works on Fastify and Express.",
5
+ "license": "Apache-2.0",
6
+ "author": "iDEVconn",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/iDEVconn/allowListGuard.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/iDEVconn/allowListGuard/issues"
13
+ },
14
+ "homepage": "https://github.com/iDEVconn/allowListGuard#readme",
15
+ "keywords": [
16
+ "nestjs",
17
+ "guard",
18
+ "ip",
19
+ "allowlist",
20
+ "whitelist",
21
+ "cidr",
22
+ "fastify",
23
+ "express"
24
+ ],
25
+ "type": "module",
26
+ "main": "./dist/index.cjs",
27
+ "module": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "import": {
32
+ "types": "./dist/index.d.ts",
33
+ "default": "./dist/index.js"
34
+ },
35
+ "require": {
36
+ "types": "./dist/index.d.cts",
37
+ "default": "./dist/index.cjs"
38
+ }
39
+ },
40
+ "./fastify": {
41
+ "import": {
42
+ "types": "./dist/fastify.d.ts",
43
+ "default": "./dist/fastify.js"
44
+ },
45
+ "require": {
46
+ "types": "./dist/fastify.d.cts",
47
+ "default": "./dist/fastify.cjs"
48
+ }
49
+ }
50
+ },
51
+ "files": [
52
+ "dist",
53
+ "README.md",
54
+ "LICENSE"
55
+ ],
56
+ "scripts": {
57
+ "build": "tsup",
58
+ "dev": "tsup --watch",
59
+ "test": "vitest run",
60
+ "test:watch": "vitest",
61
+ "lint": "eslint src",
62
+ "typecheck": "tsc --noEmit",
63
+ "prepublishOnly": "npm run typecheck && npm run test && npm run build",
64
+ "changeset": "changeset",
65
+ "version": "changeset version"
66
+ },
67
+ "peerDependencies": {
68
+ "@nestjs/common": "^10.0.0 || ^11.0.0",
69
+ "@nestjs/core": "^10.0.0 || ^11.0.0",
70
+ "fastify": ">=4.0.0",
71
+ "reflect-metadata": "^0.1.13 || ^0.2.0",
72
+ "rxjs": "^7.0.0"
73
+ },
74
+ "peerDependenciesMeta": {
75
+ "fastify": {
76
+ "optional": true
77
+ }
78
+ },
79
+ "devDependencies": {
80
+ "@changesets/cli": "^3.0.1",
81
+ "@nestjs/common": "^11.2.3",
82
+ "@nestjs/core": "^11.2.3",
83
+ "@nestjs/platform-express": "^11.2.3",
84
+ "@nestjs/platform-fastify": "^11.2.3",
85
+ "@nestjs/testing": "^11.2.3",
86
+ "@types/node": "^22.0.0",
87
+ "@typescript-eslint/eslint-plugin": "^8.0.0",
88
+ "@typescript-eslint/parser": "^8.0.0",
89
+ "eslint": "^9.0.0",
90
+ "fastify": "^5.0.0",
91
+ "reflect-metadata": "^0.2.2",
92
+ "rxjs": "^7.8.2",
93
+ "tsup": "^8.3.0",
94
+ "typescript": "^5.5.0",
95
+ "vitest": "^4.1.7"
96
+ },
97
+ "publishConfig": {
98
+ "access": "public"
99
+ },
100
+ "allowScripts": {
101
+ "esbuild@0.27.7": true
102
+ }
103
+ }