~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
289 lines · 11.2 KB Raw History
// Sign-in for the dev host, as an MCP client signs in to HUD (MCP's
// authorization spec): read the protected resource metadata for /mcp, then
// the authorization server's; register by dynamic client registration (a
// localhost page can have no client ID metadata document); open the
// authorization endpoint in a popup with PKCE (S256), `state` and
// `resource`; take the code the callback page (callback.html) broadcasts;
// exchange it for tokens, kept in sessionStorage; refresh them (rotating)
// when they lapse or the server calls them invalid; revoke them on sign
// out.
//
// The dev host reaches HUD only through Vite's proxy, so discovery and the
// token, registration and revocation endpoints are fetched at their paths
// on this origin (no CORS needed); the popup goes to the authorization
// endpoint as the server publishes it (HUD_PUBLIC_URL's), where the
// account's PDS sends the browser back.

/** What a signed-in dev host keeps: the server it signed in to, its
 * registration, and the tokens. */
export type Session = {
	issuer: string;
	resource: string;
	clientId: string;
	redirectUri: string;
	tokenEndpoint: string;
	revocationEndpoint: string | null;
	access: string;
	refresh: string | null;
	/** When the access token lapses, in ms since the epoch. */
	expiresAt: number;
	/** The account's DID, as the token response's `sub` names it. */
	sub: string | null;
};

/** A `WWW-Authenticate: Bearer` challenge's parameters. */
export type Challenge = { error: string | null; resourceMetadata: string | null; scope: string | null };

/** Server metadata, as far as the dev host reads it. */
type Resource = { resource: string; authorization_servers: string[] };
type Server = {
	issuer: string;
	authorization_endpoint: string;
	token_endpoint: string;
	registration_endpoint?: string;
	revocation_endpoint?: string;
	authorization_response_iss_parameter_supported?: boolean;
};
type Tokens = { access_token: string; token_type: string; refresh_token?: string; expires_in?: number; sub?: string };
/** What callback.html broadcasts: the authorization response's parameters. */
type Callback = { type: 'hud-dev-oauth'; params: Record<string, string> };

const SESSION = 'hud-dev-oauth';
const CLIENTS = 'hud-dev-oauth-clients';
/** The channel callback.html answers on: a popup the PDS's pages opened
 * with Cross-Origin-Opener-Policy has lost its `opener`, but not its origin. */
export const CHANNEL = 'hud-dev-oauth';

/** The path (and query) of a URL, fetched on this origin through the proxy. */
const local = (url: string) => {
	const parsed = new URL(url);
	return parsed.pathname + parsed.search;
};

const b64url = (bytes: ArrayBuffer | Uint8Array) =>
	btoa(String.fromCharCode(...new Uint8Array(bytes)))
		.replaceAll('+', '-')
		.replaceAll('/', '_')
		.replace(/=+$/, '');

const random = () => b64url(crypto.getRandomValues(new Uint8Array(32)));

export function session(): Session | null {
	const stored = sessionStorage.getItem(SESSION);
	return stored ? (JSON.parse(stored) as Session) : null;
}

function keep(next: Session | null) {
	if (next) sessionStorage.setItem(SESSION, JSON.stringify(next));
	else sessionStorage.removeItem(SESSION);
}

/** The parameters of a `WWW-Authenticate` Bearer challenge, or null when the
 * response has none. */
export function challenge(response: Response): Challenge | null {
	const header = response.headers.get('www-authenticate');
	if (!header || !/^bearer\b/i.test(header)) return null;
	const params: Record<string, string> = {};
	for (const [, key, quoted, bare] of header.matchAll(/([a-z_]+)=(?:"((?:[^"\\]|\\.)*)"|([^\s,]+))/gi)) {
		params[key.toLowerCase()] = quoted !== undefined ? quoted.replace(/\\(.)/g, '$1') : bare;
	}
	return { error: params.error ?? null, resourceMetadata: params.resource_metadata ?? null, scope: params.scope ?? null };
}

async function json<T>(response: Response, what: string): Promise<T> {
	const body = await response.text();
	if (!response.ok) throw new Error(`${what}: HTTP ${response.status} ${body}`);
	return JSON.parse(body) as T;
}

/** The protected resource metadata for /mcp and its authorization server's
 * metadata (RFC 9728, RFC 8414), checked as a client must. */
async function discover(): Promise<{ resource: Resource; server: Server }> {
	const found = await fetch('/.well-known/oauth-protected-resource/mcp');
	if (found.status === 404) throw new Error('This hud server has no sign-in: OAuth is off (HUD_OAUTH, on by default with an https HUD_PUBLIC_URL).');
	const resource = await json<Resource>(found, 'Protected resource metadata');
	const issuer = resource.authorization_servers?.[0];
	if (typeof resource.resource !== 'string' || typeof issuer !== 'string') throw new Error('The protected resource metadata names no resource or authorization server.');
	const url = new URL(issuer);
	const path = url.pathname === '/' ? '' : url.pathname;
	const server = await json<Server>(await fetch(`/.well-known/oauth-authorization-server${path}`), 'Authorization server metadata');
	if (server.issuer !== issuer) throw new Error(`The authorization server calls itself ${server.issuer}, not ${issuer}.`);
	return { resource, server };
}

/** This dev host's client ID at an authorization server, registered once
 * (RFC 7591) and remembered for the tab. */
