# Zero-Install Agent Auth & Ephemeral Diff Contract (`confighub.com/auth.md`)

> Status: PROVISIONAL (preview agent bootstrap contract — backend sidecar routes `/v1/agent/identity`, `/claim/{code}`, and `/v1/diffs` are provisional and pending live deployment on confighub.com).

## Overview & Goals

This static discovery document (`GET https://confighub.com/auth.md`) lets an unauthenticated coding agent or CLI environment with only `curl` and standard cryptographic tools discover how to:

1. Generate an **Ed25519** keypair locally so private keys never leave the client.
2. Register an unclaimed ephemeral identity via `POST /v1/agent/identity` and surface a Browser Claim URL (`https://confighub.com/claim/{claim_code}`) to a human owner.
3. Poll `GET /v1/agent/identity/{identity_id}/status` using proof-of-possession headers (`X-ConfigHub-Key-Id` + `X-ConfigHub-Signature`) until the human owner authorizes scope.
4. Publish client-side redacted diff cards via `POST /v1/diffs` with strict TTL expiry (`GET /d/{short_id}`).

---

## 1. API Base URL & Discovery Headers

- **Static Discovery Document:** `GET https://confighub.com/auth.md`
  - **Authentication:** None (public read)
  - **Headers:** `Content-Type: text/markdown; charset=utf-8`, `Cache-Control: public, max-age=300`
- **API Base URL:** `https://api.confighub.com` (or active control-plane / provisional `agentauth-server` sidecar origin when self-hosted or running in preview)
- **Supported Key Algorithm:** `Ed25519` (`"ed25519"`), encoded as standard Base64 of the raw 32-byte public key or PEM `SubjectPublicKeyInfo`.

---

## 2. Ephemeral Key Exchange: `POST /v1/agent/identity`

An agent generates an Ed25519 keypair locally and registers the public key to obtain an unclaimed ephemeral identity and a browser Claim URL.

### Request

```http
POST /v1/agent/identity HTTP/1.1
Host: api.confighub.com
Content-Type: application/json
```

```json
{
  "key_algorithm": "ed25519",
  "public_key": "<base64-encoded-32-byte-ed25519-public-key>",
  "agent_name": "claude-code",
  "workspace_label": "shop-api",
  "requested_scope": {
    "role": "proposer",
    "space_hint": "shop-staging"
  },
  "ttl_seconds": 3600
}
```

| Field | Type | Required | Constraints |
|---|---|---|---|
| `key_algorithm` | string | Yes | `"ed25519"` |
| `public_key` | string | Yes | Standard Base64-encoded raw 32-byte Ed25519 public key (or PEM SubjectPublicKeyInfo) |
| `agent_name` | string | Yes | Non-empty identifier (`<= 64` chars, e.g., `"claude-code"`, `"codex"`) |
| `workspace_label` | string | No | Human-readable folder or repo label (`<= 128` chars); no secrets |
| `requested_scope` | object | No | Advisory hint shown to the owner on the Claim screen; never self-granted |
| `ttl_seconds` | integer | No | Default `3600` (1 hour); min `300`, max `86400` (24 hours) |

### Response (`201 Created`)

```json
{
  "identity_id": "agid_01J...",
  "status": "unclaimed",
  "claim_url": "https://confighub.com/claim/CH-8F2K-9Q1M",
  "claim_code": "CH-8F2K-9Q1M",
  "ephemeral_token": "cheph_...",
  "expires_at": "2026-11-29T21:25:00Z",
  "poll_url": "/v1/agent/identity/agid_01J.../status",
  "poll_interval_seconds": 3
}
```

### Security Invariants

- **Zero ambient privilege:** While `status == "unclaimed"`, `identity_id` and `ephemeral_token` cannot read, list, propose, or approve any Space, Unit, or ChangeOrder in any organization.
- **Key binding (Proof-of-Possession):** Subsequent authenticated requests from the agent must present both `ephemeral_token` (or issued scoped token after claim) and a signature/PoP timestamp verified against `public_key` using `X-ConfigHub-Key-Id` and `X-ConfigHub-Signature`, preventing bearer-token-only replay if the token leaks.
- **Rate limiting:** Per-IP and per-public-key creation limits apply (`429 Too Many Requests` with `Retry-After`).
- **Unclaimed expiry:** If not claimed before `expires_at` (or within the claim window), the identity transitions to `expired` and cannot be claimed.

---

## 3. Browser Claim URL & Status Polling

### Owner Claim Flow (`GET` / `POST https://confighub.com/claim/{claim_code}`)

1. The agent prints `claim_url` and `claim_code` to the terminal or chat response.
2. The human owner opens `claim_url` (`GET /claim/{claim_code}`) in a browser and signs in with their ConfigHub account.
3. The Claim page displays:
   - `agent_name`, `workspace_label`, and key fingerprint (SHA-256 of `public_key`)
   - `requested_scope` (marked clearly as an untrusted client hint)
   - Target organization, Space(s), and permission boundary selectable by the owner (`read_only`, `propose_only`; never auto-approving owner-gated production changes)
   - Explicit lifetime (`expires_at`)
4. The owner submits `POST /claim/{claim_code}` (**Claim & Authorize** or **Decline / Revoke**):
   - Claiming creates a server-side `ServiceAccount` / ephemeral grant bound to that owner, organization, and selected Space scope, and records an audit event naming the claiming user and key fingerprint.
   - Declining marks the identity `revoked` immediately.

