# OAuth

_See the [README](../README.md) for what pi-keyrouter is and how to install it._

Handled entirely by pi — keyrouter implements no auth flows, calls no refresh endpoint, and
never writes `auth.json` itself.

There are two distinct OAuth features, and they are independent:

## 1. Leaving your existing login alone (API-key pools)

- **Providers you signed into** (`/login anthropic`, subscription logins): keyrouter detects the
  stored OAuth credential via pi's exported `readStoredCredential()` and **leaves the provider
  alone**. Injecting an api-key would shadow your login, so the pool is skipped with a notice.
  Opt in per pool with `"takeoverOAuth": true`.
- **OAuth-only providers** (no api-key auth method at all): skipped permanently — an injected key
  would make requests fail.
- **When the pool is exhausted or the session ends**, the overlay is removed and pi falls back to
  exactly what you had before: auth.json, env, or OAuth.

pi's own `pi auth check <provider>` / `pi auth print-bearer-token` keep working on those providers.

> **Caveat.** The guard reads the stored credential under the **pool's provider id**. If a provider
> borrows auth from somewhere else — for example a `cx-providers` entry whose credential actually
> lives under a built-in id — the login is invisible to this check and a pool for that id will take
> over. Only pool provider ids whose own credential is what you want rotated.

## 2. Rotating between several OAuth logins (`accounts` pools)

If you have **several logins for the same provider** — two subscription accounts, a work and a
personal one — an `accounts` pool rotates between them on the same signals that rotate API keys.
This is the case pi itself cannot express: `auth.json` is a `Record<providerId, Credential>`
with exactly one credential per provider id, so accounts 2..N have nowhere to live. keyrouter
holds them and swaps them in.

```jsonc
{
  "providers": [
    {
      "name": "cline",
      "accounts": [
        { "name": "work", "credential": "$CLINE_WORK" },
        { "name": "home", "credential": "@~/.pi/accounts/cline-home.json" },
        {
          "name": "inline",
          "credential": {
            "type": "oauth",
            "access": "...",
            "refresh": "...",
            "expires": 1791056623000
          }
        }
      ],
      "rotateOnQuota": true
    }
  ]
}
```

- `credential` accepts an inline object, `$ENV` holding a **JSON string**, or `@file` (a JSON
  file with one object; `~` is expanded). Use `$ENV` or `@file` with mode `0600` so tokens stay
  out of the config file.
- A credential is used only if it has `type: "oauth"`, a non-empty `access`, a `refresh`, and a
  numeric `expires`. Anything else is dropped with a warning **naming the account only**, never the
  value.