async function register(server: Server, redirectUri: string): Promise<string> {
	const clients = JSON.parse(sessionStorage.getItem(CLIENTS) ?? '{}') as Record<string, string>;
	const key = `${server.issuer} ${redirectUri}`;
	if (clients[key]) return clients[key];
	if (!server.registration_endpoint) throw new Error('The authorization server offers no dynamic client registration.');
	const registered = await json<{ client_id: string }>(
		await fetch(local(server.registration_endpoint), {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({
				client_name: 'HUD dev host',
				redirect_uris: [redirectUri],
				grant_types: ['authorization_code', 'refresh_token'],
				response_types: ['code'],
				token_endpoint_auth_method: 'none',
				scope: 'hud'
			})
		}),
		'Registration'
	);
	clients[key] = registered.client_id;
	sessionStorage.setItem(CLIENTS, JSON.stringify(clients));
	return registered.client_id;
}

/** A token request to the token endpoint, form-encoded. */
async function token(endpoint: string, form: Record<string, string>): Promise<Tokens> {
	const tokens = await json<Tokens>(
		await fetch(local(endpoint), {
			method: 'POST',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body: new URLSearchParams(form)
		}),
		'Token request'
	);
	if (typeof tokens.access_token !== 'string' || tokens.token_type?.toLowerCase() !== 'bearer') throw new Error('The token response holds no Bearer access token.');
	return tokens;
}

const expiry = (tokens: Tokens) => Date.now() + (tokens.expires_in ?? 3600) * 1000;

/** The authorization request on its way: one at a time. */
let pending: { state: string; reject: (error: Error) => void } | null = null;

/** Sign in: discover, register, authorize in `popup` (opened by the caller
 * on the click, so no blocker stops it), exchange the code. */
export async function signIn(popup: Window): Promise<Session> {
	pending?.reject(new Error('Sign-in started again.'));
	pending = null;
	try {
		const { resource, server } = await discover();
		const redirectUri = `${location.origin}/dev/callback.html`;
		const clientId = await register(server, redirectUri);
		const verifier = random();
		const challengeValue = b64url(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)));
		const state = random();
		const authorize = new URL(server.authorization_endpoint);
		for (const [key, value] of Object.entries({
			response_type: 'code',
			client_id: clientId,
			redirect_uri: redirectUri,
			code_challenge: challengeValue,
			code_challenge_method: 'S256',
			state,
			resource: resource.resource,
			scope: 'hud'
		})) {
			authorize.searchParams.set(key, value);
		}
		const answered = Promise.withResolvers<Record<string, string>>();
		const channel = new BroadcastChannel(CHANNEL);
		const done = () => {
			channel.close();
			if (pending?.state === state) pending = null;
		};
		pending = {
			state,
			reject: (error) => {
				done();
				answered.reject(error);
			}
		};
		channel.onmessage = ({ data }: MessageEvent<Callback>) => {
			if (data?.type !== 'hud-dev-oauth' || data.params.state !== state) return;
			done();
			answered.resolve(data.params);
		};
		popup.location.href = authorize.href;
		const params = await answered.promise;
		if (params.error) throw new Error(`Sign-in refused: ${params.error}${params.error_description ? ` (${params.error_description})` : ''}`);
		if (server.authorization_response_iss_parameter_supported && params.iss !== server.issuer) throw new Error(`The answer came from ${params.iss ?? 'no issuer'}, not ${server.issuer}.`);
		if (!params.code) throw new Error('The answer holds no code.');
		const tokens = await token(server.token_endpoint, {
			grant_type: 'authorization_code',
			code: params.code,
			redirect_uri: redirectUri,
			client_id: clientId,
			code_verifier: verifier,
			resource: resource.resource
		});
		const signed: Session = {
			issuer: server.issuer,
			resource: resource.resource,
			clientId,
			redirectUri,
			tokenEndpoint: server.token_endpoint,
			revocationEndpoint: server.revocation_endpoint ?? null,
			access: tokens.access_token,
			refresh: tokens.refresh_token ?? null,
			expiresAt: expiry(tokens),
			sub: tokens.sub ?? null
		};
		keep(signed);
		return signed;
	} finally {
		if (!popup.closed) popup.close();
	}
}

/** Stop waiting for the sign-in under way. */
export function cancelSignIn() {
	pending?.reject(new Error('Sign-in cancelled.'));
}

let refreshing: Promise<boolean> | null = null;

/** Trade the refresh token for new tokens, one exchange at a time. False,
 * and signed out, when there is none or the server refuses it. */
export function refresh(): Promise<boolean> {
	refreshing ??= (async () => {
		const current = session();
		if (!current?.refresh) {
			keep(null);
			return false;
		}
		try {
			const tokens = await token(current.tokenEndpoint, {
				grant_type: 'refresh_token',
				refresh_token: current.refresh,
				client_id: current.clientId,
				resource: current.resource
			});
			keep({ ...current, access: tokens.access_token, refresh: tokens.refresh_token ?? current.refresh, expiresAt: expiry(tokens), sub: tokens.sub ?? current.sub });
			return true;
		} catch {
			keep(null);
			return false;
		}
	})().finally(() => (refreshing = null));
	return refreshing;
}

/** The access token to send, refreshed first when it has lapsed; null when
 * signed out. */
export async function bearer(): Promise<string | null> {
	const current = session();
	if (!current) return null;
	if (Date.now() < current.expiresAt - 30_000) return current.access;
	return (await refresh()) ? (session()?.access ?? null) : null;
}

/** Sign out: revoke the refresh token (which ends the session at HUD) and
 * forget the tokens. */
export async function signOut() {
	const current = session();
	keep(null);
	if (!current?.revocationEndpoint) return;
	const revoke = current.refresh ?? current.access;
	await fetch(local(current.revocationEndpoint), {
		method: 'POST',
		headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
		body: new URLSearchParams({ token: revoke, client_id: current.clientId })
	}).catch(() => undefined);
}