# Add AT Protocol OAuth to SvelteKit + Cloudflare Workers You are adding AT Protocol OAuth authentication to an existing SvelteKit project deployed on Cloudflare Workers. This uses server-side OAuth with `@atcute/oauth-node-client`, Cloudflare KV for session storage, and SvelteKit remote functions. ## Prerequisites The project must already use: - SvelteKit with `@sveltejs/adapter-cloudflare` - A `wrangler.jsonc` (or `wrangler.toml`) config ## Step 0: Ask the user Before making any changes, ask the user these questions: 1. **UI**: Should I add a login UI? - **`foxui`** — Use `@foxui/social` login modal (polished, recommended) - **`basic`** — Simple login/logout page at `/user` route (uses Tailwind if available) - **`none`** — Backend only, no UI (you'll build your own) 2. **Collections**: What AT Protocol collections should your app write to? (e.g. `xyz.statusphere.status`, `app.bsky.feed.like`). Leave empty for read-only. 3. **Blobs**: Does the app need to upload blobs (images, video)? If yes, what types? (e.g. `image/*`, `video/*`) Use the answers to customize `settings.ts` (marked with `CUSTOMIZE` below) and choose which UI dependencies/files to create. ## Step 1: Install dependencies Always install: ```sh pnpm add valibot pnpm add -D @atcute/oauth-node-client @atcute/identity-resolver @atcute/lexicons @atcute/client @atcute/tid @cloudflare/workers-types tsx @atcute/atproto @atcute/bluesky ``` If UI choice is `foxui`: ```sh pnpm add @foxui/social @foxui/core ``` ## Step 2: Create files Create all of the following files. These go into `src/lib/atproto/` and `src/routes/(oauth)/`. ### `src/lib/atproto/settings.ts` Fill in `collections` and `blobs` from the user's answers. If no collections were specified, use an empty array. ```ts import { dev } from '$app/environment'; type Permissions = { collections: readonly string[]; rpc: Record; blobs: readonly string[]; }; export const permissions = { // CUSTOMIZE: add the user's collections collections: [], // CUSTOMIZE: add any authenticated RPC requests needed rpc: {}, // CUSTOMIZE: add blob types if the user needs uploads (e.g. ['image/*']) blobs: [] } as const satisfies Permissions; type ExtractCollectionBase = T extends `${infer Base}?${string}` ? Base : T; export type AllowedCollection = ExtractCollectionBase<(typeof permissions.collections)[number]>; // PDS to use for signup (change to preferred PDS) const devPDS = 'https://bsky.social/'; const prodPDS = 'https://bsky.social/'; export const signUpPDS = dev ? devPDS : prodPDS; export const REDIRECT_PATH = '/oauth/callback'; export const DOH_RESOLVER = 'https://mozilla.cloudflare-dns.com/dns-query'; ``` ### `src/lib/atproto/metadata.ts` ### `src/lib/atproto/auth.svelte.ts` ### `src/lib/atproto/methods.ts` ### `src/lib/atproto/index.ts` ### `src/lib/atproto/server/signed-cookie.ts` ### `src/lib/atproto/server/kv-store.ts` ### `src/lib/atproto/server/oauth.ts` ### `src/lib/atproto/server/oauth.remote.ts` ### `src/lib/atproto/server/repo.remote.ts` ### `src/lib/atproto/server/session.ts` ### `src/lib/atproto/server/profile.ts` ### `src/lib/atproto/scripts/generate-key.ts` ### `src/lib/atproto/scripts/generate-secret.ts` ### `src/lib/atproto/scripts/setup-dev.ts` ### `src/routes/(oauth)/oauth/callback/+server.ts` ### `src/routes/(oauth)/oauth/jwks.json/+server.ts` ### `src/routes/(oauth)/oauth-client-metadata.json/+server.ts` ### `.env.example` ## Step 3: Modify existing files ### `src/app.d.ts` Add these to the existing `App` namespace. Merge with any existing `Locals` or `Platform` fields — do not remove existing fields. ```ts import type { OAuthSession } from '@atcute/oauth-node-client'; import type { Client } from '@atcute/client'; import type { Did } from '@atcute/lexicons'; ``` Add to `App.Locals`: ```ts session: OAuthSession | null; client: Client | null; did: Did | null; ``` Add to `App.Platform`: ```ts env: { OAUTH_SESSIONS: KVNamespace; OAUTH_STATES: KVNamespace; CLIENT_ASSERTION_KEY: string; COOKIE_SECRET: string; OAUTH_PUBLIC_URL: string; PROFILE_CACHE?: KVNamespace; }; ``` Add at the bottom of the file (for lexicon type augmentation): ```ts import type {} from '@atcute/atproto'; import type {} from '@atcute/bluesky'; ``` ### `src/hooks.server.ts` Add session restoration. If the file already has a `handle` export, wrap both in `sequence()` from `@sveltejs/kit`. ```ts import type { Handle } from '@sveltejs/kit'; import { restoreSession } from '$lib/atproto/server/session'; const atprotoHandle: Handle = async ({ event, resolve }) => { const { session, client, did } = await restoreSession( event.cookies, event.platform?.env ); event.locals.session = session; event.locals.client = client; event.locals.did = did; return resolve(event); }; ``` If no existing hooks: `export const handle = atprotoHandle;` If existing hooks: `export const handle = sequence(existingHandle, atprotoHandle);` (import `sequence` from `@sveltejs/kit`) ### `src/routes/+layout.server.ts` Add profile loading. Merge with any existing load function. ```ts import type { LayoutServerLoad } from './$types'; import { loadProfile } from '$lib/atproto/server/profile'; export const load: LayoutServerLoad = async ({ locals, platform }) => { if (!locals.did) return { did: null, profile: null }; const profile = await loadProfile(locals.did, platform?.env?.PROFILE_CACHE); return { did: locals.did, profile }; }; ``` If a load function already exists, merge the profile data into its return value. ### `src/routes/+layout.svelte` (foxui only) Only if the user chose `foxui`. Add the login modal to the existing layout: ```svelte { await login(handle); return true; }} signup={async () => { signup(); return true; }} /> ``` To show the modal from anywhere, use `@foxui/social` state and `@foxui/core` components: ```svelte {#if user.isLoggedIn}