- `keys` and `accounts` are mutually exclusive for one provider.
- `rotateOnQuota` (default `true`) decides whether an account-level limit rotates the pool. Each
  account is a separate subscription, so this defaults the opposite way from `keys` pools — see
  [Rotation rules](configuration.md#rotation-rules).
- `identityPath` (optional) says where this provider's account identity lives inside a credential.
  See [Attributing a refreshed credential](#attributing-a-refreshed-credential).
- `sweepRefresh` (default `false`) lets this pool refresh its **idle** accounts at session start — the
  accounts no request has touched for a while, whose tokens would otherwise sit expired until the day
  one of them is needed. It is **opt-in per pool**: one provider that needs it says so, and every other
  pool keeps its tokens untouched. The exchange is not race-free yet (see `TODO.md`), so it is off by
  default; enable it only for a pool that has actually gone stale.
- `leases` (default `true`) coordinates this pool with other pi processes through the lease files
  described under [Leases](configuration.md#leases--one-credential-per-concurrent-worker). Set it to `false` to make
  this provider ignore leases entirely: it neither claims an entry nor skips an entry another process
  has claimed, and an OAuth sweep does not take the provider-wide sweep claim. Applies to both pool
  kinds.

**How it works.** keyrouter installs an account with pi's own credential store
(`runtime.credentials.modify`), so pi's file lock, cache and revision counter all stay coherent.
pi then owns auth resolution, headers and refresh exactly as it does for a single login. It never
uses the api-key overlay for an `accounts` pool: `setRuntimeApiKey` stores only a string, and pi's
resolver returns early on any override — on an OAuth-only provider that yields **no auth at all**,
and on a dual-auth provider it **freezes the token** so pi stops refreshing it.

**Refresh stays pi's job, always.** keyrouter never refreshes a token. pi refreshes lazily and
persists the result to `auth.json` — so keyrouter reads the live credential back into the pool both
when it leaves an account and after installing one, and **writes the refreshed values back to
`keyrouter.json`**. That last part is essential rather than tidy: pi holds one credential per
provider, so installing account #2 overwrites whatever pi refreshed, and keyrouter's own copy would
otherwise still carry the access token from an account's **last login**. Since access tokens are
short-lived (60 minutes for Cline), a stale copy means every account in the pool presents an
expired token and the whole pool reads as dead. A dead refresh token is treated as a dead account,
and the pool rotates away from it.

**Idle accounts are refreshed at session start.** An account that sits in the pool unused goes
through none of that — pi never sees it, so its stored copy keeps an expired access token and an
unexercised refresh token, and whether that token still redeems weeks later is up to the provider.
At `session_start`, keyrouter therefore asks **pi's own refresh implementation** — the provider's
`oauth.refresh`, the same function pi's request path calls — to renew every *idle* account whose
token has less than ~5 minutes of validity left, with pi's own 15-second exchange timeout, and
writes the result back through the usual write-back rules. keyrouter still implements no part of
OAuth. The *active* account is skipped: pi refreshes it at request time and the capture machinery
syncs that; sweeping its pool copy as well would race pi's refresh of the same token — and for
providers that rotate the refresh token on every exchange, each side would consume the other's
token. The sweep is non-blocking and never touches `auth.json`, only the pool and
`keyrouter.json`. An account whose refresh fails is marked like a request-time refresh failure and
named in one notice: reviving a dead login still needs a `/login` only you can perform.

The write-back is scoped and conservative: only accounts written as an **inline object** are
updated (`$ENV` and `@file` references are left alone), only the credential fields change, and the
write is skipped entirely when nothing moved, so a normal run never rewrites your config. It is
atomic (temp file + rename), so an interrupted write cannot truncate a file holding live
credentials. If the write fails you get one warning and the session continues — persistence is an
optimization, not a requirement.

## Attributing a refreshed credential

When pi hands back a refreshed credential, keyrouter must decide **which pool account it belongs
to** before writing it. It cannot simply use the `active` field: pi holds exactly one credential per
provider, so if you `/login` as account A while the saved `active` still names slot B, `auth.json`
holds A's token while the file says B. Writing it to the slot the pointer names would alias B onto
A, orphan B's own refresh token, and make B fail with `invalid_grant` on its next use even though
nothing had been wrong with it.

So the credential is matched, strongest signal first:

| # | Signal | Notes |
|---|---|---|
| 1 | your `identityPath` | authoritative; beats every guess below |
| 2 | an identity claim decoded from a token field | `email`, `preferred_username`, `sub`, ... |
| 3 | a known credential field | `accountId`, `projectId`, `userID`, `machineID`, `clientId` |
| 4 | exact `refresh`-token equality | works on opaque credentials; tried late because it rotates |
| 5 | the `active` pointer | only when keyrouter itself installed the credential |

Levels 2 and 3 are best-effort by nature — providers do not agree on where an identity lives, and
some credentials carry none at all. That is what `identityPath` is for.

```json
{
  "name": "cline",
  "identityPath": "access:email",
  "accounts": [ /* ... */ ]
}
```

The format is **`level1:level2`**:

- **`level1`** — a key of the credential object: `access`, `refresh`, `accountId`, or a dotted path
  for a nested field.
- **`level2`** — a path into that value **after decoding it**. Optional: with no colon, `level1`'s own
  value is compared as-is.

Decoding is automatic and best-effort, because a credential may hold JSON, a JWT, a base64-wrapped
blob, or nothing encoded at all:

| `identityPath` | Meaning |
|---|---|
| `"refresh"` | compare the refresh token and nothing else |
| `"access:email"` | decode `access`, read its `email` |
| `"access:user.email"` | the same, for a nested claim |
| `"accountId"` | compare the credential's own `accountId` |
| `"accountId:sub"` | decode `accountId`, read its `sub` |

The decode order is JWT → JSON → base64-wrapped-JSON, stopping at the first form that yields
structure. A plain string that merely happens to be base64-decodable is **not** decoded: most opaque
tokens are base64-ish, and decoding one would produce mojibake that would then be reported as an
identity. Only a decode that produces real JSON is accepted.

A path that resolves nowhere is almost always a typo. It is reported once, and detection falls back
to the automatic levels — a typo must never stop refreshes from being persisted.

Two safeguards apply when the signals are insufficient:

- **Ambiguity is refused.** If two slots share the identity you named (two logins to one address, or a
  coarse field like a shared `projectId`) and nothing sharper separates them, nothing is written.
- **A mismatched slot is refused.** Before writing, the identity already stored in the target slot is
  compared with the incoming one. If they name different accounts the write is skipped with a warning,
  because the stored credential holds a refresh token that cannot be recovered. Only stable
  identifiers are compared — the refresh token rotates, so including it would flag every legitimate
  write as a conflict.

Both refusals are logged to the trace sink and surfaced as a warning naming the provider, so a
credential that stopped persisting is visible rather than silent.

**Persistence.** The pool owns the provider credential while the extension is loaded. On a clean
shutdown (or `/keyrouter reset`) the credential that was stored when the session started is put
back; if there was none, the active account is left installed, because that is still a valid login
and logging you out would be worse. If pi is killed mid-session, `auth.json` simply holds a pool
account — still a valid login, and the next session resumes the account the last one ended on (see
[Resuming across sessions](#resuming-across-sessions)). keyrouter keeps no side copy of your
credentials anywhere: the `active` field holds an account **name** only.

**When a pool is exhausted**, the active account is left in place and pi surfaces the original
error, rather than leaving you logged out.

> **Security.** `accounts` pools need real credentials somewhere. Prefer `$ENV` / `@file` over
> inlining them, and keep the file mode at `0600`. keyrouter logs account **names** only and
> redacts every token.

## Resuming across sessions

A rotation that lands on key #2 used to be forgotten when the session ended: the next one started
back on key #1 and had to rediscover the 429. Each pool now records which entry was active in an
`active` field, so the next session resumes there — falling forward to the next available entry if
that one is currently on cooldown.

```jsonc
{
  "providers": [{
    "name": "tokenharbor",
    "active": "jsjery123",              // ← keyrouter writes this; you don't
    "keys": [
      { "name": "jery99961",  "value": "$TOKENHARBOR_API_KEY" },
      { "name": "jsjery123",  "value": "$TOKENHARBOR_API_KEY2" }
    ]
  }]
}
```

It stores the entry **name**, not an index, because this file moves under you: reordering or
inserting entries shifts every index after it, while a name still identifies the credential you
meant. An entry that has since been renamed or deleted is simply unknown, and the pool starts at its
first entry.

Only the name is written — never a key value or a token. The write is atomic, is skipped when the
position is unchanged, and `/keyrouter reset` deletes the field so the next session genuinely starts
fresh.
