chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.3.1 Latest 5 packages
0
0
// Sign-in, as an MCP client signs in to HUD (MCP's authorization spec),
// done by an app's server for the browser (a backend for frontend): the
// browser is sent to HUD's authorization endpoint and back to the app's
// callback, and only the server ever holds the tokens (session.ts).
//
// HUD's metadata names its endpoints at its public origin; the server
// reaches them at its own way to HUD (`hud`), by the same paths. The client
// is named by its client ID metadata document (`clientMetadata`, which the
// app serves) where the app is at a public https origin, as HUD fetches one
// only from there, and else (a server on localhost) registered by dynamic
// client registration, once per run of the server. PKCE (S256), `state`
// and `resource` as the spec asks; the refresh grant rotates, and as HUD
// ends a session whose replaced refresh token is used again, a refresh is
// made once per token: requests that come with the same one meanwhile, or
// soon after (their cookie sent before the new one came), share its answer.
// Every token answer names its account (`sub`, a DID), which keys the
// browser's accounts (accounts.ts).
import { backPath, wentOn } from './back';
import { random, toBase64url } from './seal';
/** Where an app's server signs its pages in at HUD. */
export type SignInConfig = {
/** HUD as the server reaches it (`http://hud:8787`). */
hud: string;
/** The app's public origin (`https://next.grain.social`), which HUD sends the browser back to. */
origin: string;
/** The app's name on HUD's sign-in page. */
name: string;
/** Its path, where HUD sends the browser back (`/auth/callback`). */
callback: string;
/** Its logo's path on its origin, for its client metadata (`/icon-512.png`). */
logo?: string;
};
/** HUD's tokens for one account, as the session cookie keeps them. */
export type Session = {
/** The account, as HUD's token answer names it; null in a cookie from before it was kept, until its next refresh. */
did: string | null;
access: string;
refresh: string | null;
/** When the access token lapses, in ms since the epoch. */
expiresAt: number;
clientId: string;
};
/** What waits across the redirect, sealed in the sign-in cookie: the request's own, where it comes back to (`back`), and the screen it started from (`from`, its path) with the handle typed there, which a refusal goes back to. */
export type Pending = { state: string; verifier: string; clientId: string; back: string; from?: string; handle?: string };
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 };
type Discovered = { resource: string; server: Server };
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;
}
const lapse = (tokens: Tokens) => Date.now() + (tokens.expires_in ?? 3600) * 1000;
/** How long a refresh's answer is kept for requests that come with the token it spent. */
const SHARED = 5 * 60_000;
/** How long HUD may take to start a sign-in, the account's server found and asked. */
const WAIT = 15_000;
export class SignIn {
readonly #config: SignInConfig;
readonly #redirect: string;
#discovered: Promise<Discovered> | null = null;
#registered: Promise<string> | null = null;
/** Refreshes made, by the refresh token they spent, and until when an answer is kept for others that come with it. */
readonly #refreshes = new Map<string, { answer: Promise<Session | null>; until: number }>();
constructor(config: SignInConfig) {
this.#config = config;
this.#redirect = `${config.origin}${config.callback}`;
}
/** One of HUD's URLs, as this server reaches it. */
#internal(url: string) {
const parsed = new URL(url);
return `${this.#config.hud}${parsed.pathname}${parsed.search}`;
}
/** HUD's protected resource and authorization server metadata, read once (again after a failure). */
#discover(): Promise<Discovered> {
const hud = this.#config.hud;
const found = (this.#discovered ??= (async () => {
const found = await fetch(`${hud}/.well-known/oauth-protected-resource/mcp`);
if (found.status === 404) throw new Error('This HUD 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 path = new URL(issuer).pathname.replace(/^\/$/, '');
const server = await json<Server>(await fetch(`${hud}/.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: resource.resource, server };
})());
found.catch(() => (this.#discovered = null));
return found;
}
/** Whether HUD can fetch the app's client ID metadata document: an https origin with a domain name, as HUD takes one. */
get #documented() {
const url = new URL(this.#config.origin);
return url.protocol === 'https:' && url.hostname.includes('.') && !url.hostname.endsWith('.localhost') && !url.hostname.endsWith('.local') && !url.port;
}
/** The client ID metadata document, which the app serves at `/client-metadata.json`. */
clientMetadata() {
const { origin, name, logo } = this.#config;
return {
client_id: `${origin}/client-metadata.json`,
client_name: name,
client_uri: origin,
...(logo ? { logo_uri: `${origin}${logo}` } : {}),
redirect_uris: [this.#redirect],
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
token_endpoint_auth_method: 'none',
scope: 'hud'
};
}
/** The app's client ID at HUD: its metadata document's URL, or one registered (RFC 7591) once per run. */
#clientId(server: Server): Promise<string> {
if (this.#documented) return Promise.resolve(this.clientMetadata().client_id);
const registered = (this.#registered ??= (async () => {
if (!server.registration_endpoint) throw new Error('The authorization server offers no dynamic client registration.');
const { client_id } = await json<{ client_id: string }>(
await fetch(this.#internal(server.registration_endpoint), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_name: this.#config.name,
redirect_uris: [this.#redirect],
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
token_endpoint_auth_method: 'none',
scope: 'hud'
})
}),
'Registration'
);
return client_id;
})());
registered.catch(() => (this.#registered = null));
return registered;
}
async #token(server: Server, form: Record<string, string>): Promise<Tokens> {
const tokens = await json<Tokens>(
await fetch(this.#internal(server.token_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;
}
/**
* Where to send the browser to sign in, and what to keep until it comes
* back to `back`: a path of the app's (back.ts), else its home page.
* The app's own sign-in screen (`from`, its path) names the account by
* the handle typed there, HUD's `login_hint`, or asks for a new one
* (`create`, `prompt=create`); HUD then goes straight on to the
* account's server, or its sign-up PDS's. Either way each sign-in names
* its account afresh, so signing in again adds another.
*/
async authorize(back: string | null, ask: { from: string; handle: string; create: boolean }): Promise<{ url: string; pending: Pending }> {
const { resource, server } = await this.#discover();
const id = await this.#clientId(server);
const verifier = toBase64url(random(32));
const state = toBase64url(random(32));
const challenge = toBase64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
const url = new URL(server.authorization_endpoint);
for (const [key, value] of Object.entries({
response_type: 'code',
client_id: id,
redirect_uri: this.#redirect,
code_challenge: challenge,
code_challenge_method: 'S256',
state,
resource,
scope: 'hud',
...(ask.create ? { prompt: 'create' } : { login_hint: ask.handle.replace(/^@/, '') })
})) {
url.searchParams.set(key, value);
}
const pending = { state, verifier, clientId: id, back: backPath(back, this.#config.origin), from: ask.from, handle: ask.handle };
return { url: url.href, pending };
}
/**
* Where the browser goes for the sign-in at `url` (`authorize`'s): asked
* of HUD by this server first, so where HUD goes straight on, the
* browser goes on to the account's server with no page of HUD's
* between; where HUD sends it back refused (a handle that is no
* account, a server that refuses), why, for the app's screen to say; and
* where HUD answers its own page (a HUD that sends this app's sign-ins
* through its page), the browser goes there, the handle filled in.
*/
async begin(url: string): Promise<{ to: string } | { error: string }> {
const res = await fetch(this.#internal(url), { redirect: 'manual', signal: AbortSignal.timeout(WAIT) }).catch(() => null);
await res?.body?.cancel();
return wentOn(res && { status: res.status, location: res.headers.get('location') }, url, this.#redirect);
}
/** The session a sign-in comes back with, its code exchanged; throws with why when it cannot be. */
async finish(pending: Pending, params: URLSearchParams): Promise<Session> {
const { resource, server } = await this.#discover();
if (params.get('state') !== pending.state) throw new Error('The answer is not to the sign-in this browser started.');
const error = params.get('error');
if (error) throw new Error(`Sign-in refused: ${error}${params.get('error_description') ? ` (${params.get('error_description')})` : ''}`);
if (server.authorization_response_iss_parameter_supported && params.get('iss') !== server.issuer) throw new Error(`The answer came from ${params.get('iss') ?? 'no issuer'}, not ${server.issuer}.`);
const code = params.get('code');
if (!code) throw new Error('The answer holds no code.');
const tokens = await this.#token(server, {
grant_type: 'authorization_code',
code,
redirect_uri: this.#redirect,
client_id: pending.clientId,
code_verifier: pending.verifier,
resource
});
if (typeof tokens.sub !== 'string') throw new Error('The token response names no account.');
return { did: tokens.sub, access: tokens.access_token, refresh: tokens.refresh_token ?? null, expiresAt: lapse(tokens), clientId: pending.clientId };
}
/** New tokens for a session's refresh token, made once whoever asks: null when it has none or HUD refuses it. */
refresh(session: Session): Promise<Session | null> {
const spent = session.refresh;
if (!spent) return Promise.resolve(null);
const now = Date.now();
for (const [key, kept] of this.#refreshes) if (kept.until < now) this.#refreshes.delete(key);
const kept = this.#refreshes.get(spent);
if (kept) return kept.answer;
const answer = (async (): Promise<Session | null> => {
try {
const { resource, server } = await this.#discover();
const tokens = await this.#token(server, { grant_type: 'refresh_token', refresh_token: spent, client_id: session.clientId, resource });
return { ...session, did: tokens.sub ?? session.did, access: tokens.access_token, refresh: tokens.refresh_token ?? spent, expiresAt: lapse(tokens) };
} catch {
return null;
}
})();
this.#refreshes.set(spent, { answer, until: now + SHARED });
return answer;
}
/** Ends a session at HUD: its refresh token revoked, which ends the session there. */
async revoke(session: Session): Promise<void> {
const { server } = await this.#discover().catch(() => ({ server: null }));
if (!server?.revocation_endpoint) return;
await fetch(this.#internal(server.revocation_endpoint), {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ token: session.refresh ?? session.access, client_id: session.clientId })
}).catch(() => undefined);
}
}