# auth.md

You are an agent. This document tells you how to authenticate with Cachely's
protected APIs. Cachely is a remote build cache for Nx, Lerna, Turborepo, Gradle, and
Bazel. Prefer the machine-readable discovery documents below; this file is the
human- and agent-readable companion to them.

## Audiences

Cachely exposes two protected surfaces:

- **MCP server** - `https://app.cachely.dev/mcp`. A Streamable HTTP Model
  Context Protocol endpoint (workspaces, insights, plan usage). Authenticated
  with OAuth 2.1. An agent can register its OAuth client itself; obtaining an
  access token requires the user to sign in and authorize access.
- **Remote cache API** - `https://remote.cachely.dev` (Nx `/v1/cache`,
  Turborepo `/v8/artifacts`, Gradle `/v1/gradle`, Bazel `/v1/bazel`).
  Authenticated with a workspace bearer token that a human provisions in the
  dashboard. Agents cannot self-register for this surface.

## Discovery

- Protected Resource Metadata (RFC 9728):
  https://cachely.dev/.well-known/oauth-protected-resource
- Authorization Server Metadata (RFC 8414), including the `agent_auth` block:
  https://cachely.dev/.well-known/oauth-authorization-server
  (the authoritative same-origin copy is
  https://app.cachely.dev/.well-known/oauth-authorization-server)
- MCP Server Card (SEP-1649):
  https://cachely.dev/.well-known/mcp/server-card.json

The apex PRM names `https://cachely.dev` as its resource and points
`authorization_servers[0]` at `https://app.cachely.dev`, which exactly matches
the AS metadata issuer.

## MCP server - OAuth 2.1 agent registration

The supported registration method is OAuth dynamic client registration
(RFC 7591), followed by user authorization with an authorization code and
PKCE (S256). The resulting credential is an OAuth bearer access token.

Fetch the Protected Resource Metadata, follow `authorization_servers`, and
read the Authorization Server Metadata's `issuer`, `registration_endpoint`,
`authorization_endpoint`, and `token_endpoint`. The examples below use the
production endpoints. Prefer discovered endpoints if they differ.

Replace angle-bracket placeholders with values from your own flow; response
values and lifetimes are illustrative. URL-encode form and query values.

### 1. Register an OAuth client

Start a callback listener you control. This example uses
`http://127.0.0.1:33418/callback`; use your own redirect URI consistently in
registration, authorization, and token exchange. Register without a dashboard
session cookie or an existing bearer token:

```http
POST /api/auth/oauth2/register HTTP/1.1
Host: app.cachely.dev
Content-Type: application/json

{
  "client_name": "Cachely agent",
  "application_type": "native",
  "redirect_uris": ["http://127.0.0.1:33418/callback"],
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "token_endpoint_auth_method": "none",
  "scope": "openid offline_access mcp"
}
```

The successful response contains your client registration:

```json
{
  "client_id": "<client_id>",
  "client_id_issued_at": 1791638400,
  "application_type": "native",
  "redirect_uris": ["http://127.0.0.1:33418/callback"],
  "token_endpoint_auth_method": "none",
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "client_name": "Cachely agent",
  "scope": "openid offline_access mcp"
}
```

Save `client_id` for subsequent requests. This public client receives no client
secret. Registration creates an OAuth client, not a Cachely user account or an
access token. Register only when the user intends to connect an agent, never
as part of a passive discovery scan.

### 2. Obtain user authorization with PKCE

Generate a fresh random `code_verifier` and `state` for each authorization
attempt. Compute `code_challenge` as the base64url-encoded SHA-256 digest of
the verifier, without padding. For example, using Node.js:

```sh
node --input-type=module <<'JS'
import { createHash, randomBytes } from 'node:crypto';
import { mkdtemp, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const code_verifier = randomBytes(32).toString('base64url');
const code_challenge = createHash('sha256').update(code_verifier).digest('base64url');
const state = randomBytes(32).toString('base64url');
const pkce_file = join(await mkdtemp(join(tmpdir(), 'cachely-oauth-')), 'pkce.json');
await writeFile(pkce_file, JSON.stringify({ code_verifier, state }), { mode: 0o600 });
process.stdout.write(JSON.stringify({ code_challenge, state, pkce_file }, null, 2) + '\n');
JS
```

The verifier stays in the private file named by `pkce_file`. Read it directly
into the token request body without printing it or placing it in shell arguments.
Keep it out of logs and agent tool transcripts, and delete the temporary directory
after the exchange or a failed attempt. Keep the saved state for callback
validation. Open this authorization request in the user's browser, substituting
your client ID, state, and challenge:

```http
GET /api/auth/oauth2/authorize?response_type=code&client_id=<client_id>&redirect_uri=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2F127.0.0.1%3A33418%2Fcallback&scope=openid%20offline_access%20mcp&state=<state>&code_challenge=<code_challenge>&code_challenge_method=S256&resource=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttps%2Fapp.cachely.dev%2Fmcp HTTP/1.1
Host: app.cachely.dev
```

The user signs in with Google or GitHub and approves the requested permissions
on the consent screen. The `mcp` scope allows reading workspace data, insights
and usage, and creating workspaces and cache access tokens. Successful
authorization redirects the browser to your callback:

```http
HTTP/1.1 302 Found
Location: http://127.0.0.1:33418/callback?code=<code>&state=<state>&iss=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttps%2Fapp.cachely.dev
```

Check that the returned `state` exactly matches the value saved for this
attempt before exchanging the code, and check `iss` against the discovered
issuer. Stop if either differs or the callback contains an `error`. The
authorization code is single-use; the verifier stays with the
agent until the token exchange. Request `offline_access` to receive a refresh
token.

### 3. Exchange the authorization code

Send the code, the original verifier, and the same redirect URI to the token
endpoint. This public client uses `client_id` without a client secret:

```http
POST /api/auth/oauth2/token HTTP/1.1
Host: app.cachely.dev
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&client_id=<client_id>&code=<code>&redirect_uri=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2F127.0.0.1%3A33418%2Fcallback&code_verifier=<code_verifier>&resource=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttps%2Fapp.cachely.dev%2Fmcp
```

The successful response contains the credentials:

```json
{
  "access_token": "<access_token>",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "<refresh_token>",
  "scope": "openid offline_access mcp",
  "id_token": "<id_token>"
}
```

### 4. Use and refresh the credential

Send `Authorization: Bearer <access_token>` with MCP requests to
`https://app.cachely.dev/mcp`. The `id_token` describes the authenticated user;
use the `access_token` to call MCP. Cache API workspace tokens are separate
credentials and cannot replace the OAuth access token here.

Send the same `resource=https://app.cachely.dev/mcp` in authorization, code
exchange and refresh requests. It binds the access JWT to MCP; an opaque
token issued without this resource is rejected by the MCP endpoint.

Before the access token expires, exchange the refresh token:

```http
POST /api/auth/oauth2/token HTTP/1.1
Host: app.cachely.dev
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token&client_id=<client_id>&refresh_token=<refresh_token>&resource=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttps%2Fapp.cachely.dev%2Fmcp
```

The response supplies a new `access_token`, `token_type`, `expires_in`,
`refresh_token`, and `scope`. Save the returned refresh token for the next
exchange atomically, then discard the previous refresh token. Refresh tokens
are single-use: serialize refresh requests and do not retry an old token.
Replaying one revokes its token family. If the token endpoint returns
`invalid_grant`, restart user
authorization with fresh PKCE values and state.

## Remote cache API - bearer token (human-provisioned)

Agents cannot register here. A human owner creates a workspace token in the
dashboard (`https://app.cachely.dev`) and gives it to the build tool or CI.

- Send it as `Authorization: Bearer <token>`. Gradle and Bazel HTTP caches may
  send it as the HTTP Basic password instead (any username; the token is the
  password).
- The token is scoped to one workspace and is subject to that workspace's plan
  quota. Read-only tokens are recommended for developer machines and untrusted
  CI (on Bazel, pair them with `build --remote_upload_local_results=false`).

## Credential use

- Treat every token as a secret. Send it only over HTTPS in the `Authorization`
  header. Never log it, embed it in URLs, or commit it to source control.
- Prefer the shortest-lived credential that works: the OAuth access token for
  MCP (refreshable), a scoped workspace token for the cache API.

## Identity and registration methods

- Supported: OAuth 2.1 authorization code with PKCE, backed by Google or GitHub sign-in,
  via RFC 7591 dynamic client registration (MCP); human-provisioned bearer
  tokens (remote cache API).
- The agent acts as a user-authorized delegate: it obtains credentials only
  after the user approves the OAuth authorization request. Cachely advertises no
  `identity_types_supported` because the auth.md profile's canonical identity
  types (`anonymous`, `identity_assertion`, `service_auth`) do not apply.
- Not supported: ID-JAG identity assertions
  (`urn:ietf:params:oauth:token-type:id-jag`), verified-email assertions, and
  anonymous claim ceremonies. Cachely runs no `/agent/identity`, claim, or
  revocation endpoint, so those URLs are intentionally absent from metadata.
