@arcjet/node 1.0.0-beta.1 → 1.0.0-beta.11

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.
Files changed (4) hide show
  1. package/README.md +46 -71
  2. package/index.d.ts +122 -20
  3. package/index.js +71 -20
  4. package/package.json +31 -24
package/README.md CHANGED
@@ -25,6 +25,9 @@ This is the [Arcjet][arcjet] SDK for [Node.js][node-js].
25
25
  **Looking for our Next.js framework SDK?** Check out the
26
26
  [`@arcjet/next`][alt-sdk] package.
27
27
 
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)
30
+
28
31
  ## Getting started
29
32
 
30
33
  Visit the [quick start guide][quick-start] to get started.
@@ -34,111 +37,83 @@ Visit the [quick start guide][quick-start] to get started.
34
37
  Try an Arcjet protected app live at [https://example.arcjet.com][example-url]
35
38
  ([source code][example-source]).
36
39
 
37
- ## Installation
38
-
39
- ```shell
40
- npm install -S @arcjet/node
41
- ```
42
-
43
- ## Rate limit example
44
-
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.
40
+ ## What is this?
49
41
 
50
- Bot detection is also enabled to block requests from known bots.
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.
51
46
 
52
- ```ts
53
- import arcjet, { tokenBucket, detectBot } from "@arcjet/node";
54
- import http from "node:http";
47
+ ## When should I use this?
55
48
 
56
- const aj = arcjet({
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
59
- rules: [
60
- // Create a token bucket rate limit. Other algorithms are supported.
61
- tokenBucket({
62
- mode: "LIVE", // will block requests. Use "DRY_RUN" to log only
63
- refillRate: 5, // refill 5 tokens per interval
64
- interval: 10, // refill every 10 seconds
65
- capacity: 10, // bucket maximum capacity of 10 tokens
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
- }),
73
- ],
74
- });
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.
75
52
 
76
- const server = http.createServer(async function (
77
- req: http.IncomingMessage,
78
- res: http.ServerResponse,
79
- ) {
80
- const userId = "user123"; // Replace with your authenticated user ID
81
- const decision = await aj.protect(req, { userId, requested: 5 }); // Deduct 5 tokens from the bucket
82
- console.log("Arcjet decision", decision);
53
+ ## Install
83
54
 
84
- if (decision.isDenied()) {
85
- res.writeHead(403, { "Content-Type": "application/json" });
86
- res.end(JSON.stringify({ error: "Forbidden" }));
87
- } else {
88
- res.writeHead(200, { "Content-Type": "application/json" });
89
- res.end(JSON.stringify({ message: "Hello world" }));
90
- }
91
- });
55
+ This package is ESM only.
56
+ Install with npm in Node.js:
92
57
 
93
- server.listen(8000);
58
+ ```sh
59
+ npm install @arcjet/node
94
60
  ```
95
61
 
96
- ## Shield example
97
-
98
- [Arcjet Shield][shield-concepts-docs] protects your application against common
99
- attacks, including the OWASP Top 10. You can run Shield on every request with
100
- negligible performance impact.
62
+ ## Use
101
63
 
102
64
  ```ts
103
- import arcjet, { shield } from "@arcjet/node";
104
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
+ }
105
75
 
106
76
  const aj = arcjet({
107
- key: process.env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com
77
+ key: arcjetKey,
108
78
  rules: [
109
- shield({
110
- mode: "LIVE", // will block requests. Use "DRY_RUN" to log only
111
- }),
79
+ // Shield protects your app from common attacks.
80
+ // Use `DRY_RUN` instead of `LIVE` to only log.
81
+ shield({ mode: "LIVE" }),
112
82
  ],
113
83
  });
114
84
 
