@arcjet/astro 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/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,240 @@
1
+ <a href="https://arcjet.com" target="_arcjet-home">
2
+ <picture>
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
+ </picture>
6
+ </a>
7
+
8
+ # `@arcjet/astro`
9
+
10
+ <p>
11
+ <a href="https://www.npmjs.com/package/@arcjet/astro">
12
+ <picture>
13
+ <source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/npm/v/%40arcjet%2Fastro?style=flat-square&label=%E2%9C%A6Aj&labelColor=000000&color=5C5866">
14
+ <img alt="npm badge" src="https://img.shields.io/npm/v/%40arcjet%2Fastro?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, and defense
21
+ against common attacks.
22
+
23
+ This is the [Arcjet][arcjet] SDK integration for [Astro][astro].
24
+
25
+ ## Getting started
26
+
27
+ Visit the [quick start guide][quick-start] to get started.
28
+
29
+ ## Example app
30
+
31
+ Try an Arcjet protected app live at [https://example.arcjet.com][example-url]
32
+ ([source code][example-source]).
33
+
34
+ ## Installation
35
+
36
+ ```shell
37
+ npx astro add @arcjet/astro
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ If installed via the Astro CLI command above, your `astro.config.mjs` should be
43
+ changed like:
44
+
45
+ ```diff
46
+ // @ts-check
47
+ import { defineConfig } from "astro/config";
48
+ + import arcjet from "@arcjet/astro";
49
+
50
+ // https://astro.build/config
51
+ export default defineConfig({
52
+ + integrations: [
53
+ + arcjet(),
54
+ + ],
55
+ });
56
+ ```
57
+
58
+ However, if installed manually, you'll want to add the above lines to your Astro
59
+ configuration.
60
+
61
+ We also recommended validating your environment variables at build time. To do
62
+ this, update your `astro.config.mjs` to add the option:
63
+
64
+ ```diff
65
+ // @ts-check
66
+ import { defineConfig } from "astro/config";
67
+ import arcjet from "@arcjet/astro";
68
+
69
+ // https://astro.build/config
70
+ export default defineConfig({
71
+ + env: {
72
+ + validateSecrets: true
73
+ + },
74
+ integrations: [
75
+ arcjet(),
76
+ ],
77
+ });
78
+ ```
79
+
80
+ Once Arcjet is added as an integration, you'll want to start the Astro dev
81
+ server to build the `arcjet:client` virtual module and types. In your terminal,
82
+ run:
83
+
84
+ ```sh
85
+ npx astro dev
86
+ ```
87
+
88
+ You can now import from the `arcjet:client` module within your Astro project!
89
+
90
+ This example adds Arcjet to your middleware, but note this only works for
91
+ non-prerendered pages:
92
+
93
+ ```ts
94
+ // src/middleware.ts
95
+ import { defineMiddleware } from "astro:middleware";
96
+ import aj from "arcjet:client";
97
+
98
+ export const onRequest = defineMiddleware(
99
+ async ({ isPrerendered, request }, next) => {
100
+ // Arcjet can be run in your middleware; however, Arcjet can only process a
101
+ // request when the page is NOT prerendered.
102
+ if (!isPrerendered) {
103
+ // console.log(request);
104
+ const decision = await aj.protect(request);
105
+
106
+ // Deny decisions respond immediately to avoid any additional server
107
+ // processing.
108
+ if (decision.isDenied()) {
109
+ return new Response(null, { status: 403, statusText: "Forbidden" });
110
+ }
111
+ }
112
+
113
+ return next();
114
+ },
115
+ );
116
+ ```
117
+
118
+ ## Rate limit + bot detection example
119
+
120
+ The [Arcjet rate limit][rate-limit-concepts-docs] example below applies a token
121
+ bucket rate limit rule to a route where we identify the user based on their ID
122
+ e.g. if they are logged in. The bucket is configured with a maximum capacity of
123
+ 10 tokens and refills by 5 tokens every 10 seconds. Each request consumes 5
124
+ tokens.
125
+
126
+ The rule is defined in your `astro.config.mjs` file:
127
+
128
+ ```js
129
+ // @ts-check
130
+ import { defineConfig } from "astro/config";
131
+ import arcjet, { tokenBucket, detectBot } from "@arcjet/astro";
132
+
133
+ // https://astro.build/config
134
+ export default defineConfig({
135
+ env: {
136
+ validateSecrets: true,
137
+ },
138
+ integrations: [
139
+ arcjet({
140
+ characteristics: ["userId"], // track requests by a custom user ID
141
+ rules: [
142
+ // Create a token bucket rate limit. Other algorithms are supported.
143
+ tokenBucket({
144
+ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only
145
+ refillRate: 5, // refill 5 tokens per interval
146
+ interval: 10, // refill every 10 seconds
147
+ capacity: 10, // bucket maximum capacity of 10 tokens
148
+ }),
149
+ detectBot({
150
+ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only
151
+ // configured with a list of bots to allow from
152
+ // https://arcjet.com/bot-list
153
+ allow: [], // "allow none" will block all detected bots
154
+ }),
155
+ ],
156
+ }),
157
+ ],
158
+ });
159
+ ```
160
+
161
+ Then Arcjet is called from within this page route:
162
+
163
+ ```ts
164
+ // src/pages/api.json.ts
165
+ import type { APIRoute } from "astro";
166
+ import aj from "arcjet:client";
167
+
168
+ export const GET: APIRoute = async ({ request }) => {
169
+ const userId = "user123"; // Replace with your authenticated user ID
170
+ const decision = await aj.protect(request, { userId, requested: 5 }); // Deduct 5 tokens from the bucket
171
+ console.log("Arcjet decision", decision);
172
+
173
+ if (decision.isDenied()) {
174
+ return Response.json({ error: "Forbidden" }, { status: 403 });
175
+ } else {
176
+ return Response.json({ message: "Hello world" });
177
+ }
178
+ };
179
+ ```
180
+
181
+ ## Shield example
182
+
183
+ [Arcjet Shield][shield-concepts-docs] protects your application against common
184
+ attacks, including the OWASP Top 10. You can run Shield on every request with
185
+ negligible performance impact.
186
+
187
+ The rule is defined in your `astro.config.mjs` file:
188
+
189
+ ```js
190
+ // @ts-check
191
+ import { defineConfig } from "astro/config";
192
+ import arcjet, { shield } from "@arcjet/astro";
193
+
194
+ // https://astro.build/config
195
+ export default defineConfig({
196
+ env: {
197
+ validateSecrets: true,
198
+ },
199
+ integrations: [
200
+ arcjet({
201
+ rules: [
202
+ shield({
203
+ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only
204
+ }),
205
+ ],
206
+ }),
207
+ ],
208
+ });
209
+ ```
210
+
211
+ Then Arcjet is called from within this page route:
212
+
213
+ ```ts
214
+ // src/pages/api.json.ts
215
+ import type { APIRoute } from "astro";
216
+ import aj from "arcjet:client";
217
+
218
+ export const GET: APIRoute = async ({ request }) => {
219
+ const decision = await aj.protect(request);
220
+
221
+ if (decision.isDenied()) {
222
+ return Response.json({ error: "Forbidden" }, { status: 403 });
223
+ } else {
224
+ return Response.json({ message: "Hello world" });
225
+ }
226
+ };
227
+ ```
228
+
229
+ ## License
230
+
231
+ Licensed under the [Apache License, Version 2.0][apache-license].
232
+
233
+ [arcjet]: https://arcjet.com
234
+ [astro]: https://astro.build/
235
+ [example-url]: https://example.arcjet.com
236
+ [quick-start]: https://docs.arcjet.com/get-started/astro
237
+ [example-source]: https://github.com/arcjet/arcjet-js-example
238
+ [rate-limit-concepts-docs]: https://docs.arcjet.com/rate-limiting/concepts
239
+ [shield-concepts-docs]: https://docs.arcjet.com/shield/concepts
240
+ [apache-license]: http://www.apache.org/licenses/LICENSE-2.0
package/astro-env.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ declare module "astro:env/server" {
2
+ const ARCJET_BASE_URL: string | undefined;
3
+ const ARCJET_ENV: string | undefined;
4
+ const ARCJET_KEY: string | undefined;
5
+ const ARCJET_LOG_LEVEL: string | undefined;
6
+ const FLY_APP_NAME: string | undefined;
7
+ const VERCEL: string | undefined;
8
+ }
9
+
10
+ interface ImportMetaEnv {
11
+ readonly MODE: string | undefined;
12
+ }
13
+
14
+ interface ImportMeta {
15
+ readonly env: ImportMetaEnv;
16
+ }
package/index.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ import type { BotOptions, EmailOptions, FixedWindowRateLimitOptions, ProtectSignupOptions, SensitiveInfoOptions, ShieldOptions, SlidingWindowRateLimitOptions, TokenBucketRateLimitOptions } from "arcjet";
2
+ import type { AstroIntegration } from "astro";
3
+ type IntegrationRule<Characteristics extends readonly string[]> = {
4
+ type: "shield";
5
+ options?: ShieldOptions;
6
+ } | {
7
+ type: "bot";
8
+ options?: BotOptions;
9
+ } | {
10
+ type: "email";
11
+ options?: EmailOptions;
12
+ } | {
13
+ type: "sensitiveInfo";
14
+ options?: SensitiveInfoOptions<never>;
15
+ } | {
16
+ type: "fixedWindow";
17
+ options?: FixedWindowRateLimitOptions<Characteristics>;
18
+ } | {
19
+ type: "slidingWindow";
20
+ options?: SlidingWindowRateLimitOptions<Characteristics>;
21
+ } | {
22
+ type: "tokenBucket";
23
+ options?: TokenBucketRateLimitOptions<Characteristics>;
24
+ } | {
25
+ type: "protectSignup";
26
+ options?: ProtectSignupOptions<Characteristics>;
27
+ };
28
+ type ArcjetIntegrationOptions<Characteristics extends readonly string[]> = {
29
+ rules: IntegrationRule<Characteristics>[];
30
+ characteristics?: Characteristics;
31
+ client?: RemoteClientOptions;
32
+ proxies?: string[];
33
+ };
34
+ export declare function shield(options?: ShieldOptions): {
35
+ readonly type: "shield";
36
+ readonly options: ShieldOptions | undefined;
37
+ };
38
+ export declare function detectBot(options?: BotOptions): {
39
+ readonly type: "bot";
40
+ readonly options: BotOptions | undefined;
41
+ };
42
+ export declare function validateEmail(options?: EmailOptions): {
43
+ readonly type: "email";
44
+ readonly options: EmailOptions | undefined;
45
+ };
46
+ export declare function sensitiveInfo(options?: SensitiveInfoOptions<never>): {
47
+ readonly type: "sensitiveInfo";
48
+ readonly options: SensitiveInfoOptions<never> | undefined;
49
+ };
50
+ export declare function fixedWindow<Characteristics extends readonly string[]>(options?: FixedWindowRateLimitOptions<Characteristics>): {
51
+ readonly type: "fixedWindow";
52
+ readonly options: FixedWindowRateLimitOptions<Characteristics> | undefined;
53
+ };
54
+ export declare function slidingWindow<Characteristics extends readonly string[]>(options?: SlidingWindowRateLimitOptions<Characteristics>): {
55
+ readonly type: "slidingWindow";
56
+ readonly options: SlidingWindowRateLimitOptions<Characteristics> | undefined;
57
+ };
58
+ export declare function tokenBucket<Characteristics extends readonly string[]>(options?: TokenBucketRateLimitOptions<Characteristics>): {
59
+ readonly type: "tokenBucket";
60
+ readonly options: TokenBucketRateLimitOptions<Characteristics> | undefined;
61
+ };
62
+ export declare function protectSignup<Characteristics extends readonly string[]>(options?: ProtectSignupOptions<Characteristics>): {
63
+ readonly type: "protectSignup";
64
+ readonly options: ProtectSignupOptions<Characteristics> | undefined;
65
+ };
66
+ export type RemoteClientOptions = {
67
+ baseUrl?: string;
68
+ timeout?: number;
69
+ };
70
+ export declare function createRemoteClient({ baseUrl, timeout }: RemoteClientOptions): {
71
+ readonly baseUrl: string | undefined;
72
+ readonly timeout: number | undefined;
73
+ };
74
+ export default function arcjet<Characteristics extends readonly string[]>({ rules, characteristics, client, proxies, }?: ArcjetIntegrationOptions<Characteristics>): AstroIntegration;
75
+ export {};
package/index.js ADDED
@@ -0,0 +1,345 @@
1
+ import { z } from 'astro/zod';
2
+ import fs from 'node:fs/promises';
3
+
4
+ const resolvedVirtualClientId = "\0ARCJET_VIRTUAL_CLIENT";
5
+ const validateMode = z.enum(["LIVE", "DRY_RUN"]);
6
+ const validateProxies = z.array(z.string());
7
+ const validateCharacteristics = z.array(z.string());
8
+ const validateClientOptions = z
9
+ .object({
10
+ baseUrl: z.string(),
11
+ timeout: z.number(),
12
+ })
13
+ .strict()
14
+ .optional();
15
+ const validateShieldOptions = z
16
+ .object({
17
+ mode: validateMode,
18
+ })
19
+ .strict()
20
+ .optional();
21
+ const validateBotOptions = z
22
+ .union([
23
+ z
24
+ .object({
25
+ mode: validateMode,
26
+ allow: z.array(z.string()),
27
+ })
28
+ .strict(),
29
+ z
30
+ .object({
31
+ mode: validateMode,
32
+ deny: z.array(z.string()),
33
+ })
34
+ .strict(),
35
+ ])
36
+ .optional();
37
+ const validateEmailOptions = z
38
+ .union([
39
+ z
40
+ .object({
41
+ mode: validateMode,
42
+ allow: z.array(z.string()),
43
+ requireTopLevelDomain: z.boolean(),
44
+ allowDomainLiteral: z.boolean(),
45
+ })
46
+ .strict(),
47
+ z
48
+ .object({
49
+ mode: validateMode,
50
+ deny: z.array(z.string()),
51
+ requireTopLevelDomain: z.boolean(),
52
+ allowDomainLiteral: z.boolean(),
53
+ })
54
+ .strict(),
55
+ ])
56
+ .optional();
57
+ const validateSensitiveInfoOptions = z
58
+ .union([
59
+ z
60
+ .object({
61
+ mode: validateMode,
62
+ allow: z.array(z.string()),
63
+ contextWindowSize: z.number(),
64
+ })
65
+ .strict(),
66
+ z
67
+ .object({
68
+ mode: validateMode,
69
+ deny: z.array(z.string()),
70
+ contextWindowSize: z.number(),
71
+ })
72
+ .strict(),
73
+ ])
74
+ .optional();
75
+ const validateFixedWindowOptions = z
76
+ .object({
77
+ mode: validateMode,
78
+ characteristics: validateCharacteristics,
79
+ window: z.union([z.string(), z.number()]),
80
+ max: z.number(),
81
+ })
82
+ .strict()
83
+ .optional();
84
+ const validateSlidingWindowOptions = z
85
+ .object({
86
+ mode: validateMode,
87
+ characteristics: validateCharacteristics,
88
+ interval: z.union([z.string(), z.number()]),
89
+ max: z.number(),
90
+ })
91
+ .strict()
92
+ .optional();
93
+ const validateTokenBucketOptions = z
94
+ .object({
95
+ mode: validateMode,
96
+ characteristics: validateCharacteristics,
97
+ refillRate: z.number(),
98
+ interval: z.union([z.string(), z.number()]),
99
+ capacity: z.number(),
100
+ })
101
+ .strict()
102
+ .optional();
103
+ const validateProtectSignupOptions = z
104
+ .object({
105
+ rateLimit: validateSlidingWindowOptions,
106
+ bots: validateBotOptions,
107
+ email: validateEmailOptions,
108
+ })
109
+ .strict()
110
+ .optional();
111
+ function validateAndSerialize(schema, value) {
112
+ const v = schema.parse(value);
113
+ return v ? JSON.stringify(v) : "";
114
+ }
115
+ function integrationRuleToClientRule(rule) {
116
+ switch (rule.type) {
117
+ case "shield": {
118
+ const serializedOpts = validateAndSerialize(validateShieldOptions, rule.options);
119
+ return {
120
+ importName: `shield`,
121
+ code: `shield(${serializedOpts})`,
122
+ };
123
+ }
124
+ case "bot": {
125
+ const serializedOpts = validateAndSerialize(validateBotOptions, rule.options);
126
+ return {
127
+ importName: `detectBot`,
128
+ code: `detectBot(${serializedOpts})`,
129
+ };
130
+ }
131
+ case "email": {
132
+ const serializedOpts = validateAndSerialize(validateEmailOptions, rule.options);
133
+ return {
134
+ importName: `validateEmail`,
135
+ code: `validateEmail(${serializedOpts})`,
136
+ };
137
+ }
138
+ case "sensitiveInfo": {
139
+ const serializedOpts = validateAndSerialize(validateSensitiveInfoOptions, rule.options);
140
+ return {
141
+ importName: `sensitiveInfo`,
142
+ code: `sensitiveInfo(${serializedOpts})`,
143
+ };
144
+ }
145
+ case "fixedWindow": {
146
+ const serializedOpts = validateAndSerialize(validateFixedWindowOptions, rule.options);
147
+ return {
148
+ importName: `fixedWindow`,
149
+ code: `fixedWindow(${serializedOpts})`,
150
+ };
151
+ }
152
+ case "slidingWindow": {
153
+ const serializedOpts = validateAndSerialize(validateSlidingWindowOptions, rule.options);
154
+ return {
155
+ importName: `slidingWindow`,
156
+ code: `slidingWindow(${serializedOpts})`,
157
+ };
158
+ }
159
+ case "tokenBucket": {
160
+ const serializedOpts = validateAndSerialize(validateTokenBucketOptions, rule.options);
161
+ return {
162
+ importName: `tokenBucket`,
163
+ code: `tokenBucket(${serializedOpts})`,
164
+ };
165
+ }
166
+ case "protectSignup": {
167
+ const serializedOpts = validateAndSerialize(validateProtectSignupOptions, rule.options);
168
+ return {
169
+ importName: `protectSignup`,
170
+ code: `protectSignup(${serializedOpts})`,
171
+ };
172
+ }
173
+ default: {
174
+ throw new Error("Cannot convert rule via integration");
175
+ }
176
+ }
177
+ }
178
+ // Mirror the rule functions in the SDK but produce serializable rules
179
+ function shield(options) {
180
+ return { type: "shield", options };
181
+ }
182
+ function detectBot(options) {
183
+ return { type: "bot", options };
184
+ }
185
+ function validateEmail(options) {
186
+ return { type: "email", options };
187
+ }
188
+ function sensitiveInfo(options) {
189
+ return { type: "sensitiveInfo", options };
190
+ }
191
+ function fixedWindow(options) {
192
+ return { type: "fixedWindow", options };
193
+ }
194
+ function slidingWindow(options) {
195
+ return { type: "slidingWindow", options };
196
+ }
197
+ function tokenBucket(options) {
198
+ return { type: "tokenBucket", options };
199
+ }
200
+ function protectSignup(options) {
201
+ return { type: "protectSignup", options };
202
+ }
203
+ function createRemoteClient({ baseUrl, timeout }) {
204
+ return { baseUrl, timeout };
205
+ }
206
+ function arcjet({ rules, characteristics, client, proxies, } = { rules: [] }) {
207
+ const arcjetImports = new Set();
208
+ const arcjetRules = [];
209
+ for (const rule of rules) {
210
+ const { importName, code } = integrationRuleToClientRule(rule);
211
+ arcjetImports.add(importName);
212
+ arcjetRules.push(code);
213
+ }
214
+ const characteristicsInjection = characteristics
215
+ ? `characteristics: ${validateAndSerialize(validateCharacteristics, characteristics)},`
216
+ : "";
217
+ const proxiesInjection = proxies
218
+ ? `proxies: ${validateAndSerialize(validateProxies, proxies)},`
219
+ : "";
220
+ const clientInjection = client
221
+ ? `client: createRemoteClient(${validateAndSerialize(validateClientOptions, client)}),`
222
+ : "";
223
+ return {
224
+ name: "@arcjet/astro",
225
+ hooks: {
226
+ "astro:config:setup"({ updateConfig, addMiddleware }) {
227
+ updateConfig({
228
+ env: {
229
+ schema: {
230
+ ARCJET_KEY: {
231
+ type: "string",
232
+ context: "server",
233
+ access: "secret",
234
+ startsWith: "ajkey_",
235
+ },
236
+ ARCJET_ENV: {
237
+ type: "enum",
238
+ context: "server",
239
+ access: "public",
240
+ values: ["production", "development"],
241
+ optional: true,
242
+ },
243
+ ARCJET_BASE_URL: {
244
+ type: "string",
245
+ context: "server",
246
+ access: "public",
247
+ startsWith: "https://",
248
+ optional: true,
249
+ },
250
+ ARCJET_LOG_LEVEL: {
251
+ type: "enum",
252
+ context: "server",
253
+ access: "public",
254
+ values: ["debug", "info", "warn", "error"],
255
+ optional: true,
256
+ },
257
+ FLY_APP_NAME: {
258
+ type: "string",
259
+ context: "server",
260
+ access: "public",
261
+ optional: true,
262
+ },
263
+ VERCEL: {
264
+ type: "string",
265
+ context: "server",
266
+ access: "public",
267
+ optional: true,
268
+ },
269
+ },
270
+ },
271
+ vite: {
272
+ plugins: [
273
+ {
274
+ name: "@arcjet/astro",
275
+ resolveId(id) {
276
+ if (id === "arcjet:client") {
277
+ return resolvedVirtualClientId;
278
+ }
279
+ return;
280
+ },
281
+ async load(id) {
282
+ if (id === resolvedVirtualClientId) {
283
+ const implSource = await fs.readFile(new URL("./internal.js", import.meta.url), { encoding: "utf-8" });
284
+ return {
285
+ code: `
286
+ ${implSource}
287
+
288
+ import {
289
+ ${Array.from(arcjetImports).join(",\n")}
290
+ } from "arcjet"
291
+
292
+ // Construct an Arcjet client for the virtual module
293
+ const aj = createArcjetClient({
294
+ key: ARCJET_KEY,
295
+ rules: [
296
+ ${arcjetRules.join(",\n")}
297
+ ],
298
+ ${characteristicsInjection}
299
+ ${proxiesInjection}
300
+ ${clientInjection}
301
+ })
302
+
303
+ export default aj;
304
+ `,
305
+ };
306
+ }
307
+ },
308
+ },
309
+ ],
310
+ },
311
+ });
312
+ addMiddleware({
313
+ entrypoint: new URL("./middleware.js", import.meta.url),
314
+ order: "pre",
315
+ });
316
+ },
317
+ "astro:config:done": async ({ injectTypes }) => {
318
+ const implTypes = await fs.readFile(new URL("./internal.d.ts", import.meta.url), { encoding: "utf-8" });
319
+ injectTypes({
320
+ content: `
321
+ declare module "arcjet:client" {
322
+ ${implTypes}
323
+
324
+ import {
325
+ ${Array.from(arcjetImports).join(",\n")}
326
+ } from "arcjet"
327
+
328
+ const client = createArcjetClient({
329
+ rules: [
330
+ ${arcjetRules.join(",\n")}
331
+ ],
332
+ ${characteristicsInjection}
333
+ ${proxiesInjection}
334
+ ${clientInjection}
335
+ })
336
+ export default client
337
+ }`,
338
+ filename: "client.d.ts",
339
+ });
340
+ },
341
+ },
342
+ };
343
+ }
344
+
345
+ export { createRemoteClient, arcjet as default, detectBot, fixedWindow, protectSignup, sensitiveInfo, shield, slidingWindow, tokenBucket, validateEmail };
package/internal.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { ArcjetDecision, ArcjetOptions as CoreOptions, Primitive, Product, ExtraProps, CharacteristicProps } 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 type RemoteClientOptions = {
14
+ baseUrl?: string;
15
+ timeout?: number;
16
+ };
17
+ export declare function createRemoteClient(options?: RemoteClientOptions): import("@arcjet/protocol/client.js").Client;
18
+ /**
19
+ * The options used to configure an {@link ArcjetAstro} client.
20
+ */
21
+ export type ArcjetOptions<Rules extends [...Array<Primitive | Product>], Characteristics extends readonly string[]> = Simplify<CoreOptions<Rules, Characteristics> & {
22
+ /**
23
+ * One or more IP Address of trusted proxies in front of the application.
24
+ * These addresses will be excluded when Arcjet detects a public IP address.
25
+ */
26
+ proxies?: Array<string>;
27
+ }>;
28
+ /**
29
+ * The ArcjetAstro client provides a public `protect()` method to
30
+ * make a decision about how an Astro request should be handled.
31
+ */
32
+ export interface ArcjetAstro<Props extends PlainObject> {
33
+ /**
34
+ * Runs a request through the configured protections. The request is
35
+ * analyzed and then a decision made on whether to allow, deny, or challenge
36
+ * the request.
37
+ *
38
+ * @param request - A `Request` provided to the fetch handler.
39
+ * @param props - Additonal properties required for running rules against a request.
40
+ * @returns An {@link ArcjetDecision} indicating Arcjet's decision about the request.
41
+ */
42
+ protect(request: Request, ...props: Props extends WithoutCustomProps ? [] : [Props]): Promise<ArcjetDecision>;
43
+ /**
44
+ * Augments the client with another rule. Useful for varying rules based on
45
+ * criteria in your handler—e.g. different rate limit for logged in users.
46
+ *
47
+ * @param rule The rule to add to this execution.
48
+ * @returns An augmented {@link ArcjetAstro} client.
49
+ */
50
+ withRule<Rule extends Primitive | Product>(rule: Rule): ArcjetAstro<Simplify<Props & ExtraProps<Rule>>>;
51
+ }
52
+ /**
53
+ * Create a new {@link ArcjetAstro} client. Always build your initial client
54
+ * outside of a request handler so it persists across requests. If you need to
55
+ * augment a client inside a handler, call the `withRule()` function on the base
56
+ * client.
57
+ *
58
+ * @param options - Arcjet configuration options to apply to all requests.
59
+ */
60
+ export declare function createArcjetClient<const Rules extends (Primitive | Product)[], const Characteristics extends readonly string[]>(options: ArcjetOptions<Rules, Characteristics>): ArcjetAstro<Simplify<ExtraProps<Rules> & CharacteristicProps<Characteristics>>>;
package/internal.js ADDED
@@ -0,0 +1,140 @@
1
+ import core__default from 'arcjet';
2
+ export * from 'arcjet';
3
+ import findIP from '@arcjet/ip';
4
+ import ArcjetHeaders from '@arcjet/headers';
5
+ import { baseUrl, isDevelopment, logLevel, 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 { VERCEL, FLY_APP_NAME, ARCJET_LOG_LEVEL, ARCJET_KEY, ARCJET_ENV, ARCJET_BASE_URL } from 'astro:env/server';
10
+
11
+ // We use a middleware to store the IP address on a `Request` with this symbol.
12
+ // This is due to Astro inconsistently using `Symbol.for("astro.clientAddress")`
13
+ // to store the client address and not exporting it from their module.
14
+ const ipSymbol = Symbol.for("arcjet.ip");
15
+ const env = {
16
+ ARCJET_BASE_URL,
17
+ ARCJET_ENV,
18
+ ARCJET_KEY,
19
+ ARCJET_LOG_LEVEL,
20
+ FLY_APP_NAME,
21
+ VERCEL,
22
+ // `MODE` is only set on `import.meta.env`.
23
+ MODE: import.meta.env.MODE,
24
+ };
25
+ // TODO: Deduplicate with other packages
26
+ function errorMessage(err) {
27
+ if (err) {
28
+ if (typeof err === "string") {
29
+ return err;
30
+ }
31
+ if (typeof err === "object" &&
32
+ "message" in err &&
33
+ typeof err.message === "string") {
34
+ return err.message;
35
+ }
36
+ }
37
+ return "Unknown problem";
38
+ }
39
+ function createRemoteClient(options) {
40
+ // The base URL for the Arcjet API. Will default to the standard production
41
+ // API unless environment variable `ARCJET_BASE_URL` is set.
42
+ const url = options?.baseUrl ?? baseUrl(env);
43
+ // The timeout for the Arcjet API in milliseconds. This is set to a low value
44
+ // in production so calls fail open.
45
+ const timeout = options?.timeout ?? (isDevelopment(env) ? 1000 : 500);
46
+ // Transport is the HTTP client that the client uses to make requests.
47
+ const transport = createTransport(url);
48
+ const sdkStack = "ASTRO";
49
+ const sdkVersion = "1.0.0-beta.2";
50
+ return createClient({
51
+ transport,
52
+ baseUrl: url,
53
+ timeout,
54
+ sdkStack,
55
+ sdkVersion,
56
+ });
57
+ }
58
+ /**
59
+ * Create a new {@link ArcjetAstro} client. Always build your initial client
60
+ * outside of a request handler so it persists across requests. If you need to
61
+ * augment a client inside a handler, call the `withRule()` function on the base
62
+ * client.
63
+ *
64
+ * @param options - Arcjet configuration options to apply to all requests.
65
+ */
66
+ function createArcjetClient(options) {
67
+ const client = options.client ?? createRemoteClient();
68
+ const log = options.log
69
+ ? options.log
70
+ : new Logger({
71
+ level: logLevel(env),
72
+ });
73
+ function toArcjetRequest(request, props) {
74
+ const clientAddress = Reflect.get(request, ipSymbol);
75
+ if (!clientAddress) {
76
+ throw new Error("`protect()` cannot be used in prerendered pages");
77
+ }
78
+ const cookies = request.headers.get("cookie") ?? undefined;
79
+ // We construct an ArcjetHeaders to normalize over Headers
80
+ const headers = new ArcjetHeaders(request.headers);
81
+ const url = new URL(request.url);
82
+ let ip = findIP({
83
+ ip: clientAddress,
84
+ headers,
85
+ }, { platform: platform(env), proxies: options.proxies });
86
+ if (ip === "") {
87
+ // If the `ip` is empty but we're in development mode, we default the IP
88
+ // so the request doesn't fail.
89
+ if (isDevelopment(env)) {
90
+ log.warn("Using 127.0.0.1 as IP address in development mode");
91
+ ip = "127.0.0.1";
92
+ }
93
+ else {
94
+ log.warn(`Client IP address is missing. If this is a dev environment set the ARCJET_ENV env var to "development"`);
95
+ }
96
+ }
97
+ return {
98
+ ...props,
99
+ ip,
100
+ method: request.method,
101
+ protocol: url.protocol,
102
+ host: url.host,
103
+ path: url.pathname,
104
+ headers,
105
+ cookies,
106
+ query: url.search,
107
+ };
108
+ }
109
+ function withClient(aj) {
110
+ return Object.freeze({
111
+ withRule(rule) {
112
+ const client = aj.withRule(rule);
113
+ return withClient(client);
114
+ },
115
+ async protect(request, ...[props]) {
116
+ // TODO(#220): The generic manipulations get really mad here, so we cast
117
+ // Further investigation makes it seem like it has something to do with
118
+ // the definition of `props` in the signature but it's hard to track down
119
+ const req = toArcjetRequest(request, props ?? {});
120
+ const getBody = async () => {
121
+ try {
122
+ const clonedRequest = request.clone();
123
+ // Awaited to throw if it rejects and we'll just return undefined
124
+ const body = await clonedRequest.text();
125
+ return body;
126
+ }
127
+ catch (e) {
128
+ log.error("failed to get request body: %s", errorMessage(e));
129
+ return;
130
+ }
131
+ };
132
+ return aj.protect({ getBody }, req);
133
+ },
134
+ });
135
+ }
136
+ const aj = core__default({ ...options, client, log });
137
+ return withClient(aj);
138
+ }
139
+
140
+ export { createArcjetClient, createRemoteClient };
@@ -0,0 +1 @@
1
+ export declare const onRequest: import("astro").MiddlewareHandler;
package/middleware.js ADDED
@@ -0,0 +1,14 @@
1
+ import { defineMiddleware } from 'astro/middleware';
2
+
3
+ // We use a middleware to store the IP address on a `Request` with this symbol.
4
+ // This is due to Astro inconsistently using `Symbol.for("astro.clientAddress")`
5
+ // to store the client address and not exporting it from their module.
6
+ const ipSymbol = Symbol.for("arcjet.ip");
7
+ const onRequest = defineMiddleware((ctx, next) => {
8
+ if (!ctx.isPrerendered) {
9
+ Reflect.set(ctx.request, ipSymbol, ctx.clientAddress);
10
+ }
11
+ return next();
12
+ });
13
+
14
+ export { onRequest };
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@arcjet/astro",
3
+ "version": "1.0.0-beta.2",
4
+ "description": "Arcjet SDK integration for Astro",
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-astro"
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
+ "type": "module",
23
+ "main": "./index.js",
24
+ "types": "./index.d.ts",
25
+ "files": [
26
+ "LICENSE",
27
+ "README.md",
28
+ "*.js",
29
+ "*.d.ts",
30
+ "!*.config.js"
31
+ ],
32
+ "scripts": {
33
+ "prepublishOnly": "npm run build",
34
+ "build": "rollup --config rollup.config.js",
35
+ "lint": "eslint .",
36
+ "pretest": "npm run build",
37
+ "test": "node --test --experimental-test-coverage"
38
+ },
39
+ "dependencies": {
40
+ "@arcjet/env": "1.0.0-beta.2",
41
+ "@arcjet/headers": "1.0.0-beta.2",
42
+ "@arcjet/ip": "1.0.0-beta.2",
43
+ "@arcjet/logger": "1.0.0-beta.2",
44
+ "@arcjet/protocol": "1.0.0-beta.2",
45
+ "@arcjet/transport": "1.0.0-beta.2",
46
+ "arcjet": "1.0.0-beta.2"
47
+ },
48
+ "peerDependencies": {
49
+ "astro": "^5"
50
+ },
51
+ "devDependencies": {
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",
55
+ "@rollup/wasm-node": "4.34.2",
56
+ "astro": "5.2.5",
57
+ "expect": "29.7.0",
58
+ "typescript": "5.7.3"
59
+ },
60
+ "publishConfig": {
61
+ "access": "public",
62
+ "tag": "latest"
63
+ },
64
+ "keywords": [
65
+ "astro-integration"
66
+ ]
67
+ }