Skip to content
Merged
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
63 changes: 10 additions & 53 deletions apps/backend/src/lib/eventEnvelope.ts
Original file line number Diff line number Diff line change
@@ -1,55 +1,12 @@
import { randomUUID } from 'node:crypto';
import { z } from 'zod';

// Central registry of all valid socket event types.
export const KNOWN_EVENT_TYPES = new Set([
// Inbound (client → server)
'join_room',
'send_message',
'message_history',
'delete_message',
'message_read',
'create_conversation',
'typing_start',
'typing_stop',
'ask_assistant',
'resume',
'join_device_channel',
// Outbound (server → client) — registered so the registry is the single source of truth
'room_joined',
'new_message',
'message_ack',
'message_deleted',
'read_receipt',
'conversation_created',
'ephemeral_replay',
'resume_complete',
'device_envelope',
'error',
]);

export const EventEnvelopeSchema = z.object({
eventId: z.string().min(1, 'eventId is required'),
type: z.string().min(1, 'type is required'),
timestamp: z.number().int().positive('timestamp must be a positive integer'),
payload: z.record(z.string(), z.unknown()).optional().default({}),
});

export declare const KNOWN_EVENT_TYPES: Set<string>;
export declare const EventEnvelopeSchema: z.ZodObject<{
eventId: z.ZodString;
type: z.ZodString;
timestamp: z.ZodNumber;
payload: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
}, z.core.$strip>;
export type EventEnvelope = z.infer<typeof EventEnvelopeSchema>;

export function isKnownEventType(type: string): boolean {
return KNOWN_EVENT_TYPES.has(type);
}

export function createEnvelope(
type: string,
payload: Record<string, unknown>,
eventId?: string,
): EventEnvelope {
return {
eventId: eventId ?? randomUUID(),
type,
timestamp: Date.now(),
payload,
};
}
export declare function isKnownEventType(type: string): boolean;
export declare function createEnvelope(type: string, payload: Record<string, unknown>, eventId?: string): EventEnvelope;
//# sourceMappingURL=eventEnvelope.d.ts.map
1 change: 1 addition & 0 deletions apps/backend/src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export async function requireAuth(
return;
}


req.auth = payload;
next();
}
1 change: 1 addition & 0 deletions apps/backend/src/middleware/socketAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export async function socketAuthMiddleware(
return;
}


