Zerda 文档
Zerda 保护注册、登录、试用申领和内容发布等接口,识别自动化工具、伪造的浏览器环境和批量账号。网页取一个一次性令牌,你的后端用核验密钥换回判定结果和建议的处置方式。
快速接入
- 使用 Zerda 开通的账号登录控制台,在「站点接入」中新建站点,记下公开密钥
pk_...和核验密钥sk_...。核验密钥只显示一次。 - 把站点的域名加进「允许的域名」。留空表示不限制,正式上线前建议填写。
- 在表单页面加载脚本,提交前调用
Zerda.getToken(),把令牌随表单发给你的后端。 - 后端调用
POST /api/verify,按返回的decision.action放行、二次验证或拒绝。
网页脚本
<script src="https://api.zerda.dev/z.js?k=pk_你的公开密钥" defer></script>
<script>
form.addEventListener('submit', async (event) => {
event.preventDefault();
const button = form.querySelector('[type="submit"]');
if (button.disabled) return;
button.disabled = true;
try {
const token = await window.Zerda?.getToken(undefined, { action: 'register' });
await fetch('/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...formData, token }) });
} finally {
button.disabled = false;
}
});
</script>
- 从点击提交到请求完成,请禁用提交按钮或显示加载状态。每次点击都会取一次令牌,重复点击会产生重复的核验与业务请求。
Zerda.getToken(endpoint, options)返回令牌字符串,失败时返回null,不会抛出异常。endpoint传undefined即可,脚本会使用加载它的地址。- 脚本被浏览器扩展拦截或未能加载时,
window.Zerda不存在。请按示例写成window.Zerda?.getToken(...),此时令牌为空,表单照常提交,由后端转入二次验证。 options.action是场景名,例如register、login、checkout,用于按场景统计和套用场景策略。只能包含字母、数字、下划线和短横线。options.signal可以传入AbortSignal,中止后返回null。不传时最多等待 15 秒,超时返回null。- 脚本在页面加载后就开始记录交互,越早加载、用户在页面停留越久,行为信号越完整。请在表单提交时再取令牌,令牌有效期 5 分钟。
- 脚本内容持续变化,不要把它下载到自己的服务器上托管。需要走自有域名时请使用下文的代理方式。
后端核验
curl -X POST https://api.zerda.dev/api/verify \
-H "Authorization: Bearer sk_你的核验密钥" \
-H "Content-Type: application/json" \
-d '{"token":"<令牌>","email":"user@example.com","userId":"u_1024","action":"register"}'
请求体字段:
| 字段 | 说明 |
|---|---|
token | 必填。网页取到的令牌。每个令牌只能核验一次,超过 5 分钟失效。 |
email | 可选。用户提交的邮箱,用于邮箱风险识别和多账号关联;控制台按它展示和搜索账号。 |
userId | 可选。你系统里的用户 ID(字符串或数字),用于登录、发帖等已有账号的场景;控制台在没有邮箱时用它标识账号。 |
cardFingerprint | 可选。支付服务商返回的卡指纹(如 Stripe 的 card.fingerprint),用于统计同一张卡绑定过本站多少个其他账号。只保存它的摘要;不要传卡号。 |
action | 建议必传。传入本次业务对应的场景名:与网页取令牌时的场景不一致时,结果带 action_mismatch 并判为 bot。不传时按网页上报的场景套用场景策略,而网页上报的场景可以被伪造,攻击者可能借此改用宽松场景的策略。 |
返回示例:
{
"valid": true,
"verdict": "suspicious",
"score": 55,
"groups": { "automation": 0, "email": 0, "consistency": 0, "behavior": 40, "network": 15, "environment": 0 },
"reasons": ["..."],
"decision": { "action": "challenge", "source": "policy", "ruleId": null, "ruleName": null }
}
reasons为本次命中的检测项标识,各项的名称可在控制台的事件详情中查看。付费套餐按名称列出常规检测项,Zerda 自有的检测手段按大类各合并为一项,标识为zerda_加大类名(如zerda_consistency);试用期内所有检测项均按大类列出。valid: false表示令牌不存在、已被核验过、已过期或不属于这个站点,应当按结果未知处理。- 网页没有取到令牌(
getToken()返回null)时无需调用本接口,直接按结果未知处理;令牌字段缺失或不是字符串时,本接口返回 HTTP 400;空字符串按无效令牌返回valid: false。 decision.action取值为allow(放行)、challenge(二次验证)、reduce(降低权益,例如不发放试用额度)、review(放行但进入人工复核)、block(拒绝)。decision.source为list时表示命中了放行或拒绝名单,listKind是命中的类型(ip、email、domain、visitor、user);为rule时表示命中了自定义规则,ruleName是规则名称;为policy时表示按场景策略处置。- 返回中还可能包含
velocity(同设备、同 IP 的近期频次)和accountCluster(同一设备近 24 小时的关联统计:category为multi_account表示背后有两个及以上账号,账号按userId计、未传时按邮箱计;registrations24h为账号数),可以用于自己的风控逻辑。 - 绑卡场景:用户从支付页回到你的网站后取令牌,你的服务器拿到卡指纹后再核验并传入
cardFingerprint。传入时返回带card.otherAccounts30d,即 30 天内同一张卡绑定过的本站其他账号数。这个数字不计入分数:公司常用一张卡为多个账号付款,是否处置由你决定。可以在自己的服务器上按它处理,也可以在控制台的自定义规则里设置「同卡其他账号不少于」并选择处置方式。该场景需要更严格的处置时,同样用自定义规则按场景和分数设置。
判定与分数
分数由六个维度累加,每个维度有单独的上限,对应返回中的 groups:
| 维度 | 字段 | 上限 |
|---|---|---|
| 自动化痕迹 | automation | 100 |
| 环境一致性 | consistency | 70 |
| 行为 | behavior | 100 |
| 邮箱 | email | 80 |
| 网络 | network | 80 |
| 运行环境 | environment | 25 |
总分不低于 100 判为 bot,40 到 99 为 suspicious,低于 40 为 likely_human。网页端接口不返回分数和命中原因,这些信息只出现在核验结果和控制台里。
规则与场景策略
处置方式按以下顺序决定:
- 放行与拒绝名单:按 IP、邮箱、邮箱域名(含子域名)、访客标识或用户 ID 直接放行或拒绝,两边都命中时按拒绝处理。邮箱、邮箱域名和用户 ID 只有在核验时传入
email、userId才能匹配。名单修改后立即生效。 - 自定义规则按优先级从小到大匹配,命中第一条即采用它的处置。条件可以是站点、场景、判定、分数区间、命中信号、风险维度、邮箱域名、IP 和访客标识,同一条规则中的条件需要同时满足。
- 没有命中规则时,查场景策略表:按场景和判定取处置方式。未单独配置的场景使用「其他场景」一行。
默认策略为:likely_human 放行,suspicious 二次验证,bot 拒绝;其中 claim 场景的 suspicious 降低额度(reduce),post 场景的 suspicious 转人工审核(review)。新建规则前可以用「用历史数据试运行」查看它在过去 7 天会命中多少事件。
令牌为空时
以下情况 getToken() 会返回 null:网络异常或超时、请求被限速、域名不在允许列表、工作区已暂停、试用配额已用完,或试用结束后尚未开通付费套餐。请把 null 当作「结果未知」,转入二次验证(例如短信、邮箱验证码或人机验证),不要直接放行,也不要直接拒绝。
自有域名代理
如果希望脚本和接口走你自己的域名,可以在服务器上反向代理到 Zerda,并在每个请求上附加代理密钥和访客真实 IP。代理密钥在「站点接入」页生成,只能保存在服务器上。
location /zerda/ {
proxy_pass https://api.zerda.dev/;
proxy_set_header X-Zerda-Proxy-Secret "zps_你的代理密钥";
proxy_set_header X-Zerda-Client-IP $remote_addr;
}
网页里改为加载 https://你的域名/zerda/z.js?k=pk_...。代理密钥必须属于该站点,否则请求会被拒绝。走代理时部分网络层信号不可用,其余不受影响。
保护徽标
可选。在页面中加载徽标脚本,页面右下角会显示「受 Zerda 保护」以及隐私政策与服务条款的链接。徽标只用于展示,不采集数据,也不写入任何存储。
<script src="https://api.zerda.dev/badge.js" async></script>
- 页面中放置
<zerda-badge></zerda-badge>元素时,徽标显示在该元素的位置,例如表单下方。 - 文字跟随页面
<html lang>:以zh开头时显示中文,以ja开头时显示日文,其余显示英文,页面切换语言时同步更新。
Zerda Hold
Zerda 自带的二次验证,免费、可选。/api/verify 返回的 decision.action 为 challenge 时,在页面上显示它;访客把圆点拖进框里并按住跟着框走,大约几秒完成,得到一个新令牌。也可以不用它,改用你自己的短信、邮箱或其他验证。
// firstToken 是这次操作中 getToken() 拿到的令牌
const token = await window.Zerda?.challenge(document.getElementById('verify-box'), { from: firstToken, action: 'register' }) ?? null;
// token 不为 null 时,由后端用它再调用一次 /api/verify;为 null 时转入你自己的替代验证
from为第一轮的令牌,用于核对两轮在同一个浏览器中完成;第一轮没拿到令牌时可以不传。action与getToken()相同。- 返回的 Promise 在完成时得到新令牌;访客选择「无法完成验证」、组件加载失败或网络异常时得到
null,与getToken()的约定一致。组件从加载/z.js的同一地址按需加载h.js。 - 新令牌同样只能核验一次,返回格式不变,另有
hold.pass。这一轮不会再返回challenge:验证未通过时(除名单放行外)处置一律变为block,验证通过时本该为challenge的处置变为allow,decision.source均为hold;名单与规则给出的其他处置照常生效。 hold.bound表示这一轮是否与第一轮绑定:true为与from所指的第一轮在同一个浏览器中完成,false为不在同一个浏览器(此时hold.pass也为false),null为调用时没有传from。你的后端如果是因为第一轮的challenge才要求二次验证的,请只接受hold.bound为true的结果。- 从组件显示到
challenge()返回之间,不要在同一页面另行调用getToken(),否则这一轮无法通过核对。 - 容器宽度应在 306 到 400 px 之间。组件文字默认跟随页面语言,可用
lang指定为zh、ja或en。 - 组件只记录自身区域内的操作;按键只记录时间,不记录按下的是哪个键。单独加载
h.js并使用<zerda-hold>的写法只采集数据、不签发令牌,仅用于测试。
Webhook
可订阅的事件:event.evaluated(每次评估)、event.flagged(可疑或机器人)、event.verified(令牌被核验)、alert.fired(告警触发)。投递为 JSON POST,请求头带 Zerda-Event 和 Zerda-Signature。
Zerda-Signature 的格式为 t=时间戳,v1=签名。校验方法:用签名密钥对字符串 时间戳.原始请求体 计算 HMAC-SHA256(十六进制),与 v1 做常量时间比较,并拒绝时间戳与当前时间相差过大的请求。
import { createHmac, timingSafeEqual } from 'node:crypto';
function verifyZerda(rawBody, header, secret) {
if (typeof header !== 'string') return false;
const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
const expected = Buffer.from(createHmac('sha256', secret).update(`${parts.t}.${rawBody}`).digest('hex'));
const got = Buffer.from(String(parts.v1 ?? ''));
return got.length === expected.length && timingSafeEqual(got, expected)
&& Math.abs(Date.now() / 1000 - Number(parts.t)) < 300;
}
接收方返回 2xx 视为成功,否则会自动重试。投递记录可以在控制台查看并手动重新投递。Webhook 地址必须是 https,不能指向内网或本机地址。
管理接口
在控制台「API 密钥」页创建 zk_... 密钥后,可以用 Authorization: Bearer zk_... 调用 /api/v1。密钥只能访问创建它的工作区,分只读和读写两种。
创建时可将密钥限定到一个站点。限定站点的密钥只能读取该站点的信息、事件、访客、用量与请求计数,usage 中的 month 与 quota 仍为工作区合计;规则只返回该站点的规则与全部站点通用的规则,创建和修改仅限该站点的规则,未指定 siteId 时默认为该站点;场景策略与名单作用于全部站点,只能读取。越权操作返回 403 site_key。站点删除后,限定该站点的密钥随之吊销。
| 接口 | 说明 | 权限 |
|---|---|---|
GET /api/v1/workspace | 工作区、套餐与本月用量 | 只读 |
GET /api/v1/sites | 站点列表 | 只读 |
GET /api/v1/overview?from=&to=&siteId=&unit= | 指定时间窗口内的概览统计、趋势分桶与来源分布 | 只读 |
GET /api/v1/events?hours=&since=&siteId=&verdict=&limit=&page=&pageSize= | 事件列表。传入从 1 开始的 page(及可选 pageSize,默认 50、最大 200,可配合 from、to、q 等筛选参数)时返回分页结果与总条数 total;未传 page 时单次最多返回 10,000 条(超出时带 truncated: true),默认按时间倒序,传入毫秒时间戳 since 时改为按时间正序返回该时刻之后的事件,可将末尾事件的 t 作为下一次的 since 继续拉取 | 只读 |
GET /api/v1/events/:id | 单个事件 | 只读 |
PUT /api/v1/events/:id/label | 标记事件,请求体为 { label },取值 abuse(漏报)、fp(误判)或 null(清除) | 读写 |
POST /api/v1/events/:id/ip-check | 向外部检测商复查事件的 IP,返回 netType 与 flags;工作区未开通外部检测时返回 403,每个工作区每小时有次数上限 | 读写 |
GET /api/v1/visitors?from=&to=&siteId=&filter=&q=&page=&pageSize= | 访客分页列表(默认每页 50 条,最大 200 条) | 只读 |
GET /api/v1/visitors/:id?page=&pageSize= | 某访客的事件。传入 page 时返回访客汇总 summary、总条数 total 与当页事件;未传 page 时单次最多返回 10,000 条(超出时带 truncated: true) | 只读 |
DELETE /api/v1/visitors/:id?siteId= | 删除某访客的全部数据;传入 siteId 时只删除该站点的数据。限定站点的密钥不能调用 | 读写 |
GET /api/v1/usage?days= | 按日用量 | 只读 |
GET /api/v1/health?hours= | 按小时的请求计数 | 只读 |
GET /api/v1/rules | 自定义规则 | 只读 |
POST /api/v1/rules | 创建规则 | 读写 |
PATCH / DELETE /api/v1/rules/{id} | 修改、删除规则 | 读写 |
GET /api/v1/policy | 场景策略表 | 只读 |
PUT / DELETE /api/v1/policy | 替换场景策略,或恢复默认。PUT 的请求体为 { policy: { 场景名: { likely_human, suspicious, bot, unknown } } },_default 用于未列出的场景;缺少 policy 时返回 400 | 读写 |
GET /api/v1/lists | 放行与拒绝名单 | 只读 |
POST /api/v1/lists | 加入名单,请求体为 { kind, value, action, note } 或 { entries: [...] } | 读写 |
DELETE /api/v1/lists/{id} | 从名单中解除 | 读写 |
限制与配额
- 令牌有效期 5 分钟,只能核验一次。
- 同一 IP 在短时间内请求过多会被限速,此时
getToken()返回null。 - 每月评估次数以工作区的套餐为准,可在控制台查看。试用用完配额后、试用结束后尚未开通付费套餐时,暂停签发令牌;付费套餐超出后不中断服务。
- 事件按工作区设置的保留天数保存,超过的数据每小时清理一次。
数据与隐私
- 访客 IP 按原样随事件保存,供控制台展示、搜索和外部复查,保存期与事件相同;频次与关联统计只使用 IP 的 HMAC 摘要。
- 脚本在你的站点域名下写入第一方 Cookie
_dpr_s(有效期 1 年)及浏览器本地存储,用于识别同一设备,仅用于安全防护。 - 请求头只保存白名单内的字段;键盘事件只记录按键时长,不记录按下的是哪个键,也不记录输入内容。
- 核验时提交的邮箱和用户 ID 随事件保存,供控制台展示和搜索,保存期与事件相同;在控制台删除访客时一并删除。
- 可以在控制台或通过接口删除某个访客的全部数据,用于响应用户的删除请求。详见隐私政策和数据处理协议。
有问题请在控制台提交工单。
Zerda documentation
Zerda protects sign-up, login, trial and posting endpoints from automation tools, forged browser environments and bulk accounts. Your page gets a one-time token, and your backend trades it with a secret key for a verdict and a suggested decision.
Quick start
- Sign in to the console with the account Zerda set up for you and create a site under Sites. Note the public key
pk_...and the secret keysk_.... The secret key is shown once. - Add your domains to Allowed domains. Empty means any domain; fill it in before going live.
- Load the script on the form page, call
Zerda.getToken()before submitting and send the token to your backend with the form. - Your backend calls
POST /api/verifyand allows, challenges or blocks based ondecision.action.
Browser script
<script src="https://api.zerda.dev/z.js?k=pk_your_public_key" defer></script>
<script>
form.addEventListener('submit', async (event) => {
event.preventDefault();
const button = form.querySelector('[type="submit"]');
if (button.disabled) return;
button.disabled = true;
try {
const token = await window.Zerda?.getToken(undefined, { action: 'register' });
await fetch('/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...formData, token }) });
} finally {
button.disabled = false;
}
});
</script>
- Disable the submit button or show a loading state from the click until the request completes. Each click requests a token, so repeated clicks send repeated verifications and requests.
Zerda.getToken(endpoint, options)resolves to a token string, ornullon failure. It never throws. Passundefinedas the endpoint to use the address the script was loaded from.- If the script is blocked by a browser extension or fails to load,
window.Zerdadoes not exist. Writewindow.Zerda?.getToken(...)as in the example: the token is then empty, the form still submits, and your backend sends the user to a second check. options.actionnames the action, such asregister,loginorcheckout. It is used for per-action stats and the action policy. Letters, digits, underscores and hyphens only.options.signaltakes anAbortSignal; an aborted call resolves tonull. Without one, the call waits at most 15 seconds and then resolves tonull.- The script records interaction from page load, so load it early. Get the token when the form is submitted; it is valid for 5 minutes.
- The script changes continuously. Do not self-host a copy; use the proxy setup below to serve it from your domain.
Verify on the backend
curl -X POST https://api.zerda.dev/api/verify \
-H "Authorization: Bearer sk_your_secret_key" \
-H "Content-Type: application/json" \
-d '{"token":"<token>","email":"user@example.com","userId":"u_1024","action":"register"}'
| Field | Meaning |
|---|---|
token | Required. The token from the page. Each token verifies once and expires after 5 minutes. |
email | Optional. The submitted email, used for email risk checks and to link accounts that belong together; the console shows and searches accounts by it. |
userId | Optional. The user's ID in your system (string or number), for actions with an existing account such as sign-in or posting; the console names the account by it when there is no email. |
cardFingerprint | Optional. The card fingerprint from your payment provider (such as Stripe's card.fingerprint), to count the other accounts on your site the same card was bound to. Only a digest of it is kept; never send the card number. |
action | Strongly recommended. Pass the action of this request: if it differs from the action used when the token was requested, the result carries action_mismatch and is judged bot. Without it the action policy uses the action reported by the page, which can be forged to pick a laxer action. |
{
"valid": true,
"verdict": "suspicious",
"score": 55,
"groups": { "automation": 0, "email": 0, "consistency": 0, "behavior": 40, "network": 15, "environment": 0 },
"reasons": ["..."],
"decision": { "action": "challenge", "source": "policy", "ruleId": null, "ruleName": null }
}
reasonslists the IDs of the checks that matched. Their names are shown in the event details in the console. Paid plans list the common checks by name, while Zerda's own techniques are merged into one item per group, with the IDzerda_followed by the group (for examplezerda_consistency); during a trial every check is listed by group.valid: falsemeans the token is unknown, already used, expired or belongs to another site. Treat it as an unknown result.- If the page got no token (
getToken()returnednull), skip this call and treat the result as unknown. A missing or non-string token returns HTTP 400; an empty string is treated as an unknown token and returnsvalid: false. decision.actionis one ofallow,challenge(second check),reduce(grant less, for example no trial credit),review(allow and queue for review) andblock.decision.sourceislistwhen the allow or block list matched (listKindisip,email,domain,visitororuser),rulewhen a custom rule matched (ruleNamenames it) andpolicywhen the action policy decided.- The response may also include
velocity(recent counts for the device and IP) andaccountCluster(counts for the same device over the last 24 hours:categoryismulti_accountwhen two or more accounts are behind it, counted byuserId, or by email when none was sent;registrations24his the number of accounts), for your own logic. - Card binding: get the token after the user returns to your site from the payment page, and verify it once your server has the card fingerprint, passing
cardFingerprint. The response then includescard.otherAccounts30d, the number of other accounts on your site the same card was bound to in the last 30 days. This number is not scored: companies often pay for several accounts with one card, so whether to act on it is your call. Handle it on your server, or add a custom rule in the console with "Other accounts on the same card at least" and the action you want. For stricter handling of this action in general, add a custom rule with the action name and a score condition.
Verdicts and scores
The score adds up six groups, each with its own cap, reported as groups in the response:
| Group | Field | Cap |
|---|---|---|
| Automation | automation | 100 |
| Consistency | consistency | 70 |
| Behavior | behavior | 100 |
email | 80 | |
| Network | network | 80 |
| Environment | environment | 25 |
A total of 100 or more is bot, 40 to 99 is suspicious and below 40 is likely_human. Browser-facing endpoints never return scores or reasons; they appear only in the verify response and the console.
Rules and policy
- Allow and block lists allow or block by IP, email, email domain (subdomains included), visitor ID or user ID. If both lists match, the request is blocked. Emails, email domains and user IDs match only when you send
emailanduserIdto verify. Changes apply at once. - Custom rules run from the lowest priority number up, and the first match decides. Conditions can use site, action, verdict, score range, signals, risk groups, email domains, IPs and visitor IDs; all conditions in a rule must hold.
- Without a matching rule, the action policy table picks the decision by action and verdict. Actions without their own row use Other actions.
The default policy allows likely_human, challenges suspicious and blocks bot, except that suspicious is reduced (reduce) for the claim action and sent for review (review) for the post action. Use Test on past events to see how many events of the last 7 days a rule would match.
When the token is null
getToken() resolves to null on network errors or timeouts, when rate limited, when the domain is not allowed, or when the workspace is suspended, its trial has used its monthly quota, or its trial has ended without a paid plan. Treat null as unknown and send the user to a second check such as an SMS or email code or a CAPTCHA, rather than allowing or blocking outright.
Proxy setup
To serve the script and API from your own domain, reverse-proxy to Zerda on your server and add the proxy secret and the visitor's IP to each request. Create the proxy secret on the Sites page and keep it on the server.
location /zerda/ {
proxy_pass https://api.zerda.dev/;
proxy_set_header X-Zerda-Proxy-Secret "zps_your_proxy_secret";
proxy_set_header X-Zerda-Client-IP $remote_addr;
}
Then load https://your-domain/zerda/z.js?k=pk_.... The proxy secret must belong to that site or the request is refused. Some network signals are not available through a proxy; everything else works the same.
Protection badge
Optional. Load the badge script and the page shows "Protected by Zerda" with links to the privacy policy and terms at the bottom right. The badge is display only: it collects no data and writes no storage.
<script src="https://api.zerda.dev/badge.js" async></script>
- Place a
<zerda-badge></zerda-badge>element in the page to show the badge at that spot instead, for example under a form. - The label follows
<html lang>: Chinese when it starts withzh, Japanese when it starts withja, English otherwise, and it updates when the page changes language.
Zerda Hold
Zerda's own step-up check, free and optional. Show it on the page when /api/verify returns decision.action challenge: the visitor drags a dot into a box and holds it there as the box moves, which takes a few seconds, and gets a new token. You can use your own SMS, email or other verification instead.
// firstToken is the token getToken() returned earlier in this action
const token = await window.Zerda?.challenge(document.getElementById('verify-box'), { from: firstToken, action: 'register' }) ?? null;
// With a token, your backend calls /api/verify again with it; with null, switch to your own fallback
fromis the first round's token, used to check that both rounds ran in the same browser; leave it out when the first round got no token.actionis the same as ingetToken().- The promise resolves to the new token when completed, or to
nullwhen the visitor chooses that they cannot complete it, the widget fails to load, or the network fails, the same contract asgetToken(). The widget'sh.jsis loaded on demand from where/z.jswas loaded. - The new token can be verified once, in the same format plus
hold.pass. This round never returnschallengeagain: when the check fails, the decision becomesblockunless allowlisted; when it passes, a decision that would bechallengebecomesallow, both withdecision.sourcehold. Other actions from your lists and rules still apply. hold.boundtells whether this round is tied to the first one:truewhen it ran in the same browser as the first round named byfrom,falsewhen it did not (hold.passis thenfalseas well), andnullwhenfromwas not passed. If your backend asked for this check because the first round returnedchallenge, accept only results whosehold.boundistrue.- From the moment the widget is shown until
challenge()resolves, do not callgetToken()on the same page; the round cannot be verified otherwise. - Give the container a width between 306 and 400 px. The text follows the page language by default; set
langtozh,jaorento choose. - The widget records only interaction inside its own area. Key presses keep only their timing, never which key. Loading
h.json its own with<zerda-hold>only collects data and issues no token; it is for testing.
Webhooks
Events: event.evaluated, event.flagged (suspicious or bot), event.verified and alert.fired. Each delivery is a JSON POST with the Zerda-Event and Zerda-Signature headers.
Zerda-Signature reads t=timestamp,v1=signature. Compute HMAC-SHA256 (hex) of timestamp.rawBody with the signing secret, compare it with v1 in constant time and reject timestamps far from now.
import { createHmac, timingSafeEqual } from 'node:crypto';
function verifyZerda(rawBody, header, secret) {
if (typeof header !== 'string') return false;
const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
const expected = Buffer.from(createHmac('sha256', secret).update(`${parts.t}.${rawBody}`).digest('hex'));
const got = Buffer.from(String(parts.v1 ?? ''));
return got.length === expected.length && timingSafeEqual(got, expected)
&& Math.abs(Date.now() / 1000 - Number(parts.t)) < 300;
}
A 2xx response counts as delivered; anything else is retried. Deliveries can be inspected and redelivered in the console. Webhook URLs must use https and cannot point to private or local addresses.
Management API
Create a zk_... key on the API keys page and call /api/v1 with Authorization: Bearer zk_.... A key reaches only its own workspace and is either read-only or read and write.
A key can be limited to one site when it is created. Such a key reads only that site's details, events, visitors, usage and request counts; month and quota in usage remain workspace totals. It sees the rules of its site and the rules for all sites, and creates or changes only rules of its site, which is also the default when siteId is omitted. The action policy and lists apply to every site and are read-only for such a key. Anything else returns 403 site_key. Deleting the site revokes the keys limited to it.
| Endpoint | Purpose | Scope |
|---|---|---|
GET /api/v1/workspace | Workspace, plan and this month's usage | read |
GET /api/v1/sites | Sites | read |
GET /api/v1/overview?from=&to=&siteId=&unit= | Overview totals, time-series buckets and breakdowns for a window | read |
GET /api/v1/events?hours=&since=&siteId=&verdict=&limit=&page=&pageSize= | Events. With 1-based page (and optional pageSize, default 50, max 200, plus optional from, to, q and filter parameters), returns a page with total. Without page, returns up to 10,000 per call (with truncated: true when more remain), newest first by default; with since (millisecond timestamp), returns events after it oldest first so the last event's t can be passed as the next since | read |
GET /api/v1/events/:id | One event | read |
PUT /api/v1/events/:id/label | Label an event with body { label }: abuse (missed abuse), fp (false positive) or null (clear) | write |
POST /api/v1/events/:id/ip-check | Re-check the event's IP with external providers and return netType and flags; 403 when the workspace has no external checks, with an hourly limit per workspace | write |
GET /api/v1/visitors?from=&to=&siteId=&filter=&q=&page=&pageSize= | Paginated visitors (default 50 per page, max 200) | read |
GET /api/v1/visitors/:id?page=&pageSize= | Events of a visitor. With page, returns summary, total and one page of events; without page, returns up to 10,000 per call (with truncated: true when more remain) | read |
DELETE /api/v1/visitors/:id?siteId= | Delete all data of a visitor; with siteId, only that site's data. Not available to site-limited keys | write |
GET /api/v1/usage?days= | Daily usage | read |
GET /api/v1/health?hours= | Hourly request counts | read |
GET /api/v1/rules | Custom rules | read |
POST /api/v1/rules | Create a rule | write |
PATCH / DELETE /api/v1/rules/{id} | Change or delete a rule | write |
GET /api/v1/policy | Action policy | read |
PUT / DELETE /api/v1/policy | Replace the action policy or reset it. The PUT body is { policy: { scene: { likely_human, suspicious, bot, unknown } } }, with _default for scenes not listed; 400 without policy | write |
GET /api/v1/lists | Allow and block lists | read |
POST /api/v1/lists | Add entries: { kind, value, action, note } or { entries: [...] } | write |
DELETE /api/v1/lists/{id} | Remove an entry | write |
Limits and quotas
- Tokens are valid for 5 minutes and verify once.
- Too many requests from one IP in a short time are rate limited, and
getToken()then resolves tonull. - Monthly events depend on the workspace's plan, shown in the console. A trial stops issuing tokens at its quota, and none are issued once it ends without a paid plan; paid plans keep working.
- Events are kept for the workspace's retention period and older data is removed hourly.
Data and privacy
- Visitor IPs are stored as received with their event, for display, search and external re-checks in the console, and kept as long as the event; counting and linking use only an HMAC hash of the IP.
- The script sets a first-party cookie
_dpr_s(valid for 1 year) and browser storage under your domain to recognize the same device for security only. - Only allow-listed request headers are stored. Keyboard events keep only key-press durations, never which key or what was typed.
- The email and user ID submitted at verify time are stored with the event so the console can show and search them. They are kept as long as the event and are deleted with the visitor in the console.
- You can delete all data of a visitor from the console or the API to answer deletion requests. See the privacy policy and the DPA.
Questions? Open a ticket in the console.
Zerda ドキュメント
Zerda は、新規登録、ログイン、トライアル、投稿などのエンドポイントを、自動化ツール、偽装されたブラウザ環境、大量のアカウントから保護します。ページでワンタイムトークンを取得し、バックエンドがシークレットキーを使ってトークンを判定と推奨アクションに交換します。コンソールは現在、英語と中国語で提供しています。
クイックスタート
- Zerda が用意したアカウントでコンソールにサインインし、「Sites」でサイトを作成します。公開キー
pk_...とシークレットキーsk_...を控えてください。シークレットキーは一度しか表示されません。 - 「Allowed domains」にドメインを追加します。空欄の場合はすべてのドメインが許可されるため、本番公開の前に必ず設定してください。
- フォームのページでスクリプトを読み込み、送信前に
Zerda.getToken()を呼び出して、トークンをフォームと一緒にバックエンドへ送信します。 - バックエンドで
POST /api/verifyを呼び出し、decision.actionに従って許可、追加認証、拒否のいずれかを行います。
ブラウザスクリプト
<script src="https://api.zerda.dev/z.js?k=pk_your_public_key" defer></script>
<script>
form.addEventListener('submit', async (event) => {
event.preventDefault();
const button = form.querySelector('[type="submit"]');
if (button.disabled) return;
button.disabled = true;
try {
const token = await window.Zerda?.getToken(undefined, { action: 'register' });
await fetch('/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...formData, token }) });
} finally {
button.disabled = false;
}
});
</script>
- クリックからリクエストの完了までは、送信ボタンを無効にするか読み込み中の表示にしてください。クリックのたびにトークンを取得するため、連続でクリックされると検証とリクエストが重複します。
Zerda.getToken(endpoint, options)はトークン文字列を返し、失敗した場合はnullを返します。例外は発生しません。エンドポイントにundefinedを渡すと、スクリプトを読み込んだアドレスを使用します。- スクリプトがブラウザ拡張機能にブロックされた場合や読み込みに失敗した場合、
window.Zerdaは存在しません。例のようにwindow.Zerda?.getToken(...)と書いてください。この場合トークンは空のままフォームが送信され、バックエンドで追加認証に案内します。 options.actionはregister、login、checkoutなどのアクション名です。アクション別の統計とアクション別ポリシーに使われます。使用できるのは英字、数字、アンダースコア、ハイフンのみです。options.signalにはAbortSignalを渡せます。中止された呼び出しはnullを返します。渡さない場合は最大 15 秒待機し、時間切れになるとnullを返します。- スクリプトはページの読み込み時点から操作を記録するため、できるだけ早く読み込んでください。トークンはフォームの送信時に取得します。有効期間は 5 分です。
- スクリプトは継続的に変化します。コピーを自社でホストせず、下記のプロキシ設定を使って自社ドメインから配信してください。
バックエンドでの検証
curl -X POST https://api.zerda.dev/api/verify \
-H "Authorization: Bearer sk_your_secret_key" \
-H "Content-Type: application/json" \
-d '{"token":"<token>","email":"user@example.com","userId":"u_1024","action":"register"}'
| フィールド | 説明 |
|---|---|
token | 必須。ページで取得したトークンです。各トークンは一度だけ検証でき、5 分で失効します。 |
email | 任意。送信されたメールアドレスです。メールアドレスのリスク判定と関連アカウントの紐付けに使われ、コンソールではこの値でアカウントを表示、検索できます。 |
userId | 任意。お客様のシステムにおけるユーザー ID(文字列または数値)です。サインインや投稿など既存アカウントがあるアクション向けで、メールアドレスがない場合はコンソールでこの値をアカウント名として表示します。 |
cardFingerprint | 任意。決済サービスが返すカードのフィンガープリント(Stripe の card.fingerprint など)です。同じカードがお客様のサイトの他のアカウントにいくつ登録されたかを数えるために使います。保存するのはそのダイジェストのみです。カード番号は送信しないでください。 |
action | 強く推奨。このリクエストのアクションを指定します。トークン取得時のアクションと異なる場合、結果に action_mismatch が含まれ、bot と判定されます。指定しない場合、アクション別ポリシーはページが報告したアクションを使用しますが、この値は偽装されて、より緩いアクションが選ばれるおそれがあります。 |
{
"valid": true,
"verdict": "suspicious",
"score": 55,
"groups": { "automation": 0, "email": 0, "consistency": 0, "behavior": 40, "network": 15, "environment": 0 },
"reasons": ["..."],
"decision": { "action": "challenge", "source": "policy", "ruleId": null, "ruleName": null }
}
reasonsには該当した検知項目の ID が並びます。各項目の名称はコンソールのイベント詳細に表示されます。有料プランでは一般的な検知項目を名称どおりに示し、Zerda 独自の検知手法はグループごとに 1 項目へまとめ、ID はzerda_にグループ名を続けたもの(例:zerda_consistency)になります。トライアル期間中はすべての検知項目をグループ単位で示します。valid: falseは、トークンが不明、使用済み、期限切れ、または別のサイトのものであることを示します。結果は不明として扱ってください。- ページでトークンを取得できなかった場合(
getToken()がnullを返した場合)は、この呼び出しを行わず、結果を不明として扱ってください。トークンが欠けている、または文字列でない場合は HTTP 400 を返します。空文字列は不明なトークンとして扱われ、valid: falseを返します。 decision.actionはallow、challenge(追加認証)、reduce(トライアルクレジットを付与しないなど、特典を縮小)、review(許可したうえで審査待ちに追加)、blockのいずれかです。decision.sourceは、許可リストまたは拒否リストに該当した場合はlist(listKindはip、email、domain、visitor、userのいずれか)、カスタムルールに該当した場合はrule(ruleNameにルール名)、アクション別ポリシーで決定した場合はpolicyです。- レスポンスには、独自のロジックで使える
velocity(端末と IP の直近の回数)とaccountCluster(同じ端末の直近 24 時間の関連集計。背後に 2 つ以上のアカウントがあるとcategoryがmulti_accountになります。アカウントはuserId、送られていない場合はメールアドレスで数え、registrations24hがアカウント数です)が含まれる場合があります。 - カード登録:ユーザーが決済ページからお客様のサイトに戻った後にトークンを取得し、サーバーがカードのフィンガープリントを受け取ってから
cardFingerprintを付けて検証します。レスポンスにはcard.otherAccounts30d(直近 30 日間に同じカードが登録された、お客様のサイトの他のアカウント数)が含まれます。この数はスコアに加算されません。企業では 1 枚のカードで複数のアカウントを支払うことが多いため、対応するかどうかはお客様が決めます。サーバー側でこの数を使うか、コンソールのカスタムルールで「同じカードの他のアカウント数」の下限と対応を設定してください。このアクション全体をより厳しく扱う場合は、アクション名とスコア条件付きのカスタムルールを追加してください。
判定とスコア
スコアは 6 つのグループの合計で、グループごとに上限があります。レスポンスでは groups として返されます。
| グループ | フィールド | 上限 |
|---|---|---|
| 自動化 | automation | 100 |
| 整合性 | consistency | 70 |
| 行動 | behavior | 100 |
| メールアドレス | email | 80 |
| ネットワーク | network | 80 |
| 実行環境 | environment | 25 |
合計が 100 以上なら bot、40〜99 なら suspicious、40 未満なら likely_human です。ブラウザ向けのエンドポイントはスコアや該当項目を返しません。これらは検証のレスポンスとコンソールにのみ表示されます。
ルールとアクション別ポリシー
- 許可リストと拒否リストでは、IP、メールアドレス、メールドメイン(サブドメインを含む)、訪問者 ID、ユーザー ID の単位で許可または拒否できます。両方のリストに該当した場合は拒否されます。メールアドレス、メールドメイン、ユーザー ID は、検証時に
emailとuserIdを送信した場合にのみ照合されます。変更は即時に反映されます。 - カスタムルールは優先度の数値が小さい順に評価され、最初に該当したルールで決定します。条件にはサイト、アクション、判定、スコアの範囲、シグナル、リスクグループ、メールドメイン、IP、訪問者 ID を使用でき、ルール内のすべての条件を満たす必要があります。
- 該当するルールがない場合は、アクション別ポリシーの表に従い、アクションと判定から対応を選びます。独自の行がないアクションには「Other actions」が適用されます。
既定のポリシーでは、likely_human を許可、suspicious を追加認証、bot を拒否とします。ただし claim アクションの suspicious は付与量を減らし(reduce)、post アクションの suspicious は審査に回します(review)。「Test on past events」を使うと、直近 7 日間のイベントのうちルールに該当する件数を確認できます。
トークンが null の場合
getToken() は、ネットワークエラーやタイムアウト、レート制限、許可されていないドメイン、ワークスペースの停止、トライアルの月間上限への到達、または有料プランなしでのトライアル終了の場合に null を返します。null は不明として扱い、そのまま許可または拒否するのではなく、SMS やメールの確認コード、CAPTCHA などの追加認証にユーザーを案内してください。
独自ドメインでのプロキシ
スクリプトと API を自社ドメインから提供するには、サーバーで Zerda へのリバースプロキシを設定し、各リクエストにプロキシシークレットと訪問者の IP を付加します。プロキシシークレットは「Sites」ページで作成し、サーバー上で管理してください。
location /zerda/ {
proxy_pass https://api.zerda.dev/;
proxy_set_header X-Zerda-Proxy-Secret "zps_your_proxy_secret";
proxy_set_header X-Zerda-Client-IP $remote_addr;
}
そのうえで https://your-domain/zerda/z.js?k=pk_... を読み込みます。プロキシシークレットがそのサイトに属していない場合、リクエストは拒否されます。プロキシ経由では一部のネットワークシグナルを利用できませんが、それ以外は同じように動作します。
保護バッジ
任意。バッジのスクリプトを読み込むと、ページの右下に「Zerda で保護」と、プライバシーポリシーおよび利用規約へのリンクが表示されます。バッジは表示のみを行い、データの収集やストレージへの書き込みは行いません。
<script src="https://api.zerda.dev/badge.js" async></script>
- ページに
<zerda-badge></zerda-badge>要素を置くと、その位置(フォームの下など)にバッジが表示されます。 - 表示言語は
<html lang>に従います。zhで始まる場合は中国語、jaで始まる場合は日本語、それ以外は英語で、ページの言語が切り替わると表示も更新されます。
Zerda Hold
Zerda に組み込まれた追加確認で、無料で任意に利用できます。/api/verify が返す decision.action が challenge のときにページに表示します。訪問者は点を枠の中にドラッグし、動く枠に合わせて押し続けます。数秒で完了し、新しいトークンが得られます。代わりに独自の SMS、メールなどの確認を使うこともできます。
// firstToken は、この操作で getToken() が返したトークンです
const token = await window.Zerda?.challenge(document.getElementById('verify-box'), { from: firstToken, action: 'register' }) ?? null;
// token があればバックエンドからそのトークンで /api/verify をもう一度呼び出し、null なら独自の代替確認に切り替えます
fromは 1 回目のトークンで、両方の確認が同じブラウザで行われたことの確認に使います。1 回目でトークンを取得できなかった場合は省略できます。actionはgetToken()と同じです。- Promise は、完了した場合は新しいトークンを返し、訪問者が完了できないことを選んだ場合、ウィジェットの読み込みに失敗した場合、またはネットワークエラーの場合は
nullを返します。getToken()と同じ取り決めです。ウィジェットのh.jsは、/z.jsを読み込んだのと同じ場所から必要に応じて読み込まれます。 - 新しいトークンも検証できるのは 1 回のみで、応答の形式は同じで
hold.passが加わります。この回でchallengeが再び返ることはありません。確認に不合格の場合は(許可リストによる許可を除き)対応がblockになり、合格の場合はchallengeになるはずの対応がallowになります(いずれもdecision.sourceはhold)。リストやルールによるその他の対応はそのまま適用されます。 hold.boundは、この回が 1 回目と結び付いているかどうかを示します。trueはfromで指定した 1 回目と同じブラウザで完了した場合、falseは同じブラウザではない場合(このときhold.passもfalseです)、nullはfromを渡さなかった場合です。1 回目のchallengeを受けて二次確認を求めた場合、バックエンドではhold.boundがtrueの結果だけを受け入れてください。- ウィジェットを表示してから
challenge()が結果を返すまでの間は、同じページでgetToken()を呼び出さないでください。呼び出すと、この回は確認に合格できません。 - コンテナの幅は 306〜400 px にしてください。表示言語は既定でページの言語に従います。
langにzh、ja、enを指定して選ぶこともできます。 - ウィジェットは自身の領域内の操作のみを記録します。キー入力はタイミングのみを保持し、どのキーが押されたかは記録しません。
h.jsを単独で読み込み<zerda-hold>を使う方法はデータの収集のみでトークンを発行せず、テスト専用です。
Webhook
イベントは event.evaluated、event.flagged(suspicious または bot)、event.verified、alert.fired です。各配信は JSON の POST で、Zerda-Event と Zerda-Signature ヘッダーが付きます。
Zerda-Signature の形式は t=timestamp,v1=signature です。署名シークレットで timestamp.rawBody の HMAC-SHA256(16 進数)を計算し、v1 と定数時間で比較したうえで、現在時刻から大きく離れたタイムスタンプは拒否してください。
import { createHmac, timingSafeEqual } from 'node:crypto';
function verifyZerda(rawBody, header, secret) {
if (typeof header !== 'string') return false;
const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
const expected = Buffer.from(createHmac('sha256', secret).update(`${parts.t}.${rawBody}`).digest('hex'));
const got = Buffer.from(String(parts.v1 ?? ''));
return got.length === expected.length && timingSafeEqual(got, expected)
&& Math.abs(Date.now() / 1000 - Number(parts.t)) < 300;
}
2xx のレスポンスで配信済みとみなし、それ以外は再試行します。配信状況はコンソールで確認でき、再配信も行えます。Webhook の URL は https である必要があり、プライベートアドレスやローカルアドレスは指定できません。
管理 API
「API keys」ページで zk_... キーを作成し、Authorization: Bearer zk_... を付けて /api/v1 を呼び出します。キーは自身のワークスペースにのみアクセスでき、読み取り専用または読み書き可能のいずれかです。
キーは作成時に 1 つのサイトに限定できます。限定されたキーは、そのサイトの詳細、イベント、訪問者、利用量、リクエスト数のみを読み取れます。usage の month と quota はワークスペース全体の値のままです。そのサイトのルールとすべてのサイト向けのルールを参照でき、作成、変更できるのはそのサイトのルールのみです。siteId を省略した場合もそのサイトが既定になります。アクション別ポリシーとリストはすべてのサイトに適用されるため、限定されたキーでは読み取り専用です。それ以外の操作には 403 site_key を返します。サイトを削除すると、そのサイトに限定されたキーは無効になります。
| エンドポイント | 用途 | 権限 |
|---|---|---|
GET /api/v1/workspace | ワークスペース、プラン、今月の利用量 | read |
GET /api/v1/sites | サイト | read |
GET /api/v1/overview?from=&to=&siteId=&unit= | 指定期間の概要集計、時系列バケット、内訳 | read |
GET /api/v1/events?hours=&since=&siteId=&verdict=&limit=&page=&pageSize= | イベント。1 始まりの page(および任意の pageSize、既定 50、最大 200。from、to、q などの絞り込み指定に対応)を渡すと総件数 total 付きのページ結果を返します。page を省略した場合は 1 回最大 10,000 件(続きがある場合は truncated: true)を既定で新しい順で返し、since(ミリ秒のタイムスタンプ)を指定するとそれ以降のイベントを古い順で返すため、末尾イベントの t を次の since に渡して続きを取得できます | read |
GET /api/v1/events/:id | 単一のイベント | read |
PUT /api/v1/events/:id/label | イベントにラベルを付けます。リクエスト本文は { label } で、abuse(見逃し)、fp(誤検知)、null(解除)のいずれかです | write |
POST /api/v1/events/:id/ip-check | イベントの IP を外部の検出事業者で再確認し、netType と flags を返します。ワークスペースで外部確認が有効でない場合は 403 で、ワークスペースごとに 1 時間あたりの回数上限があります | write |
GET /api/v1/visitors?from=&to=&siteId=&filter=&q=&page=&pageSize= | 訪問者のページ一覧(既定 50 件、最大 200 件) | read |
GET /api/v1/visitors/:id?page=&pageSize= | 訪問者のイベント。page を指定すると集計 summary、総件数 total、該当ページのイベントを返し、省略した場合は 1 回最大 10,000 件(続きがある場合は truncated: true)を返します | read |
DELETE /api/v1/visitors/:id?siteId= | 訪問者のすべてのデータを削除。siteId を指定するとそのサイトのデータのみ削除します。サイト限定のキーでは使えません | write |
GET /api/v1/usage?days= | 日別の利用量 | read |
GET /api/v1/health?hours= | 時間別のリクエスト数 | read |
GET /api/v1/rules | カスタムルール | read |
POST /api/v1/rules | ルールを作成 | write |
PATCH / DELETE /api/v1/rules/{id} | ルールを変更または削除 | write |
GET /api/v1/policy | アクション別ポリシー | read |
PUT / DELETE /api/v1/policy | アクション別ポリシーを置き換え、または初期化。PUT の本文は { policy: { シーン名: { likely_human, suspicious, bot, unknown } } } で、記載のないシーンには _default が使われます。policy がない場合は 400 | write |
GET /api/v1/lists | 許可リストと拒否リスト | read |
POST /api/v1/lists | エントリを追加:{ kind, value, action, note } または { entries: [...] } | write |
DELETE /api/v1/lists/{id} | エントリを削除 | write |
制限とクォータ
- トークンの有効期間は 5 分で、検証は一度だけ行えます。
- 同じ IP から短時間に多数のリクエストがあるとレート制限がかかり、
getToken()はnullを返します。 - 月間の評価回数はワークスペースのプランによって決まり、コンソールに表示されます。トライアルは上限に達するとトークンの発行を停止し、有料プランなしで終了した後は発行されません。有料プランは停止しません。
- イベントはワークスペースの保存期間中保持され、それより古いデータは 1 時間ごとに削除されます。
データとプライバシー
- 訪問者の IP は受信したままの形でイベントとともに保存され、コンソールでの表示、検索、外部での再確認に使われ、イベントと同じ期間保持されます。回数の集計と紐付けには IP の HMAC ハッシュのみを使用します。
- スクリプトは、セキュリティのためだけに同一端末を識別する目的で、お客様のドメインにファーストパーティ Cookie
_dpr_s(有効期間 1 年)とブラウザストレージを設定します。 - 保存するリクエストヘッダーは許可リストに含まれるもののみです。キーボードイベントはキーを押していた時間のみを保持し、どのキーか、何が入力されたかは記録しません。
- 検証時に送信されたメールアドレスとユーザー ID は、コンソールで表示、検索できるようイベントとともに保存されます。イベントと同じ期間保持され、コンソールで訪問者を削除すると一緒に削除されます。
- 削除依頼に対応するため、コンソールまたは API から訪問者のすべてのデータを削除できます。詳しくはプライバシーポリシーと DPA をご覧ください。
ご不明な点は、コンソールからチケットを送信してください。