# Authentication

Every authenticated request carries `Authorization: Bearer <token>`. The token is either an `sk_live_*` API key (machine partners) or an OAuth 2.1 access token (a PredictAsiaX builder account signed in through connect.predictasiax.com). To place orders for regular PredictAsiaX users on their own accounts, use [App connections](https://docs.predictasiax.com/builders#app-connections). Sandbox and production share the same host + the same `sk_live_` prefix — capability is differentiated by the key's tier flag. HMAC request signing (`PAX-*` headers) is live for any active API key — see [section 3](https://docs.predictasiax.com/auth#hmac).

## Overview

| Scheme | Use case | Header(s) | Status |
|---|---|---|---|
| [API Key (Bearer)](https://docs.predictasiax.com/auth#api-key) | Machine-to-machine, creator bots, aggregators | `Authorization: Bearer sk_live_…` | Live |
| [OAuth 2.1 + PKCE](https://docs.predictasiax.com/auth#oauth) | Apps acting on a builder account (Builder Portal, apps a builder signed in to) | `Authorization: Bearer <access_token>` | Live |
| [Sign in with PredictAsiaX](https://docs.predictasiax.com/auth#signin-with) | Let any PredictAsiaX user sign in to your app (identity only, no account access) | OpenID Connect: `id_token` (ES256) | Live |
| [HMAC request-signing](https://docs.predictasiax.com/auth#hmac) | Machine-to-machine — any active API key signs per-request | `PAX-ADDRESS / PAX-TIMESTAMP / PAX-NONCE / PAX-SIGNATURE` | Live |

## 1. API Key (Bearer)

Send your `sk_live_*` key as a Bearer token. No signing. Rate-limited per key. Same header the OAuth flow uses — the router decides based on prefix.

```
curl https://api.predictasiax.com/v1/balance \
  -H "Authorization: Bearer sk_live_YOUR_KEY_HERE"
```

### Minting a key

Fastest path: hit [/sandbox/](https://docs.predictasiax.com/sandbox/) or `POST /v1/sandbox-keys` — no auth, tier `sandbox`, $10/order + $100/day caps, sandbox and production share the same host so no environment swap is needed later. See [Getting Started](https://docs.predictasiax.com/getting-started) for the end-to-end flow. Long-lived production keys are issued the moment you apply — `POST /v1/apply` returns a live `sk_live_*` key in the response body for every track, with no approval step (you can also mint and rotate additional keys from the Builder Portal → Settings → API Keys).

Every successful mint returns the raw `api_key` exactly once. The server keeps only a one-way `sha256(key)` hash plus an 8-character prefix for lookup — the raw key itself is never stored, so if you lose it, rotate.

### Environments & tiers

Every `sk_live_*` key carries a *tier* flag that controls its capabilities and per-order / daily notional caps — enforced server-side on every request. The tier does **not** change your request rate: the published [rate limits](https://docs.predictasiax.com/rate-limits) are identical for every tier.

| Tier | Capability | Notional cap |
|---|---|---|
| `sandbox` SANDBOX | 1,000 virtual USDT; orders are validated, cap-checked and filled in a simulation at the live market price. Zero real-money risk. Minted anonymously via `POST /v1/sandbox-keys`; 30-day expiry. | $10 / order · $100 / day |
| `self_serve` LIVE | Instant live key from `POST /v1/apply` (any track). Real-money trading with entry notional caps. | $100 / order · $1,000 / day |
| `read_live` LIVE | Reached at $100 30-day volume. Live market data + account reads; order placement requires auto-graduation to `trade_capped`. | Read-only — cannot place orders |
| `trade_capped` LIVE | Real-money trading with per-order + daily notional ceilings. | $100 / order · $1,000 / day |
| `trade_full` LIVE | Unrestricted real-money trading, MM-tier order sizes. | Uncapped |
| `genesis` LIVE | Live top-20 ranking by 30-day attributed volume — uncapped API keys and 1.5× builder points. Auto-granted and auto-revoked; not an application destination. | Uncapped |
| `partner` | Highest auto-graduated tier — reached at `$1,000,000` 30-day volume. Same automatic ladder as every other tier; no signed agreement, no negotiated terms. (`institutional` is just an application label whose key climbs this same ladder.) | Uncapped |

The caps apply to orders on your own account and your subaccount slots. Orders you place for another account with `on_behalf_of` (a user who connected your app, or an account that made you its trading agent) are bounded by the limits that account set on the connection instead: per-order maximum, rolling 24h total, markets and expiry, reserved atomically on every order. A `read_live` key cannot place them either (`TIER_UPGRADE_REQUIRED`).

Mismatched credentials return `401 WRONG_ENV_KEY`.

## 2. OAuth 2.1 + PKCE

For apps that act on a PredictAsiaX **builder account**. [connect.predictasiax.com](https://connect.predictasiax.com) signs in with builder account credentials only; a regular predictasiax.com account cannot sign in there. To trade for regular users on their own accounts, use [App connections](https://docs.predictasiax.com/builders#app-connections) instead: the user approves your app on `predictasiax.com/connect` and you send your API key with `on_behalf_of=pxu_...`. Full OAuth flow: authorize → callback with `code` + PKCE `code_verifier` → `POST /oauth/token` → receive `access_token` (short-lived) + `refresh_token` (rotating).

```
curl https://api.predictasiax.com/v1/balance \
  -H "Authorization: Bearer <access_token>"
```

Access tokens expire; refresh with the standard OAuth 2.1 rotating refresh flow. Reuse of a refresh token revokes the whole family (`REFRESH_TOKEN_REUSED`).

## 3. HMAC request signing

Per-request signing for machine-to-machine integrations. It is **live** — no ops provisioning or enterprise agreement required. Any active API key carries its own signing secret, so the same credential works as either `Authorization: Bearer` or an HMAC signature; pick whichever your stack prefers. `POLY-*` header aliases are accepted, so an existing signer that sends those header names ports over by swapping the host and credentials. Keys minted or rotated before HMAC shipped have no signing secret on file — [rotate](https://docs.predictasiax.com/auth#rotate) such a key once to enable signing.

| Header | Value |
|---|---|
| `PAX-ADDRESS` | Your API key **id** — the `api_…` identifier returned as `api_key_id` when the key was minted. This is *not* the secret. |
| `PAX-TIMESTAMP` | UNIX **seconds** epoch (not milliseconds). Must be within ±300s (5 min) of server clock — outside window returns `TIMESTAMP_SKEW`. |
| `PAX-NONCE` | Fresh random unique-per-request string, at most 256 characters. Cached 600s and bound into the signature; replay returns `NONCE_REUSED`, a longer value `401 AUTH_INVALID`. |
| `PAX-METHOD` | *Optional, not needed.* The signature always covers the HTTP method the request is sent with. If this header is present it must name that same method, or the request is rejected with `401 AUTH_INVALID`. |
| `PAX-SIGNATURE` | Standard base64 of `HMAC-SHA256(apiSecret, signingString)` — see below. |

The signing key is your full issued secret string (the `sk_live_…` / `sk_test_…` value shown once at mint). The signing string is five fields joined by newlines:

```
signingString =
  timestamp + "\n" +      # same value as PAX-TIMESTAMP
  nonce     + "\n" +      # same value as PAX-NONCE
  method    + "\n" +      # uppercase HTTP method
  path      + "\n" +      # request path INCLUDING query string, e.g. /v1/orders
  body                    # raw request body, or "" for GET/no-body

PAX-SIGNATURE = base64( HMAC_SHA256( apiSecret, signingString ) )
```

```
// Node — sign a POST /v1/orders request
import crypto from "node:crypto";
const apiKeyId = "api_live_...";          // PAX-ADDRESS
const apiSecret = "sk_live_...";          // signing key (shown once at mint)
const ts = Math.floor(Date.now() / 1000).toString();
const nonce = crypto.randomBytes(16).toString("hex");
const method = "POST";
const path = "/v1/orders";
const body = JSON.stringify({ market_id: "hadjar-f1-2026", side: "yes", price: "0.05", size: "20", client_order_id: "c-1" });
const signingString = [ts, nonce, method, path, body].join("\n");
const sig = crypto.createHmac("sha256", apiSecret).update(signingString).digest("base64");
// headers: PAX-ADDRESS=apiKeyId, PAX-TIMESTAMP=ts, PAX-NONCE=nonce, PAX-SIGNATURE=sig
// The official SDKs (3.0.0+) do this for you: new PaxClient({ apiKey, keyId }) / PaxClient(api_key=..., key_id=...)
```

Until the signature verifies, every failure returns the same `401 SIGNATURE_INVALID` (wrong signature, unknown key id, or a key with no signing secret), so key ids cannot be probed. Once the signature verifies: a replayed nonce returns `401 NONCE_REUSED`; an inactive or expired key, or a failed IP allowlist, returns `401 AUTH_INVALID`; a key used in the wrong environment returns `401 WRONG_ENV_KEY`. The nonce is recorded only after the signature verifies. A timestamp more than 300 s off returns `401 TIMESTAMP_SKEW`.

Send one credential type per request. A request that carries both `Authorization: Bearer` and `PAX-*` signing headers is rejected with `401 AUTH_INVALID`.

## 4. Sign in with PredictAsiaX (OpenID Connect)

Let any PredictAsiaX user sign in to your app with their PredictAsiaX account. It is identity only: your app learns who the user is and gets no access to their account, balance or trading. To trade for a user, ask for that separately with [App connections](https://docs.predictasiax.com/builders#app-connections).

- Issuer: `https://predictasiax.com/api/oidc`. Discovery: `https://predictasiax.com/api/oidc/.well-known/openid-configuration`, so a standard OpenID Connect client library configures itself.
- Authorization Code flow with PKCE (`S256`, required). Public clients: no client secret. Your `client_id` and redirect URIs are the ones you register for App connections (`PATCH /v1/apps/{app_id}`), and your app must be approved.
- Send the user to `https://predictasiax.com/signin-with?response_type=code&client_id=<client_id>&redirect_uri=<registered URI>&scope=openid%20profile%20email&state=<yours>&nonce=<yours>&code_challenge=<S256 challenge>&code_challenge_method=S256`. The user signs in on predictasiax.com and sees what your app will get. A `redirect_uri` you did not register is never redirected to.
- Approved: the user returns with `code` and your `state`. Declined: `error=access_denied`. The code is single-use and expires after 60 seconds.
- Exchange it: `POST https://predictasiax.com/api/oidc/token` (`application/x-www-form-urlencoded`) with `grant_type=authorization_code`, `code`, `client_id`, `redirect_uri`, `code_verifier`. You get `id_token`, `access_token` (`pxo_...`, 600 seconds) and `scope`.
- `id_token`: ES256, verify it against `https://predictasiax.com/api/oidc/jwks`. Claims: `iss`, `sub`, `aud` and `azp` (your `client_id`), `iat`, `exp` (600 seconds), `nonce` when you sent one, and with the user's agreement `name`, `email`, `email_verified`.
- `sub` is `pxs_...`, stable for a user across all of your apps and unrelated to the value any other developer sees. It is not the account id. Key your users on `sub`, not on email.
- Scopes: `openid` (required), `profile` (`name`), `email`. The user can leave out their email even when you ask for it, and accounts created with a wallet have no email to share.
- `GET` or `POST https://predictasiax.com/api/oidc/userinfo` with `Authorization: Bearer pxo_...` returns the same claims. The token, userinfo, discovery and JWKS endpoints answer cross-origin requests from any site.
- Errors follow OAuth 2.0: `invalid_grant` (code invalid, expired, already used, or `client_id` / `redirect_uri` / `code_verifier` do not match), `unsupported_grant_type`, `invalid_token`, `slow_down` (rate limit).

```
// any OpenID Connect client, e.g. openid-client (Node)
const config = await client.discovery(new URL("https://predictasiax.com/api/oidc"), "<client_id>", undefined, client.None());
```

## WebSocket authentication

The WS endpoint at `wss://predictasiax.com/ws` accepts anonymous connections for public streams (`ticker`, `orderbook`, `fast_tick`, `markets_snapshot`). Public tapes such as `trade_executed` require no AUTH. To receive your own account's events, send an `AUTH` command after connect. Command names are uppercase per AsyncAPI — see [Downloads → AsyncAPI](https://docs.predictasiax.com/downloads).

### API clients: single-use sign-in token

Your API key is never sent on the socket. Mint a sign-in token over REST, then send it in `AUTH`:

```
curl -X POST https://api.predictasiax.com/v1/ws/token \
  -H "Authorization: Bearer sk_live_..."
{"ok":true,"data":{"token":"wst_...","expires_in":900,"expires_at_ms":...}}

wscat -c wss://predictasiax.com/ws
> {"method":"AUTH","token":"wst_..."}
< {"type":"authenticated","email":null,"account":"bld_...","auth":"api_token","isAdmin":false,"tier":"bronze","limits":{...}}
< {"type":"user_orders_update","event":"filled",...}
```

- `POST /v1/ws/token` needs scope `orders:read` and accepts every credential type the API accepts: `Authorization: Bearer` API key, HMAC signing headers, or an OAuth access token. At most 30 tokens per minute per account.
- A token is valid for 15 minutes and works once: a second `AUTH` with it, an expired token, or an unknown one gets `{"type":"auth_denied","code":"invalid_token"}`. Mint a new token for every connect and reconnect; the official SDKs (3.1.0+) do this for you.
- The socket is bound to the account the credential trades as. Order events for that account (`user_orders_update`: placed, filled, partial, rested, cancelled) are pushed to it without a subscription.
- A socket that is already signed in gets `auth_denied` / `already_authenticated`; open a new connection to sign in as another account.

### Web sessions

The predictasiax.com web app sends its own session token: `{"method":"AUTH","token":"<web session token>"}`, answered with `{"type":"authenticated","email":"...",...}`. A raw API key or OAuth access token in `AUTH` is rejected with `{"type":"auth_denied","code":"invalid_session"}`; use a sign-in token instead.

## Rotating a key

API keys mint and rotate through the Builder Portal → Settings → API Keys. OAuth apps are public clients (OAuth 2.1 + PKCE) and carry no client secret, so there is nothing to rotate at the app level. Webhook signing secrets rotate via `POST /v1/webhooks/{id}/rotate-secret` — see [/webhook-signing](https://docs.predictasiax.com/webhook-signing) for the 24h dual-signature grace behavior.

**Never commit secrets to git.** Store `sk_live_*` keys in a secret manager (AWS Secrets Manager, GCP Secret Manager, HashiCorp Vault). Rotate on any suspicion of leak.

Source: https://docs.predictasiax.com/auth
