Repository Public
1import type { FastifyInstance } from "fastify"2import { z } from "zod"3import { config } from "./config.js"4import { sql } from "./db.js"5import { hub, peersOf } from "./hub.js"6import { requireAdmin, requireUser } from "./session.js"7import { audit, bad, parse, randomToken, sha256, zUuid } from "./util.js"89export function adminRoutes(app: FastifyInstance) {10 // ---- invitations (any active member may list their own; only admins create and manage them)11 app.get("/api/admin/invitations", async (req) => {12 await requireAdmin(req)13 return sql`14 select i.id, i.recipient, i.expires_at, i.max_uses, i.uses, i.require_approval, i.revoked_at, i.created_at,15 u.display_name as created_by_name,16 (select coalesce(json_agg(json_build_object('id', x.id, 'handle', x.handle, 'display_name', x.display_name, 'status', x.status)), '[]')17 from users x where x.invitation_id = i.id) as redeemed_by18 from invitations i left join users u on u.id = i.created_by19 order by i.created_at desc limit 500`20 })2122 app.post("/api/admin/invitations", async (req) => {23 const a = await requireAdmin(req)24 const body = parse(25 z.object({26 recipient: z.string().trim().max(120).optional(),27 expires_in_hours: z.number().int().min(1).max(24 * 90).default(72),28 max_uses: z.number().int().min(1).max(1000).default(1),29 require_approval: z.boolean().default(false),30 }),31 req.body,32 )33 const token = randomToken(32) // 256 bits from the OS CSPRNG; only its SHA-256 is stored34 const [row] = await sql`35 insert into invitations (token_hash, created_by, recipient, expires_at, max_uses, require_approval)36 values (${sha256(token)}, ${a.userId}, ${body.recipient || null}, now() + make_interval(hours => ${body.expires_in_hours}),37 ${body.max_uses}, ${body.require_approval})38 returning id, expires_at`39 await audit(req, a.userId, "invitation.create", row.id, { max_uses: body.max_uses, require_approval: body.require_approval })40 // The token is placed in the URL fragment so that it never reaches proxy or server logs.41 return { id: row.id, expires_at: row.expires_at, url: `${config.origin}/invite#${token}` }42 })4344 app.delete("/api/admin/invitations/:id", async (req) => {45 const a = await requireAdmin(req)46 const { id } = parse(z.object({ id: zUuid }), req.params)47 const r = await sql`update invitations set revoked_at = now() where id = ${id} and revoked_at is null returning 1`48 if (!r.length) throw bad("not_found", 404)49 await audit(req, a.userId, "invitation.revoke", id)50 return { ok: true }51 })5253 // ---- accounts54 app.get("/api/admin/users", async (req) => {55 await requireAdmin(req)56 return sql`57 select u.id, u.handle, u.display_name, u.role, u.status, u.quota_bytes, u.used_bytes, u.created_at,58 (u.identity_key is not null) as has_identity,59 inv.display_name as invited_by_name,60 (select count(*)::int from devices d where d.user_id = u.id and d.status = 'active') as devices,61 (select count(*)::int from passkeys p where p.user_id = u.id) as passkeys,62 (select max(s.last_seen_at) from sessions s where s.user_id = u.id) as last_seen_at63 from users u left join users inv on inv.id = u.invited_by64 order by u.created_at`65 })6667 app.patch("/api/admin/users/:id", async (req) => {68 const a = await requireAdmin(req)69 const { id } = parse(z.object({ id: zUuid }), req.params)70 const body = parse(71 z.object({72 status: z.enum(["active", "disabled", "rejected"]).optional(),73 role: z.enum(["admin", "member"]).optional(),74 quota_bytes: z.number().int().min(0).max(1e13).optional(),75 }),76 req.body,77 )78 const [u] = await sql`select id, role, status from users where id = ${id}`79 if (!u) throw bad("not_found", 404)80 if (id === a.userId && (body.status && body.status !== "active" || body.role === "member"))81 throw bad("cannot_demote_self", 409, "An administrator cannot disable or demote their own account")82 if (body.status) {83 await sql`update users set status = ${body.status} where id = ${id}`84 if (body.status !== "active") {85 await sql`update sessions set revoked_at = now() where user_id = ${id} and revoked_at is null`86 // Devices of a disabled account are revoked so that other members remove them from every group.87 await sql`update devices set status = 'revoked', revoked_at = now() where user_id = ${id} and status <> 'revoked'`88 await sql`delete from key_packages where device_id in (select id from devices where user_id = ${id})`89 hub.closeUser(id)90 hub.toUsers(await peersOf(id), { t: "directory", user: id })91 } else hub.toUser(id, { t: "account", status: "active" })92 }93 if (body.role) await sql`update users set role = ${body.role} where id = ${id}`94 if (body.quota_bytes !== undefined) await sql`update users set quota_bytes = ${body.quota_bytes} where id = ${id}`95 await audit(req, a.userId, "user.update", id, body)96 return { ok: true }97 })9899 /** Clears a lost encryption identity so the member can enrol again. Their contacts see a key-change warning. */100 app.post("/api/admin/users/:id/reset-identity", async (req) => {101 const a = await requireAdmin(req)102 const { id } = parse(z.object({ id: zUuid }), req.params)103 await sql.begin(async (tx) => {104 await tx`update devices set status = 'revoked', revoked_at = now() where user_id = ${id} and status <> 'revoked'`105 await tx`delete from key_packages where device_id in (select id from devices where user_id = ${id})`106 await tx`delete from key_backups where user_id = ${id}`107 await tx`update users set identity_key = null, identity_set_at = null where id = ${id}`108 await tx`update sessions set device_id = null where user_id = ${id}`109 })110 hub.toUsers([...(await peersOf(id)), id], { t: "directory", user: id })111 await audit(req, a.userId, "user.reset-identity", id)112 return { ok: true }113 })114115 app.get("/api/admin/users/:id/sessions", async (req) => {116 await requireAdmin(req)117 const { id } = parse(z.object({ id: zUuid }), req.params)118 return sql`119 select id, ip, user_agent, created_at, last_seen_at from sessions120 where user_id = ${id} and revoked_at is null and expires_at > now() order by last_seen_at desc`121 })122 app.delete("/api/admin/sessions/:id", async (req) => {123 const a = await requireAdmin(req)124 const { id } = parse(z.object({ id: zUuid }), req.params)125 await sql`update sessions set revoked_at = now() where id = ${id} and revoked_at is null`126 hub.closeSession(id)127 await audit(req, a.userId, "session.revoke-admin", id)128 return { ok: true }129 })130131 app.get("/api/admin/audit", async (req) => {132 await requireAdmin(req)133 return sql`134 select l.id, l.at, l.action, l.target, l.meta, l.ip, u.handle as actor_handle135 from audit_log l left join users u on u.id = l.actor order by l.id desc limit 300`136 })137138 app.get("/api/admin/stats", async (req) => {139 await requireAdmin(req)140 const [s] = await sql`141 select (select count(*)::int from users where status = 'active') as users,142 (select count(*)::int from users where status = 'pending') as pending,143 (select count(*)::int from conversations) as conversations,144 (select count(*)::int from messages) as stored_ciphertexts,145 (select coalesce(sum(used_bytes), 0)::bigint from users) as used_bytes,146 (select count(*)::int from devices where status = 'active') as devices`147 return { ...s, online_connections: hub.connections(), turn_configured: !!(config.turnSecret && config.turnUrls.length) }148 })149150 // ---- directory visible to every active member (private network: members can find each other)151 app.get("/api/directory", async (req) => {152 await requireUser(req)153 return sql`select id, handle, display_name from users where status = 'active' and identity_key is not null order by display_name`154 })155}156