add-guard-protection

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Add Arcjet Guard Protection

添加Arcjet Guard保护

Arcjet Guard provides rate limiting, prompt injection detection, sensitive information blocking, and custom rules for code paths that don't have an HTTP request — AI agent tool calls, MCP tool handlers, background job processors, queue workers, and similar.
Arcjet Guard可为无HTTP请求的代码路径(如AI agent工具调用、MCP工具处理器、后台任务处理器、队列工作器等)提供限流、提示注入检测、敏感信息拦截以及自定义规则功能。

Step 0: Set Up the Arcjet CLI

步骤0:配置Arcjet CLI

The Arcjet CLI is the primary tool for authenticating, managing sites, configuring remote rules, and monitoring traffic. Install it if not already available:
bash
undefined
Arcjet CLI是用于身份验证、站点管理、远程规则配置和流量监控的核心工具。如果尚未安装,请按以下方式安装:
bash
undefined

Via npx (no install required)

通过npx运行(无需安装)

npx @arcjet/cli --help
npx @arcjet/cli --help

Or install globally via npm

或通过npm全局安装

npm install -g @arcjet/cli
npm install -g @arcjet/cli

Or via Homebrew

或通过Homebrew安装

brew install arcjet
undefined
brew install arcjet
undefined

Authenticate

身份验证

bash
arcjet auth login
Opens the browser for authentication. Check status with
arcjet auth status
.
bash
arcjet auth login
此命令会打开浏览器进行身份验证。可通过
arcjet auth status
检查验证状态。

Site & Key Setup

站点与密钥配置

bash
undefined
bash
undefined

List your teams

列出你的团队

arcjet teams list
arcjet teams list

List sites for a team

列出指定团队下的站点

arcjet sites list --team-id <team-id>
arcjet sites list --team-id <team-id>

Create a new site

创建新站点

arcjet sites create --team-id <team-id> --name "My Guard App" --confirm
arcjet sites create --team-id <team-id> --name "My Guard App" --confirm

Get the SDK key for a site

获取指定站点的SDK密钥

arcjet sites get-key --site-id <site-id>

Add the key to your environment file (`.env`, `.env.local`, etc.) as `ARCJET_KEY`.
arcjet sites get-key --site-id <site-id>

将密钥添加到环境文件(`.env`、`.env.local`等)中,命名为`ARCJET_KEY`。

Step 1: Detect the Language and Install

步骤1:检测开发语言并安装依赖

Check the project for language indicators:
  • package.json
    → JavaScript/TypeScript →
    npm install @arcjet/guard
    (requires
    @arcjet/guard
    >= 1.4.0)
  • requirements.txt
    /
    pyproject.toml
    → Python →
    pip install arcjet
    (requires
    arcjet
    >= 0.7.0; Guard is included)
  • go.mod
    ,
    Cargo.toml
    ,
    pom.xml
    , or other languages → Guard is not available. Tell the user that Arcjet Guard currently only supports JavaScript/TypeScript and Python. Do not create a hand-rolled imitation or hallucinate a package that doesn't exist. Suggest they reach out to Arcjet with their use case.
检查项目中的语言标识文件:
  • package.json
    → JavaScript/TypeScript → 执行
    npm install @arcjet/guard
    (要求
    @arcjet/guard
    版本 ≥ 1.4.0)
  • requirements.txt
    /
    pyproject.toml
    → Python → 执行
    pip install arcjet
    (要求
    arcjet
    版本 ≥ 0.7.0;Guard已包含在内)
  • go.mod
    Cargo.toml
    pom.xml
    或其他语言 → 暂不支持Guard。告知用户Arcjet Guard目前仅支持JavaScript/TypeScript和Python,请勿自行编写模拟代码或虚构不存在的包,建议用户联系Arcjet反馈其使用场景。

Step 2: Read the Language Reference

步骤2:查阅语言参考文档

You must read the reference file for the detected language before writing any code. The references contain the exact imports, constructor signatures, rule configuration syntax, and guard() call patterns for that language.
  • JavaScript/TypeScript: references/javascript.md
  • Python: references/python.md
Do not guess at the API. The reference files are the source of truth for all code patterns.
在编写任何代码前,必须先查阅对应语言的参考文件。参考文件包含该语言的准确导入语句、构造函数签名、规则配置语法以及
guard()
调用模式。
  • JavaScript/TypeScript:references/javascript.md
  • Python:references/python.md
