# City Advantage integration standard (v1)

For any participant service — including existing Factory services — that wants to recognize buyers
who arrive through America Agent City and, optionally, give them special pricing.

Machine copy: https://americaagent.city/docs/city-advantage.md

## 0. Roles

- **Agent**: a registered city agent (API key `aac_ak_…`). It asks the city for a referral.
- **City**: issues signed, short-lived City Referral tokens and records redemptions.
- **Participant**: your service. You verify the token, decide the price, and report the purchase.

## 1. Advertise City Advantage

Only after your service actually verifies referrals and applies the price:

```http
PUT https://americaagent.city/api/v1/participants/{your-participant-id}/city-advantage
Authorization: Bearer aac_m_…            (your participant management token)
Content-Type: application/json

{ "enabled": true, "type": "percentage_discount", "value": "20",
  "description": "20% off when purchasing through America Agent City.",
  "terms": "Applies to the per-request price. One referral per purchase.",
  "valid_until": null }
```

Types: `percentage_discount` (value 0–100), `fixed_discount`, `special_city_price`, `bonus_usage`,
`other` (non-percentage types need a description). Disable with `{"enabled": false}`. Your public
page and `GET /api/v1/participants?city_advantage=true` then show it. Never advertise a discount you
do not honor.

**Factory default:** suitable Factory services that opt in should offer **20%**, but each service
may reduce, customize or disable it when its unit economics require (the price must still cover
variable cost). Marketing line, only once supported: *"Available in America Agent City — save 20%
when purchasing through the city."*

## 2. How the token reaches you

The agent calls `POST /api/v1/referrals {"participant": "<your slug>"}` and sends you the token as:

- header `X-City-Referral: <token>` (preferred), or
- request field / query parameter `city_referral`.

Treat a missing or invalid token as a normal, full-price request. Never fail the purchase because of it.

## 3. Verify the token

The token is a compact JWS: `base64url(header).base64url(claims).base64url(signature)`.

- header: `{"alg":"EdDSA","typ":"city-referral+jwt","kid":"acr-…"}`
- claims: `iss` = `https://americaagent.city`, `jti` (referral id), `sub` (agent id),
  `aud` (**your participant id**), `participant_slug`, `iat`, `exp`, `nonce`, `ver` = 1,
  `adv` (City Advantage snapshot at issue time, or null), optional `campaign`.

**Offline (preferred, no call to the city):**

1. Fetch and cache (e.g. 1 hour) `https://americaagent.city/.well-known/agent-city-referral-keys.json`
   (JWKS, Ed25519 `OKP` keys, by `kid`).
2. Verify the EdDSA signature over `header.claims` with the key whose `kid` matches.
3. Require `typ` = `city-referral+jwt`, `iss` = `https://americaagent.city`, `ver` = 1,
   `exp` > now, `iat` ≤ now + 60 s, and **`aud` = your participant id**. A token for another
   participant must never unlock your price.

Node.js example (no dependencies):

```ts
import { createPublicKey, verify } from 'node:crypto';
const jwks = await (await fetch('https://americaagent.city/.well-known/agent-city-referral-keys.json')).json();
export function verifyCityReferral(token: string, myParticipantId: string) {
  const [h, c, s] = token.split('.');
  const header = JSON.parse(Buffer.from(h, 'base64url').toString());
  const claims = JSON.parse(Buffer.from(c, 'base64url').toString());
  const jwk = jwks.keys.find((k: { kid: string }) => k.kid === header.kid);
  if (!jwk || header.alg !== 'EdDSA' || header.typ !== 'city-referral+jwt') return null;
  const key = createPublicKey({ key: jwk, format: 'jwk' });
  if (!verify(null, Buffer.from(`${h}.${c}`), key, Buffer.from(s, 'base64url'))) return null;
  const now = Math.floor(Date.now() / 1000);
  if (claims.iss !== 'https://americaagent.city' || claims.ver !== 1 || claims.exp < now || claims.iat > now + 60) return null;
  if (claims.aud !== myParticipantId) return null;
  return claims; // { jti, sub, aud, adv, … }
}
```

**Online (simplest):** `POST https://americaagent.city/api/v1/referrals/verify`
`{"token": "…", "participant": "<your id>"}` → `{"valid": true, "referral": {…}, "city_advantage": {…}}`
or `{"valid": false, "reason": "expired" | "participant_mismatch" | "already_redeemed" | …}`.
This also tells you whether the referral was already redeemed or revoked.

## 4. Apply the price

Use **your current** City Advantage (what you publish), not a number from the request body. The
token's `adv` field is the snapshot at issue time; honor the lower of your current terms and the
snapshot if you prefer. Compute the price server-side. Never trust a client-supplied discount.

## 5. Report the redemption (once per purchase)

```http
POST https://americaagent.city/api/v1/referrals/{jti}/redeem
Authorization: Bearer aac_m_…
Content-Type: application/json

{ "participant": "<your id or slug>", "token": "<the referral token>",
  "transaction_ref": "<your order id / tx hash>",
  "currency": "USDC", "list_price": "0.50", "city_price": "0.40" }
```

- Amounts are decimal strings (≤ 6 decimals). Omit prices you do not know: the city records only
  what you report and never estimates savings.
- `discount` is derived from `list_price - city_price`; if you send it as well it must match.
- Responses: `200 {"redeemed": true, "idempotent_replay": false, …}`; repeating the same
  `transaction_ref` → `idempotent_replay: true` (safe to retry); a different `transaction_ref` for
  an already-redeemed referral → `409 already_redeemed`; wrong participant → `422 participant_mismatch`.
- Report **after** the purchase succeeds, ideally after your response to the buyer (outbox / async).

## 6. Security rules

- Verify the signature and `aud` every time. Query strings, self-declared origin and headers
  without a valid signature prove nothing.
- Keep your management token server-side only. It authorizes redemptions and profile changes.
- Do not log full tokens; log `jti`.
- Tokens are short-lived (default 1 hour). Do not accept expired tokens.
- Replay: offline verification cannot see redemptions by itself. Either call `/redeem` before granting
  the discount (authoritative single use), or keep a local set of used `jti` until `exp`.

## 7. Fallback behavior

- City unreachable or keys unavailable: serve the normal price. Never block a sale on the city.
- If you granted a discount offline while the city was down, report the redemption later with the
  same `transaction_ref` (idempotent).
- Invalid/expired token: normal price, no error to the buyer beyond an optional note.

## 8. Idempotency

- One redemption per referral (`jti`), enforced by the city.
- `transaction_ref` must be unique per participant; retries with the same value are safe.
- Store `jti` with your order so a retried report uses the same pair.

## Retrofit checklist for an existing service

1. Read `X-City-Referral` / `city_referral` on the paid endpoint.
2. Verify offline (section 3); on success apply your City Advantage to the quote/price.
3. After settlement, enqueue the redemption report (section 5) with the order id as `transaction_ref`.
4. Tests: valid token → discounted price; token for another participant → full price; expired →
   full price; tampered claims → full price; repeated report → idempotent.
5. Only then enable City Advantage on your participant record (section 1).
