feat(federation): process inbound presence_update relay events

processPresenceUpdateEvent updates the local stub's status and broadcasts a
WS presence_update to friends + DM members + space co-members of that stub
via collectProfileBroadcastTargetIds. Closes the doc/code drift in
activity-presence.md:147 — federated stubs now have their status projected
by the home instance as documented.

Strict attribution: payload.homeInstance domain must equal source peer
domain. Silently no-ops when no local replica exists (peer broadcast fanout
covers all peers, not all hold a stub).
This commit is contained in:
Jannis Braun
2026-05-05 16:03:18 +02:00
parent 613424e1c7
commit 53fe7d2b53
2 changed files with 253 additions and 0 deletions
@@ -0,0 +1,166 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import * as schema from '../db/schema.js';
import { eq } from 'drizzle-orm';
import type { FederationRelayEvent } from '@backspace/shared';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
type TestDb = ReturnType<typeof drizzle<typeof schema>>;
let sqlite: Database.Database;
let testDb: TestDb;
const sentToUserCalls: Array<{ userId: string; payload: any }> = [];
vi.mock('../db/index.js', () => ({
getDb: () => testDb,
getRawDb: () => sqlite,
schema,
}));
vi.mock('../ws/handler.js', () => ({
connectionManager: {
sendToUser: vi.fn((uid: string, p: any) => sentToUserCalls.push({ userId: uid, payload: p })),
sendToSpace: vi.fn(),
sendToDmMembers: vi.fn(),
sendToAdmins: vi.fn(),
getAllOnlineUserIds: () => [],
evictFederatedCallsForHost: vi.fn(),
federatedCalls: new Map(),
isUserOnline: vi.fn(),
lateBindFederatedCall: vi.fn(),
},
}));
function applyMigrations(db: Database.Database): void {
const migrationsDir = path.resolve(__dirname, '../../drizzle');
const files = fs.readdirSync(migrationsDir).filter(f => f.endsWith('.sql')).sort();
for (const f of files) {
const sql = fs.readFileSync(path.join(migrationsDir, f), 'utf8');
for (const stmt of sql.split(/-->\s*statement-breakpoint/)) {
const clean = stmt.trim();
if (clean) db.exec(clean);
}
}
}
beforeEach(() => {
sqlite = new Database(':memory:');
testDb = drizzle(sqlite, { schema });
applyMigrations(sqlite);
sentToUserCalls.length = 0;
// Local user (youruser) and replicated stub (pbtest3) — they're friends.
testDb.insert(schema.users).values([
{
id: 'local-youruser', username: 'youruser', passwordHash: 'x', status: 'online', isAdmin: 0,
homeUserId: 'local-youruser', createdAt: Date.now(),
},
{
id: 'stub-pbtest3', username: 'pbtest3@orbit.ddns.net', displayName: 'pbtest3',
passwordHash: '!federation-replicated', status: 'offline', isAdmin: 0,
homeInstance: 'orbit.ddns.net', homeUserId: 'home-pbtest3', createdAt: Date.now(),
},
]).run();
testDb.insert(schema.friends).values({
userId: 'local-youruser', friendId: 'stub-pbtest3', createdAt: Date.now(),
}).run();
});
describe('processPresenceUpdateEvent', () => {
it('updates stub status and broadcasts presence_update to local friends', async () => {
const fed = await import('./federation.js');
const event: FederationRelayEvent = {
eventType: 'presence_update',
contextType: 'profile',
messageId: 'p1',
encryptionVersion: 0,
timestamp: Date.now(),
presenceUpdate: {
homeUserId: 'home-pbtest3',
homeInstance: 'orbit.ddns.net',
status: 'online',
ts: Date.now(),
},
};
const accepted: string[] = [];
const rejected: Array<{ messageId: string; reason: string }> = [];
fed.processPresenceUpdateEvent(event, 'orbit.ddns.net', testDb, accepted, rejected);
expect(rejected).toEqual([]);
expect(accepted).toEqual(['p1']);
const row = testDb.select().from(schema.users).where(eq(schema.users.id, 'stub-pbtest3')).get();
expect(row!.status).toBe('online');
const broadcast = sentToUserCalls.find((c) => c.userId === 'local-youruser');
expect(broadcast).toBeDefined();
expect(broadcast!.payload.type).toBe('presence_update');
expect(broadcast!.payload.userId).toBe('stub-pbtest3');
expect(broadcast!.payload.status).toBe('online');
});
it('rejects on attribution mismatch', async () => {
const fed = await import('./federation.js');
const event: FederationRelayEvent = {
eventType: 'presence_update', contextType: 'profile', messageId: 'p2',
encryptionVersion: 0, timestamp: Date.now(),
presenceUpdate: {
homeUserId: 'home-pbtest3', homeInstance: 'orbit.ddns.net',
status: 'online', ts: Date.now(),
},
};
const rejected: Array<{ messageId: string; reason: string }> = [];
fed.processPresenceUpdateEvent(event, 'evil.example.com', testDb, [], rejected);
expect(rejected).toEqual([{ messageId: 'p2', reason: 'attribution_mismatch' }]);
});
it('silently accepts when no replica exists locally', async () => {
const fed = await import('./federation.js');
const event: FederationRelayEvent = {
eventType: 'presence_update', contextType: 'profile', messageId: 'p3',
encryptionVersion: 0, timestamp: Date.now(),
presenceUpdate: {
homeUserId: 'unknown-id', homeInstance: 'orbit.ddns.net',
status: 'online', ts: Date.now(),
},
};
const accepted: string[] = [];
const rejected: Array<{ messageId: string; reason: string }> = [];
fed.processPresenceUpdateEvent(event, 'orbit.ddns.net', testDb, accepted, rejected);
expect(accepted).toEqual(['p3']);
expect(rejected).toEqual([]);
});
it('rejects invalid status values', async () => {
const fed = await import('./federation.js');
const event: FederationRelayEvent = {
eventType: 'presence_update', contextType: 'profile', messageId: 'p4',
encryptionVersion: 0, timestamp: Date.now(),
presenceUpdate: {
homeUserId: 'home-pbtest3', homeInstance: 'orbit.ddns.net',
status: 'invisible' as any, ts: Date.now(),
},
};
const rejected: Array<{ messageId: string; reason: string }> = [];
fed.processPresenceUpdateEvent(event, 'orbit.ddns.net', testDb, [], rejected);
expect(rejected).toEqual([{ messageId: 'p4', reason: 'invalid_status' }]);
});
it('passes activities through to the WS broadcast when present', async () => {
const fed = await import('./federation.js');
const event: FederationRelayEvent = {
eventType: 'presence_update', contextType: 'profile', messageId: 'p5',
encryptionVersion: 0, timestamp: Date.now(),
presenceUpdate: {
homeUserId: 'home-pbtest3', homeInstance: 'orbit.ddns.net',
status: 'online', activities: [{ type: 'playing', name: 'Test' }],
ts: Date.now(),
},
};
fed.processPresenceUpdateEvent(event, 'orbit.ddns.net', testDb, [], []);
const broadcast = sentToUserCalls.find((c) => c.userId === 'local-youruser');
expect(broadcast!.payload.activities).toEqual([{ type: 'playing', name: 'Test' }]);
});
});
+87
View File
@@ -3004,6 +3004,9 @@ export async function processRelayEvents(
case 'profile_update': case 'profile_update':
await processProfileUpdateEvent(event, sourceInstance, db, accepted, rejected); await processProfileUpdateEvent(event, sourceInstance, db, accepted, rejected);
break; break;
case 'presence_update':
processPresenceUpdateEvent(event, sourceInstance, db, accepted, rejected);
break;
case 'read_state_update': case 'read_state_update':
processReadStateUpdateEvent(event, sourceInstance, db, accepted, rejected); processReadStateUpdateEvent(event, sourceInstance, db, accepted, rejected);
break; break;
@@ -5841,6 +5844,90 @@ export async function processProfileUpdateEvent(
accepted.push(event.messageId); accepted.push(event.messageId);
} }
/**
* Inbound presence_update relay handler.
*
* Authority: home instance is exclusive. payload.homeInstance domain MUST equal
* the source peer's domain (attribution check, mirrors profile_update).
*
* Effect on success:
* 1. Update the local stub's status column.
* 2. Broadcast a WS presence_update to local users via collectProfileBroadcastTargetIds
* (friends + DM members + space co-members), so the green dot updates without a
* page refresh on every connected client that knows this user.
*
* Edge cases:
* - No local replica → silently accept (peer broadcasts presence to all peers,
* not all peers have a stub).
* - homeInstance domain mismatch on the existing stub → ignore (collision against
* a stub of a different identity).
* - Invalid status string → reject; sender is buggy, surface for diagnosis.
*/
export function processPresenceUpdateEvent(
event: FederationRelayEvent,
sourceInstance: string,
db: ReturnType<typeof getDb>,
accepted: string[],
rejected: Array<{ messageId: string; reason: string }>,
): void {
const payload = event.presenceUpdate;
if (!payload) {
rejected.push({ messageId: event.messageId, reason: 'missing_presence_update_payload' });
return;
}
const payloadDomain = extractDomain(payload.homeInstance);
const sourceDomain = extractDomain(sourceInstance);
if (payloadDomain !== sourceDomain) {
console.warn(`[federation] Attribution mismatch in presence_update: homeInstance=${payloadDomain} source=${sourceDomain}`);
rejected.push({ messageId: event.messageId, reason: 'attribution_mismatch' });
return;
}
if (!payload.status || !['online', 'idle', 'dnd', 'offline'].includes(payload.status)) {
rejected.push({ messageId: event.messageId, reason: 'invalid_status' });
return;
}
const localUser = db
.select()
.from(schema.users)
.where(and(
eq(schema.users.homeUserId, payload.homeUserId),
eq(schema.users.isDeleted, 0),
))
.get();
if (!localUser) {
accepted.push(event.messageId);
return;
}
if (localUser.homeInstance && extractDomain(localUser.homeInstance) !== payloadDomain) {
accepted.push(event.messageId);
return;
}
db.update(schema.users)
.set({ status: payload.status })
.where(eq(schema.users.id, localUser.id))
.run();
// Broadcast presence_update WS event to local users who care.
const targetUserIds = collectProfileBroadcastTargetIds(localUser.id);
const wsPayload = {
type: 'presence_update' as const,
userId: localUser.id,
status: payload.status,
...(payload.activities && payload.activities.length > 0 ? { activities: payload.activities } : {}),
};
for (const uid of targetUserIds) {
connectionManager.sendToUser(uid, wsPayload);
}
accepted.push(event.messageId);
}
// ─── Replicated Profile Asset Backfill ────────────────────────────────────── // ─── Replicated Profile Asset Backfill ──────────────────────────────────────
/** /**