diff --git a/README.md b/README.md index 46e082c..e134730 100644 --- a/README.md +++ b/README.md @@ -69,8 +69,9 @@ Either way, set your production secrets (`SESSION_SECRET`, OAuth credentials) on | `PATREON_CLIENT_ID` | No | N/A | Patreon OAuth2 Client ID | | `PATREON_CLIENT_SECRET` | No | N/A | Patreon OAuth2 Client Secret | | `PATREON_WEBHOOK_SECRET` | No | N/A | Secret for verifying Patreon webhook signatures | +| `ATPROTO_ENABLED` | No | N/A | Set truthy (`true`/`1`/`yes`/`on`) to enable AT Protocol (Atmosphere) login | -> AT Protocol (Bluesky) login needs **no environment variables at all** — it is a public OAuth client with no secret, so it is configured entirely through the `createStartupAPI` factory (see [Bluesky / AT Protocol](#bluesky--at-protocol-atproto) below). +> AT Protocol (Atmosphere) login needs **no client secret** — it is a public OAuth client. Enable it either by setting `ATPROTO_ENABLED` truthy (a per-deployment switch) **or** through the `createStartupAPI` factory (see [AT Protocol / Atmosphere](#at-protocol--atmosphere-atproto) below). A factory `atproto: { enabled: false }` overrides the env flag, so a deployment can force it off. > Environment variables hold only credentials/secrets (OAuth client IDs and all secrets) plus the per‑deployment values `ORIGIN_URL`, `AUTH_ORIGIN`, `USERS_PATH`, `ADMIN_IDS`, and `ENVIRONMENT`. **All other configuration — OAuth scopes, Patreon campaign id, the access policy, entitlement freshness — is passed to the `createStartupAPI` factory** (see [Access policy & provider entitlements](#access-policy--provider-entitlements)). @@ -101,11 +102,16 @@ Either way, set your production secrets (`SESSION_SECRET`, OAuth credentials) on 3. Add your authorized redirect URI: `https:///users/auth/patreon/callback` 4. Copy the **Client ID** and **Client Secret** and add them to your Worker's environment variables -#### Bluesky / AT Protocol (atproto) +#### AT Protocol / Atmosphere (atproto) -atproto login is decentralized: there is **no central provider to register with and no client secret**. Instead the worker acts as a [public OAuth client](https://atproto.com/specs/oauth) identified by a client-metadata document it serves itself, and it discovers the right authorization server **per user** from their handle or DID — so it works with `bsky.social` and any self-hosted PDS alike, with no Bluesky host hardcoded. +atproto login is decentralized: there is **no central provider to register with and no client secret**. Instead the worker acts as a [public OAuth client](https://atproto.com/specs/oauth) identified by a client-metadata document it serves itself, and it discovers the right authorization server **per user** from their handle or DID — so it works with `bsky.social` and any self-hosted PDS alike, with no provider host hardcoded. -Because it has no secrets, atproto is configured **entirely through the `createStartupAPI` factory** (not env vars). Just like the env-credential providers are enabled by the presence of their credentials, atproto is enabled simply by **including its config key** — an empty object is enough: +Because it has no secrets, atproto is enabled in one of two ways: + +- **Env flag (no code):** set `ATPROTO_ENABLED` truthy (`true`/`1`/`yes`/`on`) — handy for toggling it per deployment (e.g. on in prod, off in preview) without touching code. This uses the default settings. +- **Factory config (for customization):** include its config key in `createStartupAPI` — an empty object is enough, and the optional fields below let you set the client name, resolvers, or scopes. + +A factory `atproto: { enabled: false }` is an explicit opt-out that **overrides** the env flag, so a deployment can force the provider off. ```ts import { createStartupAPI } from '@startup-api/cloudflare'; @@ -128,9 +134,9 @@ export default api.default; export const { UserDO, AccountDO, SystemDO, CredentialDO } = api; ``` -1. Include `atproto: {}` in the factory `providers` config (no client id/secret needed). Pass `enabled: false` to opt out explicitly. +1. Enable it — set `ATPROTO_ENABLED` truthy, or include `atproto: {}` in the factory `providers` config (no client id/secret needed either way). A factory `enabled: false` forces it off. 2. Deploy over **HTTPS** with a stable hostname. The worker automatically serves its client metadata at `https:///users/auth/atproto/client-metadata.json` (this URL is the OAuth `client_id`) and registers the redirect URI `https:///users/auth/atproto/callback`. -3. That's it. When a visitor clicks **Continue with Bluesky**, they're asked for their handle (e.g. `alice.bsky.social`) or DID; the worker then resolves it through the full atproto discovery chain and redirects them to _their own_ server to sign in: +3. That's it. When a visitor clicks **Login with your Atmosphere account**, they're asked for their handle (e.g. `alice.bsky.social`) or DID; the worker then resolves it through the full atproto discovery chain and redirects them to _their own_ server to sign in: ``` handle ─▶ DID (HTTPS .well-known/atproto-did, then DNS _atproto. via DoH) diff --git a/package-lock.json b/package-lock.json index 9edc773..e70cae3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,20 +1,22 @@ { - "name": "startup-api-cloudflare", - "version": "0.4.0", + "name": "@startup-api/cloudflare", + "version": "0.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "startup-api-cloudflare", - "version": "0.4.0", + "name": "@startup-api/cloudflare", + "version": "0.4.1", "license": "Apache-2.0", "dependencies": { + "he": "^1.2.0", "prettier": "^3.8.1", "zod": "^3.25.76" }, "devDependencies": { "@cloudflare/vitest-pool-workers": "^0.12.4", "@eslint/js": "^10.0.1", + "@types/he": "^1.2.3", "@vitest/coverage-istanbul": "^3.2.4", "@vitest/coverage-v8": "^3.2.4", "eslint": "^10.0.1", @@ -2195,6 +2197,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/he": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@types/he/-/he-1.2.3.tgz", + "integrity": "sha512-q67/qwlxblDzEDvzHhVkwc1gzVWxaNxeyHUBF4xElrvjL11O+Ytze+1fGpBHlr/H9myiBUaUXNnNPmBHxxfAcA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -3449,6 +3458,15 @@ "node": ">=8" } }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, "node_modules/html-escaper": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", diff --git a/package.json b/package.json index 4ade782..af74f77 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@startup-api/cloudflare", - "version": "0.4.0", + "version": "0.4.1", "license": "Apache-2.0", "publishConfig": { "access": "public" @@ -37,6 +37,7 @@ "devDependencies": { "@cloudflare/vitest-pool-workers": "^0.12.4", "@eslint/js": "^10.0.1", + "@types/he": "^1.2.3", "@vitest/coverage-istanbul": "^3.2.4", "@vitest/coverage-v8": "^3.2.4", "eslint": "^10.0.1", @@ -47,6 +48,7 @@ "wrangler": "^4.60.0" }, "dependencies": { + "he": "^1.2.0", "prettier": "^3.8.1", "zod": "^3.25.76" } diff --git a/public/users/power-strip.js b/public/users/power-strip.js index 4a4fb94..e7cdf50 100644 --- a/public/users/power-strip.js +++ b/public/users/power-strip.js @@ -1,3 +1,8 @@ +// Atmosphere (atproto) logo mark — the "union" glyph, drawn on a 0 0 32 32 viewBox. +// Shared by the provider badge and the login button so the two never drift apart. +const ATMOSPHERE_MARK_PATH = + 'M16 0C18.1127 1.0372e-05 19.9555 1.15414 20.9332 2.8662C21.1045 3.16613 21.4647 3.31517 21.7979 3.22403C22.2761 3.09321 22.7795 3.02333 23.2992 3.02333C26.4347 3.02335 28.9765 5.56529 28.9765 8.70083C28.9765 9.22048 28.9066 9.72378 28.7758 10.2019C28.6846 10.5351 28.8337 10.8953 29.1336 11.0666C30.8458 12.0442 32 13.8872 32 16C32 16.0822 31.9981 16.1639 31.9946 16.2452C31.9946 16.2456 31.9944 16.246 31.9942 16.2463C31.9939 16.2465 31.9937 16.2469 31.9937 16.2473C31.8599 19.6701 29.2873 22.4 26.1329 22.4L25.9815 22.3979C24.3638 22.353 22.909 21.59 21.8719 20.3888C21.5701 20.0392 20.9949 20.0275 20.6799 20.3652C19.5117 21.6171 17.8474 22.4 16 22.4C12.4654 22.4 9.6 19.5346 9.6 16C9.6 12.4654 12.4654 9.6 16 9.6C17.4368 9.6 18.7629 10.0736 19.831 10.8731C20.0053 11.0036 20.2667 10.8843 20.2667 10.6667C20.2667 10.0776 20.7442 9.6 21.3333 9.6C21.9224 9.6 22.4 10.0776 22.4 10.6667V16C22.4158 18.5458 24.26 20.2666 26.1329 20.2667C27.9447 20.2667 29.7293 18.6564 29.8583 16.2467C29.8583 16.2466 29.8583 16.2464 29.8581 16.2463C29.858 16.2461 29.8579 16.2459 29.8579 16.2458C29.8591 16.2281 29.8597 16.2104 29.8606 16.1927C29.8634 16.1293 29.8654 16.0654 29.8658 16.001C29.8658 16.0006 29.866 16.0003 29.8663 16C29.8665 15.9997 29.8667 15.9994 29.8667 15.999C29.8663 14.5464 28.9914 13.2933 27.7308 12.7465L26.4045 12.1712C26.0876 12.0337 25.937 11.6696 26.0641 11.3484L26.5963 10.0042C26.7549 9.60324 26.8431 9.16479 26.8431 8.70083C26.8431 6.77399 25.3056 5.20644 23.3906 5.15792L23.2992 5.15667C22.8351 5.15667 22.3965 5.24487 21.9956 5.40354L20.6515 5.93568C20.3304 6.06282 19.9663 5.91222 19.8288 5.59538L19.2533 4.26917C18.7234 3.04774 17.5306 2.18836 16.1356 2.13583L16 2.13333C14.547 2.13333 13.2934 3.00824 12.7465 4.26896L12.1712 5.59529C12.0337 5.91217 11.6696 6.06282 11.3484 5.93568L10.0042 5.40354C9.62831 5.25477 9.21941 5.16798 8.7875 5.15771L8.70083 5.15667C6.74349 5.15667 5.15667 6.74349 5.15667 8.70083C5.15667 9.16475 5.24485 9.60323 5.40354 10.0042L5.93568 11.3484C6.06282 11.6696 5.91217 12.0337 5.59529 12.1712L4.26896 12.7465C3.00823 13.2934 2.13333 14.5469 2.13333 16C2.13333 17.4529 3.00832 18.7063 4.26917 19.2533L5.59538 19.8288C5.91222 19.9663 6.06282 20.3304 5.93568 20.6515L5.40354 21.9956C5.24487 22.3965 5.15667 22.835 5.15667 23.2992C5.15667 25.2565 6.74349 26.8433 8.70083 26.8433C9.1644 26.8433 9.60287 26.7551 10.0042 26.5963L11.3484 26.0641C11.6696 25.937 12.0337 26.0876 12.1712 26.4045L12.7465 27.7308C13.2934 28.9917 14.547 29.8667 16 29.8667C17.4529 29.8667 18.7063 28.9918 19.2533 27.7308L19.6555 26.8037C19.8871 26.2698 20.5083 26.0256 21.0415 26.2589C21.561 26.4862 21.8066 27.0847 21.5966 27.6115L21.2104 28.5798C20.3374 30.5922 18.3333 32 16 32C13.8872 32 12.0442 30.8458 11.0666 29.1336C10.8953 28.8337 10.5351 28.6846 10.2019 28.7758C9.72378 28.9067 9.22049 28.9767 8.70083 28.9767C5.56528 28.9767 3.02333 26.4347 3.02333 23.2992C3.02333 22.7795 3.09321 22.2761 3.22403 21.7979C3.31516 21.4647 3.16613 21.1045 2.86619 20.9332C1.15412 19.9555 0 18.1127 0 16C5.927e-07 13.8873 1.1541 12.0443 2.8662 11.0666C3.16613 10.8953 3.31517 10.5351 3.22403 10.2019C3.09323 9.72379 3.02333 9.22047 3.02333 8.70083C3.02333 5.56528 5.56528 3.02333 8.70083 3.02333C9.22047 3.02334 9.72379 3.09323 10.2019 3.22404C10.5351 3.31517 10.8953 3.16614 11.0666 2.86621C12.0443 1.15411 13.8873 0 16 0ZM16 11.7333C13.6436 11.7333 11.7333 13.6436 11.7333 16C11.7333 18.3564 13.6436 20.2667 16 20.2667C18.3564 20.2667 20.2667 18.3564 20.2667 16C20.2667 13.6436 18.3564 11.7333 16 11.7333Z'; + class PowerStrip extends HTMLElement { constructor() { super(); @@ -213,7 +218,7 @@ class PowerStrip extends HTMLElement { } else if (provider === 'patreon') { return ``; } else if (provider === 'atproto') { - return ``; + return ``; } return ''; } @@ -263,10 +268,10 @@ class PowerStrip extends HTMLElement { if (providers.includes('atproto')) { authButtons += ` - - + + - Continue with Bluesky + Login with your Atmosphere account `; } @@ -597,7 +602,7 @@ class PowerStrip extends HTMLElement { .provider-badge.google { color: #3c4043; } .provider-badge.twitch { color: #9146FF; } .provider-badge.patreon { color: #FF424D; } - .provider-badge.atproto { color: #0085FF; } + .provider-badge.atproto { color: #4a8ad4; } .user-info { display: flex; @@ -671,7 +676,7 @@ class PowerStrip extends HTMLElement { box-shadow: var(--ps-dialog-shadow); background: var(--ps-dialog-bg); color: var(--ps-dialog-text); - max-width: 20rem; + max-width: 25rem; width: 90%; overflow: hidden; } @@ -736,7 +741,8 @@ class PowerStrip extends HTMLElement { justify-content: center; gap: 0.75rem; font-weight: 500; - font-size: 1rem; + font-size: 0.95rem; + white-space: nowrap; transition: all 0.2s ease; text-decoration: none; color: inherit; @@ -755,6 +761,7 @@ class PowerStrip extends HTMLElement { .auth-btn svg { width: 1.5rem; height: 1.5rem; + flex-shrink: 0; } .auth-btn.google { @@ -787,13 +794,13 @@ class PowerStrip extends HTMLElement { } .auth-btn.atproto { - background-color: #0085FF; + background-color: #4a8ad4; color: white; - border-color: #0085FF; + border-color: #4a8ad4; } .auth-btn.atproto:hover { - background-color: #006fd6; - border-color: #006fd6; + background-color: #3d77ba; + border-color: #3d77ba; } /* Account Switcher Styling */ diff --git a/src/StartupAPIEnv.ts b/src/StartupAPIEnv.ts index 7c20c8c..fcffde0 100644 --- a/src/StartupAPIEnv.ts +++ b/src/StartupAPIEnv.ts @@ -12,4 +12,7 @@ export type StartupAPIEnv = { ADMIN_IDS: string; SESSION_SECRET: string; ENVIRONMENT?: string; + // atproto has no credentials; this per-deployment flag enables it without touching the factory + // config (truthy = "true"/"1"/"yes"/"on"). A factory `atproto: { enabled: false }` still overrides it. + ATPROTO_ENABLED?: string; } & Env; diff --git a/src/auth/AtprotoProvider.ts b/src/auth/AtprotoProvider.ts index b9fd239..44229c8 100644 --- a/src/auth/AtprotoProvider.ts +++ b/src/auth/AtprotoProvider.ts @@ -1,3 +1,6 @@ +import { escape as escapeHtml } from 'he'; + +import { ATMOSPHERE_MARK_PATH } from './atmosphereMark'; import type { StartupAPIEnv } from '../StartupAPIEnv'; import type { ProviderOptions } from '../schemas/config'; @@ -27,18 +30,27 @@ interface AtprotoFlowState { returnUrl: string | null; } +/** A string env flag is truthy when it reads as "true"/"1"/"yes"/"on" (case-insensitive). */ +function isEnvFlagTruthy(value: string | undefined): boolean { + return value !== undefined && ['true', '1', 'yes', 'on'].includes(value.trim().toLowerCase()); +} + /** - * Whether the atproto provider is turned on. It has no client secret (public OAuth client), so — like - * the env-credential providers are enabled by the presence of their credentials — atproto is enabled - * simply by including its config key (`providers: { atproto: {} }`). Pass `enabled: false` to opt out - * explicitly (e.g. when the config is built dynamically). + * Whether the atproto provider is turned on. It has no client secret (public OAuth client), so it is + * enabled either by: + * - including its factory config key (`providers: { atproto: {} }`), or + * - setting the `ATPROTO_ENABLED` env var truthy (a per-deployment switch needing no code change). + * A factory `atproto: { enabled: false }` is an explicit opt-out that overrides the env flag, so a + * deployment can force the provider off regardless of the environment. */ -export function isAtprotoEnabled(options?: ProviderOptions): boolean { - return options !== undefined && options.enabled !== false; +export function isAtprotoEnabled(options?: ProviderOptions, env?: Pick): boolean { + if (options?.enabled === false) return false; // explicit factory opt-out always wins + if (options !== undefined) return true; // present in the factory config + return isEnvFlagTruthy(env?.ATPROTO_ENABLED); // otherwise honor the per-deployment env toggle } /** - * AT Protocol (Bluesky and any atproto PDS) authentication. + * AT Protocol (Atmosphere) authentication — works with any atproto PDS. * * Unlike the classic OAuth2 providers, atproto requires PKCE, DPoP-bound tokens, Pushed Authorization * Requests (PAR), and per-user dynamic endpoints discovered from the identity (handle → DID → PDS → @@ -52,8 +64,8 @@ export class AtprotoProvider extends OAuthProvider { private clientName = 'StartupAPI'; private resolverOptions: ResolverOptions = {}; - static create(_env: StartupAPIEnv, redirectBase: string, options?: ProviderOptions): AtprotoProvider | null { - if (!isAtprotoEnabled(options)) return null; + static create(env: StartupAPIEnv, redirectBase: string, options?: ProviderOptions): AtprotoProvider | null { + if (!isAtprotoEnabled(options, env)) return null; const provider = new AtprotoProvider('', '', redirectBase + '/atproto/callback', 'atproto', options?.scopes); provider.clientMetadataUrl = redirectBase + '/atproto/client-metadata.json'; provider.clientUri = new URL(redirectBase).origin; @@ -66,10 +78,10 @@ export class AtprotoProvider extends OAuthProvider { } getIcon(): string { - // AT Protocol / Bluesky butterfly mark. - return ` - - + // Atmosphere (atproto) "union" logo mark, white on the brand-blue badge. + return ` + + `; } @@ -109,6 +121,19 @@ export class AtprotoProvider extends OAuthProvider { return this.renderHandleForm(ctx, returnUrl); } + try { + return await this.startAuthorization(ctx, identifier, returnUrl); + } catch (e) { + // The user supplied a handle and is still on our side of the redirect, so the most useful + // recovery is to re-render the entry form with the failure shown and their handle pre-filled, + // rather than a dead-end error page. (Callback-phase failures fall back to renderAuthError.) + const message = e instanceof Error ? e.message : String(e); + return this.renderHandleForm(ctx, returnUrl, { error: message, handle: identifier }); + } + } + + /** Resolve the identity, run the DPoP-protected PAR, and redirect to the discovered auth endpoint. */ + private async startAuthorization(ctx: AuthContext, identifier: string, returnUrl: string | null): Promise { const identity = await resolveIdentity(identifier, this.resolverOptions); const { verifier, challenge } = await generatePkce(); const dpopKey = await generateDpopKey(); @@ -227,38 +252,67 @@ export class AtprotoProvider extends OAuthProvider { return { token, profile, returnUrl: flow.returnUrl ?? null, setCookies: [clearCookie] }; } - /** Minimal handle-entry page shown when the user starts the flow without an identifier. */ - private renderHandleForm(ctx: AuthContext, returnUrl: string | null): Response { + /** + * Handle-entry page. Shown when the user starts the flow without an identifier, and re-shown when a + * supplied handle fails to authorize — in which case `options.error` renders an inline banner and + * `options.handle` pre-fills the input so the user can correct and retry without leaving the page. + */ + private renderHandleForm( + ctx: AuthContext, + returnUrl: string | null, + options: { error?: string; handle?: string } = {}, + ): Response { const action = `${ctx.authPath}/atproto`; const returnField = returnUrl ? `` : ''; + const errorBanner = options.error ? `` : ''; + const handleValue = options.handle ? ` value="${escapeHtml(options.handle)}"` : ''; + const status = options.error ? 400 : 200; + const stylesheet = `${escapeHtml(ctx.usersPath)}style.css`; const html = ` -Sign in with Bluesky / atproto +Login with your Atmosphere account + -
-

Sign in with Bluesky / atproto

+ +

Login with your Atmosphere account

+ ${errorBanner} - + ${returnField}

Enter your atproto handle (e.g. alice.bsky.social) or DID. Your account's own server handles the login.

`; - return new Response(html, { status: 200, headers: { 'Content-Type': 'text/html; charset=utf-8' } }); + return new Response(html, { + status, + headers: { + 'Content-Type': 'text/html; charset=utf-8', + // Same hardening as the auth error page: only same-origin styles/form, never framed, never cached + // (the re-rendered form reflects the user-supplied handle). + 'Content-Security-Policy': + "default-src 'none'; style-src 'self' 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'", + 'X-Content-Type-Options': 'nosniff', + 'Referrer-Policy': 'no-referrer', + 'Cache-Control': 'no-store', + }, + }); } } @@ -271,12 +325,3 @@ function readCookie(header: string | null, name: string): string | undefined { } return undefined; } - -function escapeHtml(value: string): string { - return value - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); -} diff --git a/src/auth/atmosphereMark.ts b/src/auth/atmosphereMark.ts new file mode 100644 index 0000000..932af4e --- /dev/null +++ b/src/auth/atmosphereMark.ts @@ -0,0 +1,7 @@ +/** + * Atmosphere (atproto) "union" logo mark, drawn on a `0 0 32 32` viewBox with `fill-rule: evenodd`. + * Shared by every server-rendered atproto icon so they never drift apart. The client-side + * `public/users/power-strip.js` keeps its own copy since it cannot import from `src/`. + */ +export const ATMOSPHERE_MARK_PATH = + 'M16 0C18.1127 1.0372e-05 19.9555 1.15414 20.9332 2.8662C21.1045 3.16613 21.4647 3.31517 21.7979 3.22403C22.2761 3.09321 22.7795 3.02333 23.2992 3.02333C26.4347 3.02335 28.9765 5.56529 28.9765 8.70083C28.9765 9.22048 28.9066 9.72378 28.7758 10.2019C28.6846 10.5351 28.8337 10.8953 29.1336 11.0666C30.8458 12.0442 32 13.8872 32 16C32 16.0822 31.9981 16.1639 31.9946 16.2452C31.9946 16.2456 31.9944 16.246 31.9942 16.2463C31.9939 16.2465 31.9937 16.2469 31.9937 16.2473C31.8599 19.6701 29.2873 22.4 26.1329 22.4L25.9815 22.3979C24.3638 22.353 22.909 21.59 21.8719 20.3888C21.5701 20.0392 20.9949 20.0275 20.6799 20.3652C19.5117 21.6171 17.8474 22.4 16 22.4C12.4654 22.4 9.6 19.5346 9.6 16C9.6 12.4654 12.4654 9.6 16 9.6C17.4368 9.6 18.7629 10.0736 19.831 10.8731C20.0053 11.0036 20.2667 10.8843 20.2667 10.6667C20.2667 10.0776 20.7442 9.6 21.3333 9.6C21.9224 9.6 22.4 10.0776 22.4 10.6667V16C22.4158 18.5458 24.26 20.2666 26.1329 20.2667C27.9447 20.2667 29.7293 18.6564 29.8583 16.2467C29.8583 16.2466 29.8583 16.2464 29.8581 16.2463C29.858 16.2461 29.8579 16.2459 29.8579 16.2458C29.8591 16.2281 29.8597 16.2104 29.8606 16.1927C29.8634 16.1293 29.8654 16.0654 29.8658 16.001C29.8658 16.0006 29.866 16.0003 29.8663 16C29.8665 15.9997 29.8667 15.9994 29.8667 15.999C29.8663 14.5464 28.9914 13.2933 27.7308 12.7465L26.4045 12.1712C26.0876 12.0337 25.937 11.6696 26.0641 11.3484L26.5963 10.0042C26.7549 9.60324 26.8431 9.16479 26.8431 8.70083C26.8431 6.77399 25.3056 5.20644 23.3906 5.15792L23.2992 5.15667C22.8351 5.15667 22.3965 5.24487 21.9956 5.40354L20.6515 5.93568C20.3304 6.06282 19.9663 5.91222 19.8288 5.59538L19.2533 4.26917C18.7234 3.04774 17.5306 2.18836 16.1356 2.13583L16 2.13333C14.547 2.13333 13.2934 3.00824 12.7465 4.26896L12.1712 5.59529C12.0337 5.91217 11.6696 6.06282 11.3484 5.93568L10.0042 5.40354C9.62831 5.25477 9.21941 5.16798 8.7875 5.15771L8.70083 5.15667C6.74349 5.15667 5.15667 6.74349 5.15667 8.70083C5.15667 9.16475 5.24485 9.60323 5.40354 10.0042L5.93568 11.3484C6.06282 11.6696 5.91217 12.0337 5.59529 12.1712L4.26896 12.7465C3.00823 13.2934 2.13333 14.5469 2.13333 16C2.13333 17.4529 3.00832 18.7063 4.26917 19.2533L5.59538 19.8288C5.91222 19.9663 6.06282 20.3304 5.93568 20.6515L5.40354 21.9956C5.24487 22.3965 5.15667 22.835 5.15667 23.2992C5.15667 25.2565 6.74349 26.8433 8.70083 26.8433C9.1644 26.8433 9.60287 26.7551 10.0042 26.5963L11.3484 26.0641C11.6696 25.937 12.0337 26.0876 12.1712 26.4045L12.7465 27.7308C13.2934 28.9917 14.547 29.8667 16 29.8667C17.4529 29.8667 18.7063 28.9918 19.2533 27.7308L19.6555 26.8037C19.8871 26.2698 20.5083 26.0256 21.0415 26.2589C21.561 26.4862 21.8066 27.0847 21.5966 27.6115L21.2104 28.5798C20.3374 30.5922 18.3333 32 16 32C13.8872 32 12.0442 30.8458 11.0666 29.1336C10.8953 28.8337 10.5351 28.6846 10.2019 28.7758C9.72378 28.9067 9.22049 28.9767 8.70083 28.9767C5.56528 28.9767 3.02333 26.4347 3.02333 23.2992C3.02333 22.7795 3.09321 22.2761 3.22403 21.7979C3.31516 21.4647 3.16613 21.1045 2.86619 20.9332C1.15412 19.9555 0 18.1127 0 16C5.927e-07 13.8873 1.1541 12.0443 2.8662 11.0666C3.16613 10.8953 3.31517 10.5351 3.22403 10.2019C3.09323 9.72379 3.02333 9.22047 3.02333 8.70083C3.02333 5.56528 5.56528 3.02333 8.70083 3.02333C9.22047 3.02334 9.72379 3.09323 10.2019 3.22404C10.5351 3.31517 10.8953 3.16614 11.0666 2.86621C12.0443 1.15411 13.8873 0 16 0ZM16 11.7333C13.6436 11.7333 11.7333 13.6436 11.7333 16C11.7333 18.3564 13.6436 20.2667 16 20.2667C18.3564 20.2667 20.2667 18.3564 20.2667 16C20.2667 13.6436 18.3564 11.7333 16 11.7333Z'; diff --git a/src/auth/atproto/identity.ts b/src/auth/atproto/identity.ts index 7bd45bf..ccc9e9f 100644 --- a/src/auth/atproto/identity.ts +++ b/src/auth/atproto/identity.ts @@ -1,6 +1,6 @@ /** * AT Protocol identity resolution. Given a user-supplied handle or DID we walk the full discovery - * chain — with NO hardcoded Bluesky/PDS hosts — to find the authorization server that owns the + * chain — with NO hardcoded provider/PDS hosts — to find the authorization server that owns the * identity: * * handle ──▶ DID (HTTPS `.well-known/atproto-did`, then DNS TXT `_atproto.` via DoH) @@ -49,8 +49,12 @@ async function fetchJson(url: string, init?: RequestInit): Promise { /** Resolve a handle to a DID via the HTTPS well-known method, falling back to DNS TXT over DoH. */ async function resolveHandleToDid(handle: string, options: ResolverOptions): Promise { // 1. HTTPS well-known (works for any host that serves it; no third-party dependency). + // Use `redirect: 'manual'` rather than `'error'`: the Cloudflare Workers runtime does not implement + // the `'error'` redirect mode and throws a TypeError when it is used, which would silently disable + // this method (and break resolution for *.bsky.social handles, which have no `_atproto` DNS record). + // With `'manual'`, a redirected response is not followed and `res.ok` is false, so we fall through. try { - const res = await fetch(`https://${handle}/.well-known/atproto-did`, { redirect: 'error' }); + const res = await fetch(`https://${handle}/.well-known/atproto-did`, { redirect: 'manual' }); if (res.ok) { const did = (await res.text()).trim(); if (DID_PREFIX.test(did)) return did; diff --git a/src/auth/errorPage.ts b/src/auth/errorPage.ts new file mode 100644 index 0000000..07dc674 --- /dev/null +++ b/src/auth/errorPage.ts @@ -0,0 +1,73 @@ +/** + * Styled error page for the auth flow. + * + * Auth error messages frequently embed UNTRUSTED text from outside our trust boundary: the + * user-supplied handle, and raw response bodies from a user's PDS or authorization server + * (e.g. `Token request failed: 400 `). Protection is layered: + * + * 1. Encode — the untrusted message is HTML-escaped with `he` (a battle-tested, dependency-free + * output encoder) before it ever reaches the markup. We do not hand-roll escaping. + * 2. Contain — the page is served under a restrictive Content-Security-Policy (no script may run) + * plus `nosniff`, so even an encoding bypass cannot execute code or be re-sniffed. + * + * Theming matches the rest of the app: we link `/users/style.css` and use its CSS variables, so the + * page follows the user's OS / chosen theme via `prefers-color-scheme` exactly like profile.html. + * The CSP allows `style-src 'self'` for that same-origin stylesheet; scripts remain fully blocked. + */ +import { escape as escapeHtml } from 'he'; + +/** Hard cap on rendered detail length — external bodies can be arbitrarily large. */ +const MAX_DETAIL_LENGTH = 300; + +/** + * Content-Security-Policy for the error page. `default-src 'none'` blocks every resource type + * (scripts, images, frames, connections). We additively allow `style-src 'self' 'unsafe-inline'` + * for the linked `style.css` (same-origin) and the page's own inline ` + + +
+

Sign-in failed

+

We couldn't complete your sign-in. Please return to the sign-in page and try again.

+ ${detail ? `
${detail}
` : ''} +
+ +`; + return new Response(html, { + status, + headers: { + 'Content-Type': 'text/html; charset=utf-8', + 'Content-Security-Policy': CONTENT_SECURITY_POLICY, + 'X-Content-Type-Options': 'nosniff', + 'Referrer-Policy': 'no-referrer', + // Reflects a user handle / remote server message — never let a browser or intermediary cache it. + 'Cache-Control': 'no-store', + }, + }); +} diff --git a/src/auth/index.ts b/src/auth/index.ts index 4b364b3..78acace 100644 --- a/src/auth/index.ts +++ b/src/auth/index.ts @@ -2,6 +2,7 @@ import type { StartupAPIEnv } from '../StartupAPIEnv'; import { CookieManager } from '../CookieManager'; import { refreshEntitlements } from '../entitlements/service'; +import { renderAuthError } from './errorPage'; import { computeRedirectBase, createProviders } from './providers'; import type { ProviderConfigs } from './providers'; import type { AuthContext, ExchangeResult, OAuthProvider } from './OAuthProvider'; @@ -40,7 +41,7 @@ export async function handleAuth( try { return await provider.authorize(ctx); } catch (e) { - return new Response(`Auth failed: ${e instanceof Error ? e.message : String(e)}`, { status: 500 }); + return renderAuthError(e instanceof Error ? e.message : String(e), 500, usersPath); } } } @@ -54,7 +55,7 @@ export async function handleAuth( return await finishLogin(provider, result, ctx); } catch (e) { const status = (e as { status?: number })?.status ?? 500; - return new Response(`Auth failed: ${e instanceof Error ? e.message : String(e)}`, { status }); + return renderAuthError(e instanceof Error ? e.message : String(e), status, usersPath); } } } diff --git a/src/handlers/ssr.ts b/src/handlers/ssr.ts index 21c327a..f4f80e5 100644 --- a/src/handlers/ssr.ts +++ b/src/handlers/ssr.ts @@ -2,6 +2,7 @@ import { StartupAPIEnv } from '../StartupAPIEnv'; import { CookieManager } from '../CookieManager'; import { getUserFromSession, checkAndClearStaleSession, isAdmin, getActiveProviders } from './utils'; import type { ProviderConfigs } from '../auth/providers'; +import { ATMOSPHERE_MARK_PATH } from '../auth/atmosphereMark'; import { Plan } from '../billing/Plan'; export async function handleSSR( @@ -215,7 +216,7 @@ function getProviderIcon(provider: string): string { } else if (provider === 'patreon') { return ''; } else if (provider === 'atproto') { - return ''; + return ``; } return ''; } diff --git a/src/handlers/utils.ts b/src/handlers/utils.ts index 05aa4c2..bf9da73 100644 --- a/src/handlers/utils.ts +++ b/src/handlers/utils.ts @@ -14,8 +14,8 @@ export function getActiveProviders(env: StartupAPIEnv, providerConfigs: Provider if (env.PATREON_CLIENT_ID && env.PATREON_CLIENT_SECRET) { providers.push('patreon'); } - // atproto has no env credentials; it is enabled purely via factory config. - if (isAtprotoEnabled(providerConfigs.atproto)) { + // atproto has no env credentials; it is enabled via factory config or the ATPROTO_ENABLED env flag. + if (isAtprotoEnabled(providerConfigs.atproto, env)) { providers.push('atproto'); } return providers; diff --git a/test/atproto.spec.ts b/test/atproto.spec.ts index 8e5dd55..fffa45f 100644 --- a/test/atproto.spec.ts +++ b/test/atproto.spec.ts @@ -98,10 +98,20 @@ describe('atproto provider', () => { expect(res.status).toBe(200); expect(res.headers.get('Content-Type')).toContain('text/html'); + // Auth page hardening: not framable, not cached (it can reflect the user's handle). + expect(res.headers.get('Content-Security-Policy')).toContain("frame-ancestors 'none'"); + expect(res.headers.get('Cache-Control')).toBe('no-store'); const html = await res.text(); expect(html).toContain('name="handle"'); }); + it('serves the error page non-framable and non-cacheable', async () => { + const { renderAuthError } = await import('../src/auth/errorPage'); + const res = renderAuthError('Could not resolve handle "x"', 500, '/users/'); + expect(res.headers.get('Content-Security-Policy')).toContain("frame-ancestors 'none'"); + expect(res.headers.get('Cache-Control')).toBe('no-store'); + }); + it('resolves identity, performs PAR with DPoP + PKCE (with nonce retry), and redirects', async () => { let parInit: RequestInit | undefined; let parDpopProofs = 0; @@ -221,6 +231,38 @@ describe('atproto provider', () => { expect(await cbRes.text()).toContain('State mismatch'); }); + it('re-renders the handle form (pre-filled) with an inline error when resolution fails', async () => { + // Every identity lookup fails → resolveHandleToDid throws "Could not resolve handle ...". + globalThis.fetch = (async () => new Response('not found', { status: 404 })) as typeof fetch; + + const api = createStartupAPI(atprotoConfig); + const ctx = createExecutionContext(); + const res = await api.fetch(new Request('http://example.com/users/auth/atproto?handle=ghost.invalid'), env, ctx); + await waitOnExecutionContext(ctx); + + expect(res.status).toBe(400); + expect(res.headers.get('Content-Type')).toContain('text/html'); + const html = await res.text(); + expect(html).toContain('name="handle"'); // the entry form is shown again + expect(html).toContain('value="ghost.invalid"'); // with the handle pre-filled to retry + expect(html).toContain('role="alert"'); // and an error banner + expect(html).toContain('Could not resolve handle "ghost.invalid" to a DID'); + }); + + it('HTML-escapes an untrusted handle when re-rendering the error form', async () => { + globalThis.fetch = (async () => new Response('not found', { status: 404 })) as typeof fetch; + + const api = createStartupAPI(atprotoConfig); + const ctx = createExecutionContext(); + const malicious = encodeURIComponent('">'); + const res = await api.fetch(new Request(`http://example.com/users/auth/atproto?handle=${malicious}`), env, ctx); + await waitOnExecutionContext(ctx); + + const html = await res.text(); + expect(html).not.toContain(''); // no markup breaks out + expect(html).toContain('<script>'); // it is encoded instead + }); + it('enables atproto by presence of its config key, and opts out via enabled: false', async () => { const { getActiveProviders } = await import('../src/handlers/utils'); // Present (even empty) → enabled. @@ -230,4 +272,18 @@ describe('atproto provider', () => { // Explicit opt-out → disabled. expect(getActiveProviders(env, { atproto: { enabled: false } })).not.toContain('atproto'); }); + + it('enables atproto via the ATPROTO_ENABLED env flag, with factory enabled:false still winning', async () => { + const { getActiveProviders } = await import('../src/handlers/utils'); + // Env flag on, no factory config → enabled. + for (const truthy of ['true', '1', 'YES', 'on']) { + expect(getActiveProviders({ ...env, ATPROTO_ENABLED: truthy })).toContain('atproto'); + } + // Non-truthy / unset env values → disabled. + for (const falsy of ['false', '0', '', 'nope']) { + expect(getActiveProviders({ ...env, ATPROTO_ENABLED: falsy })).not.toContain('atproto'); + } + // Explicit factory opt-out overrides a truthy env flag. + expect(getActiveProviders({ ...env, ATPROTO_ENABLED: 'true' }, { atproto: { enabled: false } })).not.toContain('atproto'); + }); });