请勿猜测API用法,参考文件是所有代码模式的唯一可信来源。

Step 3: Create the Guard Client (Once, at Module Scope)

步骤3:创建Guard客户端(仅需在模块作用域创建一次)

The client holds a persistent connection. Create it once at module scope and reuse it — never inside a function or per-call. Name the variable
arcjet
.
Check if
ARCJET_KEY
is set in the environment file (
.env
,
.env.local
, etc.). If not, obtain the key in this priority order:
  1. CLI (preferred): Run
    arcjet sites get-key --site-id <site-id>
    (requires
    arcjet auth login
    first — see Step 0)
  2. MCP: If the Arcjet MCP server is connected, use it to list sites and retrieve the key
  3. Manual (last resort): Add a placeholder and tell the user to get a key from https://app.arcjet.com
客户端会保持持久连接,需在模块作用域创建一次并重复使用——切勿在函数内部或每次调用时创建。将变量命名为
arcjet
检查环境文件(
.env
.env.local
等)中是否已设置
ARCJET_KEY
。若未设置,按以下优先级获取密钥:
  1. CLI(推荐):执行
    arcjet sites get-key --site-id <site-id>
    (需先执行
    arcjet auth login
    ——参见步骤0)
  2. MCP:若已连接Arcjet MCP服务器,可通过它列出站点并获取密钥
  3. 手动方式(最后选择):添加占位符并告知用户从https://app.arcjet.com获取密钥

Step 4: Configure Rules at Module Scope

步骤4:在模块作用域配置规则

Rules are configured once as reusable factories, then called with per-invocation input. This two-phase pattern matters — the rule config carries a stable ID used for server-side aggregation, while the per-call input varies.
When configuring rate limit rules, set
bucket
to a descriptive name (e.g.
"tool-calls"
,
"session-api"
) for semantic clarity and fewer collisions.
规则需配置为可复用的工厂函数,然后传入每次调用的输入参数。这种分阶段模式至关重要——规则配置包含用于服务器端聚合的稳定ID,而每次调用的输入参数会变化。
配置限流规则时,需为
bucket
设置描述性名称(如
"tool-calls"
"session-api"
),以提升语义清晰度并减少冲突。

Choosing Rules by Use Case

根据使用场景选择规则

Use caseRecommended rules
AI agent tool calls
tokenBucket
+
detectPromptInjection
MCP tool handlers
slidingWindow
or
tokenBucket
+
detectPromptInjection
Background AI task processor
tokenBucket
+
localDetectSensitiveInfo
Queue worker with user input
tokenBucket
+
detectPromptInjection
+
localDetectSensitiveInfo
Scanning tool results for injection
detectPromptInjection
(scan the returned content)
使用场景推荐规则
AI agent工具调用
tokenBucket
+
detectPromptInjection
MCP工具处理器
slidingWindow
tokenBucket
+
detectPromptInjection
后台AI任务处理器
tokenBucket
+
localDetectSensitiveInfo
含用户输入的队列工作器
tokenBucket
+
detectPromptInjection
+
localDetectSensitiveInfo
扫描工具结果中的注入风险
detectPromptInjection
(扫描返回内容)

Step 5: Call guard() Inline Before Each Operation

步骤5:在每次操作前直接调用guard()

Call
guard()
directly where each operation happens — inline in each tool handler, task processor, or function that needs protection. Do not wrap guard in a shared helper function.
Each
guard()
call takes:
  • label: descriptive string for the dashboard (e.g.
    "tools.search_web"
    ,
    "tasks.generate"
    )
  • rules: array of bound rule invocations
  • metadata (optional): key-value pairs for analytics/auditing (e.g.
    { userId }
    )
