Learn
How to Protect Expensive API Actions from AI Agents and Automated Abuse
Learn how to protect costly API calls, AI inference, free credits, and trials from automated abuse using server-side trust decisions before execution.
Published 2026-11-19 · Updated 2026-11-19
A successful API request can still be an expensive mistake.
Imagine an AI application with a free plan. Users can create an account, receive credits, and call a model-backed endpoint. Most requests are legitimate. But someone can also automate the full sequence: open the site, sign up, collect credits, and trigger paid inference calls, possibly across many accounts.
Your API may return 200 OK every time. Authentication may work. The browser may look ordinary. The application can still lose money.
The right question is not only, "Is this a bot?" It is also:
"Should this specific request be allowed to consume something that costs us money?"
This guide shows where to put that decision, how to integrate it into a TypeScript backend using Chitmark Trust Decisions, and what to measure after rollout.
What counts as an expensive API action?
A costly action is any operation that spends money, grants economic value, or creates a liability your business must absorb.
Examples include:
| Action | What the business spends or grants | Best place to evaluate |
|---|---|---|
| Free account activation | Trial credits or free quota | Before the initial grant |
| Trial activation | Time-limited access to paid infrastructure | Before activating the trial |
| API key issuance | Access to calls that consume your quota or compute | Before issuing or enabling the key |
| AI inference or image generation | Model tokens, GPU time, or vendor fees | Before dispatching the job |
| Third-party data enrichment | Paid upstream lookup charges | Before calling the provider |
| Large batch export | Infrastructure, data-transfer, or licensed-data cost | Before scheduling the export |
These are not all the same risk. A $0.001 request may be routine; a large GPU job or a new quota grant may deserve a stronger check. Protect the value-transfer boundary, not every page view.
Why agent-powered browsers change the threat model
A growing number of AI agents can use ordinary web applications through browsers, complete forms, and interact with authenticated workflows. This is useful: a legitimate customer may authorize an assistant to do real work.
It also means that browser automation alone does not tell you whether a costly action should be approved. A user-controlled agent, a human customer, and an abusive automation workflow can reach similar endpoints.
Traditional controls remain useful, but answer different questions:
- Authentication: Which account or credential is making the request?
- Rate limiting: How much traffic has this identity or network source sent?
- Bot detection: What signals suggest that the browser or traffic is automated?
- Application authorization: Is this account allowed to perform the operation?
- Billing and budgets: Is this request covered by available funds, credits, and limits?
- Action-level trust decisions: Given the available context, should the application allow, challenge, or deny this particular high-cost attempt?
You generally want multiple controls, not a replacement for all of them.
A legitimate AI agent may pass the trust check and proceed. An unfamiliar request may need a step-up. An abusive request may be denied. Being an agent is not, by itself, evidence of abuse.
The key architectural decision: check before you spend
Consider an endpoint such as POST /api/generate that triggers a paid model call.
An unsafe order looks like this:
Request
-> Run paid model
-> Deduct credits / record usage
-> Investigate suspicious activity laterBy the time you identify a problem, the vendor charge has already happened.
A safer order is:
Request
-> Authenticate and validate inputs
-> Check local permission, balance, and rate limits
-> Ask for an action-level trust decision
|- Allow -> Reserve budget -> Execute once -> Record cost
|- Challenge -> Hold operation -> Step-up -> Verify again
|- Deny -> Do not execute
-> Send relevant outcome feedback laterThis placement matters more than detecting a particular browser. It prevents a request from reaching the expensive side effect until the application has deliberately authorized it.
Important: Chitmark does not perform your inference call, enforce your billing ledger, or make your application's own access-control decisions. Your backend must still do those jobs.
Three decisions are more useful than a single blocklist
Chitmark's Trust Decisions API returns one of three values: allow, challenge, or deny.
| Decision | Meaning for the application | Suggested application behavior |
|---|---|---|
| allow | The action is eligible to proceed under the trust verdict | Continue only if local authorization, budget, and other checks also pass |
| challenge | More assurance is required | Hold the costly operation and initiate an appropriate step-up |
| deny | The requested action should not proceed | Reject the action without consuming the expensive resource |
The response also includes an eventId used to join later outcomes, a degraded operational flag, and an enforcementMode of enforce or log_only.
A degraded response is not permission to proceed: Chitmark's documented failure behavior is to challenge rather than silently allow. Likewise, a log_only verdict is an observation, not authorization to spend.
See the Verify API reference for the contract.
Tutorial: gate an AI inference request in TypeScript
This example uses a custom action at an AI model endpoint. It shows the decision boundary, not a full production application.
1. Create a server-side API key
In the Chitmark dashboard, create a scoped key with verify:write. If you will report outcomes, also grant feedback:write. If you plan to use Chitmark's challenge API, grant challenge:write.
Keep the key on your backend, not in a browser or mobile application.
npm install @chitmark/sdk
# In your server environment, not client code
CHITMARK_API_KEY=your_server_side_key2. Persist an action attempt before verification
Each logical model-generation attempt should have an application-owned identifier and a server-generated session binding. Store these before calling Chitmark, and reuse them if the same attempt is retried.
For example, your application could persist:
{
"id": "job_123",
"sessionId": "server_generated_random_session",
"accountId": "acct_456",
"operation": "generate",
"status": "pending"
}Do not use a new session or idempotency key for every network retry of the same attempt. Distinguish a genuine new job from a retry of an existing one.
3. Verify before enqueueing the expensive job
import { Chitmark, isEligibleAllow } from "@chitmark/sdk";
const chitmark = new Chitmark({
apiKey: process.env.CHITMARK_API_KEY!,
});
type PendingJob = {
id: string; // Durable application attempt ID
sessionId: string; // High-entropy, server-generated session ID
ipTrunc: string; // Collected/truncated at a trusted server boundary
plan: "free" | "paid";
};
// Application-owned functions you must implement:
declare function saveDecision(
jobId: string,
decision: {
eventId: string;
verdict: string;
enforcementMode: string;
degraded: boolean;
}
): Promise<void>;
declare function enqueueGenerationOnce(jobId: string): Promise<void>;
export async function gateGeneration(job: PendingJob) {
// Before this function, your app should already have authenticated
// the user and checked its own authorization, quota, and budget.
const verdict = await chitmark.verify({
action: "custom",
session: job.sessionId,
surface: "app.example.com/api/generate",
subject: { ipTrunc: job.ipTrunc },
context: { operation: "model_inference", plan: job.plan },
idempotencyKey: `generation:${job.id}:verify`,
});
// Save the actual verify event ID before any side effect.
await saveDecision(job.id, {
eventId: verdict.eventId,
verdict: verdict.decision,
enforcementMode: verdict.enforcementMode,
degraded: verdict.degraded,
});
// This example assumes the route is configured to ENFORCE.
// A log-only verdict cannot authorize a grant.
if (verdict.enforcementMode !== "enforce") {
return { status: "not_enforcing" as const };
}
if (verdict.degraded || verdict.decision === "challenge") {
return { status: "challenge" as const, eventId: verdict.eventId };
}
if (verdict.decision === "deny") {
return { status: "denied" as const };
}
if (!isEligibleAllow(verdict)) {
return { status: "challenge" as const, eventId: verdict.eventId };
}
// Your app must atomically reserve capacity / credits and ensure
// retries cannot enqueue or execute the same paid operation twice.
await enqueueGenerationOnce(job.id);
return { status: "accepted" as const };
}The SDK supports action: "custom"; context can carry application metadata. This does not mean Chitmark automatically understands your inference pricing, reserves funds, or has been calibrated on every custom action. Treat the return value as one signal in your own enforcement workflow and validate it against real outcomes.
The saveDecision and enqueueGenerationOnce functions above are application placeholders, not Chitmark SDK calls. Implement durable storage, transactional credit reservation, unique-job constraints, and an execution ledger. If any required save, reservation, or eligibility check fails, do not start the paid job.
4. Handle challenge and deny without spending
At the HTTP boundary, a common mapping is:
- accepted: return an accepted-job response once your application has reserved resources and queued the work.
- challenge: return HTTP 428 Precondition Required; do not start inference.
- denied: return HTTP 403 Forbidden.
- not_enforcing: apply your existing policy; for this enforcement example, hold the action and fix the environment configuration.
To handle a Chitmark step-up, call POST /v1/challenge using the original eventId and session; present the returned method to the requester; submit its proof; then re-verify with context.challengeId and a new idempotency key for that re-verification.
Completing a challenge does not itself authorize the operation. Only a new, non-degraded allow in enforce mode can let the costly action continue, and your local authorization and budget checks still apply. Store the new eventId as the decision that authorized the operation.
See the Challenge API reference and end-to-end walkthrough.
5. Connect decisions to real business outcomes
A decision without follow-up can tell you how much traffic was challenged or denied. It cannot, by itself, tell you how much abuse cost you, or whether legitimate customers suffered unnecessary friction.
When your application has a supported, meaningful outcome, report it against the stored Chitmark eventId for the relevant action.
For example, after usage review confirms that a particular allowed attempt belongs to an abusive credit-burning workflow:
await chitmark.feedback({
eventId: savedAttempt.chitmarkEventId,
outcome: "credit_burn",
value: savedAttempt.confirmedAbuseCostUsd,
unit: "usd",
source: "usage_metering",
idempotencyKey: `credit-burn:${savedAttempt.id}`,
});Here savedAttempt is your own persisted record, not an SDK object. The outcome value should be measured cost attributable to the event, not a guessed estimate, the face value of a credit, or every ordinary customer's legitimate usage. Chitmark's credit_burn label should not be treated as a generic usage-metering event.
Other supported outcomes include converted, abuse_confirmed, and chargeback, depending on what really happened. Feedback is asynchronous; it does not need to be in the latency-sensitive request path. It also does not automatically retrain a model on each call.
The Feedback API and outcome-label connectors explain the join rules and accepted labels.
Do not accidentally create a second billing system
Trust enforcement and economic authorization are different layers.
Before any model run or paid lookup, your application should still:
- Authenticate the caller and check the account's access to the operation.
- Enforce plan quotas, spending ceilings, and provider limits.
- Create a durable attempt and an idempotent reservation for the estimated operation cost.
- Obtain an eligible action-level trust decision in enforcement mode.
- Execute the paid side effect at most once, or reconcile safely after ambiguous failures.
- Finalize actual usage and record supported outcomes later.
Do not use a Chitmark allow as proof of a credit balance, a payment, or permission to access a private resource. Chitmark's separate Agent Paid Access product handles a different seller/buyer purchase lifecycle; it is not interchangeable with a Trust Decisions verdict.
Start in observation mode before enforcing
If you are not sure how the policy will affect legitimate customers, start with Chitmark's log-only mode.
In this mode, the application records what Chitmark would have decided without using those verdicts to block traffic. Keep your existing authorization and spending controls active. Save eventId, decision, and enforcementMode with the attempt, and join eventual outcomes to those records.
Look for:
| Measurement | What it tells you |
|---|---|
| Cost from confirmed abusive activity | Whether the problem is materially expensive |
| Legitimate conversion after challenge | Whether friction is losing good customers |
| Challenge and deny rate by action | Which boundaries need further tuning |
| Cost per completed operation | Which endpoints have the largest downside |
| Repeat attempts and duplicate executions | Whether idempotency and accounting are working |
| Decision latency and degraded responses | Whether the gate is operationally reliable |
Do not report "money saved" simply by multiplying rejected requests by the highest possible action cost. A denied request may never have completed, and blocked traffic is not automatically proven abuse. Use an explicitly defined, defensible estimate and separate prevented exposure from observed loss.
Deployment checklist
Before enabling action-level enforcement, verify that:
- The trust call runs before credits, compute, or external vendor calls are committed.
- All Chitmark credentials are server-side and appropriately scoped.
- Session IDs, attempt IDs, and idempotency keys are generated and persisted by the server.
- Subject details are obtained at a trusted boundary, with hashed or truncated fields preferred where appropriate.
- Only an explicit, non-degraded allow in enforce mode can advance the operation.
- challenge and failures hold the action rather than silently allowing it.
- Step-up completion is followed by a new verification, not treated as automatic authorization.
- Local permissions, quotas, and money limits remain enforceable independently.
- Work queues and paid side effects are idempotent or safely reconciled.
- eventId is stored so real outcomes can be reported later.
- You monitor legitimate-user friction as carefully as suspected abuse.
Frequently asked questions
Common questions about putting a trust decision in front of costly operations.
Does this require identifying whether a request came from an AI agent?
No. The trust decision can evaluate the action without universally identifying the browser as human or AI. Agent identity can be useful evidence when a trustworthy proof is available, but a missing or unrecognized identity is not proof of malicious behavior.
Does a CAPTCHA solve expensive API abuse?
Not completely. Challenges can add friction, but they do not replace an application-owned spending limit or a decision at the exact place credits, quota, or compute are granted.
Should every API endpoint call a trust-decision service?
Usually not. Start with actions that grant something of value or incur real variable costs. Public documentation fetches and low-cost reads often have different security and economic requirements.
What happens if the trust service becomes unavailable?
For protected actions, Chitmark's documented contract degrades to challenge instead of allow. Your app should hold the expensive operation and provide a controlled recovery path. Do not treat network errors as permission to spend.
Can this protect against all automated abuse?
No. Any risk system can misclassify requests, and abuse patterns change. Combine action-level decisions with authentication, usage limits, durable accounting, monitoring, and human review where warranted.
The principle to design around
As AI agents become better at navigating applications, the browser alone becomes a less useful place to make a financial decision.
The durable control belongs at the action that grants value: the signup that issues credits, the key that unlocks quota, the trial that starts paid infrastructure, or the inference call that bills your account.
Decide before you spend. Measure what happened afterward.
If you want to add this boundary to your backend, start with the Chitmark Trust Decisions quickstart or explore the Verify API reference.
For the related economics of signup and trial farming, read How much are fake signups actually costing your SaaS?.