Zerda 文档

Zerda 保护注册、登录、试用申领和内容发布等接口,识别自动化工具、伪造的浏览器环境和批量账号。网页取一个一次性令牌,你的后端用核验密钥换回判定结果和建议的处置方式。

快速接入

  1. 使用 Zerda 开通的账号登录控制台,在「站点接入」中新建站点,记下公开密钥 pk_... 和核验密钥 sk_...。核验密钥只显示一次。
  2. 把站点的域名加进「允许的域名」。留空表示不限制,正式上线前建议填写。
  3. 在表单页面加载脚本,提交前调用 Zerda.getToken(),把令牌随表单发给你的后端。
  4. 后端调用 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:

维度字段上限
自动化痕迹automation100
环境一致性consistency70
行为behavior100
邮箱email80
网络network80
运行环境environment25

总分不低于 100 判为 bot,40 到 99 为 suspicious,低于 40 为 likely_human。网页端接口不返回分数和命中原因,这些信息只出现在核验结果和控制台里。

规则与场景策略

处置方式按以下顺序决定:

  1. 放行与拒绝名单:按 IP、邮箱、邮箱域名(含子域名)、访客标识或用户 ID 直接放行或拒绝,两边都命中时按拒绝处理。邮箱、邮箱域名和用户 ID 只有在核验时传入 email、userId 才能匹配。名单修改后立即生效。
  2. 自定义规则按优先级从小到大匹配,命中第一条即采用它的处置。条件可以是站点、场景、判定、分数区间、命中信号、风险维度、邮箱域名、IP 和访客标识,同一条规则中的条件需要同时满足。
  3. 没有命中规则时,查场景策略表:按场景和判定取处置方式。未单独配置的场景使用「其他场景」一行。

默认策略为: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

  1. 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 key sk_.... The secret key is shown once.
  2. Add your domains to Allowed domains. Empty means any domain; fill it in before going live.
  3. Load the script on the form page, call Zerda.getToken() before submitting and send the token to your backend with the form.
  4. Your backend calls POST /api/verify and allows, challenges or blocks based on decision.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, or null on failure. It never throws. Pass undefined as 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.Zerda does not exist. Write window.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.action names the action, such as register, login or checkout. It is used for per-action stats and the action policy. Letters, digits, underscores and hyphens only.
  • options.signal takes an AbortSignal; an aborted call resolves to null. Without one, the call waits at most 15 seconds and then resolves to null.
  • 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"}'
