Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

8.2 KB
Raw Blame
// /api/friends/messages — the DM endpoint's contract at its boundary.
//
// This endpoint is the only place a message crosses from an untrusted request
// into the durable thread, so every rejection it owns is pinned here: a target
// that is not a UUID, a cursor that is not a UUID, a body that is empty once
// cleaned, a body over the length cap, and a pair that is not actually friends.
// The suppressed-by-mute path is pinned too, because it deliberately answers
// 200 (so a sender cannot probe who muted them) and that is easy to "fix" into
// a leak later.
//
// Mocks: the auth, rate-limit, CSRF, presence, feed, and friends-store
// boundaries only. The real handler, the real api/_lib/http.js response layer,
// and the real control flow all run.

import { describe, it, expect, vi, beforeEach } from 'vitest';

const ME = '00000000-0000-0000-0000-0000000000aa';
const FRIEND = '00000000-0000-0000-0000-0000000000bb';

const authState = { account: { userId: ME } };
vi.mock('../../api/_lib/account-auth.js', () => ({
	resolveAccount: vi.fn(async () => authState.account),
}));

const rlState = { success: true };
vi.mock('../../api/_lib/rate-limit.js', () => ({
	limits: {
		publicIp: vi.fn(async () => rlState),
		dmSend: vi.fn(async () => rlState),
	},
	clientIp: vi.fn(() => '127.0.0.1'),
}));

vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));

const notifyMultiplayer = vi.fn(async () => ({ delivered: true }));
vi.mock('../../api/_lib/presence-store.js', () => ({
	notifyMultiplayer: (...a) => notifyMultiplayer(...a),
}));

const publishUserEvent = vi.fn(async () => ({ ok: true }));
vi.mock('../../api/_lib/feed.js', () => ({
	publishUserEvent: (...a) => publishUserEvent(...a),
}));

const areFriends = vi.fn(async () => true);
const getThread = vi.fn(async () => []);
const markThreadRead = vi.fn(async () => 0);
const sendDM = vi.fn(async () => null);
const getPublicProfile = vi.fn(async () => ({ id: ME, name: 'ada' }));
vi.mock('../../api/_lib/friends-store.js', () => ({
	areFriends: (...a) => areFriends(...a),
	getThread: (...a) => getThread(...a),
	markThreadRead: (...a) => markThreadRead(...a),
	sendDM: (...a) => sendDM(...a),
	getPublicProfile: (...a) => getPublicProfile(...a),
}));

const { default: handler } = await import('../../api/friends/messages.js');

function makeRes() {
	return {
		statusCode: 200,
		_h: {},
		setHeader(k, v) { this._h[k.toLowerCase()] = v; },
		getHeader(k) { return this._h[k.toLowerCase()]; },
		end(body) { this._body = body; },
	};
}

async function call(req) {
	const res = makeRes();
	await handler({ headers: {}, query: {}, ...req }, res);
	let body = null;
	try { body = JSON.parse(res._body); } catch { /* non-JSON body stays null */ }
	return { res, body };
}

const get = (qs) => call({ method: 'GET', url: `/api/friends/messages${qs}` });

const post = (payload) => call({
	method: 'POST',
	url: '/api/friends/messages',
	headers: { 'content-type': 'application/json' },
	body: payload,
	rawBody: Buffer.from(JSON.stringify(payload)),
});

beforeEach(() => {
	vi.clearAllMocks();
	rlState.success = true;
	authState.account = { userId: ME };
	areFriends.mockResolvedValue(true);
	getThread.mockResolvedValue([]);
	markThreadRead.mockResolvedValue(0);
	getPublicProfile.mockResolvedValue({ id: ME, name: 'ada' });
});