socket.auth = payload;
socket.identityPublicKey = device.identityPublicKey;
next();
Expand Down
45 changes: 42 additions & 3 deletions apps/backend/src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import rateLimit, { type RateLimitRequestHandler } from 'express-rate-limit';
import { Keypair } from '@stellar/stellar-sdk';
import { db } from '../db/index.js';
import { users, wallets, devices } from '../db/schema.js';
import { users, wallets, devices, userDevices } from '../db/schema.js';
import { eq, and } from 'drizzle-orm';
import { createNonce, consumeNonce } from '../lib/nonce.js';
import { signToken } from '../lib/jwt.js';
Expand Down Expand Up @@ -57,6 +57,9 @@
verifyLimiter,
validate(VerifySchema),
async (req: Request, res: Response) => {

const { walletAddress, signature, nonce, identityPublicKey, deviceId: clientDeviceId, deviceName, platform, registrationId } = req.body as VerifyBody;

Check failure on line 61 in apps/backend/src/routes/auth.ts

View workflow job for this annotation

GitHub Actions / build

This assigned value is not used in subsequent statements

Check failure on line 61 in apps/backend/src/routes/auth.ts

View workflow job for this annotation

GitHub Actions / build

This assigned value is not used in subsequent statements

Check failure on line 61 in apps/backend/src/routes/auth.ts

View workflow job for this annotation

GitHub Actions / build

This assigned value is not used in subsequent statements

Check failure on line 61 in apps/backend/src/routes/auth.ts

View workflow job for this annotation

GitHub Actions / build

This assigned value is not used in subsequent statements

Check failure on line 61 in apps/backend/src/routes/auth.ts

View workflow job for this annotation

GitHub Actions / build

This assigned value is not used in subsequent statements

Check failure on line 61 in apps/backend/src/routes/auth.ts

View workflow job for this annotation

GitHub Actions / build

This assigned value is not used in subsequent statements

Check failure on line 61 in apps/backend/src/routes/auth.ts

View workflow job for this annotation

GitHub Actions / build

This assigned value is not used in subsequent statements

const {
walletAddress,
signature,
Expand All @@ -67,6 +70,7 @@
registrationId,
} = req.body as VerifyBody;


// Validate and consume nonce
const valid = consumeNonce(walletAddress, nonce);
if (!valid) {
Expand Down Expand Up @@ -159,7 +163,42 @@
deviceId = newDevice.id;
}

const token = signToken({ userId, walletAddress, deviceId });
res.json({ token });
let tokenDeviceId = deviceId;

if (clientDeviceId) {
const [userDevice] = await db
.insert(userDevices)
.values({
userId,
deviceId: clientDeviceId,
deviceName: deviceName ?? 'Web browser',
platform: platform ?? 'web',
identityPublicKey,
registrationId: registrationId ? Number(registrationId) : null,
lastSeenAt: new Date(),
})
.onConflictDoUpdate({
target: [userDevices.userId, userDevices.deviceId],
set: {
deviceName: deviceName ?? 'Web browser',
platform: platform ?? 'web',
identityPublicKey,
registrationId: registrationId ? Number(registrationId) : null,
lastSeenAt: new Date(),
revokedAt: null,
},
})
.returning({ id: userDevices.id });

if (!userDevice) {
res.status(500).json({ error: 'Failed to register messaging device' });
return;
}

tokenDeviceId = userDevice.id;
}

const token = signToken({ userId, walletAddress, deviceId: tokenDeviceId });
res.json({ token, deviceId: tokenDeviceId });
},
);
7 changes: 6 additions & 1 deletion apps/backend/src/routes/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,12 @@ messagesRouter.post('/', validate(SendMessageSchema), async (req: AuthRequest, r
};

// ── content-type-specific validation ──────────────────────────────────────
const validation = validateMessagePayload({ contentType, ciphertext, envelopes, fileId });
const validation = validateMessagePayload({
...(contentType !== undefined ? { contentType } : {}),
...(ciphertext !== undefined ? { ciphertext } : {}),
...(envelopes !== undefined ? { envelopes } : {}),
...(fileId !== undefined ? { fileId } : {}),
});
if (!validation.ok) {
res.status(validation.code).json({ error: validation.message });
return;
Expand Down
3 changes: 3 additions & 0 deletions apps/backend/src/routes/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@ syncRouter.get('/', async (req: AuthRequest, res) => {
id: r.id,
messageId: r.messageId,
conversationId: r.conversationId,
senderId: r.senderId,
senderDeviceId: r.senderDeviceId,
contentType: r.contentType,
ciphertext: r.ciphertext,
sequenceNumber: r.sequenceNumber,
senderId: r.senderId,
Expand Down
21 changes: 21 additions & 0 deletions apps/backend/src/schemas/auth.schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ export const ChallengeSchema = z.object({
walletAddress: z.string().min(1, 'walletAddress is required'),
});

const DeviceRegistrationSchema = z.object({
deviceId: z.string().min(1, 'deviceId is required').optional(),
deviceName: z.string().min(1, 'deviceName is required').optional(),
platform: z.enum(['web', 'ios', 'android']).optional(),
registrationId: z.string().optional(),
});

export const DeviceSchema = z.object({
deviceId: z.string().min(1, 'deviceId is required'),
deviceName: z.string().min(1, 'deviceName is required'),
Expand All @@ -13,6 +20,19 @@ export const DeviceSchema = z.object({
registrationId: z.string().optional(),
});


export const VerifySchema = z
.object({
walletAddress: z.string().min(1, 'walletAddress is required'),
signature: z.string().min(1, 'signature is required'),
nonce: z.string().min(1, 'nonce is required'),
/**
* Base64-encoded Ed25519 SPKI DER identity public key (44 bytes).
* Validated for correct base64 and exact byte length before any crypto operation.
*/
identityPublicKey: IdentityPublicKeySchema,
})
.merge(DeviceRegistrationSchema);
export const VerifySchema = z.object({
walletAddress: z.string().min(1, 'walletAddress is required'),
signature: z.string().min(1, 'signature is required'),
Expand All @@ -27,6 +47,7 @@ export const VerifySchema = z.object({
registrationId: z.number().int().nonnegative().optional(),
});


export type ChallengeBody = z.infer<typeof ChallengeSchema>;
export type DeviceBody = z.infer<typeof DeviceSchema>;
export type VerifyBody = z.infer<typeof VerifySchema>;
105 changes: 103 additions & 2 deletions apps/backend/src/socket/messaging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,17 @@ export function registerMessagingHandlers(io: Server, socket: AuthSocket): void
const effectiveCiphertext = ciphertext ?? content ?? undefined;

const validation = validateMessagePayload({

...(contentType !== undefined ? { contentType } : {}),
...(effectiveCiphertext !== undefined ? { ciphertext: effectiveCiphertext } : {}),
...(envelopes !== undefined ? { envelopes } : {}),
...(fileId !== undefined ? { fileId } : {}),

contentType,
ciphertext: effectiveCiphertext,
envelopes,
fileId: payloadFileId,

});
if (!validation.ok) {
socket.emit('error', {
Expand Down Expand Up @@ -176,15 +183,32 @@ export function registerMessagingHandlers(io: Server, socket: AuthSocket): void
let fileId: string | undefined = payloadFileId;
const resolvedContentType = contentType || 'text/plain';
if (FILE_CONTENT_TYPES.has(resolvedContentType)) {

const [fileRow] = await db
.insert(files)
.values({ storageKey: messageId })
.onConflictDoUpdate({ target: files.storageKey, set: { storageKey: messageId } })
.returning({ id: files.id });

persistedFileId = fileRow?.id;

fileId = fileRow?.id ?? payloadFileId;

}

let message;
const [message] = await db
.insert(messages)
.values({
id: messageId,
conversationId,
senderId: userId,
senderDeviceId: deviceId,
contentType: resolvedContentType,
ciphertext: effectiveCiphertext,
fileId: persistedFileId ?? null,
})
.returning();

let recipientDeviceIds: string[] = [];
try {
message = await db.transaction(async (tx) => {
Expand Down Expand Up @@ -267,8 +291,20 @@ export function registerMessagingHandlers(io: Server, socket: AuthSocket): void
}
}

if (!message) {
socket.emit('error', { event: 'send_message', message: 'Failed to persist message' });
return;
}

if (message) {
await deliverMessage(io, message, conversationId);
}

socket.emit('message_ack', { messageId, sequenceNumber: message.sequenceNumber });

await deliverMessage(io, message, conversationId);


const members = await db.query.conversationMembers.findMany({
where: eq(conversationMembers.conversationId, conversationId),
columns: { userId: true },
Expand Down Expand Up @@ -695,7 +731,7 @@ export function registerMessagingHandlers(io: Server, socket: AuthSocket): void
),
);

io.to(conversationId).volatile.emit('read_receipt', { userId, lastReadMessageId });
io.to(conversationId).volatile.emit('read_receipt', { conversationId, userId, lastReadMessageId });

if (redis) {
const members = await db.query.conversationMembers.findMany({
Expand All @@ -710,6 +746,71 @@ export function registerMessagingHandlers(io: Server, socket: AuthSocket): void
}
});

// ── message_delivered ──────────────────────────────────────────────────────
dispatcher.register('message_delivered', async (payload) => {
const { conversationId, messageId, envelopeId, sequenceNumber } = payload as {
conversationId?: string;
messageId?: string;
envelopeId?: string;
sequenceNumber?: number;
};

if (!conversationId || !messageId) {
socket.emit('error', {
event: 'message_delivered',
message: 'conversationId and messageId are required',
});
return;
}

const membership = await db.query.conversationMembers.findFirst({
where: and(
eq(conversationMembers.conversationId, conversationId),
eq(conversationMembers.userId, userId),
),
});

if (!membership) {
socket.emit('error', { event: 'message_delivered', message: 'Not a member of this conversation' });
return;
}

await db
.update(messageEnvelopes)
.set({ deliveredAt: new Date() })
.where(
and(
eq(messageEnvelopes.messageId, messageId),
eq(messageEnvelopes.recipientDeviceId, socket.auth!.deviceId),
),
);

io.to(conversationId).volatile.emit('delivery_receipt', {
conversationId,
messageId,
envelopeId,
userId,
deviceId: socket.auth!.deviceId,
sequenceNumber,
deliveredAt: new Date().toISOString(),
});

if (redis) {
const members = await db.query.conversationMembers.findMany({
where: eq(conversationMembers.conversationId, conversationId),
columns: { userId: true },
});
await publishEphemeral(
redis,
members.map((member) => member.userId),
{
type: 'delivery_receipt',
data: { conversationId, messageId, envelopeId, userId, deviceId: socket.auth!.deviceId, sequenceNumber },
},
);
}
});

// ── resume ─────────────────────────────────────────────────────────────────
dispatcher.register('resume', async (payload) => {
if (!redis) {
Expand Down
Loading
Loading