Skip to content
NearGate

CONCEPTS

Security model

NearGate splits trust deliberately: the registry contract enforces what it can see on-chain, and the gateway reports what only it can observe. This page states which is which, then covers the guards on the money, the owner-signed mapping, outbound requests and keys.

CLI v0.2.1SDK v0.1.0registry neargate-app-registry.testnetnear-testnet

Trust model

Read a service’s score as two different kinds of statement:

Claim, and who guarantees itHow
Every counted call has a real paymentThe registry, on-chain — trustlessrecord_attestation only accepts a nonce the registry itself holds a payment for, once, and never for a self-paid payment (payer is the service owner or payment target). The registry also forwards the price itself, so a payment record means the price really moved.
The call succeeded or failedThe service’s attestor or owner — reportedThe success flag is whatever the attestor (the gateway, by default) or the owner submits; the registry lets both attest. The gateway sets it from the upstream’s HTTP status (2xx is success) and the registry cannot check that it did.
A nonce pays onceThe registry and the gatewaypay refuses a used nonce (ERR_NONCE_USED); the gateway burns it before proxying. See single-use nonce.
Only the owner controls a serviceThe registryset_active and set_attestor are owner-only. The contract has no admin and no owner of its own.

WHAT THE SCORE DOES NOT PROVE

A seller who controls the attestor can report any success flag for a payment that really happened, and the self-payment guard compares accounts, not people: a seller that pays from a second account makes a real payment. That payment costs at least the 0.002 NEAR storage fee, and the price returns to the seller’s own payment target, so it is cheap, not free. Treat a trust tier as a signal backed by real transfers, not proof of independent buyers; the payment records and attestation history are public if you want to look.

Payment integrity

The gateway verifies against the chain

A proof is never trusted for what it claims. The gateway reads the registry’s payment record for the nonce (service, amount, age, not yet attested) and, in live mode, the transaction itself: signed by the named payer, received by the registry, holding a pay or pay_from_escrow action with the same service id and nonce, and succeeded (tx_mismatch otherwise). The full order is on How it works.

The buyer’s client refuses a bad invoice

The client validates the invoice before it signs anything. It refuses, without paying, an invoice that is not valid x402 V1, is expired, has a storage fee other than the registry’s 0.002 NEAR, whose total is not price + fee (BAD_INVOICE), that is for another network (NETWORK_MISMATCH), whose payTo is not the registry it settles on (REGISTRY_MISMATCH) or that names another service than the one requested (SERVICE_MISMATCH). It never follows a redirect (REDIRECT_REFUSED).

Budget cap

--max (CLI), maxNear (MCP) and the buyer agent’s budget cap the total attached, price plus the storage fee, and are checked before the payment (BUDGET_EXCEEDED). The buyer agent checks price plus fee against its budget minus what it has already spent in the run, and then hands the client exactly that approved total as its cap, so an invoice that grew after the check is refused. The cap covers a --from-escrow payment the same way, and the client also reads the escrow first and refuses (ERR_ESCROW_INSUFFICIENT) before sending anything it cannot pay. Because pay_from_escrow carries no amount and debits the service’s on-chain price whatever the invoice says, the client first checks the invoice’s total against the registry and refuses a differing one (PRICE_MISMATCH), so the cap holds for escrow payments too.

Self-payment guard

A payment whose payer is the service’s owner or payment target is recorded as self_paid. The gateway serves it (the buyer did pay) but does not attest it, and the registry would reject the attestation anyway (ERR_SELF_PAYMENT). See the caveat in the trust model.

Owner-signed mapping (self-map)

The gateway holds the private upstream URL of each service. To let a service owner set it without a shared admin token, POST /services/:id/map accepts a request signed with the owner’s NEAR key. This is what neargate wrap and neargate map send in live mode.

POST /services/<id>/map

{
  "upstreamUrl": "https://api.example.com/gold",
  "accountId": "<service owner account id>",
  "publicKey": "ed25519:<owner key>",
  "timestamp": 1794407336851,
  "signature": "<base64 ed25519 signature>"
}

The signature is an ed25519 signature over these exact bytes (UTF-8, joined by newlines):

signed message

NearGate/self-map/v1
<network>
<serviceId>
<upstreamUrl>
<timestamp>

The fixed prefix separates the message from any other use of the key, and network and serviceId stop a signature being replayed on another chain or for another service; upstreamUrl is the string exactly as sent. The gateway rebuilds the bytes itself and checks, cheapest first:

CheckAnswer on failure
The id is a valid service id; the body has the right shape400 invalid_service_id 400 invalid_body
The service exists on the registry404 service_not_found
The timestamp is within 120 seconds of the gateway’s clock400 stale_timestamp
The signature verifies for the public key over the rebuilt message401 owner_signature_invalid
The account is the service’s owner on the registry403 not_service_owner
The public key is a FullAccess key of that account (a function-call key, such as a dapp login key, is not the owner’s authority)403 key_not_full_accessIf the chain cannot answer: 503 chain_unavailable. It fails closed and maps nothing.
The timestamp is newer than the last accepted mapping of this service409 replayed
The upstream URL passes the SSRF guard (below)400 invalid_upstream_url 400 forbidden_upstream_host

