feat(demo): P2.7 Vite React two-pane realtime demo + dev token endpoint (P2 complete)
apps/message-demo: Alice creates a thread, Bob joins; live two-way chat, typing, read receipts (useMessages now exposes reads[]). Dev-only /v1/dev/token endpoint (gated by IIOS_DEV_TOKENS) so the browser can auth. .env autoloaded (dotenv). Realtime smoke script passes end-to-end (message + unread + receipt). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -22,6 +22,7 @@
|
||||
"socket.io": "^4.8.3",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"dotenv": "^16.4.7",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.2"
|
||||
@@ -34,6 +35,7 @@
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/node": "^26.0.1",
|
||||
"prisma": "^6.2.1",
|
||||
"socket.io-client": "^4.8.3",
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
// P2 realtime smoke: two socket.io clients (Alice, Bob) on one thread.
|
||||
// Requires the service running with IIOS_DEV_TOKENS=1 + APP_SECRETS set.
|
||||
// Run: node scripts/smoke-realtime.mjs
|
||||
import 'dotenv/config';
|
||||
import { io } from 'socket.io-client';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const SERVICE = process.env.SMOKE_URL ?? 'http://localhost:3200';
|
||||
const APP_ID = 'portal-demo';
|
||||
const SECRET = JSON.parse(process.env.APP_SECRETS ?? '{"portal-demo":"dev-secret"}')[APP_ID];
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
const sign = (userId) =>
|
||||
jwt.sign({ sub: userId, name: userId, appId: APP_ID, orgId: `org_${APP_ID}` }, SECRET, {
|
||||
algorithm: 'HS256',
|
||||
expiresIn: '1h',
|
||||
});
|
||||
|
||||
const connect = (userId) =>
|
||||
io(`${SERVICE}/message`, { auth: { token: sign(userId) }, transports: ['websocket'], forceNew: true });
|
||||
|
||||
const once = (socket, event) => new Promise((res) => socket.once(event, res));
|
||||
const assert = (cond, msg) => {
|
||||
if (!cond) {
|
||||
console.error('✗', msg);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('✓', msg);
|
||||
};
|
||||
|
||||
async function unread(threadId, userId) {
|
||||
const handle = await prisma.iiosSourceHandle.findFirst({ where: { externalId: userId } });
|
||||
if (!handle) return 0;
|
||||
const actor = await prisma.iiosActorRef.findFirst({ where: { sourceHandleId: handle.id } });
|
||||
if (!actor) return 0;
|
||||
const c = await prisma.iiosUnreadCounter.findUnique({
|
||||
where: { threadId_actorId: { threadId, actorId: actor.id } },
|
||||
});
|
||||
return c?.unreadCount ?? 0;
|
||||
}
|
||||
|
||||
const alice = connect('alice');
|
||||
const bob = connect('bob');
|
||||
|
||||
try {
|
||||
// Alice creates a thread; Bob joins it.
|
||||
const opened = await alice.emitWithAck('open_thread', {});
|
||||
const threadId = opened.threadId;
|
||||
assert(!!threadId, `Alice created thread ${threadId}`);
|
||||
await bob.emitWithAck('open_thread', { threadId });
|
||||
|
||||
// Alice sends; Bob should receive it live.
|
||||
const bobGetsMessage = once(bob, 'message');
|
||||
const sent = await alice.emitWithAck('send_message', { threadId, content: 'hi bob' });
|
||||
const received = await bobGetsMessage;
|
||||
assert(received.content === 'hi bob', `Bob received "${received.content}" in realtime`);
|
||||
assert((await unread(threadId, 'bob')) === 1, "Bob's unread = 1");
|
||||
|
||||
// Bob reads; Alice should get the receipt; Bob's unread resets.
|
||||
const aliceGetsReceipt = once(alice, 'receipt');
|
||||
await bob.emitWithAck('read', { threadId, interactionId: sent.id });
|
||||
const receipt = await aliceGetsReceipt;
|
||||
assert(receipt.kind === 'READ' && receipt.interactionId === sent.id, 'Alice received READ receipt');
|
||||
assert((await unread(threadId, 'bob')) === 0, "Bob's unread reset to 0");
|
||||
|
||||
console.log('\nP2 realtime smoke: PASS');
|
||||
} finally {
|
||||
alice.close();
|
||||
bob.close();
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
process.exit(0);
|
||||
@@ -6,9 +6,10 @@ import { OutboxModule } from './outbox/outbox.module';
|
||||
import { ThreadsModule } from './threads/threads.module';
|
||||
import { MessageModule } from './messaging/message.module';
|
||||
import { HealthController } from './health.controller';
|
||||
import { DevController } from './dev/dev.controller';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, PlatformModule, InteractionsModule, OutboxModule, ThreadsModule, MessageModule],
|
||||
controllers: [HealthController],
|
||||
controllers: [HealthController, DevController],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { BadRequestException, Body, Controller, ForbiddenException, Post } from '@nestjs/common';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
/**
|
||||
* Dev-only helper: mints an HS256 token a host app would normally sign, so the
|
||||
* browser demo can authenticate. Gated by IIOS_DEV_TOKENS=1 — never enable in
|
||||
* production (the host app signs its own tokens there).
|
||||
*/
|
||||
@Controller('v1/dev')
|
||||
export class DevController {
|
||||
@Post('token')
|
||||
token(@Body() body: { appId: string; userId: string; name?: string; orgId?: string }): { token: string } {
|
||||
if (process.env.IIOS_DEV_TOKENS !== '1') throw new ForbiddenException('dev tokens disabled');
|
||||
let secrets: Record<string, string>;
|
||||
try {
|
||||
secrets = JSON.parse(process.env.APP_SECRETS ?? '{}');
|
||||
} catch {
|
||||
secrets = {};
|
||||
}
|
||||
const secret = secrets[body.appId];
|
||||
if (!secret) throw new BadRequestException(`unknown app: ${body.appId}`);
|
||||
const token = jwt.sign(
|
||||
{ sub: body.userId, name: body.name ?? body.userId, appId: body.appId, orgId: body.orgId ?? `org_${body.appId}` },
|
||||
secret,
|
||||
{ algorithm: 'HS256', expiresIn: '2h' },
|
||||
);
|
||||
return { token };
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dotenv/config';
|
||||
import 'reflect-metadata';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
|
||||
Reference in New Issue
Block a user