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
// An app's server's sessions at HUD, for the browsers it draws pages for:
// each browser's accounts (accounts.ts), HUD's tokens for each sealed in
// one HttpOnly cookie (seal.ts) that only the server opens, signed in to
// as an MCP client of HUD (oauth.ts). The host makes one `Sessions` with
// its configuration, and for each request a `Hud` (`request`): the
// request's way to HUD as the account in use, and the endpoints the
// shell's pages reach (the host routes each to it): signing in and its
// callback, signing out, switching accounts, the pages' tool calls and
// uploads.
//
// Sealed in the cookie rather than kept in a store, so the server holds
// nothing a restart or a rollback loses and needs no volume: five
// accounts' tokens (two opaque 43-character tokens, a DID, the client's
// ID and a time each) seal to under 2 KB, well within a cookie's 4 KB,
// which `fit` holds it to whatever they are. A session ends when its
// tokens do, or at sign-out, when its refresh token is revoked at HUD.
// What a row of the accounts shows (a name, a handle, a picture) is read
// with the account's own tokens, as the frame's `account.picture` says,
// and kept in memory a while, by DID, never in the cookie.
//
// `__Host-` keeps each cookie to the app's origin over https, at `/`. The
// pending sign-in's lasts its ten minutes; the accounts' as long as a
// refresh token (30 days from its last rotation), written again at each.
// The account's scheme is no secret, but kept the same way; it is read
// only beside a session, and let go as the account in use changes.
//
// No mixing: a page is drawn as one account, start to end. Where HUD
// refuses the account in use partway through a request, the rest of the
// request is drawn signed out, and the next as the account the cookie
// then has in use. Switching, adding or signing out, the shell loads the
// page anew, so nothing of the account before (its screens remembered,
// what was read ahead, its counts, an open form) is drawn again.
import type { ToolResult } from '@hud/shared/result';
import { added, fit, keptOf, removed, renewed, used, type Kept } from './accounts';
import { at, type App } from './app';
import { SignInNeeded, toolRequest, toolResult } from './client';
import { SignIn, type Pending, type Session, type SignInConfig } from './oauth';
import { same } from './routes';
import { Seal } from './seal';
import type { Caller } from './server';
import { schemeIn, schemeOf } from './theme';
/** A request's cookies, as a host's server reads and sets them (SvelteKit's `cookies`). */
export type Cookies = {
get(name: string): string | undefined;
set(name: string, value: string, options: { path: string; httpOnly?: boolean; secure?: boolean; sameSite?: 'lax'; maxAge?: number }): void;
delete(name: string, options: { path: string; secure?: boolean }): void;
};
/** What the server's sessions are kept with. */
export type SessionsConfig = SignInConfig & {
/** The secret the cookies are sealed with: at least 32 characters; null under a dev server, a key made per run. Changing it signs everyone out. */
secret: string | null;
/** What the seal's key is derived with beside the secret; changing it signs everyone out. */
salt: string;
/** The start of the cookies' names: `__Host-<prefix>-session`, `__Host-<prefix>-signin`, `<prefix>-scheme`. */
prefix: string;
};
/** One account the browser is signed in to, as a row of the accounts shows it. */
export type AccountRow = { did: string; handle: string | null; name: string | null; picture: string | null };
/** The browser's accounts: the rows, in the order they were added, and the one in use. */
export type AccountsData = { list: AccountRow[]; current: string };
/** How long a call to HUD may take before the page gives up on it. */
const WAIT = 15_000;
/** How long before its access token lapses a session is refreshed, so a page's calls, streamed ones too, carry a live one. */
const EARLY = 60_000;
const SESSION_LIFE = 30 * 86_400;
const SIGNIN_LIFE = 600;
/** How long a row of the accounts is kept, and how many. */
const ROW_LIFE = 10 * 60_000;
const ROWS_MAX = 1000;
/** Handles resolved, how many and how long. */
const DIDS_MAX = 10_000;
const DID_LIFE = 10 * 60_000;
const NO_STORE = { 'cache-control': 'private, no-store' };
const options = (maxAge: number) => ({ path: '/', httpOnly: true, secure: true, sameSite: 'lax' as const, maxAge });
/** A row of the accounts from the account's own answer to the frame's picture call: its name, handle and picture where the frame says where they are. */
function rowOf(did: string, answer: unknown, app: App): AccountRow {
const shown = app.frame?.account?.picture;
const text = (path: string | undefined) => {
const found = path ? at(answer, path) : undefined;
return typeof found === 'string' && found !== '' ? found : null;
};
const picture = text(shown?.at);
return { did, name: text(shown?.name), handle: text(shown?.handle), picture: picture?.startsWith('https://') ? picture : null };
}
export class Sessions {
readonly signIn: SignIn;
readonly seal: Seal;
readonly names: { session: string; signIn: string; scheme: string };
readonly #config: SessionsConfig;
/** Each account's row, by DID, and until when it is drawn without being read again. */
readonly rows = new Map<string, { row: AccountRow; until: number }>();
/** Handles resolved: a handle in a URL is resolved once in a while, not on every page. */
readonly dids = new Map<string, { did: string; until: number }>();
constructor(config: SessionsConfig) {
this.#config = config;
this.signIn = new SignIn(config);
this.seal = new Seal(config.secret, config.salt);
this.names = { session: `__Host-${config.prefix}-session`, signIn: `__Host-${config.prefix}-signin`, scheme: `${config.prefix}-scheme` };
}
get hud() {
return this.#config.hud;
}
get origin() {
return this.#config.origin;
}
/** The app as an OAuth client of HUD: its client ID metadata document, for the app to serve at `/client-metadata.json`. */
clientMetadata() {
return this.signIn.clientMetadata();
}
/** A row kept, as an account's own answer read it. */
remember(row: AccountRow) {
if (this.rows.size >= ROWS_MAX) this.rows.delete(this.rows.keys().next().value!);
this.rows.delete(row.did);
this.rows.set(row.did, { row, until: Date.now() + ROW_LIFE });
}
/**
* A request's way to HUD: its cookie's accounts, the one in use
* refreshed where its access token lapses soon (or where a cookie from
* before accounts were kept does not name it yet); one HUD no longer
* takes let go, the one before it in use after.
*/
async request(cookies: Cookies): Promise<Hud> {
const raw = cookies.get(this.names.session);
let kept = keptOf(await this.seal.open(this.names.session, raw));
let changed = raw !== undefined && kept === null;
while (kept) {
const session = kept.sessions[kept.active];
if (session.did !== null && session.expiresAt - EARLY >= Date.now()) break;
const fresh = await this.signIn.refresh(session);
changed = true;
if (fresh) {
kept = renewed(kept, kept.active, fresh);
break;
}
kept = removed(kept, kept.active);
}
const hud = new Hud(this, cookies, kept, raw !== undefined);
if (changed) await hud.keep(kept);
return hud;
}
}
/** A request's way to HUD, as the account its cookie has in use, and the shell's endpoints. */
export class Hud implements Caller {
readonly #sessions: Sessions;
readonly #cookies: Cookies;
#kept: Kept | null;
/** The account in use, as the request started; null signed out, or once HUD refused it here. */
#session: Session | null;
/** Writes of the cookie begun: only the last sets it. */
#writes = 0;
/** Whether the request came with a session cookie, live or not. */
readonly asked: boolean;
constructor(sessions: Sessions, cookies: Cookies, kept: Kept | null, asked: boolean) {
this.#sessions = sessions;
this.#cookies = cookies;
this.#kept = kept;
this.#session = kept ? kept.sessions[kept.active] : null;
this.asked = asked;
}
/** The account in use's session, as this request is drawn: null signed out. */
get session(): Session | null {
return this.#session;
}
/** The account's own scheme, as its cookie keeps it: read only beside a session, so it alone never changes a page anyone else is sent. */
get scheme(): 'light' | 'dark' | null {
return this.#session ? schemeOf(this.#cookies.get(this.#sessions.names.scheme)) : null;
}
/** Whether the account's scheme is kept in its cookie yet. */
get schemeKept(): boolean {
return this.#cookies.get(this.#sessions.names.scheme) !== undefined;
}
/** The account's own scheme kept for the pages drawn next (`undefined` forgets it, for the next account's to be read). */
keepScheme(scheme: 'light' | 'dark' | null | undefined) {
const name = this.#sessions.names.scheme;
if (scheme === undefined) this.#cookies.delete(name, { path: '/', secure: true });
else this.#cookies.set(name, scheme ?? 'system', options(365 * 86_400));
}
/** The accounts changed: the cookie follows them, as many as fit it (the rest revoked), where the response has not begun (a promise streamed after it cannot: the next request's cookie, its refresh shared, carries it). */
async keep(kept: Kept | null) {
this.#kept = kept;
const write = ++this.#writes;
const { session } = this.#sessions.names;
if (!kept) {
if (write === this.#writes) this.#forget(session);
return;
}
const fitted = await fit(kept, (k) => this.#sessions.seal.seal(session, k));
for (const gone of fitted.dropped) void this.#sessions.signIn.revoke(gone);
if (fitted.kept !== kept) this.#kept = fitted.kept;
if (write !== this.#writes) return;
try {
this.#cookies.set(session, fitted.sealed, options(SESSION_LIFE));
} catch {
// Streaming already.
}
}
#forget(name: string) {
try {
this.#cookies.delete(name, { path: '/', secure: true });
} catch {
// Streaming already.
}
}
#send(session: Session | null, name: string, args: Record<string, unknown>) {
return fetch(`${this.#sessions.hud}/mcp`, { ...toolRequest(name, args, session?.access ?? null), signal: AbortSignal.timeout(WAIT) });
}
/**
* A call as one of the browser's accounts: a token HUD refuses
* refreshed once and the call made again; a session HUD no longer takes
* let go (`SignInNeeded` thrown). Its new tokens are kept as the session
* it is now, found by itself in the accounts, as calls run side by side.
*/
async #as(session: Session, name: string, args: Record<string, unknown>): Promise<{ result: Promise<ToolResult>; now: Session | null }> {
let res = await this.#send(session, name, args);
let now: Session | null = session;
if (res.status === 401) {
now = await this.#sessions.signIn.refresh(session);
const kept = this.#kept;
const i = kept ? kept.sessions.indexOf(session) : -1;
if (kept && i >= 0) await this.keep(now ? renewed(kept, i, now) : removed(kept, i));
if (now) res = await this.#send(now, name, args);
if (res.status === 401 && now) {
const later = this.#kept;
const j = later ? later.sessions.indexOf(now) : -1;
if (later && j >= 0) await this.keep(removed(later, j));
now = null;
}
}
return { result: toolResult(res), now };
}
/** One of HUD's tools as the account in use: its result, failures included (`isError`); throws `SignInNeeded` where it needs an account this request has not, and with why where HUD could not be reached. */
async call(name: string, args: Record<string, unknown>): Promise<ToolResult> {
const session = this.#session;
if (!session) return toolResult(await this.#send(null, name, args));
const { result, now } = await this.#as(session, name, args);
// The account in use refused: the rest of this request is drawn signed out, never as another.
if (this.#session === session) this.#session = now;
return result;
}
/** A handle's DID, as `describe_repo` resolves it, kept a while; the handle as it is where it cannot. */
async resolve(actor: string): Promise<string> {
const dids = this.#sessions.dids;
const now = Date.now();
const kept = dids.get(actor);
if (kept && kept.until > now) return kept.did;
const result = await this.call('describe_repo', { actor }).catch(() => null);
const did = (result?.structuredContent as { did?: unknown } | null | undefined)?.did;
if (result?.isError || typeof did !== 'string') return actor;
if (dids.size >= DIDS_MAX) dids.delete(dids.keys().next().value!);
dids.set(actor, { did, until: now + DID_LIFE });
return did;
}
/**
* The browser's accounts as rows: the one in use's from `own`, its
* answer to the frame's picture call; each other's kept a while, else
* read with its own tokens. Null signed out.
*/
async accounts(app: App, own: Promise<unknown>): Promise<AccountsData | null> {
const kept = this.#kept;
const active = this.#session;
if (!kept || !active?.did) return null;
const shown = app.frame?.account?.picture;
const rows = await Promise.all(
kept.sessions.map(async (session): Promise<AccountRow | null> => {
const did = session.did;
if (!did) return null;
const cached = this.#sessions.rows.get(did);
if (session === active) {
const answer = await own;
if (answer === null && cached) return cached.row;
const row = rowOf(did, answer, app);
if (answer !== null) this.#sessions.remember(row);
return row;
}
if (cached && cached.until > Date.now()) return cached.row;
if (!shown) return rowOf(did, null, app);
const read = await this.#as(session, shown.call.name, shown.call.args).catch(() => null);
const result = await read?.result.catch(() => null);
// Let go (HUD no longer takes it): no row; not reached: as it was.
if (read && !read.now) return null;
if (!result || result.isError) return cached?.row ?? rowOf(did, null, app);
const row = rowOf(did, result.structuredContent, app);
this.#sessions.remember(row);
return row;
})
);
return { list: rows.filter((row) => row !== null), current: active.did };
}
/** Whether a request that changes something comes from the app's own pages: its `Origin`, where a browser sends one, the app's public origin (or the one it was asked at, under a dev server). */
#own(request: Request, url: URL): boolean {
const from = request.headers.get('origin');
return from === null || from === this.#sessions.origin || from === url.origin;
}
/**
* The app's own sign-in screen's form, posted to it at `url` (the host's
* sign-in path): the account its `handle` names, or with `create` a new
* one, signed in to, then back to its `back`. Where HUD goes straight on,
* where the browser goes (`to`: the account's server), what it comes
* back to kept in its sign-in cookie; else why not, with the handle as
* typed, for the screen to say. Signed in already, another account is
* added. Only from the app's origin.
*/
async signIn(request: Request, url: URL): Promise<{ to: string } | { handle: string; error: string }> {
if (!this.#own(request, url)) return { handle: '', error: 'Not from this site.' };
const form = await request.formData().catch(() => null);
const field = (name: string) => {
const value = form?.get(name);
return typeof value === 'string' ? value : null;
};
const handle = (field('handle') ?? '').trim();
const create = field('create') === '1';
if (!create && !handle.replace(/^@/, '')) return { handle, error: 'Enter your handle, as alice.bsky.social.' };
try {
const { url: at, pending } = await this.#sessions.signIn.authorize(field('back'), { from: url.pathname, handle, create });
const went = await this.#sessions.signIn.begin(at);
if ('error' in went) return { handle, error: went.error };
this.#cookies.set(this.#sessions.names.signIn, await this.#sessions.seal.seal(this.#sessions.names.signIn, pending), options(SIGNIN_LIFE));
return { to: went.to };
} catch (why) {
return { handle, error: why instanceof Error ? why.message : String(why) };
}
}
/**
* HUD's sign-in come back: its code exchanged for the account's tokens,
* the account added to the browser's (in place of its own where it was
* signed in to already, whose old session is revoked) and put in use,
* and the browser sent back where it signed in from. Refused (the
* account's server, or the person there, said no), the browser goes
* back to the screen it signed in from, saying why, its handle filled
* in.
*/
async callback(url: URL): Promise<Response> {
const name = this.#sessions.names.signIn;
const pending = await this.#sessions.seal.open<Pending>(name, this.#cookies.get(name));
this.#forget(name);
const refused = (message: string) => new Response(message, { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8', ...NO_STORE } });
if (!pending) return refused('No sign-in was under way in this browser, or it took longer than ten minutes. Sign in again.');
let session: Session;
try {
session = await this.#sessions.signIn.finish(pending, url.searchParams);
} catch (why) {
const params = url.searchParams;
const message = params.has('error') ? params.get('error_description') || 'Signing in was refused.' : why instanceof Error ? why.message : String(why);
if (!pending.from) return refused(message);
const screen = new URLSearchParams({ back: pending.back, handle: pending.handle ?? '', error: message });
return new Response(null, { status: 303, headers: { location: `${pending.from}?${screen}`, ...NO_STORE } });
}
const { kept, replaced, dropped } = added(this.#kept, session);
for (const gone of [...(replaced && replaced.refresh !== session.refresh ? [replaced] : []), ...dropped]) void this.#sessions.signIn.revoke(gone);
await this.keep(kept);
this.keepScheme(undefined);
return new Response(null, { status: 303, headers: { location: pending.back, ...NO_STORE } });
}
/** Sign out of the account in use: its refresh token revoked at HUD, which ends its session there; the one before it in use after, if any is left. Only from the app's origin, by POST. */
async signOut(request: Request, url: URL): Promise<Response> {
if (!this.#own(request, url)) return new Response(null, { status: 403 });
const kept = this.#kept;
const session = kept ? kept.sessions[kept.active] : null;
await this.keep(kept && removed(kept, kept.active));
this.keepScheme(undefined);
if (session) await this.#sessions.signIn.revoke(session);
return new Response(null, { status: 204, headers: NO_STORE });
}
/** Switch to another of the browser's accounts (`{did}`, JSON): only one it is signed in to, only from the app's origin, by POST. */
async use(request: Request, url: URL): Promise<Response> {
if (!this.#own(request, url)) return Response.json({ message: 'Not from this site.' }, { status: 403, headers: NO_STORE });
const asked = (await request.json().catch(() => null)) as { did?: unknown } | null;
const now = this.#kept && typeof asked?.did === 'string' ? used(this.#kept, asked.did) : null;
if (!now) return Response.json({ message: 'This browser is not signed in to that account.' }, { status: 404, headers: NO_STORE });
await this.keep(now);
this.keepScheme(undefined);
return new Response(null, { status: 204, headers: NO_STORE });
}
/**
* The pages' calls of HUD's tools: `{name, args}`, made as the account
* in use, answered with the tool's result; 401 where it needs an account
* the request has not. JSON only, so a page elsewhere cannot send one
* without asking first (CORS), and only from the app's origin. Where it
* is the app's scheme call, the scheme it answers is kept in its cookie,
* for the pages drawn next.
*/
async mcp(request: Request, url: URL, app: App): Promise<Response> {
const answer = (body: unknown, status = 200) => Response.json(body, { status, headers: NO_STORE });
if (!this.#own(request, url)) return answer({ message: 'Not from this site.' }, 403);
if (!request.headers.get('content-type')?.startsWith('application/json')) return answer({ message: 'Send JSON.' }, 415);
const asked = (await request.json().catch(() => null)) as { name?: unknown; args?: unknown } | null;
if (typeof asked?.name !== 'string' || typeof asked.args !== 'object' || asked.args === null || Array.isArray(asked.args)) return answer({ message: 'A call is {name, args}.' }, 400);
const call = { name: asked.name, args: asked.args as Record<string, unknown> };
try {
const result = await this.call(call.name, call.args);
const scheme = app.scheme;
if (scheme && this.#session && !result.isError && same(call, scheme.call)) this.keepScheme(schemeIn(result.structuredContent, scheme.at));
return answer(result);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return answer({ message }, error instanceof SignInNeeded ? 401 : 502);
}
}
/** A picture uploaded as the account in use: its bytes streamed on to HUD's `place.hud.uploadBlob` with its token, HUD's answer (the blob ref, or why not) streamed back. */
async upload(request: Request, url: URL): Promise<Response> {
const answer = (body: unknown, status: number) => Response.json(body, { status, headers: NO_STORE });
if (!this.#own(request, url)) return answer({ message: 'Not from this site.' }, 403);
const session = this.#session;
if (!session) return answer({ message: 'Sign in to upload.' }, 401);
const res = await fetch(`${this.#sessions.hud}/xrpc/place.hud.uploadBlob`, {
method: 'POST',
headers: { authorization: `Bearer ${session.access}`, 'content-type': request.headers.get('content-type') ?? 'application/octet-stream' },
body: request.body,
// @ts-expect-error: Node's fetch streams a request body only half duplex, which its types do not name.
duplex: 'half'
}).catch(() => null);
if (!res) return answer({ message: 'The upload could not reach HUD.' }, 502);
return new Response(res.body, { status: res.status, headers: { 'content-type': res.headers.get('content-type') ?? 'application/json', ...NO_STORE } });
}
}