chadtmiller.com/monolith
An atproto PDS
0
0
The OAuth authorization pages as a Svelte app, checked in a browser beside the reference's
.claude/skills/ui/SKILL.mdnew+107−0
| @@ -0,0 +1,107 @@ | ||
--- | ||
name: ui | ||
description: Build or change the OAuth authorization pages (web/) so they look right, not only work. Use for any change to a view, component or style under web/. Look at every state of what you touch with `just look` before pushing, hold it to the house rules here, and have it critiqued by eyes that did not write it. | ||
--- | ||
| ||
# Building the authorization pages | ||
| ||
`--pages` checks that each control has its name and makes the right | ||
call. It does not check that the page is good to look at. A view nobody | ||
looked at shows it: an alert jammed against the button above it, a long | ||
handle running out of its card on a phone, two buttons that look | ||
primary. So look at every state before pushing. | ||
| ||
`web/AGENTS.md` has the mechanics: layers, tokens, the | ||
Content-Security-Policy's limits, and inline text. `spec/OAUTH-PAGES.md` | ||
says what each view holds. This file says how the views should read, and | ||
how to check that they do. | ||
| ||
## Looking | ||
| ||
`just look` builds `web/` and `pds`, then starts the server on a data | ||
directory of its own, with a PLC directory of its own and two accounts | ||
(`alice.test` and one with a long handle). It makes a PAR for the state | ||
you name, drives a browser to it, and writes pictures to `target/look` | ||
to open with Read. Each state is drawn on desktop in light and on a phone | ||
in dark. `cd harness && node look.mjs ...` skips the build when it is | ||
fresh. | ||
| ||
```sh | ||
just look sign-in # the first view of a new device | ||
just look sign-in --hint # with login_hint: the identifier filled | ||
just look wrong-password # the alert under the form | ||
just look rate-limited # 429: "Too many tries…" (the answer given by look itself) | ||
just look email-code # the code view (the answer given by look itself) | ||
just look choose # two remembered accounts, one with a long handle | ||
just look consent # loopback client, atproto transition:generic, the long handle | ||
just look consent --scope 'atproto repo:com.example.foo?action=create rpc:com.example.bar?aud=* blob:image/* account:email?action=manage identity:handle' | ||
just look consent --details # Technical details open | ||
just look ended # consent answered 400: "This sign-in has ended…" | ||
just look busy # the sign-in held on its way: the button busy, the rest disabled | ||
just look error # the error page | ||
just look consent --phone --light # one size and scheme alone | ||
``` | ||
| ||
It prints each console message, and says when a view is wider than the | ||
screen, naming the element that runs past the edge. Fix that before | ||
anything else, because on a phone the page then scrolls sideways. | ||
| ||
## The states to look at | ||
| ||
For every view you touch, look at each of these that applies: | ||
| ||
- **Empty and filled**: a field as it first shows, and with text typed. | ||
- **Long text**: a long handle, a long client name, a client with no | ||
name (its host), a scope with many tokens, a collection NSID that | ||
cannot wrap. | ||
- **One and many**: one remembered account, then several. | ||
- **Every alert**: each of the view's answers in `spec/OAUTH-PAGES.md`. | ||
- **Busy**: each button that calls the API, pressed, with its call held. | ||
- **Phone** and **dark**: the defaults draw desktop light and phone dark. | ||
Look at phone light and desktop dark too when you change a colour. | ||
- **Open**: `Technical details`. | ||
| ||
## House rules | ||
| ||
**Case.** Sentence case everywhere: headings, buttons, labels, links and | ||
alerts ("Sign in", "Another account", "Technical details"). Only the | ||
first word and proper nouns take a capital: Bluesky, PDS, DID. A label | ||
ends with no full stop. Something said in a sentence, such as an alert, | ||
ends with one. Names stay as they are written: handles, NSIDs, scopes, | ||
hosts. Use no `text-transform` to change case; write the label as it | ||
should read. | ||
| ||
**Space.** Every block stacked on another has a gap from the space | ||
scale between them. Text never touches a row of controls. Things that | ||
belong together sit closer than things that do not: a label to its | ||
field, less than the field to the next field. | ||
| ||
**Weight.** One primary button on a view at most: the one that goes on | ||
(`Sign in`, `Allow`). `Deny`, `Cancel`, `Back` and `Another account` are | ||
quiet. Quiet what is said about a thing (`--mute`, `--text-sm`) next to | ||
the thing itself: a handle under a name, a host under a client. | ||
| ||
**Consistency.** Do the same thing the same way on every view: the same | ||
component where one exists (look in `web/src/lib` before making one), the | ||
same words for the same act, and the same order of controls (the primary | ||
button first, at the start of the row). People and clients are drawn by | ||
their molecules, never by hand. | ||
| ||
**Trust.** The page asks for a password. Keep it plain and calm: the | ||
server's host shown, no decoration that a phishing page could copy more | ||
easily than the server's own name, and nothing that moves. | ||
| ||
## Critique | ||
| ||
You read your own pictures kindly. Before pushing a change that moves a | ||
view, hand the pictures to an agent that did not write it. Give a fresh | ||
one the paths under `target/look`, this file's house rules, and only | ||
this question: "What looks wrong, out of place, or unlike the other | ||
views here? Be specific: element, what is wrong, which rule." Do not give | ||
it the code, nor what you meant: it judges what is drawn. Fix what it | ||
finds, or say in the pull why not. | ||
| ||
## Then | ||
| ||
Push. Give the pull the `just look` pictures of every view you changed, | ||
each as an `--image` to `knotless pull create` or `knotless pull edit`. | ||
.knotless/workflows/gates.yml+43−13
| @@ -1,28 +1,33 @@ | ||
# The gates, as `just gates` runs them: the code gates (cargo fmt, clippy, | ||
# cargo deny, no unsafe code), the server's own tests, and the harness runs | ||
# of the server against the reference PDS, several at once, a short crashing | ||
# run among them. On every pull into main, so the merge queue waits on them, | ||
# and on every push to main. The long crash runs and the performance step | ||
# are nightly.yml's. | ||
# cargo deny, no unsafe code, and the pages' layers, contrast and | ||
# svelte-check), the server's own tests, and the harness runs of the server | ||
# against the reference PDS, several at once, a short crashing run and the | ||
# pages in Chromium among them. On every pull into main, so the merge queue | ||
# waits on them, and on every push to main. The long crash runs and the | ||
# performance step are nightly.yml's. | ||
# | ||
# Only a change to what they check runs them: the server's source and its | ||
# build, the data and lexicons it reads from spec/, the harness the gates | ||
# run (not bench.mjs or compat.mjs, which no gate runs), and this workflow. | ||
# Anything else, as the README, the spec's prose, bench/ and compat/, is | ||
# filed as skipped, which the merge queue takes as passing. | ||
# build, the pages it embeds (web/), the data and lexicons it reads from | ||
# spec/, the harness the gates run (not bench.mjs, compat.mjs or look.mjs, | ||
# which no gate runs), and this workflow. Anything else, as the README, the | ||
# spec's prose, bench/ and compat/, is filed as skipped, which the merge | ||
# queue takes as passing. | ||
# | ||
# Node, the harness's packages, cargo-deny and the build are kept between runs. | ||
# Node, the harness's and the pages' packages, Chromium and the libraries | ||
# it needs, cargo-deny and the build are kept between runs. | ||
image: rust:1.98 | ||
runners: [runner.knotless.dev] | ||
# The two lists are the same; keep them so. | ||
on: | ||
push: | ||
refs: [refs/heads/main] | ||
paths: [crates/**, Cargo.*, deny.toml, .cargo/**, .node-version, .knotless/uses.lock, .knotless/workflows/gates.yml, spec/atproto/**, spec/data/**, spec/interop/**, spec/lexicons/**, spec/mcp/**, spec/rfc/**, spec/spaces/**, harness/checks/**, harness/lib/**, harness/spaces/**, harness/compare.mjs, harness/conformance.*, harness/code.mjs, harness/gates.mjs, harness/perf.mjs, harness/package*.json] | ||
paths: [crates/**, Cargo.*, deny.toml, .cargo/**, .node-version, .knotless/uses.lock, .knotless/workflows/gates.yml, web/**, spec/atproto/**, spec/data/**, spec/interop/**, spec/lexicons/**, spec/mcp/**, spec/rfc/**, spec/spaces/**, harness/checks/**, harness/lib/**, harness/spaces/**, harness/compare.mjs, harness/conformance.*, harness/code.mjs, harness/layers.mjs, harness/contrast.mjs, harness/gates.mjs, harness/perf.mjs, harness/package*.json] | ||
pull: | ||
base: [refs/heads/main] | ||
paths: [crates/**, Cargo.*, deny.toml, .cargo/**, .node-version, .knotless/uses.lock, .knotless/workflows/gates.yml, spec/atproto/**, spec/data/**, spec/interop/**, spec/lexicons/**, spec/mcp/**, spec/rfc/**, spec/spaces/**, harness/checks/**, harness/lib/**, harness/spaces/**, harness/compare.mjs, harness/conformance.*, harness/code.mjs, harness/gates.mjs, harness/perf.mjs, harness/package*.json] | ||
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/node, /opt/cargo-deny, harness/node_modules, harness/spaces/node_modules] | ||
paths: [crates/**, Cargo.*, deny.toml, .cargo/**, .node-version, .knotless/uses.lock, .knotless/workflows/gates.yml, web/**, spec/atproto/**, spec/data/**, spec/interop/**, spec/lexicons/**, spec/mcp/**, spec/rfc/**, spec/spaces/**, harness/checks/**, harness/lib/**, harness/spaces/**, harness/compare.mjs, harness/conformance.*, harness/code.mjs, harness/layers.mjs, harness/contrast.mjs, harness/gates.mjs, harness/perf.mjs, harness/package*.json] | ||
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/node, /opt/cargo-deny, /opt/browsers, /opt/chromium-debs, harness/node_modules, harness/spaces/node_modules, web/node_modules] | ||
env: | ||
PLAYWRIGHT_BROWSERS_PATH: /opt/browsers | ||
steps: | ||
- uses: chadtmiller.com/steps/node@1 | ||
with: {version: 24.22.1} | ||
| @@ -30,6 +35,31 @@ steps: | ||
with: {dir: harness} | ||
- uses: chadtmiller.com/steps/npm-ci@1 | ||
with: {dir: harness/spaces} | ||
- uses: chadtmiller.com/steps/npm-ci@1 | ||
with: {dir: web} | ||
# The pages, which pds-server embeds: built before anything compiles it. | ||
- name: web | ||
run: cd web && PATH=/opt/node/bin:$PATH npm run build | ||
- name: chromium | ||
run: | | ||
export PATH=/opt/node/bin:$PATH | ||
cd harness | ||
# The browser, into /opt/browsers once for each Playwright version. | ||
npx playwright install chromium | ||
# The libraries it needs, which `install-deps` would fetch with apt on | ||
# every run: their .debs are kept, fetched again only when this | ||
# Playwright or this Debian asks for others, and installed offline. | ||
pkgs=$(npx playwright install-deps --dry-run chromium | sed -n "s/.*--no-install-recommends \([^\"']*\).*/\1/p") | ||
[ -n "$pkgs" ] || { echo "no packages in: $(npx playwright install-deps --dry-run chromium)"; exit 1; } | ||
debs=/opt/chromium-debs | ||
want="$(. /etc/os-release && echo "$VERSION_ID") $pkgs" | ||
if [ "$(cat $debs/.want 2>/dev/null)" != "$want" ]; then | ||
rm -rf "${debs:?}"/* && mkdir -p $debs/partial | ||
apt-get update -qq | ||
apt-get install -y -qq --no-install-recommends --download-only -o Dir::Cache::archives=$debs $pkgs | ||
echo "$want" > $debs/.want | ||
fi | ||
dpkg -i $debs/*.deb > /dev/null | ||
# A step at a time, each under the runner's limit on one. The tests' | ||
# scratch directories are in memory where /dev/shm has room for them (they | ||
# take 8 MB at most): the server's durability tests start it on its log | ||
.knotless/workflows/nightly.yml+8−2
| @@ -5,19 +5,25 @@ | ||
# wait on (gates.yml runs a short crashing run instead); a failure here is | ||
# fixed by a pull, as any other. | ||
# | ||
# Node, the harness's packages and the build are kept between runs. | ||
# Node, the harness's and the pages' packages and the build are kept | ||
# between runs. | ||
image: rust:1.98 | ||
runners: [runner.knotless.dev] | ||
on: | ||
schedule: | ||
- cron: '0 10 * * *' | ||
asked: {refs: [refs/heads/main]} | ||
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/node, harness/node_modules] | ||
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/node, harness/node_modules, web/node_modules] | ||
steps: | ||
- uses: chadtmiller.com/steps/node@1 | ||
with: {version: 24.22.1} | ||
- uses: chadtmiller.com/steps/npm-ci@1 | ||
with: {dir: harness} | ||
- uses: chadtmiller.com/steps/npm-ci@1 | ||
with: {dir: web} | ||
# The pages, which pds-server embeds. | ||
- name: web | ||
run: cd web && PATH=/opt/node/bin:$PATH npm run build | ||
- name: build | ||
run: cargo build --release -p pds | ||
- name: crash | ||
bench/impls.json+1−1
| @@ -3,7 +3,7 @@ | ||
"spec-pds": { | ||
"source": "this repository, at the commit checked out", | ||
"toolchain": "stable", | ||
"build": ["rustup", "run", "stable", "cargo", "build", "--release", "-p", "pds"] | ||
"build": ["sh", "-c", "(cd web && npm ci --no-audit --no-fund && npm run build) && rustup run stable cargo build --release -p pds"] | ||
}, | ||
"reference": { | ||
"source": "@atproto/pds 0.5.55 through @atproto/dev-env 0.6.26, from npm, pinned by harness/package-lock.json", | ||
bench/README.md+3−2
| @@ -10,7 +10,7 @@ nothing on the machine is set up by hand. | ||
| ||
| implementation | from | pinned by | | ||
|---|---|---| | ||
| spec-pds | this repository, `cargo build --release -p pds` | the commit checked out | | ||
| spec-pds | this repository, its pages built in `web/` and then `cargo build --release -p pds` | the commit checked out | | ||
| reference | `@atproto/pds` 0.5.55 through `@atproto/dev-env` 0.6.26, from npm | `harness/package-lock.json` | | ||
| vlpds | its release image `ghcr.io/jazware/vlpds`, v1.3.0 (commit `91fa452`) | image digest in `impls.json` | | ||
| RustFS (vlpds's S3 store) | `rustfs/rustfs` 1.0.4 | image digest in `impls.json` | | ||
| @@ -77,7 +77,8 @@ first, the baseline the others are read against. | ||
| ||
1. checks Node 24+, rustup, npm, git and a running Docker daemon, and stops | ||
with a message naming whatever is missing; | ||
2. builds **spec-pds** (`rustup run stable cargo build --release -p pds`); | ||
2. builds **spec-pds** (`npm ci` and `npm run build` in `web/`, then | ||
`rustup run stable cargo build --release -p pds`); | ||
3. installs the **reference** (`npm ci` in `harness/`); | ||
4. unless Docker has the image `spec-pds-bench-zds:cef2c63` already, fetches | ||
**zds** at its pinned commit into `bench/vendor/zds` (gitignored) and | ||
crates/pds-server/src/oauth/assets.rsnew+34−0
| @@ -0,0 +1,34 @@ | ||
//! The authorization pages' build, embedded when the crate is compiled | ||
//! (`build.rs`), and `/oauth/assets/<name>`, which serves it | ||
//! (`spec/OAUTH-PAGES.md`, "Assets"). | ||
| ||
use axum::{ | ||
extract::Path, | ||
http::{Method, StatusCode, header}, | ||
response::{IntoResponse, Response}, | ||
}; | ||
| ||
include!(concat!(env!("OUT_DIR"), "/web.rs")); | ||
| ||
/// `GET` or `HEAD /oauth/assets/<name>`: a file of the build, which never | ||
/// changes under its name. | ||
pub(super) async fn asset(method: Method, Path(name): Path<String>) -> Response { | ||
let found = ASSETS | ||
.binary_search_by_key(&name.as_str(), |(n, _, _)| n) | ||
.ok(); | ||
match found { | ||
Some(i) if method == Method::GET || method == Method::HEAD => { | ||
let (_, content_type, bytes) = ASSETS[i]; | ||
( | ||
[ | ||
(header::CONTENT_TYPE, content_type), | ||
(header::CACHE_CONTROL, "public, max-age=31536000, immutable"), | ||
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"), | ||
], | ||
bytes, | ||
) | ||
.into_response() | ||
} | ||
_ => StatusCode::NOT_FOUND.into_response(), | ||
} | ||
} | ||
crates/pds-server/src/oauth/page.rs+62−57
| @@ -1,11 +1,13 @@ | ||
//! The authorization page, the API its script calls, and the redirect back | ||
//! The authorization page and the error page, each the app the build | ||
//! embeds (`super::assets`) with its data, as `spec/OAUTH-PAGES.md` says; | ||
//! the API the app calls, and the redirect back | ||
//! to the client, as `spec/OAUTH.md` says. A browser is a *device*, named by | ||
//! a sealed `device-id` cookie; the accounts signed in on each device are | ||
//! kept, and a request is bound to the device that loads it. API calls carry | ||
//! the page's `csrf-token` cookie back as their `x-csrf-token` header. | ||
| ||
use super::{ | ||
EPHEMERAL_LIFE, REQUEST_LIFE, REQUEST_URI, Request, State, Tx, client, clients, finish, | ||
EPHEMERAL_LIFE, REQUEST_LIFE, REQUEST_URI, Request, State, Tx, assets, client, clients, finish, | ||
json_response, new_id, scope, set, | ||
}; | ||
use crate::email::Purpose::AuthFactor; | ||
| @@ -17,7 +19,9 @@ use axum::{ | ||
http::{HeaderMap, Method, StatusCode, Uri, header}, | ||
response::{IntoResponse, Response}, | ||
}; | ||
use base64::Engine; | ||
use serde_json::{Map, Value as Json, json}; | ||
use sha2::{Digest, Sha256}; | ||
| ||
const DEVICE_COOKIE: &str = "device-id"; | ||
const CSRF_COOKIE: &str = "csrf-token"; | ||
| @@ -143,17 +147,29 @@ fn html_escape(s: &str) -> String { | ||
.replace('\'', "'") | ||
} | ||
| ||
/// A page: its data, as `window["<name>"]=JSON.parse("…");` statements, and its script. | ||
fn page(status: u16, title: &str, data: &[(&str, &Json)], script: &str) -> Response { | ||
/// The Content-Security-Policy of a page whose one inline script is `script` | ||
/// (`spec/OAUTH-PAGES.md`): scripts and stylesheets from the server alone, | ||
/// and that script, by its hash. | ||
fn csp(script: &str) -> String { | ||
let hash = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(script)); | ||
format!( | ||
"default-src 'none'; script-src 'self' 'sha256-{hash}'; style-src 'self'; img-src 'self' https: data:; \ | ||
connect-src 'self'; font-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" | ||
) | ||
} | ||
| ||
/// A page: the app the build embeds (`super::assets`), and its data, as | ||
/// `window["<name>"]=JSON.parse("…");` statements, its one inline script. | ||
fn page(status: u16, title: &'static str, data: &[(&str, &Json)]) -> Response { | ||
let statements: String = data | ||
.iter() | ||
.map(|(name, v)| format!("window[\"{name}\"]=JSON.parse({});", js_json(v))) | ||
.collect(); | ||
let body = format!( | ||
"<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\ | ||
<title>{}</title><style>{STYLE}</style></head>\n<body><main id=\"app\"><noscript>This page needs JavaScript.</noscript></main>\n\ | ||
<script>{statements}</script>\n<script>{script}</script></body></html>\n", | ||
html_escape(title) | ||
<title>{title}</title>{}</head>\n<body><main id=\"app\"><noscript>This page needs JavaScript.</noscript></main>\n\ | ||
<script>{statements}</script></body></html>\n", | ||
assets::HEAD | ||
); | ||
let mut r = ( | ||
StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_REQUEST), | ||
| @@ -162,24 +178,21 @@ fn page(status: u16, title: &str, data: &[(&str, &Json)], script: &str) -> Respo | ||
) | ||
.into_response(); | ||
set(&mut r, "cache-control", "no-store"); | ||
set(&mut r, "content-security-policy", &csp(&statements)); | ||
set(&mut r, "x-frame-options", "DENY"); | ||
set(&mut r, "x-content-type-options", "nosniff"); | ||
set(&mut r, "referrer-policy", "same-origin"); | ||
r | ||
} | ||
| ||
const STYLE: &str = "body{font-family:system-ui,sans-serif;max-width:30rem;margin:3rem auto;padding:0 1rem}\ | ||
form{display:grid;gap:.6rem;margin:1rem 0}button{padding:.5rem 1rem;margin:.2rem 0}.err{color:#b00020}"; | ||
| ||
const ERROR_SCRIPT: &str = "document.getElementById(\"app\").replaceChildren(Object.assign(document.createElement(\"h1\"),{textContent:window.__errorData.error}),\ | ||
Object.assign(document.createElement(\"p\"),{textContent:window.__errorData.error_description}));"; | ||
| ||
fn error_page(status: u16, error: &str, description: &str) -> Response { | ||
page( | ||
status, | ||
"Error", | ||
"Something went wrong", | ||
&[( | ||
"__errorData", | ||
&json!({ "error": error, "error_description": description }), | ||
)], | ||
ERROR_SCRIPT, | ||
) | ||
} | ||
| ||
| @@ -459,52 +472,11 @@ fn authorization_page( | ||
} | ||
page( | ||
200, | ||
"Authorize", | ||
"Sign in", | ||
&[("__authorizeData", &data), ("__sessions", &json!(sessions))], | ||
PAGE_SCRIPT, | ||
) | ||
} | ||
| ||
/// The authorization page's script: sign in, or choose an account signed in | ||
/// on this device, then allow or deny. | ||
const PAGE_SCRIPT: &str = r#"(() => { | ||
const data = window.__authorizeData, sessions = window.__sessions, app = document.getElementById("app"); | ||
const csrf = () => decodeURIComponent((document.cookie.split("; ").find((c) => c.startsWith("csrf-token=")) || "=").split("=")[1]); | ||
const api = async (endpoint, body, token) => { | ||
const headers = { "content-type": "application/json", "x-csrf-token": csrf() }; | ||
if (token) headers.authorization = "Bearer " + token; | ||
const res = await fetch("/@atproto/oauth-provider/~api/" + endpoint, { method: "POST", headers, body: JSON.stringify(body), credentials: "same-origin" }); | ||
const json = await res.json(); | ||
if (!res.ok) throw new Error(json.error_description || json.error); | ||
return json; | ||
}; | ||
const el = (tag, props, ...children) => { const e = Object.assign(document.createElement(tag), props); e.append(...children); return e; }; | ||
const go = async (call) => { try { window.location.assign((await call()).url); } catch (e) { alert(e.message); } }; | ||
const deny = () => el("button", { onclick: () => go(() => api("reject", {})) }, "Deny"); | ||
const consent = (account, token) => app.replaceChildren( | ||
el("h1", {}, "Allow " + data.clientId + "?"), | ||
el("p", {}, "Signed in as " + account.handle + ". It asks for: " + data.scope), | ||
el("button", { onclick: () => go(() => api("consent", { did: account.did }, token)) }, "Allow"), deny()); | ||
const signIn = () => { | ||
const error = el("p", { className: "err" }); | ||
const identifier = el("input", { placeholder: "Handle or email", value: data.loginHint || "", required: true, autocomplete: "username" }); | ||
const password = el("input", { type: "password", placeholder: "Password", required: true, autocomplete: "current-password" }); | ||
const remember = el("input", { type: "checkbox", checked: true }); | ||
const submit = async (e) => { | ||
e.preventDefault(); | ||
try { | ||
const r = await api("sign-in", { locale: "en", identifier: identifier.value, password: password.value, remember: remember.checked }); | ||
consent(r.account, r.ephemeralToken); | ||
} catch (err) { error.textContent = err.message; } | ||
}; | ||
const choices = sessions.filter((s) => !s.loginRequired).map((s) => el("button", { onclick: () => consent(s.account) }, "Continue as " + s.account.handle)); | ||
app.replaceChildren(el("h1", {}, "Sign in to " + data.clientId), ...choices, | ||
el("form", { onsubmit: submit }, identifier, password, el("label", {}, remember, " Remember this account"), el("button", { type: "submit" }, "Sign in"), error), deny()); | ||
}; | ||
const selected = sessions.find((s) => s.account.did === data.selectedDid && !s.loginRequired); | ||
selected ? consent(selected.account) : signIn(); | ||
})();"#; | ||
| ||
/// `GET /oauth/authorize/redirect`: send the browser on to the client. | ||
pub(super) async fn redirect( | ||
AxState(svc): AxState<Shared>, | ||
| @@ -1216,6 +1188,39 @@ mod tests { | ||
} | ||
} | ||
| ||
/// The page's Content-Security-Policy allows its one inline script, by | ||
/// the hash of that script as sent, and each asset its head names is one | ||
/// the build has. | ||
#[tokio::test] | ||
async fn page_policy() { | ||
let r = error_page(400, "invalid_request", "</script>\u{2028}'\"&"); | ||
let policy = r.headers()["content-security-policy"] | ||
.to_str() | ||
.unwrap() | ||
.to_string(); | ||
let body = axum::body::to_bytes(r.into_body(), usize::MAX) | ||
.await | ||
.unwrap(); | ||
let html = String::from_utf8(body.to_vec()).unwrap(); | ||
let inline: Vec<&str> = html | ||
.split("<script>") | ||
.skip(1) | ||
.map(|s| s.split("</script>").next().unwrap()) | ||
.collect(); | ||
assert_eq!(inline.len(), 1, "{html}"); | ||
let hash = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(inline[0])); | ||
assert!(policy.contains(&format!("'sha256-{hash}'")), "{policy}"); | ||
let named: Vec<&str> = html | ||
.split("/oauth/assets/") | ||
.skip(1) | ||
.map(|s| &s[..s.find('"').unwrap()]) | ||
.collect(); | ||
assert!(named.len() >= 3, "{html}"); | ||
for n in named { | ||
assert!(assets::ASSETS.iter().any(|(a, _, _)| *a == n), "{n}"); | ||
} | ||
} | ||
| ||
#[test] | ||
fn script_literals() { | ||
let v = json!({ "a": "</script>\u{2028}\"" }); | ||
crates/pds-server/src/oauth.rs+3−0
| @@ -1,6 +1,7 @@ | ||
//! OAuth: the server as authorization server for its own accounts, as | ||
//! `spec/OAUTH.md` says: its metadata, loopback clients, pushed | ||
//! authorization requests, the authorization page and its API (`page`), | ||
//! the pages' build, embedded and served (`assets`), | ||
//! the token and revocation endpoints, DPoP (`dpop`), and the check every | ||
//! XRPC call with an OAuth access token makes of it (`access`). | ||
//! | ||
| @@ -22,6 +23,7 @@ | ||
//! and below the free-space floor (`low`) nothing that would keep anything | ||
//! is taken. | ||
| ||
mod assets; | ||
mod client; | ||
mod clients; | ||
mod dpop; | ||
| @@ -994,6 +996,7 @@ pub(crate) fn routes() -> Router<Shared> { | ||
any(|s, m, h, p, b| endpoint(s, m, h, p, b, Endpoint::Revoke)), | ||
) | ||
.route("/oauth/authorize", any(page::authorize)) | ||
.route("/oauth/assets/{name}", any(assets::asset)) | ||
.route("/oauth/authorize/redirect", any(page::redirect)) | ||
.route("/@atproto/oauth-provider/~api/{endpoint}", any(page::api)) | ||
} | ||
crates/pds-server/src/ops.rs+7−0
| @@ -398,6 +398,10 @@ const ROUTES: &[&str] = &[ | ||
"/@atproto/oauth-provider/~api/sign-out", | ||
]; | ||
| ||
/// The route of every path under `/oauth/assets/`, whatever its name, | ||
/// served or not: the pages' build (`spec/OAUTH-PAGES.md`, "Assets"). | ||
const ASSETS: &str = "/oauth/assets/{name}"; | ||
| ||
/// A request's route, as its log line and metrics label it: the NSID of a | ||
/// method served, `_health`, a path served outside `/xrpc/`, or `_unknown`. | ||
fn route_of(path: &str) -> &'static str { | ||
| @@ -407,6 +411,9 @@ fn route_of(path: &str) -> &'static str { | ||
if let Some(nsid) = path.strip_prefix("/xrpc/") { | ||
return pds_lexicon::method(nsid).map_or("_unknown", |m| m.nsid.as_str()); | ||
} | ||
if path.starts_with("/oauth/assets/") { | ||
return ASSETS; | ||
} | ||
ROUTES | ||
.iter() | ||
.find(|r| **r == path) | ||
crates/pds-server/build.rsnew+119−0
| @@ -0,0 +1,119 @@ | ||
//! Embeds the authorization pages' build, `web/dist` (`spec/OAUTH-PAGES.md`, | ||
//! "How the pages are built"): every file Vite wrote under `web/dist/assets`, | ||
//! by name, with its content type, and the `<head>` tags that name the | ||
//! entry's stylesheets and script and the pages' icon, read from Vite's | ||
//! manifest. A build without `web/dist` fails, saying to build `web/` first. | ||
| ||
#![forbid(unsafe_code)] | ||
| ||
use serde_json::Value as Json; | ||
use std::{env, fmt::Write, fs, path::Path}; | ||
| ||
const BUILD_WEB: &str = "build the pages first: `just web`, or `cd web && npm ci && npm run build`"; | ||
| ||
/// The content type a file of the build is served with, by its extension. | ||
fn content_type(name: &str) -> &'static str { | ||
match name.rsplit_once('.').map(|(_, ext)| ext) { | ||
Some("js") => "text/javascript", | ||
Some("css") => "text/css", | ||
Some("svg") => "image/svg+xml", | ||
Some("woff2") => "font/woff2", | ||
Some("png") => "image/png", | ||
_ => panic!( | ||
"web/dist/assets/{name}: the pages serve no file of this kind (spec/OAUTH-PAGES.md, \"Assets\")" | ||
), | ||
} | ||
} | ||
| ||
fn main() { | ||
let dist = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap()).join("../../web/dist"); | ||
println!("cargo:rerun-if-changed={}", dist.display()); | ||
let manifest_path = dist.join(".vite/manifest.json"); | ||
let manifest: Json = match fs::read_to_string(&manifest_path) { | ||
Ok(text) => serde_json::from_str(&text) | ||
.unwrap_or_else(|e| panic!("{}: {e}; {BUILD_WEB}", manifest_path.display())), | ||
Err(e) => panic!("{}: {e}; {BUILD_WEB}", manifest_path.display()), | ||
}; | ||
| ||
let mut assets: Vec<(String, std::path::PathBuf)> = fs::read_dir(dist.join("assets")) | ||
.unwrap_or_else(|e| panic!("web/dist/assets: {e}; {BUILD_WEB}")) | ||
.map(|e| e.unwrap()) | ||
.filter(|e| e.file_type().unwrap().is_file()) | ||
.map(|e| (e.file_name().into_string().unwrap(), e.path())) | ||
.collect(); | ||
assets.sort(); | ||
| ||
// A file the manifest names, as its name under `assets/`, which must be one of the build's. | ||
let asset = |file: &Json| -> String { | ||
let file = file.as_str().expect("a manifest file is a string"); | ||
let name = file | ||
.strip_prefix("assets/") | ||
.unwrap_or_else(|| panic!("web/dist/{file} is not under assets/; {BUILD_WEB}")); | ||
assert!( | ||
assets.iter().any(|(n, _)| n == name), | ||
"web/dist/{file}, which the manifest names, is missing; {BUILD_WEB}" | ||
); | ||
name.to_string() | ||
}; | ||
let chunks = manifest.as_object().expect("the manifest is an object"); | ||
let entry = chunks | ||
.values() | ||
.find(|c| c["isEntry"] == Json::Bool(true)) | ||
.unwrap_or_else(|| panic!("the manifest names no entry; {BUILD_WEB}")); | ||
// The entry's stylesheets: those it lists, or, as one stylesheet is | ||
// built for the whole app (`cssCodeSplit: false`), the build's. | ||
let mut stylesheets: Vec<String> = entry["css"] | ||
.as_array() | ||
.into_iter() | ||
.flatten() | ||
.map(asset) | ||
.collect(); | ||
if stylesheets.is_empty() { | ||
stylesheets = chunks | ||
.values() | ||
.filter(|c| c["file"].as_str().is_some_and(|f| f.ends_with(".css"))) | ||
.map(|c| asset(&c["file"])) | ||
.collect(); | ||
} | ||
let script = asset(&entry["file"]); | ||
let icon = asset( | ||
&chunks | ||
.get("src/assets/icon.svg") | ||
.unwrap_or_else(|| panic!("the manifest names no src/assets/icon.svg; {BUILD_WEB}"))["file"], | ||
); | ||
| ||
let mut head = | ||
format!("<link rel=\"icon\" href=\"/oauth/assets/{icon}\" type=\"image/svg+xml\">"); | ||
for s in &stylesheets { | ||
write!(head, "<link rel=\"stylesheet\" href=\"/oauth/assets/{s}\">").unwrap(); | ||
} | ||
write!( | ||
head, | ||
"<script type=\"module\" src=\"/oauth/assets/{script}\"></script>" | ||
) | ||
.unwrap(); | ||
| ||
let mut out = String::from( | ||
"/// The build's files under `web/dist/assets`, by name: its content type and bytes.\n\ | ||
pub(super) static ASSETS: &[(&str, &str, &[u8])] = &[\n", | ||
); | ||
for (name, path) in &assets { | ||
let path = path.canonicalize().unwrap(); | ||
writeln!( | ||
out, | ||
" ({name:?}, {:?}, include_bytes!({:?})),", | ||
content_type(name), | ||
path.display().to_string() | ||
) | ||
.unwrap(); | ||
} | ||
out.push_str("];\n\n"); | ||
writeln!( | ||
out, | ||
"/// The pages' `<head>` tags naming the build's icon, its entry's stylesheets and its script.\n\ | ||
pub(super) const HEAD: &str = {head:?};" | ||
) | ||
.unwrap(); | ||
let to = Path::new(&env::var("OUT_DIR").unwrap()).join("web.rs"); | ||
fs::write(to, out).unwrap(); | ||
} | ||
crates/pds-server/Cargo.toml+3−0
harness/checks/email.mjs+31−0
harness/checks/operations.mjs+2−2
harness/checks/pages.mjsnew+933−0
933 lines changed: not loaded until asked for.
harness/lib/args.mjs+7−2
harness/lib/observe.mjs+6−1
harness/compare.mjs+12−2
harness/compat.mjs+1−1
harness/contrast.mjsnew+80−0
harness/gates.mjs+11−3
harness/layers.mjsnew+50−0
harness/look.mjsnew+221−0
harness/package-lock.json+56−1
harness/package.json+3−1
spec/OAUTH-PAGES.mdnew+353−0
spec/OAUTH.md+7−4
spec/OPERATIONS.md+3−1
spec/PDS.md+1−0
web/src/assets/icon.svgnew+1−0
web/src/lib/atoms/Alert.sveltenew+15−0
web/src/lib/atoms/Avatar.sveltenew+40−0
web/src/lib/atoms/Button.sveltenew+95−0
web/src/lib/atoms/Checkbox.sveltenew+46−0
web/src/lib/atoms/ExternalLink.sveltenew+27−0
web/src/lib/atoms/Icon.sveltenew+41−0
web/src/lib/atoms/Input.sveltenew+72−0
web/src/lib/molecules/Account.sveltenew+52−0
web/src/lib/molecules/Client.sveltenew+47−0
web/src/lib/molecules/Field.sveltenew+44−0
web/src/lib/molecules/Permission.sveltenew+32−0
web/src/lib/molecules/TechnicalDetails.sveltenew+45−0
web/src/lib/organisms/AccountList.sveltenew+38−0
web/src/lib/organisms/CodeForm.sveltenew+55−0
web/src/lib/organisms/PermissionList.sveltenew+41−0
web/src/lib/organisms/Request.sveltenew+63−0
web/src/lib/organisms/SignInForm.sveltenew+66−0
web/src/lib/templates/Card.sveltenew+120−0
web/src/lib/api.tsnew+98−0
web/src/lib/contrast.jsonnew+10−0
web/src/lib/data.tsnew+88−0
web/src/lib/focus.tsnew+15−0
web/src/lib/scopes.tsnew+214−0
web/src/lib/words.tsnew+64−0
web/src/views/ChooseAccount.sveltenew+45−0
web/src/views/Consent.sveltenew+75−0
web/src/views/EmailCode.sveltenew+64−0
web/src/views/ErrorPage.sveltenew+28−0
web/src/views/SignIn.sveltenew+91−0
web/src/app.cssnew+61−0
web/src/App.sveltenew+103−0
web/src/main.tsnew+12−0
web/src/tokens.cssnew+144−0
web/AGENTS.mdnew+70−0
web/CLAUDE.mdnew+1−0
web/package-lock.jsonnew+1217−0
1217 lines changed: not loaded until asked for.