~ 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
70 lines · 3.1 KB Raw History
// What an app's server keeps in a browser's cookies, sealed: encrypted and
// authenticated with AES-256-GCM, so the browser can neither read nor
// change it. The key is derived by HKDF (SHA-256) from the app's secret
// and its `salt`; each cookie's name is its additional data, so one sealed
// for a cookie opens as no other. With no secret (a server under a dev
// server: the host refuses to start without one otherwise), a key is made
// as the server starts, and what is sealed lasts as long as the server.
// Web Crypto alone, so it runs wherever the host's server does.

const VERSION = 1;
const IV = 12;
const TAG = 16;

const bytes = (text: string) => new TextEncoder().encode(text);

/** Bytes as base64url, unpadded. */
export function toBase64url(data: Uint8Array): string {
	let binary = '';
	for (const byte of data) binary += String.fromCharCode(byte);
	return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
}

/** base64url as bytes; throws on anything else. */
export function fromBase64url(text: string): Uint8Array<ArrayBuffer> {
	if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error('Not base64url.');
	const binary = atob(text.replaceAll('-', '+').replaceAll('_', '/'));
	return Uint8Array.from(binary, (c) => c.charCodeAt(0));
}

/** `n` random bytes. */
export const random = (n: number) => crypto.getRandomValues(new Uint8Array(n));

export class Seal {
	readonly #key: Promise<CryptoKey>;

	/** The key from `secret` and `salt` (changing either opens nothing sealed before), or one of this run's where there is no secret. */
	constructor(secret: string | null, salt: string) {
		this.#key = secret
			? crypto.subtle
					.importKey('raw', bytes(secret), 'HKDF', false, ['deriveKey'])
					.then((base) =>
						crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: bytes(salt), info: bytes('cookie seal v1') }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
					)
			: crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
	}

	/** A value sealed for the cookie `name`: version, IV, ciphertext and tag, base64url. */
	async seal(name: string, value: unknown): Promise<string> {
		const iv = random(IV);
		const body = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: bytes(name) }, await this.#key, bytes(JSON.stringify(value)));
		const out = new Uint8Array(1 + IV + body.byteLength);
		out[0] = VERSION;
		out.set(iv, 1);
		out.set(new Uint8Array(body), 1 + IV);
		return toBase64url(out);
	}

	/** What a cookie `name` holds, sealed by `seal`; null for anything else (forged, of another cookie, of another key). */
	async open<T>(name: string, sealed: string | undefined): Promise<T | null> {
		if (!sealed) return null;
		try {
			const data = fromBase64url(sealed);
			if (data.length < 1 + IV + TAG || data[0] !== VERSION) return null;
			const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: data.subarray(1, 1 + IV), additionalData: bytes(name) }, await this.#key, data.subarray(1 + IV));
			return JSON.parse(new TextDecoder().decode(plain)) as T;
		} catch {
			return null;
		}
	}
}