@network-decode/node-guard 0.0.0-stage → 0.2.0-alpha.6
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/CONTRIBUTING.md +3 -0
- package/DEVELOPER_SETUP.md +33 -0
- package/LICENSE +176 -0
- package/NEXT_ROUTE_GUIDE.md +27 -0
- package/README.md +66 -2
- package/SECURITY.md +3 -0
- package/bin/nodeguard.mjs +76 -0
- package/examples/auth-observations.json +22 -0
- package/examples/auth-policy.json +12 -0
- package/express.d.ts +14 -0
- package/express.mjs +24 -0
- package/guard-core.mjs +162 -0
- package/index.d.ts +45 -0
- package/index.mjs +8 -0
- package/next-route.d.ts +11 -0
- package/next-route.mjs +28 -0
- package/package.json +80 -4
- package/policy-runtime.d.ts +31 -0
- package/policy-runtime.mjs +128 -0
- package/policy.d.ts +33 -0
- package/policy.mjs +92 -0
- package/trusted-source.d.ts +7 -0
- package/trusted-source.mjs +40 -0
package/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Open a focused issue or pull request with a reproducible case. Run `npm test` and `npm run smoke:package` before submitting. Do not include customer data, secrets, private HoneyMesh bridge code, or proprietary release artifacts. Security issues should follow SECURITY.md.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Developer setup
|
|
2
|
+
|
|
3
|
+
1. Use Node.js 20 or newer in a persistent Node process. Install `@network-decode/node-guard@0.2.0-alpha.6` and run `npx nodeguard init`.
|
|
4
|
+
2. Run `npx nodeguard doctor nodeguard.policy.json`. The `source_trust: not checked` result means the CLI cannot verify your ingress topology.
|
|
5
|
+
3. Inspect the generated OBSERVE policy. Set `application_id` and `route_id` to stable identifiers. Keep `mode` as `OBSERVE` until normal traffic has been reviewed.
|
|
6
|
+
4. Determine the actual socket peer address. If a reverse proxy is used, list each trusted proxy IP in `createTrustedSourceResolver({ trustedProxyIps })`. Never trust `X-Forwarded-For` from an unlisted peer.
|
|
7
|
+
5. Let application authentication and route handlers identify verified events. Use `createPolicyGuardV1` and call `record` for explicit events only. Use a random unique `event_id` for each observation. Avoid logging credentials or request bodies.
|
|
8
|
+
6. Run `nodeguard policy test` against representative sanitized observations. Use the decision callback and your own monitoring to review normal activity in OBSERVE.
|
|
9
|
+
7. To enforce, change the policy mode to `ENFORCE`, define `canActOnSource` to exclude management and other protected addresses, restart the application, and test with a noncritical source. Use `createExpressNodeGuard` or `createNextRouteGuard` to apply the resulting application restriction. If behavior is unexpected, revert to OBSERVE and restart; `guard.release(ip)` removes a specific local restriction in a running process.
|
|
10
|
+
8. Treat each worker as independent. A restart clears in-memory state. There is no shared quota or durable audit store in this alpha.
|
|
11
|
+
|
|
12
|
+
## Express outline
|
|
13
|
+
|
|
14
|
+
```js
|
|
15
|
+
import express from 'express';
|
|
16
|
+
import { createPolicyGuardV1 } from '@network-decode/node-guard/policy-runtime';
|
|
17
|
+
import { createExpressNodeGuard } from '@network-decode/node-guard/express';
|
|
18
|
+
import { createTrustedSourceResolver } from '@network-decode/node-guard/trusted-source';
|
|
19
|
+
import policy from './nodeguard.policy.json' with { type: 'json' };
|
|
20
|
+
|
|
21
|
+
const app = express();
|
|
22
|
+
const source = createTrustedSourceResolver({ trustedProxyIps: ['127.0.0.1'] });
|
|
23
|
+
const guard = createPolicyGuardV1({ policy, canActOnSource: (ip) => !protectedIps.has(ip) });
|
|
24
|
+
app.use(createExpressNodeGuard({ guard, getVerifiedSourceIp: source }));
|
|
25
|
+
// In the login handler, after verifying a failed login, record an observation.
|
|
26
|
+
// See examples/auth-observations.json for its complete v1 shape.
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Replace `protectedIps` with your own explicit protected-source set and `trustedProxyIps` with the actual immediate proxies. The sample proxy IP is illustrative. `createExpressNodeGuard` replies `429` for THROTTLE and `403` for DENY and includes `Retry-After`.
|
|
30
|
+
|
|
31
|
+
## Recovery
|
|
32
|
+
|
|
33
|
+
Application restrictions are local and temporary. On an unexpected restriction, call `guard.release(verifiedIp)` from an authenticated operator path or switch back to OBSERVE and restart. Never expose release without authentication. HoneyMesh host enforcement, when separately installed, has its own recovery procedure.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
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 name) to the interfaces of,
|
|
46
|
+
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
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Next.js Route Handler integration
|
|
2
|
+
|
|
3
|
+
Use Node Guard only in App Router Route Handlers that execute in the Node.js runtime. The default in-memory state is tied to one persistent process. Edge and serverless instances are outside this alpha's qualified scope.
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
export const runtime = 'nodejs';
|
|
7
|
+
|
|
8
|
+
import { createNextRouteGuard } from '@network-decode/node-guard/next-route';
|
|
9
|
+
|
|
10
|
+
const check = createNextRouteGuard({
|
|
11
|
+
guard,
|
|
12
|
+
getVerifiedSourceIp: async (request) => ingress.getVerifiedSourceIp(request),
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export async function POST(request) {
|
|
16
|
+
const restriction = await check(request);
|
|
17
|
+
if (restriction) return restriction;
|
|
18
|
+
// Authenticate, process the request, and record only verified security events.
|
|
19
|
+
return Response.json({ ok: true });
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`ingress.getVerifiedSourceIp` is an application-owned function backed by a trusted deployment boundary. Next Route Handler `Request` does not by itself establish a trusted socket peer. Do not take `X-Forwarded-For` directly from the request without authenticating the ingress path. If the source cannot be verified, the adapter returns `503` with `Cache-Control: no-store`.
|
|
24
|
+
|
|
25
|
+
With Next.js Cache Components enabled, omit the `runtime` export; that mode uses the Node.js runtime by default. The installed Next.js 16.4.3 documentation marks Edge runtime as deprecated.
|
|
26
|
+
|
|
27
|
+
For a deployment with multiple workers or changing serverless instances, use OBSERVE only until a qualified shared state adapter exists. Never claim a fleet-wide rate limit from one process's memory.
|
package/README.md
CHANGED
|
@@ -1,3 +1,67 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Node Guard Free
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Node Guard Free is a local application protection SDK for Node.js. It requires no account, license key, HoneyMesh agent, root access, or subscription. It does not attach XDP, enforce host firewall rules, or participate in Exchange.
|
|
4
|
+
|
|
5
|
+
**Status:** experimental alpha for evaluation. This release is not a promise of production support.
|
|
6
|
+
|
|
7
|
+
## Supported scope
|
|
8
|
+
|
|
9
|
+
- Node.js 20 or newer, one persistent Node.js process.
|
|
10
|
+
- Express adapter and Next.js App Router Route Handler adapter in the Node.js runtime.
|
|
11
|
+
- Explicit source verification and application-level observe, throttle, or deny decisions.
|
|
12
|
+
- In-memory state. Restart clears restrictions; workers and replicas do not share state.
|
|
13
|
+
- Only explicitly recorded observations count. The SDK does not infer hostile behavior from every HTTP response.
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
Install the published alpha with:
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
npm install @network-decode/node-guard@0.2.0-alpha.6
|
|
21
|
+
npx nodeguard init
|
|
22
|
+
npx nodeguard doctor nodeguard.policy.json
|
|
23
|
+
npx nodeguard policy validate nodeguard.policy.json
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
For source evaluation, clone this repository, run `npm ci`, `npm test`, `npm run typecheck`, and `npm run smoke:package`. `init` writes an OBSERVE policy with permissions `0600` and refuses to overwrite an existing file. Review the application ID, route, source trust, and exclusions before enabling ENFORCE.
|
|
27
|
+
|
|
28
|
+
A direct application decision can be created with the v1 engine:
|
|
29
|
+
|
|
30
|
+
```js
|
|
31
|
+
import { createPolicyGuardV1 } from '@network-decode/node-guard/policy-runtime';
|
|
32
|
+
|
|
33
|
+
const policy = {
|
|
34
|
+
schema_version: 1, policy_id: 'login-v1', application_id: 'billing-api',
|
|
35
|
+
mode: 'OBSERVE', route_id: 'auth.login', reason_code: 'authentication_failure',
|
|
36
|
+
window_seconds: 60, threshold: 5, action: 'THROTTLE', restriction_seconds: 60,
|
|
37
|
+
};
|
|
38
|
+
const guard = createPolicyGuardV1({ policy, canActOnSource: (ip) => !protectedIps.has(ip) });
|
|
39
|
+
// After your application verifies the source and detects a failed login:
|
|
40
|
+
// guard.record({ schema_version: 1, application_id: 'billing-api',
|
|
41
|
+
// event_id: crypto.randomUUID(), observed_at: new Date().toISOString(),
|
|
42
|
+
// route_id: 'auth.login', reason_code: 'authentication_failure',
|
|
43
|
+
// source_ip: verifiedSourceIp, protocol: 'HTTPS' });
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
See [developer setup](DEVELOPER_SETUP.md) and [Next route guide](NEXT_ROUTE_GUIDE.md) for complete integration rules. `nodeguard policy test` simulates decisions at a specified timestamp.
|
|
47
|
+
|
|
48
|
+
## Security model
|
|
49
|
+
|
|
50
|
+
The application owns authentication and supplies verified client identity. Only trust forwarding headers from explicitly named proxy IPs. The enforcement mode requires a `canActOnSource` callback so operators can protect management addresses. Never derive `source_ip` or a subject from an untrusted request body or arbitrary header. The application must call `record` only after it has verified an event, such as an authentication failure.
|
|
51
|
+
|
|
52
|
+
This package stores no request bodies, tokens, or passwords. The default state is local to one process and bounded by `maxSources` and `maxObservations`. A full state store, management API, and console are later phases. The private HoneyMesh bridge remains a separate paid host integration and is not present in this package.
|
|
53
|
+
|
|
54
|
+
## Commands
|
|
55
|
+
|
|
56
|
+
- `nodeguard init [--output file]`
|
|
57
|
+
- `nodeguard doctor [policy.json]`
|
|
58
|
+
- `nodeguard policy validate policy.json`
|
|
59
|
+
- `nodeguard policy test policy.json observations.json --at 2026-11-03T18:00:00Z`
|
|
60
|
+
- `nodeguard inspect policy.json`
|
|
61
|
+
- `nodeguard export policy.json --output sanitized-policy.json`
|
|
62
|
+
|
|
63
|
+
`export` includes validated policy fields only, no observations or runtime events. It refuses to overwrite files.
|
|
64
|
+
|
|
65
|
+
## License and reporting
|
|
66
|
+
|
|
67
|
+
Apache-2.0. See [LICENSE](LICENSE). Report suspected security issues privately using [SECURITY.md](SECURITY.md).
|
package/SECURITY.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
# Security policy
|
|
2
|
+
|
|
3
|
+
Please report security issues privately to security@network-decode.com. Include the package version, a minimal reproduction, and the expected and observed behavior. Do not post credentials, customer data, or exploit details in a public issue. Node Guard Free is an alpha candidate; supported deployment scope is in README.md.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { simulatePolicyV1, validatePolicyV1 } from "../policy.mjs";
|
|
4
|
+
|
|
5
|
+
const usage = "Usage: nodeguard init [--output <policy.json>] | nodeguard doctor [policy.json] | nodeguard policy validate <policy.json> | nodeguard policy test <policy.json> <observations.json> --at <UTC timestamp> | nodeguard inspect <policy.json> | nodeguard export <policy.json> --output <file>";
|
|
6
|
+
const examplePolicy = new URL("../examples/auth-policy.json", import.meta.url);
|
|
7
|
+
|
|
8
|
+
async function readJson(path) {
|
|
9
|
+
const info = await stat(path);
|
|
10
|
+
if (!info.isFile() || info.size > 1_048_576) throw new Error("input must be a JSON file no larger than 1 MiB");
|
|
11
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async function main(args) {
|
|
15
|
+
if (args[0] === "init" && (args.length === 1 || (args.length === 3 && args[1] === "--output"))) {
|
|
16
|
+
const output = args.length === 3 ? args[2] : "nodeguard.policy.json";
|
|
17
|
+
if (!output || output.startsWith("-")) throw new Error("choose a policy output path");
|
|
18
|
+
const policyText = await readFile(examplePolicy, "utf8");
|
|
19
|
+
validatePolicyV1(JSON.parse(policyText));
|
|
20
|
+
await writeFile(output, policyText, { flag: "wx", mode: 0o600 });
|
|
21
|
+
process.stdout.write(`Created OBSERVE policy: ${output}\nReview application_id, route_id, trusted source, and exclusions before integration.\n`);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
if (args[0] === "doctor" && (args.length === 1 || args.length === 2)) {
|
|
25
|
+
const major = Number(process.versions.node.split(".")[0]);
|
|
26
|
+
if (major < 20) throw new Error("Node.js 20 or newer is required");
|
|
27
|
+
const output = { node: process.version, runtime: "supported", source_trust: "not checked",
|
|
28
|
+
state_scope: "one_process", multi_worker_consistency: "not provided" };
|
|
29
|
+
if (args.length === 2) {
|
|
30
|
+
const policy = validatePolicyV1(await readJson(args[1]));
|
|
31
|
+
output.policy_id = policy.policy_id;
|
|
32
|
+
output.policy_mode = policy.mode;
|
|
33
|
+
}
|
|
34
|
+
process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (args[0] === "inspect" && args.length === 2) {
|
|
38
|
+
const policy = validatePolicyV1(await readJson(args[1]));
|
|
39
|
+
process.stdout.write(`${JSON.stringify({ schema_version: 1, policy_id: policy.policy_id,
|
|
40
|
+
application_id: policy.application_id, route_id: policy.route_id, mode: policy.mode,
|
|
41
|
+
action: policy.action, threshold: policy.threshold, window_seconds: policy.window_seconds,
|
|
42
|
+
restriction_seconds: policy.restriction_seconds, state_scope: "one_process" }, null, 2)}\n`);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (args[0] === "export" && args.length === 4 && args[2] === "--output") {
|
|
46
|
+
const policy = validatePolicyV1(await readJson(args[1]));
|
|
47
|
+
if (!args[3] || args[3].startsWith("-")) throw new Error("choose an export output path");
|
|
48
|
+
const exported = { schema_version: policy.schema_version, policy_id: policy.policy_id,
|
|
49
|
+
application_id: policy.application_id, mode: policy.mode, route_id: policy.route_id,
|
|
50
|
+
reason_code: policy.reason_code, window_seconds: policy.window_seconds,
|
|
51
|
+
threshold: policy.threshold, action: policy.action,
|
|
52
|
+
restriction_seconds: policy.restriction_seconds };
|
|
53
|
+
await writeFile(args[3], `${JSON.stringify(exported, null, 2)}\n`, { flag: "wx", mode: 0o600 });
|
|
54
|
+
process.stdout.write(`Exported policy without runtime events: ${args[3]}\n`);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (args[0] !== "policy") throw new Error(usage);
|
|
58
|
+
if (args[1] === "validate" && args.length === 3) {
|
|
59
|
+
const policy = validatePolicyV1(await readJson(args[2]));
|
|
60
|
+
process.stdout.write(`Valid policy v1: ${policy.policy_id}\n`);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (args[1] === "test" && args.length === 6 && args[4] === "--at") {
|
|
64
|
+
const policy = await readJson(args[2]);
|
|
65
|
+
const observations = await readJson(args[3]);
|
|
66
|
+
const results = simulatePolicyV1(policy, observations, { at: args[5] });
|
|
67
|
+
process.stdout.write(`${JSON.stringify({ schema_version: 1, results }, null, 2)}\n`);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
throw new Error(usage);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
main(process.argv.slice(2)).catch((error) => {
|
|
74
|
+
process.stderr.write(`nodeguard: ${error.message}\n`);
|
|
75
|
+
process.exitCode = 1;
|
|
76
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"schema_version": 1,
|
|
4
|
+
"application_id": "billing-api",
|
|
5
|
+
"event_id": "example-event-0001",
|
|
6
|
+
"observed_at": "2026-11-03T17:59:25Z",
|
|
7
|
+
"route_id": "auth.login",
|
|
8
|
+
"reason_code": "authentication_failure",
|
|
9
|
+
"source_ip": "8.8.8.8",
|
|
10
|
+
"protocol": "HTTPS"
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
"schema_version": 1,
|
|
14
|
+
"application_id": "billing-api",
|
|
15
|
+
"event_id": "example-event-0002",
|
|
16
|
+
"observed_at": "2026-11-03T17:59:35Z",
|
|
17
|
+
"route_id": "auth.login",
|
|
18
|
+
"reason_code": "authentication_failure",
|
|
19
|
+
"source_ip": "8.8.8.8",
|
|
20
|
+
"protocol": "HTTPS"
|
|
21
|
+
}
|
|
22
|
+
]
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema_version": 1,
|
|
3
|
+
"policy_id": "auth-login-v1",
|
|
4
|
+
"application_id": "billing-api",
|
|
5
|
+
"mode": "OBSERVE",
|
|
6
|
+
"route_id": "auth.login",
|
|
7
|
+
"reason_code": "authentication_failure",
|
|
8
|
+
"window_seconds": 60,
|
|
9
|
+
"threshold": 2,
|
|
10
|
+
"action": "THROTTLE",
|
|
11
|
+
"restriction_seconds": 120
|
|
12
|
+
}
|
package/express.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare function createExpressNodeGuard<Request = unknown>(options: {
|
|
2
|
+
guard: {
|
|
3
|
+
restriction(sourceIp: string): {
|
|
4
|
+
expiresAt: string;
|
|
5
|
+
retryAfterSeconds: number;
|
|
6
|
+
action?: "THROTTLE" | "DENY";
|
|
7
|
+
} | null;
|
|
8
|
+
};
|
|
9
|
+
/** Return only an address verified by the application's trusted ingress. */
|
|
10
|
+
getVerifiedSourceIp: (request: Request) => string;
|
|
11
|
+
}): (request: Request, response: {
|
|
12
|
+
set(field: string, value: string): unknown;
|
|
13
|
+
status(code: number): { json(body: unknown): unknown };
|
|
14
|
+
}, next: (error?: unknown) => void) => unknown;
|
package/express.mjs
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Express adapter for a Guard instance and an application-verified source. */
|
|
2
|
+
export function createExpressNodeGuard({ guard, getVerifiedSourceIp } = {}) {
|
|
3
|
+
if (!guard || typeof guard.restriction !== "function") {
|
|
4
|
+
throw new TypeError("guard must provide restriction(sourceIp)");
|
|
5
|
+
}
|
|
6
|
+
if (typeof getVerifiedSourceIp !== "function") {
|
|
7
|
+
throw new TypeError("getVerifiedSourceIp must be a function");
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
return function nodeGuardMiddleware(req, res, next) {
|
|
11
|
+
try {
|
|
12
|
+
const sourceIp = getVerifiedSourceIp(req);
|
|
13
|
+
if (typeof sourceIp !== "string" || sourceIp.length === 0) {
|
|
14
|
+
throw new TypeError("trusted ingress did not provide a verified source IP");
|
|
15
|
+
}
|
|
16
|
+
const restriction = guard.restriction(sourceIp);
|
|
17
|
+
if (!restriction) return next();
|
|
18
|
+
res.set("Retry-After", String(restriction.retryAfterSeconds));
|
|
19
|
+
return res.status(restriction.action === "DENY" ? 403 : 429).json({ error: "node_guard_restricted" });
|
|
20
|
+
} catch (error) {
|
|
21
|
+
return next(error);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
}
|
package/guard-core.mjs
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { BlockList, isIP } from "node:net";
|
|
2
|
+
|
|
3
|
+
export const REASON_CODES = Object.freeze([
|
|
4
|
+
"invalid_signature_burst",
|
|
5
|
+
"replay_burst",
|
|
6
|
+
"anonymous_rate_burst",
|
|
7
|
+
"oversized_body_burst",
|
|
8
|
+
"api_probe_burst",
|
|
9
|
+
]);
|
|
10
|
+
|
|
11
|
+
const DEFAULT_THRESHOLDS = Object.freeze({
|
|
12
|
+
invalid_signature_burst: 12,
|
|
13
|
+
replay_burst: 12,
|
|
14
|
+
anonymous_rate_burst: 40,
|
|
15
|
+
oversized_body_burst: 12,
|
|
16
|
+
api_probe_burst: 20,
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const nonPublic = new BlockList();
|
|
20
|
+
const globalV6 = new BlockList();
|
|
21
|
+
globalV6.addSubnet("2000::", 3, "ipv6");
|
|
22
|
+
for (const [address, prefix] of [
|
|
23
|
+
["0.0.0.0", 8], ["10.0.0.0", 8], ["127.0.0.0", 8],
|
|
24
|
+
["100.64.0.0", 10], ["169.254.0.0", 16], ["172.16.0.0", 12],
|
|
25
|
+
["192.0.0.0", 24], ["192.0.2.0", 24], ["192.168.0.0", 16],
|
|
26
|
+
["198.18.0.0", 15], ["198.51.100.0", 24], ["203.0.113.0", 24],
|
|
27
|
+
["224.0.0.0", 4], ["240.0.0.0", 4],
|
|
28
|
+
]) nonPublic.addSubnet(address, prefix, "ipv4");
|
|
29
|
+
for (const [address, prefix] of [
|
|
30
|
+
["::", 128], ["::1", 128], ["2001:db8::", 32], ["fc00::", 7],
|
|
31
|
+
["fe80::", 10], ["ff00::", 8],
|
|
32
|
+
]) nonPublic.addSubnet(address, prefix, "ipv6");
|
|
33
|
+
|
|
34
|
+
function validPositiveInteger(value, name) {
|
|
35
|
+
if (!Number.isSafeInteger(value) || value < 1) throw new TypeError(`${name} must be a positive integer`);
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function eligibleAddress(address) {
|
|
40
|
+
const family = isIP(address);
|
|
41
|
+
return family !== 0 && !address.toLowerCase().startsWith("::ffff:") &&
|
|
42
|
+
(family === 4 || globalV6.check(address, "ipv6")) &&
|
|
43
|
+
!nonPublic.check(address, family === 4 ? "ipv4" : "ipv6");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function isEligibleSource(address) {
|
|
47
|
+
return typeof address === "string" && eligibleAddress(address);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A bounded application-level guard. The caller must provide a verified client IP.
|
|
52
|
+
* This does not attach XDP or infer an attacker from arbitrary HTTP traffic.
|
|
53
|
+
*/
|
|
54
|
+
export function createGuardCore(options = {}) {
|
|
55
|
+
const mode = options.mode ?? "observe";
|
|
56
|
+
if (mode !== "observe" && mode !== "enforce") throw new TypeError("mode must be observe or enforce");
|
|
57
|
+
if (mode === "enforce" && typeof options.canActOnSource !== "function") {
|
|
58
|
+
throw new TypeError("enforce mode requires canActOnSource");
|
|
59
|
+
}
|
|
60
|
+
const canActOnSource = options.canActOnSource ?? (() => true);
|
|
61
|
+
const onDecision = options.onDecision ?? (() => {});
|
|
62
|
+
const now = options.now ?? Date.now;
|
|
63
|
+
if (typeof canActOnSource !== "function" || typeof onDecision !== "function" || typeof now !== "function") {
|
|
64
|
+
throw new TypeError("callbacks must be functions");
|
|
65
|
+
}
|
|
66
|
+
const windowMs = validPositiveInteger(options.windowMs ?? 60_000, "windowMs");
|
|
67
|
+
const blockMs = validPositiveInteger(options.blockMs ?? 120_000, "blockMs");
|
|
68
|
+
const maxSources = validPositiveInteger(options.maxSources ?? 20_000, "maxSources");
|
|
69
|
+
if (windowMs > 300_000 || blockMs > 300_000 || maxSources > 100_000) {
|
|
70
|
+
throw new RangeError("guard windows and capacity exceed safety limits");
|
|
71
|
+
}
|
|
72
|
+
const thresholds = { ...DEFAULT_THRESHOLDS, ...options.thresholds };
|
|
73
|
+
if (Object.keys(thresholds).some((key) => !REASON_CODES.includes(key))) {
|
|
74
|
+
throw new TypeError("unknown reason code in thresholds");
|
|
75
|
+
}
|
|
76
|
+
for (const [reason, threshold] of Object.entries(thresholds)) {
|
|
77
|
+
validPositiveInteger(threshold, reason);
|
|
78
|
+
if (threshold < 2) throw new RangeError(`${reason} requires at least two observations`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const state = new Map();
|
|
82
|
+
const keyFor = (reasonCode, sourceIp) => `${reasonCode}|${sourceIp}`;
|
|
83
|
+
function policyAllows(sourceIp) {
|
|
84
|
+
try { return canActOnSource(sourceIp) === true; }
|
|
85
|
+
catch { return false; }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function prune(at) {
|
|
89
|
+
for (const [key, entry] of state) {
|
|
90
|
+
entry.hits = entry.hits.filter((hit) => at - hit < windowMs);
|
|
91
|
+
if (entry.hits.length === 0 && entry.blockedUntil <= at && entry.reportedUntil <= at) state.delete(key);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function record({ sourceIp, reasonCode, protocol = "HTTP" } = {}) {
|
|
96
|
+
if (typeof sourceIp !== "string" || !eligibleAddress(sourceIp)) return { accepted: false, reason: "ineligible_source" };
|
|
97
|
+
if (!REASON_CODES.includes(reasonCode)) return { accepted: false, reason: "unknown_reason" };
|
|
98
|
+
if (protocol !== "HTTP" && protocol !== "HTTPS") return { accepted: false, reason: "invalid_protocol" };
|
|
99
|
+
if (!policyAllows(sourceIp)) return { accepted: false, reason: "source_excluded" };
|
|
100
|
+
const at = now();
|
|
101
|
+
const key = keyFor(reasonCode, sourceIp);
|
|
102
|
+
let entry = state.get(key);
|
|
103
|
+
if (!entry) {
|
|
104
|
+
if (state.size >= maxSources) prune(at);
|
|
105
|
+
if (state.size >= maxSources) return { accepted: false, reason: "capacity_exhausted" };
|
|
106
|
+
entry = { hits: [], blockedUntil: 0, reportedUntil: 0, protocol };
|
|
107
|
+
state.set(key, entry);
|
|
108
|
+
}
|
|
109
|
+
entry.hits = entry.hits.filter((hit) => at - hit < windowMs);
|
|
110
|
+
entry.hits.push(at);
|
|
111
|
+
const threshold = thresholds[reasonCode];
|
|
112
|
+
if (entry.hits.length > threshold) entry.hits.shift();
|
|
113
|
+
entry.protocol = protocol;
|
|
114
|
+
if (entry.hits.length < threshold || entry.reportedUntil > at) return { accepted: true, action: "recorded" };
|
|
115
|
+
|
|
116
|
+
entry.reportedUntil = at + windowMs;
|
|
117
|
+
if (mode === "enforce") entry.blockedUntil = at + blockMs;
|
|
118
|
+
const decision = Object.freeze({
|
|
119
|
+
sourceIp, reasonCode, protocol, hitCount: entry.hits.length,
|
|
120
|
+
observedAt: new Date(at).toISOString(),
|
|
121
|
+
action: mode === "enforce" ? "limit_armed" : "observed",
|
|
122
|
+
expiresAt: mode === "enforce" ? new Date(entry.blockedUntil).toISOString() : null,
|
|
123
|
+
});
|
|
124
|
+
Promise.resolve().then(() => onDecision(decision)).catch(() => {});
|
|
125
|
+
return { accepted: true, action: decision.action, decision };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function restriction(sourceIp) {
|
|
129
|
+
if (mode !== "enforce" || typeof sourceIp !== "string" || !eligibleAddress(sourceIp) || !policyAllows(sourceIp)) return null;
|
|
130
|
+
const at = now();
|
|
131
|
+
let blockedUntil = 0;
|
|
132
|
+
for (const reasonCode of REASON_CODES) {
|
|
133
|
+
blockedUntil = Math.max(blockedUntil, state.get(keyFor(reasonCode, sourceIp))?.blockedUntil ?? 0);
|
|
134
|
+
}
|
|
135
|
+
if (blockedUntil <= at) return null;
|
|
136
|
+
return { expiresAt: new Date(blockedUntil).toISOString(), retryAfterSeconds: Math.ceil((blockedUntil - at) / 1_000) };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function isBlocked(sourceIp) {
|
|
140
|
+
return restriction(sourceIp) !== null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function release(sourceIp) {
|
|
144
|
+
let removed = 0;
|
|
145
|
+
for (const reasonCode of REASON_CODES) removed += Number(state.delete(keyFor(reasonCode, sourceIp)));
|
|
146
|
+
return removed;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function snapshot() {
|
|
150
|
+
const at = now();
|
|
151
|
+
prune(at);
|
|
152
|
+
return [...state.entries()].filter(([key, entry]) => entry.blockedUntil > at && policyAllows(key.slice(key.indexOf("|") + 1))).map(([key, entry]) => {
|
|
153
|
+
const separator = key.indexOf("|");
|
|
154
|
+
return {
|
|
155
|
+
reasonCode: key.slice(0, separator), sourceIp: key.slice(separator + 1),
|
|
156
|
+
protocol: entry.protocol, expiresAt: new Date(entry.blockedUntil).toISOString(),
|
|
157
|
+
};
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return Object.freeze({ record, restriction, isBlocked, release, snapshot });
|
|
162
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export type ReasonCode =
|
|
2
|
+
| "invalid_signature_burst"
|
|
3
|
+
| "replay_burst"
|
|
4
|
+
| "anonymous_rate_burst"
|
|
5
|
+
| "oversized_body_burst"
|
|
6
|
+
| "api_probe_burst";
|
|
7
|
+
|
|
8
|
+
export type GuardDecision = Readonly<{
|
|
9
|
+
sourceIp: string;
|
|
10
|
+
reasonCode: ReasonCode;
|
|
11
|
+
protocol: "HTTP" | "HTTPS";
|
|
12
|
+
hitCount: number;
|
|
13
|
+
observedAt: string;
|
|
14
|
+
action: "observed" | "limit_armed";
|
|
15
|
+
expiresAt: string | null;
|
|
16
|
+
}>;
|
|
17
|
+
|
|
18
|
+
export type RecordResult =
|
|
19
|
+
| { accepted: false; reason: "ineligible_source" | "unknown_reason" | "invalid_protocol" | "source_excluded" | "capacity_exhausted" }
|
|
20
|
+
| { accepted: true; action: "recorded" | "observed" | "limit_armed"; decision?: GuardDecision };
|
|
21
|
+
|
|
22
|
+
export declare const REASON_CODES: readonly ReasonCode[];
|
|
23
|
+
export declare function isEligibleSource(address: string): boolean;
|
|
24
|
+
|
|
25
|
+
export type GuardOptions = {
|
|
26
|
+
mode?: "observe" | "enforce";
|
|
27
|
+
thresholds?: Partial<Record<ReasonCode, number>>;
|
|
28
|
+
windowMs?: number;
|
|
29
|
+
blockMs?: number;
|
|
30
|
+
maxSources?: number;
|
|
31
|
+
canActOnSource?: (verifiedClientIp: string) => boolean;
|
|
32
|
+
onDecision?: (decision: GuardDecision) => void | Promise<void>;
|
|
33
|
+
now?: () => number;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export type GuardInstance = Readonly<{
|
|
37
|
+
record(event: { sourceIp: string; reasonCode: ReasonCode; protocol?: "HTTP" | "HTTPS" }): RecordResult;
|
|
38
|
+
restriction(sourceIp: string): { expiresAt: string; retryAfterSeconds: number } | null;
|
|
39
|
+
isBlocked(sourceIp: string): boolean;
|
|
40
|
+
release(sourceIp: string): number;
|
|
41
|
+
snapshot(): Array<{ sourceIp: string; reasonCode: ReasonCode; protocol: "HTTP" | "HTTPS"; expiresAt: string }>;
|
|
42
|
+
}>;
|
|
43
|
+
|
|
44
|
+
/** License-free, in-process application protection; no host-level enforcement. */
|
|
45
|
+
export declare function createNodeGuard(options?: GuardOptions): GuardInstance;
|
package/index.mjs
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createGuardCore, isEligibleSource, REASON_CODES } from "./guard-core.mjs";
|
|
2
|
+
|
|
3
|
+
export { isEligibleSource, REASON_CODES };
|
|
4
|
+
|
|
5
|
+
/** Standalone application protection. It cannot create host or XDP grants. */
|
|
6
|
+
export function createNodeGuard(options = {}) {
|
|
7
|
+
return createGuardCore(options);
|
|
8
|
+
}
|
package/next-route.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare function createNextRouteGuard<RequestType = Request>(options: {
|
|
2
|
+
guard: {
|
|
3
|
+
restriction(sourceIp: string): {
|
|
4
|
+
expiresAt: string;
|
|
5
|
+
retryAfterSeconds: number;
|
|
6
|
+
action?: "THROTTLE" | "DENY";
|
|
7
|
+
} | null;
|
|
8
|
+
};
|
|
9
|
+
/** Must use a deployment-verified source; never raw client headers. */
|
|
10
|
+
getVerifiedSourceIp: (request: RequestType) => string | Promise<string>;
|
|
11
|
+
}): (request: RequestType) => Promise<Response | null>;
|
package/next-route.mjs
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Check one Next.js App Router Route Handler request in the Node.js runtime. */
|
|
2
|
+
export function createNextRouteGuard({ guard, getVerifiedSourceIp } = {}) {
|
|
3
|
+
if (!guard || typeof guard.restriction !== "function") {
|
|
4
|
+
throw new TypeError("guard must provide restriction(sourceIp)");
|
|
5
|
+
}
|
|
6
|
+
if (typeof getVerifiedSourceIp !== "function") {
|
|
7
|
+
throw new TypeError("getVerifiedSourceIp must be a function");
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
return async function checkRoute(request) {
|
|
11
|
+
try {
|
|
12
|
+
const sourceIp = await getVerifiedSourceIp(request);
|
|
13
|
+
if (typeof sourceIp !== "string" || sourceIp.length === 0) {
|
|
14
|
+
throw new TypeError("trusted ingress did not provide a verified source IP");
|
|
15
|
+
}
|
|
16
|
+
const restriction = guard.restriction(sourceIp);
|
|
17
|
+
if (!restriction) return null;
|
|
18
|
+
return Response.json({ error: "node_guard_restricted" }, {
|
|
19
|
+
status: restriction.action === "DENY" ? 403 : 429,
|
|
20
|
+
headers: { "Retry-After": String(restriction.retryAfterSeconds), "Cache-Control": "no-store" },
|
|
21
|
+
});
|
|
22
|
+
} catch {
|
|
23
|
+
return Response.json({ error: "verified_source_unavailable" }, {
|
|
24
|
+
status: 503, headers: { "Cache-Control": "no-store" },
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,82 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@network-decode/node-guard",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0-alpha.6",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Smccann01/node-guard-free.git"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/Smccann01/node-guard-free#readme",
|
|
11
|
+
"bugs": "https://github.com/Smccann01/node-guard-free/issues",
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"README.md",
|
|
17
|
+
"DEVELOPER_SETUP.md",
|
|
18
|
+
"NEXT_ROUTE_GUIDE.md",
|
|
19
|
+
"index.mjs",
|
|
20
|
+
"index.d.ts",
|
|
21
|
+
"guard-core.mjs",
|
|
22
|
+
"express.mjs",
|
|
23
|
+
"express.d.ts",
|
|
24
|
+
"policy.mjs",
|
|
25
|
+
"policy.d.ts",
|
|
26
|
+
"policy-runtime.mjs",
|
|
27
|
+
"policy-runtime.d.ts",
|
|
28
|
+
"trusted-source.mjs",
|
|
29
|
+
"trusted-source.d.ts",
|
|
30
|
+
"next-route.mjs",
|
|
31
|
+
"next-route.d.ts",
|
|
32
|
+
"bin/nodeguard.mjs",
|
|
33
|
+
"examples/auth-policy.json",
|
|
34
|
+
"examples/auth-observations.json",
|
|
35
|
+
"LICENSE",
|
|
36
|
+
"SECURITY.md",
|
|
37
|
+
"CONTRIBUTING.md"
|
|
38
|
+
],
|
|
39
|
+
"exports": {
|
|
40
|
+
".": {
|
|
41
|
+
"types": "./index.d.ts",
|
|
42
|
+
"default": "./index.mjs"
|
|
43
|
+
},
|
|
44
|
+
"./express": {
|
|
45
|
+
"types": "./express.d.ts",
|
|
46
|
+
"default": "./express.mjs"
|
|
47
|
+
},
|
|
48
|
+
"./policy": {
|
|
49
|
+
"types": "./policy.d.ts",
|
|
50
|
+
"default": "./policy.mjs"
|
|
51
|
+
},
|
|
52
|
+
"./policy-runtime": {
|
|
53
|
+
"types": "./policy-runtime.d.ts",
|
|
54
|
+
"default": "./policy-runtime.mjs"
|
|
55
|
+
},
|
|
56
|
+
"./trusted-source": {
|
|
57
|
+
"types": "./trusted-source.d.ts",
|
|
58
|
+
"default": "./trusted-source.mjs"
|
|
59
|
+
},
|
|
60
|
+
"./next-route": {
|
|
61
|
+
"types": "./next-route.d.ts",
|
|
62
|
+
"default": "./next-route.mjs"
|
|
63
|
+
},
|
|
64
|
+
"./package.json": "./package.json"
|
|
65
|
+
},
|
|
66
|
+
"bin": {
|
|
67
|
+
"nodeguard": "bin/nodeguard.mjs"
|
|
68
|
+
},
|
|
69
|
+
"engines": {
|
|
70
|
+
"node": ">=20"
|
|
71
|
+
},
|
|
72
|
+
"scripts": {
|
|
73
|
+
"test": "node --test",
|
|
74
|
+
"typecheck": "tsc --noEmit --strict --module NodeNext --moduleResolution NodeNext --target ES2022 --lib ES2022,DOM scripts/types-smoke.mts",
|
|
75
|
+
"smoke:package": "node scripts/clean-install-smoke.mjs",
|
|
76
|
+
"smoke:next": "node scripts/next-clean-app-smoke.mjs"
|
|
77
|
+
},
|
|
78
|
+
"devDependencies": {
|
|
79
|
+
"express": "^5.3.0",
|
|
80
|
+
"typescript": "5.9.3"
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ObservationV1, PolicyV1 } from "./policy.js";
|
|
2
|
+
|
|
3
|
+
export type PolicyRuntimeDecision = Readonly<{
|
|
4
|
+
schema_version: 1;
|
|
5
|
+
policy_id: string;
|
|
6
|
+
application_id: string;
|
|
7
|
+
route_id: string;
|
|
8
|
+
source_ip: string;
|
|
9
|
+
reason_code: string;
|
|
10
|
+
action: "OBSERVE" | "THROTTLE" | "DENY";
|
|
11
|
+
hit_count: number;
|
|
12
|
+
observed_at: string;
|
|
13
|
+
restriction_expires_at: string | null;
|
|
14
|
+
}>;
|
|
15
|
+
export declare function createPolicyGuardV1(options: {
|
|
16
|
+
policy: PolicyV1;
|
|
17
|
+
canActOnSource?: (verifiedSourceIp: string) => boolean;
|
|
18
|
+
onDecision?: (decision: PolicyRuntimeDecision) => void | Promise<void>;
|
|
19
|
+
now?: () => number;
|
|
20
|
+
maxSources?: number;
|
|
21
|
+
maxObservations?: number;
|
|
22
|
+
}): Readonly<{
|
|
23
|
+
policy: Readonly<PolicyV1>;
|
|
24
|
+
record(observation: ObservationV1):
|
|
25
|
+
| { accepted: false; reason: "policy_mismatch" | "source_excluded" | "outside_window" | "capacity_exhausted" | "duplicate_event" }
|
|
26
|
+
| { accepted: true; action: "recorded" | "OBSERVE" | "THROTTLE" | "DENY"; decision?: PolicyRuntimeDecision };
|
|
27
|
+
restriction(sourceIp: string): { action: "THROTTLE" | "DENY"; policyId: string; expiresAt: string; retryAfterSeconds: number } | null;
|
|
28
|
+
isBlocked(sourceIp: string): boolean;
|
|
29
|
+
release(sourceIp: string): number;
|
|
30
|
+
snapshot(): Array<{ sourceIp: string; action: "THROTTLE" | "DENY"; policyId: string; expiresAt: string; retryAfterSeconds: number }>;
|
|
31
|
+
}>;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { isEligibleSource } from "./guard-core.mjs";
|
|
2
|
+
import { validateObservationV1, validatePolicyV1 } from "./policy.mjs";
|
|
3
|
+
|
|
4
|
+
function boundedInteger(value, name, maximum) {
|
|
5
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > maximum) {
|
|
6
|
+
throw new RangeError(`${name} must be 1-${maximum}`);
|
|
7
|
+
}
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** One policy, one application, one exact route. State is local to this process. */
|
|
12
|
+
export function createPolicyGuardV1({ policy: policyInput, canActOnSource, onDecision = () => {},
|
|
13
|
+
now = Date.now, maxSources = 20_000, maxObservations = 50_000 } = {}) {
|
|
14
|
+
const policy = validatePolicyV1(policyInput);
|
|
15
|
+
if (policy.mode === "ENFORCE" && typeof canActOnSource !== "function") {
|
|
16
|
+
throw new TypeError("ENFORCE requires canActOnSource");
|
|
17
|
+
}
|
|
18
|
+
if (canActOnSource !== undefined && typeof canActOnSource !== "function") throw new TypeError("canActOnSource must be a function");
|
|
19
|
+
if (typeof onDecision !== "function" || typeof now !== "function") throw new TypeError("callbacks must be functions");
|
|
20
|
+
boundedInteger(maxSources, "maxSources", 100_000);
|
|
21
|
+
boundedInteger(maxObservations, "maxObservations", 100_000);
|
|
22
|
+
if (maxObservations < policy.threshold) throw new RangeError("maxObservations must meet the policy threshold");
|
|
23
|
+
const windowMs = policy.window_seconds * 1_000;
|
|
24
|
+
const restrictionMs = policy.restriction_seconds * 1_000;
|
|
25
|
+
const state = new Map();
|
|
26
|
+
const seenIds = new Map();
|
|
27
|
+
|
|
28
|
+
function allows(sourceIp) {
|
|
29
|
+
try { return (canActOnSource ?? (() => true))(sourceIp) === true; }
|
|
30
|
+
catch { return false; }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function pruneEntry(entry, at) {
|
|
34
|
+
for (const [id, observedAt] of entry.hits) {
|
|
35
|
+
if (observedAt <= at - windowMs) {
|
|
36
|
+
entry.hits.delete(id);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function pruneSeen(at) {
|
|
42
|
+
for (const [id, observedAt] of seenIds) {
|
|
43
|
+
if (observedAt <= at - windowMs) seenIds.delete(id);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function prune(at) {
|
|
48
|
+
pruneSeen(at);
|
|
49
|
+
for (const [sourceIp, entry] of state) {
|
|
50
|
+
pruneEntry(entry, at);
|
|
51
|
+
if (entry.hits.size === 0 && entry.restrictionUntil <= at && entry.reportedUntil <= at) state.delete(sourceIp);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function record(input) {
|
|
56
|
+
const observation = validateObservationV1(input);
|
|
57
|
+
if (observation.application_id !== policy.application_id || observation.route_id !== policy.route_id ||
|
|
58
|
+
observation.reason_code !== policy.reason_code) return { accepted: false, reason: "policy_mismatch" };
|
|
59
|
+
if (!allows(observation.source_ip)) return { accepted: false, reason: "source_excluded" };
|
|
60
|
+
const at = now();
|
|
61
|
+
if (!Number.isSafeInteger(at)) throw new TypeError("now must return epoch milliseconds");
|
|
62
|
+
const observedAt = Date.parse(observation.observed_at);
|
|
63
|
+
if (observedAt <= at - windowMs || observedAt > at + 5_000) return { accepted: false, reason: "outside_window" };
|
|
64
|
+
const prior = seenIds.get(observation.event_id);
|
|
65
|
+
if (prior !== undefined && prior > at - windowMs) return { accepted: false, reason: "duplicate_event" };
|
|
66
|
+
if (prior !== undefined) seenIds.delete(observation.event_id);
|
|
67
|
+
if (seenIds.size >= maxObservations) pruneSeen(at);
|
|
68
|
+
if (seenIds.size >= maxObservations) return { accepted: false, reason: "capacity_exhausted" };
|
|
69
|
+
|
|
70
|
+
let entry = state.get(observation.source_ip);
|
|
71
|
+
if (entry) pruneEntry(entry, at);
|
|
72
|
+
if (!entry) {
|
|
73
|
+
if (state.size >= maxSources) prune(at);
|
|
74
|
+
if (state.size >= maxSources) return { accepted: false, reason: "capacity_exhausted" };
|
|
75
|
+
entry = { hits: new Map(), restrictionUntil: 0, reportedUntil: 0 };
|
|
76
|
+
state.set(observation.source_ip, entry);
|
|
77
|
+
}
|
|
78
|
+
if (entry.hits.size >= policy.threshold) {
|
|
79
|
+
entry.hits.delete(entry.hits.keys().next().value);
|
|
80
|
+
}
|
|
81
|
+
entry.hits.set(observation.event_id, observedAt);
|
|
82
|
+
seenIds.set(observation.event_id, observedAt);
|
|
83
|
+
if (entry.hits.size < policy.threshold || entry.reportedUntil > at) return { accepted: true, action: "recorded" };
|
|
84
|
+
|
|
85
|
+
entry.reportedUntil = at + windowMs;
|
|
86
|
+
if (policy.mode === "ENFORCE") entry.restrictionUntil = at + restrictionMs;
|
|
87
|
+
const decision = Object.freeze({
|
|
88
|
+
schema_version: 1, policy_id: policy.policy_id, application_id: policy.application_id,
|
|
89
|
+
route_id: policy.route_id, source_ip: observation.source_ip, reason_code: policy.reason_code,
|
|
90
|
+
action: policy.mode === "OBSERVE" ? "OBSERVE" : policy.action,
|
|
91
|
+
hit_count: entry.hits.size, observed_at: new Date(at).toISOString(),
|
|
92
|
+
restriction_expires_at: policy.mode === "ENFORCE" ? new Date(entry.restrictionUntil).toISOString() : null,
|
|
93
|
+
});
|
|
94
|
+
Promise.resolve().then(() => onDecision(decision)).catch(() => {});
|
|
95
|
+
return { accepted: true, action: decision.action, decision };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function restriction(sourceIp) {
|
|
99
|
+
if (policy.mode !== "ENFORCE" || !isEligibleSource(sourceIp) || !allows(sourceIp)) return null;
|
|
100
|
+
const at = now();
|
|
101
|
+
const entry = state.get(sourceIp);
|
|
102
|
+
if (!entry || entry.restrictionUntil <= at) return null;
|
|
103
|
+
return {
|
|
104
|
+
action: policy.action, policyId: policy.policy_id,
|
|
105
|
+
expiresAt: new Date(entry.restrictionUntil).toISOString(),
|
|
106
|
+
retryAfterSeconds: Math.ceil((entry.restrictionUntil - at) / 1_000),
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function release(sourceIp) {
|
|
111
|
+
const entry = state.get(sourceIp);
|
|
112
|
+
if (!entry) return 0;
|
|
113
|
+
state.delete(sourceIp);
|
|
114
|
+
return 1;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function snapshot() {
|
|
118
|
+
const at = now();
|
|
119
|
+
prune(at);
|
|
120
|
+
if (policy.mode !== "ENFORCE") return [];
|
|
121
|
+
return [...state.keys()].filter((sourceIp) => allows(sourceIp)).map((sourceIp) => {
|
|
122
|
+
const active = restriction(sourceIp);
|
|
123
|
+
return active ? { sourceIp, ...active } : null;
|
|
124
|
+
}).filter(Boolean);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return Object.freeze({ policy, record, restriction, isBlocked: (sourceIp) => restriction(sourceIp) !== null, release, snapshot });
|
|
128
|
+
}
|
package/policy.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export type PolicyReasonCode = import("./index.js").ReasonCode | "authentication_failure";
|
|
2
|
+
export type PolicyV1 = {
|
|
3
|
+
schema_version: 1;
|
|
4
|
+
policy_id: string;
|
|
5
|
+
application_id: string;
|
|
6
|
+
mode: "OBSERVE" | "ENFORCE";
|
|
7
|
+
route_id: string;
|
|
8
|
+
reason_code: PolicyReasonCode;
|
|
9
|
+
window_seconds: number;
|
|
10
|
+
threshold: number;
|
|
11
|
+
action: "THROTTLE" | "DENY";
|
|
12
|
+
restriction_seconds: number;
|
|
13
|
+
};
|
|
14
|
+
export type ObservationV1 = {
|
|
15
|
+
schema_version: 1;
|
|
16
|
+
application_id: string;
|
|
17
|
+
event_id: string;
|
|
18
|
+
observed_at: string;
|
|
19
|
+
route_id: string;
|
|
20
|
+
reason_code: PolicyReasonCode;
|
|
21
|
+
source_ip: string;
|
|
22
|
+
protocol: "HTTP" | "HTTPS";
|
|
23
|
+
};
|
|
24
|
+
export declare const POLICY_REASON_CODES: readonly PolicyReasonCode[];
|
|
25
|
+
export declare function validatePolicyV1(policy: unknown): Readonly<PolicyV1>;
|
|
26
|
+
export declare function validateObservationV1(observation: unknown): Readonly<ObservationV1>;
|
|
27
|
+
export declare function simulatePolicyV1(policy: unknown, observations: unknown[], options: { at: string }): Array<{
|
|
28
|
+
policy_id: string;
|
|
29
|
+
source_ip: string;
|
|
30
|
+
hit_count: number;
|
|
31
|
+
decision: "NONE" | "OBSERVE" | "THROTTLE" | "DENY";
|
|
32
|
+
restriction_expires_at: string | null;
|
|
33
|
+
}>;
|
package/policy.mjs
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { isEligibleSource, REASON_CODES } from "./guard-core.mjs";
|
|
2
|
+
|
|
3
|
+
export const POLICY_REASON_CODES = Object.freeze([...REASON_CODES, "authentication_failure"]);
|
|
4
|
+
const POLICY_FIELDS = new Set(["schema_version", "policy_id", "application_id", "mode", "route_id", "reason_code", "window_seconds", "threshold", "action", "restriction_seconds"]);
|
|
5
|
+
const OBSERVATION_FIELDS = new Set(["schema_version", "application_id", "event_id", "observed_at", "route_id", "reason_code", "source_ip", "protocol"]);
|
|
6
|
+
const IDENTIFIER = /^[a-z][a-z0-9._-]{1,63}$/;
|
|
7
|
+
const EVENT_ID = /^[A-Za-z0-9_-]{8,128}$/;
|
|
8
|
+
const UTC_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
|
|
9
|
+
|
|
10
|
+
function object(value, name, fields) {
|
|
11
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError(`${name} must be an object`);
|
|
12
|
+
for (const key of Object.keys(value)) {
|
|
13
|
+
if (!fields.has(key)) throw new TypeError(`${name} has unknown field ${key}`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function identifier(value, name) {
|
|
18
|
+
if (typeof value !== "string" || !IDENTIFIER.test(value)) throw new TypeError(`${name} must be a 2-64 character identifier`);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function integer(value, name, min, max) {
|
|
22
|
+
if (!Number.isSafeInteger(value) || value < min || value > max) throw new RangeError(`${name} must be ${min}-${max}`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function timestamp(value, name) {
|
|
26
|
+
if (typeof value !== "string" || !UTC_TIME.test(value) || !Number.isFinite(Date.parse(value))) {
|
|
27
|
+
throw new TypeError(`${name} must be an ISO 8601 UTC timestamp`);
|
|
28
|
+
}
|
|
29
|
+
const milliseconds = Date.parse(value);
|
|
30
|
+
const canonical = value.replace(/(?:\.(\d{1,3}))?Z$/, (_match, fraction) => `.${(fraction ?? "").padEnd(3, "0")}Z`);
|
|
31
|
+
if (new Date(milliseconds).toISOString() !== canonical) throw new TypeError(`${name} must be a valid UTC timestamp`);
|
|
32
|
+
return milliseconds;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function validatePolicyV1(policy) {
|
|
36
|
+
object(policy, "policy", POLICY_FIELDS);
|
|
37
|
+
if (policy.schema_version !== 1) throw new TypeError("unsupported policy schema_version");
|
|
38
|
+
identifier(policy.policy_id, "policy_id");
|
|
39
|
+
identifier(policy.application_id, "application_id");
|
|
40
|
+
identifier(policy.route_id, "route_id");
|
|
41
|
+
if (!POLICY_REASON_CODES.includes(policy.reason_code)) throw new TypeError("unknown policy reason_code");
|
|
42
|
+
if (policy.mode !== "OBSERVE" && policy.mode !== "ENFORCE") throw new TypeError("mode must be OBSERVE or ENFORCE");
|
|
43
|
+
if (policy.action !== "THROTTLE" && policy.action !== "DENY") throw new TypeError("action must be THROTTLE or DENY");
|
|
44
|
+
integer(policy.window_seconds, "window_seconds", 1, 300);
|
|
45
|
+
integer(policy.threshold, "threshold", 2, 10_000);
|
|
46
|
+
integer(policy.restriction_seconds, "restriction_seconds", 1, 300);
|
|
47
|
+
return Object.freeze({ ...policy });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function validateObservationV1(observation) {
|
|
51
|
+
object(observation, "observation", OBSERVATION_FIELDS);
|
|
52
|
+
if (observation.schema_version !== 1) throw new TypeError("unsupported observation schema_version");
|
|
53
|
+
identifier(observation.application_id, "application_id");
|
|
54
|
+
identifier(observation.route_id, "route_id");
|
|
55
|
+
if (typeof observation.event_id !== "string" || !EVENT_ID.test(observation.event_id)) throw new TypeError("invalid event_id");
|
|
56
|
+
timestamp(observation.observed_at, "observed_at");
|
|
57
|
+
if (!POLICY_REASON_CODES.includes(observation.reason_code)) throw new TypeError("unknown observation reason_code");
|
|
58
|
+
if (!isEligibleSource(observation.source_ip)) throw new TypeError("source_ip must be an eligible public IP");
|
|
59
|
+
if (observation.protocol !== "HTTP" && observation.protocol !== "HTTPS") throw new TypeError("protocol must be HTTP or HTTPS");
|
|
60
|
+
return Object.freeze({ ...observation });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Pure, source-scoped simulation. It does not install a live restriction. */
|
|
64
|
+
export function simulatePolicyV1(policyInput, observationInputs, { at } = {}) {
|
|
65
|
+
const policy = validatePolicyV1(policyInput);
|
|
66
|
+
if (!Array.isArray(observationInputs) || observationInputs.length > 10_000) {
|
|
67
|
+
throw new RangeError("observations must be an array of at most 10000 events");
|
|
68
|
+
}
|
|
69
|
+
const atMs = timestamp(at, "at");
|
|
70
|
+
const seen = new Set();
|
|
71
|
+
const counts = new Map();
|
|
72
|
+
for (const input of observationInputs) {
|
|
73
|
+
const observation = validateObservationV1(input);
|
|
74
|
+
const observedMs = Date.parse(observation.observed_at);
|
|
75
|
+
if (observedMs > atMs) throw new RangeError("observation occurs after simulation time");
|
|
76
|
+
if (observation.application_id !== policy.application_id ||
|
|
77
|
+
observation.route_id !== policy.route_id || observation.reason_code !== policy.reason_code ||
|
|
78
|
+
observedMs <= atMs - policy.window_seconds * 1_000) continue;
|
|
79
|
+
if (seen.has(observation.event_id)) continue;
|
|
80
|
+
seen.add(observation.event_id);
|
|
81
|
+
counts.set(observation.source_ip, (counts.get(observation.source_ip) ?? 0) + 1);
|
|
82
|
+
}
|
|
83
|
+
return [...counts.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([sourceIp, hitCount]) => {
|
|
84
|
+
const triggered = hitCount >= policy.threshold;
|
|
85
|
+
return {
|
|
86
|
+
policy_id: policy.policy_id, source_ip: sourceIp, hit_count: hitCount,
|
|
87
|
+
decision: !triggered ? "NONE" : policy.mode === "OBSERVE" ? "OBSERVE" : policy.action,
|
|
88
|
+
restriction_expires_at: triggered && policy.mode === "ENFORCE"
|
|
89
|
+
? new Date(atMs + policy.restriction_seconds * 1_000).toISOString() : null,
|
|
90
|
+
};
|
|
91
|
+
});
|
|
92
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare function createTrustedSourceResolver(options?: {
|
|
2
|
+
/** Exact proxy addresses. CIDR ranges are intentionally unsupported in v1. */
|
|
3
|
+
trustedProxyIps?: string[];
|
|
4
|
+
}): (request: {
|
|
5
|
+
socket?: { remoteAddress?: string };
|
|
6
|
+
headers?: { "x-forwarded-for"?: string | string[] };
|
|
7
|
+
}) => string;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { isIP } from "node:net";
|
|
2
|
+
|
|
3
|
+
const MAX_TRUSTED_PROXIES = 32;
|
|
4
|
+
const MAX_FORWARDED_HOPS = 16;
|
|
5
|
+
const MAX_FORWARDED_LENGTH = 1024;
|
|
6
|
+
|
|
7
|
+
function normalizeIp(value, name) {
|
|
8
|
+
if (typeof value !== "string" || value.length === 0 || value !== value.trim()) {
|
|
9
|
+
throw new TypeError(`${name} must be an IP address`);
|
|
10
|
+
}
|
|
11
|
+
const mapped = value.toLowerCase().startsWith("::ffff:") && isIP(value.slice(7)) === 4 ? value.slice(7) : value;
|
|
12
|
+
const family = isIP(mapped);
|
|
13
|
+
if (family === 0) throw new TypeError(`${name} must be an IP address`);
|
|
14
|
+
return family === 6 ? new URL(`http://[${mapped}]/`).hostname.slice(1, -1) : mapped;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Resolve an address using only explicitly named immediate and upstream proxies. */
|
|
18
|
+
export function createTrustedSourceResolver({ trustedProxyIps = [] } = {}) {
|
|
19
|
+
if (!Array.isArray(trustedProxyIps) || trustedProxyIps.length > MAX_TRUSTED_PROXIES) {
|
|
20
|
+
throw new TypeError(`trustedProxyIps must contain at most ${MAX_TRUSTED_PROXIES} addresses`);
|
|
21
|
+
}
|
|
22
|
+
const trusted = new Set(trustedProxyIps.map((ip) => normalizeIp(ip, "trusted proxy")));
|
|
23
|
+
|
|
24
|
+
return function getVerifiedSourceIp(request) {
|
|
25
|
+
const remote = normalizeIp(request?.socket?.remoteAddress, "socket remoteAddress");
|
|
26
|
+
if (!trusted.has(remote)) return remote;
|
|
27
|
+
|
|
28
|
+
const forwarded = request?.headers?.["x-forwarded-for"];
|
|
29
|
+
if (typeof forwarded !== "string" || forwarded.length === 0 || forwarded.length > MAX_FORWARDED_LENGTH) {
|
|
30
|
+
throw new TypeError("trusted proxy must provide one bounded X-Forwarded-For header");
|
|
31
|
+
}
|
|
32
|
+
const hops = forwarded.split(",");
|
|
33
|
+
if (hops.length > MAX_FORWARDED_HOPS) throw new RangeError("too many forwarded hops");
|
|
34
|
+
const chain = hops.map((hop) => normalizeIp(hop.trim(), "forwarded hop"));
|
|
35
|
+
for (let index = chain.length - 1; index >= 0; index--) {
|
|
36
|
+
if (!trusted.has(chain[index])) return chain[index];
|
|
37
|
+
}
|
|
38
|
+
throw new TypeError("forwarded chain has no untrusted source");
|
|
39
|
+
};
|
|
40
|
+
}
|