Cipher SDK and API
Validate survey responses from your own application.
The Cipher API lets you score responses you collect anywhere, not just inside Surbee. Send a response plus the behavioral signals you captured, and Cipher returns a quality score and a recommendation.
You will need an API key first. See API keys.
Install the SDK
pnpm add @surbee/cipherimport { Cipher } from '@surbee/cipher';
const cipher = new Cipher({
apiKey: process.env.CIPHER_API_KEY!, // cipher_sk_...
level: 2, // 1 Basic, 2 Pro, 3 Max. Defaults to 2
thresholds: { fail: 0.5, review: 0.75 }, // optional, defaults to { fail: 0.4, review: 0.7 }
// endpoint: 'https://www.surbee.dev/v1/cipher', // optional, this is the default
});How scoring works
Every level is scored on Surbee's servers, so the SDK is a thin client: it collects the response and behavioral signals and sends them to Cipher. The detection logic, weights, and thresholds are never shipped to your client and can't be inspected or reverse-engineered. That matters, since the people you are screening are exactly the ones who would read a local bundle.
The difference between levels is what runs:
- Basic (1) runs fast checks for speed, careless patterns, attention, pasting, automation and device spoofing, with no AI review. It returns in milliseconds and is free.
- Pro (2) adds how each written answer was produced (typed, revised, pasted or copied out, how fast and when), hidden characters, typing rhythm, tab switching, pointer, hover and scroll behavior, sentence rhythm, contradictions, copied text and a light AI review. It costs per response.
- Max (3) adds checks across responses (fraud rings, shared answers, coordinated timing, shared devices), network checks (VPN, datacenter, Tor, proxy, timezone), a thorough AI review, and a web search for long written answers that match text already published online. Questions that ask people to quote, cite sources, or paste text are skipped.
AI-written answers are caught from behavior: how each answer originated, where it came from, whether it was typed or pasted, how quickly, and when.
Because everything is server-side, an API key is required for every level. Treat any client-side signal collection as input only, never as a trusted score.
The older tier option (1 to 5) still works and maps to levels: tiers 1 and 2
to Basic, tier 3 to Pro, tiers 4 and 5 to Max. level wins when both are set.
cipher.getLevelInfo().checks; // CheckId[] the configured level runs
cipher.getLevelInfo().usesAI; // false for Basic, true for Pro and Max
cipher.estimateCost(); // per-response price (0 for Basic)Validate a response
POST /api/cipher/validate runs the checks for the requested level and returns a
verdict. Authenticate with a bearer token.
Request
{
"level": 2,
"thresholds": { "fail": 0.5, "review": 0.75 },
"input": {
"responses": [
{ "question": "Would you recommend us?", "answer": "Yes" },
{ "question": "What stood out?", "answer": "It saved me time", "responseTimeMs": 8200 }
],
"behavioralMetrics": { },
"deviceInfo": { },
"context": { }
}
}- level. Which set of checks to run: 1 Basic, 2 Pro or 3 Max. Must be within your key's level limit. Older clients may send
tierfrom 1 to 5 instead. - thresholds.
failis the minimum score to keep a response.reviewis the score above which a response is accepted without review. - input. The response data plus any behavioral, device, and context signals you captured.
Response
{
"score": 0.91,
"passed": true,
"recommendation": "keep",
"confidence": 0.62,
"flags": [],
"summary": {
"verdict": "High-quality legitimate response",
"issues": [],
"positives": ["Response timing appears natural", "No automation tools detected"],
"suggestion": "Response can be accepted as-is"
},
"checks": [
{ "checkId": "rapid_completion", "passed": true, "score": 0, "details": null },
{ "checkId": "writing_process", "passed": true, "score": 0, "details": null }
],
"perQuestion": {
"q2": { "writing": "composed", "analysisMs": 0.014 }
},
"meta": {
"tier": 2,
"processingTimeMs": 41,
"analysisMs": 0.12,
"checksRun": 15,
"checksPassed": 15,
"requestId": "req_ab12cd34",
"timestamp": 1730000000000
}
}Key fields:
- score. Quality from 0 to 1, where higher is better. This is the inverse of risk.
- recommendation. One of
keep,review, ordiscard, derived from your thresholds. - flags. Human readable names of any checks that failed.
- summary. A plain language verdict with the issues, positive signals, and a suggested action.
- checks. The per check breakdown. A check marked
skippeddid not have the data it needs, such as mouse movement from a phone. - perQuestion. What Cipher found on each question, keyed by
questionId(orq1,q2and so on): how the answer was written (typed,composed,pasted,transcribedoruntyped), any hidden characters or chatbot phrasing, and the time spent analysing it. - meta.tier. The level that ran, from 1 to 3.
- meta.analysisMs. Time the engine spent on the whole response, separate from network time.
Cipher scores SDK requests with the same engine as surveys hosted on Surbee, so every check described in these docs applies to both.
To get perQuestion.writing, collect signals with CipherTracker and call tracker.questionStart(questionId) as each question appears, or put data-question-id on the element that wraps each question.
Example
// level and thresholds come from the new Cipher({ ... }) config above.
// validate() takes just the response data.
const result = await cipher.validate({
responses: [
{ question: 'Would you recommend us?', answer: 'Yes' },
{ question: 'What stood out?', answer: 'It saved me time', responseTimeMs: 8200 },
],
behavioralMetrics, // optional, from the client-side tracker
deviceInfo, // optional
context, // optional
});
if (result.recommendation === 'discard') {
// reject or quarantine the response
} else if (result.recommendation === 'review') {
// queue for a human to look at
}Validate a batch
When you have many responses at once (a finished study, a nightly job, a CSV
export), send them together with validateBatch. On top of scoring each
response, a batch can run cross-respondent fraud detection: identical answers
across people, synchronized timing, and shared devices. Cross-analysis is on by
default at Max and opt-in below it.
const batch = await cipher.validateBatch({
submissions: rows.map((r) => ({
responses: r.responses,
behavioralMetrics: r.metrics,
deviceInfo: r.device,
})),
crossAnalysis: true,
});
console.log(batch.summary); // { total, passed, review, failed, avgScore }
console.log(batch.fraudIndicators); // { duplicateAnswers, coordinatedTiming, deviceSharing, fraudRingScore }
const clean = batch.results.filter((r) => r.recommendation === 'keep');One credit is charged per submission. fraudIndicators is only returned when
cross-analysis runs (Max, or crossAnalysis: true).
Network checks (IP reputation)
The Max network checks (datacenter IP, VPN, Tor, proxy) use IPQualityScore. Two things turn them on:
-
Pass the respondent's IP. Capture it server-side when you collect the response (for example
req.headers['x-forwarded-for']) and send it ascontext.ipAddress. The IP of your call to Cipher is your own server, so we never use it.await cipher.validate({ responses, deviceInfo, context: { ipAddress: respondentIp }, // the survey taker's IP }); -
Set the key on the Surbee server. Network lookups run server-side with an
IPQS_API_KEYenvironment variable. Get one by creating a free account at ipqualityscore.com (the free tier covers about 5,000 lookups per month). The key is on the Proxy & VPN Detection API settings page in the dashboard.
Without an IP or without the key, the network checks are skipped (they never produce a false positive). All other checks are unaffected.
Build a complete integration
A production setup has three pieces: capture signals in the browser, validate on your server, then act on the verdict. Never call Cipher straight from the browser with a secret key. The browser only collects signals; your server does the scoring.
1. Capture behavior in the browser
You do not need a separate library. Collect the handful of signals the checks read and post them to your own API alongside the answers.
// useBehaviorTracker.ts (client)
export function startTracker() {
const startedAt = Date.now();
let keypressCount = 0, backspaceCount = 0, pasteEvents = 0, tabSwitchCount = 0;
const onKey = (e: KeyboardEvent) => { keypressCount++; if (e.key === 'Backspace') backspaceCount++; };
const onPaste = () => { pasteEvents++; };
const onBlur = () => { tabSwitchCount++; };
document.addEventListener('keydown', onKey);
document.addEventListener('paste', onPaste);
window.addEventListener('blur', onBlur);
return {
stop() {
document.removeEventListener('keydown', onKey);
document.removeEventListener('paste', onPaste);
window.removeEventListener('blur', onBlur);
return {
metrics: {
sessionId: crypto.randomUUID(),
duration: Date.now() - startedAt,
keypressCount, backspaceCount, pasteEvents, tabSwitchCount,
},
device: {
userAgent: navigator.userAgent,
platform: navigator.platform,
language: navigator.language,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
screenWidth: screen.width,
screenHeight: screen.height,
webDriver: navigator.webdriver === true,
},
};
},
};
}2. Validate on your server
// app/api/survey/submit/route.ts (Next.js App Router)
import { Cipher } from '@surbee/cipher';
import { NextResponse } from 'next/server';
const cipher = new Cipher({ apiKey: process.env.CIPHER_API_KEY!, level: 3 });
export async function POST(req: Request) {
const { answers, metrics, device } = await req.json();
const result = await cipher.validate({
responses: answers, // [{ question, answer, responseTimeMs? }]
behavioralMetrics: metrics,
deviceInfo: device,
});
if (result.recommendation === 'discard') {
return NextResponse.json({ ok: false, reason: result.summary.verdict }, { status: 422 });
}
await saveResponse({ answers, cipher: { score: result.score, recommendation: result.recommendation, flags: result.flags } });
return NextResponse.json({ ok: true });
}3. Act on the verdict
Store the score with every response so you can filter later, and route the in-between cases to a human instead of throwing them away.
switch (result.recommendation) {
case 'keep': await accept(response); break;
case 'review': await sendToReviewQueue(response, result.flags); break;
case 'discard': await quarantine(response, result.summary); break;
}Pick a level
| You need | Level | Cost |
|---|---|---|
| Catch bots, speeders and careless answers, free | 1 Basic | Free |
| The above plus AI-written answers, contradictions and low-quality text | 2 Pro | Per response |
| Everything, plus fraud rings, network checks and a web search for copied answers | 3 Max | Highest |
Start at the lowest level that meets your need and move up if junk is getting
through. The API takes level on every call. In the SDK, each Cipher
instance runs one level, so create a second instance for a different level.
Quick examples
For drop-in recipes (React form, Next.js route, Express, dataset screening, retry logic, browser capture), see Quick examples.
Predict with the ML model
POST /api/cipher/predict returns the machine learning model's fraud
probability for a stored response. Useful when you have already extracted
features and want the model's view directly.
Request
{ "responseId": "resp_123", "modelVersion": "latest" }Response
{
"fraudProbability": 0.08,
"fraudVerdict": "low_risk",
"confidence": 0.74,
"topSignals": [
{ "feature": "completionTimeSeconds", "contribution": 0.03, "value": 142 }
],
"modelVersion": "2025.11",
"inferenceTimeMs": 12
}- fraudProbability. 0 to 1, where higher means more likely fraudulent.
- fraudVerdict.
low_risk,medium_risk,high_risk, orfraud. - topSignals. The features that contributed most to the prediction.
Errors
| Code | Meaning |
|---|---|
INVALID_API_KEY | Missing, malformed, or inactive key |
INSUFFICIENT_CREDITS | The key has no credits left |
TIER_NOT_AVAILABLE | Requested a level above the key's limit |
SERVER_ERROR | Something went wrong on our side |
Health check
GET /api/cipher/health returns the service status, for uptime monitoring.
{ "status": "operational", "service": "cipher", "version": "1.0.0" }