Stateless auth proxy that converts AT Protocol native apps from public to confidential OAuth clients. Deploy once, get 180-day refresh token
README.md

atproto-auth-proxy #

A generic, stateless auth proxy that converts any AT Protocol native app from a public OAuth client to a confidential client. Deploy it once and your users get confidential-client session lifetimes (on Bluesky's auth server today: refresh tokens that survive 3 months of inactivity inside a 2-year session) instead of the 2-week hard cap applied to public clients — no more forced re-logins every two weeks.

Quick Start #

# 1. Generate a signing key
openssl ecparam -genkey -name prime256v1 -noout | openssl pkcs8 -topk8 -nocrypt -out auth-key.pem

# 2. Run the proxy
AUTH_PRIVATE_KEY=$(cat auth-key.pem) \
AUTH_CLIENT_ID="https://yourapp.com/oauth/client-metadata.json" \
./atproto-auth-proxy

# 3. Update your client-metadata.json (see "Client Metadata Changes" below)

Docker #

# Build
docker build -t atproto-auth-proxy .

# Run
docker run -e AUTH_PRIVATE_KEY="$(cat auth-key.pem)" \
           -e AUTH_CLIENT_ID="https://yourapp.com/oauth/client-metadata.json" \
           -p 8080:8080 \
           atproto-auth-proxy

Deploy to Railway #

Railway builds the Dockerfile and provisions HTTPS certificates for custom domains. From a clone of this repository:

# 1. Create a project and a service, and link this directory to them
railway init --name atproto-auth-proxy
railway add --service atproto-auth-proxy
railway service link atproto-auth-proxy

# 2. Add the variables
railway variable set AUTH_CLIENT_ID=https://yourapp.com/oauth/client-metadata.json --skip-deploys
railway variable set AUTH_PRIVATE_KEY --stdin --skip-deploys < auth-key.pem
railway variable set AUTH_TRUST_PROXY_HEADERS=true --skip-deploys
railway variable set PORT=8080 --skip-deploys

# 3. Have Railway check /health before a new deployment takes traffic
railway environment edit --service-config atproto-auth-proxy deploy.healthcheckPath /health

# 4. Deploy, then add your domain and create the CNAME and TXT records it prints
railway up
railway domain auth.yourapp.com --port 8080

railway up uploads the directory without the paths .gitignore lists, so a .pem file in it stays on your machine. Deploying from a GitHub fork connected to the service works too.

  • Health check: with /health as the service's health check path (step 3, or the service's settings in the dashboard), Railway keeps the previous deployment serving until a new one answers it. The proxy refuses to start with a bad configuration, so a deployment with a missing or invalid variable never takes traffic. Setting a variable redeploys the service unless you pass --skip-deploys.
  • PORT: Railway always sets PORT and sends health checks to it, and the proxy listens on it. Setting it to 8080 keeps the listening port, the health check and the domain's target port the same.
  • AUTH_TRUST_PROXY_HEADERS=true: requests reach the service through Railway's proxy. Without it, every request appears to come from the proxy, and the per-IP limit acts as a global one.
  • Upgrading a service from an older version: older versions ignored PORT and always listened on 8080. This one listens on PORT, so set PORT=8080 on the service before deploying it. Otherwise the domain keeps pointing at 8080 while the proxy listens on whatever port Railway assigned.

Environment Variables #

Variable Required Default Description
AUTH_PRIVATE_KEY Yes — PEM-encoded EC P-256 private key (active signing key)
AUTH_CLIENT_ID Yes — Your app's OAuth client_id (client-metadata.json URL)
AUTH_KEY_ID No atproto-auth-1 JWKS key identifier (kid) for the active key
AUTH_OLD_PRIVATE_KEY No — PEM-encoded EC P-256 private key (previous key, for rotation)
AUTH_OLD_KEY_ID No — JWKS key identifier (kid) for the old key (required with AUTH_OLD_PRIVATE_KEY)
AUTH_CLIENTS No — Comma-separated app slugs, to serve several apps from one deployment instead of the variables above (see "Multiple Apps")
AUTH_BIND No :8080 Listen address; takes precedence over PORT
PORT No — Port to listen on when AUTH_BIND is unset; set by platforms such as Railway
AUTH_ALLOWED_ORIGINS No * CORS allowed origins
AUTH_RATE_LIMIT_PER_IP No 10 Max requests per IP per minute on /oauth/token and /oauth/par (0 to disable)
AUTH_RATE_LIMIT_GLOBAL No 100 Max total requests per minute on /oauth/token and /oauth/par (0 to disable)
AUTH_TRUST_PROXY_HEADERS No false Trust X-Forwarded-For / X-Real-IP for per-IP rate limiting when deployed behind a trusted reverse proxy

