@arcjet/node 1.0.0-alpha.9 → 1.0.0-beta.2
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 +42 -24
- package/index.d.ts +22 -4
- package/index.js +164 -79
- package/package.json +16 -13
- 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,13 +17,22 @@
|
|
|
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
|
+
|
|
28
|
+
## Getting started
|
|
29
|
+
|
|
30
|
+
Visit the [quick start guide][quick-start] to get started.
|
|
31
|
+
|
|
32
|
+
## Example app
|
|
33
|
+
|
|
34
|
+
Try an Arcjet protected app live at [https://example.arcjet.com][example-url]
|
|
35
|
+
([source code][example-source]).
|
|
27
36
|
|
|
28
37
|
## Installation
|
|
29
38
|
|
|
@@ -33,27 +42,34 @@ npm install -S @arcjet/node
|
|
|
33
42
|
|
|
34
43
|
## Rate limit example
|
|
35
44
|
|
|
36
|
-
The
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
45
|
+
The example below applies a token bucket rate limit rule to a route where we
|
|
46
|
+
identify the user based on their ID e.g. if they are logged in. The bucket is
|
|
47
|
+
configured with a maximum capacity of 10 tokens and refills by 5 tokens every 10
|
|
48
|
+
seconds. Each request consumes 5 tokens.
|
|
49
|
+
|
|
50
|
+
Bot detection is also enabled to block requests from known bots.
|
|
41
51
|
|
|
42
52
|
```ts
|
|
43
|
-
import arcjet, { tokenBucket } from "@arcjet/node";
|
|
53
|
+
import arcjet, { tokenBucket, detectBot } from "@arcjet/node";
|
|
44
54
|
import http from "node:http";
|
|
45
55
|
|
|
46
56
|
const aj = arcjet({
|
|
47
57
|
key: process.env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com
|
|
58
|
+
characteristics: ["userId"], // track requests by a custom user ID
|
|
48
59
|
rules: [
|
|
49
60
|
// Create a token bucket rate limit. Other algorithms are supported.
|
|
50
61
|
tokenBucket({
|
|
51
62
|
mode: "LIVE", // will block requests. Use "DRY_RUN" to log only
|
|
52
|
-
characteristics: ["userId"], // track requests by a custom user ID
|
|
53
63
|
refillRate: 5, // refill 5 tokens per interval
|
|
54
64
|
interval: 10, // refill every 10 seconds
|
|
55
65
|
capacity: 10, // bucket maximum capacity of 10 tokens
|
|
56
66
|
}),
|
|
67
|
+
detectBot({
|
|
68
|
+
mode: "LIVE", // will block requests. Use "DRY_RUN" to log only
|
|
69
|
+
// configured with a list of bots to allow from
|
|
70
|
+
// https://arcjet.com/bot-list
|
|
71
|
+
allow: [], // "allow none" will block all detected bots
|
|
72
|
+
}),
|
|
57
73
|
],
|
|
58
74
|
});
|
|
59
75
|
|
|
@@ -66,10 +82,8 @@ const server = http.createServer(async function (
|
|
|
66
82
|
console.log("Arcjet decision", decision);
|
|
67
83
|
|
|
68
84
|
if (decision.isDenied()) {
|
|
69
|
-
res.writeHead(
|
|
70
|
-
res.end(
|
|
71
|
-
JSON.stringify({ error: "Too Many Requests", reason: decision.reason }),
|
|
72
|
-
);
|
|
85
|
+
res.writeHead(403, { "Content-Type": "application/json" });
|
|
86
|
+
res.end(JSON.stringify({ error: "Forbidden" }));
|
|
73
87
|
} else {
|
|
74
88
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
75
89
|
res.end(JSON.stringify({ message: "Hello world" }));
|
|
@@ -82,19 +96,20 @@ server.listen(8000);
|
|
|
82
96
|
## Shield example
|
|
83
97
|
|
|
84
98
|
[Arcjet Shield][shield-concepts-docs] protects your application against common
|
|
85
|
-
attacks, including the OWASP Top 10.
|
|
86
|
-
|
|
99
|
+
attacks, including the OWASP Top 10. You can run Shield on every request with
|
|
100
|
+
negligible performance impact.
|
|
87
101
|
|
|
88
102
|
```ts
|
|
89
|
-
import arcjet from "@arcjet/node";
|
|
103
|
+
import arcjet, { shield } from "@arcjet/node";
|
|
90
104
|
import http from "node:http";
|
|
91
105
|
|
|
92
106
|
const aj = arcjet({
|
|
93
|
-
// Get your site key from https://app.arcjet.com
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
107
|
+
key: process.env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com
|
|
108
|
+
rules: [
|
|
109
|
+
shield({
|
|
110
|
+
mode: "LIVE", // will block requests. Use "DRY_RUN" to log only
|
|
111
|
+
}),
|
|
112
|
+
],
|
|
98
113
|
});
|
|
99
114
|
|
|
100
115
|
const server = http.createServer(async function (
|
|
@@ -121,6 +136,9 @@ Licensed under the [Apache License, Version 2.0][apache-license].
|
|
|
121
136
|
|
|
122
137
|
[arcjet]: https://arcjet.com
|
|
123
138
|
[node-js]: https://nodejs.org/
|
|
124
|
-
[
|
|
139
|
+
[alt-sdk]: https://www.npmjs.com/package/@arcjet/next
|
|
140
|
+
[example-url]: https://example.arcjet.com
|
|
141
|
+
[quick-start]: https://docs.arcjet.com/get-started/nodejs
|
|
142
|
+
[example-source]: https://github.com/arcjet/arcjet-js-example
|
|
125
143
|
[shield-concepts-docs]: https://docs.arcjet.com/shield/concepts
|
|
126
144
|
[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,45 @@
|
|
|
1
|
-
import
|
|
2
|
-
import core__default, { defaultBaseUrl, createRemoteClient, ArcjetHeaders } from 'arcjet';
|
|
1
|
+
import core__default from 'arcjet';
|
|
3
2
|
export * from 'arcjet';
|
|
4
3
|
import findIP from '@arcjet/ip';
|
|
4
|
+
import ArcjetHeaders from '@arcjet/headers';
|
|
5
|
+
import { logLevel, baseUrl, isDevelopment, 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
|
+
// TODO: Deduplicate with other packages
|
|
12
|
+
function errorMessage(err) {
|
|
13
|
+
if (err) {
|
|
14
|
+
if (typeof err === "string") {
|
|
15
|
+
return err;
|
|
16
|
+
}
|
|
17
|
+
if (typeof err === "object" &&
|
|
18
|
+
"message" in err &&
|
|
19
|
+
typeof err.message === "string") {
|
|
20
|
+
return err.message;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return "Unknown problem";
|
|
24
|
+
}
|
|
25
|
+
function createRemoteClient(options) {
|
|
7
26
|
// The base URL for the Arcjet API. Will default to the standard production
|
|
8
27
|
// API unless environment variable `ARCJET_BASE_URL` is set.
|
|
9
|
-
const
|
|
28
|
+
const url = options?.baseUrl ?? baseUrl(process.env);
|
|
29
|
+
// The timeout for the Arcjet API in milliseconds. This is set to a low value
|
|
30
|
+
// in production so calls fail open.
|
|
31
|
+
const timeout = options?.timeout ?? (isDevelopment(process.env) ? 1000 : 500);
|
|
10
32
|
// 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`
|
|
33
|
+
const transport = createTransport(url);
|
|
17
34
|
const sdkStack = "NODEJS";
|
|
18
|
-
const sdkVersion = "1.0.0-
|
|
19
|
-
return
|
|
35
|
+
const sdkVersion = "1.0.0-beta.2";
|
|
36
|
+
return createClient({
|
|
37
|
+
transport,
|
|
38
|
+
baseUrl: url,
|
|
39
|
+
timeout,
|
|
40
|
+
sdkStack,
|
|
41
|
+
sdkVersion,
|
|
42
|
+
});
|
|
20
43
|
}
|
|
21
44
|
function cookiesToString(cookies) {
|
|
22
45
|
if (typeof cookies === "undefined") {
|
|
@@ -28,70 +51,6 @@ function cookiesToString(cookies) {
|
|
|
28
51
|
}
|
|
29
52
|
return cookies;
|
|
30
53
|
}
|
|
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
54
|
/**
|
|
96
55
|
* Create a new {@link ArcjetNode} client. Always build your initial client
|
|
97
56
|
* outside of a request handler so it persists across requests. If you need to
|
|
@@ -101,9 +60,135 @@ function withClient(aj) {
|
|
|
101
60
|
* @param options - Arcjet configuration options to apply to all requests.
|
|
102
61
|
*/
|
|
103
62
|
function arcjet(options) {
|
|
104
|
-
const client = options.client ??
|
|
105
|
-
const
|
|
63
|
+
const client = options.client ?? createRemoteClient();
|
|
64
|
+
const log = options.log
|
|
65
|
+
? options.log
|
|
66
|
+
: new Logger({
|
|
67
|
+
level: logLevel(process.env),
|
|
68
|
+
});
|
|
69
|
+
function toArcjetRequest(request, props) {
|
|
70
|
+
// We pull the cookies from the request before wrapping them in ArcjetHeaders
|
|
71
|
+
const cookies = cookiesToString(request.headers?.cookie);
|
|
72
|
+
// We construct an ArcjetHeaders to normalize over Headers
|
|
73
|
+
const headers = new ArcjetHeaders(request.headers);
|
|
74
|
+
let ip = findIP({
|
|
75
|
+
socket: request.socket,
|
|
76
|
+
headers,
|
|
77
|
+
}, { platform: platform(process.env), proxies: options.proxies });
|
|
78
|
+
if (ip === "") {
|
|
79
|
+
// If the `ip` is empty but we're in development mode, we default the IP
|
|
80
|
+
// so the request doesn't fail.
|
|
81
|
+
if (isDevelopment(process.env)) {
|
|
82
|
+
log.warn("Using 127.0.0.1 as IP address in development mode");
|
|
83
|
+
ip = "127.0.0.1";
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
log.warn(`Client IP address is missing. If this is a dev environment set the ARCJET_ENV env var to "development"`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const method = request.method ?? "";
|
|
90
|
+
const host = headers.get("host") ?? "";
|
|
91
|
+
let path = "";
|
|
92
|
+
let query = "";
|
|
93
|
+
let protocol = "";
|
|
94
|
+
if (typeof request.socket?.encrypted !== "undefined") {
|
|
95
|
+
protocol = request.socket.encrypted ? "https:" : "http:";
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
protocol = "http:";
|
|
99
|
+
}
|
|
100
|
+
// Do some very simple validation, but also try/catch around URL parsing
|
|
101
|
+
if (typeof request.url !== "undefined" &&
|
|
102
|
+
request.url !== "" &&
|
|
103
|
+
host !== "") {
|
|
104
|
+
try {
|
|
105
|
+
const url = new URL(request.url, `${protocol}//${host}`);
|
|
106
|
+
path = url.pathname;
|
|
107
|
+
query = url.search;
|
|
108
|
+
protocol = url.protocol;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
// If the parsing above fails, just set the path as whatever url we
|
|
112
|
+
// received.
|
|
113
|
+
path = request.url ?? "";
|
|
114
|
+
log.warn('Unable to parse URL. Using "%s" as `path`.', path);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
path = request.url ?? "";
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
...props,
|
|
122
|
+
ip,
|
|
123
|
+
method,
|
|
124
|
+
protocol,
|
|
125
|
+
host,
|
|
126
|
+
path,
|
|
127
|
+
headers,
|
|
128
|
+
cookies,
|
|
129
|
+
query,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function withClient(aj) {
|
|
133
|
+
return Object.freeze({
|
|
134
|
+
withRule(rule) {
|
|
135
|
+
const client = aj.withRule(rule);
|
|
136
|
+
return withClient(client);
|
|
137
|
+
},
|
|
138
|
+
async protect(request, ...[props]) {
|
|
139
|
+
// TODO(#220): The generic manipulations get really mad here, so we cast
|
|
140
|
+
// Further investigation makes it seem like it has something to do with
|
|
141
|
+
// the definition of `props` in the signature but it's hard to track down
|
|
142
|
+
const req = toArcjetRequest(request, props ?? {});
|
|
143
|
+
const getBody = async () => {
|
|
144
|
+
try {
|
|
145
|
+
// If request.body is present then the body was likely read by a package like express' `body-parser`.
|
|
146
|
+
// If it's not present then we attempt to read the bytes from the IncomingMessage ourselves.
|
|
147
|
+
if (typeof request.body === "string") {
|
|
148
|
+
return request.body;
|
|
149
|
+
}
|
|
150
|
+
else if (typeof request.body !== "undefined" &&
|
|
151
|
+
// BigInt cannot be serialized with JSON.stringify
|
|
152
|
+
typeof request.body !== "bigint") {
|
|
153
|
+
return JSON.stringify(request.body);
|
|
154
|
+
}
|
|
155
|
+
if (typeof request.on === "function" &&
|
|
156
|
+
typeof request.removeListener === "function") {
|
|
157
|
+
let expectedLength;
|
|
158
|
+
// TODO: This shouldn't need to build headers again but the type
|
|
159
|
+
// for `req` above is overly relaxed
|
|
160
|
+
const headers = new ArcjetHeaders(request.headers);
|
|
161
|
+
const expectedLengthStr = headers.get("content-length");
|
|
162
|
+
if (typeof expectedLengthStr === "string") {
|
|
163
|
+
try {
|
|
164
|
+
expectedLength = parseInt(expectedLengthStr, 10);
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
// If the expected length couldn't be parsed we'll just not set one.
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
// Awaited to throw if it rejects and we'll just return undefined
|
|
171
|
+
const body = await readBody(request, {
|
|
172
|
+
// We will process 1mb bodies
|
|
173
|
+
limit: 1048576,
|
|
174
|
+
expectedLength,
|
|
175
|
+
});
|
|
176
|
+
return body;
|
|
177
|
+
}
|
|
178
|
+
log.warn("no body available");
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
catch (e) {
|
|
182
|
+
log.error("failed to get request body: %s", errorMessage(e));
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
return aj.protect({ getBody }, req);
|
|
187
|
+
},
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
const aj = core__default({ ...options, client, log });
|
|
106
191
|
return withClient(aj);
|
|
107
192
|
}
|
|
108
193
|
|
|
109
|
-
export {
|
|
194
|
+
export { createRemoteClient, arcjet as default };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arcjet/node",
|
|
3
|
-
"version": "1.0.0-
|
|
3
|
+
"version": "1.0.0-beta.2",
|
|
4
4
|
"description": "Arcjet SDK for Node.js",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"homepage": "https://arcjet.com",
|
|
@@ -29,7 +29,6 @@
|
|
|
29
29
|
"README.md",
|
|
30
30
|
"*.js",
|
|
31
31
|
"*.d.ts",
|
|
32
|
-
"*.ts",
|
|
33
32
|
"!*.config.js"
|
|
34
33
|
],
|
|
35
34
|
"scripts": {
|
|
@@ -37,22 +36,26 @@
|
|
|
37
36
|
"build": "rollup --config rollup.config.js",
|
|
38
37
|
"lint": "eslint .",
|
|
39
38
|
"pretest": "npm run build",
|
|
40
|
-
"test": "
|
|
39
|
+
"test": "node --test --experimental-test-coverage"
|
|
41
40
|
},
|
|
42
41
|
"dependencies": {
|
|
43
|
-
"@arcjet/
|
|
44
|
-
"@
|
|
45
|
-
"arcjet": "1.0.0-
|
|
42
|
+
"@arcjet/env": "1.0.0-beta.2",
|
|
43
|
+
"@arcjet/headers": "1.0.0-beta.2",
|
|
44
|
+
"@arcjet/ip": "1.0.0-beta.2",
|
|
45
|
+
"@arcjet/logger": "1.0.0-beta.2",
|
|
46
|
+
"@arcjet/protocol": "1.0.0-beta.2",
|
|
47
|
+
"@arcjet/transport": "1.0.0-beta.2",
|
|
48
|
+
"@arcjet/body": "1.0.0-beta.2",
|
|
49
|
+
"arcjet": "1.0.0-beta.2"
|
|
46
50
|
},
|
|
47
51
|
"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",
|
|
52
|
+
"@arcjet/eslint-config": "1.0.0-beta.2",
|
|
53
|
+
"@arcjet/rollup-config": "1.0.0-beta.2",
|
|
54
|
+
"@arcjet/tsconfig": "1.0.0-beta.2",
|
|
52
55
|
"@types/node": "18.18.0",
|
|
53
|
-
"@rollup/wasm-node": "4.
|
|
54
|
-
"
|
|
55
|
-
"typescript": "5.
|
|
56
|
+
"@rollup/wasm-node": "4.34.2",
|
|
57
|
+
"expect": "29.7.0",
|
|
58
|
+
"typescript": "5.7.3"
|
|
56
59
|
},
|
|
57
60
|
"publishConfig": {
|
|
58
61
|
"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
|
-
}
|