describe('GET /api/friends/messages', () => {
	it('returns the thread and clears unread on a first (non-paginated) load', async () => {
		const thread = [{ id: 'm-1', from: FRIEND, to: ME, body: 'hi', mine: false, read: false }];
		getThread.mockResolvedValue(thread);
		const { res, body } = await get(`?with=${FRIEND}`);
		expect(res.statusCode).toBe(200);
		expect(body.data.messages).toEqual(thread);
		expect(getThread).toHaveBeenCalledWith(ME, FRIEND, { beforeId: null });
		expect(markThreadRead).toHaveBeenCalledWith(ME, FRIEND);
	});

	it('passes the cursor through and leaves unread alone when paginating older history', async () => {
		const cursor = '00000000-0000-0000-0000-0000000000cc';
		await get(`?with=${FRIEND}&before=${cursor}`);
		expect(getThread).toHaveBeenCalledWith(ME, FRIEND, { beforeId: cursor });
		// Paging backwards is not "opening the thread" — it must not mark it read.
		expect(markThreadRead).not.toHaveBeenCalled();
	});

	it('rejects a target that is not a uuid before touching the store', async () => {
		const { res, body } = await get('?with=not-a-uuid');
		expect(res.statusCode).toBe(400);
		expect(body.error).toBe('bad_target');
		expect(areFriends).not.toHaveBeenCalled();
		expect(getThread).not.toHaveBeenCalled();
	});

	it('rejects a cursor that is not a uuid', async () => {
		const { res, body } = await get(`?with=${FRIEND}&before=oldest`);
		expect(res.statusCode).toBe(400);
		expect(body.error).toBe('bad_cursor');
		expect(getThread).not.toHaveBeenCalled();
	});

	it('refuses to open a thread with an account that is not a friend', async () => {
		areFriends.mockResolvedValue(false);
		const { res, body } = await get(`?with=${FRIEND}`);
		expect(res.statusCode).toBe(403);
		expect(body.error).toBe('not_friends');
		expect(getThread).not.toHaveBeenCalled();
	});

	it('requires a signed-in account', async () => {
		authState.account = null;
		const { res, body } = await get(`?with=${FRIEND}`);
		expect(res.statusCode).toBe(401);
		expect(body.error).toBe('unauthorized');
	});
});

describe('POST /api/friends/messages', () => {
	it('persists the message, pushes it live, and files a durable bell notification', async () => {
		const message = { id: 'm-9', from: ME, to: FRIEND, body: 'gm' };
		sendDM.mockResolvedValue(message);
		const { res, body } = await post({ to: FRIEND, body: 'gm' });
		expect(res.statusCode).toBe(200);
		expect(body.data.message).toEqual(message);
		expect(sendDM).toHaveBeenCalledWith(ME, FRIEND, 'gm');
		expect(notifyMultiplayer).toHaveBeenCalledWith('dm', FRIEND, { message });
		// The bell write is fire-and-forget; let its promise chain settle.
		await new Promise((r) => setImmediate(r));
		expect(publishUserEvent).toHaveBeenCalledWith(FRIEND, expect.objectContaining({ type: 'dm_received', actor: 'ada' }));
	});

	it('cleans control characters and collapsed whitespace out of the body', async () => {
		sendDM.mockResolvedValue({ id: 'm-10' });
		await post({ to: FRIEND, body: '  hello\u0000\u0007   there \t ' });
		expect(sendDM).toHaveBeenCalledWith(ME, FRIEND, 'hello there');
	});

	it('reports success without delivering when the recipient has muted the sender', async () => {
		sendDM.mockResolvedValue(null);
		const { res, body } = await post({ to: FRIEND, body: 'gm' });
		// 200 on purpose: a distinguishable error would let a sender enumerate who
		// has muted them.
		expect(res.statusCode).toBe(200);
		expect(body.data).toEqual({ message: null, suppressed: true });
		expect(notifyMultiplayer).not.toHaveBeenCalled();
		expect(publishUserEvent).not.toHaveBeenCalled();
	});

	it('rejects a body that is empty once cleaned', async () => {
		const { res, body } = await post({ to: FRIEND, body: '   \u0001 ' });
		expect(res.statusCode).toBe(400);
		expect(body.error).toBe('empty');
		expect(sendDM).not.toHaveBeenCalled();
	});

	it('rejects a body over the length cap instead of silently truncating it', async () => {
		const { res, body } = await post({ to: FRIEND, body: 'x'.repeat(2001) });
		expect(res.statusCode).toBe(400);
		expect(body.error).toBe('too_long');
		expect(sendDM).not.toHaveBeenCalled();
	});

	it('rejects a target that is not a uuid', async () => {
		const { res, body } = await post({ to: 'someone', body: 'gm' });
		expect(res.statusCode).toBe(400);
		expect(body.error).toBe('bad_target');
		expect(sendDM).not.toHaveBeenCalled();
	});

	it('refuses to message an account that is not a friend', async () => {
		areFriends.mockResolvedValue(false);
		const { res, body } = await post({ to: FRIEND, body: 'gm' });
		expect(res.statusCode).toBe(403);
		expect(body.error).toBe('not_friends');
		expect(sendDM).not.toHaveBeenCalled();
	});

	it('answers 429 with the limiter headers when the send rate limit trips', async () => {
		rlState.success = false;
		const { res, body } = await post({ to: FRIEND, body: 'gm' });
		expect(res.statusCode).toBe(429);
		expect(body.error_description).toBe('you are sending messages too fast');
		expect(sendDM).not.toHaveBeenCalled();
	});
});