Then it stores the mapping and answers 204. Replays are bounded twice: the 120-second window, and a per-service monotonic timestamp (a rejected request never moves it). That second guard lives in the gateway’s memory, so across a restart the window is the bound. The route is rate limited to 20 requests per minute. In mock mode the mapping goes through the token-protected admin route instead.

Outbound requests (SSRF)

Two parties fetch a URL a seller controls: the gateway, fetching the upstream, and the buyer’s client, fetching the endpoint it read from the registry.

The gateway and the upstream

LayerWhat it does
At mapping timeThe upstream must be an http(s) URL of at most 2048 characters with no user name or password in it; in live mode its host must not be private: localhost names, 0.0.0.0/8, loopback, RFC 1918, link-local (cloud metadata), CGNAT, 192.0.0.0/16, the 198.18.0.0/15 benchmark range, IPv4 multicast, reserved and broadcast (224.0.0.0 and up), and in IPv6 the unspecified and loopback addresses, unique-local, link-local and IPv4-mapped private addresses.
At request time (live)Before a payment is even challenged, the host is resolved again and refused if any address is private or it does not resolve (503 service_unavailable). This defeats a host that was public when mapped and re-pointed later.
On the connection (live)The proxy resolves the host once more right before it connects, refuses it if any address is private, and pins the connection to the first address of that lookup, so the address it checked is the one it uses. If the pinning connector cannot be built, it connects without the pin.
RedirectsLive mode never follows an upstream redirect (it would let a public host bounce the gateway into a private network); the 3xx status passes through without its Location header. Mock mode follows them so local demos work.
What reaches the upstreamOnly accept, accept-language and user-agent, the JSON body and the query string. The payment proof, cookies, authorization and forwarding headers are never forwarded; bodies are capped at 1 MiB each way; the upstream URL never appears in any response.

The buyer’s client and the endpoint

The endpoint comes from the registry, which accepts any bytes there. The client refuses one that is not http(s) (BAD_URL) and, off the offline devnet, one whose host is private or resolves to a private address (FORBIDDEN_HOST); it never follows a redirect, so the payment proof cannot be bounced to an unchecked address; and it caps each request at 30 seconds. This dashboard applies the same distrust: it links a service’s endpoint only when it is http(s), and puts it into the copy-paste curl snippet only as a single quoted shell word.

Agent keys and the escrow

An AI agent that pays for calls needs a key, and a full-access key can drain its owner’s account. NearGate gives the agent a different kind of key instead: a NEAR function-call access key that the account’s owner adds with neargate agent-key add. It is restricted, by NEAR itself, to one receiver (the registry) and one method (pay_from_escrow), and it can attach no deposit.

BLAST RADIUS

An agent key restricted to pay_from_escrow can spend the escrow and nothing else. Withdrawing needs a full-access key (withdraw_escrow attaches 1 yocto, which a function-call key cannot). The escrow is the spending limit: a leaked agent key can spend all of it, on any active service, and no more NEAR than that. Its gas, though, comes from the account’s own balance, not from the escrow: a leaked key can also burn gas from the account balance up to its allowance, so set the allowance low. Apart from that gas it cannot touch the rest of the account, change a service or move NEAR anywhere else.
WhatHow it is handled
The spending limitThe escrow balance, funded from the full-access key (neargate escrow deposit). Keep in it what the agent may spend. --max and maxNear still cap each call’s total; they are per call, the escrow is the total.
The key’s allowancePays only the key’s gas, a small amount per call, and that gas is drawn from the account balance, not from the escrow. A leaked key can burn gas from the account balance up to its allowance, so set it low; it is not the spending limit.
The key fileagent-key add writes the secret to ~/.near-credentials/<network>/<account>.neargate-agent.json with mode 0600, refuses to overwrite an existing file and prints only the public key and the path, never the secret. Treat it like any key file: it is what the agent uses as --key-file.
RevokingDelete the key from the account with its full-access key (for example with the near CLI). The escrow stays; take it back with neargate escrow withdraw.
What it does not limitThe agent chooses the service: it can pay any active service for any price the escrow covers, including one that is not worth it. Choose the escrow size accordingly, and use maxNear / --max to bound a single call.

The offline devnet models only one public, full-access key per account (it signs the mock gasless delegates), never a restricted one, so the restriction itself is a live-chain property (agent keys need live mode). The registry’s own rules around it are in the contract reference.

The gasless relayer

With RELAYER_ENABLED the gateway account (GATEWAY_ACCOUNT_ID) relays buyers’ signed pay_from_escrow delegates and pays their gas: the gasless rail. The buyer’s escrow pays the price and the fee, as for any pay_from_escrow.

RELAYER EXPOSURE

The relayer’s exposure is gas only. NEAR has a relayer pay any deposit that a relayed call attaches, so the gateway relays exactly one shape and nothing else: one zero-deposit pay_from_escrow to the registry, for an invoice it issued, with 30 TGas. It never relays a transfer, another method or another contract, and the escrow, not the relayer, pays the service.

