# @arcjet/bun 中文文档

规范地址：https://npmcn.com/package/%40arcjet/bun/

版本：1\.15\.0
npm 元数据更新时间：2026-10-28T18:47:28.546Z
中文译文更新时间：2026-11-06T15:01:23.244Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40arcjet/bun
原文对照：https://npmcn.com/package/%40arcjet/bun/?lang=original
项目主页：https://arcjet.com/
源码仓库：https://github.com/arcjet/arcjet-js

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：41.2 kB，5 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：8 个
- 首次发布：2024-05-20T15:22:57.103Z
- 最新版本发布：2026-10-28T18:47:27.818Z
- 近 30 天下载量：4430（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：66（近 12 个月 30 个）

## 中文简介

Bun的Arcjet 运行时安全 SDK——机器人保护、限速、即时注射检测、PII阻塞和WAF

## 安装

```sh
npm install @arcjet/bun
```

也可以使用：`pnpm add @arcjet/bun`、`yarn add @arcjet/bun`、`bun add @arcjet/bun`

## README

[![Arcjet Logo](https://arcjet.com/logo/arcjet-light-lockup-voyage-horizontal.svg)](https://arcjet.com/)

# `@arcjet/bun`

[![npm badge](https://img.shields.io/npm/v/%40arcjet%2Fbun?style=flat-square&label=%E2%9C%A6Aj&labelColor=ECE6F0&color=ECE6F0)](https://www.npmjs.com/package/@arcjet/bun)

[弧喷](https://arcjet.com/) 是您AI代码中的运行时安全平台。 检测出快速注射,授权代理工具呼叫,编辑敏感数据,并阻断bots和滥用. 在行动发生前,您在应用程序内拨打实时安全构件.

这是 [弧喷](https://arcjet.com/) SDK 为 [阿宝](https://bun.sh/) **请求保护** —— 说 使用它来保护HTTP路由处理器和API端点. 如果你需要保护 AI代理工具呼叫, MCP 服务器处理器, 或背景任务( 任何没有 hTTP 请求,参见 [`@arcjet/guard`](https://github.com/arcjet/arcjet-js/tree/main/arcjet-guard)。 。 。 .

## 为什么是Arcjet?

您的应用程序的AI功能和代理采取真实的行动,呼叫工具,读取数据,打击API. Arcjet在代码内运行 让你实时执行每个动作的安全 然后审计发生了什么

## 开始

### 快速设置 AI 代理

1.  登录 CLI :
    
    ```sh
    npx @arcjet/cli auth login
    ```
    
2.  安装版本代理技能, 这样您的编码代理匹配 SDK :
    
    ```sh
    npx @tanstack/intent@latest install
    ```
    
3.  告诉你的探员要保护什么 剩下的就交给他.

### 手动设置

1.  **登录** 使用 CLI(或 [`app.arcjet.com`](https://app.arcjet.com/?utm_campaign=arcjet-js):
    
    ```sh
    npx @arcjet/cli auth login
    ```
    
2.  `bun add @arcjet/bun`
3.  设定 `ARCJET_KEY=ajkey_yourkey` 在你的环境中
4.  将 Arcjet 添加到您的服务器中 [快速开始](https://npmcn.com/package/%40arcjet/bun/#readme-quick-start) 下级

[npm 软件包](https://www.npmjs.com/package/@arcjet/bun) | [GitHub 来源](https://github.com/arcjet/arcjet-js/tree/main/arcjet-bun) | [完整文档](https://docs.arcjet.com/reference/bun) | [GitHub 上的其他 SDK 软件](https://github.com/arcjet)

## 特征

以下所有特征均可使用 `@arcjet/bun` 请求保护. 警卫保护(工具呼叫、MCP服务器、队列)见 [`@arcjet/guard`](https://github.com/arcjet/arcjet-js/tree/main/arcjet-guard)。 。 。 .

| 特性 | `@arcjet/bun` | `@arcjet/guard` |
| --- | :-: | :-: |
| 限制费率 | ✅ | ✅ |
| 快速注射检测 | ✅ | ✅ |
| 敏感信息检测 | ✅ | ✅ |
| 瓶装保护 | ✅ | —— 说 |
| 盾牌 WAF | ✅ | —— 说 |
| 电子邮件验证 | ✅ | —— 说 |
| 注册表保护 | ✅ | —— 说 |
| 请求过滤器 | ✅ | —— 说 |
| IP 分析 | ✅ | —— 说 |
| 自定义规则 | —— 说 | ✅ |

-   🔒 [快速注射检测](https://npmcn.com/package/%40arcjet/bun/#readme-prompt-injection-detection) - 探测和阻断 在到达你的LLM前立即注射.
-   🤖 [瓶装保护](https://npmcn.com/package/%40arcjet/bun/#readme-bot-protection) · 停止刮刮机、证明材料和 AI爬行者滥用你的终点.
-   🛑 [限制费率](https://npmcn.com/package/%40arcjet/bun/#readme-rate-limiting) - 标志桶、固定窗口和滑动 窗口算法; 每个用户的模型 AI 符号预算.
-   🕵️ [敏感信息检测](https://npmcn.com/package/%40arcjet/bun/#readme-sensitive-information-detection) - 块 PII,信用卡和定制模式 从进入你的AI管道.
-   🛡️ [盾牌 WAF](https://npmcn.com/package/%40arcjet/bun/#readme-shield-waf) • 防止SQL注射、XSS和其他 常见的网络攻击.
-   📧 [电子邮件验证](https://npmcn.com/package/%40arcjet/bun/#readme-email-validation) 一次性、无效和 注册时无法提供地址 .
-   📝 [注册表保护](https://docs.arcjet.com/signup-protection) 结合机器人保护, 电子邮件验证, 以及限制您注册表格的速率 .
-   🎯 [请求过滤器](https://npmcn.com/package/%40arcjet/bun/#readme-request-filters) ——IP,路径上以表达为主的规则, 标题和自定义字段.
-   🌐 [IP 分析](https://npmcn.com/package/%40arcjet/bun/#readme-ip-analysis) 地理定位、ASN、VPN、代理、Tor和托管 检测包括每个请求.

## 快开始

这个例子保护一个带有bot检测器的 Bun HTTP 服务器, Shield WAF, 以及 符号桶率限制 .

```ts
// index.ts
import arcjet, { detectBot, shield, tokenBucket } from "@arcjet/bun";
import { isSpoofedBot } from "@arcjet/inspect";
import { env } from "bun";

const aj = arcjet({
  key: env.ARCJET_KEY!, // Get your key with: npx @arcjet/cli sites get-key
  rules: [
    // Shield protects your app from common attacks e.g. SQL injection
    shield({ mode: "LIVE" }),
    // Create a bot detection rule
    detectBot({
      mode: "LIVE", // Blocks requests. Use "DRY_RUN" to log only
      // Block all bots except the following
      allow: [
        "CATEGORY:SEARCH_ENGINE", // Google, Bing, etc
        // Uncomment to allow these other common bot categories
        // See the full list at https://arcjet.com/bot-list
        //"CATEGORY:MONITOR", // Uptime monitoring services
        //"CATEGORY:PREVIEW", // Link previews e.g. Slack, Discord
      ],
    }),
    // Token bucket rate limit. Other algorithms are supported.
    tokenBucket({
      mode: "LIVE",
      // Tracked by IP address by default, but this can be customized
      // See https://docs.arcjet.com/fingerprints
      refillRate: 5, // Refill 5 tokens per interval
      interval: 10, // Refill every 10 seconds
      capacity: 10, // Bucket capacity of 10 tokens
    }),
  ],
});

export default {
  port: 3000,
  fetch: aj.handler(async (req) => {
    const decision = await aj.protect(req, { requested: 5 }); // Deduct 5 tokens
    console.log("Arcjet decision", decision);

    if (decision.isDenied()) {
      if (decision.reason.isRateLimit()) {
        return new Response("Too many requests", { status: 429 });
      } else if (decision.reason.isBot()) {
        return new Response("No bots allowed", { status: 403 });
      } else {
        return new Response("Forbidden", { status: 403 });
      }
    }

    // Requests from hosting IPs are likely from bots.
    // https://docs.arcjet.com/blueprints/vpn-proxy-detection
    if (decision.ip.isHosting()) {
      return new Response("Forbidden", { status: 403 });
    }

    // Verifies the authenticity of common bots using IP data.
    // Verification isn't always possible, so check the results separately.
    // https://docs.arcjet.com/bot-protection/reference#bot-verification
    if (decision.results.some(isSpoofedBot)) {
      return new Response("Forbidden", { status: 403 });
    }

    return new Response("Hello world");
  }),
};
```

全文见 [Arcjet Bun SDK 文档](https://docs.arcjet.com/reference/bun)。 。 。 .

## 快速注射检测

检测和阻止快速注射攻击——试图推翻你的AI 模型的指示——在他们到达你的模型之前. 传递用户消息 通过 `detectPromptInjectionMessage` 每个 `protect()` 电话.

```ts
import arcjet, { detectPromptInjection } from "@arcjet/bun";
import { env } from "bun";

const aj = arcjet({
  key: env.ARCJET_KEY!,
  rules: [
    detectPromptInjection({
      mode: "LIVE", // Blocks requests. Use "DRY_RUN" to log only
    }),
  ],
});

export default {
  fetch: aj.handler(async (req) => {
    const { message } = await req.json();

    const decision = await aj.protect(req, {
      detectPromptInjectionMessage: message,
    });

    if (decision.isDenied() && decision.reason.isPromptInjection()) {
      return new Response(
        "Prompt injection detected — please rephrase your message",
        { status: 400 },
      );
    }

    // Forward to your AI model...
    return new Response("OK");
  }),
};
```

## 瓶装保护

Arcjet允许您配置一个 bots 列表以允许或拒绝 。 指定 `allow` 意味着所有其他的bots被否定。 一个空的允许列表块全部块 .

可用类别 : `CATEGORY:ACADEMIC`, (中文(简体) ), `CATEGORY:ADVERTISING`, (中文(简体) ), `CATEGORY:AI`, (中文(简体) ), `CATEGORY:AMAZON`, (中文(简体) ), `CATEGORY:APPLE`, (中文(简体) ), `CATEGORY:ARCHIVE`, (中文(简体) ), `CATEGORY:BOTNET`, (中文(简体) ), `CATEGORY:FEEDFETCHER`, (中文(简体) ), `CATEGORY:GOOGLE`, (中文(简体) ), `CATEGORY:META`, (中文(简体) ), `CATEGORY:MICROSOFT`, (中文(简体) ), `CATEGORY:MONITOR`, (中文(简体) ), `CATEGORY:OPTIMIZER`, (中文(简体) ), `CATEGORY:PREVIEW`, (中文(简体) ), `CATEGORY:PROGRAMMATIC`, (中文(简体) ), `CATEGORY:SEARCH_ENGINE`, (中文(简体) ), `CATEGORY:SLACK`, (中文(简体) ), `CATEGORY:SOCIAL`, (中文(简体) ), `CATEGORY:TOOL`, (中文(简体) ), `CATEGORY:UNKNOWN`, (中文(简体) ), `CATEGORY:VERCEL`, (中文(简体) ), `CATEGORY:WEBHOOK`, (中文(简体) ), `CATEGORY:YAHOO`。也可以允许或拒绝 [按名称排列的特定块](https://arcjet.com/bot-list)。 。 。 .

```ts
import arcjet, { detectBot } from "@arcjet/bun";
import { isSpoofedBot } from "@arcjet/inspect";
import { env } from "bun";

const aj = arcjet({
  key: env.ARCJET_KEY!,
  rules: [
    detectBot({
      mode: "LIVE",
      allow: [
        "CATEGORY:SEARCH_ENGINE",
        // See the full list at https://arcjet.com/bot-list
      ],
    }),
  ],
});

export default {
  fetch: aj.handler(async (req) => {
    const decision = await aj.protect(req);

    if (decision.isDenied() && decision.reason.isBot()) {
      return new Response("No bots allowed", { status: 403 });
    }

    // Verifies the authenticity of common bots using IP data.
    if (decision.results.some(isSpoofedBot)) {
      return new Response("Forbidden", { status: 403 });
    }

    return new Response("Hello world");
  }),
};
```

### 瓶类

波茨可以被配置为 [类别](https://docs.arcjet.com/bot-protection/identifying-bots) 和(或) [具体 机器人名称](https://arcjet.com/bot-list)。例如,允许搜索引擎和OpenAI 爬行者,但否认 所有其他bots:

```ts
detectBot({
  mode: "LIVE",
  allow: ["CATEGORY:SEARCH_ENGINE", "OPENAI_CRAWLER_SEARCH"],
});
```

### 已验证 vs spoofed bots

自称是知名爬行者(如:Googlebot)的Bots通过验证 对照已知的 IP 范围检查他们的 IP 地址 。 如果一个机器人无法核实, 被贴上"被骗"的标签 使用 `isSpoofedBot` 从 `@arcjet/inspect` 检查 :

```ts
import { isSpoofedBot } from "@arcjet/inspect";

if (decision.results.some(isSpoofedBot)) {
  return new Response("Forbidden", { status: 403 });
}
```

## 限制费率

Arcjet支持符号桶,固定窗口和滑动窗口算法. Token桶是控制AI符号预算的理想工具——设置 `capacity` 改为 用户可以花费的最大代币, `refillRate` 以还原多少个令牌 百分比 `interval`,并通过 `requested` 内 `protect()`。 。 。 . 这个 `interval` 接受字符串( r)`"1s"`, (中文(简体) ), `"1m"`, (中文(简体) ), `"1h"`, (中文(简体) ), `"1d"`)或秒为 一个数字。 使用 `characteristics` 以跟踪每个用户的限制,而不是每个IP.

```ts
import arcjet, { tokenBucket } from "@arcjet/bun";
import { env } from "bun";

const aj = arcjet({
  key: env.ARCJET_KEY!,
  characteristics: ["userId"], // Track per user
  rules: [
    tokenBucket({
      mode: "LIVE",
      refillRate: 2_000, // Refill 2,000 tokens per hour
      interval: "1h",
      capacity: 5_000, // Maximum 5,000 tokens in the bucket
    }),
  ],
});

const decision = await aj.protect(req, {
  userId: "user-123",
  requested: estimate, // Number of tokens to deduct
});

if (decision.isDenied() && decision.reason.isRateLimit()) {
  return new Response("Rate limit exceeded", { status: 429 });
}
```

## 敏感信息检测

检测和封存请求中的 PII 内容 [`@arcjet/sensitive-info-rampart`](https://www.npmjs.com/package/@arcjet/sensitive-info-rampart), (中文(简体) ), 在本地运行着Rampart命名实体识别模型,所以没有数据 离开你的环境。 通过扫描传送内容 `sensitiveInfoValue` 打开 每个 `protect()` 电话 Rampart侦测到姓名、地址、政府和 财务识别符、电子邮件地址、电话号码、IP地址和卡片 数字。 添加识别器以检测自定义模式 .

```sh
bun add @arcjet/sensitive-info-rampart
```

```ts
import arcjet, { sensitiveInfo } from "@arcjet/bun";
import { rampart } from "@arcjet/sensitive-info-rampart";
import { env } from "bun";

const aj = arcjet({
  key: env.ARCJET_KEY!,
  rules: [
    sensitiveInfo({
      mode: "LIVE", // Blocks requests. Use "DRY_RUN" to log only
      deny: ["CREDIT_CARD_NUMBER", "EMAIL", "PHONE_NUMBER"],
      backend: rampart(),
    }),
  ],
});

const decision = await aj.protect(req, {
  sensitiveInfoValue: userMessage, // The text content to scan
});

if (decision.isDenied() && decision.reason.isSensitiveInfo()) {
  return new Response("Sensitive information detected", { status: 400 });
}
```

## 盾牌 WAF

保护您的应用程序免受常见的网络攻击, 包括 OWASP 排行前10名.

```ts
import arcjet, { shield } from "@arcjet/bun";
import { env } from "bun";

const aj = arcjet({
  key: env.ARCJET_KEY!,
  rules: [
    shield({
      mode: "LIVE", // Blocks requests. Use "DRY_RUN" to log only
    }),
  ],
});
```

## 电子邮件验证

验证和验证电子邮件地址。 拒绝类型 : `DISPOSABLE`, (中文(简体) ), `FREE`, (中文(简体) ), `NO_MX_RECORDS`, (中文(简体) ), `NO_GRAVATAR`, (中文(简体) ), `INVALID`。 。 。 .

```ts
import arcjet, { validateEmail } from "@arcjet/bun";
import { env } from "bun";

const aj = arcjet({
  key: env.ARCJET_KEY!,
  rules: [
    validateEmail({
      mode: "LIVE",
      deny: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"],
    }),
  ],
});

const decision = await aj.protect(req, {
  email: "user@example.com",
});

if (decision.isDenied() && decision.reason.isEmail()) {
  return new Response("Invalid email address", { status: 400 });
}
```

## 请求过滤器

使用基于表达式的规则对请求属性过滤请求(IP, 页: 1.

```ts
import arcjet, { filter } from "@arcjet/bun";
import { env } from "bun";

const aj = arcjet({
  key: env.ARCJET_KEY!,
  rules: [
    filter({
      mode: "LIVE",
      deny: ['ip.src == "1.2.3.4"'],
    }),
  ],
});
```

### 按国家分列的区块

限制进入特定国家——有助于发放许可证、遵守或 区域推广。 这个 `allow` 拒绝所有未列入名单的国家:

```ts
filter({
  mode: "LIVE",
  // Allow only US traffic — all other countries are denied
  allow: ['ip.src.country == "US"'],
});
```

### 屏蔽 VPN 和代理流量

防止匿名交通进入敏感终点——对 预防欺诈、实施地理限制并减少滥用:

```ts
filter({
  mode: "LIVE",
  deny: [
    "ip.src.vpn", // VPN services
    "ip.src.proxy", // Open proxies
    "ip.src.tor", // Tor exit nodes
  ],
});
```

对于更细致的处理,使用 `decision.ip` 呼叫后帮助 `protect()`数字 :

```ts
const decision = await aj.protect(req);

if (decision.ip.isVpn() || decision.ip.isTor()) {
  return new Response("VPN traffic not allowed", { status: 403 });
}
```

见 [请求过滤文件](https://docs.arcjet.com/filters), (中文(简体) ), [IP 地理定位蓝图](https://docs.arcjet.com/blueprints/ip-geolocation),以及 [VPN/Proxy检测蓝图](https://docs.arcjet.com/blueprints/vpn-proxy-detection) 更多细节.

## 知识产权分析

Arcjet用IP元数据丰富了每个请求. 使用这些助手来制作 基于网络信号的政策决定:

```ts
const decision = await aj.protect(req);

if (decision.ip.isHosting()) {
  // Requests from cloud/hosting providers are often automated.
  // https://docs.arcjet.com/blueprints/vpn-proxy-detection
  return new Response("Forbidden", { status: 403 });
}

if (decision.ip.isVpn() || decision.ip.isProxy() || decision.ip.isTor()) {
  // Handle VPN/proxy traffic according to your policy
}

// Access geolocation and network details
console.log(decision.ip.country, decision.ip.city, decision.ip.asn);
```

## 自定义特性

跟踪和限制任何稳定的标识符的请求——用户ID,API密钥,会话, ——而不是仅IP地址.

```ts
const aj = arcjet({
  key: env.ARCJET_KEY!,
  characteristics: ["userId"], // Declare at the SDK level
  rules: [
    tokenBucket({
      mode: "LIVE",
      refillRate: 2_000,
      interval: "1h",
      capacity: 5_000,
    }),
  ],
});

// Pass the characteristic value at request time
const decision = await aj.protect(req, {
  userId: "user-123", // Replace with your actual user ID
  requested: estimate,
});
```

## 最佳做法

见 [Arcjet 最佳做法](https://docs.arcjet.com/best-practices) 详细指导。 密钥 建议:

**创建单一客户端实例** 并重新使用它与 `withRule()` 页:1 特定路线规则。 SDK 缓存决定和配置,因此创建 每一个请求的新实例 有效的废物.

```ts
// lib/arcjet.ts — create once, import everywhere
import arcjet, { shield } from "@arcjet/bun";
import { env } from "bun";

export default arcjet({
  key: env.ARCJET_KEY!,
  rules: [
    shield({ mode: "LIVE" }), // base rules applied to every request
  ],
});
```

```ts
// routes/chat.ts — extend per-route with withRule()
import aj from "./lib/arcjet.js";
import { detectBot, tokenBucket } from "@arcjet/bun";

const routeAj = aj.withRule(detectBot({ mode: "LIVE", allow: [] })).withRule(
  tokenBucket({
    mode: "LIVE",
    refillRate: 2_000,
    interval: "1h",
    capacity: 5_000,
  }),
);

export async function handler(req: Request) {
  const decision = await routeAj.protect(req, { requested: 500 });
  // ...
}
```

**其他建议:**

-   **打电话 `protect()` 每个请求一次** 在需要它的地方处理它.
-   **开始规则 `DRY_RUN` 模式** 在切换到前观察行为 `LIVE`。这使得您可以调取阈值而不影响真实流量.
-   **配置代理** 如果您的应用程序运行在负载平衡器或倒置代理服务器后 因此Arcjet解决了真正的客户端IP:
    
    ```ts
    arcjet({ key: env.ARCJET_KEY!, rules: [], proxies: ["100.100.100.100"] });
    ```
    
-   **明确处理错误 .** `protect()` 永不扔出 — 在错误时返回 a 一个 `ERROR` 结果。 无法通过日志和允许请求打开 :
    
    ```ts
    if (decision.isErrored()) {
      console.error("Arcjet error", decision.reason.message);
      // allow the request to proceed
    }
    ```
    

## 测试

这个单相机是用节点Js测试的 但是这个包的目标Bun. 以 :

```sh
bun test
```

## 许可证

[Apache 许可证,2.0版本](http://www.apache.org/licenses/LICENSE-2.0) © [Arcjet实验室股份有限公司.](https://arcjet.com/)

## 常见问题

### @arcjet/bun 是什么？

Bun的Arcjet 运行时安全 SDK——机器人保护、限速、即时注射检测、PII阻塞和WAF

### 如何安装 @arcjet/bun？

在项目目录运行 npm install @arcjet/bun，或使用 pnpm add / yarn add / bun add。

### @arcjet/bun 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @arcjet/bun 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @arcjet/bun 可以商用吗？

@arcjet/bun 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @arcjet/bun 的下载量有多少？

根据 npm 官方下载统计，@arcjet/bun 在 2026/10/07 – 2026/11/05 这 30 天内被下载 4,430 次，日均约 148 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @arcjet/bun 还在维护吗？

最新版本 1\.15\.0 发布于 2026/10/29（8 天前）；至今共发布 66 个版本，其中过去 12 个月发布了 30 个；首次发布于 2024/05/20。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

