# Xybrid Platform API auth.md

This is the canonical registration guide for software agents using the Xybrid
Platform API. An agent can register **anonymously**: it solves a proof of
work and receives a restricted API key for a new provisional workspace, plus
a claim token that a human later uses to adopt the workspace. No account,
browser, OAuth client or prior credential is needed.

The identity provider advertises this guide in the `agent_auth` member of its
authorization-server discovery documents:

```json
{
  "agent_auth": {
    "skill": "https://api.xybrid.dev/auth.md",
    "register_uri": "https://api.xybrid.dev/v1/agent/connect",
    "claim_uri": "https://api.xybrid.dev/v1/claims/accept",
    "identity_types_supported": ["anonymous"],
    "anonymous": {
      "credential_types_supported": ["api_key"]
    }
  }
}
```

`register_uri` is the connect request in step 4. `claim_uri` is the
browser-only acceptance endpoint behind the human claim page (step 8);
agents never call it.

## Origins

Use one environment's origins together. Never follow redirects on these
requests, and never take a host from a response.

| Environment | API origin | Console (claim links) | OTLP traces | Identity provider |
|---|---|---|---|---|
| Production | `https://api.xybrid.dev` | `https://console.xybrid.dev` | `https://ingest.xybrid.dev/v1/traces` | `https://auth.xybrid.dev` |
| Staging | `https://staging.api.xybrid.dev` | `https://staging.xybrid.dev` | `https://staging.ingest.xybrid.dev/v1/traces` | `https://staging.auth.xybrid.dev` |

Agent signup, claim and workspace routes, and other REST/MCP errors, are flat
JSON: `{"error": "<code>", "message": "...", ...details}`. Managed inference
and other gateway routes (`/v1/chat/completions`, `/v1/embeddings`,
`/v1/audio/*`, `/v1/text-to-speech/*`, and the voice catalogs) use the
OpenAI-compatible shape instead:
`{"error": {"code": "<code>", "message": "...", "type": "<type>"}}`. Read
`error.code` there, not a top-level `error` string. Responses that carry
credentials are sent with `Cache-Control: no-store`.

## 1. Get a challenge

```http
GET /v1/agent/challenge
```

`200` answers:

```json
{
  "challenge": "v1.1767225600.20.<random>.<mac>",
  "difficulty": 20,
  "expires_at": "2026-01-01T00:05:00Z",
  "algorithm": "sha256-leading-zero-bits",
  "collect_via": false
}
```

Treat `challenge` as opaque. It is valid for five minutes (until
`expires_at`) and for one workspace only. `difficulty` is between 18 and 28
bits; 20 by default.

Send `client_info.via` only if `collect_via` is `true`. It is `false` until
collection is enabled; older APIs omit the field, which also means `false`.

- `403 agent_signup_closed`: signup is switched off (`"reason": "disabled"`)
  or at its global daily capacity (`"reason": "capacity"`). The body also
  carries `console_url` and `min_cli_version`. Stop and tell the human to
  create a workspace and API key in the console instead.
- `503 agent_signup_unavailable`: signup is temporarily unavailable. Try
  again later; do not loop.

## 2. Solve the proof of work

Find a `nonce` such that

```text
SHA256(UTF8(challenge) || ":" || ASCII(nonce))
```

starts with at least `difficulty` zero bits, counted from the most
significant bit of the first byte. The nonce is sent as a string holding a
canonical decimal unsigned 64-bit integer: ASCII digits only, no sign, no
whitespace, no leading zeros (`"0"` itself is allowed), at most
`18446744073709551615`. Any other spelling, such as `"047"`, is rejected even
when its hash qualifies.

A reference solver, in Python's standard library:

```python
import hashlib

def leading_zero_bits(digest: bytes) -> int:
    bits = 0
    for byte in digest:
        if byte:
            return bits + 8 - byte.bit_length()
        bits += 8
    return bits

def solve(challenge: str, difficulty: int) -> str:
    nonce = 0
    while True:
        digest = hashlib.sha256(f"{challenge}:{nonce}".encode("utf-8")).digest()
        if leading_zero_bits(digest) >= difficulty:
            return str(nonce)
        nonce += 1
```

Test vectors (smallest qualifying nonce):

| Challenge | Difficulty | Nonce | Leading zero bits |
|---|---|---|---|
| `xybrid-pow-test-vector` | 8 | `47` | 8 |
| `xybrid-pow-test-vector` | 13 | `2900` | 13 |
| `xybrid-pow-test-vector` | 20 | `440423` | 21 |
| `v1.1767225600.20.AAAAAAAAAAAAAAAAAAAAAA.vector` | 13 | `3285` | 13 |
| `v1.1767225600.20.AAAAAAAAAAAAAAAAAAAAAA.vector` | 20 | `1184772` | 20 |

## 3. Save retry state before connecting

Generate an `Idempotency-Key` of 32 to 128 characters from `[A-Za-z0-9_-]`,
for example 32 random bytes in unpadded base64url. Save it, with the
challenge and nonce, in private storage **before** sending the connect
request. If the answer is lost, repeating the same request returns the same
workspace instead of creating a second one.

