@arcjet/bun 1.0.0-alpha.31 → 1.0.0-alpha.32

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 (3) hide show
  1. package/index.js +1 -1
  2. package/package.json +14 -15
  3. package/index.ts +0 -296
package/index.js CHANGED
@@ -33,7 +33,7 @@ function createRemoteClient(options) {
33
33
  // Transport is the HTTP client that the client uses to make requests.
34
34
  const transport = createTransport(url);
35
35
  const sdkStack = "BUN";
36
- const sdkVersion = "1.0.0-alpha.31";
36
+ const sdkVersion = "1.0.0-alpha.32";
37
37
  return createClient({
38
38
  transport,
39
39
  baseUrl: url,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcjet/bun",
3
- "version": "1.0.0-alpha.31",
3
+ "version": "1.0.0-alpha.32",
4
4
  "description": "Arcjet SDK for Bun.sh",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://arcjet.com",
@@ -27,7 +27,6 @@
27
27
  "README.md",
28
28
  "*.js",
29
29
  "*.d.ts",
30
- "*.ts",
31
30
  "!*.config.js"
32
31
  ],
33
32
  "scripts": {
@@ -38,24 +37,24 @@
38
37
  "test": "NODE_OPTIONS=--experimental-vm-modules jest --passWithNoTests"
39
38
  },
40
39
  "dependencies": {
41
- "@arcjet/env": "1.0.0-alpha.31",
42
- "@arcjet/headers": "1.0.0-alpha.31",
43
- "@arcjet/ip": "1.0.0-alpha.31",
44
- "@arcjet/logger": "1.0.0-alpha.31",
45
- "@arcjet/protocol": "1.0.0-alpha.31",
46
- "@arcjet/transport": "1.0.0-alpha.31",
47
- "arcjet": "1.0.0-alpha.31"
40
+ "@arcjet/env": "1.0.0-alpha.32",
41
+ "@arcjet/headers": "1.0.0-alpha.32",
42
+ "@arcjet/ip": "1.0.0-alpha.32",
43
+ "@arcjet/logger": "1.0.0-alpha.32",
44
+ "@arcjet/protocol": "1.0.0-alpha.32",
45
+ "@arcjet/transport": "1.0.0-alpha.32",
46
+ "arcjet": "1.0.0-alpha.32"
48
47
  },
49
48
  "devDependencies": {
50
- "@arcjet/eslint-config": "1.0.0-alpha.31",
51
- "@arcjet/rollup-config": "1.0.0-alpha.31",
52
- "@arcjet/tsconfig": "1.0.0-alpha.31",
49
+ "@arcjet/eslint-config": "1.0.0-alpha.32",
50
+ "@arcjet/rollup-config": "1.0.0-alpha.32",
51
+ "@arcjet/tsconfig": "1.0.0-alpha.32",
53
52
  "@jest/globals": "29.7.0",
54
53
  "@types/node": "20.12.12",
55
- "@rollup/wasm-node": "4.27.3",
56
- "bun-types": "1.1.36",
54
+ "@rollup/wasm-node": "4.27.4",
55
+ "bun-types": "1.1.37",
57
56
  "jest": "29.7.0",
58
- "typescript": "5.6.3"
57
+ "typescript": "5.7.2"
59
58
  },
60
59
  "publishConfig": {
61
60
  "access": "public",
package/index.ts DELETED
@@ -1,296 +0,0 @@
1
- /// <reference types="bun-types/bun.d.ts" />
2
- import core from "arcjet";
3
- import type {
4
- ArcjetDecision,
5
- ArcjetOptions,
6
- Primitive,
7
- Product,
8
- ArcjetRequest,
9
- ExtraProps,
10
- Arcjet,
11
- CharacteristicProps,
12
- } from "arcjet";
13
- import findIP from "@arcjet/ip";
14
- import ArcjetHeaders from "@arcjet/headers";
15
- import type { Server } from "bun";
16
- import { env } from "bun";
17
- import { baseUrl, isDevelopment, logLevel, platform } from "@arcjet/env";
18
- import { Logger } from "@arcjet/logger";
19
- import { createClient } from "@arcjet/protocol/client.js";
20
- import { createTransport } from "@arcjet/transport";
21
-
22
- // Re-export all named exports from the generic SDK
23
- export * from "arcjet";
24
-
25
- // TODO: Deduplicate with other packages
26
- function errorMessage(err: unknown): string {
27
- if (err) {
28
- if (typeof err === "string") {
29
- return err;
30
- }
31
-
32
- if (
33
- typeof err === "object" &&
34
- "message" in err &&
35
- typeof err.message === "string"
36
- ) {
37
- return err.message;
38
- }
39
- }
40
-
41
- return "Unknown problem";
42
- }
43
-
44
- // Type helpers from https://github.com/sindresorhus/type-fest but adjusted for
45
- // our use.
46
- //
47
- // Simplify:
48
- // https://github.com/sindresorhus/type-fest/blob/964466c9d59c711da57a5297ad954c13132a0001/source/simplify.d.ts
49
- // EmptyObject:
50
- // https://github.com/sindresorhus/type-fest/blob/b9723d4785f01f8d2487c09ee5871a1f615781aa/source/empty-object.d.ts
51
- //
52
- // Licensed: MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com>
53
- // (https://sindresorhus.com)
54
- //
55
- // Permission is hereby granted, free of charge, to any person obtaining a copy
56
- // of this software and associated documentation files (the "Software"), to deal
57
- // in the Software without restriction, including without limitation the rights
58
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
59
- // copies of the Software, and to permit persons to whom the Software is
60
- // furnished to do so, subject to the following conditions: The above copyright
61
- // notice and this permission notice shall be included in all copies or
62
- // substantial portions of the Software.
63
- //
64
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
65
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
66
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
67
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
68
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
69
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
70
- // SOFTWARE.
71
- type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};
72
- declare const emptyObjectSymbol: unique symbol;
73
- type WithoutCustomProps = {
74
- [emptyObjectSymbol]?: never;
75
- };
76
-
77
- type PlainObject = {
78
- [key: string]: unknown;
79
- };
80
-
81
- export type RemoteClientOptions = {
82
- baseUrl?: string;
83
- timeout?: number;
84
- };
85
-
86
- export function createRemoteClient(options?: RemoteClientOptions) {
87
- // The base URL for the Arcjet API. Will default to the standard production
88
- // API unless environment variable `ARCJET_BASE_URL` is set.
89
- const url = options?.baseUrl ?? baseUrl(env);
90
-
91
- // The timeout for the Arcjet API in milliseconds. This is set to a low value
92
- // in production so calls fail open.
93
- const timeout = options?.timeout ?? (isDevelopment(env) ? 1000 : 500);
94
-
95
- // Transport is the HTTP client that the client uses to make requests.
96
- const transport = createTransport(url);
97
-
98
- const sdkStack = "BUN";
99
- const sdkVersion = "__ARCJET_SDK_VERSION__";
100
-
101
- return createClient({
102
- transport,
103
- baseUrl: url,
104
- timeout,
105
- sdkStack,
106
- sdkVersion,
107
- });
108
- }
109
-
110
- /**
111
- * The ArcjetBun client provides a public `protect()` method to
112
- * make a decision about how a Bun.sh request should be handled.
113
- */
114
- export interface ArcjetBun<Props extends PlainObject> {
115
- /**
116
- * Runs a request through the configured protections. The request is
117
- * analyzed and then a decision made on whether to allow, deny, or challenge
118
- * the request.
119
- *
120
- * @param request - A `Request` provided to the fetch handler.
121
- * @param props - Additonal properties required for running rules against a request.
122
- * @returns An {@link ArcjetDecision} indicating Arcjet's decision about the request.
123
- */
124
- protect(
125
- request: Request,
126
- // We use this neat trick from https://stackoverflow.com/a/52318137 to make a single spread parameter
127
- // that is required if the ExtraProps aren't strictly an empty object
128
- ...props: Props extends WithoutCustomProps ? [] : [Props]
129
- ): Promise<ArcjetDecision>;
130
-
131
- /**
132
- * Augments the client with another rule. Useful for varying rules based on
133
- * criteria in your handler—e.g. different rate limit for logged in users.
134
- *
135
- * @param rule The rule to add to this execution.
136
- * @returns An augmented {@link ArcjetBun} client.
137
- */
138
- withRule<Rule extends Primitive | Product>(
139
- rule: Rule,
140
- ): ArcjetBun<Simplify<Props & ExtraProps<Rule>>>;
141
-
142
- /**
143
- * Wraps the Bun.sh `fetch` handler to provide additional Request details
144
- * when calling the SDK's `protect()` function.
145
- *
146
- * @param fetch: The user provided `fetch` handler
147
- */
148
- handler(
149
- fetch: (
150
- this: Server,
151
- request: Request,
152
- server: Server,
153
- ) => Response | Promise<Response>,
154
- ): (
155
- this: Server,
156
- request: Request,
157
- server: Server,
158
- ) => Response | Promise<Response>;
159
- }
160
-
161
- /**
162
- * Create a new {@link ArcjetBun} client. Always build your initial client
163
- * outside of a request handler so it persists across requests. If you need to
164
- * augment a client inside a handler, call the `withRule()` function on the base
165
- * client.
166
- *
167
- * @param options - Arcjet configuration options to apply to all requests.
168
- */
169
- export default function arcjet<
170
- const Rules extends (Primitive | Product)[],
171
- const Characteristics extends readonly string[],
172
- >(
173
- options: ArcjetOptions<Rules, Characteristics>,
174
- ): ArcjetBun<
175
- Simplify<ExtraProps<Rules> & CharacteristicProps<Characteristics>>
176
- > {
177
- const client = options.client ?? createRemoteClient();
178
-
179
- // Assuming the `handler()` function was used around Bun's fetch handler this
180
- // WeakMap should be populated with IP addresses inspected via
181
- // `server.requestIP()`
182
- const ipCache = new WeakMap<Request, string>();
183
-
184
- const log = options.log
185
- ? options.log
186
- : new Logger({
187
- level: logLevel(env),
188
- });
189
-
190
- function toArcjetRequest<Props extends PlainObject>(
191
- request: Request,
192
- props: Props,
193
- ): ArcjetRequest<Props> {
194
- const cookies = request.headers.get("cookie") ?? undefined;
195
-
196
- // We construct an ArcjetHeaders to normalize over Headers
197
- const headers = new ArcjetHeaders(request.headers);
198
-
199
- const url = new URL(request.url);
200
- let ip = findIP(
201
- {
202
- // This attempts to lookup the IP in the `ipCache`. This is primarily a
203
- // workaround to the API design in Bun that requires access to the
204
- // `Server` to lookup an IP.
205
- ip: ipCache.get(request),
206
- headers,
207
- },
208
- { platform: platform(env) },
209
- );
210
- if (ip === "") {
211
- // If the `ip` is empty but we're in development mode, we default the IP
212
- // so the request doesn't fail.
213
- if (isDevelopment(env)) {
214
- log.warn("Using 127.0.0.1 as IP address in development mode");
215
- ip = "127.0.0.1";
216
- } else {
217
- log.warn(
218
- `Client IP address is missing. If this is a dev environment set the ARCJET_ENV env var to "development"`,
219
- );
220
- }
221
- }
222
-
223
- return {
224
- ...props,
225
- ip,
226
- method: request.method,
227
- protocol: url.protocol,
228
- host: url.host,
229
- path: url.pathname,
230
- headers,
231
- cookies,
232
- query: url.search,
233
- };
234
- }
235
-
236
- function withClient<const Rules extends (Primitive | Product)[]>(
237
- aj: Arcjet<ExtraProps<Rules>>,
238
- ): ArcjetBun<ExtraProps<Rules>> {
239
- return Object.freeze({
240
- withRule(rule: Primitive | Product) {
241
- const client = aj.withRule(rule);
242
- return withClient(client);
243
- },
244
- async protect(
245
- request: Request,
246
- ...[props]: ExtraProps<Rules> extends WithoutCustomProps
247
- ? []
248
- : [ExtraProps<Rules>]
249
- ): Promise<ArcjetDecision> {
250
- // TODO(#220): The generic manipulations get really mad here, so we cast
251
- // Further investigation makes it seem like it has something to do with
252
- // the definition of `props` in the signature but it's hard to track down
253
- const req = toArcjetRequest(request, props ?? {}) as ArcjetRequest<
254
- ExtraProps<Rules>
255
- >;
256
-
257
- const getBody = async () => {
258
- try {
259
- const clonedRequest = request.clone();
260
- // Awaited to throw if it rejects and we'll just return undefined
261
- const body = await clonedRequest.text();
262
- return body;
263
- } catch (e) {
264
- log.error("failed to get request body: %s", errorMessage(e));
265
- return;
266
- }
267
- };
268
-
269
- return aj.protect({ getBody }, req);
270
- },
271
- handler(
272
- fetch: (
273
- this: Server,
274
- request: Request,
275
- server: Server,
276
- ) => Response | Promise<Response>,
277
- ) {
278
- return async function (
279
- request: Request,
280
- server: Server,
281
- ): Promise<Response> {
282
- const socketAddress = server.requestIP(request);
283
- if (socketAddress) {
284
- ipCache.set(request, socketAddress.address);
285
- }
286
-
287
- return fetch.call(server, request, server);
288
- };
289
- },
290
- });
291
- }
292
-
293
- const aj = core({ ...options, client, log });
294
-
295
- return withClient(aj);
296
- }