Skip to content

Verify on the server

Never trust the cookie as it arrives: anyone can write a cookie. Verify it on your server on each request that depends on location.

The SDK is one TypeScript file with no dependencies, for Node 18 or later. Download it and copy it into your backend:

terrastamp.ts

Using another language? See Other languages.

import { verifyStamp, jwksFromUrl } from './terrastamp'
// Fetches terrastamp's public keys and caches them.
const jwks = jwksFromUrl('https://api.terrastamp.dev/.well-known/jwks.json')
const r = await verifyStamp(req.cookies.terrastamp, {
jwks,
host: 'www.brand.com', // exactly as in your site key
bindingKey: process.env.TERRASTAMP_BINDING_KEY, // tsb_…
ip: visitorIp, // the visitor's IP as your server sees it
})
if (r.ok && r.stamp.status === 'consensus') {
route(r.stamp.region) // "US-NY", "GB", …
}

verifyStamp checks, in order:

  1. The token is a well-formed EdDSA JWT signed by one of terrastamp’s keys.
  2. iss (when you pass issuer), aud equals your host, and the stamp hasn’t expired (60 s leeway).
  3. With bindingKey and ip: the stamp was issued to this visitor’s IP address.

It returns { ok: true, stamp, ipMatch } or { ok: false, error, stamp? }. See Stamp reference for each error.

The IP binding is only as good as the IP you pass. Behind a load balancer, CDN or proxy, the socket address is the proxy’s, not the visitor’s. Take the address your trusted proxy reports, for example Cloudflare’s CF-Connecting-IP, or the right entry of X-Forwarded-For for the number of proxies you run. Never take the left-most X-Forwarded-For entry: the visitor can set it.

Visitors with both IPv4 and IPv6 get a stamp bound to both addresses, so it verifies whichever one reaches your server.

A stamp bound to only one family (for example IPv6) that arrives over the other passes by default, with ipMatch: null. Pass allowOtherFamily: false to reject it instead.

verifyStamp takes these options:

Option
jwks jwksFromUrl(...), or a fixed { keys: [...] } object.
host Your host, exactly as in your site key.
bindingKey Your binding key. With ip, rejects stamps copied to another network.
ip The visitor’s IP address.
issuer Also require iss to equal this, e.g. https://api.terrastamp.dev.
allowOtherFamily Whether a stamp with no binding for the visitor’s IP family passes. Default true.
leewaySeconds Clock skew to tolerate. Default 60.

terrastamp’s signing keys rotate. jwksFromUrl refetches the key set when a stamp names a key it hasn’t seen, so rotation needs nothing from you.

Your binding key is secret: keep it in your server’s environment, never in page code or a repository. If it leaks, ask terrastamp for a new site key and binding key.