### Agent Status Polling (`GET /v1/agent/identity/{identity_id}/status`)

Authenticated with `Authorization: Bearer <ephemeral_token>` plus PoP headers `X-ConfigHub-Key-Id` and `X-ConfigHub-Signature`:

```http
GET /v1/agent/identity/agid_01J.../status HTTP/1.1
Host: api.confighub.com
Authorization: Bearer cheph_...
X-ConfigHub-Key-Id: agid_01J...
X-ConfigHub-Signature: <base64-ed25519-signature>
```

```json
{
  "identity_id": "agid_01J...",
  "status": "claimed",
  "organization_id": "org_...",
  "granted_scope": {
    "role": "proposer",
    "spaces": ["shop-staging"]
  },
  "expires_at": "2026-11-29T21:25:00Z"
}
```

Possible `status` values:
- `"unclaimed"` — waiting on owner browser action; keep polling at `poll_interval_seconds`.
- `"claimed"` — owner bound scope; the agent may now use `granted_scope` until `expires_at`.
- `"revoked"` — owner declined or revoked the identity; agent must stop and discard keys.
- `"expired"` — TTL elapsed; agent must generate a new keypair to try again.

---

## 4. Hosted Redacted Short-Link Diff (`POST /v1/diffs`)

When a user or agent wants to share a diff card produced by `cub mini changes --export-md` or `--export-html` via a short link instead of pasting a file, it uploads **only the already-redacted** diff payload to obtain a time-limited URL.

### Create Short-Link Diff (`POST /v1/diffs`)

```http
POST /v1/diffs HTTP/1.1
Host: api.confighub.com
Authorization: Bearer <token>
X-ConfigHub-Key-Id: <identity_id>
X-ConfigHub-Signature: <base64-ed25519-signature>
Content-Type: application/json
```

```json
{
  "title": "shop-api · Raise rate limit for launch",
  "format": "html",
  "content": "<!doctype html>...",
  "content_sha256": "<hex-sha256>",
  "redacted_count": 1,
  "ttl_seconds": 86400,
  "visibility": "unlisted_link"
}
```

| Field | Type | Required | Constraints |
|---|---|---|---|
| `title` | string | Yes | Summary title (`<= 160` chars) |
| `format` | string | Yes | `"markdown"` or `"html"` |
| `content` | string | Yes | Self-contained redacted Markdown or HTML (`<= 512 KiB`) |
| `content_sha256` | string | Yes | Lowercase hex SHA-256 of `content` |
| `redacted_count` | integer | No | Number of secrets redacted client-side |
| `ttl_seconds` | integer | No | Default `86400` (24 hours); min `300` (5 minutes); max `604800` (7 days) |
| `visibility` | string | No | `"unlisted_link"` (default) or `"org_only"` (requires claimed org membership) |

### Server Defense-in-Depth & Response

1. **Server-side secret scan:** Before persisting, the server scans `title` and `content` for unredacted high-risk token patterns (e.g., `sk_live_`, `rk_live_`, `ghp_`, `glpat-`, `AKIA`, JWTs, URL userinfo passwords). If detected, the server rejects the upload with `422 Unprocessable Entity` (`error: "unredacted_credential_detected"`) and stores nothing.
2. **HTML sanitization & strict CSP:** When serving `"html"` diffs on `GET /d/{short_id}`, the server enforces sandbox headers (`Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox`, `X-Content-Type-Options: nosniff`, `X-Robots-Tag: noindex, nofollow`, `Cache-Control: no-store`).
3. **Response (`201 Created`):**

```json
{
  "diff_id": "diff_01J...",
  "short_url": "https://confighub.com/d/k9mP4xR2vQ",
  "expires_at": "2026-11-30T20:25:00Z",
  "ttl_seconds": 86400,
  "content_sha256": "<hex-sha256>"
}
```

### Read & Expiry Lifecycle

- **Read (`GET https://confighub.com/d/{short_id}`):**
  - High-entropy opaque `short_id` (at least 120 bits of randomness encoded in URL-safe base62/base64url).
  - Returns `200 OK` while `now < expires_at`.
  - Returns `410 Gone` (or `404 Not Found` after background purge) once `now >= expires_at`; expired blobs are hard-deleted by background sweep.
- **Early revocation (`DELETE /v1/diffs/{diff_id}`):**
  - The creating identity (or claiming organization admin) can delete a short link immediately before `expires_at`, returning `204 No Content`.

---

## 5. Client-Side Redaction Rules (Mandatory)

Agents and CLIs **must never** upload raw credentials, `.env` secrets, private keys, or unredacted sensitive configuration to `POST /v1/diffs` or any registration metadata field (`agent_name`, `workspace_label`, `requested_scope`):

1. Run `Secret` and `Credential` redaction before any diff payload leaves the client machine.
2. Strip or mask all secret values, Kubernetes `Secret` `data`/`stringData` payloads, private keys (`-----BEGIN ... PRIVATE KEY-----`), URLs with embedded userinfo passwords (`https://user:pass@host`), and database connection-string passwords.
3. Redact all recognized credential prefixes and token formats (`sk_live_`, `rk_live_`, `ghp_`, `glpat-`, `AKIA`, bearer tokens, and JWTs) prior to computing `content_sha256`.
4. Verify `422 unredacted_credential_detected` failures locally rather than retrying with raw payloads.
