Repository Public
1import type { FastifyInstance } from "fastify"2import crypto from "node:crypto"3import { z } from "zod"4import { config } from "./config.js"5import { sql } from "./db.js"6import { hub, memberIds, peersOf } from "./hub.js"7import { requireDevice, requireSession, requireUser } from "./session.js"8import { audit, b64, bad, limitReq, parse, rateLimit, unb64, uuidBytes, zB64, zUuid } from "./util.js"910const ed25519Spki = Buffer.from("302a300506032b6570032100", "hex")11function verifyEd25519(publicKey: Buffer, message: Buffer, signature: Buffer): boolean {12 try {13 const key = crypto.createPublicKey({ key: Buffer.concat([ed25519Spki, publicKey]), format: "der", type: "spki" })14 return crypto.verify(null, message, key, signature)15 } catch {16 return false17 }18}19/** Byte string a device certificate signs. Must match web/src/core/identity.ts. */20export function certMessage(userId: string, deviceId: string, signatureKey: Buffer) {21 return Buffer.concat([Buffer.from("spm-device-cert-v1"), uuidBytes(userId), uuidBytes(deviceId), signatureKey])22}2324const zKey32 = zB64(64)25const deviceOut = (d: Record<string, unknown>) => ({26 id: d.id,27 user_id: d.user_id,28 label: d.label,29 status: d.status,30 signature_key: b64(d.signature_key as Buffer),31 cert: d.cert ? b64(d.cert as Buffer) : null,32})3334async function directoryFor(userIds: string[]) {35 if (!userIds.length) return []36 const users = await sql`select id, handle, display_name, status, identity_key, presence_opt_in from users where id in ${sql(userIds)}`37 const devices = await sql`select id, user_id, label, status, signature_key, cert from devices where user_id in ${sql(userIds)} and status = 'active'`38 return users.map((u) => ({39 id: u.id,40 handle: u.handle,41 display_name: u.display_name,42 status: u.status,43 identity_key: u.identity_key ? b64(u.identity_key) : null,44 online: u.presence_opt_in ? hub.online(u.id) : null,45 devices: devices.filter((d) => d.user_id === u.id).map(deviceOut),46 }))47}4849async function assertMember(conversationId: string, userId: string) {50 const [m] = await sql`select role from conversation_members where conversation_id = ${conversationId} and user_id = ${userId} and left_at is null`51 if (!m) throw bad("not_a_member", 403)52 return m.role as "owner" | "member"53}5455export function messagingRoutes(app: FastifyInstance) {56 // ================= identity & devices =================5758 /** First device: publishes the account identity key and its own certificate in one step. */59 app.post("/api/identity", async (req) => {60 const a = await requireSession(req)61 const body = parse(62 z.object({ identity_key: zKey32, device_id: zUuid, label: z.string().trim().min(1).max(60), signature_key: zKey32, cert: zB64(128), backup: zB64(4096) }),63 req.body,64 )65 const ik = unb64(body.identity_key), sk = unb64(body.signature_key), cert = unb64(body.cert)66 if (ik.length !== 32 || sk.length !== 32) throw bad("invalid_key")67 if (!verifyEd25519(ik, certMessage(a.userId, body.device_id, sk), cert)) throw bad("invalid_certificate")68 await sql.begin(async (tx) => {69 const r = await tx`update users set identity_key = ${ik}, identity_set_at = now() where id = ${a.userId} and identity_key is null returning 1`70 if (!r.length) throw bad("identity_exists", 409)71 await tx`insert into devices (id, user_id, label, signature_key, cert, status, enrolled_via) values (${body.device_id}, ${a.userId}, ${body.label}, ${sk}, ${cert}, 'active', 'first')`72 await tx`insert into key_backups (user_id, blob) values (${a.userId}, ${unb64(body.backup)}) on conflict (user_id) do update set blob = excluded.blob, updated_at = now()`73 await tx`update sessions set device_id = ${body.device_id} where id = ${a.sessionId}`74 })75 hub.bindDevice(a.sessionId, body.device_id)76 await audit(req, a.userId, "identity.create", body.device_id)77 hub.toUsers(await peersOf(a.userId), { t: "directory", user: a.userId })78 return { ok: true }79 })8081 /** Additional device, step 1: registers as pending and waits for approval or proves the recovery key. */82 app.post("/api/devices", async (req) => {83 const a = await requireSession(req)84 const body = parse(85 z.object({ device_id: zUuid, label: z.string().trim().min(1).max(60), signature_key: zKey32, link_pub: zKey32.optional(), cert: zB64(128).optional() }),86 req.body,87 )88 const [u] = await sql`select identity_key from users where id = ${a.userId}`89 if (!u.identity_key) throw bad("no_identity", 409)90 const sk = unb64(body.signature_key)91 const [{ n }] = await sql`select count(*)::int as n from devices where user_id = ${a.userId} and status <> 'revoked'`92 if (n >= 12) throw bad("too_many_devices", 409)93 if (body.cert) {94 // Recovery path: the device holds the identity key (restored from the recovery key) and certifies itself.95 const cert = unb64(body.cert)96 if (!verifyEd25519(u.identity_key, certMessage(a.userId, body.device_id, sk), cert)) throw bad("invalid_certificate")97 await sql`insert into devices (id, user_id, label, signature_key, cert, status, enrolled_via) values (${body.device_id}, ${a.userId}, ${body.label}, ${sk}, ${cert}, 'active', 'recovery')`98 await sql`update sessions set device_id = ${body.device_id} where id = ${a.sessionId}`99 hub.bindDevice(a.sessionId, body.device_id)100 await audit(req, a.userId, "device.add-recovery", body.device_id, { label: body.label })101 hub.toUsers([...(await peersOf(a.userId)), a.userId], { t: "directory", user: a.userId })102 hub.toUser(a.userId, { t: "device-added", device: body.device_id, label: body.label, via: "recovery" }, body.device_id)103 return { ok: true, status: "active" }104 }105 if (!body.link_pub) throw bad("link_pub_required")106 await sql`delete from devices where user_id = ${a.userId} and status = 'pending' and created_at < now() - interval '1 day'`107 await sql`insert into devices (id, user_id, label, signature_key, link_pub, status) values (${body.device_id}, ${a.userId}, ${body.label}, ${sk}, ${unb64(body.link_pub)}, 'pending')`108 await sql`update sessions set device_id = ${body.device_id} where id = ${a.sessionId}`109 hub.bindDevice(a.sessionId, body.device_id)110 await audit(req, a.userId, "device.request", body.device_id, { label: body.label })111 hub.toUser(a.userId, { t: "device-pending", device: body.device_id }, body.device_id)112 return { ok: true, status: "pending" }113 })114115 app.get("/api/devices", async (req) => {116 const a = await requireSession(req)117 const rows = await sql`select * from devices where user_id = ${a.userId} and status <> 'revoked' order by created_at`118 return rows.map((d) => ({119 ...deviceOut(d),120 enrolled_via: d.enrolled_via,121 created_at: d.created_at,122 last_seen_at: d.last_seen_at,123 link_pub: d.link_pub ? b64(d.link_pub) : null,124 link_payload: d.link_payload ? b64(d.link_payload) : null,125 current: d.id === a.deviceId,126 }))127 })128129 /** Step 2, run on an already trusted device after the person compared the verification code. */130 app.post("/api/devices/:id/approve", async (req) => {131 const a = await requireDevice(req)132 const { id } = parse(z.object({ id: zUuid }), req.params)133 const body = parse(z.object({ cert: zB64(128), link_payload: zB64(2048) }), req.body)134 const [d] = await sql`select signature_key from devices where id = ${id} and user_id = ${a.userId} and status = 'pending'`135 if (!d) throw bad("not_found", 404)136 const [u] = await sql`select identity_key from users where id = ${a.userId}`137 const cert = unb64(body.cert)138 if (!verifyEd25519(u.identity_key, certMessage(a.userId, id, d.signature_key), cert)) throw bad("invalid_certificate")139 await sql`update devices set status = 'active', cert = ${cert}, link_payload = ${unb64(body.link_payload)}, enrolled_via = 'approval' where id = ${id}`140 await audit(req, a.userId, "device.approve", id, { by: a.deviceId })141 hub.toUsers([...(await peersOf(a.userId)), a.userId], { t: "directory", user: a.userId })142 hub.toUser(a.userId, { t: "device-added", device: id, via: "approval" })143 return { ok: true }144 })145146 app.delete("/api/devices/:id", async (req) => {147 const a = await requireSession(req)148 const { id } = parse(z.object({ id: zUuid }), req.params)149 const r = await sql`update devices set status = 'revoked', revoked_at = now(), link_payload = null where id = ${id} and user_id = ${a.userId} and status <> 'revoked' returning 1`150 if (!r.length) throw bad("not_found", 404)151 await sql`delete from key_packages where device_id = ${id}`152 const sessions = await sql`update sessions set revoked_at = now() where device_id = ${id} and revoked_at is null and id <> ${a.sessionId} returning id`153 for (const s of sessions) hub.closeSession(s.id)154 if (a.deviceId === id) await sql`update sessions set device_id = null where id = ${a.sessionId}`155 await audit(req, a.userId, "device.revoke", id)156 hub.toUsers([...(await peersOf(a.userId)), a.userId], { t: "directory", user: a.userId })157 return { ok: true }158 })159160 /** Re-binds a new session to a device that already exists in this browser (proof of possession of its key). */161 app.post("/api/session/device", async (req) => {162 const a = await requireSession(req)163 const body = parse(z.object({ device_id: zUuid, signature: zB64(128) }), req.body)164 const [d] = await sql`select signature_key, status from devices where id = ${body.device_id} and user_id = ${a.userId}`165 if (!d || d.status === "revoked") throw bad("unknown_device", 404)166 const msg = Buffer.concat([Buffer.from("spm-session-bind-v1"), uuidBytes(a.sessionId), uuidBytes(body.device_id)])167 if (!verifyEd25519(d.signature_key, msg, unb64(body.signature))) throw bad("invalid_signature", 403)168 await sql`update sessions set device_id = ${body.device_id} where id = ${a.sessionId}`169 hub.bindDevice(a.sessionId, body.device_id)170 return { ok: true, status: d.status }171 })172173 app.get("/api/backup", async (req) => {174 limitReq(req, "backup", 10)175 const a = await requireSession(req)176 const [b] = await sql`select blob from key_backups where user_id = ${a.userId}`177 if (!b) throw bad("not_found", 404)178 return { blob: b64(b.blob) }179 })180 app.put("/api/backup", async (req) => {181 const a = await requireDevice(req)182 const { blob } = parse(z.object({ blob: zB64(4096) }), req.body)183 await sql`insert into key_backups (user_id, blob) values (${a.userId}, ${unb64(blob)}) on conflict (user_id) do update set blob = excluded.blob, updated_at = now()`184 await audit(req, a.userId, "backup.rotate", a.userId)185 return { ok: true }186 })187188 // ================= key packages =================189 app.post("/api/keypackages", async (req) => {190 const a = await requireDevice(req)191 const body = parse(z.object({ packages: z.array(zB64(8192)).max(100), last_resort: zB64(8192).optional() }), req.body)192 const [{ n: had }] = await sql`select count(*)::int as n from key_packages where device_id = ${a.deviceId}`193 if (had + body.packages.length > 120) throw bad("too_many_key_packages", 409)194 await sql.begin(async (tx) => {195 for (const p of body.packages) await tx`insert into key_packages (device_id, data) values (${a.deviceId}, ${unb64(p)})`196 if (body.last_resort) {197 await tx`delete from key_packages where device_id = ${a.deviceId} and last_resort`198 await tx`insert into key_packages (device_id, data, last_resort) values (${a.deviceId}, ${unb64(body.last_resort)}, true)`199 }200 })201 // A device that just became reachable: members of its conversations can now add it to their groups.202 if (had === 0) hub.toUsers([...(await peersOf(a.userId)), a.userId], { t: "directory", user: a.userId }, a.deviceId)203 return { ok: true }204 })205 app.get("/api/keypackages/count", async (req) => {206 const a = await requireDevice(req)207 const [{ n }] = await sql`select count(*)::int as n from key_packages where device_id = ${a.deviceId} and not last_resort`208 return { count: n }209 })210 /** Hands out one key package per requested device; one-time packages are deleted as they are claimed. */211 app.post("/api/keypackages/claim", async (req) => {212 const a = await requireDevice(req)213 rateLimit(`claim:${a.userId}`, 300, 60_000)214 const { device_ids } = parse(z.object({ device_ids: z.array(zUuid).min(1).max(200) }), req.body)215 const out: { device_id: string; data: string }[] = []216 for (const id of device_ids) {217 const [d] = await sql`select 1 from devices where id = ${id} and status = 'active'`218 if (!d) continue219 const [kp] = await sql`220 delete from key_packages where id = (221 select id from key_packages where device_id = ${id} and not last_resort order by id limit 1 for update skip locked222 ) returning data`223 if (kp) out.push({ device_id: id, data: b64(kp.data) })224 else {225 const [lr] = await sql`select data from key_packages where device_id = ${id} and last_resort`226 if (lr) out.push({ device_id: id, data: b64(lr.data) })227 }228 }229 return out230 })231232 // ================= users =================233 app.post("/api/users/lookup", async (req) => {234 await requireUser(req)235 const { ids } = parse(z.object({ ids: z.array(zUuid).max(500) }), req.body)236 return directoryFor(ids)237 })238239 // ================= sync =================240 app.get("/api/sync", async (req) => {241 const a = await requireDevice(req)242 await sql`update devices set last_seen_at = now() where id = ${a.deviceId}`243 const convs = await sql`244 select c.id, c.kind, c.epoch, c.next_seq - 1 as last_seq, c.created_by, c.created_at,245 coalesce(dc.delivered_seq, 0) as cursor246 from conversations c247 join conversation_members m on m.conversation_id = c.id and m.user_id = ${a.userId} and m.left_at is null248 left join device_cursors dc on dc.conversation_id = c.id and dc.device_id = ${a.deviceId}`249 const ids = convs.map((c) => c.id as string)250 const members = ids.length251 ? await sql`select conversation_id, user_id, role from conversation_members where conversation_id in ${sql(ids)} and left_at is null`252 : []253 const delivered = ids.length254 ? await sql`255 select dc.conversation_id, d.user_id, max(dc.delivered_seq) as seq256 from device_cursors dc join devices d on d.id = dc.device_id257 where dc.conversation_id in ${sql(ids)} group by 1, 2`258 : []259 const resync = ids.length ? await sql`select conversation_id, device_id from resync_requests where conversation_id in ${sql(ids)}` : []260 const welcomes = await sql`select id, conversation_id, after_seq, data from welcomes where device_id = ${a.deviceId} order by id`261 const userIds = new Set<string>([a.userId])262 for (const m of members) userIds.add(m.user_id)263 return {264 conversations: convs.map((c) => ({265 ...c,266 members: members.filter((m) => m.conversation_id === c.id).map((m) => ({ user_id: m.user_id, role: m.role })),267 delivered: Object.fromEntries(delivered.filter((d) => d.conversation_id === c.id).map((d) => [d.user_id, d.seq])),268 resync: resync.filter((r) => r.conversation_id === c.id).map((r) => r.device_id),269 })),270 welcomes: welcomes.map((w) => ({ id: w.id, conversation_id: w.conversation_id, after_seq: w.after_seq, data: b64(w.data) })),271 users: await directoryFor([...userIds]),272 server_time: Date.now(),273 }274 })275276 app.post("/api/welcomes/ack", async (req) => {277 const a = await requireDevice(req)278 const { ids } = parse(z.object({ ids: z.array(z.number().int()).max(500) }), req.body)279 if (ids.length) await sql`delete from welcomes where device_id = ${a.deviceId} and id in ${sql(ids)}`280 return { ok: true }281 })282283 // ================= conversations =================284 const zWelcome = z.object({ device_id: zUuid, data: zB64(1024 * 1024) })285286 app.post("/api/conversations", async (req) => {287 const a = await requireDevice(req)288 rateLimit(`conv:${a.userId}`, 30, 60_000)289 const body = parse(290 z.object({291 id: zUuid,292 kind: z.enum(["dm", "group"]),293 member_ids: z.array(zUuid).max(256),294 client_id: zUuid,295 commit: zB64(2 * 1024 * 1024),296 welcomes: z.array(zWelcome).max(1000),297 }),298 req.body,299 )300 const others = [...new Set(body.member_ids)].filter((u) => u !== a.userId)301 if (body.kind === "dm" && others.length !== 1) throw bad("dm_needs_one_peer")302 if (others.length) {303 const ok = await sql`select id from users where id in ${sql(others)} and status = 'active'`304 if (ok.length !== others.length) throw bad("unknown_member")305 }306 const dmKey = body.kind === "dm" ? [a.userId, others[0]].sort().join(":") : null307 if (dmKey) {308 const [ex] = await sql`select id from conversations where dm_key = ${dmKey}`309 if (ex) throw bad("dm_exists", 409, ex.id)310 }311 await sql.begin(async (tx) => {312 await tx`insert into conversations (id, kind, dm_key, epoch, next_seq, created_by) values (${body.id}, ${body.kind}, ${dmKey}, 1, 2, ${a.userId})`313 await tx`insert into conversation_members (conversation_id, user_id, role) values (${body.id}, ${a.userId}, 'owner')`314 for (const u of others) await tx`insert into conversation_members (conversation_id, user_id, role) values (${body.id}, ${u}, ${body.kind === "dm" ? "owner" : "member"})`315 await tx`insert into messages (conversation_id, seq, sender_user, sender_device, kind, epoch, client_id, data)316 values (${body.id}, 1, ${a.userId}, ${a.deviceId}, 'commit', 0, ${body.client_id}, ${unb64(body.commit)})`317 await tx`insert into device_cursors (device_id, conversation_id, delivered_seq) values (${a.deviceId}, ${body.id}, 1)`318 for (const w of body.welcomes)319 await tx`insert into welcomes (device_id, conversation_id, after_seq, data)320 select d.id, ${body.id}, 1, ${unb64(w.data)} from devices d321 where d.id = ${w.device_id} and d.status = 'active' and d.user_id in ${sql([a.userId, ...others])}`322 })323 hub.toUsers([a.userId, ...others], { t: "welcome", conversation: body.id }, a.deviceId)324 return { ok: true, seq: 1, epoch: 1 }325 })326327 /** A commit advances the group epoch. It is accepted only when it was built on the current epoch. */328 app.post("/api/conversations/:id/commit", async (req) => {329 const a = await requireDevice(req)330 const { id } = parse(z.object({ id: zUuid }), req.params)331 const body = parse(332 z.object({333 epoch: z.number().int().min(0),334 client_id: zUuid,335 commit: zB64(2 * 1024 * 1024),336 welcomes: z.array(zWelcome).max(1000).default([]),337 add_users: z.array(zUuid).max(256).default([]),338 remove_users: z.array(zUuid).max(256).default([]),339 resynced: z.array(zUuid).max(256).default([]),340 }),341 req.body,342 )343 const role = await assertMember(id, a.userId)344 const result = await sql.begin(async (tx) => {345 const [c] = await tx`select kind, epoch, next_seq from conversations where id = ${id} for update`346 if (c.epoch !== body.epoch) return { conflict: true as const, epoch: c.epoch as number }347 if (c.kind === "dm" && (body.add_users.length || body.remove_users.length)) throw bad("dm_membership_fixed", 409)348 if (body.remove_users.length && role !== "owner") throw bad("only_owner_removes", 403)349 if (body.remove_users.includes(a.userId)) throw bad("use_leave", 409)350 if (body.add_users.length) {351 const ok = await tx`select id from users where id in ${sql(body.add_users)} and status = 'active'`352 if (ok.length !== new Set(body.add_users).size) throw bad("unknown_member")353 }354 const seq = c.next_seq as number355 await tx`insert into messages (conversation_id, seq, sender_user, sender_device, kind, epoch, client_id, data)356 values (${id}, ${seq}, ${a.userId}, ${a.deviceId}, 'commit', ${body.epoch}, ${body.client_id}, ${unb64(body.commit)})`357 await tx`update conversations set epoch = epoch + 1, next_seq = next_seq + 1 where id = ${id}`358 for (const u of body.add_users)359 await tx`insert into conversation_members (conversation_id, user_id) values (${id}, ${u})360 on conflict (conversation_id, user_id) do update set left_at = null, joined_at = now(), role = 'member'`361 for (const u of body.remove_users) await tx`update conversation_members set left_at = now() where conversation_id = ${id} and user_id = ${u}`362 const members = (await tx`select user_id from conversation_members where conversation_id = ${id} and left_at is null`).map((r) => r.user_id as string)363 for (const w of body.welcomes)364 await tx`insert into welcomes (device_id, conversation_id, after_seq, data)365 select d.id, ${id}, ${seq}, ${unb64(w.data)} from devices d366 where d.id = ${w.device_id} and d.status = 'active' and d.user_id in ${sql(members)}`367 if (body.resynced.length) await tx`delete from resync_requests where conversation_id = ${id} and device_id in ${sql(body.resynced)}`368 await tx`insert into device_cursors (device_id, conversation_id, delivered_seq) values (${a.deviceId}, ${id}, ${seq})369 on conflict (device_id, conversation_id) do update set delivered_seq = greatest(device_cursors.delivered_seq, excluded.delivered_seq)`370 return { conflict: false as const, seq, members }371 })372 if (result.conflict) throw bad("epoch_conflict", 409, String(result.epoch))373 const envelope = {374 t: "msg", conversation: id, seq: result.seq, kind: "commit", epoch: body.epoch, sender_user: a.userId, sender_device: a.deviceId,375 client_id: body.client_id, data: body.commit, created_at: Date.now(),376 }377 hub.toUsers(result.members, envelope, a.deviceId)378 if (body.welcomes.length) hub.toUsers(result.members, { t: "welcome", conversation: id }, a.deviceId)379 for (const u of body.remove_users) hub.toUser(u, { t: "removed", conversation: id })380 return { ok: true, seq: result.seq, epoch: body.epoch + 1 }381 })382383 app.post("/api/conversations/:id/messages", async (req) => {384 const a = await requireDevice(req)385 rateLimit(`send:${a.deviceId}`, 600, 60_000)386 const { id } = parse(z.object({ id: zUuid }), req.params)387 const body = parse(388 z.object({389 epoch: z.number().int().min(0),390 client_id: zUuid,391 data: zB64(256 * 1024),392 transient: z.boolean().default(false),393 expires_in: z.number().int().min(5).max(366 * 86400).optional(),394 }),395 req.body,396 )397 await assertMember(id, a.userId)398 const result = await sql.begin(async (tx) => {399 const [dup] = await tx`select seq from messages where conversation_id = ${id} and sender_device = ${a.deviceId} and client_id = ${body.client_id}`400 if (dup) return { seq: dup.seq as number, dup: true as const }401 const [c] = await tx`select epoch, next_seq from conversations where id = ${id} for update`402 // Receivers keep keys for a few past epochs only; older ciphertext must be re-encrypted by the sender.403 if (body.epoch > c.epoch || body.epoch < c.epoch - 2) return { stale: true as const, epoch: c.epoch as number }404 const seq = c.next_seq as number405 const expires = body.transient406 ? new Date(Date.now() + config.transientRetentionHours * 3600_000)407 : body.expires_in ? new Date(Date.now() + body.expires_in * 1000) : null408 await tx`insert into messages (conversation_id, seq, sender_user, sender_device, kind, epoch, client_id, data, transient, expires_at)409 values (${id}, ${seq}, ${a.userId}, ${a.deviceId}, 'app', ${body.epoch}, ${body.client_id}, ${unb64(body.data)}, ${body.transient}, ${expires})`410 await tx`update conversations set next_seq = next_seq + 1 where id = ${id}`411 return { seq }412 })413 if ("stale" in result) throw bad("stale_epoch", 409, String(result.epoch))414 if (!("dup" in result)) {415 hub.toUsers(await memberIds(id), {416 t: "msg", conversation: id, seq: result.seq, kind: "app", epoch: body.epoch, sender_user: a.userId, sender_device: a.deviceId,417 client_id: body.client_id, data: body.data, created_at: Date.now(),418 }, a.deviceId)419 }420 return { ok: true, seq: result.seq }421 })422423 app.get("/api/conversations/:id/messages", async (req) => {424 const a = await requireDevice(req)425 const { id } = parse(z.object({ id: zUuid }), req.params)426 const { after } = parse(z.object({ after: z.coerce.number().int().min(0).default(0) }), req.query)427 await assertMember(id, a.userId)428 const rows = await sql`429 select seq, kind, epoch, sender_user, sender_device, client_id, data, created_at from messages430 where conversation_id = ${id} and seq > ${after} and (expires_at is null or expires_at > now())431 order by seq limit 200`432 return rows.map((r) => ({ ...r, data: b64(r.data), created_at: new Date(r.created_at).getTime() }))433 })434435 /** Delivery acknowledgement: metadata only (which device has fetched up to which sequence number). */436 app.post("/api/conversations/:id/ack", async (req) => {437 const a = await requireDevice(req)438 const { id } = parse(z.object({ id: zUuid }), req.params)439 const { seq } = parse(z.object({ seq: z.number().int().min(0) }), req.body)440 await assertMember(id, a.userId)441 const [c] = await sql`select next_seq from conversations where id = ${id}`442 const s = Math.min(seq, c.next_seq - 1)443 const r = await sql`444 insert into device_cursors (device_id, conversation_id, delivered_seq) values (${a.deviceId}, ${id}, ${s})445 on conflict (device_id, conversation_id) do update set delivered_seq = excluded.delivered_seq446 where device_cursors.delivered_seq < excluded.delivered_seq returning 1`447 if (r.length) hub.toUsers(await memberIds(id), { t: "delivered", conversation: id, user: a.userId, seq: s }, a.deviceId)448 return { ok: true }449 })450451 app.post("/api/conversations/:id/leave", async (req) => {452 const a = await requireDevice(req)453 const { id } = parse(z.object({ id: zUuid }), req.params)454 await assertMember(id, a.userId)455 const [c] = await sql`select kind from conversations where id = ${id}`456 if (c.kind === "dm") throw bad("cannot_leave_dm", 409)457 await sql`update conversation_members set left_at = now() where conversation_id = ${id} and user_id = ${a.userId}`458 const rest = await memberIds(id)459 if (rest.length && !(await sql`select 1 from conversation_members where conversation_id = ${id} and left_at is null and role = 'owner'`).length)460 await sql`update conversation_members set role = 'owner' where conversation_id = ${id} and user_id = (461 select user_id from conversation_members where conversation_id = ${id} and left_at is null order by joined_at limit 1)`462 hub.toUsers(rest, { t: "membership", conversation: id })463 hub.toUser(a.userId, { t: "removed", conversation: id })464 return { ok: true }465 })466467 /** A device that lost its group state asks the other members to remove and re-add it. */468 app.post("/api/conversations/:id/resync", async (req) => {469 const a = await requireDevice(req)470 const { id } = parse(z.object({ id: zUuid }), req.params)471 await assertMember(id, a.userId)472 await sql`insert into resync_requests (conversation_id, device_id) values (${id}, ${a.deviceId}) on conflict do nothing`473 hub.toUsers(await memberIds(id), { t: "membership", conversation: id }, a.deviceId)474 return { ok: true }475 })476477 // ================= data synced between a user's own devices (sealed client-side) =================478 app.get("/api/self", async (req) => {479 const a = await requireDevice(req)480 const rows = await sql`select key, data, updated_at from self_blobs where user_id = ${a.userId}`481 return rows.map((r) => ({ key: r.key, data: b64(r.data), updated_at: new Date(r.updated_at).getTime() }))482 })483 app.put("/api/self/:key", async (req) => {484 const a = await requireDevice(req)485 const { key } = parse(z.object({ key: z.string().min(1).max(120) }), req.params)486 const { data } = parse(z.object({ data: zB64(256 * 1024) }), req.body)487 const [{ n }] = await sql`select count(*)::int as n from self_blobs where user_id = ${a.userId}`488 if (n > 200) throw bad("too_many_blobs", 409)489 await sql`insert into self_blobs (user_id, key, data) values (${a.userId}, ${key}, ${unb64(data)})490 on conflict (user_id, key) do update set data = excluded.data, updated_at = now()`491 hub.toUser(a.userId, { t: "self", key }, a.deviceId)492 return { ok: true }493 })494 app.delete("/api/self/:key", async (req) => {495 const a = await requireDevice(req)496 const { key } = parse(z.object({ key: z.string().min(1).max(120) }), req.params)497 await sql`delete from self_blobs where user_id = ${a.userId} and key = ${key}`498 hub.toUser(a.userId, { t: "self", key }, a.deviceId)499 return { ok: true }500 })501502 // ================= TURN credentials (time-limited, HMAC of a shared secret; coturn "use-auth-secret") =================503 app.get("/api/turn", async (req) => {504 const a = await requireDevice(req)505 const ice: { urls: string[]; username?: string; credential?: string }[] = []506 if (config.turnSecret && config.turnUrls.length) {507 const username = `${Math.floor(Date.now() / 1000) + 6 * 3600}:${a.userId}`508 const credential = crypto.createHmac("sha1", config.turnSecret).update(username).digest("base64")509 ice.push({ urls: config.turnUrls, username, credential })510 }511 return { ice_servers: ice }512 })513}514