Repository Public
1import assert from "node:assert/strict"2import fs from "node:fs"3import path from "node:path"4import { after, before, test } from "node:test"5import WebSocket from "ws"6import { Engine } from "../web/src/core/engine"7import { MemoryStore } from "../web/src/core/store"8import { ApiError } from "../web/src/core/types"9import { Actor, Authenticator, dataDir, issueBootstrap, NodeTransport, ORIGIN, sleep, sql, startServer, stopServer, tokenOf, until } from "./harness"1011const alice = new Actor("alice"), bob = new Actor("bob"), carol = new Actor("carol")12let dm = "", group = ""13let aliceRecovery = ""14const MARK = "PLAINTEXT-MARKER-7f3a"1516async function rejects(p: Promise<unknown>, code: string | number) {17 try {18 await p19 } catch (e) {20 if (e instanceof ApiError) return assert.ok(e.code === code || e.status === code, `expected ${code}, got ${e.status} ${e.code}`)21 throw e22 }23 assert.fail(`expected rejection ${code}`)24}25async function invite(opts: Record<string, unknown> = {}) {26 const r = await alice.t.request<{ id: string; url: string }>("POST", "/api/admin/invitations", opts)27 return { id: r.id, token: tokenOf(r.url) }28}2930before(startServer)31after(async () => {32 for (const a of [alice, bob, carol]) a.engine?.stop()33 await stopServer()34})3536test("bootstrap: one-time administrator creation with a passkey", async () => {37 const token = await issueBootstrap()38 await rejects(new NodeTransport().request("POST", "/api/register/options", { token: "x".repeat(43), bootstrap: true, handle: "eve", display_name: "Eve" }), "invalid_bootstrap_token")39 const r = await alice.register(token, true)40 assert.equal(r.status, "active")41 assert.equal(alice.me.role, "admin")42 // the token is single use43 await rejects(new Actor("mallory").register(token, true), "invalid_bootstrap_token")44 const [{ n }] = await sql`select count(*)::int as n from users`45 assert.equal(n, 1)46})4748test("registration is impossible without an invitation", async () => {49 await rejects(new Actor("mallory").register("y".repeat(43)), "invalid_invitation")50})5152test("invitations: single use, revocation, expiry, approval", async () => {53 const inv = await invite({ max_uses: 1, expires_in_hours: 1 })54 const check = await new NodeTransport().request<any>("POST", "/api/invitations/check", { token: inv.token })55 assert.equal(check.inviter.handle, "alice")56 await bob.register(inv.token)57 assert.equal(bob.me.status, "active")58 await rejects(new Actor("mallory").register(inv.token), "invalid_invitation") // used up5960 const revoked = await invite({})61 await alice.t.request("DELETE", `/api/admin/invitations/${revoked.id}`)62 await rejects(new Actor("mallory").register(revoked.token), "invalid_invitation")6364 const expired = await invite({})65 await sql`update invitations set expires_at = now() - interval '1 minute' where id = ${expired.id}`66 await rejects(new Actor("mallory").register(expired.token), "invalid_invitation")6768 // approval required: the account exists but cannot use the network until an administrator approves it69 const gated = await invite({ require_approval: true })70 const r = await carol.register(gated.token)71 assert.equal(r.status, "pending")72 await rejects(carol.t.request("GET", "/api/directory"), "account_not_active")73 const users = await alice.t.request<any[]>("GET", "/api/admin/users")74 await alice.t.request("PATCH", `/api/admin/users/${users.find((u) => u.handle === "carol").id}`, { status: "active" })75 await carol.loadMe()76 assert.equal(carol.me.status, "active")77 // only administrators manage invitations78 await rejects(bob.t.request("POST", "/api/admin/invitations", {}), "forbidden")79})8081test("passkey sign-in, counters, sessions", async () => {82 const fresh = new Actor("alice")83 await fresh.login(alice.auth)84 assert.equal(fresh.me.handle, "alice")85 // a response signed by an unknown credential is refused86 const { challenge_id, options } = await fresh.t.request<any>("POST", "/api/login/options", {})87 const stranger = new Authenticator()88 await stranger.create({ rp: { id: "localhost" }, user: { id: "AAAA" }, challenge: "x" })89 await rejects(new NodeTransport().request("POST", "/api/login/verify", { challenge_id, response: await stranger.get(options) }), "unknown_passkey")90 // a challenge cannot be replayed91 const o2 = await fresh.t.request<any>("POST", "/api/login/options", {})92 const resp = await alice.auth.get(o2.options)93 await new NodeTransport().request("POST", "/api/login/verify", { challenge_id: o2.challenge_id, response: resp })94 await rejects(new NodeTransport().request("POST", "/api/login/verify", { challenge_id: o2.challenge_id, response: resp }), "challenge_expired")95 // session revocation96 const sessions = await alice.t.request<any[]>("GET", "/api/sessions")97 assert.ok(sessions.length >= 2)98 await alice.t.request("DELETE", `/api/sessions/${fresh.sessionId}`)99 await rejects(fresh.t.request("GET", "/api/me"), 401)100})101102test("CSRF and transport checks", async () => {103 const t = new NodeTransport()104 t.cookie = alice.t.cookie105 t.headers = { origin: "https://evil.example", "x-spm": "1" }106 await rejects(t.request("POST", "/api/admin/invitations", {}), "csrf")107 t.headers = { origin: ORIGIN }108 await rejects(t.request("POST", "/api/admin/invitations", {}), "csrf")109 // WebSocket: refused without a session, and refused from another origin110 const status = (headers: Record<string, string>) =>111 new Promise<number>((resolve) => {112 const ws = new WebSocket(ORIGIN.replace("http", "ws") + "/ws", { headers })113 ws.on("unexpected-response", (_r, res) => resolve(res.statusCode ?? 0))114 ws.on("open", () => (ws.close(), resolve(101)))115 ws.on("error", () => {})116 })117 assert.equal(await status({ origin: ORIGIN }), 401)118 assert.equal(await status({ origin: "https://evil.example", cookie: alice.t.cookie }), 403)119 const res = await fetch(`${ORIGIN}/api/health/live`)120 assert.match(res.headers.get("content-security-policy") ?? "", /default-src 'self'/)121 assert.equal(res.headers.get("x-frame-options"), "DENY")122})123124test("identity creation on the client; the server only receives public keys", async () => {125 aliceRecovery = await alice.setup()126 await bob.setup()127 await carol.setup()128 assert.match(aliceRecovery, /^([A-Z2-9]{4}-){7}[A-Z2-9]{4}$/)129 const [u] = await sql`select identity_key from users where handle = 'alice'`130 assert.equal(Buffer.from(u.identity_key).length, 32)131 // a certificate that is not signed by the identity key is refused132 const t = new Actor("xavier")133 const inv = await invite({})134 await t.register(inv.token)135 await rejects(136 t.t.request("POST", "/api/identity", { identity_key: Buffer.alloc(32, 1).toString("base64"), device_id: crypto.randomUUID(), label: "x", signature_key: Buffer.alloc(32, 2).toString("base64"), cert: Buffer.alloc(64).toString("base64"), backup: "AAAA" }),137 "invalid_certificate",138 )139})140141test("direct conversation: end-to-end encrypted, authenticated sender, no plaintext on the server", async () => {142 dm = await alice.engine.createConversation("dm", [bob.me.id])143 await alice.engine.send(dm, { t: "text", body: `hello bob ${MARK}` })144 await until(() => bob.engine.convs.has(dm) && bob.texts(dm).length === 1, "bob receives")145 assert.equal(bob.texts(dm)[0], `hello bob ${MARK}`)146 assert.equal(bob.conv(dm).messages.find((m) => m.kind === "text")!.from, alice.me.id)147 await bob.engine.send(dm, { t: "text", body: "hello alice" })148 await until(() => alice.texts(dm).length === 2, "alice receives")149 // creating the same DM again returns the existing conversation150 assert.equal(await bob.engine.createConversation("dm", [alice.me.id]), dm)151152 // nothing stored by the server contains the plaintext153 const rows = await sql`select data from messages`154 for (const r of rows) assert.ok(!Buffer.from(r.data).includes(MARK))155 const dump = await sql`select row_to_json(m)::text as j from messages m`156 for (const r of dump) assert.ok(!r.j.includes(MARK))157 // delivery acknowledgement reaches the sender158 await until(() => (alice.conv(dm).delivered[bob.me.id] ?? 0) >= 2, "delivery ack")159})160161test("edits, deletions, reactions, pins, read receipts; only the author can edit", async () => {162 const id = await alice.engine.send(dm, { t: "text", body: "tpyo" })163 await until(() => bob.texts(dm).includes("tpyo"), "bob gets message")164 await alice.engine.send(dm, { t: "edit", target: id, body: "typo fixed" })165 await bob.engine.send(dm, { t: "react", target: id, emoji: "👍", on: true })166 await bob.engine.send(dm, { t: "edit", target: id, body: "HACKED" }) // not the author: ignored by every client167 await bob.engine.send(dm, { t: "pin", target: id, on: true })168 await until(() => !!alice.conv(dm).messages.find((m) => m.id === id)?.pinned, "pin arrives")169 const a = alice.conv(dm).messages.find((m) => m.id === id)!170 const b = bob.conv(dm).messages.find((m) => m.id === id)!171 assert.equal(a.body, "typo fixed")172 assert.equal(b.body, "typo fixed")173 assert.ok(b.edited)174 assert.deepEqual(a.reactions, { "👍": [bob.me.id] })175 await bob.engine.markRead(dm)176 await until(() => (alice.conv(dm).read[bob.me.id] ?? 0) >= a.seq!, "read receipt")177 await alice.engine.send(dm, { t: "del", target: id })178 await until(() => !!bob.conv(dm).messages.find((m) => m.id === id)?.deleted, "deletion")179 assert.equal(bob.conv(dm).messages.find((m) => m.id === id)!.body, "")180})181182test("offline delivery, ordering and deduplication after reconnection", async () => {183 bob.engine.stop()184 await sleep(200)185 for (let i = 1; i <= 5; i++) await alice.engine.send(dm, { t: "text", body: `offline ${i}` })186 await until(() => alice.conv(dm).messages.filter((m) => m.body.startsWith("offline")).every((m) => m.status === "sent"), "alice sent all")187 const before = bob.texts(dm).length188 await bob.startEngine() // same local store: the device resumes from its saved group state189 await until(() => bob.texts(dm).length === before + 5, "bob catches up")190 assert.deepEqual(bob.texts(dm).slice(-5), [1, 2, 3, 4, 5].map((i) => `offline ${i}`))191 await bob.engine.sync()192 await bob.engine.sync()193 assert.equal(bob.texts(dm).length, before + 5, "no duplicates after repeated sync")194 // composing while offline: the message waits in the outbox and leaves on reconnection195 alice.engine.stop()196 await sleep(100)197 alice.engine.online = false198 await alice.engine.send(dm, { t: "text", body: "written offline" })199 assert.equal(alice.conv(dm).messages.at(-1)!.status, "sending")200 await alice.startEngine()201 await until(() => bob.texts(dm).includes("written offline"), "outbox delivered")202})203204test("group conversation: add, remove, removed member loses access", async () => {205 group = await alice.engine.createConversation("group", [bob.me.id, carol.me.id], "Projet")206 await alice.engine.send(group, { t: "text", body: "bienvenue" })207 await until(() => bob.engine.convs.has(group) && carol.engine.convs.has(group) && bob.texts(group).length === 1 && carol.texts(group).length === 1, "group delivery")208 assert.equal(carol.conv(group).name, "Projet")209 await carol.engine.send(group, { t: "text", body: "salut" })210 await until(() => alice.texts(group).length === 2 && bob.texts(group).length === 2, "carol speaks")211 // only the owner removes members212 await assert.rejects(bob.engine.removeMember(group, carol.me.id))213 await bob.engine.sync()214 await alice.engine.removeMember(group, carol.me.id)215 await alice.engine.send(group, { t: "text", body: "after removal" })216 await until(() => bob.texts(group).includes("after removal"), "bob still receives")217 await sleep(500)218 assert.ok(!carol.texts(group).includes("after removal"))219 await rejects(carol.t.request("GET", `/api/conversations/${group}/messages?after=0`), "not_a_member")220 await rejects(carol.t.request("POST", `/api/conversations/${group}/messages`, { epoch: 3, client_id: crypto.randomUUID(), data: "AAAA" }), "not_a_member")221 // re-adding works and gives a fresh group state222 await alice.engine.addMembers(group, [carol.me.id])223 await alice.engine.send(group, { t: "text", body: "welcome back" })224 await until(() => carol.texts(group).includes("welcome back"), "carol rejoined", 20000)225 assert.ok(!carol.texts(group).includes("after removal"), "messages sent while removed stay unreadable")226})227228test("concurrent commits: the server orders epochs and the loser recovers", async () => {229 const dave = new Actor("dave"), erin = new Actor("erin")230 await dave.register((await invite({})).token)231 await erin.register((await invite({})).token)232 await dave.setup()233 await erin.setup()234 const results = await Promise.allSettled([alice.engine.addMembers(group, [dave.me.id]), bob.engine.addMembers(group, [erin.me.id])])235 // bob is not an owner but adding is allowed; at least one commit lands, and a retry of the other succeeds236 for (const [i, r] of results.entries())237 if (r.status === "rejected") await (i === 0 ? alice.engine.addMembers(group, [dave.me.id]) : bob.engine.addMembers(group, [erin.me.id]))238 await alice.engine.send(group, { t: "text", body: "everyone here?" })239 await until(() => dave.engine.convs.has(group) && erin.engine.convs.has(group) && dave.texts(group).includes("everyone here?") && erin.texts(group).includes("everyone here?"), "both new members receive", 20000)240 await until(() => bob.texts(group).includes("everyone here?") && carol.texts(group).includes("everyone here?"), "existing members receive")241 dave.engine.stop()242 erin.engine.stop()243})244245test("second device by approval: same code on both sides, joins every conversation", async () => {246 const a2 = new Actor("alice")247 await a2.login(alice.auth)248 const { code, deviceId } = await Engine.requestLink(a2.t, a2.store, a2.me, "Alice phone")249 // not approved yet: the new device has no access to conversations250 await rejects(a2.t.request("GET", "/api/sync"), "device_not_active")251 assert.equal(await Engine.completeLink(a2.t, a2.store, a2.me), null)252 await until(() => alice.engine.pendingDevices.length === 1, "pending device visible on the trusted device")253 assert.equal(alice.engine.pendingDevices[0].code, code)254 await alice.engine.approveDevice(deviceId)255 const dev = await Engine.completeLink(a2.t, a2.store, a2.me)256 assert.ok(dev)257 await a2.loadMe()258 a2.engine = new Engine(a2.t, a2.store, a2.me, dev!)259 await a2.engine.start()260 await until(() => !!a2.engine.convs.get(dm)?.state && !!a2.engine.convs.get(group)?.state, "new device added to the groups", 30000)261 await bob.engine.send(dm, { t: "text", body: "to both alice devices" })262 await until(() => a2.texts(dm).includes("to both alice devices") && alice.texts(dm).includes("to both alice devices"), "both devices receive")263 // messages sent from one device appear on the other264 await a2.engine.send(dm, { t: "text", body: "sent from phone" })265 await until(() => alice.texts(dm).includes("sent from phone") && bob.texts(dm).includes("sent from phone"), "multi-device sync")266 assert.ok(!a2.texts(dm).includes(`hello bob ${MARK}`), "history from before enrolment is not readable (forward secrecy)")267268 // revocation: the device is removed from the groups and can no longer decrypt269 await alice.t.request("DELETE", `/api/devices/${deviceId}`)270 await until(() => a2.engine.fatal !== null || !a2.engine.online, "revoked device is cut off")271 await sleep(3500)272 await bob.engine.send(dm, { t: "text", body: "after revocation" })273 await until(() => alice.texts(dm).includes("after revocation"), "alice receives")274 await rejects(a2.t.request("GET", `/api/conversations/${dm}/messages?after=0`), 401)275 a2.engine.stop()276})277278test("device approval rejects a forged certificate; recovery key restores the identity", async () => {279 const a3 = new Actor("alice")280 await a3.login(alice.auth)281 await rejects(Engine.recover(a3.t, new MemoryStore(), a3.me, "AAAA-AAAA-AAAA-AAAA-AAAA-AAAA-AAAA-AAAA", "x").catch((e) => { throw e instanceof ApiError ? e : new ApiError(400, "wrong_key", e.message) }), "wrong_key")282 const dev = await Engine.recover(a3.t, a3.store, a3.me, aliceRecovery, "Alice laptop")283 a3.engine = new Engine(a3.t, a3.store, a3.me, dev)284 await a3.engine.start()285 await until(() => alice.engine.notices.some((n) => n.text.includes("recovery key")), "existing device is told about the new device")286 await until(() => !!a3.engine.convs.get(dm)?.state, "recovered device joins", 30000)287 await bob.engine.send(dm, { t: "text", body: "hello recovered device" })288 await until(() => a3.texts(dm).includes("hello recovered device"), "recovered device receives")289 // a device cannot be activated with a certificate from another key290 const a4 = new Actor("alice")291 await a4.login(alice.auth)292 await rejects(a4.t.request("POST", "/api/devices", { device_id: crypto.randomUUID(), label: "ghost", signature_key: Buffer.alloc(32, 9).toString("base64"), cert: Buffer.alloc(64, 1).toString("base64") }), "invalid_certificate")293 // rotating the recovery key invalidates the old one294 const fresh = await alice.engine.rotateRecoveryKey()295 await assert.rejects(Engine.recover(a4.t, new MemoryStore(), a4.me, aliceRecovery, "x"))296 assert.notEqual(fresh, aliceRecovery)297 a3.engine.stop()298})299300test("a server-injected device without a valid certificate is never added to a group", async () => {301 // Simulates a malicious server inserting a ghost device for bob with a key it controls.302 const ghost = crypto.randomUUID()303 await sql`insert into devices (id, user_id, label, signature_key, cert, status) values (${ghost}, ${bob.me.id}, 'ghost', ${Buffer.alloc(32, 7)}, ${Buffer.alloc(64, 7)}, 'active')`304 await alice.engine.sync()305 await sleep(3500)306 const { members } = await import("../web/src/core/mls")307 assert.ok(!members(alice.conv(dm).state!).some((m) => m.deviceId === ghost))308 await sql`delete from devices where id = ${ghost}`309})310311test("an account the server adds to the member list on its own is never given the group keys", async () => {312 // Simulates a malicious server listing a real, fully enrolled account (dave) as a member of a private conversation.313 const [dave] = await sql`select id from users where handle = 'dave'`314 await sql`insert into conversation_members (conversation_id, user_id) values (${dm}, ${dave.id})`315 await alice.engine.sync()316 await bob.engine.sync()317 await sleep(3500)318 const { members } = await import("../web/src/core/mls")319 for (const who of [alice, bob]) assert.ok(!members(who.conv(dm).state!).some((m) => m.userId === dave.id), "no leaf for the injected account")320 assert.ok(alice.conv(dm).missing.includes(dave.id), "the interface is told that this listed member holds no key")321 await sql`delete from conversation_members where conversation_id = ${dm} and user_id = ${dave.id}`322 await alice.engine.sync()323 await bob.engine.sync()324})325326test("identity key change raises a warning instead of being trusted silently", async () => {327 const frank = new Actor("frank")328 await frank.register((await invite({})).token)329 await frank.setup()330 const conv = await frank.engine.createConversation("dm", [bob.me.id])331 await frank.engine.send(conv, { t: "text", body: "first identity" })332 await until(() => bob.engine.convs.has(conv) && bob.texts(conv).length === 1, "bob receives")333 const pinBefore = bob.engine.pins.get(frank.me.id)!.ik334 frank.engine.stop()335 await alice.t.request("POST", `/api/admin/users/${frank.me.id}/reset-identity`)336 const f2 = new Actor("frank")337 await f2.login(frank.auth)338 await f2.setup()339 await bob.engine.sync()340 await until(() => !!bob.engine.pins.get(frank.me.id)?.changed, "key change detected")341 assert.equal(bob.engine.pins.get(frank.me.id)!.ik, pinBefore, "the pinned key is unchanged until the person accepts")342 assert.ok(bob.engine.notices.some((n) => n.text.includes("security key")))343 await sleep(3500)344 const { members } = await import("../web/src/core/mls")345 assert.ok(!members(bob.conv(conv).state!).some((m) => m.userId === frank.me.id && m.identityKey.toString() === f2.engine.dev.identityKey.toString()), "devices under the new key are not added before acceptance")346 await bob.engine.acceptIdentityChange(frank.me.id)347 await until(() => !!f2.engine.convs.get(conv)?.state, "after acceptance the new device is added", 30000)348 f2.engine.stop()349})350351test("attachments: client-side encryption, resumable chunks, tamper detection, access control, quota", async () => {352 const data = new Uint8Array(2.5 * 1024 * 1024)353 for (let i = 0; i < data.length; i++) data[i] = (i * 31 + 7) & 255354 data.set(Buffer.from(MARK), 1000)355 let progress = 0356 const ref = await alice.engine.upload(dm, new Blob([data]), { name: "secret.bin", mime: "application/octet-stream" }, (f) => (progress = f))357 assert.equal(progress, 1)358 assert.equal(ref.chunks, 3)359 await alice.engine.send(dm, { t: "text", body: "", files: [ref] })360 await until(() => !!bob.conv(dm).messages.at(-1)?.files?.length, "bob gets the attachment message")361 const got = new Uint8Array(await (await bob.engine.download(bob.conv(dm).messages.at(-1)!.files![0])).arrayBuffer())362 assert.deepEqual(Buffer.from(got), Buffer.from(data))363 // stored chunks are ciphertext364 const dir = path.join(dataDir, "blobs", ref.id.slice(0, 2), ref.id)365 for (const f of fs.readdirSync(dir)) assert.ok(!fs.readFileSync(path.join(dir, f)).includes(MARK))366 // someone outside the conversation cannot fetch it, even knowing the id367 await rejects(carol.t.getBytes(`/api/files/${ref.id}/chunks/0`), 404)368 // forwarding grants access to the target conversation only369 await alice.engine.forward(alice.conv(dm).messages.at(-1)!, group)370 await until(() => !!carol.conv(group).messages.at(-1)?.files?.length, "forward arrives")371 assert.equal(carol.conv(group).messages.at(-1)!.fwd?.from, "Alice")372 assert.equal((await carol.engine.download(carol.conv(group).messages.at(-1)!.files![0])).size, data.length)373 // tampering with one stored byte makes decryption fail374 const f1 = path.join(dir, "1.bin")375 const raw = fs.readFileSync(f1)376 raw[100] ^= 1377 fs.writeFileSync(f1, raw)378 const dave = new Actor("bob")379 await assert.rejects(new Engine(bob.t, new MemoryStore(), bob.me, bob.engine.dev).download(ref))380 void dave381 // swapping two chunks is detected as well382 raw[100] ^= 1383 fs.writeFileSync(f1, raw)384 fs.copyFileSync(path.join(dir, "0.bin"), f1)385 await assert.rejects(new Engine(bob.t, new MemoryStore(), bob.me, bob.engine.dev).download(ref))386 // quota387 await alice.t.request("PATCH", `/api/admin/users/${bob.me.id}`, { quota_bytes: 1000 })388 await rejects(bob.engine.upload(dm, new Blob([new Uint8Array(5000)]), { name: "big", mime: "x/y" }).catch((e) => { throw e }), "quota_exceeded")389 await alice.t.request("PATCH", `/api/admin/users/${bob.me.id}`, { quota_bytes: 5e9 })390 // an incomplete upload cannot be attached391 const { id } = await bob.t.request<{ id: string }>("POST", "/api/files", { size: 3000000, chunk_size: 1048592, chunk_count: 3 })392 await rejects(bob.t.request("POST", `/api/files/${id}/complete`, { conversation_id: dm }), "incomplete")393})394395test("disappearing messages are removed from the server", async () => {396 await alice.engine.send(dm, { t: "meta", ttl: 5 })397 await alice.engine.send(dm, { t: "text", body: "self-destruct" })398 await until(() => bob.texts(dm).includes("self-destruct"), "bob receives")399 assert.ok(bob.conv(dm).messages.find((m) => m.body === "self-destruct")!.expiresAt)400 const [row] = await sql`select expires_at from messages where conversation_id = ${dm} order by seq desc limit 1`401 assert.ok(row.expires_at)402 await alice.engine.send(dm, { t: "meta", ttl: 0 })403})404405test("administration: disabling an account cuts sessions and removes its devices from groups", async () => {406 await alice.t.request("PATCH", `/api/admin/users/${carol.me.id}`, { status: "disabled" })407 await rejects(carol.t.request("GET", "/api/me"), 401)408 await until(async () => {409 const { members } = await import("../web/src/core/mls")410 return !members(alice.conv(group).state!).some((m) => m.userId === carol.me.id) || !members(bob.conv(group).state!).some((m) => m.userId === carol.me.id)411 }, "carol's leaves removed by a member", 20000)412 await rejects(alice.t.request("PATCH", `/api/admin/users/${alice.me.id}`, { status: "disabled" }), "cannot_demote_self")413 const log = await alice.t.request<any[]>("GET", "/api/admin/audit")414 assert.ok(log.some((l) => l.action === "user.update"))415 for (const l of log) assert.ok(!JSON.stringify(l).includes(MARK))416 const turn = await alice.t.request<any>("GET", "/api/turn")417 assert.match(turn.ice_servers[0].username, /^\d+:/)418})419420test("rate limiting on sign-in", async () => {421 const t = new NodeTransport()422 let limited = false423 for (let i = 0; i < 700 && !limited; i++)424 await t.request("POST", "/api/login/options", {}).catch((e) => {425 if (e instanceof ApiError && e.status === 429) limited = true426 else throw e427 })428 assert.ok(limited)429})430