~ 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
101 lines · 5.5 KB Raw History
// `npm run unit` in web/ (`just check` runs it).
import { strict as assert } from 'node:assert';
import { createCipheriv, hkdfSync, randomBytes } from 'node:crypto';
import { test } from 'node:test';
import { added, COOKIE_MAX, fit, keptOf, MAX, removed, renewed, used, type Kept } from './accounts.ts';
import type { Session } from './oauth.ts';
import { Seal } from './seal.ts';

/** A session as HUD's tokens make one: two 43-character tokens, a DID, the app's client ID. */
const session = (n: number, did: string | null = `did:plc:${String(n).padStart(24, 'a')}`): Session => ({
	did,
	access: randomBytes(32).toString('base64url'),
	refresh: randomBytes(32).toString('base64url'),
	expiresAt: Date.now() + 3_600_000,
	clientId: 'https://next.grain.social/client-metadata.json'
});
const dids = (kept: Kept | null) => kept?.sessions.map((s) => s.did);

test('a cookie of one session, from before several were kept, opens as one account', () => {
	const old = session(1);
	const { did: _, ...before } = old;
	assert.deepEqual(keptOf(before), { sessions: [{ ...before, did: null }], active: 0 });
	assert.deepEqual(keptOf({ sessions: [old], active: 0 }), { sessions: [old], active: 0 });
	// An active past the end is the first; nothing else opens.
	assert.equal(keptOf({ sessions: [old], active: 3 })?.active, 0);
	for (const bad of [null, 1, {}, { sessions: [] }, { sessions: [{ access: 1 }] }]) assert.equal(keptOf(bad), null, JSON.stringify(bad));
});

test('signing in adds an account in use, takes an account kept anew, and keeps at most MAX', () => {
	let kept: Kept | null = null;
	for (let n = 0; n < MAX; n++) kept = added(kept, session(n)).kept;
	assert.equal(kept?.active, MAX - 1);
	const again = session(1);
	const replaced = added(kept, again);
	assert.equal(replaced.kept.active, 1);
	assert.equal(replaced.kept.sessions[1], again);
	assert.equal(replaced.replaced, kept?.sessions[1]);
	const more = added(kept, session(9));
	assert.deepEqual(more.dropped, [kept?.sessions[0]]);
	assert.equal(more.kept.sessions.length, MAX);
	assert.equal(more.kept.active, MAX - 1);
	// A session not yet naming its account is never taken for another's.
	const unnamed = added({ sessions: [session(0, null)], active: 0 }, session(1, null)).kept;
	assert.equal(unnamed.sessions.length, 2);
});

test('switching uses only an account kept; signing out uses the one before', () => {
	let kept: Kept | null = null;
	for (let n = 0; n < 3; n++) kept = added(kept, session(n)).kept;
	const three = kept as Kept;
	const first = three.sessions[0].did as string;
	assert.equal(used(three, first)?.active, 0);
	assert.equal(used(three, 'did:plc:nobody'), null);
	assert.deepEqual(dids(removed(three, 2)), [three.sessions[0].did, three.sessions[1].did]);
	assert.equal(removed(three, 2)?.active, 1);
	assert.equal(removed({ ...three, active: 0 }, 0)?.active, 0);
	assert.equal(removed({ ...three, active: 2 }, 0)?.active, 1);
	assert.equal(removed({ ...three, active: 0 }, 2)?.active, 0);
	assert.equal(removed({ sessions: [three.sessions[0]], active: 0 }, 0), null);
	const fresh = session(7);
	assert.equal(renewed(three, 1, fresh).sessions[1], fresh);
});

test('five accounts seal well within a cookie, and what does not fit gives way, never the one in use', async () => {
	const seal = new Seal('a secret of at least thirty-two characters', 'test');
	let kept: Kept | null = null;
	for (let n = 0; n < MAX; n++) kept = added(kept, session(n)).kept;
	const five = kept as Kept;
	const sealed = await seal.seal('__Host-grain-session', five);
	assert.ok(sealed.length < 2000, `five accounts seal to ${sealed.length} characters`);
	assert.deepEqual(await seal.open('__Host-grain-session', sealed), five);
	const all = await fit(five, (k) => seal.seal('__Host-grain-session', k));
	assert.deepEqual(all.dropped, []);
	// Accounts too long to fit (DIDs of did:web at their longest): the earliest give way, never the one in use.
	const long = { sessions: five.sessions.map((s, i) => ({ ...s, did: `did:web:${'x'.repeat(900)}${i}` })), active: 0 };
	const fitted = await fit(long, (k) => seal.seal('__Host-grain-session', k));
	assert.ok(fitted.sealed.length <= COOKIE_MAX);
	assert.equal(fitted.kept.sessions[fitted.kept.active], long.sessions[0]);
	assert.deepEqual(fitted.dropped, long.sessions.slice(1, 1 + fitted.dropped.length));
});

test('a cookie sealed before, by node:crypto, opens: no one is signed out by the move', async () => {
	const secret = 'a secret of at least thirty-two characters';
	const key = Buffer.from(hkdfSync('sha256', secret, 'grain-next', 'cookie seal v1', 32));
	const iv = randomBytes(12);
	const cipher = createCipheriv('aes-256-gcm', key, iv);
	cipher.setAAD(Buffer.from('__Host-grain-session'));
	const before = { access: 'a', refresh: 'r', expiresAt: 1, clientId: 'c' };
	const body = Buffer.concat([cipher.update(JSON.stringify(before), 'utf8'), cipher.final()]);
	const sealed = Buffer.concat([Buffer.of(1), iv, body, cipher.getAuthTag()]).toString('base64url');
	const seal = new Seal(secret, 'grain-next');
	assert.deepEqual(await seal.open('__Host-grain-session', sealed), before);
	// Of another cookie, another key, or nothing sealed: nothing.
	assert.equal(await seal.open('__Host-grain-signin', sealed), null);
	assert.equal(await new Seal(secret, 'other').open('__Host-grain-session', sealed), null);
	assert.equal(await seal.open('__Host-grain-session', 'not sealed!'), null);
	assert.equal(await seal.open('__Host-grain-session', undefined), null);
	// With no secret, a key of the run's own.
	const run = new Seal(null, 'x');
	assert.deepEqual(await run.open('n', await run.seal('n', [1])), [1]);
});