The proxy checks the whole configuration at startup, including parsing every key, and refuses to start if anything is wrong. atproto-auth-proxy -check-config runs the same checks, logs the client ID, routes and public key of each app it would serve, and exits without serving.

Multiple Apps #

One deployment can sign for several apps. Set AUTH_CLIENTS to a list of slugs, and configure each app with variables named after its slug:

AUTH_CLIENTS=photos,notes

AUTH_PHOTOS_CLIENT_ID=https://photos.example.com/oauth/client-metadata.json
AUTH_PHOTOS_PRIVATE_KEY=<PEM>

AUTH_NOTES_CLIENT_ID=https://notes.example.com/oauth/client-metadata.json
AUTH_NOTES_PRIVATE_KEY=<PEM>
AUTH_NOTES_HOSTS=auth.notes.example.com

Each app is then served under its slug: /photos/.well-known/jwks.json, /photos/oauth/token and /photos/oauth/par, and the same three routes under /notes/. /health is shared. Point each app at its own path:

  • client-metadata.json: "jwks_uri": "https://auth.example.com/photos/.well-known/jwks.json". The JWKS doesn't have to be on the client metadata's domain.
  • The app's auth proxy base URL: https://auth.example.com/photos, with no trailing slash.

<SLUG> in a variable name is the slug in uppercase, with hyphens as underscores: the slug my-app reads AUTH_MY_APP_CLIENT_ID.

Variable Required Description
AUTH_<SLUG>_CLIENT_ID Yes As AUTH_CLIENT_ID, for this app
AUTH_<SLUG>_PRIVATE_KEY Yes As AUTH_PRIVATE_KEY, for this app
AUTH_<SLUG>_KEY_ID No As AUTH_KEY_ID (default atproto-auth-1)
AUTH_<SLUG>_OLD_PRIVATE_KEY No As AUTH_OLD_PRIVATE_KEY
AUTH_<SLUG>_OLD_KEY_ID No As AUTH_OLD_KEY_ID
AUTH_<SLUG>_HOSTS No Comma-separated hostnames whose root routes (/.well-known/jwks.json, /oauth/token, /oauth/par) also serve this app, such as the dedicated host it used before joining a shared deployment. Requests for root routes on any other host get 404.

Each app has its own keys, JWKS, refresh cache and rate limits: AUTH_RATE_LIMIT_PER_IP and AUTH_RATE_LIMIT_GLOBAL apply to each app separately, so one app's burst can't use up another's budget. Each app's log lines start with its slug.

Give each app its own key. Its JWKS then lists only that key, and a leaked or rotated key affects only that app's sessions. A kid only has to be unique within one app, so every app can keep atproto-auth-1.

Slugs are lowercase letters, digits and hyphens, and can't be old or end in -old, because their variables would collide with the key rotation ones. A slug is permanent once a jwks_uri uses it: changing it means moving that app's JWKS. The proxy refuses to start if an app is misconfigured, if two apps share a client ID or a host, or if a single-app variable such as AUTH_PRIVATE_KEY is still set.

With several apps on one deployment, an outage affects all of them at once, and a configuration change for one app redeploys the others. A health check on /health stops a deployment that fails to start from taking traffic (see "Deploy to Railway"), and -check-config checks a configuration on your machine before you set it.

Moving an app into a shared deployment #

The auth server binds each session to the key that started it (its kid, algorithm and thumbprint), not to the URL its JWKS was published at. An app can therefore move from its own deployment to a shared one without signing anyone out, as long as it keeps its key and kid:

  1. Add the app to the shared deployment with its current key and kid. Check that /<slug>/.well-known/jwks.json serves exactly the same JWKS as the old deployment. Don't go on until it does: a refresh signed with a different key is rejected, and the session is revoked.
  2. Change jwks_uri in the app's client metadata to the new path. Both deployments hold the same key, so the auth server accepts assertions from either one, and its cached copy of the old metadata points at the same key.
  3. In the app's next release, change its proxy base URL to the new path.
  4. Older builds keep calling the old deployment, so keep it running. To retire it before those builds are gone, add the old hostname to AUTH_<SLUG>_HOSTS and to the shared deployment, then point the hostname's DNS there. Older builds then reach the shared deployment instead.

