Add sender_did to chat messages and new chat tables

Introduces a migration to add a sender_did column to the chat_messages table and creates new tables for chat_device_bundles, chat_inbox, and chat_one_time_keys. Updates related API routes and adds a script for sender DID migration. These changes support device-based messaging and improved chat security.
This commit is contained in:
Christopher
2026-01-27 21:57:33 -08:00
parent 3c7937312d
commit c8e4dedd61
8 changed files with 4885 additions and 15 deletions
@@ -0,0 +1,43 @@
CREATE TABLE "chat_device_bundles" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" uuid NOT NULL,
"did" text NOT NULL,
"device_id" text NOT NULL,
"identity_key" text NOT NULL,
"signed_pre_key" text NOT NULL,
"signature" text NOT NULL,
"last_seen_at" timestamp DEFAULT now() NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "chat_inbox" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"recipient_did" text NOT NULL,
"recipient_device_id" text,
"sender_did" text NOT NULL,
"envelope_json" text NOT NULL,
"is_read" boolean DEFAULT false NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"expires_at" timestamp NOT NULL
);
--> statement-breakpoint
CREATE TABLE "chat_one_time_keys" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" uuid NOT NULL,
"bundle_id" uuid NOT NULL,
"key_id" integer NOT NULL,
"public_key" text NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "chat_messages" ADD COLUMN "sender_did" text;--> statement-breakpoint
ALTER TABLE "chat_device_bundles" ADD CONSTRAINT "chat_device_bundles_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "chat_one_time_keys" ADD CONSTRAINT "chat_one_time_keys_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "chat_one_time_keys" ADD CONSTRAINT "chat_one_time_keys_bundle_id_chat_device_bundles_id_fk" FOREIGN KEY ("bundle_id") REFERENCES "public"."chat_device_bundles"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "chat_bundles_user_idx" ON "chat_device_bundles" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "chat_bundles_did_idx" ON "chat_device_bundles" USING btree ("did");--> statement-breakpoint
CREATE UNIQUE INDEX "chat_bundles_device_unique" ON "chat_device_bundles" USING btree ("user_id","device_id");--> statement-breakpoint
CREATE INDEX "chat_inbox_recipient_idx" ON "chat_inbox" USING btree ("recipient_did","recipient_device_id");--> statement-breakpoint
CREATE INDEX "chat_inbox_created_idx" ON "chat_inbox" USING btree ("created_at");--> statement-breakpoint
CREATE INDEX "chat_otk_bundle_idx" ON "chat_one_time_keys" USING btree ("bundle_id");--> statement-breakpoint
CREATE UNIQUE INDEX "chat_otk_unique" ON "chat_one_time_keys" USING btree ("bundle_id","key_id");
File diff suppressed because it is too large Load Diff
+7
View File
@@ -71,6 +71,13 @@
"when": 1769562092857, "when": 1769562092857,
"tag": "0009_sweet_chat", "tag": "0009_sweet_chat",
"breakpoints": true "breakpoints": true
},
{
"idx": 10,
"version": "7",
"when": 1769579537338,
"tag": "0010_add_sender_did_to_chat_messages",
"breakpoints": true
} }
] ]
} }
+9
View File
@@ -0,0 +1,9 @@
import { db } from '../src/db';
async function main() {
await db.execute(`ALTER TABLE chat_messages ADD COLUMN IF NOT EXISTS sender_did text;`);
console.log('Added sender_did column to chat_messages');
process.exit(0);
}
main();
+8 -1
View File
@@ -128,13 +128,20 @@ export async function POST(request: NextRequest) {
const localDomain = process.env.NEXT_PUBLIC_NODE_DOMAIN || 'localhost'; const localDomain = process.env.NEXT_PUBLIC_NODE_DOMAIN || 'localhost';
const swarmMessageId = `swarm:${localDomain}:${messageId}`; const swarmMessageId = `swarm:${localDomain}:${messageId}`;
// Store full envelope data for decryption
const envelopeData = {
did: user.did,
handle: user.handle,
ciphertext: ciphertext
};
const [newMessage] = await db.insert(chatMessages).values({ const [newMessage] = await db.insert(chatMessages).values({
conversationId: conversation.id, conversationId: conversation.id,
senderHandle: user.handle, senderHandle: user.handle,
senderDisplayName: user.displayName, senderDisplayName: user.displayName,
senderAvatarUrl: user.avatarUrl, senderAvatarUrl: user.avatarUrl,
senderNodeDomain: null, // Local sender senderNodeDomain: null, // Local sender
encryptedContent: ciphertext, encryptedContent: JSON.stringify(envelopeData), // Full envelope
senderChatPublicKey: null, // V2 E2E - keys are in the envelope senderChatPublicKey: null, // V2 E2E - keys are in the envelope
swarmMessageId, swarmMessageId,
deliveredAt: null, // Will update when remote confirms deliveredAt: null, // Will update when remote confirms
+8 -1
View File
@@ -95,6 +95,13 @@ export async function POST(request: NextRequest) {
} }
// Store message reference so it appears in UI // Store message reference so it appears in UI
// Store full envelope data as JSON so we can decrypt later
const envelopeData = {
did: body.did,
handle: body.handle,
ciphertext: body.data.ciphertext
};
const messageId = crypto.randomUUID(); const messageId = crypto.randomUUID();
await db.insert(chatMessages).values({ await db.insert(chatMessages).values({
conversationId: conversation.id, conversationId: conversation.id,
@@ -102,7 +109,7 @@ export async function POST(request: NextRequest) {
senderDisplayName: null, // Unknown until decrypted senderDisplayName: null, // Unknown until decrypted
senderAvatarUrl: null, senderAvatarUrl: null,
senderNodeDomain: body.did?.split(':')[2] || null, senderNodeDomain: body.did?.split(':')[2] || null,
encryptedContent: ciphertext, encryptedContent: JSON.stringify(envelopeData), // Full envelope for decryption
senderChatPublicKey: null, senderChatPublicKey: null,
swarmMessageId: `swarm:v2:${messageId}`, swarmMessageId: `swarm:v2:${messageId}`,
deliveredAt: new Date(), deliveredAt: new Date(),
+1 -1
View File
@@ -115,7 +115,7 @@ export async function GET(request: NextRequest) {
// - Received messages: need sender's public key // - Received messages: need sender's public key
senderPublicKey: senderPubKey, senderPublicKey: senderPubKey,
isE2E: !!msg.senderChatPublicKey || (isSentByMe && !!recipientPublicKey), isE2E: !!msg.senderChatPublicKey || (isSentByMe && !!recipientPublicKey),
encryptedContent: msg.encryptedContent, encryptedContent: msg.encryptedContent, // This is now the full envelope JSON
deliveredAt: msg.deliveredAt, deliveredAt: msg.deliveredAt,
readAt: msg.readAt, readAt: msg.readAt,
createdAt: msg.createdAt, createdAt: msg.createdAt,
+16 -12
View File
@@ -207,19 +207,23 @@ export default function ChatPage() {
// return { ...msg, decryptedContent: '[Sent Message]' }; // return { ...msg, decryptedContent: '[Sent Message]' };
} }
// Attempt decrypt // encryptedContent is now the full envelope JSON
const envelopeMock = {
did: msg.senderDid || 'unknown', // We need this!
data: {
ciphertext: msg.encryptedContent
}
};
// If it's V2, this should work.
if (msg.encryptedContent && msg.encryptedContent.startsWith('{')) { if (msg.encryptedContent && msg.encryptedContent.startsWith('{')) {
const dec = await decryptMessage(envelopeMock); try {
if (!dec.startsWith('[')) { const envelope = JSON.parse(msg.encryptedContent);
return { ...msg, decryptedContent: dec }; // envelope contains { did, handle, ciphertext }
const envelopeMock = {
did: envelope.did,
data: {
ciphertext: envelope.ciphertext
}
};
const dec = await decryptMessage(envelopeMock);
if (!dec.startsWith('[')) {
return { ...msg, decryptedContent: dec };
}
} catch (e) {
console.error('[Chat] Failed to parse envelope:', e);
} }
} }