CPAPI reference server
Candidate preview. This page describes the candidate Canonical Provider API v1 contract, candidate manifest SHA-256 c85d92a38cd495f7d8a0cf1b5d4b0c2783abdd90f3c51d4827ca24e24d11ea0e. It is non-normative: it explains the contract and does not define it.
This page is a starting point for your integration: about 250 lines of Node.js 22 or later, with no dependencies beyond node:http and node:crypto. It answers the three Control calls with the signature checks certification expects, and it signs and settles your Money calls. Before we published this page, we ran checks 13 to 16 and 23 of our conformance runner against this server over local HTTP, and all five passed; a certification run from the cabinet is still the test that counts. Port it to your own stack, or run it next to your game server while you build.
It keeps everything in memory, so it is not production code: Before production lists what to replace.
What you need
Section titled “What you need”Complete the first two cabinet steps in CPAPI setup: your certification endpoint with at least one launch domain, and both certification keys. The code reads its configuration from environment variables, never from the code itself. The Control server does not start without its Control variables, and the Money client refuses to sign a call without its Money key:
| Variable | Value |
|---|---|
CPAPI_ENVIRONMENT |
certification, or live for your production server |
CPAPI_AUTHORITY |
The host of your registered API URL in lowercase, with :port when the URL names a port other than 443, for example api.studio.example.com |
CPAPI_LAUNCH_BASE |
An https URL on one of your launch domains, where your game client starts, for example https://play.studio.example.com/. The server adds a session query parameter to it |
CPAPI_CONTROL_KEYID, CPAPI_CONTROL_SECRET_BASE64 |
Your Control key ID and secret |
CPAPI_MONEY_KEYID, CPAPI_MONEY_SECRET_BASE64 |
Your Money key ID and secret |
PORT |
The port the server listens on, 8080 by default |
Shared signing
Section titled “Shared signing”Both directions use one signing profile, as CPAPI signatures describes. This module holds the covered components of every call and builds the signature base.
// cpapi-sign.mjs: the RFC 9421 profile both directions use.import crypto from "node:crypto";
export const COMPONENTS = { "POST /v1/sessions": ["@method", "@authority", "@path", "content-digest", "idempotency-key"], "GET /v1/session-recovery": ["@method", "@authority", "@path", "idempotency-key"], "GET /v1/sessions/{id}": ["@method", "@authority", "@path"], "POST /v1/balance": ["@method", "@authority", "@path", "content-digest"], "POST /v1/transactions/bet": ["@method", "@authority", "@path", "content-digest"], "POST /v1/transactions/win": ["@method", "@authority", "@path", "content-digest"], "POST /v1/transactions/refund": ["@method", "@authority", "@path", "content-digest"], "GET /v1/transactions/{id}": ["@method", "@authority", "@path"],};
export function route(method, path) { if (method === "GET" && /^\/v1\/sessions\/[A-Za-z0-9._:-]{1,128}$/.test(path)) return "GET /v1/sessions/{id}"; if (method === "GET" && /^\/v1\/transactions\/[A-Za-z0-9._:-]{1,128}$/.test(path)) return "GET /v1/transactions/{id}"; const name = `${method} ${path}`; return name in COMPONENTS ? name : null;}
export const contentDigest = (body) => `sha-256=:${crypto.createHash("sha256").update(body).digest("base64")}:`;
export function signatureParams(components, { created, expires, nonce, keyid, tag }) { const list = components.map((c) => `"${c}"`).join(" "); return `(${list});created=${created};expires=${expires};nonce="${nonce}";keyid="${keyid}";alg="hmac-sha256";tag="${tag}"`;}
export function signatureBase(components, values, params) { const lines = components.map((c) => `"${c}": ${values[c]}`); lines.push(`"@signature-params": ${params}`); return lines.join("\n");}
export const hmac = (secret, base) => crypto.createHmac("sha256", secret).update(base, "utf8").digest("base64");Control server
Section titled “Control server”The server answers POST /v1/sessions, GET /v1/sessions/{session_id} and GET /v1/session-recovery, and refuses every other path. It verifies each call in the order CPAPI signatures lists, so a refused call never uses its nonce up, and it answers a refusal with the problem certification expects.
// control-server.mjs: the three Control calls, in memory. Node.js 22 or later, no dependencies.import http from "node:http";import crypto from "node:crypto";import { COMPONENTS, route, contentDigest, signatureBase, hmac } from "./cpapi-sign.mjs";
for (const name of ["CPAPI_ENVIRONMENT", "CPAPI_AUTHORITY", "CPAPI_LAUNCH_BASE", "CPAPI_CONTROL_KEYID", "CPAPI_CONTROL_SECRET_BASE64"]) { if (!process.env[name]) throw new Error(`Set ${name}`);}const ENV = process.env.CPAPI_ENVIRONMENT; // "certification" or "live"const AUTHORITY = process.env.CPAPI_AUTHORITY; // host of your registered API URLconst LAUNCH_BASE = process.env.CPAPI_LAUNCH_BASE; // https URL on one of your launch domainsconst KEYS = new Map([[process.env.CPAPI_CONTROL_KEYID, Buffer.from(process.env.CPAPI_CONTROL_SECRET_BASE64, "base64")]]);// After a rotation, also add the previous Control key here until its hour is over.const CONTROL_CALLS = ["POST /v1/sessions", "GET /v1/session-recovery", "GET /v1/sessions/{id}"];const TAGS = { certification: "cpapi-control-certification", live: "cpapi-control-live" };const MAX_BODY = 8192; // our session requests are far smaller
const PROBLEMS = { // code: [status, requirement_id, title], as the problems registry lists them invalid_signature: [401, "CPAPI-SEC-001", "Signature verification failed"], expired_signature: [401, "CPAPI-SEC-003", "Signature outside its validity window"], replayed_nonce: [401, "CPAPI-SEC-003", "Replay detected for this signature nonce"], unknown_keyid: [401, "CPAPI-SEC-004", "Unknown signing key"], wrong_environment_credential: [403, "CPAPI-SEC-005", "Credential environment does not match the addressed subject"], session_invalid: [404, "CPAPI-CONF-001", "Session unknown, expired, or not addressable by this integration"], validation_failed: [400, "CPAPI-WIRE-002", "Request failed schema validation"], idempotency_fingerprint_conflict: [409, "CPAPI-IDEMP-003", "Idempotency key reused with a different request fingerprint"],};class Problem extends Error {}
const nonces = new Map(); // nonce -> expiry (ms); keep 24 hours in a shared store in productionconst byKey = new Map(); // Idempotency-Key -> { fingerprint, session, request }const byId = new Map(); // session_id -> { session, request }const launches = new Map(); // launch token -> session_id, for your game clientsetInterval(() => { const now = Date.now(); for (const [nonce, until] of nonces) if (until < now) nonces.delete(nonce);}, 60_000).unref();
function single(req, name) { const values = req.headersDistinct[name]; if (values === undefined) return undefined; if (values.length !== 1) throw new Problem("invalid_signature"); return values[0];}
function verify(req, name, body) { const input = single(req, "signature-input") ?? ""; const m = /^sig1=\(([^)]*)\);created=(0|[1-9][0-9]{0,14});expires=(0|[1-9][0-9]{0,14});nonce="([^"]{16,128})";keyid="([^"]+)";alg="([^"]+)";tag="([^"]+)"$/.exec(input); const expected = COMPONENTS[name]; if (!m || m[1] !== expected.map((c) => `"${c}"`).join(" ")) throw new Problem("invalid_signature"); const hasBody = expected.includes("content-digest"); if (hasBody !== (body.length > 0) || (!hasBody && single(req, "content-digest") !== undefined)) { throw new Problem("invalid_signature"); } const [created, expires] = [Number(m[2]), Number(m[3])]; const [nonce, keyid, alg, tag] = m.slice(4); if (!(expires - created > 0 && expires - created <= 300)) throw new Problem("invalid_signature"); const secret = KEYS.get(keyid); if (!secret) { // a key ID of the other environment gets 403 const other = ENV === "live" ? "cpapi_certification_control_" : "cpapi_production_control_"; throw new Problem(keyid.startsWith(other) ? "wrong_environment_credential" : "unknown_keyid"); } if (alg !== "hmac-sha256") throw new Problem("invalid_signature"); const now = Math.floor(Date.now() / 1000); if (!(created - 300 <= now && now <= expires + 300)) throw new Problem("expired_signature"); const values = { "@method": req.method, "@authority": AUTHORITY, "@path": req.url }; if (hasBody) { values["content-digest"] = single(req, "content-digest"); if (values["content-digest"] !== contentDigest(body)) throw new Problem("invalid_signature"); } if (expected.includes("idempotency-key")) { values["idempotency-key"] = single(req, "idempotency-key"); if (!/^[\x21-\x7e]{1,255}$/.test(values["idempotency-key"] ?? "")) throw new Problem("invalid_signature"); } const sig = /^sig1=:([A-Za-z0-9+/=]+):$/.exec(single(req, "signature") ?? ""); const mine = Buffer.from(hmac(secret, signatureBase(expected, values, input.slice(5))), "base64"); const theirs = Buffer.from(sig ? sig[1] : "", "base64"); if (mine.length !== theirs.length || !crypto.timingSafeEqual(mine, theirs)) throw new Problem("invalid_signature"); if (!tag.endsWith(`-${ENV}`)) throw new Problem("wrong_environment_credential"); if (tag !== TAGS[ENV]) throw new Problem("invalid_signature"); // a Money tag on a Control call if (nonces.has(nonce)) throw new Problem("replayed_nonce"); // record the nonce last nonces.set(nonce, Date.now() + 86_400_000); return values["idempotency-key"];}
function openSession(key, body) { const fingerprint = crypto.createHash("sha256").update(body).digest("hex"); const known = byKey.get(key); if (known) { if (known.fingerprint !== fingerprint) throw new Problem("idempotency_fingerprint_conflict"); return known.session; } let request; try { request = JSON.parse(body); } catch { throw new Problem("validation_failed"); } if (request?.environment !== ENV) throw new Problem("validation_failed"); const token = crypto.randomUUID(); const launch = new URL(LAUNCH_BASE); launch.searchParams.set("session", token); const session = { session_id: crypto.randomUUID(), state: "active", environment: ENV, launch_url: launch.href }; // Keep the request: your Money calls repeat its tenant_id, integration_id, player_ref and currency. byKey.set(key, { fingerprint, session, request }); byId.set(session.session_id, { session, request }); launches.set(token, session.session_id); return session;}
function send(res, status, value) { const body = JSON.stringify(value); const type = status < 300 ? "application/json" : "application/problem+json"; res.writeHead(status, { "Content-Type": type, "Content-Length": Buffer.byteLength(body) }).end(body);}
http.createServer((req, res) => { const name = route(req.method, req.url); // exact paths only, never normalized if (!CONTROL_CALLS.includes(name)) { req.resume(); // refuse before reading the body return res.writeHead(404).end(); } let size = 0; const chunks = []; req.on("data", (c) => { size += c.length; if (size <= MAX_BODY) chunks.push(c); }); req.on("end", () => { if (size > MAX_BODY) return res.writeHead(413).end(); const body = Buffer.concat(chunks); try { const key = verify(req, name, body); if (name === "POST /v1/sessions") return send(res, 201, openSession(key, body)); const stored = name === "GET /v1/session-recovery" ? byKey.get(key) : byId.get(req.url.slice("/v1/sessions/".length)); if (!stored) throw new Problem("session_invalid"); return send(res, 200, stored.session); } catch (error) { if (!(error instanceof Problem)) { console.error(error); return res.writeHead(500).end(); } const code = error.message; const [status, requirement_id, title] = PROBLEMS[code]; send(res, status, { type: code.replaceAll("_", "-"), title, status, code, requirement_id, retry_class: "never" }); } });}).listen(Number(process.env.PORT ?? 8080));- Exact paths. The server matches the raw request path and never normalizes it, so a trailing slash or a percent escape is refused. An unknown path gets
404before the server reads the body, and a body over 8 KiB gets413. - One header each. A signed header that appears twice is refused, so a duplicated
Idempotency-Keycannot slip past the signature. - Problems. Each refusal is
application/problem+jsonwith thetype,title,status,code,requirement_idandretry_classof its row in the problems registry. - Keys.
KEYSholds one Control key. After a rotation, add the previous key until its hour is over, as rotation explains. - Session data. The server keeps our session request next to each session. Your Money calls for the session repeat its
tenant_id,integration_id,player_refandcurrency. - Launch token. The launch URL carries a token that maps to the session, so your game client can find the session it starts.
- Demo play. This server does not implement the optional demo module and answers its three paths with
404, so an operator’s demo launch fails. While you run it, keep demo play off in the cabinet and do not declarehas_demo: true. To offer demos, add the three operations in optional demo play and their rows from covered components toCOMPONENTS.
Money client
Section titled “Money client”Your game server calls our Money API through settle() for bets and wins and balance() for the balance. Each attempt is signed again with a new nonce. The transaction_id is also the Idempotency-Key, so every attempt for one transaction keeps both, even after a restart, as retries and recovery requires.
// money-client.mjs: signed calls to our Money API, with safe recovery after a timeout.import crypto from "node:crypto";import { COMPONENTS, route, contentDigest, signatureParams, signatureBase, hmac } from "./cpapi-sign.mjs";
const BASE = "https://api.aggregator.gg";const AUTHORITY = "api.aggregator.gg";const TAG = process.env.CPAPI_ENVIRONMENT === "live" ? "cpapi-money-live" : "cpapi-money-certification";
export function signMoney(method, path, body, { keyid = process.env.CPAPI_MONEY_KEYID, secret = Buffer.from(process.env.CPAPI_MONEY_SECRET_BASE64 ?? "", "base64"), tag = TAG, created = Math.floor(Date.now() / 1000), nonce = crypto.randomBytes(16).toString("hex") } = {}) { if (!keyid || !secret.length) throw new Error("Set CPAPI_MONEY_KEYID and CPAPI_MONEY_SECRET_BASE64"); const components = COMPONENTS[route(method, path)]; const values = { "@method": method, "@authority": AUTHORITY, "@path": path }; const headers = {}; if (body.length) { headers["Content-Type"] = "application/json"; headers["Content-Digest"] = values["content-digest"] = contentDigest(body); } const params = signatureParams(components, { created, expires: created + 300, nonce, keyid, tag }); headers["Signature-Input"] = `sig1=${params}`; headers["Signature"] = `sig1=:${hmac(secret, signatureBase(components, values, params))}:`; return headers;}
async function call(method, path, payload, idempotencyKey) { const body = payload ? Buffer.from(JSON.stringify(payload)) : Buffer.alloc(0); const headers = signMoney(method, path, body); // a new nonce on every attempt if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey; const res = await fetch(BASE + path, { method, headers, body: body.length ? body : undefined, signal: AbortSignal.timeout(20_000) }); // above our 15-second deadline const text = await res.text(); try { return { status: res.status, body: JSON.parse(text) }; } catch { return { status: res.status, body: null }; } // a proxy's error page, not our answer}
// Submit one saved ordinary refund. The caller owns status lookup and recovery.export function postRefund(payload, originalKey) { if (!originalKey) throw new Error("Supply the saved refund idempotency key"); return call("POST", "/v1/transactions/refund", payload, originalKey);}
export function readTransaction(id) { return call("GET", `/v1/transactions/${id}`);}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));export class Refused extends Error {} // this attempt was refused; an earlier one may have completedexport class Unresolved extends Error {} // the outcome is unknown: keep it for reconciliation
// Start a new bet only while the game is active. Save the original payload before calling.// betRetryUntil is an optional, known-safe cutoff in Unix milliseconds for ordinary BET retries.export async function settle(kind, payload, { resume = false, betRetryUntil } = {}) { if (kind !== "bet" && kind !== "win") throw new Error("settle expects a bet or win"); const id = payload.transaction_id; const bet = kind === "bet"; const windowOpen = () => Number.isFinite(betRetryUntil) && Date.now() < betRetryUntil; let unsure = resume || (bet && Number.isFinite(betRetryUntil) && !windowOpen()); for (let attempt = 0; attempt < 6; attempt++) { if (attempt) await sleep(2 ** attempt * 250 + Math.random() * 250); if (unsure) { const status = await readTransaction(id).catch(() => null); const result = status?.status === 200 ? status.body : null; if (result?.outcome_finality === "terminal") return result; const finalize = result?.outcome === "pending" && result.outcome_reason === "finalization_pending"; const missing = status?.status === 404 && status.body?.code === "transaction_not_found"; const prepared = result?.outcome === "pending" && !result.outcome_reason; // Finishing a recorded wallet answer is safe after expiry. Check the clock after each GET. if (!finalize && (!(missing || prepared) || (bet && !windowOpen()))) continue; } let res; try { res = await call("POST", `/v1/transactions/${kind}`, payload, id); } catch (error) { if (!(error instanceof TypeError || ["TimeoutError", "AbortError"].includes(error.name))) throw error; unsure = true; continue; } if (res.status === 201 && res.body?.outcome_finality === "terminal") return res.body; if (!unsure && res.body?.retry_class === "never") throw new Refused(`${id}: ${res.body.code}`); if (!bet && (res.status === 429 || res.body?.retry_class === "after_backoff")) continue; unsure = true; // Read the original ID before retrying, including after throttling. } throw new Unresolved(`${id}: outcome unknown, keep it for reconciliation`);}
export async function balance(payload) { const res = await call("POST", "/v1/balance", payload); if (res.status !== 200 || !res.body) throw new Error(`balance: ${res.status} ${res.body?.code ?? ""}`); return res.body;}For a session opened with ordinary refunds enabled, persist the refund payload and its key before calling postRefund(payload, originalKey). After a timeout or 500, call readTransaction(payload.transaction_id). A terminal status settles the refund even without a balance. For indeterminate, stop and reconcile with support using both transaction IDs. For pending or a missing status after an uncertain POST, follow the refund recovery steps.
settle() ends in one of three ways:
- It returns the outcome,
committedordeclined, from the201or from the status call. An outcome read through the status call carries no balance: callbalance()when you need it. - It throws
Refusedwhen we refused this attempt, for example withvalidation_failed,session_invalidoridempotency_fingerprint_conflict. An earlier attempt with that transaction ID may already have completed. For an idempotency conflict, keep the originaltransaction_idandIdempotency-Key, read its status, and compare the rejected payload with your saved original. Resolve the mismatch before deciding whether to retry the original call. Never give the same bet or win a new ID to bypass the refusal; a new ID identifies a new money movement. A new bet refused withsession_invalidcannot start a round on that session. Offer the player a relaunch from the operator’s site for new bets. If an earlier attempt timed out, keep reconciling its original ID. A displayed refusal for this attempt cannot settle the earlier one. - It throws
Unresolvedafter a bounded number of attempts. Keep the original session,transaction_id,Idempotency-Keyand body. For a win, callsettle()again later with the same payload and{ resume: true }, even after expiry. It reads the status before it resends. To retry an active BET with the same bytes, pass{ resume: true, betRetryUntil }using a known-safe cutoff. When the deadline has passed or is uncertain, callreadTransaction(id)for a signed GET without a POST and follow the status checks at expiry. After expiry, a404,pendingwithout a reason, orindeterminatecan race an earlier request. Poll with backoff. If the outcome remains unresolved, send the original ID to support@aggregator.gg. A freshpendingwithfinalization_pendingletssettle()finish the recorded wallet result with the same payload and{ resume: true }, even after expiry.
For a BET, provide betRetryUntil only when you have a reliable cutoff. For example, if the operator shares when it first sent the original launch request and you know the applicable session duration, their sum is a conservative cutoff with synchronized clocks. Keep the original timestamp across retries. The Control request does not supply the exact deadline. When the cutoff is unknown, the helper can start a fresh bet during play but only checks its status after an uncertain attempt. It can always finalize an already recorded wallet answer. An expired cutoff or unavailable status yields Unresolved after bounded reads. A fresh refusal alone only describes that attempt.
A round with one bet and one win looks like this. stored is what your Control server kept for the session:
import crypto from "node:crypto";import { settle } from "./money-client.mjs";
// stored = { session, request }: your answer to our session request, and the request itself.const { session, request } = stored;const identity = { tenant_id: request.tenant_id, integration_id: request.integration_id, environment: request.environment, session_id: session.session_id, player_ref: request.player_ref,};const round_id = crypto.randomUUID();const bet = { ...identity, transaction_id: crypto.randomUUID(), round_id, amount: { currency: request.currency, amount_minor: 100 } };// Store bet in your database here, before the first call.const result = await settle("bet", bet);if (result.outcome === "committed") { const win = { ...identity, transaction_id: crypto.randomUUID(), round_id, bet_transaction_id: bet.transaction_id, amount: { currency: request.currency, amount_minor: 250 } }; // Store win here as well. await settle("win", win);}A bet that ends declined moved no money: show the player the decline and do not send a win for it.
Check it before a run
Section titled “Check it before a run”Certification calls only your Control API, and no check calls your Money client before you go live. Check both against the test vectors in CPAPI signatures first.
-
Money signer. Sign the Money test vector and compare the result:
import { signMoney } from "./money-client.mjs";const body = Buffer.from(process.argv[2]); // the 288-byte body of the test vectorconst headers = signMoney("POST", "/v1/transactions/bet", body, {keyid: "cpapi_production_money_00000000000000000000000000000000",secret: Buffer.from("Y3BhcGktdGVzdC12ZWN0b3ItYnVybmVkLWtleS0wMDE=", "base64"),tag: "cpapi-money-live", created: 1760000000, nonce: "00112233445566778899aabbccddeeff",});console.log(headers.Signature); // sig1=:R9GX6U0TLBLhlI+svFkxE1R2l3ig+ez0YEPToOzjTt0=: -
Control server. The Control test vector was signed in the past, so start the server with its clock set to the vector’s time. Save
Date.now = () => 1760000010000;asfake-clock.mjs, then start the server withCPAPI_ENVIRONMENT=live,CPAPI_AUTHORITY=studio.example.com, anyCPAPI_LAUNCH_BASEsuch ashttps://play.example.com/start, the vector’s key ID and key inCPAPI_CONTROL_KEYIDandCPAPI_CONTROL_SECRET_BASE64, andnode --import ./fake-clock.mjs control-server.mjs. Send the vector’s session request: it must get201. Send it again unchanged: it must get401replayed_nonce. Then send the recovery lookup: it must get200with the same session. -
A real run. Register your server’s URL, then start a certification run from the cabinet, as CPAPI certification describes. If a check fails, common failures lists the usual causes.
Before production
Section titled “Before production”- Storage. Keep sessions, their
Idempotency-Keyvalues and seen nonces in your database, shared by every instance. Keep nonces for 24 hours and idempotency keys for as long as their sessions. Store each bet and win before its first call. - Players. Key a player by
tenant_idandplayer_reftogether. - Your game. Enforce your own bet limits and open each round only on a
committedbet. A player’s new ordinary or Sweepstakes session accepts bets for 24 hours from the operator’s launch. At expiry, settle any win for a committed bet on the original session and ask the player to reopen the game from the operator’s site. - Unresolved calls. Record when you first receive each signed session create request. Keep each uncertain bet with its original transaction ID, launch and payload. Use the Money client to read the bet’s status with backoff. Follow the bet status checks across the session lifetime change. Contact support if the bet’s outcome stays unresolved. Reuse the original idempotency key and body for any permitted retry.
- Delivery. Serve your API over
httpswithout compression, answer within 5 seconds, and keep your clock in sync.