@arcjet/node 1.0.0-alpha.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +126 -0
- package/index.d.ts +57 -0
- package/index.js +109 -0
- package/index.ts +235 -0
- package/package.json +61 -0
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 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
|
|
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 [yyyy] [name of copyright owner]
|
|
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
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
<a href="https://arcjet.com" target="_arcjet-home">
|
|
2
|
+
<picture>
|
|
3
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://arcjet.com/arcjet-logo-dark-planet-arrival.svg">
|
|
4
|
+
<img src="https://arcjet.com/arcjet-logo-light-planet-arrival.svg" alt="Arcjet Logo" height="144" width="auto">
|
|
5
|
+
</picture>
|
|
6
|
+
</a>
|
|
7
|
+
|
|
8
|
+
# `@arcjet/node`
|
|
9
|
+
|
|
10
|
+
<p>
|
|
11
|
+
<a href="https://www.npmjs.com/package/@arcjet/node">
|
|
12
|
+
<picture>
|
|
13
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/npm/v/%40arcjet%2Fnode?style=flat-square&label=%E2%9C%A6Aj&labelColor=000000&color=5C5866">
|
|
14
|
+
<img alt="npm badge" src="https://img.shields.io/npm/v/%40arcjet%2Fnode?style=flat-square&label=%E2%9C%A6Aj&labelColor=ECE6F0&color=ECE6F0">
|
|
15
|
+
</picture>
|
|
16
|
+
</a>
|
|
17
|
+
</p>
|
|
18
|
+
|
|
19
|
+
[Arcjet][arcjet] helps developers protect their apps in just a few lines of
|
|
20
|
+
code. Implement rate limiting, bot protection, email verification & defend
|
|
21
|
+
against common attacks.
|
|
22
|
+
|
|
23
|
+
This is the [Arcjet][arcjet] SDK for [Node.js][node-js].
|
|
24
|
+
|
|
25
|
+
**Looking for our Next.js framework SDK?** Check out the
|
|
26
|
+
[`@arcjet/next`](https://www.npmjs.com/package/@arcjet/next) package.
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
```shell
|
|
31
|
+
npm install -S @arcjet/node
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Rate limit example
|
|
35
|
+
|
|
36
|
+
The [Arcjet rate limit][rate-limit-concepts-docs] example below applies a token
|
|
37
|
+
bucket rate limit rule to a route where we identify the user based on their ID
|
|
38
|
+
e.g. if they are logged in. The bucket is configured with a maximum capacity of
|
|
39
|
+
10 tokens and refills by 5 tokens every 10 seconds. Each request consumes 5
|
|
40
|
+
tokens.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import arcjet, { tokenBucket } from "@arcjet/node";
|
|
44
|
+
import http from "node:http";
|
|
45
|
+
|
|
46
|
+
const aj = arcjet({
|
|
47
|
+
key: process.env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com
|
|
48
|
+
rules: [
|
|
49
|
+
// Create a token bucket rate limit. Other algorithms are supported.
|
|
50
|
+
tokenBucket({
|
|
51
|
+
mode: "LIVE", // will block requests. Use "DRY_RUN" to log only
|
|
52
|
+
characteristics: ["userId"], // track requests by a custom user ID
|
|
53
|
+
refillRate: 5, // refill 5 tokens per interval
|
|
54
|
+
interval: 10, // refill every 10 seconds
|
|
55
|
+
capacity: 10, // bucket maximum capacity of 10 tokens
|
|
56
|
+
}),
|
|
57
|
+
],
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const server = http.createServer(async function (
|
|
61
|
+
req: http.IncomingMessage,
|
|
62
|
+
res: http.ServerResponse,
|
|
63
|
+
) {
|
|
64
|
+
const userId = "user123"; // Replace with your authenticated user ID
|
|
65
|
+
const decision = await aj.protect(req, { userId, requested: 5 }); // Deduct 5 tokens from the bucket
|
|
66
|
+
console.log("Arcjet decision", decision);
|
|
67
|
+
|
|
68
|
+
if (decision.isDenied()) {
|
|
69
|
+
res.writeHead(429, { "Content-Type": "application/json" });
|
|
70
|
+
res.end(
|
|
71
|
+
JSON.stringify({ error: "Too Many Requests", reason: decision.reason }),
|
|
72
|
+
);
|
|
73
|
+
} else {
|
|
74
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
75
|
+
res.end(JSON.stringify({ message: "Hello world" }));
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
server.listen(8000);
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Shield example
|
|
83
|
+
|
|
84
|
+
[Arcjet Shield][shield-concepts-docs] protects your application against common
|
|
85
|
+
attacks, including the OWASP Top 10. It’s enabled by default and runs on every
|
|
86
|
+
request with negligible performance impact.
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import arcjet from "@arcjet/node";
|
|
90
|
+
import http from "node:http";
|
|
91
|
+
|
|
92
|
+
const aj = arcjet({
|
|
93
|
+
// Get your site key from https://app.arcjet.com
|
|
94
|
+
// and set it as an environment variable rather than hard coding.
|
|
95
|
+
// See: https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
|
|
96
|
+
key: process.env.ARCJET_KEY,
|
|
97
|
+
rules: [], // Shield requires no rule configuration
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const server = http.createServer(async function (
|
|
101
|
+
req: http.IncomingMessage,
|
|
102
|
+
res: http.ServerResponse,
|
|
103
|
+
) {
|
|
104
|
+
const decision = await aj.protect(req);
|
|
105
|
+
|
|
106
|
+
if (decision.isDenied()) {
|
|
107
|
+
res.writeHead(403, { "Content-Type": "application/json" });
|
|
108
|
+
res.end(JSON.stringify({ error: "Forbidden" }));
|
|
109
|
+
} else {
|
|
110
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
111
|
+
res.end(JSON.stringify({ message: "Hello world" }));
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
server.listen(8000);
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## License
|
|
119
|
+
|
|
120
|
+
Licensed under the [Apache License, Version 2.0][apache-license].
|
|
121
|
+
|
|
122
|
+
[arcjet]: https://arcjet.com
|
|
123
|
+
[node-js]: https://nodejs.org/
|
|
124
|
+
[rate-limit-concepts-docs]: https://docs.arcjet.com/rate-limiting/concepts
|
|
125
|
+
[shield-concepts-docs]: https://docs.arcjet.com/shield/concepts
|
|
126
|
+
[apache-license]: http://www.apache.org/licenses/LICENSE-2.0
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { ArcjetDecision, ArcjetOptions, Primitive, Product, Runtime, ExtraProps, RemoteClient, RemoteClientOptions } from "arcjet";
|
|
2
|
+
export * from "arcjet";
|
|
3
|
+
type Simplify<T> = {
|
|
4
|
+
[KeyType in keyof T]: T[KeyType];
|
|
5
|
+
} & {};
|
|
6
|
+
declare const emptyObjectSymbol: unique symbol;
|
|
7
|
+
type WithoutCustomProps = {
|
|
8
|
+
[emptyObjectSymbol]?: never;
|
|
9
|
+
};
|
|
10
|
+
type PlainObject = {
|
|
11
|
+
[key: string]: unknown;
|
|
12
|
+
};
|
|
13
|
+
export declare function createNodeRemoteClient(options?: RemoteClientOptions): RemoteClient;
|
|
14
|
+
export interface ArcjetNodeRequest {
|
|
15
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
16
|
+
socket?: Partial<{
|
|
17
|
+
remoteAddress: string;
|
|
18
|
+
encrypted: boolean;
|
|
19
|
+
}>;
|
|
20
|
+
method?: string;
|
|
21
|
+
httpVersion?: string;
|
|
22
|
+
url?: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The ArcjetNode client provides a public `protect()` method to
|
|
26
|
+
* make a decision about how a Node.js request should be handled.
|
|
27
|
+
*/
|
|
28
|
+
export interface ArcjetNode<Props extends PlainObject> {
|
|
29
|
+
get runtime(): Runtime;
|
|
30
|
+
/**
|
|
31
|
+
* Runs a request through the configured protections. The request is
|
|
32
|
+
* analyzed and then a decision made on whether to allow, deny, or challenge
|
|
33
|
+
* the request.
|
|
34
|
+
*
|
|
35
|
+
* @param req - An `IncomingMessage` provided to the request handler.
|
|
36
|
+
* @param props - Additonal properties required for running rules against a request.
|
|
37
|
+
* @returns An {@link ArcjetDecision} indicating Arcjet's decision about the request.
|
|
38
|
+
*/
|
|
39
|
+
protect(request: ArcjetNodeRequest, ...props: Props extends WithoutCustomProps ? [] : [Props]): Promise<ArcjetDecision>;
|
|
40
|
+
/**
|
|
41
|
+
* Augments the client with another rule. Useful for varying rules based on
|
|
42
|
+
* criteria in your handler—e.g. different rate limit for logged in users.
|
|
43
|
+
*
|
|
44
|
+
* @param rule The rule to add to this execution.
|
|
45
|
+
* @returns An augmented {@link ArcjetNode} client.
|
|
46
|
+
*/
|
|
47
|
+
withRule<Rule extends Primitive | Product>(rule: Rule): ArcjetNode<Simplify<Props & ExtraProps<Rule>>>;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Create a new {@link ArcjetNode} client. Always build your initial client
|
|
51
|
+
* outside of a request handler so it persists across requests. If you need to
|
|
52
|
+
* augment a client inside a handler, call the `withRule()` function on the base
|
|
53
|
+
* client.
|
|
54
|
+
*
|
|
55
|
+
* @param options - Arcjet configuration options to apply to all requests.
|
|
56
|
+
*/
|
|
57
|
+
export default function arcjet<const Rules extends (Primitive | Product)[]>(options: ArcjetOptions<Rules>): ArcjetNode<Simplify<ExtraProps<Rules>>>;
|
package/index.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { createConnectTransport } from '@connectrpc/connect-node';
|
|
2
|
+
import core__default, { defaultBaseUrl, createRemoteClient, ArcjetHeaders } from 'arcjet';
|
|
3
|
+
export * from 'arcjet';
|
|
4
|
+
import findIP from '@arcjet/ip';
|
|
5
|
+
|
|
6
|
+
function createNodeRemoteClient(options) {
|
|
7
|
+
// The base URL for the Arcjet API. Will default to the standard production
|
|
8
|
+
// API unless environment variable `ARCJET_BASE_URL` is set.
|
|
9
|
+
const baseUrl = options?.baseUrl ?? defaultBaseUrl();
|
|
10
|
+
// Transport is the HTTP client that the client uses to make requests.
|
|
11
|
+
const transport = options?.transport ??
|
|
12
|
+
createConnectTransport({
|
|
13
|
+
baseUrl,
|
|
14
|
+
httpVersion: "2",
|
|
15
|
+
});
|
|
16
|
+
// TODO(#223): Do we want to allow overrides to either of these? If not, we should probably define a separate type for `options`
|
|
17
|
+
const sdkStack = "NODEJS";
|
|
18
|
+
const sdkVersion = "1.0.0-alpha.9";
|
|
19
|
+
return createRemoteClient({ ...options, transport, sdkStack, sdkVersion });
|
|
20
|
+
}
|
|
21
|
+
function cookiesToString(cookies) {
|
|
22
|
+
if (typeof cookies === "undefined") {
|
|
23
|
+
return "";
|
|
24
|
+
}
|
|
25
|
+
// This should never be the case with a Node.js cookie header, but we are safe
|
|
26
|
+
if (Array.isArray(cookies)) {
|
|
27
|
+
return cookies.join("; ");
|
|
28
|
+
}
|
|
29
|
+
return cookies;
|
|
30
|
+
}
|
|
31
|
+
function toArcjetRequest(request, props) {
|
|
32
|
+
// We construct an ArcjetHeaders to normalize over Headers
|
|
33
|
+
const headers = new ArcjetHeaders(request.headers);
|
|
34
|
+
const ip = findIP(request, headers);
|
|
35
|
+
const method = request.method ?? "";
|
|
36
|
+
const host = headers.get("host") ?? "";
|
|
37
|
+
let path = "";
|
|
38
|
+
let query = "";
|
|
39
|
+
let protocol = "";
|
|
40
|
+
if (typeof request.socket?.encrypted !== "undefined") {
|
|
41
|
+
protocol = request.socket.encrypted ? "https:" : "http:";
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
protocol = "http:";
|
|
45
|
+
}
|
|
46
|
+
// Do some very simple validation, but also try/catch around URL parsing
|
|
47
|
+
if (typeof request.url !== "undefined" && request.url !== "" && host !== "") {
|
|
48
|
+
try {
|
|
49
|
+
const url = new URL(request.url, `${protocol}//${host}`);
|
|
50
|
+
path = url.pathname;
|
|
51
|
+
query = url.search;
|
|
52
|
+
protocol = url.protocol;
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// If the parsing above fails, just set the path as whatever url we
|
|
56
|
+
// received.
|
|
57
|
+
// TODO(#216): Add logging to arcjet-node
|
|
58
|
+
path = request.url ?? "";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
path = request.url ?? "";
|
|
63
|
+
}
|
|
64
|
+
const cookies = cookiesToString(request.headers?.cookie);
|
|
65
|
+
return {
|
|
66
|
+
...props,
|
|
67
|
+
ip,
|
|
68
|
+
method,
|
|
69
|
+
protocol,
|
|
70
|
+
host,
|
|
71
|
+
path,
|
|
72
|
+
headers,
|
|
73
|
+
cookies,
|
|
74
|
+
query,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function withClient(aj) {
|
|
78
|
+
return Object.freeze({
|
|
79
|
+
get runtime() {
|
|
80
|
+
return aj.runtime;
|
|
81
|
+
},
|
|
82
|
+
withRule(rule) {
|
|
83
|
+
const client = aj.withRule(rule);
|
|
84
|
+
return withClient(client);
|
|
85
|
+
},
|
|
86
|
+
async protect(request, ...[props]) {
|
|
87
|
+
// TODO(#220): The generic manipulations get really mad here, so we cast
|
|
88
|
+
// Further investigation makes it seem like it has something to do with
|
|
89
|
+
// the definition of `props` in the signature but it's hard to track down
|
|
90
|
+
const req = toArcjetRequest(request, props ?? {});
|
|
91
|
+
return aj.protect(req);
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Create a new {@link ArcjetNode} client. Always build your initial client
|
|
97
|
+
* outside of a request handler so it persists across requests. If you need to
|
|
98
|
+
* augment a client inside a handler, call the `withRule()` function on the base
|
|
99
|
+
* client.
|
|
100
|
+
*
|
|
101
|
+
* @param options - Arcjet configuration options to apply to all requests.
|
|
102
|
+
*/
|
|
103
|
+
function arcjet(options) {
|
|
104
|
+
const client = options.client ?? createNodeRemoteClient();
|
|
105
|
+
const aj = core__default({ ...options, client });
|
|
106
|
+
return withClient(aj);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export { createNodeRemoteClient, arcjet as default };
|
package/index.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { createConnectTransport } from "@connectrpc/connect-node";
|
|
2
|
+
import core, {
|
|
3
|
+
ArcjetDecision,
|
|
4
|
+
ArcjetOptions,
|
|
5
|
+
Primitive,
|
|
6
|
+
Product,
|
|
7
|
+
ArcjetHeaders,
|
|
8
|
+
Runtime,
|
|
9
|
+
ArcjetRequest,
|
|
10
|
+
ExtraProps,
|
|
11
|
+
RemoteClient,
|
|
12
|
+
RemoteClientOptions,
|
|
13
|
+
defaultBaseUrl,
|
|
14
|
+
createRemoteClient,
|
|
15
|
+
Arcjet,
|
|
16
|
+
} from "arcjet";
|
|
17
|
+
import findIP from "@arcjet/ip";
|
|
18
|
+
|
|
19
|
+
// Re-export all named exports from the generic SDK
|
|
20
|
+
export * from "arcjet";
|
|
21
|
+
|
|
22
|
+
// Type helpers from https://github.com/sindresorhus/type-fest but adjusted for
|
|
23
|
+
// our use.
|
|
24
|
+
//
|
|
25
|
+
// Simplify:
|
|
26
|
+
// https://github.com/sindresorhus/type-fest/blob/964466c9d59c711da57a5297ad954c13132a0001/source/simplify.d.ts
|
|
27
|
+
// EmptyObject:
|
|
28
|
+
// https://github.com/sindresorhus/type-fest/blob/b9723d4785f01f8d2487c09ee5871a1f615781aa/source/empty-object.d.ts
|
|
29
|
+
//
|
|
30
|
+
// Licensed: MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com>
|
|
31
|
+
// (https://sindresorhus.com)
|
|
32
|
+
//
|
|
33
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
34
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
35
|
+
// in the Software without restriction, including without limitation the rights
|
|
36
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
37
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
38
|
+
// furnished to do so, subject to the following conditions: The above copyright
|
|
39
|
+
// notice and this permission notice shall be included in all copies or
|
|
40
|
+
// substantial portions of the Software.
|
|
41
|
+
//
|
|
42
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
43
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
44
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
45
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
46
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
47
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
48
|
+
// SOFTWARE.
|
|
49
|
+
type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};
|
|
50
|
+
declare const emptyObjectSymbol: unique symbol;
|
|
51
|
+
type WithoutCustomProps = {
|
|
52
|
+
[emptyObjectSymbol]?: never;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
type PlainObject = {
|
|
56
|
+
[key: string]: unknown;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export function createNodeRemoteClient(
|
|
60
|
+
options?: RemoteClientOptions,
|
|
61
|
+
): RemoteClient {
|
|
62
|
+
// The base URL for the Arcjet API. Will default to the standard production
|
|
63
|
+
// API unless environment variable `ARCJET_BASE_URL` is set.
|
|
64
|
+
const baseUrl = options?.baseUrl ?? defaultBaseUrl();
|
|
65
|
+
|
|
66
|
+
// Transport is the HTTP client that the client uses to make requests.
|
|
67
|
+
const transport =
|
|
68
|
+
options?.transport ??
|
|
69
|
+
createConnectTransport({
|
|
70
|
+
baseUrl,
|
|
71
|
+
httpVersion: "2",
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// TODO(#223): Do we want to allow overrides to either of these? If not, we should probably define a separate type for `options`
|
|
75
|
+
const sdkStack = "NODEJS";
|
|
76
|
+
const sdkVersion = "__ARCJET_SDK_VERSION__";
|
|
77
|
+
|
|
78
|
+
return createRemoteClient({ ...options, transport, sdkStack, sdkVersion });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Interface of fields that the Arcjet Node.js SDK expects on `IncomingMessage`
|
|
82
|
+
// objects.
|
|
83
|
+
export interface ArcjetNodeRequest {
|
|
84
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
85
|
+
socket?: Partial<{ remoteAddress: string; encrypted: boolean }>;
|
|
86
|
+
method?: string;
|
|
87
|
+
httpVersion?: string;
|
|
88
|
+
url?: string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function cookiesToString(cookies: string | string[] | undefined): string {
|
|
92
|
+
if (typeof cookies === "undefined") {
|
|
93
|
+
return "";
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// This should never be the case with a Node.js cookie header, but we are safe
|
|
97
|
+
if (Array.isArray(cookies)) {
|
|
98
|
+
return cookies.join("; ");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return cookies;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The ArcjetNode client provides a public `protect()` method to
|
|
106
|
+
* make a decision about how a Node.js request should be handled.
|
|
107
|
+
*/
|
|
108
|
+
export interface ArcjetNode<Props extends PlainObject> {
|
|
109
|
+
get runtime(): Runtime;
|
|
110
|
+
/**
|
|
111
|
+
* Runs a request through the configured protections. The request is
|
|
112
|
+
* analyzed and then a decision made on whether to allow, deny, or challenge
|
|
113
|
+
* the request.
|
|
114
|
+
*
|
|
115
|
+
* @param req - An `IncomingMessage` provided to the request handler.
|
|
116
|
+
* @param props - Additonal properties required for running rules against a request.
|
|
117
|
+
* @returns An {@link ArcjetDecision} indicating Arcjet's decision about the request.
|
|
118
|
+
*/
|
|
119
|
+
protect(
|
|
120
|
+
request: ArcjetNodeRequest,
|
|
121
|
+
// We use this neat trick from https://stackoverflow.com/a/52318137 to make a single spread parameter
|
|
122
|
+
// that is required if the ExtraProps aren't strictly an empty object
|
|
123
|
+
...props: Props extends WithoutCustomProps ? [] : [Props]
|
|
124
|
+
): Promise<ArcjetDecision>;
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Augments the client with another rule. Useful for varying rules based on
|
|
128
|
+
* criteria in your handler—e.g. different rate limit for logged in users.
|
|
129
|
+
*
|
|
130
|
+
* @param rule The rule to add to this execution.
|
|
131
|
+
* @returns An augmented {@link ArcjetNode} client.
|
|
132
|
+
*/
|
|
133
|
+
withRule<Rule extends Primitive | Product>(
|
|
134
|
+
rule: Rule,
|
|
135
|
+
): ArcjetNode<Simplify<Props & ExtraProps<Rule>>>;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function toArcjetRequest<Props extends PlainObject>(
|
|
139
|
+
request: ArcjetNodeRequest,
|
|
140
|
+
props: Props,
|
|
141
|
+
): ArcjetRequest<Props> {
|
|
142
|
+
// We construct an ArcjetHeaders to normalize over Headers
|
|
143
|
+
const headers = new ArcjetHeaders(request.headers);
|
|
144
|
+
|
|
145
|
+
const ip = findIP(request, headers);
|
|
146
|
+
const method = request.method ?? "";
|
|
147
|
+
const host = headers.get("host") ?? "";
|
|
148
|
+
let path = "";
|
|
149
|
+
let query = "";
|
|
150
|
+
let protocol = "";
|
|
151
|
+
|
|
152
|
+
if (typeof request.socket?.encrypted !== "undefined") {
|
|
153
|
+
protocol = request.socket.encrypted ? "https:" : "http:";
|
|
154
|
+
} else {
|
|
155
|
+
protocol = "http:";
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Do some very simple validation, but also try/catch around URL parsing
|
|
159
|
+
if (typeof request.url !== "undefined" && request.url !== "" && host !== "") {
|
|
160
|
+
try {
|
|
161
|
+
const url = new URL(request.url, `${protocol}//${host}`);
|
|
162
|
+
path = url.pathname;
|
|
163
|
+
query = url.search;
|
|
164
|
+
protocol = url.protocol;
|
|
165
|
+
} catch {
|
|
166
|
+
// If the parsing above fails, just set the path as whatever url we
|
|
167
|
+
// received.
|
|
168
|
+
// TODO(#216): Add logging to arcjet-node
|
|
169
|
+
path = request.url ?? "";
|
|
170
|
+
}
|
|
171
|
+
} else {
|
|
172
|
+
path = request.url ?? "";
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const cookies = cookiesToString(request.headers?.cookie);
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
...props,
|
|
179
|
+
ip,
|
|
180
|
+
method,
|
|
181
|
+
protocol,
|
|
182
|
+
host,
|
|
183
|
+
path,
|
|
184
|
+
headers,
|
|
185
|
+
cookies,
|
|
186
|
+
query,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function withClient<const Rules extends (Primitive | Product)[]>(
|
|
191
|
+
aj: Arcjet<ExtraProps<Rules>>,
|
|
192
|
+
): ArcjetNode<ExtraProps<Rules>> {
|
|
193
|
+
return Object.freeze({
|
|
194
|
+
get runtime() {
|
|
195
|
+
return aj.runtime;
|
|
196
|
+
},
|
|
197
|
+
withRule(rule: Primitive | Product) {
|
|
198
|
+
const client = aj.withRule(rule);
|
|
199
|
+
return withClient(client);
|
|
200
|
+
},
|
|
201
|
+
async protect(
|
|
202
|
+
request: ArcjetNodeRequest,
|
|
203
|
+
...[props]: ExtraProps<Rules> extends WithoutCustomProps
|
|
204
|
+
? []
|
|
205
|
+
: [ExtraProps<Rules>]
|
|
206
|
+
): Promise<ArcjetDecision> {
|
|
207
|
+
// TODO(#220): The generic manipulations get really mad here, so we cast
|
|
208
|
+
// Further investigation makes it seem like it has something to do with
|
|
209
|
+
// the definition of `props` in the signature but it's hard to track down
|
|
210
|
+
const req = toArcjetRequest(request, props ?? {}) as ArcjetRequest<
|
|
211
|
+
ExtraProps<Rules>
|
|
212
|
+
>;
|
|
213
|
+
|
|
214
|
+
return aj.protect(req);
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Create a new {@link ArcjetNode} client. Always build your initial client
|
|
221
|
+
* outside of a request handler so it persists across requests. If you need to
|
|
222
|
+
* augment a client inside a handler, call the `withRule()` function on the base
|
|
223
|
+
* client.
|
|
224
|
+
*
|
|
225
|
+
* @param options - Arcjet configuration options to apply to all requests.
|
|
226
|
+
*/
|
|
227
|
+
export default function arcjet<const Rules extends (Primitive | Product)[]>(
|
|
228
|
+
options: ArcjetOptions<Rules>,
|
|
229
|
+
): ArcjetNode<Simplify<ExtraProps<Rules>>> {
|
|
230
|
+
const client = options.client ?? createNodeRemoteClient();
|
|
231
|
+
|
|
232
|
+
const aj = core({ ...options, client });
|
|
233
|
+
|
|
234
|
+
return withClient(aj);
|
|
235
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@arcjet/node",
|
|
3
|
+
"version": "1.0.0-alpha.9",
|
|
4
|
+
"description": "Arcjet SDK for Node.js",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://arcjet.com",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/arcjet/arcjet-js.git",
|
|
10
|
+
"directory": "arcjet-node"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/arcjet/arcjet-js/issues",
|
|
14
|
+
"email": "support@arcjet.com"
|
|
15
|
+
},
|
|
16
|
+
"author": {
|
|
17
|
+
"name": "Arcjet",
|
|
18
|
+
"email": "support@arcjet.com",
|
|
19
|
+
"url": "https://arcjet.com"
|
|
20
|
+
},
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=18"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"main": "./index.js",
|
|
26
|
+
"types": "./index.d.ts",
|
|
27
|
+
"files": [
|
|
28
|
+
"LICENSE",
|
|
29
|
+
"README.md",
|
|
30
|
+
"*.js",
|
|
31
|
+
"*.d.ts",
|
|
32
|
+
"*.ts",
|
|
33
|
+
"!*.config.js"
|
|
34
|
+
],
|
|
35
|
+
"scripts": {
|
|
36
|
+
"prepublishOnly": "npm run build",
|
|
37
|
+
"build": "rollup --config rollup.config.js",
|
|
38
|
+
"lint": "eslint .",
|
|
39
|
+
"pretest": "npm run build",
|
|
40
|
+
"test": "NODE_OPTIONS=--experimental-vm-modules jest --passWithNoTests"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@arcjet/ip": "1.0.0-alpha.9",
|
|
44
|
+
"@connectrpc/connect-node": "1.4.0",
|
|
45
|
+
"arcjet": "1.0.0-alpha.9"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@arcjet/eslint-config": "1.0.0-alpha.9",
|
|
49
|
+
"@arcjet/rollup-config": "1.0.0-alpha.9",
|
|
50
|
+
"@arcjet/tsconfig": "1.0.0-alpha.9",
|
|
51
|
+
"@jest/globals": "29.7.0",
|
|
52
|
+
"@types/node": "18.18.0",
|
|
53
|
+
"@rollup/wasm-node": "4.12.0",
|
|
54
|
+
"jest": "29.7.0",
|
|
55
|
+
"typescript": "5.3.3"
|
|
56
|
+
},
|
|
57
|
+
"publishConfig": {
|
|
58
|
+
"access": "public",
|
|
59
|
+
"tag": "latest"
|
|
60
|
+
}
|
|
61
|
+
}
|