Every refusal below comes before the relay, so a delegate the gateway refuses there costs it nothing (the full list is on How it works):

A delegate that…Refused as
Is not a valid SignedDelegate, or has any other shape: another sender, receiver, method, arguments or gas, a deposit, a second actiondelegate_* (e.g. delegate_wrong_action)
Expires within 20 blocks, or carries a nonce NEAR would call too largedelegate_expired, delegate_nonce_too_large
Is not signed by the key it names (a forged or altered delegate)bad_signature
Names a key the payer does not hold, or a function-call key not allowed to call pay_from_escrow on the registryunknown_key, key_not_allowed
Carries a nonce the key already used (read at optimistic finality, so a block not yet final counts), or one this gateway relayed for that key and that may still run, or is relaying nowstale_nonce
Comes from an escrow that cannot pay price + 0.002 NEARescrow_insufficient
Is for an invoice already paid, or whose relay is in flight or may still landinvoice_used, settlement_pending (never relayed twice)

What can still cost gas is a delegate that passes every check and then fails on chain — the buyer drained its escrow, or used or deleted the key, in between. The gateway answers relay_failed with a code that says whose failure it was: the registry’s ERR_* when NEAR ran the delegate (its nonce is then spent), DELEGATE_REJECTED when NEAR refused the delegate itself, RELAYER_ERROR when the relay failed on the gateway’s side (the detail stays in the gateway’s log, never in the answer). The relayer has paid at most one relay’s gas; the rate limit on /svc bounds how often. Keep the gateway account funded for that gas, as for its attestations.

Front-running

On the tx rails (pay, and pay_from_escrow sent by the buyer) the payment is public on chain before the buyer presents its proof: someone watching the registry can present that transaction, nonce and payer first and receive the response, and the buyer then gets invoice_used (PAID_NOT_SERVED). That is inherent to paying first and proving after. On the gasless rail nothing a third party can redeem is public before the request reaches the gateway: the signed delegate travels only in the buyer’s own request, and the gateway burns the nonce for that request before it proxies. Between the relay landing and the burn the payment is already public on chain; the protection there is invoice_used for anything this gateway process did not relay. After a relay timeout the payment is public on chain, so the retry has the same front-running residual as the tx rails; so does any settlement_pending answer that names the relay transaction.

Keys, secrets and the admin token

TopicBehaviour
Key resolution (live)A secret key in the environment, else a key file, else ~/.near-credentials/<network>/<account>.json. The CLI resolves it before any chain call, so a missing or bad key fails fast. The gateway loads its key (GATEWAY_PRIVATE_KEY or a key file) only when it first signs, so it boots and verifies payments without one; a missing key then shows as failed attestations and relay_failed (RELAYER_ERROR) on the gasless rail.
Never printedError messages name the source of a bad key, never its content, and no RPC URL or key reaches an error text. The CLI warns when a key file is readable by group or others.
Agent key fileA restricted function-call key (see Agent keys and the escrow): mode 0600, never overwritten, secret never printed or logged. It can spend the escrow and nothing else.
Never committedThe repository’s .gitignore covers .env files, keys/ and *.near-credentials*. Secrets belong in your environment or in an untracked .env.
Admin tokenGuards /admin/services. Live mode refuses the shipped default (dev-admin-token) at config load; the gateway compares tokens in constant time. Passing it as a CLI flag leaves it in shell history and ps — prefer the environment variable.
Gateway accountLive mode refuses to start without GATEWAY_ACCOUNT_ID: it signs attestations (and, with RELAYER_ENABLED, the relays), and there is no mock-signer fallback.

Gateway limits

RouteLimit
/svc60 requests per minute per client
/receipts60 requests per minute per client
/services (self-map)20 requests per minute per client
/admin20 requests per minute per client

Limits key on the client IP. Behind one reverse proxy set TRUST_PROXY=1 so that is the real client, never higher than the real number of hops, or X-Forwarded-For becomes spoofable. JSON request bodies to the gateway are capped at 256 KB; the gateway sets security headers (helmet) and has no CORS: it is a server-to-server API, and the dashboard reads through its own server routes.

Before you go live

Check
☐A strong, unique AGENTGATE_ADMIN_TOKEN (config refuses the default in live mode).
☐REGISTRY_CONTRACT_ID names your deployed registry, and npm run smoke:live passes.
☐GATEWAY_ACCOUNT_ID and its key are set, and each service you register names that account as its attestor.
☐The gateway is served over https; its public URL is final, because the registry stores it for good as the service’s gateway_base_url.
☐TRUST_PROXY matches your real proxy hop count.
☐INVOICE_STORE_PATH and ATTESTATION_QUEUE_PATH point at persistent files, so a restart keeps open invoices and replays unconfirmed attestations.
☐No key, .env or credentials file is committed.
☐RELAYER_ENABLED=1 only if you mean to pay buyers’ gas; the gateway account then needs the balance for it.