How It Works #

┌─────────────┐         ┌──────────────────────┐         ┌─────────────────────┐
│ Native App  │────────>│  atproto-auth-proxy   │────────>│  AT Proto Auth      │
│ (iOS/Android│<────────│  auth.yourapp.com     │<────────│  Server             │
│  /Desktop)  │         │                       │         │                     │
│             │         │ Stores:               │         │ Validates:          │
│ Stores:     │         │ - client private key  │         │ - client_assertion  │
│ - tokens    │         │   (env var)           │         │ - DPoP proof        │
│ - DPoP key  │         │                       │         │ - refresh token     │
└─────────────┘         └──────────────────────┘         └─────────────────────┘

The proxy is stateless — no database, no session storage, no user data. It holds the client signing key material, verifies issuer metadata before each proxied flow, and uses the selected key to authenticate token requests on behalf of your app. The one piece of in-memory state is a 10-minute cache of successful refresh responses: AT Protocol refresh tokens are single-use, so a client whose response was lost in transit can retry with the same token and get the rotated result instead of losing its session. That cache is per-process, so it only helps while a single instance is running.

A refresh is finished even when the client hangs up before the answer: a suspended app or a phone changing networks drops the request, but by then the authorization server may have spent the token. The proxy fetches the answer regardless and keeps it for the retry. So a client that gets no answer to a refresh should send the same refresh again within ten minutes, not treat the session as lost. At no time are two refreshes of one token on their way to the authorization server: a request that arrives while another is in flight waits for it.

  1. Native app initiates OAuth and gets an auth code
  2. App sends the auth code to the proxy (POST /oauth/token)
  3. Proxy signs a client_assertion JWT and forwards the request to the AT Protocol auth server
  4. Auth server validates the assertion, issues tokens, and responds
  5. Proxy returns the tokens to the app unchanged
  6. On refresh: same flow via POST /oauth/token with grant_type=refresh_token

The proxy also handles Pushed Authorization Requests (POST /oauth/par) the same way.

DPoP proofs are generated on the device and forwarded through the proxy transparently.

The proxy returns the selected signing key via the Auth-Proxy-Key-ID response header. Clients must persist that value per account and send it back as key_id on every later /oauth/token request for that session. The auth server binds a confidential session to the client key that started it, so a refresh signed with any other key is rejected with invalid_grant and the session is revoked. See "Key Rotation" for what that means operationally.

API Endpoints #

Method Path Description
GET /.well-known/jwks.json Public key for auth server verification
POST /oauth/token Proxy token exchange and refresh requests
POST /oauth/par Proxy Pushed Authorization Requests
GET /health Health check

With AUTH_CLIENTS set, the first three are served under each app's slug, such as /photos/oauth/token (see "Multiple Apps").

POST /oauth/token #

Request body:

{
  "token_endpoint": "https://bsky.social/oauth/token",
  "issuer": "https://bsky.social",
  "key_id": "atproto-auth-2",
  "grant_type": "refresh_token",
  "refresh_token": "<refresh_token>"
}

How key_id is used depends on the grant:

  • authorization_code: key_id is optional. Without it the proxy signs with the active key and, if the auth server answers invalid_client, retries once with the old key. This covers the window right after a rotation when the auth server's cached JWKS does not include the new key yet.
  • refresh_token: clients must send the key_id they received when the session started. The proxy signs with exactly that key and never probes others, because the auth server revokes the session when a refresh is signed with the wrong key. A refresh without key_id is signed with the active key only, which is correct unless the key has been rotated since the session started.

POST /oauth/par #

Request body:

{
  "par_endpoint": "https://bsky.social/oauth/par",
  "issuer": "https://bsky.social",
  "key_id": "atproto-auth-2",
  "login_hint": "user.bsky.social",
  "scope": "atproto transition:generic",
  "code_challenge": "<pkce_challenge>",
  "code_challenge_method": "S256",
  "state": "<state>",
  "redirect_uri": "https://yourapp.com/oauth/callback"
}

The proxy validates that issuer, token_endpoint, and par_endpoint match the authorization server’s well-known metadata before forwarding the request.

Client Metadata Changes #

Update your app's client-metadata.json to use the proxy:

Before (public client):

{
  "client_id": "https://yourapp.com/oauth/client-metadata.json",
  "token_endpoint_auth_method": "none"
}