## 4. Connect (register)

```http
POST /v1/agent/connect
Content-Type: application/json
Idempotency-Key: <32-128 characters of [A-Za-z0-9_-]>

{
  "challenge": "<challenge from step 1>",
  "nonce": "<nonce from step 2>",
  "source": "claude-code",
  "project_name": "my-app",
  "client_info": {"cli_version": "0.18.0", "os": "macos", "arch": "arm64"}
}
```

Send exactly one `Idempotency-Key` header. The body is at most 16 KiB.

| Field | Required | Meaning |
|---|---|---|
| `challenge` | yes | The challenge from step 1 |
| `nonce` | yes | The canonical decimal nonce from step 2, as a string |
| `source` | no | The self-reported agent, normalized to at most 32 characters of `[a-z0-9-]`; never verified |
| `project_name` | no | Becomes the workspace name, at most 48 characters |
| `install_id` | no | A random install identifier, 16 to 128 characters of `[A-Za-z0-9_-]`; stored only as an HMAC |
| `client_info` | no | Only the string keys `cli_version`, `sdk_version`, `os`, `arch` and `binding` are kept, 64 characters each. Optional `via` accepts exactly `web-copy`, `setup-prompt`, `llms-txt`, `skill`, `mcp` or `docs`; it is ignored until attribution collection is enabled, and never overwrites a reused provision's original attribution. |

`201 Created` answers a new workspace; `200 OK` with `"replayed": true`
answers a retry with the same `Idempotency-Key` within ten minutes:

```json
{
  "api_key": "sk_live_...",
  "key_prefix": "sk_live_abcd1234",
  "scope": "client",
  "organization": {"slug": "my-app", "name": "my-app"},
  "project": {"slug": "default", "name": "Default"},
  "key_expires_at": "2026-01-08T00:00:00Z",
  "claim_expires_at": "2026-01-15T00:00:00Z",
  "claim_token": "<43 characters of [A-Za-z0-9_-]>",
  "limits": {"gateway_daily_requests": 25, "max_projects": 5},
  "terms_url": "https://www.xybrid.ai/terms",
  "privacy_url": "https://www.xybrid.ai/privacy",
  "replayed": false
}
```

| Field | Meaning |
|---|---|
| `api_key` | The credential, shown once. Use it as a bearer token |
| `key_prefix` | A non-secret identifier for the key, safe to log |
| `scope` | Always `client` (see "What the key can do") |
| `organization`, `project` | The provisional workspace and its first project |
| `key_expires_at` | When the key stops working unless the workspace is claimed (RFC 3339) |
| `claim_expires_at` | The last moment a human can claim the workspace; after it the workspace is deleted (RFC 3339) |
| `claim_token` | The secret a human uses to claim the workspace |
| `limits` | `gateway_daily_requests` for managed inference and `max_projects` for this workspace |
| `terms_url`, `privacy_url` | The documents the human accepts when claiming; omitted when not configured |
| `replayed` | `true` when an `Idempotency-Key` retry re-issued the credentials |

A replayed answer keeps the same workspace and deadlines but carries a
**new** `api_key` and `claim_token`; the previous key is revoked. Always keep
the latest pair.

### Errors and retries

| Answer | What to do |
|---|---|
| `400 challenge_expired`, `challenge_invalid`, `proof_of_work_invalid` | Get and solve a fresh challenge, then retry once with the same `Idempotency-Key` |
| `400 idempotency_key_required`, `idempotency_key_invalid`, `invalid_request` | Fix the request; do not retry it unchanged |
| `409 idempotency_key_expired`, `idempotency_key_conflict`, `workspace_claimed`, `workspace_unavailable` | Start over once with a new `Idempotency-Key` and a new challenge |
| `409 challenge_replayed` | Stop and report it |
| `409 slug_unavailable` | Retry the same request once |
| `403 agent_signup_closed` | Stop; signup is closed (see step 1) |
| `429 agent_signup_rate_limited` | Stop and report it; `Retry-After` says when the network's cap resets |
| `503 agent_signup_busy` | Wait `Retry-After` seconds (2) and retry with the same `Idempotency-Key`, up to three times |
| `503 agent_signup_unavailable`, `client_ip_unavailable` | Temporarily unavailable; report it and keep the retry state |
| No answer, another 5xx or a malformed 2xx | The request may have been applied: repeat the identical request (same key, challenge and nonce) within ten minutes |

A retry with a known `Idempotency-Key` is resolved before the challenge is
checked, so an expired challenge does not prevent recovering a lost answer
inside the ten-minute window.

## 5. Store the credentials

Check that `api_key` matches `^[A-Za-z0-9_-]{8,256}$` and `claim_token`
matches `^[A-Za-z0-9_-]{32,128}$`. Then save both, with `key_expires_at`,
`claim_expires_at`, `terms_url` and `privacy_url`, in storage private to the
current user (for example a file with mode `0600`) before doing anything
else with them.

- Never print either secret, pass it on a command line, or put it in a URL,
  chat transcript, log, tracked file, commit, pull request or issue.
- Read the key from the environment or a gitignored file at run time, for
  example as `XYBRID_API_KEY`.
