v4: a moderator's or an admin's @everyone in the chat notifies every user — there was no way to reach everyone at once. The new chat:everyone permission, held by moderators and admins, lets a chat message saying @everyone notify every user but its author and those reading the chat, through notifyEveryone, after notifyMentions, so a user also named is told once, by name; the notification is a user_mentioned with everyone set, which the notifications page and the digest word as "mentioned everyone in the chat". chat_messages.mentions_everyone, sent as ChatMessage.mentionsEveryone, is set from the author's role each time the body is written, so a user's @everyone reaches no one, a moderator's edit of a user's message can't make it reach everyone, and a demoted author's next edit loses it. Only an edit that adds @everyone notifies, so fixing an announcement's typo reaches no one new. The client highlights and chimes by the flag, never by the text; Markdown shows @everyone as a mention only in a flagged message, and never links it to a profile. The chat composer offers @everyone first to those who may say it. No account may be named everyone, in any case: migration 0023 adds the column, flags the moderators' and admins' past @everyone messages, renames a user named everyone to everyone_N and drops an alias everyone. 265 backend tests and 681 frontend tests pass, and deno check, tsc, eslint, doc:lint and i18n:compile --strict are clean; checked in screenshots of the chat at 1280 and 390px, with a moderator's and a user's @everyone and the suggestions open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-10-09 12:54:09 +00:00
parent 5f239a144d
commit 134d1a0b97
37 changed files with 806 additions and 263 deletions

View File

