~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
85 lines · 3.9 KB Raw History
// The web OAuth clients publish their documents on (spec/OAUTH-CLIENTS.md):
// one local HTTP server standing for every https origin in ORIGINS, which
// both sides fetch client metadata documents and JWKS from.
//
// The server is told of it with PDS_OAUTH_CLIENT_FETCH, which maps each of
// those origins to a URL here. The reference runs in this process, and
// fetches through globalThis.fetch, so a URL on one of those hosts is sent
// here instead. Each side's requests come to their own path prefix,
// `/<side>/<host>`, so the harness knows who fetched what.

import http from 'node:http'

/// The hosts of the clients the harness makes: under a public suffix, so
/// that both sides take them as discoverable clients (spec/OAUTH-CLIENTS.md).
/// The last stands for Claude's, whose documents an MCP client signs in
/// with (spec/OAUTH-MCP.md).
export const HOSTS = ['app.pds-harness.net', 'other.pds-harness.net', 'claude.pds-harness.net']
export const ORIGINS = HOSTS.map((h) => `https://${h}`)

/// What each path serves, by `host + path` (the query is not part of it):
/// a function answering `{status, headers, body}`, `body` a string.
const routes = new Map()
/// Every request each side made, in order: `{host, path, query, method, accept}`.
export const fetchLog = { reference: [], server: [] }
let base = null

/// Serve `url` (https, one of ORIGINS, any query ignored): `doc` a JSON
/// value served as `200 application/json`, or a function answering
/// `{status, headers, body}`.
export function serve(url, doc) {
  const u = new URL(url)
  routes.set(u.host + u.pathname, typeof doc === 'function' ? doc : () => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify(doc) }))
}

/// How many times `side` fetched `url` (its query ignored).
export function fetchCount(side, url) {
  const u = new URL(url)
  return fetchLog[side.name].filter((f) => f.host === u.host && f.path === u.pathname).length
}

/// Age everything the reference keeps by `performance.now()` by `ms`: its
/// kept client documents and JWKS (spec/OAUTH-CLIENTS.md, 10 minutes), which
/// it keeps in this process. The server's are untouched.
let clockOffset = 0
const realNow = performance.now.bind(performance)
export async function ageReferenceCaches(ms) {
  clockOffset += ms
  performance.now = () => realNow() + clockOffset
  // lru-cache reads the clock at most once per millisecond.
  await new Promise((ok) => setTimeout(ok, 20))
}

/// Start the web; answers the server's PDS_OAUTH_CLIENT_FETCH
/// (spec/OAUTH-CLIENTS.md, "The development fetch").
export async function startClientWeb() {
  const srv = http.createServer((req, res) => {
    const u = new URL(req.url, 'http://x')
    const [, side, host, ...rest] = u.pathname.split('/')
    const path = `/${rest.join('/')}`
    if (fetchLog[side]) fetchLog[side].push({ host, path, query: u.search, method: req.method, accept: req.headers.accept ?? null })
    const route = routes.get(host + path)
    const a = route ? route() : { status: 404, headers: { 'content-type': 'text/plain' }, body: 'not found' }
    res.writeHead(a.status, a.headers ?? {})
    res.end(a.body ?? '')
  })
  await new Promise((ok) => srv.listen(0, '127.0.0.1', ok))
  srv.unref()
  base = `http://127.0.0.1:${srv.address().port}`
  const realFetch = globalThis.fetch
  globalThis.fetch = async (input, init) => {
    const req = input instanceof Request ? input : null
    const url = new URL(req ? req.url : String(input))
    if (url.protocol === 'https:' && HOSTS.includes(url.hostname)) {
      const to = `${base}/reference/${url.host}${url.pathname}${url.search}`
      return realFetch(to, {
        method: init?.method ?? req?.method ?? 'GET',
        headers: init?.headers ?? req?.headers,
        redirect: init?.redirect ?? req?.redirect ?? 'follow',
        signal: init?.signal ?? req?.signal,
      })
    }
    return realFetch(input, init)
  }
  return ORIGINS.map((o) => `${o}=${base}/server/${new URL(o).host}`).join(',')
}