FieldMeaning
tokenRequired. The token from the page. Each token verifies once and expires after 5 minutes.
emailOptional. The submitted email, used for email risk checks and to link accounts that belong together; the console shows and searches accounts by it.
userIdOptional. 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.
cardFingerprintOptional. 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.
actionStrongly 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 }
}
  • reasons lists 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 ID zerda_ followed by the group (for example zerda_consistency); during a trial every check is listed by group.
  • valid: false means 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() returned null), 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 returns valid: false.
  • decision.action is one of allow, challenge (second check), reduce (grant less, for example no trial credit), review (allow and queue for review) and block.
  • decision.source is list when the allow or block list matched (listKind is ip, email, domain, visitor or user), rule when a custom rule matched (ruleName names it) and policy when the action policy decided.
  • The response may also include velocity (recent counts for the device and IP) and accountCluster (counts for the same device over the last 24 hours: category is multi_account when two or more accounts are behind it, counted by userId, or by email when none was sent; registrations24h is 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 includes card.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.
Keep the secret key on your server. Never put it in a web page, an app bundle or a public repository. Rotate it in the console if it leaks.

Verdicts and scores

The score adds up six groups, each with its own cap, reported as groups in the response:

GroupFieldCap
Automationautomation100
Consistencyconsistency70
Behaviorbehavior100
Emailemail80
Networknetwork80
Environmentenvironment25

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

  1. 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 email and userId to verify. Changes apply at once.
  2. 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.
  3. 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 with zh, Japanese when it starts with ja, 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
  • from is 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. action is the same as in getToken().
  • The promise resolves to the new token when completed, or to null when the visitor chooses that they cannot complete it, the widget fails to load, or the network fails, the same contract as getToken(). The widget's h.js is loaded on demand from where /z.js was loaded.
  • The new token can be verified once, in the same format plus hold.pass. This round never returns challenge again: when the check fails, the decision becomes block unless allowlisted; when it passes, a decision that would be challenge becomes allow, both with decision.source hold. Other actions from your lists and rules still apply.
  • hold.bound tells whether this round is tied to the first one: true when it ran in the same browser as the first round named by from, false when it did not (hold.pass is then false as well), and null when from was not passed. If your backend asked for this check because the first round returned challenge, accept only results whose hold.bound is true.
  • From the moment the widget is shown until challenge() resolves, do not call getToken() 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 lang to zh, ja or en to choose.
  • The widget records only interaction inside its own area. Key presses keep only their timing, never which key. Loading h.js on 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.

EndpointPurposeScope
GET /api/v1/workspaceWorkspace, plan and this month's usageread
GET /api/v1/sitesSitesread
GET /api/v1/overview?from=&to=&siteId=&unit=Overview totals, time-series buckets and breakdowns for a windowread
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 sinceread
GET /api/v1/events/:idOne eventread
PUT /api/v1/events/:id/labelLabel an event with body { label }: abuse (missed abuse), fp (false positive) or null (clear)write
POST /api/v1/events/:id/ip-checkRe-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 workspacewrite
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 keyswrite
GET /api/v1/usage?days=Daily usageread
GET /api/v1/health?hours=Hourly request countsread
GET /api/v1/rulesCustom rulesread
POST /api/v1/rulesCreate a rulewrite
PATCH / DELETE /api/v1/rules/{id}Change or delete a rulewrite
GET /api/v1/policyAction policyread
PUT / DELETE /api/v1/policyReplace 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 policywrite
GET /api/v1/listsAllow and block listsread
POST /api/v1/listsAdd entries: { kind, value, action, note } or { entries: [...] }write
DELETE /api/v1/lists/{id}Remove an entrywrite

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 to null.
  • 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 は、新規登録、ログイン、トライアル、投稿などのエンドポイントを、自動化ツール、偽装されたブラウザ環境、大量のアカウントから保護します。ページでワンタイムトークンを取得し、バックエンドがシークレットキーを使ってトークンを判定と推奨アクションに交換します。コンソールは現在、英語と中国語で提供しています。

クイックスタート

  1. Zerda が用意したアカウントでコンソールにサインインし、「Sites」でサイトを作成します。公開キー pk_... とシークレットキー sk_... を控えてください。シークレットキーは一度しか表示されません。
  2. 「Allowed domains」にドメインを追加します。空欄の場合はすべてのドメインが許可されるため、本番公開の前に必ず設定してください。
  3. フォームのページでスクリプトを読み込み、送信前に Zerda.getToken() を呼び出して、トークンをフォームと一緒にバックエンドへ送信します。
  4. バックエンドで 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 として返されます。

グループフィールド上限
自動化automation100
整合性consistency70
行動behavior100
メールアドレスemail80
ネットワークnetwork80
実行環境environment25

合計が 100 以上なら bot、40〜99 なら suspicious、40 未満なら likely_human です。ブラウザ向けのエンドポイントはスコアや該当項目を返しません。これらは検証のレスポンスとコンソールにのみ表示されます。

ルールとアクション別ポリシー

  1. 許可リストと拒否リストでは、IP、メールアドレス、メールドメイン(サブドメインを含む)、訪問者 ID、ユーザー ID の単位で許可または拒否できます。両方のリストに該当した場合は拒否されます。メールアドレス、メールドメイン、ユーザー ID は、検証時に email と userId を送信した場合にのみ照合されます。変更は即時に反映されます。
  2. カスタムルールは優先度の数値が小さい順に評価され、最初に該当したルールで決定します。条件にはサイト、アクション、判定、スコアの範囲、シグナル、リスクグループ、メールドメイン、IP、訪問者 ID を使用でき、ルール内のすべての条件を満たす必要があります。
  3. 該当するルールがない場合は、アクション別ポリシーの表に従い、アクションと判定から対応を選びます。独自の行がないアクションには「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 がない場合は 400write
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 をご覧ください。

ご不明な点は、コンソールからチケットを送信してください。