Signed in as {user.profile?.handle ?? user.did}

{:else} {/if} ``` `@foxui/core` also exports `Avatar`, `Input`, and other UI primitives you can use. ### `src/routes/user/+page.svelte` (basic only) Only if the user chose `basic`. Create this file: ```svelte
{#if user.isLoggedIn}

Signed in as {user.profile?.handle ?? user.did}

{:else}

Sign in

{#if error}

{error}

{/if}
{/if}
``` If the project does not use Tailwind, replace the Tailwind classes with plain inline styles. ### `svelte.config.js` Add `remoteFunctions: true` inside `kit.experimental`: ```js kit: { adapter: adapter(), experimental: { remoteFunctions: true } } ``` If `experimental` already exists, merge into it. Do not remove other experimental flags. ### `vite.config.ts` Add dev server config for loopback OAuth: ```ts server: { host: '127.0.0.1', port: 5183 } ``` Add this inside `defineConfig()`. Do not remove existing plugins or config. ### `wrangler.jsonc` Add or merge these fields: - Add `"nodejs_compat_v2"` to `compatibility_flags` (create the array if it doesn't exist) - Add `"OAUTH_PUBLIC_URL": "https://your-domain.com"` to `vars` (create `vars` if needed) - Add KV namespace placeholders to `kv_namespaces`: ```jsonc { "binding": "OAUTH_SESSIONS", "id": "TODO" }, { "binding": "OAUTH_STATES", "id": "TODO" } ``` Do not remove existing bindings or vars. ### `tsconfig.json` Add `"@cloudflare/workers-types"` to `compilerOptions.types`. Create the `types` array if it doesn't exist. ### `package.json` Add these to the `scripts` section: ```json "env:generate-key": "npx tsx src/lib/atproto/scripts/generate-key.ts", "env:generate-secret": "npx tsx src/lib/atproto/scripts/generate-secret.ts", "env:setup-dev": "npx tsx src/lib/atproto/scripts/setup-dev.ts" ``` ### `.gitignore` Ensure these lines are present: ``` .env .env.* !.env.example ``` ## Step 4: Run setup and verify 1. Run `pnpm env:setup-dev` to generate secrets in `.env` 2. Run `pnpm dev` to start the dev server 3. Verify it starts on `http://127.0.0.1:5183` 4. Tell the user: - Dev mode uses a loopback client (no keys needed) - For production: create KV namespaces with `npx wrangler kv namespace create OAUTH_SESSIONS` and `OAUTH_STATES`, update the IDs in `wrangler.jsonc`, set `OAUTH_PUBLIC_URL` to their domain, and run `npx wrangler secret put CLIENT_ASSERTION_KEY` / `COOKIE_SECRET` with values from `pnpm env:generate-key` / `pnpm env:generate-secret` ## Usage examples ### Login / Logout ```svelte {#if user.isLoggedIn}

Signed in as {user.did}

{:else} {/if} ``` ### Write operations ```ts import { putRecord, deleteRecord, uploadBlob, createTID } from '$lib/atproto'; await putRecord({ collection: 'your.collection.name', rkey: createTID(), record: { text: 'hello', createdAt: new Date().toISOString() } }); await deleteRecord({ collection: 'your.collection.name', rkey: 'some-key' }); const blob = await uploadBlob({ blob: file }); ``` ### Read operations (no auth needed) ```ts import { listRecords, getRecord, getDetailedProfile } from '$lib/atproto'; const records = await listRecords({ did: 'did:plc:...', collection: 'your.collection.name' }); const profile = await getDetailedProfile({ did: 'did:plc:...' }); ```