chadtmiller.com/monolith
An atproto PDS
0
0
// The authorization pages in a browser (spec/OAUTH-PAGES.md), a run of its
// own (`--pages`). Each step is a flow: a PAR on both sides, then the page
// in Chromium, driven as a person would drive it, to the client's redirect
// URI. Every random choice of a flow is drawn before either side is driven,
// so both sides take the same path whatever order their pages answer in.
//
// The server's controls are found by the accessible names of
// spec/OAUTH-PAGES.md, the reference's by its own (REFERENCE below). What is
// compared on both sides: the API calls each page made, in order, with
// their bodies and whether they carried an ephemeral token; where the
// browser landed; and the token answers for the codes it brought back. The
// server alone is held to the rest of the spec: its views, words, consent
// list, focus, busy buttons, headers, HTML, assets, console, origins, width
// on a phone, and axe-core's WCAG rules. Then, on the server alone, started
// again on `http://localhost:<port>`, its passkey flows, in Chromium with its
// virtual authenticator (spec/PASSKEYS.md).
import http from 'node:http'
import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { createHash } from 'node:crypto'
import { isDeepStrictEqual } from 'node:util'
import { chromium } from 'playwright'
import { PAGES_STEPS } from '../lib/args.mjs'
import { below, chance, pick } from '../lib/random.mjs'
import { cand, metricsUrl, ref, server, waitReady } from '../lib/processes.mjs'
import { checkMail } from '../lib/mail.mjs'
import { ASSETS } from '../lib/observe.mjs'
import { parseMetrics } from '../lib/prometheus.mjs'
import { fail } from '../lib/plc.mjs'
import { count, differ, run } from '../lib/report.mjs'
import { accounts, didOf } from '../lib/state.mjs'
import { strip } from '../lib/xrpc.mjs'
import { issuer } from '../lib/server.mjs'
import { CLIENTS, exchange, handleOf, newRequest, norm, sides } from './oauth.mjs'
import { SETS, SPACE_TYPES, grantOf, inc, includeOf, textOf } from '../lib/sets.mjs'
import { setEmailFactor, signInCodes } from './email.mjs'
import { createAccount } from './accounts.mjs'
import { addLink, newClient, passkeysAble, passkeysOf, redeem, serverRequest, whoOf } from './passkeys.mjs'
const AXE = readFileSync(createRequire(import.meta.url).resolve('axe-core/axe.min.js'), 'utf8')
/// The loopback clients a flow draws from: oauth.mjs's, some asking for
/// what spec/OAUTH-PAGES.md's consent list merges and covers, and some
/// asking for the harness's permission sets (lib/sets.mjs): titled and
/// not, with a detail and without, in other languages, long, granting
/// nothing, and towards audiences each said its own way.
const PAGE_CLIENTS = [
...CLIENTS.slice(1),
{ scope: 'atproto repo:com.example.foo?action=create&action=delete rpc:com.example.bar?aud=did:web:svc.test%23x blob:video/* blob:application/pdf account:status?action=manage account:repo identity:* transition:chat.bsky' },
{ scope: 'atproto repo:app.bsky.feed.post?action=create&action=delete repo:app.bsky.feed.like repo:com.example.foo?action=update repo:*?action=create blob:image/png blob:image/* blob:text/plain rpc:app.bsky.feed.getTimeline?aud=did:web:api.bsky.app%23bsky_appview rpc:app.bsky.actor.getProfile?aud=did:web:api.bsky.app%23bsky_appview rpc:app.bsky.actor.getProfile?aud=* rpc:*?aud=did:web:svc.test%23x account:email identity:handle' },
{ scope: 'atproto repo:* repo:app.bsky.feed.post account:email?action=manage account:status account:repo?action=manage blob:*/* blob:image/*' },
{ scope: 'atproto transition:generic transition:email transition:chat.bsky repo:app.bsky.feed.post repo:* rpc:*?aud=did:web:api.bsky.app%23bsky_appview blob:image/* account:email?action=manage account:status?action=manage account:repo identity:handle identity:*' },
{ scope: 'atproto repo:app.bsky.graph.listItem repo:com.example.notes?action=update repo:app.bsky.graph.follow?action=create repo:com.example.status repo:app.bsky.feed.post?action=create&action=delete repo:com.example.diaryEntry?action=create repo:com.example.inbox rpc:com.example.ping?aud=did:plc:aaaaaaaaaaaaaaaaaaaaaaaa%23svc rpc:com.example.pong?aud=did:plc:bbbbbbbbbbbbbbbbbbbbbbbb%23svc rpc:com.example.ping?aud=did:web:api.example.com%23a rpc:com.example.pong?aud=did:web:api.example.com%23b blob:application/json blob:text/plain blob:image/png' },
{ scope: `atproto ${inc(SETS.full, true)} ${inc(SETS.titleOnly)} repo:com.example.foo?action=create identity:handle` },
{ scope: `atproto ${inc(SETS.untitled, true)} repo:app.bsky.feed.post rpc:com.example.bar?aud=did:web:svc.test%23x ${inc(SETS.none)} ${inc(SETS.titleOnly, true)}` },
{ scope: `atproto ${inc(SETS.long)} ${inc(SETS.dropped, true)} ${inc(SETS.full)} ${inc(SETS.untitled)} blob:image/*` },
{ scope: `atproto transition:generic ${inc(SETS.full)} ${inc(SETS.untitled, true)} transition:email` },
{ scope: `atproto ${inc(SETS.bare)} include:${SETS.full}?aud=did:web:api.bsky.app%23bsky_appview include:${SETS.titleOnly}?aud=did:web:api.bsky.chat%23bsky_chat include:${SETS.bare}?aud=did:plc:aaaaaaaaaaaaaaaaaaaaaaaa%23svc` },
].map((c) => ({ redirects: ['http://127.0.0.1/callback'], ...c }))
// ------------------------------------------------------------ the names
/// The server's controls, by their accessible names (spec/OAUTH-PAGES.md,
/// "Sign in", "Email code", "Choose an account", "Consent", "Add a
/// passkey", "Passkey added", "The error page").
const SERVER = {
identifier: 'Handle or email',
password: 'Password',
remember: 'Remember this account on this device',
signIn: 'Sign in',
passkey: 'Sign in with a passkey',
code: 'Code',
codeSubmit: 'Sign in',
continueAs: (h) => `Continue as @${h}`,
another: 'Another account',
allow: 'Allow',
deny: 'Deny',
cancel: 'Cancel',
back: 'Back',
addPasskey: 'Add passkey',
headings: { signIn: 'Sign in', code: 'Check your email', choose: 'Choose an account', consent: 'Allow access', error: 'Something went wrong', addPasskey: 'Add a passkey', added: 'Passkey added' },
}
/// The reference's controls, as its pages name them. Its first view on a
/// device with no account, `Welcome`, takes a click on `Sign in` more.
const REFERENCE = {
identifier: 'Username or Email',
password: 'Password',
remember: 'Remember this account on this device',
signIn: 'Sign in',
code: '2FA Confirmation',
codeSubmit: 'Confirm',
continueAs: (h) => `Sign in as @${h}`,
another: 'Sign in to an account that is not listed',
allow: 'Authorize',
deny: 'Deny access',
cancel: 'Cancel',
back: 'Back',
}
const namesOf = (side) => (side === cand ? SERVER : REFERENCE)
// ------------------------------------------------------- the spec's words
const ALERTS = {
wrong: 'Wrong handle, email or password.',
wrongCode: 'Wrong code. Use the code in the latest email.',
space: 'The server is out of space. Try again later.',
other: 'Something went wrong. Try again.',
ended: 'This sign-in has ended. Go back to the app and start again.',
tries: (secs) => {
const n = Math.max(1, Math.ceil(secs / 60))
return `Too many tries. Try again in ${n} minute${n === 1 ? '' : 's'}.`
},
noPasskey: 'No passkey was used.',
otherAccount: 'That passkey is for another account.',
passkeyRefused: 'That passkey did not sign in. Try again, or use your password.',
noWebAuthn: 'This browser cannot make passkeys.',
hasPasskey: (h) => `This device already has a passkey for @${h}.`,
notMade: 'No passkey was made. Try again.',
linkEnded: 'This link has ended. Make a new one with pds passkey add.',
notAdded: 'That passkey was not added. Try again.',
}
/// The passkey page's words (spec/OAUTH-PAGES.md, "Add a passkey",
/// "Passkey added").
const PASSKEY_WORDS = {
add: (name, h) => `This passkey, named ${name}, will sign in to @${h} on this server.`,
added: (h) => `@${h} can now sign in with this passkey. You can close this page.`,
}
/// Words joined as spec/OAUTH-PAGES.md joins them: `a`, `a and b`, `a, b and c`.
const join = (xs) => (xs.length < 2 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs.at(-1)}`)
const capital = (s) => `${s[0].toUpperCase()}${s.slice(1)}`
/// Clauses, each a sentence of its own, joined with a space.
const sentences = (xs) => xs.map((x) => `${capital(x)}.`).join(' ')
const ACTIONS = [['create', 'add'], ['update', 'change'], ['delete', 'remove']]
const ACCOUNT = {
email: { read: 'see your email address', manage: 'see and change your email address' },
status: { read: 'see whether your account is active', manage: 'deactivate and reactivate your account' },
repo: { read: 'see the state of your data', manage: 'import your data from elsewhere' },
}
/// An upload's kind, by its type's first part.
const KIND = { image: 'images', video: 'videos', audio: 'audio', text: 'text' }
/// The domain an NSID's namespace is rooted at: its first two segments, reversed.
const appOf = (nsid) => nsid.split('.').slice(0, 2).reverse().join('.')
/// An NSID's last segment as a plain thing: words, lower case, its last
/// made plural (spec/OAUTH-PAGES.md, "<Data clauses>").
const thingOf = (nsid) => {
const words = nsid.split('.').at(-1).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase()
if (words.endsWith('s')) return words
if (/[b-df-hj-np-tv-z]y$/.test(words)) return `${words.slice(0, -1)}ies`
if (/(x|z|ch|sh)$/.test(words)) return `${words}es`
return `${words}s`
}
/// A permission's resource, positional parameter and query, from either
/// form: `repo:a?action=create` or `repo?collection=a&collection=b`.
function permission(token) {
const m = /^([a-z]+)(?::([^?]*))?(?:\?(.*))?$/.exec(token)
if (!m) return null
return { resource: m[1], positional: m[2] ? decodeURIComponent(m[2]) : null, q: new URLSearchParams(m[3] ?? '') }
}
const values = (p, name) => [...(p.positional ? [p.positional] : []), ...p.q.getAll(name)]
const verbs = (set) => join(ACTIONS.filter(([a]) => set.has(a)).map(([, v]) => v))
/// The actions `repo:` permissions ask of each collection, in the order
/// they first name them.
function askedOf(repos) {
const asked = new Map()
for (const p of repos) {
const given = p.q.getAll('action')
for (const c of values(p, 'collection')) {
if (!asked.has(c)) asked.set(c, new Set())
for (const a of given.length ? given : ['create', 'update', 'delete']) asked.get(c).add(a)
}
}
return asked
}
/// The collections of `asked` but `*` and those it covers, by app, each
/// app's `<Data clauses>` as `[app, clauses]`.
function dataClauses(asked, star) {
const apps = new Map()
for (const c of asked.keys()) {
if (c === '*' || (star && [...asked.get(c)].every((a) => star.has(a)))) continue
const app = appOf(c)
if (!apps.has(app)) apps.set(app, new Map())
const k = ACTIONS.filter(([a]) => asked.get(c).has(a)).map(([a]) => a).join(',')
const groups = apps.get(app)
if (!groups.has(k)) groups.set(k, [])
groups.get(k).push(thingOf(c))
}
return [...apps].map(([app, groups]) => [app, [...groups].map(([k, things]) => `${verbs(new Set(k.split(',')))} ${join(things)}`)])
}
/// `<services>`: what `rpc:` permissions name.
function servicesOf(rpcs) {
const auds = rpcs.map((p) => p.q.get('aud'))
const hosts = auds.filter((a) => a.startsWith('did:web:')).map((a) => a.slice('did:web:'.length).split('#')[0])
return [...new Set(hosts), ...(auds.some((a) => a !== '*' && !a.startsWith('did:web:')) ? ['a service'] : []), ...(auds.includes('*') ? ['any service'] : [])]
}
/// A text's length in Unicode code points.
const length = (s) => [...s].length
/// A space type's name (spec/OAUTH-PAGES.md, "<Space heading>"): its
/// declaration's title, or else its NSID's last segment in words.
function spaceName(type, spaces) {
const t = textOf(spaces?.[type], 'title')
if (typeof t === 'string' && t !== '') return t
const w = type.split('.').at(-1).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase()
return capital(w)
}
/// The spaces `space` permissions `ps` name, merged by type, authority and
/// key, as spec/OAUTH-PAGES.md says them ("<Space heading>", "<Space
/// clauses>"), with `spaces` and `handles` the page's `spaces` and
/// `spaceHandles`: each `{heading, sentence, codes}`, in the order first
/// named.
function spaceRows(ps, spaces, handles) {
const groups = new Map()
for (const p of ps) {
const type = values(p, 'spaceType')[0]
const authority = p.q.get('authority') ?? 'self'
const skey = p.q.get('skey') ?? '*'
const key = JSON.stringify([type, authority, skey])
if (!groups.has(key)) groups.set(key, { type, authority, skey, read: false, readSelf: false, writes: new Map(), manage: new Set() })
const g = groups.get(key)
const given = p.q.getAll('action')
const actions = given.length ? given : ['read', 'create', 'update', 'delete']
if (actions.includes('read')) g.read = true
if (actions.includes('read_self')) g.readSelf = true
let colls = p.q.getAll('collection')
if (!colls.length && type !== '*') colls = Array.isArray(spaces?.[type]?.collections) ? spaces[type].collections : []
const writes = actions.filter((a) => ACTIONS.some(([x]) => x === a))
if (writes.length) {
for (const c of colls) {
if (!g.writes.has(c)) g.writes.set(c, new Set())
for (const a of writes) g.writes.get(c).add(a)
}
}
for (const m of p.q.getAll('manage')) g.manage.add(m)
}
return [...groups.values()].map((g) => {
const did = g.authority.startsWith('did:')
const owner = did ? (handles?.[g.authority] ? `@${handles[g.authority]}` : g.authority) : null
const name = g.type === '*' ? null : spaceName(g.type, spaces)
const key = g.skey !== '*' ? ` named “${g.skey}”` : ''
const heading = g.type === '*'
? (g.authority === 'self' ? `All your spaces${key}` : g.authority === '*' ? `Every space${key} you're in` : `${owner}'s spaces${key} you're in`)
: (g.authority === 'self' ? `Your ${name} spaces${key}` : g.authority === '*' ? `${name} spaces${key} you're in` : `${owner}'s ${name} spaces${key} you're in`)
const clauses = []
if (g.read) clauses.push('read everything in them')
else if (g.readSelf) clauses.push("see what you've written in them")
const star = g.writes.get('*')
const byActions = new Map()
for (const [c, acts] of g.writes) {
if (c !== '*' && star && [...acts].every((a) => star.has(a))) continue
const k = ACTIONS.filter(([a]) => acts.has(a)).map(([a]) => a).join(',')
if (!byActions.has(k)) byActions.set(k, [])
byActions.get(k).push(c === '*' ? 'records of any kind' : thingOf(c))
}
for (const [k, things] of byActions) clauses.push(`${verbs(new Set(k.split(',')))} your own ${join(things)}`)
if (g.authority === 'self') {
const manage = [['create', 'make new ones'], ['update', "change who's in them"], ['delete', 'delete them']].filter(([m]) => g.manage.has(m)).map(([, w]) => w)
if (manage.length) clauses.push(join(manage))
} else if (g.authority === '*') {
const made = [['update', "change who's in"], ['delete', 'delete']].filter(([m]) => g.manage.has(m)).map(([, w]) => w)
const parts = [...(g.manage.has('create') ? ['make new ones'] : []), ...(made.length ? [`${made.join(' or ')} the ones you made`] : [])]
if (parts.length) clauses.push(parts.join(', and '))
}
const sentence = clauses.length ? sentences(clauses) : 'Asks for nothing this server grants.'
return { heading, sentence, codes: did && !handles?.[g.authority] ? [g.authority] : [] }
})
}
/// What a set's `Details` holds for its grant (spec/OAUTH-PAGES.md, "What
/// it grants"): `{summary, sentence, tables, spaces}`, each table `{head,
/// rows}` and each row `{cells, spans}`, a cell's text and its `rowspan`;
/// each space `{heading, sentence}`.
function grantDetails(grant, spaces, handles) {
const ps = grant.map(permission)
const sorted = (xs) => [...xs].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
const calls = new Map()
for (const p of ps.filter((p) => p.resource === 'rpc')) {
const aud = p.q.get('aud')
if (!calls.has(aud)) calls.set(aud, new Set())
for (const m of values(p, 'lxm')) calls.get(aud).add(m)
}
const towards = (aud) =>
aud === '*' ? 'Any service'
: aud.startsWith('did:web:api.bsky.app#') ? 'Bluesky App services'
: aud.startsWith('did:web:api.bsky.chat#') ? 'Bluesky Chat services'
: aud.startsWith('did:web:') && aud.includes('#') ? `A service controlled by ${aud.slice('did:web:'.length, aud.indexOf('#'))}`
: aud
const callRows = sorted(calls.keys()).flatMap((aud) => {
const ms = sorted(calls.get(aud))
return ms.map((m, i) => (i === 0 ? { cells: [m, towards(aud)], spans: [1, ms.length] } : { cells: [m], spans: [1] }))
})
const asked = askedOf(ps.filter((p) => p.resource === 'repo'))
const dataRows = sorted(asked.keys()).map((c) => ({ cells: [c, ...ACTIONS.map(([a]) => (asked.get(c).has(a) ? 'Yes' : ''))], spans: [1, 1, 1, 1] }))
const tables = [
...(callRows.length ? [{ head: ['Call', 'Towards'], rows: callRows }] : []),
...(dataRows.length ? [{ head: ['Data', 'Create', 'Update', 'Delete'], rows: dataRows }] : []),
]
const spaceList = spaceRows(ps.filter((p) => p.resource === 'space'), spaces, handles)
// In `<code>`: methods, collections, an audience said by no words, and a
// space's owner with no handle.
const codes = [...callRows.flatMap(({ cells }) => cells.filter((c, i) => i === 0 || (i === 1 && calls.has(c)))), ...dataRows.map(({ cells }) => cells[0]), ...spaceList.flatMap((s) => s.codes)]
return {
details: {
summary: 'Details',
sentence: grant.length ? 'The application requests the permissions necessary to perform the following actions on your behalf:' : 'Asks for nothing this server grants.',
tables,
spaces: spaceList.map(({ heading, sentence }) => ({ heading, sentence })),
},
codes,
}
}
/// The rows the consent list shows for the scope's `tokens`, in order, as
/// spec/OAUTH-PAGES.md merges and words them, the sets it includes being
/// `sets` (the page's `permissionSets`), its space types' declarations
/// `spaces` and owners' handles `handles` (the page's `spaces` and
/// `spaceHandles`): each `{heading, sentence, codes, details}`, with the
/// texts it shows in `<code>`, and for a set's row what its `Details`
/// holds (else null); and whether every set's title and detail is short
/// enough for "Seeing it all".
export function consentRows(tokens, sets = {}, spaces = {}, handles = {}) {
const has = (t) => tokens.includes(t)
const generic = has('transition:generic')
const parsed = tokens.map((t) => [t, permission(t)])
const named = new Set(['atproto', 'transition:generic', 'transition:email', 'transition:chat.bsky', ...tokens.filter((t) => includeOf(t))])
const of = (resource) => {
const xs = parsed.filter(([t, p]) => p?.resource === resource && !named.has(t))
for (const [t] of xs) named.add(t)
return xs.map(([, p]) => p)
}
const row = (heading, sentence, codes = []) => ({ heading, sentence, codes, details: null })
const rows = []
let short = true
if (generic) rows.push(row('Full access', 'Read and change all your data, upload files and act as you on other services, as an app password can.'))
const ids = of('identity')
if (ids.length) rows.push(row('Identity', ids.some((p) => values(p, 'attr').includes('*')) ? "Change your handle, and take over your account's identity, which could move your account elsewhere." : 'Change your handle.'))
const account = {}
for (const p of of('account')) for (const a of values(p, 'attr')) account[a] = account[a] === 'manage' ? 'manage' : (p.q.get('action') ?? 'read')
if (has('transition:email')) account.email ??= 'read'
const clauses = ['email', 'status', 'repo'].filter((a) => account[a]).map((a) => ACCOUNT[a][account[a]])
if (clauses.length) rows.push(row('Account', `${capital(join(clauses))}.`))
if (has('transition:chat.bsky')) rows.push(row('Direct messages', 'Read and send your Bluesky direct messages.'))
for (const s of spaceRows(of('space'), spaces, handles)) rows.push(row(s.heading, s.sentence, s.codes))
for (const token of tokens) {
const i = includeOf(token)
if (!i) continue
const main = sets?.[i.nsid]
const text = (field) => {
const t = textOf(main, field)
return typeof t === 'string' && t !== '' ? t : null
}
const [title, detail] = [text('title'), text('detail')]
if ((title && length(title) > 60) || (detail && length(detail) > 140)) short = false
const { details, codes } = grantDetails(grantOf(i.nsid, main, i.aud), spaces, handles)
rows.push({ heading: title ?? i.nsid, sentence: detail ?? (title ? i.nsid : ''), codes, details })
}
const repos = of('repo')
if (repos.length && !generic) {
const asked = askedOf(repos)
const star = asked.get('*')
if (star) rows.push(row('All your data', `${capital(verbs(star))} all your data.`))
for (const [app, data] of dataClauses(asked, star)) rows.push(row(`Your data in ${app}`, sentences(data)))
}
const blobs = of('blob')
if (blobs.length && !generic) {
const types = blobs.flatMap((p) => values(p, 'accept'))
const families = types.map((t) => KIND[t.split('/')[0]] ?? 'files')
const kinds = types.includes('*/*') ? ['any file'] : [...new Set([...families.filter((k) => k !== 'files'), ...(families.includes('files') ? ['files'] : [])])]
rows.push(row('Uploads', `Upload ${join(kinds)}.`))
}
const rpcs = of('rpc')
if (rpcs.length && !generic) rows.push(row('Other services', `Act as you on ${join(servicesOf(rpcs))}.`))
for (const t of tokens) if (!named.has(t)) rows.push(row('Permission', t, [t]))
rows.push(row('Who you are', 'See which account is yours.'))
return { rows, short }
}
/// `Technical details` for the scope's `tokens`: each token, and under an
/// `include:` the scope strings its set grants, `[{token, grant}]`.
export const technicalDetails = (tokens, sets = {}) =>
tokens.map((token) => {
const i = includeOf(token)
return { token, grant: i ? grantOf(i.nsid, sets?.[i.nsid], i.aud) : [] }
})
// ------------------------------------------------------------ the browser
let browser
/// A browser context on `side`: a device. `phone` draws it 360 by 740 in
/// the dark colour scheme.
async function device(side, phone = false) {
const ctx = await browser.newContext(phone ? { viewport: { width: 360, height: 740 }, colorScheme: 'dark', isMobile: true, hasTouch: true } : { viewport: { width: 1200, height: 900 }, colorScheme: 'light' })
return { side, ctx, phone }
}
/// A page of `dev`, watched: its API calls, its console, the origins it
/// asks, the assets it loads, and where it lands at the client's
/// `redirect`. The browser's request to the client is seen as it goes:
/// Playwright routes no hop of a redirect, so it is answered where it can
/// be and otherwise fails, which is the client's matter, not the page's.
/// The `Location` that sent it there is kept too, for a fragment, which
/// no request carries.
async function open(dev, redirect) {
const page = await dev.ctx.newPage()
const w = { page, side: dev.side, phone: dev.phone, calls: [], console: [], strays: [], assets: [], landed: null, location: null, redirect }
const own = issuer(dev.side)
const landing = new URL(redirect)
// A redirect URI of http on port 80 Chromium tries first as https, by a
// redirect of its own: both are the client's.
const upgraded = (u) => landing.protocol === 'http:' && !landing.port && u.protocol === 'https:' && !u.port
const client = (u) => u.hostname === landing.hostname && u.pathname === landing.pathname && (u.origin === landing.origin || upgraded(u))
await page.route(client, (route) => route.fulfill({ status: 200, contentType: 'text/plain', body: 'the client' }))
page.on('response', (r) => {
const u = new URL(r.url())
if (u.origin === own && r.status() >= 300 && r.status() < 400) w.location = r.headers().location ?? null
})
page.on('request', async (r) => {
const u = new URL(r.url())
if (client(u)) {
if (!w.landed) w.landed = { url: `${landing.origin}${u.pathname}${u.search}`, method: r.method(), post: r.postData() }
return
}
if (u.pathname.includes('/~api/')) {
const headers = await r.allHeaders()
let body
try {
body = JSON.parse(r.postData() ?? 'null')
} catch {
body = r.postData()
}
w.calls.push({ endpoint: u.pathname.split('/~api/')[1], body, bearer: /^bearer /i.test(headers.authorization ?? '') })
}
if (dev.side === cand && u.origin !== own && !u.protocol.startsWith('data')) w.strays.push(r.url())
})
if (dev.side === cand) {
// The browser's own notes of a request that answered an error status,
// or got no answer, as a wrong password's does, are the browser's, not
// the page's.
page.on('console', (m) => {
if (/^Failed to load resource: /.test(m.text())) return
w.console.push(`${m.type()}: ${m.text()}`)
})
page.on('pageerror', (e) => w.console.push(`pageerror: ${e.message}`))
page.on('response', (r) => {
if (new URL(r.url()).pathname.startsWith('/oauth/assets/')) w.assets.push(r)
})
}
return w
}
const wait = (ms) => new Promise((ok) => setTimeout(ok, ms))
/// The view `w` shows: `landed`, `error`, `welcome` (the reference's
/// first), `signIn`, `code`, `choose` or `consent`; waiting up to 8 seconds
/// for one, else null.
async function viewOf(w) {
const { page } = w
for (let t = 0; t < 80; t++) {
if (w.landed) return 'landed'
try {
if (w.side === cand) {
const h = await page.locator('h1').allInnerTexts()
const found = Object.entries(SERVER.headings).find(([, text]) => h.map((x) => x.trim()).includes(text))
if (found) return found[0]
} else {
if (await page.getByRole('textbox', { name: REFERENCE.code, exact: true }).isVisible()) return 'code'
if (await page.getByRole('textbox', { name: REFERENCE.identifier, exact: true }).isVisible()) return 'signIn'
if (await page.getByRole('button', { name: REFERENCE.allow, exact: true }).isVisible()) return 'consent'
if (await page.getByText('Continue with an existing account', { exact: true }).isVisible()) return 'choose'
if (await page.getByText('Welcome', { exact: true }).isVisible()) return 'welcome'
if (await page.getByText('Something went wrong', { exact: true }).isVisible()) return 'error'
}
} catch {}
await wait(100)
}
return null
}
const button = (w, name) => w.page.getByRole('button', { name, exact: true })
const textbox = (w, name) => w.page.getByRole('textbox', { name, exact: true })
const has = async (loc) => (await loc.count()) > 0 && (await loc.first().isVisible())
/// What the page shows the person, and where it is, for a report.
const shown = async (w) => {
try {
return `${w.page.url()}\n${await w.page.locator('body').ariaSnapshot()}`
} catch (e) {
return `${w.page.url()}\n(no snapshot: ${e.message})`
}
}
// ------------------------------------------------- held to the spec, server
/// The request a failure names: the flow and the view.
let current = {}
async function held(what, want, got) {
await fail(cand, `${what} (spec/OAUTH-PAGES.md)`, current, want, got)
}
/// The control the spec puts focus on in `view`, or null.
function focusFor(w, view) {
if (view === 'signIn') return w.page.locator('input:not([type=checkbox])').filter({ hasNot: w.page.locator('[disabled]') })
if (view === 'code') return textbox(w, SERVER.code)
if (view === 'choose') return w.page.getByRole('button').first()
if (view === 'consent') return button(w, SERVER.allow)
if (view === 'addPasskey') return button(w, SERVER.addPasskey)
if (view === 'added') return w.page.locator('h1')
return null
}
/// The server's `view` held to the spec: its heading, the controls it has,
/// focus, no style, no overflow on a phone, and axe-core's rules
/// (spec/OAUTH-PAGES.md, "Every page", "Sign in", "Email code", "Choose an
/// account", "Consent", "Add a passkey", "Passkey added"). Sign in has
/// `Sign in with a passkey` in a browser with WebAuthn, and not without
/// (`ctx.webauthn` false).
async function checkView(w, view, ctx = {}) {
const { page } = w
current = { ...current, view }
const want = []
if (view === 'signIn') want.push(['textbox', SERVER.identifier], ['textbox', SERVER.password], ['checkbox', SERVER.remember], ['button', SERVER.signIn], ...(ctx.webauthn === false ? [] : [['button', SERVER.passkey]]), ['button', ctx.first ? SERVER.cancel : SERVER.back])
if (view === 'code') want.push(['textbox', SERVER.code], ['button', SERVER.codeSubmit], ['button', SERVER.back])
if (view === 'choose') want.push(['button', SERVER.another], ['button', SERVER.cancel])
if (view === 'consent') want.push(['button', SERVER.allow], ['button', SERVER.deny], ['button', ctx.first ? SERVER.another : SERVER.back])
if (view === 'addPasskey') want.push(['button', SERVER.addPasskey])
const missing = []
for (const [role, name] of want) if (!(await has(page.getByRole(role, { name, exact: true })))) missing.push(`${role} "${name}"`)
if (missing.length) await held(`the ${view} view's controls`, want.map(([r, n]) => `${r} "${n}"`), { missing, shown: await shown(w) })
if (view === 'signIn' && ctx.webauthn === false && (await has(button(w, SERVER.passkey)))) await held('the sign in view in a browser without WebAuthn', `no button "${SERVER.passkey}"`, await shown(w))
if (view === 'signIn') {
const autocomplete = await textbox(w, SERVER.identifier).first().getAttribute('autocomplete').catch(() => null)
if (autocomplete !== 'username webauthn') await held(`the "${SERVER.identifier}" field's autocomplete`, 'username webauthn', autocomplete)
}
if ((await page.locator('h1').count()) !== 1) await held(`the ${view} view's headings`, 'one h1', await page.locator('h1').allInnerTexts())
if (view === 'addPasskey') {
const text = PASSKEY_WORDS.add(ctx.name, ctx.handle)
if (!(await has(page.getByText(text, { exact: true }))) || !(await has(page.getByText(`@${ctx.handle}`, { exact: true })))) await held('the add a passkey view\'s words and account', [text, `@${ctx.handle}`], await shown(w))
}
if (view === 'added') {
const text = PASSKEY_WORDS.added(ctx.handle)
if (!(await has(page.getByText(text, { exact: true })))) await held('the passkey added view\'s words', text, await shown(w))
if ((await page.getByRole('button').count()) !== 0) await held('the passkey added view\'s buttons', 'none', await page.getByRole('button').allInnerTexts())
}
if (view === 'choose') {
const snapshot = await page.locator('main').ariaSnapshot()
const accountsShown = [...snapshot.matchAll(/button "(Continue as @[^"]+)"/g)].map((m) => m[1])
const sorted = [...accountsShown].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
if (!accountsShown.length || !isDeepStrictEqual(accountsShown, sorted)) await held('the accounts to choose, in order of handle', sorted.length ? sorted : 'a "Continue as @<handle>" button for each', accountsShown)
}
if (view === 'consent') await checkConsent(w, ctx)
if (view === 'code' && ctx.typed !== undefined) {
const text = `We sent a sign-in code to the email address of ${ctx.typed}.`
if (!(await has(page.getByText(text, { exact: true })))) await held('the email code view\'s words', text, await shown(w))
}
// Focus when the view appears: its first empty field, else its primary
// button, else its first button.
const target = ctx.appeared ? focusFor(w, view) : null
if (target) {
const fields = view === 'signIn' || view === 'code'
let ok = false
for (let t = 0; t < 20 && !ok; t++) {
ok = await page.evaluate((primary) => {
const a = document.activeElement
if (!a || a === document.body) return false
const empty = [...document.querySelectorAll('main input:not([type=checkbox]):not([type=hidden])')].find((f) => !f.value)
if (empty) return a === empty
return primary === null ? null : a.tagName === 'BUTTON' && (a.getAttribute('aria-label') ?? a.textContent.trim()) === primary
}, fields ? SERVER.signIn : null)
if (ok === null) ok = await target.first().evaluate((el) => el === document.activeElement).catch(() => false)
if (!ok) await wait(50)
}
if (!ok) await held(`focus when the ${view} view appears`, fields ? `the first empty field, else "${SERVER.signIn}"` : view === 'choose' ? 'the first button' : view === 'consent' ? `"${SERVER.allow}"` : view === 'addPasskey' ? `"${SERVER.addPasskey}"` : view === 'added' ? 'its heading' : 'none', await page.evaluate(() => document.activeElement?.outerHTML.slice(0, 200) ?? null))
}
const styled = await page.evaluate(() => [...document.querySelectorAll('[style], style')].map((e) => e.outerHTML.slice(0, 120)))
if (styled.length) await held(`the ${view} view's styles`, 'no style attribute or element', styled)
if (w.phone) {
const wide = await page.evaluate(() => ({ scrollWidth: document.documentElement.scrollWidth, innerWidth: window.innerWidth }))
if (wide.scrollWidth > wide.innerWidth) await held(`the ${view} view at 360 CSS pixels`, `scrollWidth at most ${wide.innerWidth}`, wide)
}
await page.evaluate(AXE)
const found = await page.evaluate(async () => {
const r = await window.axe.run(document, { runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa'] } })
return r.violations.map((v) => ({ id: v.id, impact: v.impact, nodes: v.nodes.map((n) => n.target.join(' ')).slice(0, 3) }))
})
if (found.length) await held(`axe-core on the ${view} view${w.phone ? ' (phone, dark)' : ''}`, 'no violation', found)
count(`pages: server ${view} view held to the spec`, true)
}
/// The consent view's list, `Technical details`, and what is in the window
/// as it appears, for the scope the page was given and the sets it
/// includes (`permissionSets`). A row's sentence is its text but its
/// heading and its `Details`; a set's `Details` is read open, after its
/// being closed as the view appears is noted (spec/OAUTH-PAGES.md,
/// "Consent").
async function checkConsent(w, ctx) {
const { page } = w
const { scope, sets, spaces, handles } = await page.evaluate(() => ({ scope: window.__authorizeData?.scope ?? '', sets: window.__authorizeData?.permissionSets ?? {}, spaces: window.__authorizeData?.spaces ?? {}, handles: window.__authorizeData?.spaceHandles ?? {} }))
const tokens = scope.split(' ').filter(Boolean)
const { rows: want, short } = consentRows(tokens, sets, spaces, handles)
const rowDetails = 'main ul > li details'
const closed = await page.evaluate((sel) => {
const ds = [...document.querySelectorAll(sel)]
const was = ds.map((d) => !d.open)
for (const d of ds) d.open = true
return was
}, rowDetails)
await page.waitForTimeout(50)
const got = await page.evaluate(() => {
const text = (el) => el.textContent.replace(/\s+/g, ' ').trim()
const cell = (c) => text(c) || [...c.querySelectorAll('[role="img"][aria-label]')].map((e) => e.getAttribute('aria-label')).join(' ')
const items = [...document.querySelectorAll('main ul > li')].filter((li) => li.querySelector('h2'))
return items.map((li) => {
const h = li.querySelector('h2')
const rest = li.cloneNode(true)
rest.querySelector('h2').remove()
for (const d of rest.querySelectorAll('details')) d.remove()
const ds = [...li.querySelectorAll('details')].map((d) => {
const summary = d.querySelector('summary')
const body = d.cloneNode(true)
for (const h3 of body.querySelectorAll('h3')) {
if (h3.nextElementSibling?.tagName === 'P') h3.nextElementSibling.remove()
h3.remove()
}
for (const x of body.querySelectorAll('summary, table')) x.remove()
return {
summary: summary ? text(summary) : null,
sentence: text(body),
spaces: [...d.querySelectorAll('h3')].map((h3) => ({ heading: text(h3), sentence: h3.nextElementSibling?.tagName === 'P' ? text(h3.nextElementSibling) : null })),
tables: [...d.querySelectorAll('table')].map((t) => ({
head: t.tHead?.rows[0] ? [...t.tHead.rows[0].cells].map((c) => (c.tagName === 'TH' ? text(c) : { td: text(c) })) : null,
rows: [...t.tBodies].flatMap((b) => [...b.rows]).map((r) => ({ cells: [...r.cells].map(cell), spans: [...r.cells].map((c) => c.rowSpan) })),
})),
}
})
return { heading: text(h), sentence: text(rest), codes: [...li.querySelectorAll('code')].map((c) => c.textContent.trim()), details: ds.length === 0 ? null : ds.length === 1 ? ds[0] : ds }
})
})
await page.evaluate((sel) => { for (const d of document.querySelectorAll(sel)) d.open = false }, rowDetails)
await page.waitForTimeout(50)
const shape = (xs) => xs.map(({ heading, sentence, codes, details }) => ({ heading, sentence, codes: [...codes].sort(), details }))
if (!isDeepStrictEqual(shape(got), shape(want))) await held('the consent list', shape(want), shape(got))
if (closed.some((c) => !c)) await held("each set's Details closed as the consent view appears", closed.map(() => true), closed)
const details = page.locator('details').filter({ has: page.locator('summary', { hasText: 'Technical details' }) })
if ((await details.count()) !== 1) return held('Technical details', 'one <details> whose summary is "Technical details"', await shown(w))
// A list of the tokens, each in <code>, and under an `include:` a list of
// its grant's scope strings.
const tech = technicalDetails(tokens, sets)
const listed = await details.first().evaluate((d) => {
const codes = [...d.querySelectorAll('code')].map((c) => c.textContent.trim())
const list = d.querySelector('ul, ol')
const items = list
? [...list.children].filter((li) => li.tagName === 'LI').map((li) => {
const sub = li.querySelector('ul, ol')
const own = [...li.querySelectorAll('code')].filter((c) => !sub?.contains(c)).map((c) => c.textContent.trim())
return { token: own.length === 1 ? own[0] : own, grant: sub ? [...sub.querySelectorAll('code')].map((c) => c.textContent.trim()) : [] }
})
: null
return { codes, items }
})
const flat = tech.flatMap(({ token, grant }) => [token, ...grant])
if (!isDeepStrictEqual(listed.codes, flat)) await held('Technical details', flat, listed.codes)
else if (!isDeepStrictEqual(listed.items, tech)) await held('Technical details, a list of the tokens and under each include: its grant', tech, listed.items)
if (ctx.loopback && !(await has(page.getByText('An app on your device', { exact: true })))) await held('the client on the consent view', 'An app on your device', await shown(w))
// Seeing it all, from the top of the page: the actions in the window
// whatever the scope, and with six rows or fewer, no set's title or
// detail long, nothing to scroll.
const fits = want.length <= 6 && short
const seen = await page.evaluate(([names, fits]) => {
window.scrollTo(0, 0)
const inside = (el) => {
const r = el.getBoundingClientRect()
return r.width > 0 && r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth
}
const buttons = [...document.querySelectorAll('main button')]
const outside = names.filter((n) => buttons.some((b) => (b.getAttribute('aria-label') ?? b.textContent.trim()) === n && !inside(b)))
const tall = fits && document.documentElement.scrollHeight > window.innerHeight
return { outside, tall, scrollHeight: document.documentElement.scrollHeight, innerHeight: window.innerHeight }
}, [[SERVER.allow, SERVER.deny, SERVER.back, SERVER.another], fits])
if (seen.outside.length) await held(`the consent view's actions in the window${w.phone ? ' (360 by 740)' : ' (1200 by 900)'}`, 'Allow, Deny and Back or Another account within the window', { ...seen, rows: want.length })
if (seen.tall) await held(`the consent view with ${want.length} rows${w.phone ? ' (360 by 740)' : ' (1200 by 900)'}`, 'no taller than the window', { ...seen, rows: want.length })
}
/// The alert the server's page shows, as its text, once it is `want` or
/// after a second and a half.
async function alertText(w, want) {
let got = null
for (let t = 0; t < 30; t++) {
const texts = (await w.page.getByRole('alert').allInnerTexts()).map((x) => x.trim()).filter(Boolean)
got = texts.length ? texts.join(' | ') : null
if (got === want) return got
await wait(50)
}
return got
}
async function checkAlert(w, want) {
const got = await alertText(w, want)
if (got !== want) await held('the alert', want, got)
}
/// The page's first answer and its HTML held to the spec
/// (spec/OAUTH-PAGES.md, "How the pages are built").
async function checkDocument(w, res) {
const h = res.headers()
const html = await res.text()
const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)].map((m) => m[1])
const bad = []
if (inline.length !== 1) bad.push(`${inline.length} inline scripts, not one`)
else if (!/^(window\["__\w+"\]=JSON\.parse\("(?:[^"\\]|\\.)*"\);)+$/.test(inline[0])) bad.push('the inline script holds more than the data statements')
const hash = inline[0] === undefined ? '' : createHash('sha256').update(inline[0]).digest('base64')
const csp = `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'`
if (h['content-security-policy'] !== csp) bad.push({ 'content-security-policy': h['content-security-policy'] ?? null, want: csp })
for (const [k, v] of [['x-frame-options', 'DENY'], ['x-content-type-options', 'nosniff'], ['referrer-policy', 'same-origin'], ['cache-control', 'no-store']]) if (h[k] !== v) bad.push({ [k]: h[k] ?? null, want: v })
if (!/<html lang="en">/.test(html)) bad.push('no <html lang="en">')
if (!/<meta charset="utf-8">/i.test(html)) bad.push('no <meta charset="utf-8">')
if (!/<meta name="viewport" content="width=device-width,initial-scale=1">/.test(html)) bad.push('no viewport meta')
if (!/<main id="app"><noscript>This page needs JavaScript\.<\/noscript><\/main>/.test(html)) bad.push('no <main id="app"> with its <noscript>')
const links = [...html.matchAll(/<link\b[^>]*>/gi)].map((m) => m[0])
const sheets = links.filter((l) => /rel="stylesheet"/.test(l))
const icons = links.filter((l) => /rel="icon"/.test(l))
const modules = [...html.matchAll(/<script\b[^>]*\btype="module"[^>]*\bsrc="([^"]*)"[^>]*>/gi)].map((m) => m[1])
if (!sheets.length || sheets.some((l) => !/href="\/oauth\/assets\/[^"]+"/.test(l))) bad.push({ stylesheets: sheets })
if (icons.length !== 1 || !/href="\/oauth\/assets\/[^"]+"/.test(icons[0])) bad.push({ icons })
if (modules.length !== 1 || !modules[0].startsWith('/oauth/assets/')) bad.push({ modules })
if (/\sstyle=|<style\b/i.test(html)) bad.push('a style attribute or element in the HTML')
if (bad.length) await held('the page\'s HTML and headers', 'as "How the pages are built" says', bad)
return { icon: /href="([^"]+)"/.exec(icons[0] ?? '')?.[1] }
}
const TYPES = { js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml', woff2: 'font/woff2', png: 'image/png' }
/// Each asset the page loaded held to the spec; and, once a run, a name the
/// build has not, `HEAD`, and another method (spec/OAUTH-PAGES.md, "How the
/// pages are built").
let assetsProbed = false
async function checkAssets(w) {
for (const r of w.assets) {
const h = r.headers()
const ext = new URL(r.url()).pathname.split('.').at(-1)
const want = { status: 200, 'content-type': TYPES[ext], 'cache-control': 'public, max-age=31536000, immutable', 'x-content-type-options': 'nosniff' }
const got = { status: r.status(), 'content-type': h['content-type'], 'cache-control': h['cache-control'], 'x-content-type-options': h['x-content-type-options'] }
if (!isDeepStrictEqual(want, got)) await held(`the asset ${new URL(r.url()).pathname}`, want, got)
}
if (assetsProbed || !w.assets.length) return
assetsProbed = true
const base = issuer(cand)
const one = new URL(w.assets[0].url()).pathname
const head = await fetch(`${base}${one}`, { method: 'HEAD' })
const headBody = await head.text()
if (head.status !== 200 || headBody !== '' || head.headers.get('cache-control') !== 'public, max-age=31536000, immutable') await held(`HEAD ${one}`, '200, no body, cached as immutable', { status: head.status, body: headBody.length, 'cache-control': head.headers.get('cache-control') })
// Sent as written, by node:http: fetch would take the dot segments out.
const raw = (path, method) => new Promise((ok) => {
const req = http.request(`${base}${path}`, { method, path }, (res) => {
res.resume()
res.on('end', () => ok(res.statusCode))
})
req.on('error', () => ok(0))
req.end()
})
for (const [path, method] of [['/oauth/assets/no-such-file.js', 'GET'], ['/oauth/assets/', 'GET'], ['/oauth/assets/../jwks', 'GET'], ['/oauth/assets/%2e%2e/jwks', 'GET'], [one, 'POST']]) {
const status = await raw(path, method)
if (status !== 404) await held(`${method} ${path}`, 404, status)
}
}
/// The server's metrics after the run: every request under
/// `/oauth/assets/` counted under the one route `/oauth/assets/{name}`
/// (spec/OPERATIONS.md), the assets the pages loaded among its `200`s and
/// the probes above among its `404`s, and no label holding a name.
async function checkAssetMetrics() {
current = { check: 'the metrics, after the flows', url: metricsUrl }
const r = await fetch(metricsUrl)
const { families } = parseMetrics(await r.text())
const samples = families.pds_requests_total?.samples ?? []
const by = (status) => samples.filter((s) => s.labels.method === ASSETS && s.labels.status === status).reduce((n, s) => n + s.value, 0)
const named = samples.filter((s) => s.labels.method?.startsWith('/oauth/assets/') && s.labels.method !== ASSETS).map((s) => s.labels.method)
const got = { '200': by('200'), '404': by('404'), named }
if (!(got['200'] >= 1 && got['404'] >= 5 && !named.length)) await held('pds_requests_total for the assets', { method: ASSETS, '200': 'at least 1', '404': 'at least the 5 probes', named: [] }, got)
else count('pages: the assets\' metrics', true)
}
/// What the server's page said and asked for, held to the spec at a flow's
/// end: no message in its console, no request to another origin
/// (spec/OAUTH-PAGES.md, "How the pages are built", "Every page").
async function checkWatched(w) {
if (w.console.length) await held('the page\'s console', 'no message', w.console)
if (w.strays.length) await held('the origins the page asked', `only ${issuer(cand)} and the client's redirect URI`, w.strays)
await checkAssets(w)
}
// ------------------------------------------------------------ the flows
/// Where `w` landed, as compared: the parameters it brought the client,
/// from the query, the fragment or the form, by the request's mode.
async function landing(w, req) {
if (!w.landed) return null
let params
if (w.landed.method === 'POST') params = Object.fromEntries(new URLSearchParams(w.landed.post ?? ''))
else if (req.mode === 'fragment') params = Object.fromEntries(new URLSearchParams(new URL(w.location ?? w.landed.url).hash.slice(1)))
else params = Object.fromEntries(new URL(w.landed.url).searchParams)
const out = {}
for (const [k, v] of Object.entries(params)) {
if (k === 'error_description') continue
out[k] = k === 'state' ? (v === req.state ? '<state>' : v) : k === 'code' ? '<code>' : strip(w.side, v)
}
return { to: `${new URL(w.landed.url).origin}${new URL(w.landed.url).pathname}`, method: w.landed.method, params: out, code: params.code }
}
/// The flow's record on `side`, as compared: each side's mailed code, which
/// differs between them, named.
const record = (w, land) => ({
calls: w.calls.map((c) => ({ endpoint: c.endpoint, body: norm(w.side, c.body?.emailOtp !== undefined && c.body.emailOtp === w.mailed ? { ...c.body, emailOtp: '<the code mailed>' } : c.body), bearer: c.bearer })),
landed: land && { to: land.to, method: land.method, params: land.params },
})
/// Drive `w` by `plan` until it lands, cancels, or has nothing more to do.
/// The plan: `acct` (who signs in), `by` (handle, email or DID), `remember`,
/// `wrong` (a wrong password first), `codes` (the email codes to type, in
/// order, if the account's factor is on: each a code, or a function of the
/// side), `back` (back from consent once), `end` (`allow`, `deny`, or
/// `cancel` at the first view with Cancel). With `stopAt`, it stops when
/// that view shows. Marks `w.remembered` when a sign-in with `remember`
/// was answered `200`.
async function drive(w, plan, { stopAt, holdOnce, hint } = {}) {
const N = namesOf(w.side)
const isServer = w.side === cand
const identifier = plan.by === 'did' ? didOf(w.side, plan.acct) : plan.by === 'email' ? plan.acct.email : handleOf(plan.acct)
let wrongDone = !plan.wrong
let codeIndex = 0
let backDone = !plan.back
const cancelling = plan.end === 'cancel'
for (let i = 0; i < 16; i++) {
const view = await viewOf(w)
if (view === null) return differ(`pages: the ${w.side.name}'s page shows no view it knows`, current, 'a view', await shown(w))
w.first ??= view
if (view === 'landed' || view === stopAt) return view
// A view is first when nothing came before it: Cancel, or on consent
// Another account, rather than Back.
if (isServer && view !== 'welcome') await checkView(w, view, { first: w.first === view && view !== 'choose', appeared: view !== w.lastView, loopback: true, typed: w.typed })
w.lastView = view
if (view === 'error') return view
if (view === 'welcome') {
await button(w, cancelling ? N.cancel : N.signIn).click()
if (cancelling) for (let t = 0; t < 100 && !w.landed; t++) await wait(50)
continue
}
if (cancelling && view !== 'consent') {
const c = button(w, N.cancel)
const hasCancel = await has(c)
await (hasCancel ? c : button(w, N.back)).click()
if (hasCancel) for (let t = 0; t < 100 && !w.landed; t++) await wait(50)
else await wait(150)
continue
}
if (view === 'choose') {
const mine = button(w, N.continueAs(handleOf(plan.acct)))
await ((await has(mine)) ? mine : button(w, N.another)).click()
await wait(150)
continue
}
if (view === 'signIn') {
const id = textbox(w, N.identifier)
// A hinted identifier is read-only, on both sides: the server's is
// held to that, and to the hint, when the view is first
// (spec/OAUTH-PAGES.md, "The authorization page").
if (isServer && hint && w.first === 'signIn' && !w.hintChecked) {
w.hintChecked = true
const got = { value: await id.inputValue(), editable: await id.isEditable() }
if (got.value !== hint || got.editable) await held('the identifier with a login_hint', { value: hint, editable: false }, got)
}
if ((await id.isEditable()) && (await id.inputValue()) !== identifier) await id.fill(identifier)
await textbox(w, N.password).fill(wrongDone ? plan.acct.password : `${plan.acct.password}-wrong`)
await w.page.getByRole('checkbox', { name: N.remember, exact: true }).setChecked(plan.remember)
w.typed = await id.inputValue()
const answered = w.page.waitForResponse((r) => r.url().includes('/~api/sign-in'), { timeout: 15_000 })
if (holdOnce && isServer) await holdOnce(w, () => button(w, N.signIn).click())
else await button(w, N.signIn).click()
const res = await answered
if (res.status() === 200 && plan.remember) w.remembered = true
if (!wrongDone) {
wrongDone = true
if (isServer) {
if (res.status() !== 400) await held('a wrong password\'s answer', 400, res.status())
await checkAlert(w, ALERTS.wrong)
const focused = await textbox(w, N.password).evaluate((el) => el === document.activeElement)
if (!focused) await held('focus after a wrong password', 'the password', await w.page.evaluate(() => document.activeElement?.outerHTML.slice(0, 200) ?? null))
}
} else if (res.status() === 400) {
// The right password refused, as by an email the sign-in does not
// take (spec/OAUTH.md, "The API"): the flow ends there.
if (isServer) await checkAlert(w, ALERTS.wrong)
return 'refused'
}
await wait(150)
continue
}
if (view === 'code') {
const code = plan.codes?.[codeIndex++]
if (code === undefined) return view
if (typeof code === 'function') w.mailed = code(w.side)
await textbox(w, N.code).fill(typeof code === 'function' ? w.mailed : code)
const answered = w.page.waitForResponse((r) => r.url().includes('/~api/sign-in'), { timeout: 15_000 })
await button(w, N.codeSubmit).click()
const res = await answered
if (res.status() === 200 && plan.remember) w.remembered = true
if (res.status() === 400 && isServer) await checkAlert(w, ALERTS.wrongCode)
await wait(150)
continue
}
if (view === 'consent') {
if (!backDone && (await has(button(w, N.back)))) {
backDone = true
await button(w, N.back).click()
await wait(150)
continue
}
backDone = true
const endpoint = plan.end === 'allow' ? 'consent' : 'reject'
const answered = w.page.waitForResponse((r) => r.url().includes(`/~api/${endpoint}`), { timeout: 15_000 })
await button(w, plan.end === 'allow' ? N.allow : N.deny).click()
const res = await answered
// An answer with no `url` (a request the server no longer keeps)
// leaves the page where it is: the flow ends there.
if (res.status() !== 200) {
if (isServer && res.status() === 400) await checkAlert(w, ALERTS.ended)
return 'refused'
}
for (let t = 0; t < 100 && !w.landed; t++) await wait(50)
continue
}
}
return 'stuck'
}
/// The harness's random choices for a flow on `acct`, drawn before either
/// side is driven.
function planFor(acct) {
return {
acct,
by: pick(['handle', 'handle', 'email', 'did']),
remember: chance(0.5),
wrong: chance(0.3),
back: chance(0.2),
end: pick(['allow', 'allow', 'allow', 'deny', 'cancel']),
}
}
const accountsToSignIn = () => accounts.filter((a) => a.password && handleOf(a))
const pageOf = (side, req) => `${issuer(side)}/oauth/authorize?${new URLSearchParams({ client_id: req.clientId, request_uri: req.requestUri[side.name] })}`
/// Both sides' records of `ws` compared; then the server's page held to
/// the spec, the flow counted, and its codes exchanged. Answers where each
/// side landed.
async function settle(kind, acct, req, ws) {
const lands = { reference: await landing(ws.reference, req), server: await landing(ws.server, req) }
const [a, b] = [record(ws.reference, lands.reference), record(ws.server, lands.server)]
if (!isDeepStrictEqual(a, b)) return differ(`pages: ${kind}`, current, { ...a, shown: lands.reference ? undefined : await shown(ws.reference) }, { ...b, shown: lands.server ? undefined : await shown(ws.server) })
await checkWatched(ws.server)
count(`pages: ${kind}`, Boolean(lands.reference?.code))
if (lands.reference?.code && lands.server?.code) await exchange(acct, req, { reference: lands.reference.code, server: lands.server.code }, { kind: `token: code from the pages (${kind})` })
return lands
}
/// Open `req`'s page on each side's device in `devs`, the server's answer
/// held to the spec. Answers the pages by side.
async function openBoth(req, devs) {
const ws = {}
await Promise.all(
sides().map(async (side) => {
const w = await open(devs[side.name], req.redirect)
ws[side.name] = w
const res = await w.page.goto(pageOf(side, req))
if (side === cand) await checkDocument(w, res)
}),
)
return ws
}
const closeAll = async (ws) => {
for (const w of Object.values(ws)) await w.page.close()
}
/// The page clients dealt as a shuffled deck, each once before any again,
/// so that a run of a few dozen flows asks for every one.
const deck = []
function nextClient() {
if (!deck.length) {
deck.push(...PAGE_CLIENTS)
for (let i = deck.length - 1; i > 0; i--) {
const j = below(i + 1)
;[deck[i], deck[j]] = [deck[j], deck[i]]
}
}
return deck.pop()
}
/// A request for `acct` on both sides, with `login_hint` the handle of
/// `hint`, or none; in English, as the pages are, and with no `prompt`:
/// `create` asks for a sign-up the server's pages have not.
async function request(acct, hint) {
return newRequest(acct, { client: nextClient(), whole: chance(0.5), kind: 'PAR (pages)', extra: () => ({ login_hint: hint ? handleOf(hint) : undefined, ui_locales: undefined, prompt: undefined }) })
}
/// The devices kept between flows, up to three, each `{reference, server,
/// remembered}`: a context on each side, and the accounts remembered there.
const pool = []
/// A kept device, or a new one; a new one is a phone, in dark, half the time.
async function poolDevice(fresh) {
if (!fresh && pool.length) return pick(pool)
const phone = chance(0.5)
const d = { reference: await device(ref, phone), server: await device(cand, phone), remembered: new Set() }
if (pool.length === 3) await closeDevice(pool.shift())
pool.push(d)
return d
}
/// A device for one flow alone.
async function loneDevice() {
const phone = chance(0.5)
return { reference: await device(ref, phone), server: await device(cand, phone), remembered: new Set() }
}
async function closeDevice(d) {
for (const s of sides()) await d[s.name].ctx.close()
}
/// Sign in on a new device or a kept one, as the plan draws it, with
/// `login_hint` naming the account, another, or none. The page lets only
/// the hinted account sign in, so a flow with a hint is that account's.
async function signInFlow(hold) {
let acct = pick(accountsToSignIn())
const d = await poolDevice(chance(0.4))
const hintKind = pick([null, null, 'self', 'other'])
const other = pick(accountsToSignIn().filter((a) => a !== acct)) ?? null
const req = await request(acct, hintKind === 'self' ? acct : hintKind === 'other' ? other : null)
if (!req) return
if (hintKind === 'other' && other) acct = other
const plan = planFor(acct)
current = { flow: 'a sign-in', step: run.step, plan: { ...plan, acct: `<account ${acct.n}>` }, remembered: [...d.remembered].map((a) => `<account ${a.n}>`), hint: hintKind && `<account ${acct.n}>`, client: req.clientId, mode: req.mode ?? 'query' }
const ws = await openBoth(req, d)
await Promise.all(sides().map((side) => drive(ws[side.name], plan, { holdOnce: side === cand ? hold : undefined, hint: hintKind ? handleOf(acct) : undefined })))
await settle(d.remembered.size ? 'a sign-in on a device with remembered accounts' : 'a sign-in on a new device', acct, req, ws)
if (ws.reference.remembered) d.remembered.add(acct)
await closeAll(ws)
}
/// The account's email factor on, on a new device: the code view, maybe a
/// wrong code, then the code mailed (spec/OAUTH-PAGES.md, "Email code").
async function factorFlow() {
const acct = pick(accountsToSignIn())
if (!(await setEmailFactor(acct, true))) return
const d = await loneDevice()
const req = await request(acct, null)
if (req) {
let codes
const plan = { ...planFor(acct), wrong: false, back: false, end: 'allow' }
plan.codes = [...(chance(0.5) ? ['AAAAA-AAAAA'] : []), (side) => codes[side.name].at(-1)]
current = { flow: 'the email code', step: run.step, plan: { ...plan, acct: `<account ${acct.n}>`, codes: plan.codes.length }, client: req.clientId }
const ws = await openBoth(req, d)
await Promise.all(sides().map((side) => drive(ws[side.name], plan, { stopAt: 'code' })))
codes = await signInCodes(acct, 'OAuth sign-in on the pages with the email factor on')
await Promise.all(sides().map((side) => drive(ws[side.name], plan)))
await settle('the email code', acct, req, ws)
await closeAll(ws)
}
await closeDevice(d)
await signInCodes(acct, 'the emails after the pages\' email code')
await setEmailFactor(acct, false)
}
/// One request in two tabs of a new device, both loaded first: signed in,
/// remembered, and approved in the first; then, in the second, still
/// showing what it showed before, signed in and approved again.
async function twoTabsFlow() {
const acct = pick(accountsToSignIn())
const plan = { ...planFor(acct), wrong: false, back: false, end: 'allow', remember: true }
const d = await loneDevice()
const req = await request(acct, null)
if (req) {
current = { flow: 'one request in two tabs', step: run.step, plan: { ...plan, acct: `<account ${acct.n}>` }, client: req.clientId }
const first = await openBoth(req, d)
const second = await openBoth(req, d)
await Promise.all(sides().map((side) => drive(first[side.name], plan)))
current.tab = 'first'
await settle('one request in two tabs, the first', acct, req, first)
await Promise.all(sides().map((side) => drive(second[side.name], plan)))
current.tab = 'second'
await settle('one request in two tabs, the second', acct, req, second)
await closeAll(first)
await closeAll(second)
}
await closeDevice(d)
}
/// The error page, on the server: a page with no `request_uri`
/// (spec/OAUTH-PAGES.md, "The error page").
async function errorFlow() {
current = { flow: 'the error page', step: run.step }
const dev = await device(cand, chance(0.5))
const w = await open(dev, 'http://127.0.0.1/callback')
const res = await w.page.goto(`${issuer(cand)}/oauth/authorize?client_id=${encodeURIComponent('http://localhost')}`)
await checkDocument(w, res)
const view = await viewOf(w)
if (view !== 'error') return held('the error page', `an h1 "${SERVER.headings.error}"`, await shown(w))
const data = await w.page.evaluate(() => window.__errorData)
if (!(await has(w.page.getByText(data.error_description, { exact: true })))) await held('the error page\'s description', data.error_description, await shown(w))
const code = await w.page.evaluate(() => [...document.querySelectorAll('main *')].find((e) => e.children.length && /^Error: /.test(e.textContent.trim()))?.innerHTML ?? null)
if (!code || !new RegExp(`^\\s*Error: <code[^>]*>${data.error}</code>\\s*$`).test(code)) await held('the error page\'s code', `Error: <code>${data.error}</code>`, code)
if ((await w.page.getByRole('button').count()) !== 0) await held('the error page\'s buttons', 'none', await w.page.getByRole('button').allInnerTexts())
await checkView(w, 'error')
await checkWatched(w)
count('pages: the error page', true)
await dev.ctx.close()
}
/// Click `name` with the next call to `endpoint` answered `answer` by the
/// harness in place of the server (`abort`: no answer), then hold the alert
/// to `want`. Answers in the order given differ from the one before, so a
/// stale alert never passes for the new one.
async function fake(w, endpoint, name, answer, want) {
await w.page.route(`**/~api/${endpoint}`, (route) => (answer === 'abort' ? route.abort() : route.fulfill({ ...answer, contentType: 'application/json' })), { times: 1 })
const settled = answer === 'abort' ? w.page.waitForEvent('requestfailed') : w.page.waitForResponse((r) => r.url().includes(`/~api/${endpoint}`))
await button(w, name).click()
await settled
current = { ...current, call: endpoint, answer: answer === 'abort' ? 'no answer' : answer.status }
await checkAlert(w, want)
}
/// The server's alerts, for answers the harness gives its page in place of
/// the API's: 429, 500, 507 and none for sign-in; 507, 500 and 400 for
/// consent, after which only Back is enabled. Its first view, on a new
/// device with no hint, is Sign in (spec/OAUTH-PAGES.md, "The authorization
/// page", "Sign in", "Consent").
async function alertsFlow() {
const acct = pick(accountsToSignIn())
const req = await request(acct, null)
if (!req) return
current = { flow: 'the alerts', step: run.step }
const dev = await device(cand, chance(0.5))
const w = await open(dev, req.redirect)
await w.page.goto(pageOf(cand, req))
if ((await viewOf(w)) !== 'signIn') return held('the first view on a new device', 'Sign in', await shown(w))
await textbox(w, SERVER.identifier).fill(handleOf(acct))
await textbox(w, SERVER.password).fill(acct.password)
const secs = pick([1, 60, 61, 600])
await fake(w, 'sign-in', SERVER.signIn, { status: 429, headers: { 'retry-after': String(secs) }, body: '{"error":"invalid_request","error_description":"Too many"}' }, ALERTS.tries(secs))
await fake(w, 'sign-in', SERVER.signIn, { status: 500, body: '{"error":"server_error"}' }, ALERTS.other)
await fake(w, 'sign-in', SERVER.signIn, { status: 507, body: '{"error":"temporarily_unavailable","error_description":"full"}' }, ALERTS.space)
await fake(w, 'sign-in', SERVER.signIn, 'abort', ALERTS.other)
const answered = w.page.waitForResponse((r) => r.url().includes('/~api/sign-in'))
await button(w, SERVER.signIn).click()
await answered
if ((await viewOf(w)) !== 'consent') return held('the view after a sign-in', 'Allow access', await shown(w))
await fake(w, 'consent', SERVER.allow, { status: 507, body: '{"error":"temporarily_unavailable"}' }, ALERTS.space)
await fake(w, 'consent', SERVER.allow, { status: 500, body: '{"error":"server_error"}' }, ALERTS.other)
await fake(w, 'consent', SERVER.allow, { status: 400, body: '{"error":"invalid_request","error_description":"gone"}' }, ALERTS.ended)
const states = await w.page.locator('main button').evaluateAll((bs) => bs.map((b) => [b.getAttribute('aria-label') ?? b.textContent.trim(), b.disabled]))
const wrong = states.filter(([name, disabled]) => (name === SERVER.back ? disabled : !disabled))
if (wrong.length) await held('the buttons after "This sign-in has ended."', `every button but "${SERVER.back}" disabled`, states)
await checkWatched(w)
count('pages: the alerts', true)
await dev.ctx.close()
}
/// The clients whose consent views show spaces, `other` the DID of an
/// account of the server (spec/OAUTH-PAGES.md, "How it is checked"): a
/// bare type merged with one managing it, another's, every space of each
/// authority, one of any owner managed in every way, the set granting
/// spaces, a type with a key, collections of another app and `*`, a DID
/// with no handle, and writes with no collection to write.
function spaceClients(other) {
const W = SPACE_TYPES.workspace
const B = SPACE_TYPES.board
const nobody = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'
return [
`atproto space:${W} space:${W}?manage=create&manage=update space:${B}?authority=${other}&action=read space:*?authority=*&action=read_self space:${B}?authority=*&collection=*&manage=create&manage=update&manage=delete repo:com.example.profile`,
`atproto include:${SETS.forum} space:${B}?action=create&collection=com.example.zz.thing&collection=*&collection=com.example.forum.post space:${W}?skey=main&action=read_self space:*?authority=${nobody}&action=read`,
`atproto space:*?action=create space:*?authority=${other}&manage=delete space:${B}?authority=*&action=update&action=delete space?spaceType=${W}&collection=com.example.zz.thing&action=create&action=read_self transition:generic`,
]
}
/// A consent view asking for `scope`'s spaces, on the server alone, as the
/// reference keeps no `space:` permission: signed in on a new device, its
/// view held to the spec, and no further (spec/OAUTH-PAGES.md, "Consent",
/// "How it is checked").
async function spacesFlow(scope) {
const acct = pick(accountsToSignIn())
const req = await newRequest(acct, { client: { scope, redirects: ['http://127.0.0.1/callback'] }, whole: true, kind: 'PAR (pages, spaces)', extra: () => ({ login_hint: undefined, ui_locales: undefined, prompt: undefined }) })
if (!req) return
current = { flow: 'a consent with spaces', step: run.step, scope }
const dev = await device(cand, chance(0.5))
const w = await open(dev, req.redirect)
await w.page.goto(pageOf(cand, req))
if ((await viewOf(w)) !== 'signIn') return held('the first view on a new device', 'Sign in', await shown(w))
await textbox(w, SERVER.identifier).fill(handleOf(acct))
await textbox(w, SERVER.password).fill(acct.password)
const answered = w.page.waitForResponse((r) => r.url().includes('/~api/sign-in'))
await button(w, SERVER.signIn).click()
await answered
// The view changes once the answer is read; until then it is Sign in still.
await w.page.getByRole('heading', { name: SERVER.headings.consent, exact: true }).waitFor({ timeout: 8000 }).catch(() => {})
if ((await viewOf(w)) !== 'consent') return held('the view after a sign-in', 'Allow access', await shown(w))
await checkView(w, 'consent', { appeared: true, loopback: true })
count('pages: a consent with spaces', true)
await dev.ctx.close()
}
/// A sign-in held on its way, once a run: the button busy, every button
/// disabled, until it is answered (spec/OAUTH-PAGES.md, "Every page").
let busyChecked = false
async function holdOnce(w, click) {
if (busyChecked) return click()
busyChecked = true
let release
const gate = new Promise((ok) => (release = ok))
let reached
const hit = new Promise((ok) => (reached = ok))
await w.page.route('**/~api/sign-in', async (route) => {
reached()
await gate
await route.continue()
}, { times: 1 })
await click()
await hit
const states = await w.page.locator('main button').evaluateAll((bs) => bs.map((b) => ({ name: b.getAttribute('aria-label') ?? b.textContent.trim(), disabled: b.disabled, busy: b.getAttribute('aria-busy') })))
release()
const pressed = states.find((s) => s.name === SERVER.signIn)
if (!pressed || pressed.busy !== 'true' || states.some((s) => !s.disabled)) await held('a sign-in on its way', `"${SERVER.signIn}" aria-busy, every button disabled`, states)
else count('pages: a sign-in held, busy', true)
}
// ------------------------------------------------------------ passkeys
/// The server started again with `PDS_PUBLIC_URL` `http://localhost:<port>`,
/// its issuer from then on: a host a browser takes as an RP ID, where it
/// takes no IP address (spec/PASSKEYS.md, "The relying party").
async function onLocalhost() {
const local = `http://localhost:${new URL(cand.url).port}`
await server.kill()
server.env.PDS_PUBLIC_URL = local
server.start()
await waitReady(server, cand.url)
cand.publicUrl = local
}
/// What the harness's tabs with an authenticator run before a page's own
/// script: the browser's autofill of passkeys, played by the harness. The
/// page's conditional request (`mediation: "conditional"`) is recorded in
/// `window.__harnessConditional`, its challenge as base64url, and held:
/// ended by its `signal`, or, when the harness calls its `answer()` as a
/// person choosing the passkey among the suggestions, passed on to the
/// virtual authenticator without `mediation`. Any other request goes
/// to the browser as it is. Chromium headless offers no autofill of its
/// own, so `isConditionalMediationAvailable()` answers `true` here
/// (spec/OAUTH-PAGES.md, "Sign in", "How it is checked").
function playAutofill() {
const b64u = (b) => {
const u = ArrayBuffer.isView(b) ? new Uint8Array(b.buffer, b.byteOffset, b.byteLength) : new Uint8Array(b)
let s = ''
for (const x of u) s += String.fromCharCode(x)
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
if (!window.PublicKeyCredential || !navigator.credentials) return
const real = navigator.credentials.get.bind(navigator.credentials)
const asked = []
window.__harnessConditional = asked
window.PublicKeyCredential.isConditionalMediationAvailable = async () => true
navigator.credentials.get = (options = {}) => {
if (options.mediation !== 'conditional') return real(options)
const { mediation: _, signal, ...rest } = options
const entry = { challenge: rest.publicKey?.challenge ? b64u(rest.publicKey.challenge) : null, aborted: false, answer: null }
asked.push(entry)
return new Promise((resolve, reject) => {
const abort = () => {
entry.aborted = true
reject(signal.reason ?? new DOMException('The operation was aborted.', 'AbortError'))
}
if (signal?.aborted) return abort()
signal?.addEventListener('abort', abort, { once: true })
entry.answer = () => void real({ ...rest, ...(signal ? { signal } : {}) }).then(resolve, reject)
})
}
}
/// The page's conditional requests, as `playAutofill` records them.
const conditionals = (w) => w.page.evaluate(() => (window.__harnessConditional ?? []).map(({ challenge, aborted }) => ({ challenge, aborted })))
/// A tab of `dev`, watched as `open` watches one, with Chromium's virtual
/// authenticator: CTAP2, internal, with resident keys and user
/// verification, the user present and verified; holding `credentials`
/// (as `WebAuthn.getCredentials` gives them), or none; and the autofill
/// played as `playAutofill` plays it.
async function withAuthenticator(dev, redirect, credentials = []) {
await dev.ctx.addInitScript(playAutofill)
const w = await open(dev, redirect)
const cdp = await dev.ctx.newCDPSession(w.page)
await cdp.send('WebAuthn.enable', { enableUI: false })
const { authenticatorId } = await cdp.send('WebAuthn.addVirtualAuthenticator', { options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true } })
for (const credential of credentials) await cdp.send('WebAuthn.addCredential', { authenticatorId, credential })
w.authenticator = { cdp, authenticatorId }
return w
}
/// The credentials `w`'s authenticator holds.
const credentialsOf = async (w) => (await w.authenticator.cdp.send('WebAuthn.getCredentials', { authenticatorId: w.authenticator.authenticatorId })).credentials
/// The alert the server's page shows, held to `want` within `ms`: the
/// browser may take a while to make or use a passkey, or give up.
async function alertWithin(w, want, ms = 20_000) {
let got = null
for (const until = Date.now() + ms; Date.now() < until; await wait(100)) {
got = await alertText(w, want)
if (got === want) return
}
await held('the alert', want, got)
}
/// The API calls `w` made from its `from`th, each `[endpoint, holds, what]`:
/// the same endpoints in the same order, each body as `holds` says
/// (spec/OAUTH-PAGES.md, "How it is checked").
async function callsHeld(w, from, want, flow) {
const got = w.calls.slice(from)
const fine = got.length === want.length && want.every(([endpoint, holds], i) => got[i].endpoint === endpoint && holds(got[i]))
if (!fine) await held(`the API calls of ${flow}`, want.map(([endpoint, , what]) => `${endpoint} ${what}`), got.map((c) => ({ endpoint: c.endpoint, body: c.body, bearer: c.bearer })))
}
/// The bodies the pages send (spec/OAUTH-PAGES.md, "Sign in", "Add a
/// passkey"; spec/PASSKEYS.md, "passkey-register", "Signing in").
const isCredential = (c, response) => c && typeof c === 'object' && typeof c.id === 'string' && c.rawId === c.id && c.type === 'public-key' && response.every((k) => typeof c.response?.[k] === 'string')
const OPTIONS_CALL = ['passkey-options', (c) => isDeepStrictEqual(c.body, {}), '{}']
const signInCall = (remember) => ['passkey-sign-in', (c) => isDeepStrictEqual(Object.keys(c.body ?? {}).sort(), ['credential', 'locale', 'remember']) && c.body.locale === 'en' && c.body.remember === remember && isCredential(c.body.credential, ['clientDataJSON', 'authenticatorData', 'signature', 'userHandle']), `{locale: "en", credential, remember: ${remember}}`]
const REGISTER_CALL = ['passkey-register', (c) => isDeepStrictEqual(Object.keys(c.body ?? {}), ['credential']) && isCredential(c.body.credential, ['clientDataJSON', 'attestationObject']), '{credential}']
const consentCall = (did, bearer, scope) => ['consent', (c) => isDeepStrictEqual(c.body, { did, scope }) && c.bearer === bearer, `{did, scope: ${JSON.stringify(scope)}}${bearer ? ', with its ephemeral token' : ''}`]
/// The passkey page of `link` in `w`: its document held to the spec, and
/// its first view, Add a passkey (spec/OAUTH-PAGES.md, "The passkey page").
async function passkeyPage(w, link, webauthn = true) {
const res = await w.page.goto(link.url)
await checkDocument(w, res)
if ((await viewOf(w)) !== 'addPasskey') return void (await held('the passkey page\'s first view', SERVER.headings.addPasskey, await shown(w)))
await checkView(w, 'addPasskey', { appeared: webauthn, name: link.name, handle: link.who.handle })
return true
}
/// The sign in view on `w`, on the page of a new request of `client`
/// (`extra` its PAR's other parameters): the page's first view, `Sign in`,
/// held to the spec; as it appears, the autofill's conditional request,
/// one, with `__passkeyOptions`' challenge, calling nothing, or with a
/// `login_hint` none (spec/OAUTH-PAGES.md, "Sign in"; spec/PASSKEYS.md,
/// "The page's options"); `Remember this account on this device` as
/// `remember` says. Answers the request, its `__authorizeData.scope`, which
/// Allow sends (spec/OAUTH-PAGES.md, "Consent"), and the index of its first
/// call in `w.calls`; or null.
async function passkeySignInView(w, client, remember, extra = {}) {
const req = await serverRequest(client, extra)
if (!req) return null
const from = w.calls.length
// A tab reused from a flow that landed at the client lands again only by this one.
w.landed = null
w.location = null
// The tab's last landing at the client, whose redirect URI nothing serves,
// may still be on its way to the browser's error page.
const res = await w.page.goto(req.page).catch(async (e) => {
if (!/interrupted by another navigation/.test(String(e))) throw e
await w.page.waitForLoadState().catch(() => {})
return w.page.goto(req.page)
})
await checkDocument(w, res)
if ((await viewOf(w)) !== 'signIn') return void (await held('the first view on a device with no account', SERVER.headings.signIn, await shown(w)))
await checkView(w, 'signIn', { first: true, appeared: true })
const hinted = extra.login_hint !== undefined
let asked = []
for (let t = 0; t < (hinted ? 5 : 50) && (hinted || !asked.length); t++) {
await wait(100)
asked = await conditionals(w)
}
const challenge = await w.page.evaluate(() => window.__passkeyOptions?.challenge ?? null)
const want = hinted ? [] : [{ challenge, aborted: false }]
if (!isDeepStrictEqual(asked, want) || (!hinted && !challenge)) await held(`the autofill's request as the sign in view appears${hinted ? ', with a login_hint' : ''}`, hinted ? 'none' : { mediation: 'conditional', challenge: `__passkeyOptions' challenge, ${challenge}` }, asked)
if (w.calls.length !== from) await held('the API calls as the sign in view appears', 'none', w.calls.slice(from).map((c) => c.endpoint))
const scope = await w.page.evaluate(() => window.__authorizeData?.scope)
await w.page.getByRole('checkbox', { name: SERVER.remember, exact: true }).setChecked(remember)
return { req, scope, from, hinted }
}
/// A sign-in with a passkey on `w`, its sign in view as
/// `passkeySignInView` holds it, `Sign in with a passkey` pressed: the
/// autofill's request then ended (spec/OAUTH-PAGES.md, "Sign in"). Answers
/// what that does, and, with `answered`, the answer to its
/// `passkey-sign-in` to come; or null.
async function passkeyPress(w, client, remember, extra = {}, answered = true) {
const view = await passkeySignInView(w, client, remember, extra)
if (!view) return null
const signIn = answered ? w.page.waitForResponse((x) => x.url().includes('/~api/passkey-sign-in'), { timeout: 20_000 }) : null
await button(w, SERVER.passkey).click()
if (!view.hinted) {
let asked = []
for (let t = 0; t < 50 && !asked[0]?.aborted; t++) {
asked = await conditionals(w)
if (!asked[0]?.aborted) await wait(100)
}
if (asked.length !== 1 || !asked[0].aborted) await held(`the autofill's request once "${SERVER.passkey}" is pressed`, 'ended, by its signal', asked)
}
return { ...view, signIn }
}
/// The autofill on `w`: the passkey chosen among the identifier field's
/// suggestions, the harness handing the page's conditional request to the
/// virtual authenticator; `passkey-sign-in` with `remember` as the checkbox
/// is, then Consent, with no call before `passkey-sign-in`
/// (spec/OAUTH-PAGES.md, "Sign in", "How it is checked").
async function autofillFlow(w, client, who, remember, flow) {
const view = await passkeySignInView(w, client, remember)
if (!view) return null
const answered = w.page.waitForResponse((x) => x.url().includes('/~api/passkey-sign-in'), { timeout: 20_000 })
await w.page.evaluate(() => window.__harnessConditional[0].answer())
const r = await answered
if (r.status() !== 200) return void (await held(`passkey-sign-in from the autofill, ${flow}`, 200, { status: r.status(), body: await r.text() }))
if (!(await passkeyConsent(w, who, view.req, flow))) return null
await callsHeld(w, view.from, [signInCall(remember), consentCall(who.did, !remember, view.scope)], flow)
return true
}
/// After a passkey sign-in answered `200`: Consent, Allow, the client's
/// redirect URI with the issuer, the request's state and a code, and the
/// code exchanged (spec/OAUTH-PAGES.md, "How it is checked").
async function passkeyConsent(w, who, req, flow) {
if ((await viewOf(w)) !== 'consent') return void (await held(`the view after ${flow}`, SERVER.headings.consent, await shown(w)))
await checkView(w, 'consent', { appeared: true, loopback: true })
await button(w, SERVER.allow).click()
for (let t = 0; t < 100 && !w.landed; t++) await wait(50)
const u = w.landed ? new URL(w.landed.url) : null
const got = { landed: Boolean(u), iss: u?.searchParams.get('iss') ?? null, state: u?.searchParams.get('state') === req.state, code: Boolean(u?.searchParams.get('code')) }
const want = { landed: true, iss: issuer(cand), state: true, code: true }
if (!isDeepStrictEqual(got, want)) return void (await held(`where ${flow} lands`, want, { ...got, error: u?.searchParams.get('error') ?? null, shown: u ? undefined : await shown(w) }))
return redeem(req, u.searchParams.get('code'))
}
/// The passkey flows, on the server alone, on a server whose
/// `PDS_PUBLIC_URL` is `http://localhost:<port>`, in Chromium with its
/// virtual authenticator (spec/OAUTH-PAGES.md, "How it is checked"): a
/// passkey added through a link, as `_passkeyAdd` makes it, Add a passkey
/// then Passkey added, after the alerts of answers the harness gives in
/// place of the server's; the link loaded again, the error page; a second
/// link in the same browser, its `InvalidStateError` alert, no call sent;
/// a link ended by a newer one, its `access_denied` alert, `Add passkey`
/// disabled; a browser without WebAuthn, its alert, and no `Sign in with a
/// passkey`. Then signing in with the passkey, not remembered and
/// remembered, through Consent to the client's redirect URI, and the code
/// exchanged, `Sign in with a passkey` pressed while the autofill asks and
/// its asking ended; with the email factor on, with no Email code and
/// nothing mailed; the alerts of `passkey-sign-in` answers the harness
/// gives; `login_hint` naming another account, its alert, and no autofill;
/// the autofill, the passkey chosen among the suggestions, not remembered
/// and remembered, through Consent with no call before `passkey-sign-in`;
/// and an authenticator that holds none, its alert, no `passkey-sign-in`
/// sent. On each, the sign in view calls nothing as it appears, and its
/// autofill asks with `__passkeyOptions`. Each held to the API calls it
/// made, and to "Held to this page, the server alone" (spec/OAUTH-PAGES.md,
/// "The passkey page", "Add a passkey", "Passkey added", "Sign in";
/// spec/PASSKEYS.md, "The relying party", "The page's options").
async function passkeyFlows() {
if (!passkeysAble()) return 0
await onLocalhost()
const acct = await createAccount({ withPassword: true })
const other = acct && (await createAccount({ withPassword: true }))
if (!other) return 0
const who = whoOf(acct, { bare: true })
const handle = who.handle
const client = newClient()
const contexts = []
const tab = async (credentials, init) => {
const dev = await device(cand, chance(0.5))
contexts.push(dev.ctx)
if (init) await dev.ctx.addInitScript(init)
return init ? open(dev, client.redirect) : withAuthenticator(dev, client.redirect, credentials)
}
// The alerts of passkey-register's answers, given by the harness, in a
// browser of their own.
current = { flow: 'a passkey page\'s alerts', step: run.step }
const first = await addLink(who)
const wf = first && (await tab([]))
if (!wf || !(await passkeyPage(wf, first))) return 0
await fake(wf, 'passkey-register', SERVER.addPasskey, { status: 400, body: '{"error":"invalid_request","error_description":"no"}' }, ALERTS.notAdded)
await fake(wf, 'passkey-register', SERVER.addPasskey, { status: 507, body: '{"error":"temporarily_unavailable","error_description":"full"}' }, ALERTS.space)
await fake(wf, 'passkey-register', SERVER.addPasskey, { status: 500, body: '{"error":"server_error"}' }, ALERTS.other)
await fake(wf, 'passkey-register', SERVER.addPasskey, 'abort', ALERTS.other)
await checkWatched(wf)
// Added through a link: Add a passkey, then Passkey added.
current = { flow: 'a passkey added through a link', step: run.step }
const link = await addLink(who)
const w = link && (await tab([]))
if (!w || !(await passkeyPage(w, link))) return 0
const from = w.calls.length
const answered = w.page.waitForResponse((r) => r.url().includes('/~api/passkey-register'), { timeout: 20_000 })
await button(w, SERVER.addPasskey).click()
const added = await answered
if (added.status() !== 200) return void (await held('passkey-register from the passkey page', 200, { status: added.status(), body: await added.text() }))
if ((await viewOf(w)) !== 'added') return void (await held('the view after a passkey is added', SERVER.headings.added, await shown(w)))
await checkView(w, 'added', { appeared: true, handle })
await callsHeld(w, from, [REGISTER_CALL], 'adding a passkey')
const listed = await passkeysOf(who)
if (listed?.length !== 1 || listed[0].name !== link.name) await held('_passkeyList after the passkey page added one (spec/PASSKEYS.md, "_passkeyList")', [{ name: link.name }], listed)
const credentials = await credentialsOf(w)
// The tab whose authenticator signed in last, whose credential, with its
// signature counter, each new tab is given: an older copy's counter would
// be one the server refuses (spec/PASSKEYS.md, "passkey-sign-in").
let source = w
if (credentials.length !== 1 || Buffer.from(credentials[0].credentialId, 'base64').toString('base64url') !== listed?.[0]?.id) await held('the passkey the browser made (spec/PASSKEYS.md, "passkey-register")', `listed as ${listed?.[0]?.id}`, credentials.map((c) => c.credentialId))
await checkWatched(w)
count('pages: a passkey added', true)
// The link loaded again: the error page.
current = { flow: 'a passkey link loaded again', step: run.step }
const again = await w.page.goto(link.url)
const errorData = (await viewOf(w)) === 'error' ? await w.page.evaluate(() => window.__errorData) : null
if (again.status() !== 400 || errorData?.error !== 'invalid_request') await held('the passkey page of a link that added a passkey', { status: 400, view: 'the error page', error: 'invalid_request' }, { status: again.status(), error: errorData?.error ?? null, shown: await shown(w) })
await checkView(w, 'error')
// A second link in the same browser: InvalidStateError, no call sent.
current = { flow: 'a second passkey link in the same browser', step: run.step }
const second = await addLink(who)
if (!second || !(await passkeyPage(w, second))) return 0
const from2 = w.calls.length
await button(w, SERVER.addPasskey).click()
await alertWithin(w, ALERTS.hasPasskey(handle))
await callsHeld(w, from2, [], 'a second link in the same browser')
await checkWatched(w)
// A link ended by a newer one: access_denied, `Add passkey` then
// disabled.
current = { flow: 'a passkey link ended by a newer one', step: run.step }
const third = await addLink(who)
const wb = third && (await tab([]))
if (!wb || !(await passkeyPage(wb, third)) || !(await addLink(who))) return 0
const ended = wb.page.waitForResponse((r) => r.url().includes('/~api/passkey-register'), { timeout: 20_000 })
await button(wb, SERVER.addPasskey).click()
const refused = await ended
if (refused.status() !== 400) await held('passkey-register through a link ended by a newer one', '400 access_denied', { status: refused.status(), body: await refused.text() })
await alertWithin(wb, ALERTS.linkEnded)
if (!(await button(wb, SERVER.addPasskey).isDisabled())) await held('Add passkey after "This link has ended."', 'disabled', 'enabled')
await checkWatched(wb)
// A browser without WebAuthn: its alert, `Add passkey` disabled, and no
// `Sign in with a passkey`.
current = { flow: 'a browser without WebAuthn', step: run.step }
const fourth = await addLink(who)
const wn = fourth && (await tab(null, () => delete window.PublicKeyCredential))
if (!wn || !(await passkeyPage(wn, fourth, false))) return 0
await alertWithin(wn, ALERTS.noWebAuthn, 3000)
if (!(await button(wn, SERVER.addPasskey).isDisabled())) await held('Add passkey in a browser without WebAuthn', 'disabled', 'enabled')
const plain = await serverRequest(client)
if (!plain) return 0
await checkDocument(wn, await wn.page.goto(plain.page))
if ((await viewOf(wn)) !== 'signIn') return void (await held('the first view on a device with no account', SERVER.headings.signIn, await shown(wn)))
await checkView(wn, 'signIn', { first: true, appeared: true, webauthn: false })
await checkWatched(wn)
count('pages: the passkey page', true)
// Signing in with the passkey, not remembered then remembered, through
// Consent, the code exchanged.
for (const remember of [false, true]) {
current = { flow: `a sign-in with a passkey, ${remember ? '' : 'not '}remembered`, step: run.step }
const pressed = await passkeyPress(w, client, remember)
if (!pressed) return 0
const r = await pressed.signIn
if (r.status() !== 200) return void (await held('passkey-sign-in from the authorization page', 200, { status: r.status(), body: await r.text() }))
if (!(await passkeyConsent(w, who, pressed.req, current.flow))) return 0
await callsHeld(w, pressed.from, [OPTIONS_CALL, signInCall(remember), consentCall(who.did, !remember, pressed.scope)], current.flow)
await checkWatched(w)
count(`pages: a sign-in with a passkey${remember ? ', remembered' : ''}`, true)
}
// The email factor on: no Email code, nothing mailed.
current = { flow: 'a sign-in with a passkey, the email factor on', step: run.step }
if (await setEmailFactor(acct, true)) {
await checkMail('the emails before a passkey sign-in on the pages', { flow: current.flow })
const we = await tab(await credentialsOf(source))
const remember = chance(0.5)
const pressed = await passkeyPress(we, client, remember)
if (!pressed) return 0
const r = await pressed.signIn
if (r.status() !== 200) return void (await held('passkey-sign-in with the email factor on', 200, { status: r.status(), body: await r.text() }))
if (!(await passkeyConsent(we, who, pressed.req, current.flow))) return 0
await callsHeld(we, pressed.from, [OPTIONS_CALL, signInCall(remember), consentCall(who.did, !remember, pressed.scope)], current.flow)
const sent = await checkMail('a passkey sign-in on the pages with the email factor on', { flow: current.flow })
if (sent.server.length) await held('the emails of a passkey sign-in with the email factor on (spec/PASSKEYS.md, "passkey-sign-in")', 'none', sent.server)
await checkWatched(we)
source = we
await setEmailFactor(acct, false)
count('pages: a sign-in with a passkey, the email factor on', true)
}
// The alerts of passkey-sign-in's answers, given by the harness.
current = { flow: 'the passkey sign-in\'s alerts', step: run.step }
const wa = await tab(await credentialsOf(source))
const page = await serverRequest(client)
if (!page) return 0
await checkDocument(wa, await wa.page.goto(page.page))
if ((await viewOf(wa)) !== 'signIn') return void (await held('the first view on a device with no account', SERVER.headings.signIn, await shown(wa)))
await fake(wa, 'passkey-sign-in', SERVER.passkey, { status: 400, body: '{"error":"invalid_request","error_description":"no"}' }, ALERTS.passkeyRefused)
await fake(wa, 'passkey-sign-in', SERVER.passkey, { status: 507, body: '{"error":"temporarily_unavailable","error_description":"full"}' }, ALERTS.space)
await fake(wa, 'passkey-sign-in', SERVER.passkey, { status: 500, body: '{"error":"server_error"}' }, ALERTS.other)
await checkWatched(wa)
// login_hint naming another account than the passkey's: its alert.
current = { flow: 'a passkey of another account than login_hint\'s', step: run.step }
const wh = await tab(await credentialsOf(source))
const hinted = await passkeyPress(wh, client, false, { login_hint: other.handle })
if (!hinted) return 0
const hr = await hinted.signIn
if (hr.status() !== 200) await held('passkey-sign-in with a login_hint of another account', 200, { status: hr.status(), body: await hr.text() })
await alertWithin(wh, ALERTS.otherAccount)
await callsHeld(wh, hinted.from, [OPTIONS_CALL, signInCall(false)], current.flow)
await checkWatched(wh)
source = wh
// The autofill, not remembered then remembered: the passkey chosen among
// the identifier field's suggestions, through Consent, with no call
// before passkey-sign-in (spec/OAUTH-PAGES.md, "Sign in").
for (const remember of [false, true]) {
current = { flow: `a passkey sign-in from the autofill, ${remember ? '' : 'not '}remembered`, step: run.step }
const wt = await tab(await credentialsOf(source))
if (!(await autofillFlow(wt, client, who, remember, current.flow))) return 0
await checkWatched(wt)
source = wt
count(`pages: a passkey sign-in from the autofill${remember ? ', remembered' : ''}`, true)
}
// An authenticator that holds none: its alert, no passkey-sign-in sent.
current = { flow: 'a passkey sign-in, the browser giving no credential', step: run.step }
const wz = await tab([])
const none = await passkeyPress(wz, client, chance(0.5), {}, false)
if (!none) return 0
await alertWithin(wz, ALERTS.noPasskey, 60_000)
await callsHeld(wz, none.from, [OPTIONS_CALL], current.flow)
await checkWatched(wz)
count('pages: passkey sign-in alerts', true)
for (const ctx of contexts) await ctx.close()
return 11
}
/// The run: the error page and the alerts, then PAGES_STEPS flows, then
/// every device closed; then, on the server alone, its passkey flows.
/// Answers how many flows.
export async function pagesRun() {
browser = await chromium.launch()
await errorFlow()
await alertsFlow()
const other = accountsToSignIn()[0]
if (other) for (const scope of spaceClients(didOf(cand, other))) await spacesFlow(scope)
for (run.step = 1; run.step <= PAGES_STEPS; run.step++) {
const r = below(100)
if (r < 60) await signInFlow(holdOnce)
else if (r < 75) await factorFlow()
else if (r < 88) await twoTabsFlow()
else if (r < 94) await errorFlow()
else await alertsFlow()
if (run.step % 10 === 0) console.error(`${run.step} page flows agree`)
}
if (!busyChecked) await signInFlow(holdOnce)
await checkAssetMetrics()
for (const d of pool) await closeDevice(d)
const passkeys = await passkeyFlows()
await browser.close()
return PAGES_STEPS + passkeys
}