@arcjet/node 1.0.0-alpha.9 → 1.0.0-beta.10
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/README.md +63 -70
- package/index.d.ts +22 -4
- package/index.js +202 -80
- package/package.json +31 -20
- package/index.ts +0 -235
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<a href="https://arcjet.com" target="_arcjet-home">
|
|
2
2
|
<picture>
|
|
3
|
-
<source media="(prefers-color-scheme: dark)" srcset="https://arcjet.com/arcjet-
|
|
4
|
-
<img src="https://arcjet.com/arcjet-
|
|
3
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://arcjet.com/logo/arcjet-dark-lockup-voyage-horizontal.svg">
|
|
4
|
+
<img src="https://arcjet.com/logo/arcjet-light-lockup-voyage-horizontal.svg" alt="Arcjet Logo" height="128" width="auto">
|
|
5
5
|
</picture>
|
|
6
6
|
</a>
|
|
7
7
|
|
|
@@ -17,110 +17,103 @@
|
|
|
17
17
|
</p>
|
|
18
18
|
|
|
19
19
|
[Arcjet][arcjet] helps developers protect their apps in just a few lines of
|
|
20
|
-
code. Implement rate limiting, bot protection, email verification
|
|
20
|
+
code. Implement rate limiting, bot protection, email verification, and defense
|
|
21
21
|
against common attacks.
|
|
22
22
|
|
|
23
23
|
This is the [Arcjet][arcjet] SDK for [Node.js][node-js].
|
|
24
24
|
|
|
25
25
|
**Looking for our Next.js framework SDK?** Check out the
|
|
26
|
-
[`@arcjet/next`]
|
|
26
|
+
[`@arcjet/next`][alt-sdk] package.
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
- [npm package (`@arcjet/node`)](https://www.npmjs.com/package/@arcjet/node)
|
|
29
|
+
- [GitHub source code (`arcjet-node/` in `arcjet/arcjet-js`)](https://github.com/arcjet/arcjet-js/tree/main/arcjet-node)
|
|
29
30
|
|
|
30
|
-
|
|
31
|
-
npm install -S @arcjet/node
|
|
32
|
-
```
|
|
31
|
+
## Getting started
|
|
33
32
|
|
|
34
|
-
|
|
33
|
+
Visit the [quick start guide][quick-start] to get started.
|
|
35
34
|
|
|
36
|
-
|
|
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.
|
|
35
|
+
## Example app
|
|
41
36
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
import http from "node:http";
|
|
37
|
+
Try an Arcjet protected app live at [https://example.arcjet.com][example-url]
|
|
38
|
+
([source code][example-source]).
|
|
45
39
|
|
|
46
|
-
|
|
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
|
-
});
|
|
40
|
+
## What is this?
|
|
59
41
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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);
|
|
42
|
+
This is our adapter to integrate Arcjet into Node.js.
|
|
43
|
+
Arcjet helps you secure your Node server.
|
|
44
|
+
This package exists so that we can provide the best possible experience to
|
|
45
|
+
Node users.
|
|
67
46
|
|
|
68
|
-
|
|
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
|
-
});
|
|
47
|
+
## When should I use this?
|
|
78
48
|
|
|
79
|
-
|
|
80
|
-
|
|
49
|
+
You can use this if you are using Node.js.
|
|
50
|
+
See our [_Get started_ guide][arcjet-get-started] for other supported
|
|
51
|
+
frameworks and runtimes.
|
|
52
|
+
|
|
53
|
+
## Install
|
|
81
54
|
|
|
82
|
-
|
|
55
|
+
This package is ESM only.
|
|
56
|
+
Install with npm in Node.js:
|
|
83
57
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
58
|
+
```sh
|
|
59
|
+
npm install @arcjet/node
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Use
|
|
87
63
|
|
|
88
64
|
```ts
|
|
89
|
-
import arcjet from "@arcjet/node";
|
|
90
65
|
import http from "node:http";
|
|
66
|
+
import arcjet, { shield } from "@arcjet/node";
|
|
67
|
+
|
|
68
|
+
// Get your Arcjet key at <https://app.arcjet.com>.
|
|
69
|
+
// Set it as an environment variable instead of hard coding it.
|
|
70
|
+
const arcjetKey = process.env.ARCJET_KEY;
|
|
71
|
+
|
|
72
|
+
if (!arcjetKey) {
|
|
73
|
+
throw new Error("Cannot find `ARCJET_KEY` environment variable");
|
|
74
|
+
}
|
|
91
75
|
|
|
92
76
|
const aj = arcjet({
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
77
|
+
key: arcjetKey,
|
|
78
|
+
rules: [
|
|
79
|
+
// Shield protects your app from common attacks.
|
|
80
|
+
// Use `DRY_RUN` instead of `LIVE` to only log.
|
|
81
|
+
shield({ mode: "LIVE" }),
|
|
82
|
+
],
|
|
98
83
|
});
|
|
99
84
|
|
|
100
85
|
const server = http.createServer(async function (
|
|
101
|
-
|
|
102
|
-
|
|
86
|
+
request: http.IncomingMessage,
|
|
87
|
+
response: http.ServerResponse,
|
|
103
88
|
) {
|
|
104
|
-
const decision = await aj.protect(
|
|
89
|
+
const decision = await aj.protect(request);
|
|
105
90
|
|
|
106
91
|
if (decision.isDenied()) {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
res.writeHead(200, { "Content-Type": "application/json" });
|
|
111
|
-
res.end(JSON.stringify({ message: "Hello world" }));
|
|
92
|
+
response.writeHead(403, { "Content-Type": "application/json" });
|
|
93
|
+
response.end(JSON.stringify({ message: "Forbidden" }));
|
|
94
|
+
return;
|
|
112
95
|
}
|
|
96
|
+
|
|
97
|
+
response.writeHead(200, { "Content-Type": "application/json" });
|
|
98
|
+
response.end(JSON.stringify({ message: "Hello world" }));
|
|
113
99
|
});
|
|
114
100
|
|
|
115
101
|
server.listen(8000);
|
|
116
102
|
```
|
|
117
103
|
|
|
104
|
+
For more on how to configure Arcjet with Node.js and how to protect Node,
|
|
105
|
+
see the [Arcjet Node.js SDK reference][arcjet-reference-node] on our website.
|
|
106
|
+
|
|
118
107
|
## License
|
|
119
108
|
|
|
120
|
-
|
|
109
|
+
[Apache License, Version 2.0][apache-license] © [Arcjet Labs, Inc.][arcjet]
|
|
121
110
|
|
|
111
|
+
[arcjet-get-started]: https://docs.arcjet.com/get-started
|
|
112
|
+
[arcjet-reference-node]: https://docs.arcjet.com/reference/nodejs
|
|
122
113
|
[arcjet]: https://arcjet.com
|
|
123
114
|
[node-js]: https://nodejs.org/
|
|
124
|
-
[
|
|
125
|
-
[
|
|
115
|
+
[alt-sdk]: https://www.npmjs.com/package/@arcjet/next
|
|
116
|
+
[example-url]: https://example.arcjet.com
|
|
117
|
+
[quick-start]: https://docs.arcjet.com/get-started/nodejs
|
|
118
|
+
[example-source]: https://github.com/arcjet/arcjet-js-example
|
|
126
119
|
[apache-license]: http://www.apache.org/licenses/LICENSE-2.0
|
package/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ArcjetDecision, ArcjetOptions, Primitive, Product,
|
|
1
|
+
import type { ArcjetDecision, ArcjetOptions as CoreOptions, Primitive, Product, ExtraProps, CharacteristicProps } from "arcjet";
|
|
2
2
|
export * from "arcjet";
|
|
3
3
|
type Simplify<T> = {
|
|
4
4
|
[KeyType in keyof T]: T[KeyType];
|
|
@@ -10,7 +10,12 @@ type WithoutCustomProps = {
|
|
|
10
10
|
type PlainObject = {
|
|
11
11
|
[key: string]: unknown;
|
|
12
12
|
};
|
|
13
|
-
export
|
|
13
|
+
export type RemoteClientOptions = {
|
|
14
|
+
baseUrl?: string;
|
|
15
|
+
timeout?: number;
|
|
16
|
+
};
|
|
17
|
+
export declare function createRemoteClient(options?: RemoteClientOptions): import("@arcjet/protocol/client.js").Client;
|
|
18
|
+
type EventHandlerLike = (event: string, listener: (...args: any[]) => void) => void;
|
|
14
19
|
export interface ArcjetNodeRequest {
|
|
15
20
|
headers?: Record<string, string | string[] | undefined>;
|
|
16
21
|
socket?: Partial<{
|
|
@@ -20,13 +25,26 @@ export interface ArcjetNodeRequest {
|
|
|
20
25
|
method?: string;
|
|
21
26
|
httpVersion?: string;
|
|
22
27
|
url?: string;
|
|
28
|
+
body?: unknown;
|
|
29
|
+
on?: EventHandlerLike;
|
|
30
|
+
removeListener?: EventHandlerLike;
|
|
31
|
+
readable?: boolean;
|
|
23
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* The options used to configure an {@link ArcjetNode} client.
|
|
35
|
+
*/
|
|
36
|
+
export type ArcjetOptions<Rules extends [...Array<Primitive | Product>], Characteristics extends readonly string[]> = Simplify<CoreOptions<Rules, Characteristics> & {
|
|
37
|
+
/**
|
|
38
|
+
* One or more IP Address of trusted proxies in front of the application.
|
|
39
|
+
* These addresses will be excluded when Arcjet detects a public IP address.
|
|
40
|
+
*/
|
|
41
|
+
proxies?: Array<string>;
|
|
42
|
+
}>;
|
|
24
43
|
/**
|
|
25
44
|
* The ArcjetNode client provides a public `protect()` method to
|
|
26
45
|
* make a decision about how a Node.js request should be handled.
|
|
27
46
|
*/
|
|
28
47
|
export interface ArcjetNode<Props extends PlainObject> {
|
|
29
|
-
get runtime(): Runtime;
|
|
30
48
|
/**
|
|
31
49
|
* Runs a request through the configured protections. The request is
|
|
32
50
|
* analyzed and then a decision made on whether to allow, deny, or challenge
|
|
@@ -54,4 +72,4 @@ export interface ArcjetNode<Props extends PlainObject> {
|
|
|
54
72
|
*
|
|
55
73
|
* @param options - Arcjet configuration options to apply to all requests.
|
|
56
74
|
*/
|
|
57
|
-
export default function arcjet<const Rules extends (Primitive | Product)[]>(options: ArcjetOptions<Rules>): ArcjetNode<Simplify<ExtraProps<Rules>>>;
|
|
75
|
+
export default function arcjet<const Rules extends (Primitive | Product)[], const Characteristics extends readonly string[]>(options: ArcjetOptions<Rules, Characteristics>): ArcjetNode<Simplify<ExtraProps<Rules> & CharacteristicProps<Characteristics>>>;
|
package/index.js
CHANGED
|
@@ -1,22 +1,77 @@
|
|
|
1
|
-
import
|
|
2
|
-
import core__default, { defaultBaseUrl, createRemoteClient, ArcjetHeaders } from 'arcjet';
|
|
1
|
+
import core__default from 'arcjet';
|
|
3
2
|
export * from 'arcjet';
|
|
4
|
-
import findIP from '@arcjet/ip';
|
|
3
|
+
import findIP, { parseProxy } from '@arcjet/ip';
|
|
4
|
+
import ArcjetHeaders from '@arcjet/headers';
|
|
5
|
+
import { logLevel, isDevelopment, baseUrl, platform } from '@arcjet/env';
|
|
6
|
+
import { Logger } from '@arcjet/logger';
|
|
7
|
+
import { createClient } from '@arcjet/protocol/client.js';
|
|
8
|
+
import { createTransport } from '@arcjet/transport';
|
|
9
|
+
import { readBody } from '@arcjet/body';
|
|
5
10
|
|
|
6
|
-
|
|
11
|
+
// An object with getters that access the `process.env.SOMEVAR` values directly.
|
|
12
|
+
// This allows bundlers to replace the dot-notation access with string literals
|
|
13
|
+
// while still allowing dynamic access in runtime environments.
|
|
14
|
+
const env = {
|
|
15
|
+
get FLY_APP_NAME() {
|
|
16
|
+
return process.env.FLY_APP_NAME;
|
|
17
|
+
},
|
|
18
|
+
get VERCEL() {
|
|
19
|
+
return process.env.VERCEL;
|
|
20
|
+
},
|
|
21
|
+
get RENDER() {
|
|
22
|
+
return process.env.RENDER;
|
|
23
|
+
},
|
|
24
|
+
get MODE() {
|
|
25
|
+
return process.env.MODE;
|
|
26
|
+
},
|
|
27
|
+
get NODE_ENV() {
|
|
28
|
+
return process.env.NODE_ENV;
|
|
29
|
+
},
|
|
30
|
+
get ARCJET_KEY() {
|
|
31
|
+
return process.env.ARCJET_KEY;
|
|
32
|
+
},
|
|
33
|
+
get ARCJET_ENV() {
|
|
34
|
+
return process.env.ARCJET_ENV;
|
|
35
|
+
},
|
|
36
|
+
get ARCJET_LOG_LEVEL() {
|
|
37
|
+
return process.env.ARCJET_LOG_LEVEL;
|
|
38
|
+
},
|
|
39
|
+
get ARCJET_BASE_URL() {
|
|
40
|
+
return process.env.ARCJET_BASE_URL;
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
// TODO: Deduplicate with other packages
|
|
44
|
+
function errorMessage(err) {
|
|
45
|
+
if (err) {
|
|
46
|
+
if (typeof err === "string") {
|
|
47
|
+
return err;
|
|
48
|
+
}
|
|
49
|
+
if (typeof err === "object" &&
|
|
50
|
+
"message" in err &&
|
|
51
|
+
typeof err.message === "string") {
|
|
52
|
+
return err.message;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return "Unknown problem";
|
|
56
|
+
}
|
|
57
|
+
function createRemoteClient(options) {
|
|
7
58
|
// The base URL for the Arcjet API. Will default to the standard production
|
|
8
59
|
// API unless environment variable `ARCJET_BASE_URL` is set.
|
|
9
|
-
const
|
|
60
|
+
const url = options?.baseUrl ?? baseUrl(env);
|
|
61
|
+
// The timeout for the Arcjet API in milliseconds. This is set to a low value
|
|
62
|
+
// in production so calls fail open.
|
|
63
|
+
const timeout = options?.timeout ?? (isDevelopment(env) ? 1000 : 500);
|
|
10
64
|
// Transport is the HTTP client that the client uses to make requests.
|
|
11
|
-
const 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`
|
|
65
|
+
const transport = createTransport(url);
|
|
17
66
|
const sdkStack = "NODEJS";
|
|
18
|
-
const sdkVersion = "1.0.0-
|
|
19
|
-
return
|
|
67
|
+
const sdkVersion = "1.0.0-beta.10";
|
|
68
|
+
return createClient({
|
|
69
|
+
transport,
|
|
70
|
+
baseUrl: url,
|
|
71
|
+
timeout,
|
|
72
|
+
sdkStack,
|
|
73
|
+
sdkVersion,
|
|
74
|
+
});
|
|
20
75
|
}
|
|
21
76
|
function cookiesToString(cookies) {
|
|
22
77
|
if (typeof cookies === "undefined") {
|
|
@@ -28,70 +83,6 @@ function cookiesToString(cookies) {
|
|
|
28
83
|
}
|
|
29
84
|
return cookies;
|
|
30
85
|
}
|
|
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
86
|
/**
|
|
96
87
|
* Create a new {@link ArcjetNode} client. Always build your initial client
|
|
97
88
|
* outside of a request handler so it persists across requests. If you need to
|
|
@@ -101,9 +92,140 @@ function withClient(aj) {
|
|
|
101
92
|
* @param options - Arcjet configuration options to apply to all requests.
|
|
102
93
|
*/
|
|
103
94
|
function arcjet(options) {
|
|
104
|
-
const client = options.client ??
|
|
105
|
-
const
|
|
95
|
+
const client = options.client ?? createRemoteClient();
|
|
96
|
+
const log = options.log
|
|
97
|
+
? options.log
|
|
98
|
+
: new Logger({
|
|
99
|
+
level: logLevel(env),
|
|
100
|
+
});
|
|
101
|
+
const proxies = Array.isArray(options.proxies)
|
|
102
|
+
? options.proxies.map(parseProxy)
|
|
103
|
+
: undefined;
|
|
104
|
+
if (isDevelopment(env)) {
|
|
105
|
+
log.warn("Arcjet will use 127.0.0.1 when missing public IP address in development mode");
|
|
106
|
+
}
|
|
107
|
+
function toArcjetRequest(request, props) {
|
|
108
|
+
// We pull the cookies from the request before wrapping them in ArcjetHeaders
|
|
109
|
+
const cookies = cookiesToString(request.headers?.cookie);
|
|
110
|
+
// We construct an ArcjetHeaders to normalize over Headers
|
|
111
|
+
const headers = new ArcjetHeaders(request.headers);
|
|
112
|
+
let ip = findIP({
|
|
113
|
+
socket: request.socket,
|
|
114
|
+
headers,
|
|
115
|
+
}, { platform: platform(env), proxies });
|
|
116
|
+
if (ip === "") {
|
|
117
|
+
// If the `ip` is empty but we're in development mode, we default the IP
|
|
118
|
+
// so the request doesn't fail.
|
|
119
|
+
if (isDevelopment(env)) {
|
|
120
|
+
ip = "127.0.0.1";
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
log.warn(`Client IP address is missing. If this is a dev environment set the ARCJET_ENV env var to "development"`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const method = request.method ?? "";
|
|
127
|
+
const host = headers.get("host") ?? "";
|
|
128
|
+
let path = "";
|
|
129
|
+
let query = "";
|
|
130
|
+
let protocol = "";
|
|
131
|
+
if (typeof request.socket?.encrypted !== "undefined") {
|
|
132
|
+
protocol = request.socket.encrypted ? "https:" : "http:";
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
protocol = "http:";
|
|
136
|
+
}
|
|
137
|
+
// Do some very simple validation, but also try/catch around URL parsing
|
|
138
|
+
if (typeof request.url !== "undefined" &&
|
|
139
|
+
request.url !== "" &&
|
|
140
|
+
host !== "") {
|
|
141
|
+
try {
|
|
142
|
+
const url = new URL(request.url, `${protocol}//${host}`);
|
|
143
|
+
path = url.pathname;
|
|
144
|
+
query = url.search;
|
|
145
|
+
protocol = url.protocol;
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
// If the parsing above fails, just set the path as whatever url we
|
|
149
|
+
// received.
|
|
150
|
+
path = request.url ?? "";
|
|
151
|
+
log.warn('Unable to parse URL. Using "%s" as `path`.', path);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
path = request.url ?? "";
|
|
156
|
+
}
|
|
157
|
+
return {
|
|
158
|
+
...props,
|
|
159
|
+
ip,
|
|
160
|
+
method,
|
|
161
|
+
protocol,
|
|
162
|
+
host,
|
|
163
|
+
path,
|
|
164
|
+
headers,
|
|
165
|
+
cookies,
|
|
166
|
+
query,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function withClient(aj) {
|
|
170
|
+
return Object.freeze({
|
|
171
|
+
withRule(rule) {
|
|
172
|
+
const client = aj.withRule(rule);
|
|
173
|
+
return withClient(client);
|
|
174
|
+
},
|
|
175
|
+
async protect(request, ...[props]) {
|
|
176
|
+
// TODO(#220): The generic manipulations get really mad here, so we cast
|
|
177
|
+
// Further investigation makes it seem like it has something to do with
|
|
178
|
+
// the definition of `props` in the signature but it's hard to track down
|
|
179
|
+
const req = toArcjetRequest(request, props ?? {});
|
|
180
|
+
const getBody = async () => {
|
|
181
|
+
try {
|
|
182
|
+
// If request.body is present then the body was likely read by a package like express' `body-parser`.
|
|
183
|
+
// If it's not present then we attempt to read the bytes from the IncomingMessage ourselves.
|
|
184
|
+
if (typeof request.body === "string") {
|
|
185
|
+
return request.body;
|
|
186
|
+
}
|
|
187
|
+
else if (typeof request.body !== "undefined" &&
|
|
188
|
+
// BigInt cannot be serialized with JSON.stringify
|
|
189
|
+
typeof request.body !== "bigint") {
|
|
190
|
+
return JSON.stringify(request.body);
|
|
191
|
+
}
|
|
192
|
+
if (typeof request.on === "function" &&
|
|
193
|
+
typeof request.removeListener === "function") {
|
|
194
|
+
let expectedLength;
|
|
195
|
+
// TODO: This shouldn't need to build headers again but the type
|
|
196
|
+
// for `req` above is overly relaxed
|
|
197
|
+
const headers = new ArcjetHeaders(request.headers);
|
|
198
|
+
const expectedLengthStr = headers.get("content-length");
|
|
199
|
+
if (typeof expectedLengthStr === "string") {
|
|
200
|
+
try {
|
|
201
|
+
expectedLength = parseInt(expectedLengthStr, 10);
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
// If the expected length couldn't be parsed we'll just not set one.
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
// Awaited to throw if it rejects and we'll just return undefined
|
|
208
|
+
const body = await readBody(request, {
|
|
209
|
+
// We will process 1mb bodies
|
|
210
|
+
limit: 1048576,
|
|
211
|
+
expectedLength,
|
|
212
|
+
});
|
|
213
|
+
return body;
|
|
214
|
+
}
|
|
215
|
+
log.warn("no body available");
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
catch (e) {
|
|
219
|
+
log.error("failed to get request body: %s", errorMessage(e));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
return aj.protect({ getBody }, req);
|
|
224
|
+
},
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
const aj = core__default({ ...options, client, log });
|
|
106
228
|
return withClient(aj);
|
|
107
229
|
}
|
|
108
230
|
|
|
109
|
-
export {
|
|
231
|
+
export { createRemoteClient, arcjet as default };
|
package/package.json
CHANGED
|
@@ -1,7 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arcjet/node",
|
|
3
|
-
"version": "1.0.0-
|
|
3
|
+
"version": "1.0.0-beta.10",
|
|
4
4
|
"description": "Arcjet SDK for Node.js",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"analyze",
|
|
7
|
+
"arcjet",
|
|
8
|
+
"attack",
|
|
9
|
+
"limit",
|
|
10
|
+
"nodejs",
|
|
11
|
+
"node",
|
|
12
|
+
"protect",
|
|
13
|
+
"secure",
|
|
14
|
+
"security",
|
|
15
|
+
"verify"
|
|
16
|
+
],
|
|
5
17
|
"license": "Apache-2.0",
|
|
6
18
|
"homepage": "https://arcjet.com",
|
|
7
19
|
"repository": {
|
|
@@ -25,34 +37,33 @@
|
|
|
25
37
|
"main": "./index.js",
|
|
26
38
|
"types": "./index.d.ts",
|
|
27
39
|
"files": [
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
"*.js",
|
|
31
|
-
"*.d.ts",
|
|
32
|
-
"*.ts",
|
|
33
|
-
"!*.config.js"
|
|
40
|
+
"index.d.ts",
|
|
41
|
+
"index.js"
|
|
34
42
|
],
|
|
35
43
|
"scripts": {
|
|
36
|
-
"prepublishOnly": "npm run build",
|
|
37
44
|
"build": "rollup --config rollup.config.js",
|
|
38
45
|
"lint": "eslint .",
|
|
39
|
-
"
|
|
40
|
-
"test": "
|
|
46
|
+
"prepublishOnly": "npm run build",
|
|
47
|
+
"test": "npm run build && npm run lint"
|
|
41
48
|
},
|
|
42
49
|
"dependencies": {
|
|
43
|
-
"@arcjet/
|
|
44
|
-
"@
|
|
45
|
-
"arcjet": "1.0.0-
|
|
50
|
+
"@arcjet/env": "1.0.0-beta.10",
|
|
51
|
+
"@arcjet/headers": "1.0.0-beta.10",
|
|
52
|
+
"@arcjet/ip": "1.0.0-beta.10",
|
|
53
|
+
"@arcjet/logger": "1.0.0-beta.10",
|
|
54
|
+
"@arcjet/protocol": "1.0.0-beta.10",
|
|
55
|
+
"@arcjet/transport": "1.0.0-beta.10",
|
|
56
|
+
"@arcjet/body": "1.0.0-beta.10",
|
|
57
|
+
"arcjet": "1.0.0-beta.10"
|
|
46
58
|
},
|
|
47
59
|
"devDependencies": {
|
|
48
|
-
"@arcjet/eslint-config": "1.0.0-
|
|
49
|
-
"@arcjet/rollup-config": "1.0.0-
|
|
50
|
-
"@arcjet/tsconfig": "1.0.0-
|
|
51
|
-
"@jest/globals": "29.7.0",
|
|
60
|
+
"@arcjet/eslint-config": "1.0.0-beta.10",
|
|
61
|
+
"@arcjet/rollup-config": "1.0.0-beta.10",
|
|
62
|
+
"@arcjet/tsconfig": "1.0.0-beta.10",
|
|
52
63
|
"@types/node": "18.18.0",
|
|
53
|
-
"@rollup/wasm-node": "4.
|
|
54
|
-
"
|
|
55
|
-
"typescript": "5.
|
|
64
|
+
"@rollup/wasm-node": "4.46.2",
|
|
65
|
+
"eslint": "9.32.0",
|
|
66
|
+
"typescript": "5.9.2"
|
|
56
67
|
},
|
|
57
68
|
"publishConfig": {
|
|
58
69
|
"access": "public",
|
package/index.ts
DELETED
|
@@ -1,235 +0,0 @@
|
|
|
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
|
-
}
|