After (confidential client via proxy):

{
  "client_id": "https://yourapp.com/oauth/client-metadata.json",
  "token_endpoint_auth_method": "private_key_jwt",
  "token_endpoint_auth_signing_alg": "ES256",
  "jwks_uri": "https://auth.yourapp.com/.well-known/jwks.json"
}
Public Client With Proxy
Refresh token lifetime 2 weeks 3 months of inactivity
Session lifetime 2 weeks, regardless of activity 2 years
User re-login frequency Every 2 weeks After 3 months away, or every 2 years

These are the values enforced by Bluesky's auth server (@atproto/oauth-provider 0.22, checked September 2026). The AT Protocol OAuth spec recommends a 2-week limit for public clients and allows confidential clients refresh tokens of up to 180 days with an unlimited session, so other PDS implementations may differ.

HTTPS Redirect URIs (Required for iOS) #

Bluesky's auth server enforces that application_type: "native" clients must use token_endpoint_auth_method: "none". This means you cannot use the proxy with application_type: "native" — the PAR request will fail with:

{"error":"invalid_client_metadata","error_description":"Native clients must authenticate using \"none\" method"}

To use private_key_jwt, your client metadata must declare application_type: "web", which requires HTTPS redirect URIs instead of custom URL schemes.

The AT Protocol OAuth spec explicitly supports this: native clients are allowed to use an HTTPS URL as long as the URL origin matches the client_id. For example, if your client_id is https://yourapp.com/oauth/client-metadata.json, your redirect URI must be https://yourapp.com/....

Your client metadata should look like:

{
  "client_id": "https://yourapp.com/oauth/client-metadata.json",
  "redirect_uris": ["https://yourapp.com/oauth/callback"],
  "application_type": "web",
  "token_endpoint_auth_method": "private_key_jwt",
  "token_endpoint_auth_signing_alg": "ES256",
  "dpop_bound_access_tokens": true,
  "jwks_uri": "https://auth.yourapp.com/.well-known/jwks.json"
}

iOS Setup #

On iOS, HTTPS OAuth callbacks are handled via ASWebAuthenticationSession's HTTPS callback API (iOS 17.4+). You also need an Apple App Site Association (AASA) file for Universal Links as a safety net.

1. Apple App Site Association File #

Serve this at https://yourapp.com/.well-known/apple-app-site-association:

{
  "applinks": {
    "details": [
      {
        "appIDs": ["<TEAM_ID>.<BUNDLE_ID>"],
        "components": [
          {
            "/": "/oauth/callback",
            "comment": "AT Protocol OAuth callback"
          }
        ]
      }
    ]
  },
  "webcredentials": {
    "apps": ["<TEAM_ID>.<BUNDLE_ID>"]
  }
}

Replace <TEAM_ID> with your Apple Developer Team ID and <BUNDLE_ID> with your app's bundle identifier.

Requirements:

  • Must be served with Content-Type: application/json
  • Must not redirect — Apple's CDN fetches it directly
  • Apple caches the file via its CDN; updates can take hours to propagate
  • Verify propagation: https://app-site-association.cdn-apple.com/a/v1/yourapp.com

2. Entitlements #

Add an Associated Domains entitlement to your app (via Xcode: target > Signing & Capabilities > Associated Domains, or via an .entitlements file):

<key>com.apple.developer.associated-domains</key>
<array>
    <string>applinks:yourapp.com</string>
    <string>webcredentials:yourapp.com</string>
</array>

3. ASWebAuthenticationSession #

Use the HTTPS callback initializer instead of the custom-scheme one:

// Before (custom scheme — won't work with the proxy)
let session = ASWebAuthenticationSession(
    url: authURL,
    callbackURLScheme: "yourapp"
) { callbackURL, error in ... }

// After (HTTPS callback — required for the proxy)
let session = ASWebAuthenticationSession(
    url: authURL,
    callback: .https(host: "yourapp.com", path: "/oauth/callback")
) { callbackURL, error in ... }

This requires iOS 17.4+.

4. Remove Custom URL Scheme #