@@ -29,6 +29,7 @@ import { up as up0019UserSettings } from "./migrations/0019_user_settings.ts";
import { up as up0020DigestSchedule } from "./migrations/0020_digest_schedule.ts";
import { up as up0021PageUrls } from "./migrations/0021_page_urls.ts";
import { up as up0022ReserveCommunity } from "./migrations/0022_reserve_community.ts";
import { up as up0023MentionEveryone } from "./migrations/0023_mention_everyone.ts";
interface Migration {
name: string;
@@ -70,6 +71,7 @@ const MIGRATIONS: Migration[] = [
{ name: "0020_digest_schedule", up: up0020DigestSchedule },
{ name: "0021_page_urls", up: up0021PageUrls },
{ name: "0022_reserve_community", up: up0022ReserveCommunity },
{ name: "0023_mention_everyone", up: up0023MentionEveryone },
];
/**

View File

@@ -0,0 +1,74 @@
/**
* Prepares the chat's `@everyone`: it adds `chat_messages.mentions_everyone`,
* and frees the name `everyone`, which no account may have any more.
*
* @module
*/
import type { DatabaseSync } from "node:sqlite";
import { EVERYONE, mentionsEveryone } from "../../../shared/mention.ts";
import { ROLE_PERMISSIONS } from "../../../shared/permissions.ts";
/**
* Run once by `runMigrations`. The messages that a moderator or an admin
* already sent with `@everyone` get the flag, so that editing one later
* doesn't notify everyone of an old message; none is notified now. A user
* named `everyone`, in any case, is renamed to the first free `everyone_2`,
* `everyone_3`…, with no alias left behind, and an alias `everyone` is
* dropped. Both are logged.
*/
export function up(db: DatabaseSync): void {
const cols = db.prepare(`PRAGMA table_info(chat_messages);`).all() as {
name: string;
}[];
if (!cols.some((c) => c.name === "mentions_everyone")) {
db.exec(
`ALTER TABLE chat_messages ADD COLUMN mentions_everyone INTEGER NOT NULL DEFAULT 0;`,
);
}
const roles = Object.entries(ROLE_PERMISSIONS)
.filter(([, perms]) => perms.includes("chat:everyone"))
.map(([role]) => role);
const messages = db.prepare(
`SELECT m.id, m.body FROM chat_messages m JOIN users u ON u.id = m.user_id
WHERE m.mentions_everyone = 0
AND u.role IN (${roles.map(() => "?").join(", ")})
AND m.body LIKE '%@%';`,
).all(...roles) as { id: string; body: string }[];
const flag = db.prepare(
`UPDATE chat_messages SET mentions_everyone = 1 WHERE id = ?;`,
);
for (const m of messages) {
if (mentionsEveryone(m.body)) flag.run(m.id);
}
const taken = (name: string) =>
!!db.prepare(
`SELECT 1 FROM users WHERE lower(username) = lower(?)
UNION ALL SELECT 1 FROM user_aliases WHERE lower(username) = lower(?);`,
).get(name, name);
const user = db.prepare(
`SELECT id, username FROM users WHERE lower(username) = ?;`,
).get(EVERYONE) as { id: string; username: string } | undefined;
if (user) {
let n = 2;
while (taken(`${EVERYONE}_${n}`)) n++;
const renamed = `${EVERYONE}_${n}`;
db.prepare(`UPDATE users SET username = ? WHERE id = ?;`).run(
renamed,
user.id,
);
console.log(
`[migrate] user "${user.username}" is now "${renamed}": @${EVERYONE} is reserved`,
);
}
const alias = db.prepare(
`DELETE FROM user_aliases WHERE lower(username) = ? RETURNING user_id;`,
).get(EVERYONE) as { user_id: string } | undefined;
if (alias) {
console.log(
`[migrate] the former name "${EVERYONE}" of user ${alias.user_id} is dropped: @${EVERYONE} is reserved`,
);
}
}

View File

@@ -265,6 +265,7 @@ CREATE TABLE chat_messages (
created_at TEXT NOT NULL,
updated_at TEXT,
reply_to_id TEXT,
mentions_everyone INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX idx_chat_messages_created_id ON chat_messages(created_at, id);

View File

@@ -35,6 +35,7 @@ export type HighlightKind =
| "mentionDump"
| "mentionPlaylist"
| "mentionChat"
| "mentionEveryone"
| "comment"
| "playlistFollow"
| "userFollow"
@@ -158,6 +159,8 @@ function highlightSentence(
return i18n._("email.digest.hl.mentionIn", values);
case "mentionPlaylist":
return i18n._("email.digest.hl.mentionPlaylist", values);
case "mentionEveryone":
return i18n._("email.digest.hl.mentionEveryone", values);
case "comment":
return i18n._("email.digest.hl.comment", values);
case "playlistFollow":
@@ -244,7 +247,7 @@ export function renderDigestEmail(
)
.join(" · "),
activity.highlights.map((h) => {
const target = h.kind === "mentionChat"
const target = h.kind === "mentionChat" || h.kind === "mentionEveryone"
? mdLink(
i18n._("email.digest.theChat"),
content.links.chat,

View File

@@ -26,6 +26,8 @@ export interface ChatMessageRow {
reply_to_author: string | null;
/** Cut to chat-service's `REPLY_SNIPPET_LEN` characters. */
reply_to_body: string | null;
/** 1 or 0. */
mentions_everyone: number;
[key: string]: SQLOutputValue;
}
@@ -50,7 +52,8 @@ export function isChatMessageRow(obj: unknown): obj is ChatMessageRow {
"reply_to_author" in obj &&
(typeof obj.reply_to_author === "string" || obj.reply_to_author === null) &&
"reply_to_body" in obj &&
(typeof obj.reply_to_body === "string" || obj.reply_to_body === null);
(typeof obj.reply_to_body === "string" || obj.reply_to_body === null) &&
"mentions_everyone" in obj && typeof obj.mentions_everyone === "number";
}
/**
@@ -69,5 +72,6 @@ export function chatMessageRowToApi(row: ChatMessageRow): ChatMessage {
replyToId: row.reply_to_id ?? undefined,
replyToAuthor: row.reply_to_author ?? undefined,
replyToBody: row.reply_to_body ?? undefined,
mentionsEveryone: row.mentions_everyone === 1 || undefined,
};
}

View File

@@ -34,6 +34,7 @@ import {
type WsClient,
} from "../services/ws-service.ts";
import {
chatMessageMentionsEveryone,
createChatMessage,
deleteChatMessage,
getChatReadState,
@@ -42,6 +43,7 @@ import {
} from "../services/chat-service.ts";
import {
getUnreadCount,
notifyEveryone,
notifyMentions,
} from "../services/notification-service.ts";
import { hasPermission } from "../../shared/permissions.ts";
@@ -369,7 +371,8 @@ function optionalString(value: unknown, maxLength: number): string | undefined {
/**
* Handles `chat_send`. It stores the message, broadcasts it, and notifies the
* @mentioned users who aren't reading the chat.
* @mentioned users who aren't reading the chat, and everyone who isn't when
* the message is flagged `mentionsEveryone`.
*/
function handleChatSend(
client: WsClient,
@@ -404,6 +407,9 @@ function handleChatSend(
undefined,
isUserChatOpen,
);
if (message.mentionsEveryone) {
notifyEveryone(userId, message.id, isUserChatOpen);
}
} catch (err) {
sendChatError(
client,
@@ -430,7 +436,8 @@ function canModerateChat(client: WsClient): boolean {
/**
* Handles `chat_edit`. It stores the new body, broadcasts it, and notifies, in
* the author's name, the users the edit newly mentions.
* the author's name, the users the edit newly mentions, and everyone when the
* edit adds a `@everyone` the author may say.
*/
function handleChatEdit(client: WsClient, id: unknown, body: unknown): void {
const userId = chatWriter(client);
@@ -441,6 +448,10 @@ function handleChatEdit(client: WsClient, id: unknown, body: unknown): void {
}
try {
// Only an edit that adds `@everyone` notifies everyone: fixing a typo in
// an announcement mustn't reach those who had the chat open when it was
// sent, nor those who joined since.
const wasEveryone = chatMessageMentionsEveryone(id);
const message = updateChatMessage(
id,
body,
@@ -460,6 +471,9 @@ function handleChatEdit(client: WsClient, id: unknown, body: unknown): void {
undefined,
isUserChatOpen,
);
if (message.mentionsEveryone && !wasEveryone) {
notifyEveryone(message.userId, message.id, isUserChatOpen);
}
} catch (err) {
sendChatError(
client,

View File

@@ -14,6 +14,9 @@ import { chatMessageRowToApi, isChatMessageRow } from "../model/chat.ts";
import { db } from "../db/connection.ts";
import { linkAttachments } from "./attachment-service.ts";
import { VALIDATION } from "../../shared/validation.ts";
import { mentionsEveryone } from "../../shared/mention.ts";
import { hasPermission } from "../../shared/permissions.ts";
import { isRole } from "../../shared/user.ts";
const DEFAULT_LIMIT = 50;
const MAX_LIMIT = 100;
@@ -28,7 +31,7 @@ const REPLY_SNIPPET_LEN = 300;
/** The columns of a `ChatMessageRow`, to select over {@link FROM_JOINS}. */
const SELECT_COLS =
`m.id, m.user_id, m.body, m.created_at, m.updated_at, m.reply_to_id,
u.username as author_username, u.avatar_mime as author_avatar_mime,
m.mentions_everyone, u.username as author_username, u.avatar_mime as author_avatar_mime,
ru.username as reply_to_author, substr(rm.body, 1, ${REPLY_SNIPPET_LEN}) as reply_to_body`;
/**
@@ -51,10 +54,27 @@ function fetchMessage(id: string): ChatMessage {
return chatMessageRowToApi(row);
}
/**
* Returns 1 when `body`, written by `authorId`, reaches everyone: it says
* `@everyone` and the author's role, read now, has `chat:everyone`. Else 0,
* for `chat_messages.mentions_everyone`.
*/
function everyoneFlag(authorId: string, body: string): number {
if (!mentionsEveryone(body)) return 0;
const row = db.prepare(`SELECT role FROM users WHERE id = ?;`).get(
authorId,
) as { role: unknown } | undefined;
return row && isRole(row.role) && hasPermission(row.role, "chat:everyone")
? 1
: 0;
}
/**
* Stores a message from `userId` on a `chat_send`, and claims the pasted images
* it links to. A `replyToId` naming no message is dropped, and the message is
* posted as no reply. The caller broadcasts the result.
* posted as no reply. The message `mentionsEveryone` when it says `@everyone`
* and `userId` may. The caller broadcasts the result, and notifies everyone
* when it is flagged.
*
* @throws {APIException} 400 when the body is blank or longer than
* `VALIDATION.CHAT_MESSAGE_MAX`.
@@ -84,8 +104,9 @@ export function createChatMessage(
const id = crypto.randomUUID();
const createdAt = new Date().toISOString();
db.prepare(
`INSERT INTO chat_messages (id, user_id, body, created_at, reply_to_id) VALUES (?, ?, ?, ?, ?);`,
).run(id, userId, trimmed, createdAt, replyTo);
`INSERT INTO chat_messages (id, user_id, body, created_at, reply_to_id, mentions_everyone)
VALUES (?, ?, ?, ?, ?, ?);`,
).run(id, userId, trimmed, createdAt, replyTo, everyoneFlag(userId, trimmed));
// Unclaimed attachments are deleted as orphans at startup.
linkAttachments(trimmed, "chat", id);
return fetchMessage(id);
@@ -102,10 +123,24 @@ function getMessageOwner(id: string): string {
return row.user_id;
}
/**
* Checks whether message `id` is flagged `mentionsEveryone`, false when there
* is no such message. The WebSocket route reads it before an edit, to notify
* everyone only when the edit adds `@everyone`.
*/
export function chatMessageMentionsEveryone(id: string): boolean {
const row = db.prepare(
`SELECT mentions_everyone FROM chat_messages WHERE id = ?;`,
).get(id) as { mentions_everyone: number } | undefined;
return row?.mentions_everyone === 1;
}
/**
* Replaces a message's body on a `chat_edit`, and claims any image the new body
* links to. `canModerate` lets a moderator edit anyone's message. The caller
* broadcasts the result.
* links to. `canModerate` lets a moderator edit anyone's message. The flag
* `mentionsEveryone` is set again from the new body and the author's role, not
* the editor's: a moderator's edit can't make a user's message reach everyone.
* The caller broadcasts the result.
*
* @throws {APIException} 404 when there is no such message, 403 when the user
* is neither its author nor a moderator, 400 when the body is blank or too
@@ -131,8 +166,10 @@ export function updateChatMessage(
`Message exceeds ${VALIDATION.CHAT_MESSAGE_MAX} characters`,
);
}
db.prepare(`UPDATE chat_messages SET body = ?, updated_at = ? WHERE id = ?;`)
.run(trimmed, new Date().toISOString(), id);
db.prepare(
`UPDATE chat_messages SET body = ?, updated_at = ?, mentions_everyone = ?
WHERE id = ?;`,
).run(trimmed, new Date().toISOString(), everyoneFlag(ownerId, trimmed), id);
linkAttachments(trimmed, "chat", id);
return fetchMessage(id);
}

View File

@@ -263,7 +263,7 @@ function highlightOf(
};
case "chat":
return {
kind: "mentionChat",
kind: d.everyone ? "mentionEveryone" : "mentionChat",
who: d.mentionerUsername,
quote: quoteOf(
(db.prepare(`SELECT body FROM chat_messages WHERE id = ?;`)

View File

@@ -379,6 +379,50 @@ export function notifyMentions(
}
}
/**
* Notifies every user but its author of chat message `messageId`, which says
* `@everyone`. The WebSocket route calls it, after {@link notifyMentions} so
* that a user also named is told by name, when the message is sent flagged
* `mentionsEveryone`, or when an edit flags it. Each user is notified once per
* message, however often it is edited. `skipUserId` spares the users who have
* the chat open, as for a mention.
*/
export function notifyEveryone(
mentionerUserId: string,
messageId: string,
skipUserId?: (userId: string) => boolean,
): void {
const mentionerRow = db.prepare(
`SELECT username FROM users WHERE id = ?;`,
).get(mentionerUserId) as { username: string } | undefined;
if (!mentionerRow) return;
const userRows = db.prepare(`SELECT id FROM users WHERE id != ?;`).all(
mentionerUserId,
) as { id: string }[];
// One transaction for the fan-out, as for a dump's followers.
transaction(() => {
for (const row of userRows) {
if (skipUserId?.(row.id)) continue;
createNotification(
row.id,
"user_mentioned",
{
mentionerId: mentionerUserId,
mentionerUsername: mentionerRow.username,
contextType: "chat",
contextId: messageId,
contextTitle: "",
everyone: true,
},
// The key of a mention by name, so a user named too gets one.
`mention:chat:${messageId}:${row.id}`,
);
}
});
}
/**
* Notifies a dump's poster that `commenterId` commented on it, unless they are
* the poster. `createComment` calls it for replies too, but not on an edit.

View File

@@ -33,6 +33,7 @@ import { parseRows } from "../model/rows.ts";
import { isEmailEnabled, sendEmail } from "./email-service.ts";
import { renderWelcomeEmail } from "../mail/welcome.ts";
import { USERNAME_RE, VALIDATION } from "../../shared/validation.ts";
import { EVERYONE } from "../../shared/mention.ts";
/** Selects full `UserRow`s from `users u`, with the inviter's name joined. */
const USER_SELECT =
@@ -43,13 +44,17 @@ const USER_SELECT =
/**
* Throws a 409 when `username` is, in any case, the name or a former name of
* an account other than `exceptUserId`. A former name stays its user's for
* good, so that old links and old @mentions can't be taken over.
* an account other than `exceptUserId`, or `everyone`, which the chat's
* `@everyone` takes. A former name stays its user's for good, so that old
* links and old @mentions can't be taken over.
*/
function assertUsernameAvailable(
username: string,
exceptUserId?: string,
): void {
if (username.toLowerCase() === EVERYONE) {
throw new APIException(409, "Username already exists");
}
const row = db.prepare(
`SELECT id FROM users WHERE lower(username) = lower(?) AND id != ?
UNION ALL

View File

@@ -28,14 +28,14 @@ Deno.test("runMigrations: a fresh database is left as schema.sql made it", () =>
.get() as {
n: number;
};
assertEquals(applied.n, 22);
assertEquals(applied.n, 23);
// Running again applies nothing.
runMigrations(db);
assertEquals(
(db.prepare(`SELECT COUNT(*) as n FROM schema_migrations;`).get() as {
n: number;
}).n,
22,
23,
);
db.close();
});

View File

@@ -0,0 +1,39 @@
import "../../setup.ts";
import { assertEquals } from "@std/assert";
import { DatabaseSync } from "node:sqlite";
import { up as up0023 } from "../../../db/migrations/0023_mention_everyone.ts";
Deno.test("migration 0023 flags past @everyone and frees the name", () => {
const db = new DatabaseSync(":memory:");
db.exec(`
CREATE TABLE users (id TEXT PRIMARY KEY, username TEXT, role TEXT);
CREATE TABLE user_aliases (username TEXT PRIMARY KEY, user_id TEXT);
CREATE TABLE chat_messages (id TEXT PRIMARY KEY, user_id TEXT, body TEXT);
INSERT INTO users VALUES
('m', 'mod', 'moderator'), ('u', 'Everyone', 'user'),
('t', 'everyone_2', 'user'), ('a', 'ann', 'user');
INSERT INTO user_aliases VALUES ('everyone_3', 't'), ('EVERYONE', 'a');
INSERT INTO chat_messages VALUES
('1', 'm', 'hi @everyone'), ('3', 'u', 'hi @everyone'),
('4', 'm', 'hi all');
`);
// In code, it says nothing.
db.prepare(`INSERT INTO chat_messages VALUES ('2', 'm', ?);`).run(
"hi `@everyone`",
);
up0023(db);
up0023(db); // idempotent
const flagged = db.prepare(
`SELECT id FROM chat_messages WHERE mentions_everyone = 1;`,
).all() as { id: string }[];
assertEquals(flagged.map((r) => r.id), ["1"]);
const names = db.prepare(`SELECT id, username FROM users ORDER BY id;`)
.all() as { id: string; username: string }[];
assertEquals(names.find((r) => r.id === "u")?.username, "everyone_4");
const aliases = db.prepare(`SELECT username FROM user_aliases;`).all() as {
username: string;
}[];
assertEquals(aliases.map((r) => r.username), ["everyone_3"]);
db.close();
});

View File

@@ -669,6 +669,19 @@ test("renaming: the old name redirects for good, and nobody else can take it", a
assertEquals((await rename(other.id, old)).status, 409);
// Nor to a current one.
assertEquals((await rename(other.id, renamed)).status, 409);
// Nor to everyone, in any case, which the chat's @everyone takes.
assertEquals((await rename(other.id, "Everyone")).status, 409);
assertEquals(
(await post("/api/users", {
json: {
username: "everyone",
password: PASSWORD,
email: `${uniqueName()}@example.test`,
inviteToken: invite(other.id),
},
})).status,
409,
);
// Signing in takes the current name only.
assertEquals(
(await post("/api/sessions", {

View File

@@ -448,6 +448,73 @@ wsTest(
},
);
wsTest(
"chat: @everyone notifies all who aren't reading, when its author may say it",
async (connect) => {
const mod = await createUser({ role: "moderator" });
const user = await createUser();
const named = await createUser();
const reader = await createUser();
const m = await connect(mod);
const u = await connect(user);
const r = await connect(reader);
r.send({ type: "chat_focus", open: true });
await r.sync();
const mentioned = () =>
Object.fromEntries(
(db.prepare(
`SELECT user_id, data FROM notifications WHERE type = 'user_mentioned';`,
).all() as { user_id: string; data: string }[])
.map((row) => [row.user_id, !!JSON.parse(row.data).everyone]),
);
// A user's @everyone reaches no one.
u.send({ type: "chat_send", body: "@everyone hi" });
const plain = (await m.next("chat_message")).message;
assertEquals(plain.mentionsEveryone, undefined);
assertEquals(mentioned(), {});
// A moderator's reaches all but its author and the reader, and a user
// named too is told by name.
m.send({
type: "chat_send",
body: `@Everyone, and @${named.username}`,
});
const byMod = (x: { message: { userId: string } }) =>
x.message.userId === mod.id;
const sent = (await u.next("chat_message", byMod)).message;
assertEquals(sent.mentionsEveryone, true);
const expected = { [user.id]: true, [named.id]: false };
assertEquals(mentioned(), expected);
// Fixing a typo reaches no one new, not even a newcomer.
const late = await createUser();
m.send({ type: "chat_edit", id: sent.id, body: "@everyone, and all" });
await u.next("chat_message_updated");
assertEquals(mentioned(), expected);
// A moderator's edit can't make a user's message reach everyone.
m.send({ type: "chat_edit", id: plain.id, body: "@everyone edited" });
const edited = (await u.next("chat_message_updated")).message;
assertEquals(edited.mentionsEveryone, undefined);
assertEquals(mentioned(), expected);
// An edit that adds it notifies, the newcomer included.
m.send({ type: "chat_send", body: "soon" });
const draft = (await u.next("chat_message", byMod)).message;
m.send({ type: "chat_edit", id: draft.id, body: "now, @everyone" });
await u.next("chat_message_updated");
assertEquals(
count(
`SELECT COUNT(*) AS n FROM notifications WHERE data LIKE ?;`,
`%${draft.id}%`,
),
3,
);
assertEquals(mentioned()[late.id], true);
},
);
wsTest("chat: typing and read markers", async (connect) => {
const alice = await createUser();
const bob = await createUser();

View File

@@ -1,6 +1,7 @@
import { createUser, db, test } from "../helpers.ts";
import { assertEquals, assertThrows } from "@std/assert";
import {
chatMessageMentionsEveryone,
createChatMessage,
deleteChatMessage,
getChatMessagesAfter,
@@ -161,3 +162,26 @@ test("read state: with no messages at all the marker can't be moved", async () =
insertMessage(other.id, "later", T(5));
assertEquals(getChatReadState(me.id).unread, 1);
});
test("mentionsEveryone: set from the author's role when the body is written", async () => {
const mod = await createUser({ role: "moderator" });
const user = await createUser();
const flagged = createChatMessage(mod.id, "hi @everyone");
assertEquals(flagged.mentionsEveryone, true);
assertEquals(chatMessageMentionsEveryone(flagged.id), true);
assertEquals(
createChatMessage(user.id, "hi @everyone").mentionsEveryone,
undefined,
);
assertEquals(
createChatMessage(mod.id, "`@everyone`").mentionsEveryone,
undefined,
);
assertEquals(chatMessageMentionsEveryone(crypto.randomUUID()), false);
// Demoted, the author's next edit loses it.
db.prepare(`UPDATE users SET role = 'user' WHERE id = ?;`).run(mod.id);
const edited = updateChatMessage(flagged.id, "hi @everyone!", mod.id, false);
assertEquals(edited.mentionsEveryone, undefined);
assertEquals(chatMessageMentionsEveryone(flagged.id), false);
});