115
85
  const server = http.createServer(async function (
116
- req: http.IncomingMessage,
117
- res: http.ServerResponse,
86
+ request: http.IncomingMessage,
87
+ response: http.ServerResponse,
118
88
  ) {
119
- const decision = await aj.protect(req);
89
+ const decision = await aj.protect(request);
120
90
 
121
91
  if (decision.isDenied()) {
122
- res.writeHead(403, { "Content-Type": "application/json" });
123
- res.end(JSON.stringify({ error: "Forbidden" }));
124
- } else {
125
- res.writeHead(200, { "Content-Type": "application/json" });
126
- res.end(JSON.stringify({ message: "Hello world" }));
92
+ response.writeHead(403, { "Content-Type": "application/json" });
93
+ response.end(JSON.stringify({ message: "Forbidden" }));
94
+ return;
127
95
  }
96
+
97
+ response.writeHead(200, { "Content-Type": "application/json" });
98
+ response.end(JSON.stringify({ message: "Hello world" }));
128
99
  });
129
100
 
130
101
  server.listen(8000);
131
102
  ```
132
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
+
133
107
  ## License
134
108
 
135
- Licensed under the [Apache License, Version 2.0][apache-license].
109
+ [Apache License, Version 2.0][apache-license] © [Arcjet Labs, Inc.][arcjet]
136
110
 
111
+ [arcjet-get-started]: https://docs.arcjet.com/get-started
112
+ [arcjet-reference-node]: https://docs.arcjet.com/reference/nodejs
137
113
  [arcjet]: https://arcjet.com
138
114
  [node-js]: https://nodejs.org/
139
115
  [alt-sdk]: https://www.npmjs.com/package/@arcjet/next
140
116
  [example-url]: https://example.arcjet.com
141
117
  [quick-start]: https://docs.arcjet.com/get-started/nodejs
142
118
  [example-source]: https://github.com/arcjet/arcjet-js-example
143
- [shield-concepts-docs]: https://docs.arcjet.com/shield/concepts
144
119
  [apache-license]: http://www.apache.org/licenses/LICENSE-2.0
package/index.d.ts CHANGED
@@ -10,66 +10,168 @@ type WithoutCustomProps = {
10
10
  type PlainObject = {
11
11
  [key: string]: unknown;
12
12
  };
13
+ /**
14
+ * Configuration for {@linkcode createRemoteClient}.
15
+ */
13
16
  export type RemoteClientOptions = {
17
+ /**
18
+ * Base URI for HTTP requests to Decide API (optional).
19
+ *
20
+ * Defaults to the environment variable `ARCJET_BASE_URL` (if that value
21
+ * is known and allowed) and the standard production API otherwise.
22
+ */
14
23
  baseUrl?: string;
24
+ /**
25
+ * Timeout in milliseconds for the Decide API (optional).
26
+ *
27
+ * Defaults to `500` in production and `1000` in development.
28
+ */
15
29
  timeout?: number;
16
30
  };
31
+ /**
32
+ * Create a remote client.
33
+ *
34
+ * @param options
35
+ * Configuration (optional).
36
+ * @returns
37
+ * Client.
38
+ */
17
39
  export declare function createRemoteClient(options?: RemoteClientOptions): import("@arcjet/protocol/client.js").Client;
18
40
  type EventHandlerLike = (event: string, listener: (...args: any[]) => void) => void;
41
+ /**
42
+ * Request for the Node.js integration of Arcjet.
43
+ *
44
+ * This is the minimum interface similar to `http.IncomingMessage`.
45
+ */
19
46
  export interface ArcjetNodeRequest {
47
+ /**
48
+ * Headers of the request.
49
+ */
20
50
  headers?: Record<string, string | string[] | undefined>;
51
+ /**
52
+ * `net.Socket` object associated with the connection.
53
+ *
54
+ * See <https://nodejs.org/api/http.html#messagesocket>.
55
+ */
21
56
  socket?: Partial<{
22
57
  remoteAddress: string;
23
58
  encrypted: boolean;
24
59
  }>;
60
+ /**
61
+ * HTTP method of the request.
62
+ */
25
63
  method?: string;
64
+ /**
65
+ * HTTP version sent by the client.
66
+ *
67
+ * See <https://nodejs.org/api/http.html#messagehttpversion>.
68
+ */
26
69
  httpVersion?: string;
70
+ /**
71
+ * URL.
72
+ */
27
73
  url?: string;
74
+ /**
75
+ * Request body.
76
+ */
28
77
  body?: unknown;
78
+ /**
79
+ * Add event handlers.
80
+ *
81
+ * This field is available through `stream.Readable` from `EventEmitter`.
82
+ *
83
+ * See <https://nodejs.org/api/events.html#emitteroneventname-listener>.
84
+ */
29
85
  on?: EventHandlerLike;
86
+ /**
87
+ * Remove event handlers.
88
+ *
89
+ * This field is available through `stream.Readable` from `EventEmitter`.
90
+ *
91
+ * See <https://nodejs.org/api/events.html#emitterremovelistenereventname-listener>.
92
+ */
30
93
  removeListener?: EventHandlerLike;
94
+ /**
95
+ * Whether the readable stream is readable.
96
+ *
97
+ * This field is available from `stream.Readable`.
98
+ *
99
+ * See <https://nodejs.org/api/stream.html#readablereadable>.
100
+ */
31
101
  readable?: boolean;
32
102
  }
33
103
  /**
34
- * The options used to configure an {@link ArcjetNode} client.
104
+ * Configuration for the Node.js integration of Arcjet.
105
+ *
106
+ * @template Rules
107
+ * List of rules.
108
+ * @template Characteristics
109
+ * Characteristics to track a user by.
35
110
  */
36
111
  export type ArcjetOptions<Rules extends [...Array<Primitive | Product>], Characteristics extends readonly string[]> = Simplify<CoreOptions<Rules, Characteristics> & {
37
112
  /**
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.
113
+ * IP addresses and CIDR ranges of trusted load balancers and proxies
114
+ * (optional, example: `["100.100.100.100", "100.100.100.0/24"]`).
40
115
  */
41
116
  proxies?: Array<string>;
42
117
  }>;
43
118
  /**
44
- * The ArcjetNode client provides a public `protect()` method to
45
- * make a decision about how a Node.js request should be handled.
119
+ * Instance of the Node.js integration of Arcjet.
120
+ *
121
+ * Primarily has a `protect()` method to make a decision about how a Node request
122
+ * should be handled.
123
+ *
124
+ * @template Props
125
+ * Configuration.
46
126
  */
47
127
  export interface ArcjetNode<Props extends PlainObject> {
48
128
  /**
49
- * Runs a request through the configured protections. The request is
50
- * analyzed and then a decision made on whether to allow, deny, or challenge
51
- * the request.
129
+ * Make a decision about how to handle a request.
130
+ *
131
+ * This will analyze the request locally where possible and otherwise call
132
+ * the Arcjet decision API.
52
133
  *
53
- * @param req - An `IncomingMessage` provided to the request handler.
54
- * @param props - Additonal properties required for running rules against a request.
55
- * @returns An {@link ArcjetDecision} indicating Arcjet's decision about the request.
134
+ * @param request
135
+ * Details about the {@linkcode ArcjetNodeRequest} that Arcjet needs to make a
136
+ * decision.
137
+ * @param props
138
+ * Additional properties required for running rules against a request.
139
+ * @returns
140
+ * Promise that resolves to an {@linkcode ArcjetDecision} indicating
141
+ * Arcjet’s decision about the request.
56
142
  */
57
143
  protect(request: ArcjetNodeRequest, ...props: Props extends WithoutCustomProps ? [] : [Props]): Promise<ArcjetDecision>;
58
144
  /**
59
- * Augments the client with another rule. Useful for varying rules based on
60
- * criteria in your handler—e.g. different rate limit for logged in users.
145
+ * Augment the client with another rule.
61
146
  *
62
- * @param rule The rule to add to this execution.
63
- * @returns An augmented {@link ArcjetNode} client.
147
+ * Useful for varying rules based on criteria in your handler such as
148
+ * different rate limit for logged in users.
149
+ *
150
+ * @template Rule
151
+ * Type of rule.
152
+ * @param rule
153
+ * Rule to add to Arcjet.
154
+ * @returns
155
+ * Arcjet instance augmented with the given rule.
64
156
  */
65
157
  withRule<Rule extends Primitive | Product>(rule: Rule): ArcjetNode<Simplify<Props & ExtraProps<Rule>>>;
66
158
  }
67
159
  /**
68
- * Create a new {@link ArcjetNode} client. Always build your initial client
69
- * outside of a request handler so it persists across requests. If you need to
70
- * augment a client inside a handler, call the `withRule()` function on the base
71
- * client.
160
+ * Create a new Node.js integration of Arcjet.
161
+ *
162
+ * > 👉 **Tip**:
163
+ * > build your initial base client with as many rules as possible outside of a
164
+ * > request handler;
165
+ * > if you need more rules inside handlers later then you can call `withRule()`
166
+ * > on that base client.
72
167
  *
73
- * @param options - Arcjet configuration options to apply to all requests.
168
+ * @template Rules
169
+ * List of rules.
170
+ * @template Characteristics
171
+ * Characteristics to track a user by.
172
+ * @param options
173
+ * Configuration.
174
+ * @returns
175
+ * Node.js integration of Arcjet.
74
176
  */
75
177
  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,13 +1,45 @@
1
1
  import core__default from 'arcjet';
2
2
  export * from 'arcjet';
3
- import findIP from '@arcjet/ip';
4
- import ArcjetHeaders from '@arcjet/headers';
5
- import { logLevel, baseUrl, isDevelopment, platform } from '@arcjet/env';
3
+ import findIp, { parseProxy } from '@arcjet/ip';
4
+ import { ArcjetHeaders } from '@arcjet/headers';
5
+ import { logLevel, isDevelopment, baseUrl, platform } from '@arcjet/env';
6
6
  import { Logger } from '@arcjet/logger';
7
7
  import { createClient } from '@arcjet/protocol/client.js';
8
8
  import { createTransport } from '@arcjet/transport';
9
9
  import { readBody } from '@arcjet/body';
10
10
 
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
+ };
11
43
  // TODO: Deduplicate with other packages
12
44
  function errorMessage(err) {
13
45
  if (err) {
@@ -22,17 +54,21 @@ function errorMessage(err) {
22
54
  }
23
55
  return "Unknown problem";
24
56
  }
57
+ /**
58
+ * Create a remote client.
59
+ *
60
+ * @param options
61
+ * Configuration (optional).
62
+ * @returns
63
+ * Client.
64
+ */
25
65
  function createRemoteClient(options) {
26
- // The base URL for the Arcjet API. Will default to the standard production
27
- // API unless environment variable `ARCJET_BASE_URL` is set.
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);
66
+ const url = options?.baseUrl ?? baseUrl(env);
67
+ const timeout = options?.timeout ?? (isDevelopment(env) ? 1000 : 500);
32
68
  // Transport is the HTTP client that the client uses to make requests.
33
69
  const transport = createTransport(url);
34
70
  const sdkStack = "NODEJS";
35
- const sdkVersion = "1.0.0-beta.1";
71
+ const sdkVersion = "1.0.0-beta.11";
36
72
  return createClient({
37
73
  transport,
38
74
  baseUrl: url,
@@ -52,34 +88,49 @@ function cookiesToString(cookies) {
52
88
  return cookies;
53
89
  }
54
90
  /**
55
- * Create a new {@link ArcjetNode} client. Always build your initial client
56
- * outside of a request handler so it persists across requests. If you need to
57
- * augment a client inside a handler, call the `withRule()` function on the base
58
- * client.
91
+ * Create a new Node.js integration of Arcjet.
59
92
  *
60
- * @param options - Arcjet configuration options to apply to all requests.
93
+ * > 👉 **Tip**:
94
+ * > build your initial base client with as many rules as possible outside of a
95
+ * > request handler;
96
+ * > if you need more rules inside handlers later then you can call `withRule()`
97
+ * > on that base client.
98
+ *
99
+ * @template Rules
100
+ * List of rules.
101
+ * @template Characteristics
102
+ * Characteristics to track a user by.
103
+ * @param options
104
+ * Configuration.
105
+ * @returns
106
+ * Node.js integration of Arcjet.
61
107
  */
62
108
  function arcjet(options) {
63
109
  const client = options.client ?? createRemoteClient();
64
110
  const log = options.log
65
111
  ? options.log
66
112
  : new Logger({
67
- level: logLevel(process.env),
113
+ level: logLevel(env),
68
114
  });
115
+ const proxies = Array.isArray(options.proxies)
116
+ ? options.proxies.map(parseProxy)
117
+ : undefined;
118
+ if (isDevelopment(env)) {
119
+ log.warn("Arcjet will use 127.0.0.1 when missing public IP address in development mode");
120
+ }
69
121
  function toArcjetRequest(request, props) {
70
122
  // We pull the cookies from the request before wrapping them in ArcjetHeaders
71
123
  const cookies = cookiesToString(request.headers?.cookie);
72
124
  // We construct an ArcjetHeaders to normalize over Headers
73
125
  const headers = new ArcjetHeaders(request.headers);
74
- let ip = findIP({
126
+ let ip = findIp({
75
127
  socket: request.socket,
76
128
  headers,
77
- }, { platform: platform(process.env), proxies: options.proxies });
129
+ }, { platform: platform(env), proxies });
78
130
  if (ip === "") {
79
131
  // If the `ip` is empty but we're in development mode, we default the IP
80
132
  // 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");
133
+ if (isDevelopment(env)) {
83
134
  ip = "127.0.0.1";
84
135
  }
85
136
  else {
package/package.json CHANGED
@@ -1,7 +1,19 @@
1
1
  {
2
2
  "name": "@arcjet/node",
3
- "version": "1.0.0-beta.1",
3
+ "version": "1.0.0-beta.11",
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,37 +37,32 @@
25
37
  "main": "./index.js",
26
38
  "types": "./index.d.ts",
27
39
  "files": [
28
- "LICENSE",
29
- "README.md",
30
- "*.js",
31
- "*.d.ts",
32
- "!*.config.js"
40
+ "index.d.ts",
41
+ "index.js"
33
42
  ],
34
43
  "scripts": {
35
- "prepublishOnly": "npm run build",
36
44
  "build": "rollup --config rollup.config.js",
37
45
  "lint": "eslint .",
38
- "pretest": "npm run build",
39
- "test": "node --test --experimental-test-coverage"
46
+ "prepublishOnly": "npm run build",
47
+ "test": "npm run build && npm run lint"
40
48
  },
41
49
  "dependencies": {
42
- "@arcjet/env": "1.0.0-beta.1",
43
- "@arcjet/headers": "1.0.0-beta.1",
44
- "@arcjet/ip": "1.0.0-beta.1",
45
- "@arcjet/logger": "1.0.0-beta.1",
46
- "@arcjet/protocol": "1.0.0-beta.1",
47
- "@arcjet/transport": "1.0.0-beta.1",
48
- "@arcjet/body": "1.0.0-beta.1",
49
- "arcjet": "1.0.0-beta.1"
50
+ "@arcjet/env": "1.0.0-beta.11",
51
+ "@arcjet/headers": "1.0.0-beta.11",
52
+ "@arcjet/ip": "1.0.0-beta.11",
53
+ "@arcjet/logger": "1.0.0-beta.11",
54
+ "@arcjet/protocol": "1.0.0-beta.11",
55
+ "@arcjet/transport": "1.0.0-beta.11",
56
+ "@arcjet/body": "1.0.0-beta.11",
57
+ "arcjet": "1.0.0-beta.11"
50
58
  },
51
59
  "devDependencies": {
52
- "@arcjet/eslint-config": "1.0.0-beta.1",
53
- "@arcjet/rollup-config": "1.0.0-beta.1",
54
- "@arcjet/tsconfig": "1.0.0-beta.1",
55
- "@types/node": "18.18.0",
56
- "@rollup/wasm-node": "4.30.1",
57
- "expect": "29.7.0",
58
- "typescript": "5.7.3"
60
+ "@arcjet/eslint-config": "1.0.0-beta.11",
61
+ "@arcjet/rollup-config": "1.0.0-beta.11",
62
+ "@types/node": "24.3.0",
63
+ "@rollup/wasm-node": "4.50.0",
64
+ "eslint": "9.34.0",
65
+ "typescript": "5.9.2"
59
66
  },
60
67
  "publishConfig": {
61
68
  "access": "public",