If you were previously using a custom URL scheme (e.g., yourapp://oauth/callback) for OAuth, remove the CFBundleURLTypes entry from your Info.plist. The custom scheme is no longer needed for OAuth callbacks.

5. Web Fallback Page #

Add a simple page at /oauth/callback on your website. ASWebAuthenticationSession intercepts the redirect before it reaches the server, but having a real page there improves the experience for edge cases (e.g., users who land there in a browser):

<h1>Redirecting to YourApp...</h1>
<p>If you're not redirected automatically, open the app on your device.</p>

Deployment Sequence #

Order matters — deploy bottom-up so each layer is ready before the one above depends on it:

  1. Deploy the auth proxy and verify it's live (curl https://auth.yourapp.com/health)
  2. Deploy the AASA file to your website
  3. Wait for Apple CDN propagation — verify via https://app-site-association.cdn-apple.com/a/v1/yourapp.com
  4. Deploy updated client metadata (application_type: "web", HTTPS redirect URI)
  5. Build and test the iOS app on a real device (Universal Links don't work in Simulator)
  6. Submit the app update

Warning: Do not deploy the client metadata update before the AASA file is cached by Apple's CDN. If it isn't, Universal Links won't work and the OAuth callback won't route to your app.

Rollback #

If something goes wrong, revert your client-metadata.json:

  • application_type: "web" back to "native"
  • redirect_uris: HTTPS URL back to custom scheme
  • token_endpoint_auth_method: "private_key_jwt" back to "none"
  • Remove jwks_uri and token_endpoint_auth_signing_alg

The iOS app also needs a new build to switch back to callbackURLScheme. To minimize rollback friction, keep the AASA file deployed permanently — it has no downside even when unused.

Key Rotation #

The proxy can serve two keys at once: the active key, used for new sessions, and one old key. During rotation both public keys are published in the JWKS so sessions started under the old key keep refreshing.

  1. Generate a new key pair with a new kid (e.g., atproto-auth-2)
  2. Set AUTH_OLD_PRIVATE_KEY and AUTH_OLD_KEY_ID to your current key values
  3. Set AUTH_PRIVATE_KEY and AUTH_KEY_ID to the new key
  4. Deploy — the JWKS now serves both keys; new PAR and code exchanges use the active key, refreshes use whichever key the client sends as key_id
  5. Keep the old key configured for as long as sessions started under it should stay alive

Removing a key revokes its sessions #

The AT Protocol OAuth spec requires the auth server to bind each confidential session to the client key (kid, alg, and key thumbprint) that started it, and to revoke the session once that key is no longer in the client's JWKS. There is no grace period. Removing AUTH_OLD_PRIVATE_KEY therefore logs out every user whose session began under that key. With Bluesky's 2-year session lifetime, the old key has to stay published for up to 2 years to avoid forcing anyone to sign in again.

Plan rotations accordingly:

  • Routine rotation: expect to keep the old key configured for the full session lifetime. The proxy holds only one old key, so rotating again before those sessions have expired logs out whichever key falls off.
  • Compromised key: remove it immediately. Revoking every session that used it is the intended response, and it is the reason confidential clients are trusted with long sessions in the first place.

Clients must persist the Auth-Proxy-Key-ID header from PAR and token responses and send it back as key_id on later code exchanges and refreshes. Only authorization_code exchanges without a key_id fall back from the active key to the old key on invalid_client; refreshes never probe (see POST /oauth/token).

Security Considerations #

  • Issuer metadata validation: The proxy resolves the authorization server’s well-known metadata and verifies the requested token/PAR endpoint matches the declared issuer metadata before sending any signed request
  • Hardened outbound HTTP: Metadata and upstream requests use a public-IP-only transport, reject localhost/private/reserved ranges, and validate redirects to prevent SSRF and DNS rebinding
  • Bounded upstream reads: Metadata and proxied token/PAR responses are size-limited in memory to avoid oversized-response abuse
  • Request timeout: Metadata and upstream requests have explicit timeouts to prevent slow-loris attacks
  • No token logging: Token values, auth codes, and refresh tokens are never logged
  • HTTPS required: The proxy must be served over HTTPS in production (handled automatically by Railway/Fly.io)
  • DPoP passthrough: The proxy never sees DPoP private keys — proofs are between the device and auth server
  • Rate limiting: Per-IP and global rate limits on /oauth/token and /oauth/par (configurable, defaults to 10/min per IP, 100/min global, counted separately for each app when serving several). Proxy headers are only trusted when AUTH_TRUST_PROXY_HEADERS=true
  • Signs only for its own clients: Anyone can call a public proxy, as with any native app's confidential client, but it only signs as the client IDs it's configured with
  • Stateless: No database, no user data stored — the only secrets are the client signing keys in environment variables

License #

MIT