# OpenContext developers: full guides Source: https://docs.opencontext.com/llms.txt --- # Overview Source: https://docs.opencontext.com/start/ OpenContext gives your product a fraud team in a box. At the moments that matter (a sign-up, a login, an application, a checkout, a payout), one API call tells you: - **Who is acting:** a person, a customer's AI agent, a good bot, or a bad bot, with the agent named and how we know. - **Which device:** a stable device ID, recognized again on every return visit, and how it links to your accounts. - **How risky it is:** a 0 to 1000 risk score, a trust score from good history, reason codes, and a recommendation from your own rules. When you later learn what happened, you report it as an outcome, and every later decision sees that history. ## The moving parts | Part | Where it runs | What it does | | --- | --- | --- | | Browser tag | Your web pages | Collects device and interaction signals, returns a `request_id` | | Decision API | Your server calls it | Returns the decision for an event | | Outcomes API | Your server calls it | Records what happened after a decision | | Rules | The console | Turns scores and facts into your recommendation, per event type | | MCP server | Your agents call it | Tools over decisions, devices, accounts, cases, and the review queue; read only unless the key allows casework | | Console | Your team's browser | Keys, rules, transactions, the review queue, and the fraud manager | ## Environments Every account has two environments. **Sandbox** keys (`oc_test_…`) see sandbox data only, so you can build and test freely. **Live** keys (`oc_live_…`) handle real traffic. Rulesets are kept separately per environment. ## Getting access We onboard every customer personally. [Request early access](https://www.opencontext.com/early-access) and we will set up your account, then you create your own keys in the console. ## Working with a coding agent These docs are written to be read by coding agents as well as people. Point your agent at [https://docs.opencontext.com/llms.txt](https://docs.opencontext.com/llms.txt): it lists every page with a one-line summary, and each page has a Markdown copy at the same address ending in `.md` (this page is [https://docs.opencontext.com/start.md](https://docs.opencontext.com/start.md)). Everything in one file is at [https://docs.opencontext.com/llms-full.txt](https://docs.opencontext.com/llms-full.txt), and the API contract is at [https://docs.opencontext.com/openapi.yaml](https://docs.opencontext.com/openapi.yaml). Next: the [quickstart](https://docs.opencontext.com/start/quickstart/). --- # Quickstart Source: https://docs.opencontext.com/start/quickstart/ This walks through a sign-up form, end to end, in the sandbox. You need a sandbox account and access to the console. ## 1. Create your keys In the console, open **API keys** and create two sandbox keys: - A **publishable site key** (`oc_pk_test_…`) for the browser tag. It is public by design and can only send signals. Add your site's hostname to its allowed domains (a sandbox key with no domains accepts any origin, for quick setup). - A **secret key** (`oc_test_…`) with the `decide` and `outcomes` scopes, for your server. It is shown once; store it in your secret manager. ## 2. Add the tag to your page Load the tag on the page with your form, and mark the form with `data-collect`: ```html
``` When the form is submitted, the tag collects signals, adds a hidden `request_id` field, and submits the form. If anything goes wrong it submits anyway, so the tag never blocks a customer. For production, serve the tag from a path on your own site; see [Browser tag](https://docs.opencontext.com/guides/browser-tag/#serve-it-from-your-own-site). ## 3. Ask for a decision On your server, read `request_id` from the form and call the decision API with your secret key: ```sh curl https://api.opencontext.com/v1/decision \ -H "Authorization: Bearer $SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "request_id": "req_01M8YGM5XB0RJ7S2N1Q4ZK6W3D", "event_type": "signup", "account_id": "cust_1842", "email": "pat@example.com", "ip": "198.51.100.7", "user_agent": "Mozilla/5.0 ..." }' ``` The same call in Node: ```js const res = await fetch("https://api.opencontext.com/v1/decision", { method: "POST", headers: { Authorization: `Bearer ${process.env.SECRET_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ request_id: req.body.request_id, event_type: "signup", account_id: user.id, email: req.body.email, ip: req.ip, user_agent: req.get("user-agent"), }), signal: AbortSignal.timeout(1500), }); const decision = await res.json(); ``` ## 4. Act on the recommendation ```js switch (decision.recommendation) { case "allow": return createAccount(); case "step_up": return askForVerification(); // email code, passkey, or agent proof case "review": return createAccount({ hold: true }); // your team or the fraud manager reviews it case "deny": return refuse(); } ``` Keep `decision.decision_id` with the account or order. You will report outcomes against it. ## 5. Report what happened When you learn more (a chargeback, a good repayment, an analyst's call), tell us: ```sh curl https://api.opencontext.com/v1/outcomes \ -H "Authorization: Bearer $SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "request_id": "dec_01M8YGM5XC012R9ZCQKTSX9RR7", "outcome": "confirmed_good", "outcome_type": "paid_in_full" }' ``` ## For coding agents If an agent is doing this integration, these are the facts it needs: - **Keys come from environment variables.** The secret key (`oc_test_…`) stays on the server; only the publishable key (`oc_pk_test_…`) goes in the page. Sandbox keys see sandbox data only, so testing is safe. - **The tag never blocks a form** and the decision call should never block your product: use a timeout of about 1.5 seconds and pick a fallback per event type (most teams allow logins and sign-ups for review, and hold payouts). - **To verify the integration,** submit the form once and look for the decision in the console's **Transactions** page. A `no_request_id` warning on the decision means the tag did not run. - **Every error has a stable `code`** and says how to fix it. See [Errors](https://docs.opencontext.com/reference/errors/). - **A person turns on production.** An agent can integrate and test in the sandbox; live keys are created by a person on the account. - Task-sized guides: [sign-up in Next.js](https://docs.opencontext.com/recipes/signup-nextjs/), [AI agents at login](https://docs.opencontext.com/recipes/login-agents/), and [credential stuffing](https://docs.opencontext.com/recipes/credential-stuffing/). Machine-readable docs: [https://docs.opencontext.com/llms.txt](https://docs.opencontext.com/llms.txt) and the [OpenAPI contract](https://docs.opencontext.com/openapi.yaml). ## What to read next - [How it works](https://docs.opencontext.com/start/how-it-works/): the flow from page to decision. - [Decisions](https://docs.opencontext.com/guides/decisions/): every field in the response, and how to use it. - [Rules](https://docs.opencontext.com/guides/rules/): change what the recommendation is for each event type. --- # How it works Source: https://docs.opencontext.com/start/how-it-works/ ```text Browser Collector Your server Decision API ─────── ───────── ─────────── ──────────── page loads the tag ───────▶ POST /v1/collect recognizes the device form gets request_id ◀────── returns request_id form submits ───────────────────────────────────▶ reads request_id POST /v1/decision ───────▶ joins the collection, your history, and your rules acts on it ◀────────────── recommendation, agent, device, reasons later: chargeback, review, repayment ─────────────▶ POST /v1/outcomes ───────▶ history for the next decision ``` ## The steps 1. **The tag runs in the browser.** It gathers device, browser, and interaction signals (counts and timings, never what someone types) and posts them to the collector with your publishable site key. 2. **The collector recognizes the device.** It stores a signed device token in first-party storage on your site, so the device is recognized again on return visits, and answers with a `request_id`. 3. **Your server asks for a decision.** It sends the `request_id`, the event type, your account ID, and what it saw (IP, user agent, and optionally email, phone, and an amount with its currency). 4. **We decide in one pass.** The decision joins the collection with the agent verdict, local network data, how this device and account link to your other accounts, the outcomes you reported before, and your ruleset for that event type. No step on this path waits on an outside service, and the target is p99 at or under 100 ms. 5. **You act, then report.** You follow the recommendation, and later report outcomes. Those become history: a device you reported for fraud scores as a bad actor next time; a device and account you marked as a good customer earns trust. ## The model behind every decision Every part of the platform works from one model of a transaction, the fraud ontology: an agent, on a device, for an account, makes a transaction that ends in an outcome. The decision API, rules, scores, the fraud manager, the console, and the MCP tools all read and write the same model. | Thing | What it is | In the API | | --- | --- | --- | | Agent | A person, an AI agent, a good bot, or a bad bot, with its operator, who it acts for, and the evidence | `bot` in the decision | | Device | One device ID per browser, recognized on return, with first seen, last seen, and visit count | `device` in the decision | | Account | Your own account ID | `account_id` in the request | | Contact details | Email (shown in your console, matched by a keyed token) and phone (a keyed token) | `email`, `phone`, or `identities` in the request | | Transaction | A signup, login, application, checkout, password reset, account change, or payout, with an optional amount | `event_type` and `amount` in the request | | Outcome | What happened next: fraud, abuse, or good, with who was the bad actor and who was the victim | `POST /v1/outcomes` | The links between them are what the decision uses: how many accounts a device has opened, how many devices an account uses, how many devices share an email or phone, and the outcomes reported on any of them before. Links are counted over 24 hours, 7, 30, and 90 days, and are kept per customer. ## What stays with you Your data is yours. Devices, links, and history are kept per customer and per environment: another customer never sees them, and a sandbox key never sees live data. Email and phone are matched by keyed tokens; the email is kept so your team sees it on each transaction, and the phone is never stored raw. Models shared across customers never see either. See [Data you send](https://docs.opencontext.com/reference/data/). --- # Browser tag Source: https://docs.opencontext.com/guides/browser-tag/ The browser tag is a small script that recognizes the device and notices automation on the pages where people sign up, sign in, apply, or pay. It sends what it gathers to the collector and gives your form a `request_id`. Your server passes that ID to the [decision API](https://docs.opencontext.com/guides/decisions/), which is how a decision knows the device. The tag reads counts and timings (how the pointer moved, how long typing took), never what someone types. ## Add it to a page ```html ``` `data-key` is your **publishable site key**. It is safe in a page: it can only send signals, and only from the domains you allow on the key. ## Attach it to forms Mark each protected form with `data-collect`, naming the event: ```html ``` On submit, the tag collects, adds a hidden input named `request_id`, and submits the form. Your server reads `request_id` like any other field. | Hidden field | Value | | --- | --- | | `request_id` | The ID to send with the decision. Empty if collection failed. | | `request_id_error` | Why there is no ID (`timeout`, `invalid_site_key`, `origin_not_allowed`, …), for your own logs. | ### Single-page apps For forms you submit with script, call the tag yourself and add the ID to your request: ```js const { request_id } = await window.__dc.collect("signup"); await fetch("/api/signup", { method: "POST", body: JSON.stringify({ ...form, request_id }) }); ``` `collect(event)` always resolves. When something fails it resolves with `request_id: null` and an `error`, after at most the timeout, so your flow carries on. You can also attach a form you render later: `window.__dc.attach(formElement, "checkout")`. ## Options Set these as `data-` attributes on the script tag. | Attribute | Default | What it does | | --- | --- | --- | | `data-key` | required | Your publishable site key. | | `data-endpoint` | `v1/collect` next to the script | Where the tag posts. Set it only if you proxy the two paths differently. | | `data-field` | `request_id` | Name of the hidden field it adds. | | `data-timeout` | `2500` | Most milliseconds to wait before submitting anyway. | | `data-auto` | on | `off` stops the automatic page view and form attach; call `collect` and `attach` yourself. | | `data-global` | `__dc` | Name of the global the tag defines, if `__dc` clashes with something on your page. | | `data-agent-policy` | `/.well-known/agent-policy.json` | Your agent policy, which the agent notice points to. See [AI agents](https://docs.opencontext.com/guides/agents/#ask-agents-to-identify-themselves). | ## Serve it from your own site We recommend serving the tag and its endpoint from a path on your own domain, for example `/c/`. The device token is then stored first party, the tag shares your page's certificate and origin, and content blockers treat it as part of your site. Forward `/c/` to the collector host with any reverse proxy. With Caddy: ```text handle_path /c/* { reverse_proxy https://c.opencontext.com { header_up Host {upstream_hostport} } } ``` With nginx: ```nginx location /c/ { proxy_pass https://c.opencontext.com/; proxy_ssl_server_name on; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } ``` Then load ` ``` ## 2. Decide after the password checks out Call the decision API after the credentials are valid and before you start the session. Forward any Web Bot Auth signature headers: agents that sign their requests can then be `verified` rather than only `declared` or `inferred`. ```js app.post("/login", async (req, res) => { const user = await checkPassword(req.body.email, req.body.password); if (!user) return res.status(401).send("Email or password is incorrect."); const sig = req.get("signature"); let decision = { recommendation: "allow" }; // if the call fails, most teams allow logins try { const r = await fetch("https://api.opencontext.com/v1/decision", { method: "POST", headers: { Authorization: `Bearer ${process.env.DECISION_SECRET_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ request_id: req.body.request_id, event_type: "login", account_id: user.id, ip: req.ip, user_agent: req.get("user-agent"), agent_signature: sig && { signature: sig, signature_input: req.get("signature-input"), signature_agent: req.get("signature-agent"), authority: req.get("host"), }, }), signal: AbortSignal.timeout(1500), }); if (r.ok) decision = await r.json(); } catch {} return act(decision, user, req, res); }); ``` ## 3. Read the bot block ```json "bot": { "verdict": "ai_agent", "agent_type": "consumer_assistant", "operator": "anthropic", "acting_for": "user", "evidence": "verified", "confidence": 0.95 } ``` - `verdict`: `human`, `ai_agent`, `good_bot`, or `bad_bot`. - `evidence`: `verified` (a signature or the operator's published network checked out), `declared` (it named itself), or `inferred` (how it behaves). - `acting_for`: `user` when it works for a person. - A session that claims to be a known agent but cannot back it up gets `BOT_AGENT_SPOOFED`. The full field list is in [AI agents](https://docs.opencontext.com/guides/agents/). ## 4. Act on it Your login ruleset already sets `recommendation`, so the simplest policy is to follow it. The starter rules step up unverified agents, ask the person to confirm the first login by a verified agent (after that, on the same device, the agent signs in without friction), and deny spoofed agents and hidden automation. ```js function act(decision, user, req, res) { switch (decision.recommendation) { case "allow": return startSession(user, res, decision.decision_id); case "step_up": // For an agent, decision.bot.step_up === "verify_agent": ask the person it // acts for to confirm (a push or email link), or ask for a signed identity. return askToConfirm(user, res, decision.decision_id); case "review": return startSession(user, res, decision.decision_id, { limited: true }); default: return res.status(403).send("We could not sign you in. Please try again later."); } } ``` To change the policy, for example to let verified assistants straight in, edit the login ruleset in the console. Your code does not change. See [Rules](https://docs.opencontext.com/guides/rules/). ## 5. Publish your agent policy Tell agents how to identify themselves on your site at `/.well-known/agent-policy.json`. The tag's hidden notice points agents there. A starting point is in [AI agents](https://docs.opencontext.com/guides/agents/#ask-agents-to-identify-themselves). ## 6. Tell us what was true When the person confirms (or denies) that their agent was allowed to act, report it as an outcome with `bot_truth` set to `agent_authorized` or `agent_unauthorized`. See [Outcomes](https://docs.opencontext.com/guides/outcomes/). ## Related - [Stop credential stuffing on login](https://docs.opencontext.com/recipes/credential-stuffing/) - [Add fraud checks to sign-up in Next.js](https://docs.opencontext.com/recipes/signup-nextjs/) --- # Stop credential stuffing on login Source: https://docs.opencontext.com/recipes/credential-stuffing/ Credential stuffing replays usernames and passwords leaked from other sites. The scripts that do it rotate IP addresses, so blocking by IP alone rarely holds. The device and how the form was filled are much harder to hide. This recipe uses the login decision to catch the logins that get through with a valid password. ## 1. Add the login decision Tag the login form and call the decision API after the password checks out, as in [Detect AI agents on your login page](https://docs.opencontext.com/recipes/login-agents/). Always send `request_id`: without the tag there is no device, and the strongest stuffing signals come from the device. ## 2. The signals that matter | Reason code | What it means | | --- | --- | | `BOT_INJECTED_CREDENTIALS` | The credentials were set directly on the fields, without typing or a password manager. | | `BOT_CREDENTIAL_TIMING` | The username and password arrived the way scripts and stuffing tools enter them. | | `BOT_AUTOMATION`, `BOT_HEADLESS`, `BOT_WEBDRIVER` | The browser is driven by automation tools. | | `VEL_DEVICE_ACCOUNTS` | One device has signed in to many of your accounts. | | `ACCT_NEW_DEVICE` | The account is on a device it has never used. | | `NET_HOSTING_IP` | The request came from a hosting provider rather than a home or mobile network. | | `DEV_NOT_COLLECTED` | The tag did not run, which scripts that skip your pages often cause. | The `this_customer` block shows the device's account counts over 24 hours and 7, 30, and 90 days, so you can see a device fanning out across accounts as it happens. Look up any code with `GET https://api.opencontext.com/v1/reason-codes` (no key needed). ## 3. Let the rules decide The starter login rules include a check named "Script entering credentials?" that denies hidden automation entering credentials this way, and they step up other risky logins, so a stuffing run meets a verification step it cannot pass, while your real customers rarely see one. To tighten it, add a rule in the login ruleset, for example: when `VEL_DEVICE_ACCOUNTS` is present and the account is on a new device, deny. Test it on your past traffic with replay before you publish. See [Rules](https://docs.opencontext.com/guides/rules/). ## 4. Act on step up with something a script cannot pass A one-time code to the account's email or phone, or a passkey, stops a replayed password. Report `step_up_passed` when a person passes, so their device builds trust and they are not asked again. ## 5. Report confirmed takeovers When an account turns out to have been taken over, report an outcome with `outcome_type` set to `account_takeover` against the login's `decision_id`. The device is then marked across your accounts, and its next attempt on any account is caught sooner. For 30 days, any other device that is new to the taken-over account, such as another browser on the attacker's computer, is asked to step up. See [Outcomes](https://docs.opencontext.com/guides/outcomes/). ## Related - [Decisions](https://docs.opencontext.com/guides/decisions/) - [Reason codes](https://docs.opencontext.com/reference/reason-codes/) --- # Using the OpenAPI spec Source: https://docs.opencontext.com/reference/openapi/ The whole public API is described in one [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) file. The [API reference](https://docs.opencontext.com/api/) on this site is generated from it, and our build checks it against the running code on every change, so it always matches what the API does. **Download:** [openapi.yaml](https://docs.opencontext.com/openapi.yaml) ```sh curl -O https://docs.opencontext.com/openapi.yaml ``` ## Generate a typed client Any OpenAPI 3.1 generator works. A few we have tried: **TypeScript**, types only, with [openapi-typescript](https://openapi-ts.dev) and its small `openapi-fetch` client: ```sh npx openapi-typescript openapi.yaml -o src/api.d.ts npm install openapi-fetch ``` ```ts import createClient from "openapi-fetch"; import type { paths } from "./api"; const api = createClient