Rate limit rules take an explicit key string — use a user ID, session ID, API key, or any stable identifier.
You MUST modify the existing source files — adding the dependency to package.json/requirements.txt alone is not enough. The guard() calls must be integrated into the actual code.
需在每个需要保护的操作发生位置直接调用
guard()
——即在每个工具处理器、任务处理器或函数内联调用。请勿将guard包装在共享辅助函数中。
每次
guard()
调用需传入:
  • label:用于仪表盘的描述性字符串(如
    "tools.search_web"
    "tasks.generate"
  • rules:绑定规则调用的数组
  • metadata(可选):用于分析/审计的键值对(如
    { userId }
限流规则需传入明确的key字符串——可使用用户ID、会话ID、API密钥或任何稳定标识符。
必须修改现有源文件——仅向package.json/requirements.txt添加依赖是不够的,需将
guard()
调用集成到实际代码中。

Step 6: Handle Decisions

步骤6:处理决策结果

Always check
decision.conclusion
:
  • "DENY"
    → block the operation. Use per-rule result accessors (see reference) for specific error messages like retry-after times.
  • "ALLOW"
    → safe to proceed
See the language reference for the exact decision-checking pattern and per-rule result accessors.
务必检查
decision.conclusion
  • "DENY"
    → 阻止操作。使用每个规则的结果访问器(参见参考文档)获取具体错误信息,如重试等待时间。
  • "ALLOW"
    → 可安全执行操作
请查阅语言参考文档获取准确的决策检查模式和各规则的结果访问器用法。

Common Mistakes to Avoid

需避免的常见错误

  • Wrapping guard in a shared helper function — calling
    guard()
    through a
    guardToolCall()
    or
    protectCall()
    wrapper hides which rules apply to each operation. Call
    guard()
    inline where each operation happens.
  • Creating the client per call — the client holds a persistent connection. Create it once at module scope.
  • Configuring rules inside a function — rule configs carry stable IDs. Creating them per call breaks dashboard tracking and rate limit state.
  • Forgetting the
    key
    parameter on rate limit rules
    — without a key, Guard can't track per-user limits.
  • Forgetting
    bucket
    on rate limit rules
    — without a named bucket, different rules may collide.
  • Using the HTTP SDK when there's no request — use
    @arcjet/guard
    /
    arcjet.guard
    for non-HTTP code, not
    @arcjet/node
    ,
    @arcjet/next
    , or
    arcjet()
    .
  • Not checking
    decision.conclusion
    — always check before proceeding.
  • Generic DENY messages — use per-rule result accessors to give users specific feedback like retry-after times.
  • 将guard包装在共享辅助函数中——通过
    guardToolCall()
    protectCall()
    等包装函数调用
    guard()
    会隐藏每个操作适用的规则。需在每个操作发生位置内联调用
    guard()
  • 每次调用创建客户端——客户端会保持持久连接,需在模块作用域创建一次。
  • 在函数内部配置规则——规则配置包含稳定ID,每次调用创建规则会破坏仪表盘跟踪和限流状态。
  • 忘记为限流规则设置
    key
    参数
    ——没有key,Guard无法跟踪每个用户的限流限制。
  • 忘记为限流规则设置
    bucket
    ——没有命名bucket,不同规则可能会发生冲突。
  • 在无请求场景使用HTTP SDK——针对非HTTP代码,需使用
    @arcjet/guard
    /
    arcjet.guard
    ,而非
    @arcjet/node
    @arcjet/next
    arcjet()
  • 未检查
    decision.conclusion
    ——执行操作前务必检查该值。
  • 通用DENY提示信息——使用各规则的结果访问器为用户提供具体反馈,如重试等待时间。

Step 7: Verify Guard Decisions with the CLI (Coming Soon)

步骤7:使用CLI验证Guard决策(即将推出)

Note: The
arcjet guards
CLI subcommand is not yet released. Once available, use this feedback loop to verify guard decisions are firing correctly.
After adding guard code, use the CLI to verify decisions are firing correctly. This creates a feedback loop: run the app, trigger a guard, inspect the decision, adjust if needed.
注意:
arcjet guards
CLI子命令尚未发布。发布后,可使用此反馈循环验证guard决策是否正确触发。
添加guard代码后,使用CLI验证决策是否正确触发。这会形成一个反馈循环:运行应用、触发guard、检查决策、按需调整。

1. Start Watching

1. 开始监控

In a separate terminal, start streaming guard decisions:
bash
arcjet guards watch --site-id <site-id>
This polls for new guard decisions and prints them as they arrive. Use
--conclusion DENY
to filter to denials only, or
--interval 2
for faster polling.
在单独的终端中,启动guard决策流监控:
bash
arcjet guards watch --site-id <site-id>
此命令会轮询新的guard决策并在到达时打印。可使用
--conclusion DENY
仅过滤拒绝决策,或使用
--interval 2
加快轮询速度。

2. Trigger the Guard

2. 触发Guard

Run the application and exercise the code paths that call
guard()
. Each call should produce a decision visible in the watch output.
运行应用并执行调用
guard()
的代码路径。每次调用都会生成一个决策,可在监控输出中查看。

3. Inspect Decisions

3. 检查决策

If a decision doesn't match expectations, inspect it:
bash
undefined
若决策不符合预期,可查看详情:
bash
undefined

List recent guard decisions

列出最近的guard决策

arcjet guards list --site-id <site-id>
arcjet guards list --site-id <site-id>

Get per-rule breakdown for a specific decision

获取特定决策的各规则执行详情

arcjet guards details --site-id <site-id> --decision-id <decision-id>

The details view shows each rule execution, its mode (live/dry-run), conclusion, reason, and whether it was skipped — use this to diagnose why a guard allowed or denied unexpectedly.
arcjet guards details --site-id <site-id> --decision-id <decision-id>

详情视图会显示每个规则的执行情况、模式(实时/试运行)、结论、原因以及是否被跳过——可用于诊断guard意外允许或拒绝请求的原因。

4. Adjust and Repeat

4. 调整并重复

If rules aren't firing as expected:
  • Check the
    label
    matches what appears in the decision
  • Verify the
    key
    is correct for rate limit rules (wrong key = wrong bucket)
  • Confirm the
    bucket
    name is unique per rule
  • Check rule ordering — rules execute in array order and a DENY from an earlier rule short-circuits later ones
Then re-run and watch again until decisions match expectations.
若规则未按预期触发:
  • 检查
    label
    是否与决策中显示的一致
  • 验证限流规则的
    key
    是否正确(错误的key会导致错误的bucket)
  • 确认
    bucket
    名称在各规则中唯一
  • 检查规则顺序——规则按数组顺序执行,前面规则的DENY结果会终止后续规则的执行
然后重新运行应用并再次监控,直到决策符合预期。

CLI Quick Reference

CLI快速参考

TaskCommand
Install/run CLI
npx @arcjet/cli
or
brew install arcjet
Authenticate
arcjet auth login
Check auth status
arcjet auth status
List teams
arcjet teams list
List sites
arcjet sites list --team-id <id>
Create site
arcjet sites create --team-id <id> --name "Name" --confirm
Get SDK key
arcjet sites get-key --site-id <id>
Watch guard decisions
arcjet guards watch --site-id <id>
List guard decisions
arcjet guards list --site-id <id>
Guard decision details
arcjet guards details --site-id <id> --decision-id <id>
任务命令
安装/运行CLI
npx @arcjet/cli
brew install arcjet
身份验证
arcjet auth login
检查验证状态
arcjet auth status
列出团队
arcjet teams list
列出站点
arcjet sites list --team-id <id>
创建站点
arcjet sites create --team-id <id> --name "Name" --confirm
获取SDK密钥
arcjet sites get-key --site-id <id>
监控guard决策
arcjet guards watch --site-id <id>
列出guard决策
arcjet guards list --site-id <id>
查看guard决策详情
arcjet guards details --site-id <id> --decision-id <id>

Global Flags

全局标志

All commands support:
  • --output text|json
    — output format (default: text on TTY, json otherwise)
  • --fields <list>
    — comma-separated fields to include in JSON output
  • --no-color
    — disable ANSI colors (also honors
    NO_COLOR
    env var)
  • --timeout <duration>
    — max execution time (e.g.
    30s
    ,
    5m
    ; 0 disables)
所有命令均支持:
  • --output text|json
    — 输出格式(默认:终端环境下为text,其他环境为json)
  • --fields <list>
    — JSON输出中包含的字段列表(逗号分隔)
  • --no-color
    — 禁用ANSI颜色(同时遵循
    NO_COLOR
    环境变量)
  • --timeout <duration>
    — 最大执行时间(如
    30s
    5m
    ;设为0则禁用超时)

Exit Codes

退出码

CodeMeaning
0Success
1General error (unknown command, API failure, network error)
2Authentication error (not logged in, token expired)
3Input validation error (invalid ID, value out of range)
4Confirmation required (mutation needs
--confirm
)
代码含义
0成功
1通用错误(未知命令、API失败、网络错误)
2身份验证错误(未登录、令牌过期)
3输入验证错误(无效ID、值超出范围)
4需要确认(修改操作需添加
--confirm