add-guard-protection
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAdd 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
undefinedArcjet CLI是用于身份验证、站点管理、远程规则配置和流量监控的核心工具。如果尚未安装,请按以下方式安装:
bash
undefinedVia 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
undefinedbrew install arcjet
undefinedAuthenticate
身份验证
bash
arcjet auth loginOpens the browser for authentication. Check status with .
arcjet auth statusbash
arcjet auth login此命令会打开浏览器进行身份验证。可通过检查验证状态。
arcjet auth statusSite & Key Setup
站点与密钥配置
bash
undefinedbash
undefinedList 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:
- → JavaScript/TypeScript →
package.json(requiresnpm install @arcjet/guard>= 1.4.0)@arcjet/guard - /
requirements.txt→ Python →pyproject.toml(requirespip install arcjet>= 0.7.0; Guard is included)arcjet - ,
go.mod,Cargo.toml, 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.pom.xml
检查项目中的语言标识文件:
- → JavaScript/TypeScript → 执行
package.json(要求npm install @arcjet/guard版本 ≥ 1.4.0)@arcjet/guard - /
requirements.txt→ Python → 执行pyproject.toml(要求pip install arcjet版本 ≥ 0.7.0;Guard已包含在内)arcjet - 、
go.mod、Cargo.toml或其他语言 → 暂不支持Guard。告知用户Arcjet Guard目前仅支持JavaScript/TypeScript和Python,请勿自行编写模拟代码或虚构不存在的包,建议用户联系Arcjet反馈其使用场景。pom.xml
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 .
arcjetCheck if is set in the environment file (, , etc.). If not, obtain the key in this priority order:
ARCJET_KEY.env.env.local- CLI (preferred): Run (requires
arcjet sites get-key --site-id <site-id>first — see Step 0)arcjet auth login - MCP: If the Arcjet MCP server is connected, use it to list sites and retrieve the key
- Manual (last resort): Add a placeholder and tell the user to get a key from https://app.arcjet.com
客户端会保持持久连接,需在模块作用域创建一次并重复使用——切勿在函数内部或每次调用时创建。将变量命名为。
arcjet检查环境文件(、等)中是否已设置。若未设置,按以下优先级获取密钥:
.env.env.localARCJET_KEY- CLI(推荐):执行(需先执行
arcjet sites get-key --site-id <site-id>——参见步骤0)arcjet auth login - MCP:若已连接Arcjet MCP服务器,可通过它列出站点并获取密钥
- 手动方式(最后选择):添加占位符并告知用户从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 to a descriptive name (e.g. , ) for semantic clarity and fewer collisions.
bucket"tool-calls""session-api"规则需配置为可复用的工厂函数,然后传入每次调用的输入参数。这种分阶段模式至关重要——规则配置包含用于服务器端聚合的稳定ID,而每次调用的输入参数会变化。
配置限流规则时,需为设置描述性名称(如、),以提升语义清晰度并减少冲突。
bucket"tool-calls""session-api"Choosing Rules by Use Case
根据使用场景选择规则
| Use case | Recommended rules |
|---|---|
| AI agent tool calls | |
| MCP tool handlers | |
| Background AI task processor | |
| Queue worker with user input | |
| Scanning tool results for injection | |
| 使用场景 | 推荐规则 |
|---|---|
| AI agent工具调用 | |
| MCP工具处理器 | |
| 后台AI任务处理器 | |
| 含用户输入的队列工作器 | |
| 扫描工具结果中的注入风险 | |
Step 5: Call guard() Inline Before Each Operation
步骤5:在每次操作前直接调用guard()
Call 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.
guard()Each call takes:
guard()- 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- → block the operation. Use per-rule result accessors (see reference) for specific error messages like retry-after times.
"DENY" - → safe to proceed
"ALLOW"
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 through a
guard()orguardToolCall()wrapper hides which rules apply to each operation. CallprotectCall()inline where each operation happens.guard() - 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 parameter on rate limit rules — without a key, Guard can't track per-user limits.
key - Forgetting on rate limit rules — without a named bucket, different rules may collide.
bucket - Using the HTTP SDK when there's no request — use /
@arcjet/guardfor non-HTTP code, notarcjet.guard,@arcjet/node, or@arcjet/next.arcjet() - Not checking — always check before proceeding.
decision.conclusion - Generic DENY messages — use per-rule result accessors to give users specific feedback like retry-after times.
- 将guard包装在共享辅助函数中——通过或
guardToolCall()等包装函数调用protectCall()会隐藏每个操作适用的规则。需在每个操作发生位置内联调用guard()。guard() - 每次调用创建客户端——客户端会保持持久连接,需在模块作用域创建一次。
- 在函数内部配置规则——规则配置包含稳定ID,每次调用创建规则会破坏仪表盘跟踪和限流状态。
- 忘记为限流规则设置参数——没有key,Guard无法跟踪每个用户的限流限制。
key - 忘记为限流规则设置——没有命名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: TheCLI subcommand is not yet released. Once available, use this feedback loop to verify guard decisions are firing correctly.arcjet guards
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.
注意:CLI子命令尚未发布。发布后,可使用此反馈循环验证guard决策是否正确触发。arcjet guards
添加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 to filter to denials only, or for faster polling.
--conclusion DENY--interval 2在单独的终端中,启动guard决策流监控:
bash
arcjet guards watch --site-id <site-id>此命令会轮询新的guard决策并在到达时打印。可使用仅过滤拒绝决策,或使用加快轮询速度。
--conclusion DENY--interval 22. Trigger the Guard
2. 触发Guard
Run the application and exercise the code paths that call . Each call should produce a decision visible in the watch output.
guard()运行应用并执行调用的代码路径。每次调用都会生成一个决策,可在监控输出中查看。
guard()3. Inspect Decisions
3. 检查决策
If a decision doesn't match expectations, inspect it:
bash
undefined若决策不符合预期,可查看详情:
bash
undefinedList 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 matches what appears in the decision
label - Verify the is correct for rate limit rules (wrong key = wrong bucket)
key - Confirm the name is unique per rule
bucket - 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会导致错误的bucket)
key - 确认名称在各规则中唯一
bucket - 检查规则顺序——规则按数组顺序执行,前面规则的DENY结果会终止后续规则的执行
然后重新运行应用并再次监控,直到决策符合预期。
CLI Quick Reference
CLI快速参考
| Task | Command |
|---|---|
| Install/run CLI | |
| Authenticate | |
| Check auth status | |
| List teams | |
| List sites | |
| Create site | |
| Get SDK key | |
| Watch guard decisions | |
| List guard decisions | |
| Guard decision details | |
| 任务 | 命令 |
|---|---|
| 安装/运行CLI | |
| 身份验证 | |
| 检查验证状态 | |
| 列出团队 | |
| 列出站点 | |
| 创建站点 | |
| 获取SDK密钥 | |
| 监控guard决策 | |
| 列出guard决策 | |
| 查看guard决策详情 | |
Global Flags
全局标志
All commands support:
- — output format (default: text on TTY, json otherwise)
--output text|json - — comma-separated fields to include in JSON output
--fields <list> - — disable ANSI colors (also honors
--no-colorenv var)NO_COLOR - — max execution time (e.g.
--timeout <duration>,30s; 0 disables)5m
所有命令均支持:
- — 输出格式(默认:终端环境下为text,其他环境为json)
--output text|json - — JSON输出中包含的字段列表(逗号分隔)
--fields <list> - — 禁用ANSI颜色(同时遵循
--no-color环境变量)NO_COLOR - — 最大执行时间(如
--timeout <duration>、30s;设为0则禁用超时)5m
Exit Codes
退出码
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | General error (unknown command, API failure, network error) |
| 2 | Authentication error (not logged in, token expired) |
| 3 | Input validation error (invalid ID, value out of range) |
| 4 | Confirmation required (mutation needs |
| 代码 | 含义 |
|---|---|
| 0 | 成功 |
| 1 | 通用错误(未知命令、API失败、网络错误) |
| 2 | 身份验证错误(未登录、令牌过期) |
| 3 | 输入验证错误(无效ID、值超出范围) |
| 4 | 需要确认(修改操作需添加 |