Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 44 additions & 9 deletions apps/api-e2e/src/api/realtime-session-boundary.e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,7 @@ describe('Realtime session boundary against persisted identity and installation
await gateway.handleConnection(client);
expect(client.data.user.role).toBe('Manager');
await gateway.broadcast('project:changed', { projectId: 'example' });
expect(client.emit).toHaveBeenCalledWith('project:changed', {
projectId: 'example',
});
expect(client.emit).toHaveBeenCalledWith('project:changed');
jest.mocked(client.emit).mockClear();
await ctx.prisma.employee.update({
where: { id: owner.id },
Expand All @@ -132,9 +130,7 @@ describe('Realtime session boundary against persisted identity and installation
update: { mode: 'Solo', ownerEmployeeId: owner.id },
});
await gateway.broadcast('time-entry:created', { employeeId: owner.id });
expect(ownerClient.emit).toHaveBeenCalledWith('time-entry:created', {
employeeId: owner.id,
});
expect(ownerClient.emit).toHaveBeenCalledWith('time-entry:created');
expect(otherClient.emit).not.toHaveBeenCalled();
expect(otherClient.disconnect).toHaveBeenCalledWith(true);
jest.mocked(ownerClient.emit).mockClear();
Expand All @@ -161,9 +157,7 @@ describe('Realtime session boundary against persisted identity and installation
});
expect(oldClient.disconnect).toHaveBeenCalledWith(true);
expect(oldClient.emit).not.toHaveBeenCalled();
expect(newClient.emit).toHaveBeenCalledWith('project:changed', {
projectId: 'after-password-change',
});
expect(newClient.emit).toHaveBeenCalledWith('project:changed');
const denied = socket(oldToken);
await gateway.handleConnection(denied);
expect(denied.disconnect).toHaveBeenCalledWith(true);
Expand All @@ -180,4 +174,45 @@ describe('Realtime session boundary against persisted identity and installation
expect(client.disconnect).toHaveBeenCalledWith(true);
expect(client.emit).not.toHaveBeenCalled();
});

it('disconnects a client whose server-side login session was revoked', async () => {
const { owner } = await fixture();
const client = socket(await login(ctx.http, owner.email));
await gateway.handleConnection(client);
const session = await ctx.prisma.authSession.findFirstOrThrow({
where: { employeeId: owner.id },
});
await ctx.prisma.authSession.update({
where: { id: session.id },
data: { revokedAt: new Date() },
});

await gateway.broadcast('project:changed', { projectId: 'revoked' });

expect(client.disconnect).toHaveBeenCalledWith(true);
expect(client.emit).not.toHaveBeenCalled();
});

it('emits opaque Team invalidations without cross-user payload metadata', async () => {
const { owner, other } = await fixture();
const ownerClient = socket(await login(ctx.http, owner.email));
const otherClient = socket(await login(ctx.http, other.email));
await gateway.handleConnection(ownerClient);
await gateway.handleConnection(otherClient);

await gateway.broadcast('request:transitioned', {
id: 'private-request',
employeeId: owner.id,
workflowState: 'PendingManager',
actorId: owner.id,
});

for (const client of [ownerClient, otherClient]) {
expect(client.emit).toHaveBeenCalledWith('request:transitioned');
expect(client.emit).not.toHaveBeenCalledWith(
'request:transitioned',
expect.anything(),
);
}
});
});
51 changes: 46 additions & 5 deletions apps/api/src/app/events/events.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { InstallationService } from '../installation/installation.service';
interface AuthorizedSocket {
client: Socket;
employeeId: string;
sessionId: string | null;
authVersion: number;
expiresAt: number;
expiryTimer: ReturnType<typeof setTimeout>;
Expand Down Expand Up @@ -62,11 +63,23 @@ export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
) {
throw new Error('Invalid access token');
}
const employee = await this.prisma.employee.findUnique({
where: { id: payload.sub },
});
const [employee, session] = await Promise.all([
this.prisma.employee.findUnique({ where: { id: payload.sub } }),
payload.sid
? this.prisma.authSession.findFirst({
where: {
id: payload.sid,
employeeId: payload.sub,
revokedAt: null,
expiresAt: { gt: new Date() },
},
select: { id: true },
})
: Promise.resolve(null),
]);
if (!employee?.isActive || employee.authVersion !== (payload.ver ?? 0))
throw new Error('Session no longer valid');
if (payload.sid && !session) throw new Error('Session no longer valid');
await this.installation.assertActorAccess(employee.id);
if (await this.installation.isSolo())
await this.installation.requireOwner(employee.id);
Expand All @@ -89,6 +102,7 @@ export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
this.connections.set(client.id, {
client,
employeeId: employee.id,
sessionId: payload.sid ?? null,
authVersion: employee.authVersion,
expiresAt,
expiryTimer,
Expand Down Expand Up @@ -124,7 +138,10 @@ export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
? payload.employeeId
: undefined;
if (ownerId && subject !== undefined && subject !== ownerId) continue;
if (client.connected) client.emit(event, payload);
// The web client treats realtime messages only as cache invalidations.
// Keep the payload server-side for recipient checks, but never disclose
// time-entry, request, employee, or actor metadata on the event channel.
if (client.connected) client.emit(event);
}
}

Expand All @@ -133,7 +150,14 @@ export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
const connections = [...this.connections.values()];
if (!connections.length) return [];
try {
const [settings, employees] = await Promise.all([
const sessionIds = [
...new Set(
connections
.map((connection) => connection.sessionId)
.filter((id): id is string => id !== null),
),
];
const [settings, employees, sessions] = await Promise.all([
this.installation.getSettings(),
this.prisma.employee.findMany({
where: {
Expand All @@ -153,16 +177,33 @@ export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
role: true,
},
}),
sessionIds.length
? this.prisma.authSession.findMany({
where: {
id: { in: sessionIds },
revokedAt: null,
expiresAt: { gt: new Date() },
},
select: { id: true, employeeId: true },
})
: Promise.resolve([]),
]);
const byId = new Map(
employees.map((employee) => [employee.id, employee]),
);
const validSessions = new Set(
sessions.map((session) => `${session.id}:${session.employeeId}`),
);
const recipients: Socket[] = [];
for (const connection of connections) {
const employee = byId.get(connection.employeeId);
if (
!employee?.isActive ||
employee.authVersion !== connection.authVersion ||
(connection.sessionId !== null &&
!validSessions.has(
`${connection.sessionId}:${connection.employeeId}`,
)) ||
connection.expiresAt <= Date.now() ||
(settings.mode === 'Solo' &&
(settings.ownerEmployeeId !== employee.id ||
Expand Down