Verificação no servidor
O navegador nunca decide nada: ele carrega uma prova até o seu backend. Há três jeitos de conferir, do mais simples ao que não faz chamada nenhuma.
| Jeito | Chamada de rede | O que você recebe | Quando usar |
|---|---|---|---|
POST /v1/verify | 1, com sk_ | resumo: visitante, nota, risco, bot | começo rápido |
| token local | nenhuma | o mesmo resumo | alto volume, latência mínima |
| resultado lacrado | nenhuma | o evento inteiro, com todos os sinais | regra fina sem chamada extra |
GET /v1/events/:requestId | 1, com sk_ | o evento inteiro | auditoria, regra fina |
1. Pela API
curl -X POST https://siftil.com/v1/verify \
-H 'authorization: Bearer sk_…' -H 'content-type: application/json' \
-d '{"token": "rst1.…"}'{ "valid": true, "rid": "fd15e76e…", "vid": "rv_2fa950ff…", "ss": 15, "risk": "high", "bot": false, "new": true, "iat": 1795314726 }Token adulterado, de outra conta ou com mais de 10 minutos volta { "valid": false } com status 400.
2. Token conferido localmente
O token tem o formato rst1.<corpo>.<assinatura>:
corpo= base64url do JSON{ rid, vid, ss, risk, bot, new, iat };assinatura= base64url(HMAC-SHA256(segredo do token,"rst1." + corpo)).
Pegue o segredo do token no painel (ou em GET /v1/account → tokenSecret).
Node, Bun, Deno, Workers
import { createHmac, timingSafeEqual } from 'node:crypto'
export function verifySiftil(token, secret, maxAge = 600) {
const [v, body, sig] = String(token).split('.')
if (v !== 'rst1' || !body || !sig) return null
const want = createHmac('sha256', secret).update('rst1.' + body).digest('base64url')
if (want.length !== sig.length || !timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return null
const p = JSON.parse(Buffer.from(body, 'base64url').toString())
return Date.now() / 1000 - p.iat <= maxAge ? p : null
}Python
import base64, hmac, hashlib, json, time
def verify_siftil(token: str, secret: str, max_age: int = 600):
try:
v, body, sig = token.split('.')
except ValueError:
return None
if v != 'rst1':
return None
want = base64.urlsafe_b64encode(hmac.new(secret.encode(), f'rst1.{body}'.encode(), hashlib.sha256).digest()).rstrip(b'=').decode()
if not hmac.compare_digest(want, sig):
return None
p = json.loads(base64.urlsafe_b64decode(body + '=' * (-len(body) % 4)))
return p if time.time() - p['iat'] <= max_age else NoneGo
func VerifySiftil(token, secret string, maxAge int64) (map[string]any, bool) {
parts := strings.Split(token, ".")
if len(parts) != 3 || parts[0] != "rst1" {
return nil, false
}
m := hmac.New(sha256.New, []byte(secret))
m.Write([]byte("rst1." + parts[1]))
want := base64.RawURLEncoding.EncodeToString(m.Sum(nil))
if !hmac.Equal([]byte(want), []byte(parts[2])) {
return nil, false
}
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, false
}
var p map[string]any
if json.Unmarshal(raw, &p) != nil {
return nil, false
}
iat, _ := p["iat"].(float64)
return p, time.Now().Unix()-int64(iat) <= maxAge
}PHP
function verify_siftil(string $token, string $secret, int $maxAge = 600): ?array {
$p = explode('.', $token);
if (count($p) !== 3 || $p[0] !== 'rst1') return null;
$b64u = fn($s) => rtrim(strtr(base64_encode($s), '+/', '-_'), '=');
if (!hash_equals($b64u(hash_hmac('sha256', 'rst1.' . $p[1], $secret, true)), $p[2])) return null;
$data = json_decode(base64_decode(strtr($p[1], '-_', '+/')), true);
return (time() - $data['iat'] <= $maxAge) ? $data : null;
}3. Resultado lacrado
server.sealed é o evento inteiro cifrado com AES-256-GCM: rss1.<base64url(iv de 12 bytes ‖ texto cifrado ‖ tag de 16 bytes)>. A chave AES é o SHA-256 da sua chave do lacre (texto). Só quem tem a chave abre; o navegador só carrega.
import { createHash, createDecipheriv } from 'node:crypto'
export function unsealSiftil(sealed, sealKey) {
if (!sealed.startsWith('rss1.')) return null
const b = Buffer.from(sealed.slice(5), 'base64url')
const key = createHash('sha256').update(sealKey).digest()
const d = createDecipheriv('aes-256-gcm', key, b.subarray(0, 12))
d.setAuthTag(b.subarray(b.length - 16))
return JSON.parse(Buffer.concat([d.update(b.subarray(12, b.length - 16)), d.final()]).toString())
}# pip install cryptography
import base64, hashlib, json
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def unseal_siftil(sealed: str, seal_key: str):
b = base64.urlsafe_b64decode(sealed[5:] + '=' * (-len(sealed[5:]) % 4))
key = hashlib.sha256(seal_key.encode()).digest()
return json.loads(AESGCM(key).decrypt(b[:12], b[12:], None))O evento lacrado tem o mesmo formato de GET /v1/events/:requestId (veja Evento). Confira t (milissegundos) para não aceitar evento velho, e guarde o requestId para não aceitar o mesmo duas vezes.
Como decidir
Uma regra inicial que funciona na maioria dos cadastros:
const e = unsealSiftil(body.siftilSealed, process.env.SIFTIL_SEAL_KEY) // ou GET /v1/events/:id
if (!e || Date.now() - e.t > 10 * 60_000) return exigirVerificacao()
if (e.suspect.risk === 'high') return bloquearOuRevisar(e.suspect.reasons)
if (e.signals.multiAccount) return limitarTesteGratis(e.visitorId)
if (e.suspect.risk === 'medium') return exigirVerificacao() // e-mail, SMS
return liberar()- Não bloqueie só por
medium: VPN corporativa, aba anônima e fuso diferente sozinhos são comuns em gente honesta. Peça uma verificação a mais. - Use o
visitorIdcomo chave de limite: um teste grátis por aparelho, N cadastros por aparelho por dia. - Guarde
requestIdevisitorIdna sua tabela de cadastros e pedidos. Fica fácil rotular depois e responder a chargeback. - Rede institucional: hospital, empresa e universidade aparecem em
signals.network. Muitos usuários no mesmo IP ali é normal, e a nota já não pune isso.
Siftil · documentação da API v1