- The claim token goes only to private storage and, as a claim link, to the
  human in private chat. Anyone holding it can claim the workspace.

## 6. Use the key

Send the key as a bearer token:

```http
Authorization: Bearer <api_key>
```

Check the workspace at any time; this works for an expired, unpurged
workspace too:

```http
GET /v1/agent/workspace
Authorization: Bearer <api_key>
```

It answers `200` with `organization`, `project`, `scope`, `provisional`,
`claimed`, `expired`, `key_expires_at`, `claim_expires_at` and
`verification` (`state` is `received`, `none` or `unavailable`, with
`traces_received`, `spans`, `traces`, `first_ingested_at` and
`last_ingested_at`). An unknown, revoked or purged key gets
`401 invalid_api_key`.

### What the key can do

Agent-signup keys have `client` scope. On the API origin they are accepted
only by:

- `POST /v1/chat/completions`, `POST /v1/embeddings` and
  `POST /v1/audio/speech`, `/v1/audio/transcriptions`,
  `/v1/audio/translations` (managed inference, within
  `limits.gateway_daily_requests`)
- `POST /v1/text-to-speech/{voice_id}` and `.../stream`
- `GET /v1/models`, `GET /v1/voices`, `GET /v2/voices`
- `GET /v1/routing/advice`
- `POST /v1/skills/{slug}/resolve`
- `GET /v1/agent/workspace`

They can also write OpenTelemetry traces to the environment's OTLP endpoint
with the same bearer header.

A `client` key **cannot** read telemetry (traces, usage, analytics), use the
telemetry MCP endpoint `/mcp`, manage keys, or administer the workspace;
those requests get `403`. Claiming the workspace does not change this: the
key keeps `client` scope after a claim. Reading telemetry needs a full-scope
key that a developer creates in the console, or an OAuth grant a human
approves for MCP.

### Expiry

Use the deadlines from the response; do not compute them. By default the
key stops on day 7 and the claim window closes on day 14, but the platform
can set shorter windows.

- Before `key_expires_at`: the key works as described above.
- After `key_expires_at`, until `claim_expires_at`: protected routes answer
  `401` with `X-Xybrid-Workspace: expired`. REST and MCP use flat
  `{"error": "workspace_expired", "message": "...", "key_expires_at",
  "claim_expires_at"}`. Gateway routes use
  `{"error": {"code": "workspace_expired", "message": "...",
  "type": "authentication_error"}}` and **do not** include the deadlines.
  Call `GET /v1/agent/workspace` for `key_expires_at` and
  `claim_expires_at`; it still answers with `"expired": true`. Ask the
  human to claim; claiming restores the key.
- After `claim_expires_at`: the unclaimed workspace and its data are
  deleted, and the key is refused with `401` (`invalid_api_key` from
  `GET /v1/agent/workspace`). Register again only if the human asks.

### Another project in the same workspace

```http
POST /v1/agent/projects
Content-Type: application/json
Idempotency-Key: <a new 32-128 character key>

{"claim_token": "<claim_token>", "project_name": "another-repo"}
```

`201` (or `200` with `"replayed": true`) returns the same fields as connect,
without `claim_token`, for a new project with its own `client` key. The
workspace's deadlines never reset. It answers `409 project_limit_reached`
past `limits.max_projects`, `409 workspace_claimed` once claimed,
`403 workspace_expired` after `key_expires_at`, `404 claim_token_invalid`
for an unknown token, and the signup-closed answers above.

## 7. Hand off to the human

Build the claim link locally from the environment's pinned console origin:

```text
<console-origin>/claim/<URL-encoded claim_token>
```

For production: `https://console.xybrid.dev/claim/<claim_token>`. Show it to
the human in private chat only, with the actual `key_expires_at`,
`claim_expires_at`, `terms_url` and `privacy_url`.

## 8. The human claims the workspace

Opening the link stores the token in a short-lived cookie and redirects to
the console's claim page, so the token never stays in the address bar. There
the human:

1. signs in with GitHub (no prior account needed);
2. reviews what the workspace holds: its projects, key prefixes and trace
   counts;
3. accepts the terms of service and privacy policy, and optionally rotates
   the workspace's keys;
4. claims it, becoming the workspace's owner.

The console's server performs the acceptance with
`POST /v1/claims/accept` (the `claim_uri`), authenticated by the human's
browser session, with the claim token and `"accept_terms": true` in the
body. API keys are refused there with `403`, and agents must never call it.
After a claim the workspace and its history are kept, a stopped key works
again, and `GET /v1/agent/workspace` reports `"claimed": true`. If the human
rotated keys, the agent's key is revoked; the human supplies the new one.

## What this is not

- There is no token exchange: the credential is the API key returned by
  connect. No OAuth client, client-credentials grant, ID-JAG or
  `service_auth` registration is involved, and `identity_types_supported` is
  only `anonymous`.
- Registration grants no access to any existing workspace, and claiming
  never widens a key's scope.
- OAuth client registration on the identity provider (for the telemetry MCP
  endpoint) creates client metadata only; it does not provision a workspace,
  key or project access.
