From 874666751b9a413a4dd074680a5b5c36ed8146fc Mon Sep 17 00:00:00 2001 From: Ferdinand99 Date: Tue, 17 Nov 2026 05:52:59 +0100 Subject: [PATCH 1/8] fix(dashboard): show servers the bot joins after sign-in, and add a Refresh server list action A server the bot joined after someone signed in stayed out of their server list until they signed in again. A join now marks the lists on that platform as due and each identity is looked at once on its next request, through the bot's own view of the server. The server switcher gets a Refresh server list action (POST /api/v2/account/refresh-guilds, once per 30 seconds per account, own identities only). --- docs/fluxer.md | 2 +- docs/mobile-app.md | 7 +- src/bot/events/adminSnapshot.js | 7 +- src/bot/fluxerModuleEvents.js | 7 +- src/bot/lib/guildJoins.js | 49 ++++ src/web/lib/guildListRefresh.js | 92 ++++++++ src/web/lib/routeAccess.js | 1 + src/web/middleware/auth.js | 26 ++- src/web/routes/v2Api.js | 22 +- test/guildListRefresh.test.js | 210 ++++++++++++++++++ .../__tests__/ServerSwitcherRefresh.test.jsx | 88 ++++++++ web-v2/src/api.js | 2 + web-v2/src/components/ServerSwitcher.jsx | 28 ++- web-v2/src/components/Shell.jsx | 15 +- web-v2/src/styles.css | 18 ++ 15 files changed, 563 insertions(+), 11 deletions(-) create mode 100644 src/bot/lib/guildJoins.js create mode 100644 src/web/lib/guildListRefresh.js create mode 100644 test/guildListRefresh.test.js create mode 100644 web-v2/src/__tests__/ServerSwitcherRefresh.test.jsx diff --git a/docs/fluxer.md b/docs/fluxer.md index b9625071..b5cb191d 100644 --- a/docs/fluxer.md +++ b/docs/fluxer.md @@ -308,7 +308,7 @@ codebase to keep up with and no separate releases. | The bot connects, commands do nothing | Use the prefix (`!ping`) or a mention (`@Sylo ping`), not `/`. If you changed `COMMAND_PREFIX` or the server's **Command prefix** setting, use the new one. The bot needs permission to read and send messages in that channel. | | "You don't have permission to use this command" | The command needs the same permission as on Discord, or a per-server override blocks it. Check the dashboard's Commands page. | | Login with Fluxer fails or loops | The redirect URL on the application must be exactly `/auth/fluxer/callback`. Behind a proxy set `DASHBOARD_URL` to the public https address. | -| Logged in, but my Fluxer server is missing | You need to own the server, or have Administrator or Manage Server there, and the bot has to be in it. Sign out and in again to refresh the list (it is refreshed automatically about every 10 minutes). | +| Logged in, but my Fluxer server is missing | You need to own the server, or have Administrator or Manage Server there, and the bot has to be in it. A server the bot joins after you signed in appears on your next page load; if it does not, open the server switcher and choose **Refresh server list** (once every 30 seconds), or sign out and in again. | | `Log in with Fluxer` button missing | `FLUXER_CLIENT_SECRET` (and `FLUXER_CLIENT_ID`) must both be set. | | `/health` says forbidden | Your id has to be in `FLUXER_OWNER_IDS` (Fluxer) or `OWNER_IDS` (Discord). The lists are separate on purpose. | | A temporary voice channel is created but I am not moved | Expected on Fluxer. Open the link in the DM from the bot. | diff --git a/docs/mobile-app.md b/docs/mobile-app.md index d03cd0c3..5a35d4ca 100644 --- a/docs/mobile-app.md +++ b/docs/mobile-app.md @@ -435,7 +435,12 @@ difference is how server access is checked: - Both use the server list stored at login. The bot keeps it current: when it sees someone gain or lose Manage Server or Administrator, or become the owner, that server is added to or removed from their list. Neither the dashboard nor - the app sends anyone through the platform login again to refresh it. + the app sends anyone through the platform login again to refresh it. A server the + bot joins later is looked for once on each signed-in person's list (their next + request), and the dashboard's **Refresh server list** action + (`POST /api/v2/account/refresh-guilds`, once per 30 seconds per account, the + caller's own sign-ins only) does the same on demand. Both read the person's + rights through the bot, never through their platform login. - The web dashboard trusts that list for 10 minutes after login, then checks live through the bot, like the app. - For app requests Sylo checks **live, through the bot, on every request**: diff --git a/src/bot/events/adminSnapshot.js b/src/bot/events/adminSnapshot.js index 5e78a624..2ad4bc26 100644 --- a/src/bot/events/adminSnapshot.js +++ b/src/bot/events/adminSnapshot.js @@ -1,11 +1,16 @@ // Discord side of src/bot/lib/adminSnapshot.js: a member's roles change, or the server changes -// owner, and the signed-in person's list of servers they run follows. +// owner, and the signed-in person's list of servers they run follows. Joining a server is noted too, so +// the dashboard looks for it on the lists of the people who run it (src/web/lib/guildListRefresh.js). import { Events } from 'discord.js'; import { guildKey } from '../../platform/platformOf.js'; import { syncAdminSnapshot, syncNewOwner } from '../lib/adminSnapshot.js'; +import { noteGuildJoin } from '../lib/guildJoins.js'; /** @param {import('discord.js').Client} client */ export function register(client) { + client.on(Events.GuildCreate, (guild) => { + noteGuildJoin('discord', guildKey(guild), guild, { ready: client.isReady() }); + }); client.on(Events.GuildMemberUpdate, (_old, member) => { if (member?.guild) void syncAdminSnapshot('discord', guildKey(member.guild), member.guild, member); }); diff --git a/src/bot/fluxerModuleEvents.js b/src/bot/fluxerModuleEvents.js index dc6e108a..dfd740ef 100644 --- a/src/bot/fluxerModuleEvents.js +++ b/src/bot/fluxerModuleEvents.js @@ -11,6 +11,7 @@ import { fluxerReactionAdd } from '../platform/fluxerEvents.js'; import { beginModeration } from '../modules/lib/messageModeration.js'; import { log } from '../lib/log.js'; import { syncAdminSnapshot, syncNewOwner } from './lib/adminSnapshot.js'; +import { noteGuildJoin } from './lib/guildJoins.js'; import { restoreOldRoles } from '../platform/compat.js'; const keyOf = (rawGuildId) => (rawGuildId ? makePlatformGuildId('fluxer', rawGuildId) : null); @@ -117,7 +118,11 @@ export function registerFluxerModuleEvents( on('inviteCreate', (invite) => send('inviteCreate', invite.guildSnapshot?.id, invite)); on('inviteDelete', (payload) => send('inviteDelete', payload.guildId, payload)); - on('guildCreate', (guild) => send('guildCreate', guild.id, guild)); + on('guildCreate', (guild) => { + // The dashboard looks for the new server on the lists of the people who run it (src/web/lib/guildListRefresh.js). + noteGuildJoin('fluxer', keyOf(guild.id), guild, { ready: client.isReady?.() !== false }); + return send('guildCreate', guild.id, guild); + }); on('guildDelete', async (guild) => { // Also fires when a guild merely becomes unavailable; don't wipe data then. if (guild.available === false) return; diff --git a/src/bot/lib/guildJoins.js b/src/bot/lib/guildJoins.js new file mode 100644 index 00000000..3cd178ab --- /dev/null +++ b/src/bot/lib/guildJoins.js @@ -0,0 +1,49 @@ +// When the bot joined each server, as far as this process saw it. A signed-in person's list of +// servers they run comes from sign-in (src/db/accounts.js) and follows the bot's rights events +// (src/bot/lib/adminSnapshot.js), but a server the bot joins afterwards is on nobody's list, so the +// dashboard would not show it until they sign in again. The dashboard compares these times with when +// each person's list was last looked at (src/web/lib/guildListRefresh.js) and re-checks only then. + +/** A join older than this when its event arrives is startup catch-up, not a new server. */ +const RECENT_MS = 5 * 60 * 1000; +/** How long a join is remembered; the dashboard looks at a list on the person's next request. */ +const KEEP_MS = 24 * 60 * 60 * 1000; + +/** @type {Map} guild key -> when the bot joined */ +const joinedAt = new Map(); +/** @type {Record} platform -> when the bot last joined a server there */ +const lastJoin = {}; + +/** + * The bot joined a server (guildCreate). Startup replays every existing server through the same event; + * `ready` is false then, and a join the platform dates long ago is ignored too. + * @param {'discord'|'fluxer'} platform + * @param {string} key the guild key + * @param {{ joinedTimestamp?: number } | null} guild + * @param {{ ready?: boolean, now?: number }} [opts] + */ +export function noteGuildJoin(platform, key, guild, { ready = true, now = Date.now() } = {}) { + if (!key || !ready) return; + const stamp = Number(guild?.joinedTimestamp); + if (Number.isFinite(stamp) && stamp > 0 && now - stamp > RECENT_MS) return; + for (const [k, at] of joinedAt) if (now - at > KEEP_MS) joinedAt.delete(k); + joinedAt.set(key, now); + lastJoin[platform] = now; +} + +/** When the bot last joined a server on this platform (0: not since this process started). */ +export const lastGuildJoin = (platform) => lastJoin[platform] ?? 0; + +/** When the bot joined this server: seen by this process, else the platform's own date, else 0. */ +export function guildJoinedAt(key, guild) { + const seen = joinedAt.get(key); + if (seen) return seen; + const stamp = Number(guild?.joinedTimestamp); + return Number.isFinite(stamp) && stamp > 0 ? stamp : 0; +} + +/** For tests: forget every join. */ +export function resetGuildJoins() { + joinedAt.clear(); + for (const p of Object.keys(lastJoin)) delete lastJoin[p]; +} diff --git a/src/web/lib/guildListRefresh.js b/src/web/lib/guildListRefresh.js new file mode 100644 index 00000000..2db907e3 --- /dev/null +++ b/src/web/lib/guildListRefresh.js @@ -0,0 +1,92 @@ +// Brings a signed-in person's list of servers they run up to date with servers the bot has joined since +// they signed in. The list comes from the platform at sign-in and then follows the bot's own events; +// a new server is on nobody's list until this adds it. Rights are read through the bot (owner, cached +// member, one member fetch), never through the person's OAuth token, which Sylo does not keep. +import { allGuildKeys, guildByKey } from '../../platform/platformOf.js'; +import { splitPlatformGuildId } from '../../lib/platformId.js'; +import { setIdentityGuildAdmin } from '../../db/accounts.js'; +import { guildJoinedAt, lastGuildJoin } from '../../bot/lib/guildJoins.js'; +import { log } from '../../lib/log.js'; + +/** Most member lookups one refresh may make: each is one platform API call. */ +const MAX_LOOKUPS = 25; + +/** @type {Map} "platform:userId" -> when the automatic check last ran for that identity */ +const checkedAt = new Map(); +/** @type {Map>} */ +const running = new Map(); + +const idKey = (identity) => `${identity.platform}:${identity.platformUserId}`; +const platformOfKey = (key) => splitPlatformGuildId(key)?.platform ?? 'discord'; + +/** + * Add the servers this identity runs but has not listed. `check(key, userId)` is the live rights check + * (serverRightsLive in auth.js: `{ right }` or null). Owners are found for free; anyone else costs a + * lookup, made only for servers the bot joined after `since`, and at most MAX_LOOKUPS of them. + * @returns {Promise} how many servers were added + */ +export async function addJoinedGuilds(identity, check, { since = identity.guildsFetchedAt } = {}) { + const listed = new Set(identity.guildIds); + let lookups = 0; + let added = 0; + for (const key of allGuildKeys()) { + if (listed.has(key) || platformOfKey(key) !== identity.platform) continue; + const guild = guildByKey(key); + if (!guild) continue; + const owner = guild.ownerId === identity.platformUserId; + if (!owner && (guildJoinedAt(key, guild) <= since || lookups >= MAX_LOOKUPS)) continue; + if (!owner) lookups += 1; + const live = await check(key, identity.platformUserId).catch(() => null); + if (live?.right && (await setIdentityGuildAdmin(identity.platform, identity.platformUserId, key, true))) { + added += 1; + } + } + return added; +} + +/** + * The automatic refresh, run for the account on each request: an identity is looked at once after the + * bot joins a server on its platform, and not again until the next join. Costs one map lookup per + * identity otherwise. + * @returns {Promise} whether any list changed (the caller then reads the identities again) + */ +export async function refreshAfterJoins(account, check, now = Date.now()) { + let changed = false; + for (const identity of account?.identities ?? []) { + const key = idKey(identity); + if (lastGuildJoin(identity.platform) <= (checkedAt.get(key) ?? 0)) continue; + let work = running.get(key); + if (!work) { + checkedAt.set(key, now); + work = addJoinedGuilds(identity, check) + .catch((err) => { + log.warn('auth', `could not refresh the server list of ${key}: ${err.message}`); + return 0; + }) + .finally(() => running.delete(key)); + running.set(key, work); + } + if ((await work) > 0) changed = true; + } + return changed; +} + +/** + * The "Refresh server list" action: every identity of this account, now, whatever the join times say. + * Only the account's own identities are touched. + * @returns {Promise} servers added + */ +export async function refreshAccountGuilds(account, check, now = Date.now()) { + let added = 0; + for (const identity of account?.identities ?? []) { + checkedAt.set(idKey(identity), now); + added += await addJoinedGuilds(identity, check); + } + return added; +} + +/** For tests. */ +export function resetGuildListRefresh() { + checkedAt.clear(); + running.clear(); +} diff --git a/src/web/lib/routeAccess.js b/src/web/lib/routeAccess.js index fb09e393..85b8a7af 100644 --- a/src/web/lib/routeAccess.js +++ b/src/web/lib/routeAccess.js @@ -25,6 +25,7 @@ export const ROUTE_ACCESS = Object.freeze({ 'GET /guilds': 'self', 'GET /account': 'self', 'POST /account/devices/:id/revoke': 'self', + 'POST /account/refresh-guilds': 'self', 'POST /account/disconnect/:platform': 'self', 'POST /account/delete': 'self', 'GET /changelog': 'self', diff --git a/src/web/middleware/auth.js b/src/web/middleware/auth.js index 84f2c7ac..a6939139 100644 --- a/src/web/middleware/auth.js +++ b/src/web/middleware/auth.js @@ -42,6 +42,7 @@ import { bearerToken, isTokenRequest } from '../lib/bearer.js'; import { enabledProviders, fluxerOrigins, providers, adminGuildIdsFromOAuth } from '../lib/oauthProviders.js'; import { buildBotInvites } from '../lib/botInvites.js'; import { adminKeysOf, identityFor, isOperator, primaryUserId, sessionUserLabel } from '../lib/accountAuth.js'; +import { refreshAfterJoins, refreshAccountGuilds } from '../lib/guildListRefresh.js'; import { clientKey, rateLimit } from './rateLimit.js'; import { hasValidCsrfToken } from './csrf.js'; import { log } from '../../lib/log.js'; @@ -250,6 +251,21 @@ export async function serverRightsLive(key, userId, fetchMember) { return { right, member }; } +/** The live rights check the server-list refresh uses: the bot's cache, else one member lookup. */ +const rightsLive = (key, userId) => serverRightsLive(key, userId, fetchMemberFromGuild); + +/** + * The account with its server lists brought up to date for servers the bot has joined since (see + * src/web/lib/guildListRefresh.js); the same account when nothing changed. + */ +async function withJoinedServers(account) { + if (!(await refreshAfterJoins(account, rightsLive))) return account; + return { ...account, identities: await identitiesOf(account.id) }; +} + +/** "Refresh server list": look at every server the bot joined for this account now. Resolves to the servers added. */ +export const refreshServerLists = (account) => refreshAccountGuilds(account, rightsLive); + /** * Does this person own the guild or hold Manage Server (or Administrator) in it right now? The * live check the dashboard access levels rely on, minus the bot-master role: for what only real server @@ -355,7 +371,10 @@ async function attachAccount(req, _res, next) { if (token !== null) { const record = await findApiToken(token); if (record) { - req.account = { id: record.accountId, identities: await identitiesOf(record.accountId) }; + req.account = await withJoinedServers({ + id: record.accountId, + identities: await identitiesOf(record.accountId), + }); req.viaToken = true; req.apiTokenId = record.id; touchApiToken(record, { ttlMs: API_TOKEN_TTL_MS }).catch((err) => @@ -368,7 +387,10 @@ async function attachAccount(req, _res, next) { if (sid) { const session = await getSession(sid); if (session) { - req.account = { id: session.accountId, identities: await identitiesOf(session.accountId) }; + req.account = await withJoinedServers({ + id: session.accountId, + identities: await identitiesOf(session.accountId), + }); } else { req.session.sid = undefined; // expired or unknown } diff --git a/src/web/routes/v2Api.js b/src/web/routes/v2Api.js index 1db30f44..1f201412 100644 --- a/src/web/routes/v2Api.js +++ b/src/web/routes/v2Api.js @@ -30,6 +30,7 @@ import { currentUser, sessionUserId, botInviteUrls, + refreshServerLists, } from '../middleware/auth.js'; import { checkLevelRewardGrants, @@ -49,7 +50,7 @@ import { accountGuildAccess, checksLive, } from '../middleware/access.js'; -import { limitWhen, platformActionLimit, rateLimit } from '../middleware/rateLimit.js'; +import { clientKey, limitWhen, platformActionLimit, rateLimit } from '../middleware/rateLimit.js'; import { asyncHandler } from '../lib/asyncHandler.js'; import { changelogHandler } from '../lib/changelogFeed.js'; import { ticketsRouter, staffRouter } from './v2Staff.js'; @@ -444,6 +445,25 @@ router.post( }) ); +// "Refresh server list": look again for servers the bot joined since sign-in, for this account's own +// identities only. Each look can cost the platform a member lookup, so once per 30 seconds per account. +const refreshGuildsLimit = rateLimit({ + windowMs: 30_000, + max: 1, + message: 'The server list was just refreshed. Wait a few seconds and try again.', + keyFn: (req) => `refresh-guilds|${req.account?.id ?? clientKey(req)}`, +}); + +router.post( + '/account/refresh-guilds', + refreshGuildsLimit, + asyncHandler(async (req, res) => { + // Open mode lists every server already. + if (!req.account) return res.json({ ok: true, added: 0 }); + res.json({ ok: true, added: await refreshServerLists(req.account) }); + }) +); + router.post( '/account/disconnect/:platform', asyncHandler(async (req, res) => { diff --git a/test/guildListRefresh.test.js b/test/guildListRefresh.test.js new file mode 100644 index 00000000..e88fbdd7 --- /dev/null +++ b/test/guildListRefresh.test.js @@ -0,0 +1,210 @@ +// A server the bot joins after someone signed in shows up in their server list without signing in +// again: the join marks the lists on that platform as due, and the next request looks once. The +// "Refresh server list" action does the same on demand, for the caller's own identities only, at +// most once per 30 seconds per account. See helpers/oauthApp.js for the harness. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { + D_GUILD, + F_GUILD, + memberFetches, + browser, + guildIds, + profiles, + setProfiles, + signIn, + startOAuthApp, + uid, +} from './helpers/oauthApp.js'; + +await startOAuthApp(); + +const { runtime } = await import('../src/runtime.js'); +const { findIdentity } = await import('../src/db/accounts.js'); +const { noteGuildJoin, lastGuildJoin, guildJoinedAt, resetGuildJoins } = + await import('../src/bot/lib/guildJoins.js'); +const { register: registerDiscordSnapshot } = await import('../src/bot/events/adminSnapshot.js'); +const { registerFluxerModuleEvents } = await import('../src/bot/fluxerModuleEvents.js'); + +const tick = () => new Promise((resolve) => setTimeout(resolve, 5)); + +/** A server the bot is in, on one platform's fake client. `ownerId` is who owns it; others are not members. */ +function addGuild(platform, rawId, ownerId) { + const client = runtime.clients[platform]; + const guild = { + id: rawId, + name: `new-${rawId}`, + client, + iconURL: () => null, + members: { + cache: new Map(), + fetch: async (arg) => { + memberFetches.push(arg); + throw new Error('Unknown Member'); + }, + }, + ownerId, + channels: { cache: new Map() }, + roles: { cache: new Map() }, + emojis: { cache: new Map() }, + }; + client.guilds.cache.set(rawId, guild); + return { guild, key: platform === 'discord' ? rawId : `fluxer:${rawId}` }; +} + +const csrf = async (b) => (await (await b.get('/api/v2/csrf')).json()).token; +const refresh = async (b) => { + const res = await b.get('/api/v2/account/refresh-guilds', { + method: 'POST', + headers: { 'x-csrf-token': await csrf(b) }, + }); + return { status: res.status, body: await res.json().catch(() => null) }; +}; + +test.beforeEach(() => resetGuildJoins()); + +// --- the join event ------------------------------------------------------------------ + +test('the join registry ignores startup replays and joins the platform dates long ago', () => { + noteGuildJoin('discord', 'g-startup', { joinedTimestamp: Date.now() }, { ready: false }); + assert.equal(lastGuildJoin('discord'), 0, 'before the client is ready: not a join'); + noteGuildJoin('discord', 'g-old', { joinedTimestamp: Date.now() - 3_600_000 }); + assert.equal(lastGuildJoin('discord'), 0, 'dated an hour ago: not a join'); + noteGuildJoin('discord', 'g-new', { joinedTimestamp: Date.now() - 1000 }); + assert.ok(lastGuildJoin('discord') > 0); + assert.equal(lastGuildJoin('fluxer'), 0, 'the other platform is not touched'); + assert.ok(guildJoinedAt('g-new', null) > 0); + assert.equal(guildJoinedAt('g-other', null), 0); +}); + +test('Discord guildCreate marks the platform, but not before the client is ready', () => { + const client = new EventEmitter(); + client.isReady = () => false; + registerDiscordSnapshot(client); + client.emit('guildCreate', { id: '900000000000000801', client }); + assert.equal(lastGuildJoin('discord'), 0); + client.isReady = () => true; + client.emit('guildCreate', { id: '900000000000000802', client }); + assert.ok(lastGuildJoin('discord') > 0); + assert.equal(lastGuildJoin('fluxer'), 0); +}); + +test('Fluxer guildCreate marks the Fluxer lists, keyed with the platform', async () => { + const client = new EventEmitter(); + const dispatched = []; + registerFluxerModuleEvents(client, { dispatch: (...args) => dispatched.push(args) }); + client.emit('guildCreate', { id: '900000000000000803' }); + await tick(); + assert.ok(lastGuildJoin('fluxer') > 0); + assert.ok(guildJoinedAt('fluxer:900000000000000803', null) > 0); + assert.equal(lastGuildJoin('discord'), 0); + assert.equal(dispatched[0][0], 'guildCreate', 'the modules still get the event'); +}); + +// --- the next request ---------------------------------------------------------------- + +test('a server the bot joins after sign-in appears on the next request, once, without signing in again', async () => { + setProfiles(); + const b = browser(); + await signIn(b, 'discord'); + const before = await guildIds(b); + + const { guild, key } = addGuild('discord', uid('9000000000'), profiles.discord.id); + assert.deepEqual(await guildIds(b), before, 'nothing marks the list yet, so the server is not offered'); + + await tick(); + noteGuildJoin('discord', key, guild); + assert.deepEqual(await guildIds(b), [...before, key].sort()); + assert.ok((await findIdentity('discord', profiles.discord.id)).guildIds.includes(key), 'stored for later'); +}); + +test('after a join each list is looked at once: later requests make no member lookups', async () => { + setProfiles(); + const b = browser(); + await signIn(b, 'discord'); + const { guild, key } = addGuild('discord', uid('9000000000'), 'somebody-else'); + await tick(); + noteGuildJoin('discord', key, guild); + + const lookups = memberFetches.length; + const ids = await guildIds(b); + assert.ok(!ids.includes(key), 'they do not run it'); + assert.equal(memberFetches.length, lookups + 1, 'one lookup for the new server'); + await guildIds(b); + await guildIds(b); + assert.equal(memberFetches.length, lookups + 1, 'not looked at again until the next join'); + + const second = addGuild('discord', uid('9000000000'), 'somebody-else'); + await tick(); + noteGuildJoin('discord', second.key, second.guild); + await guildIds(b); + assert.equal(memberFetches.length, lookups + 2, 'a later join is looked at once more'); +}); + +test('a join on one platform leaves the other platform’s lists alone', async () => { + setProfiles(); + const b = browser(); + await signIn(b, 'discord'); + await signIn(b, 'fluxer', { connect: true }); + const fluxerGuild = addGuild('fluxer', uid('9100000000'), profiles.fluxer.id); + await tick(); + noteGuildJoin('discord', 'unrelated-discord-guild', null); + assert.ok(!(await guildIds(b)).includes(fluxerGuild.key), 'a Discord join says nothing about Fluxer'); + noteGuildJoin('fluxer', fluxerGuild.key, fluxerGuild.guild); + assert.ok((await guildIds(b)).includes(fluxerGuild.key)); + assert.ok((await guildIds(b)).includes(F_GUILD)); + assert.ok((await guildIds(b)).includes(D_GUILD)); +}); + +// --- the Refresh server list action ----------------------------------------------------- + +test('POST /account/refresh-guilds adds what the bot joined and is limited to once per 30 seconds', async () => { + setProfiles(); + const b = browser(); + await signIn(b, 'discord'); + const { key } = addGuild('discord', uid('9000000000'), profiles.discord.id); // no join was noted (a restart) + + assert.ok(!(await guildIds(b)).includes(key)); + const first = await refresh(b); + assert.equal(first.status, 200); + assert.equal(first.body.added, 1); + assert.ok((await guildIds(b)).includes(key)); + + const again = await refresh(b); + assert.equal(again.status, 429); + assert.match(again.body.error, /refreshed/); +}); + +test('the refresh only touches the caller’s own identities', async () => { + setProfiles(); + const a = browser(); + await signIn(a, 'discord'); + const idA = profiles.discord.id; + setProfiles(); + const c = browser(); + await signIn(c, 'discord'); + const idC = profiles.discord.id; + assert.notEqual(idA, idC); + + const { key } = addGuild('discord', uid('9000000000'), idA); + const other = await refresh(c); + assert.equal(other.status, 200, "C's own limit is not used up by A"); + assert.equal(other.body.added, 0); + assert.ok(!(await findIdentity('discord', idA)).guildIds.includes(key), "A's list is not changed by C"); + assert.ok(!(await findIdentity('discord', idC)).guildIds.includes(key)); + + assert.equal((await refresh(a)).body.added, 1); + assert.ok((await findIdentity('discord', idA)).guildIds.includes(key)); + assert.ok(!(await findIdentity('discord', idC)).guildIds.includes(key)); +}); + +test('the refresh needs a sign-in and the CSRF token', async () => { + const anonymous = await browser().get('/api/v2/account/refresh-guilds', { method: 'POST' }); + assert.equal(anonymous.status, 401); + setProfiles(); + const b = browser(); + await signIn(b, 'discord'); + const noToken = await b.get('/api/v2/account/refresh-guilds', { method: 'POST' }); + assert.equal(noToken.status, 403); +}); diff --git a/web-v2/src/__tests__/ServerSwitcherRefresh.test.jsx b/web-v2/src/__tests__/ServerSwitcherRefresh.test.jsx new file mode 100644 index 00000000..d52b69b6 --- /dev/null +++ b/web-v2/src/__tests__/ServerSwitcherRefresh.test.jsx @@ -0,0 +1,88 @@ +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { MemoryRouter, RouterProvider, createMemoryRouter } from 'react-router-dom'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import ServerSwitcher from '../components/ServerSwitcher.jsx'; +import Shell from '../components/Shell.jsx'; +import GuildPicker from '../pages/GuildPicker.jsx'; +import { getGuilds, refreshGuildList } from '../api.js'; + +vi.mock('../api.js', async (importOriginal) => ({ + ...(await importOriginal()), + getGuilds: vi.fn(), + refreshGuildList: vi.fn(), + getOverview: vi.fn().mockResolvedValue(null), + getAnnouncement: vi.fn().mockResolvedValue(null), + getAccount: vi.fn().mockResolvedValue({ open: true, platforms: [], devices: [] }), + getInvites: vi.fn().mockResolvedValue([]), + getCsrfToken: vi.fn().mockResolvedValue('t'), +})); + +const HOME = { id: '123456789012345678', name: 'Home', icon: null, platform: 'discord' }; +const NEW = { id: '223456789012345678', name: 'Brand new', icon: null, platform: 'discord' }; + +describe('"Refresh server list" in the server switcher', () => { + beforeEach(() => { + window.scrollTo = vi.fn(); + Element.prototype.scrollIntoView = vi.fn(); + window.matchMedia = vi.fn().mockReturnValue({ + matches: false, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + }); + getGuilds.mockReset().mockResolvedValue([HOME]); + refreshGuildList.mockReset().mockResolvedValue({ ok: true, added: 1 }); + }); + afterEach(() => vi.clearAllMocks()); + + it('asks the server to look again, then lists the new server', async () => { + getGuilds.mockResolvedValueOnce([HOME]).mockResolvedValue([HOME, NEW]); + const router = createMemoryRouter( + [{ element: , children: [{ path: '/', element: }] }], + { initialEntries: ['/'] } + ); + await act(async () => { + render(); + }); + expect(screen.queryByText('Brand new')).toBeNull(); + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Refresh server list' })); + }); + expect(refreshGuildList).toHaveBeenCalledTimes(1); + expect(getGuilds).toHaveBeenCalledTimes(2); + expect(screen.getAllByText('Brand new').length).toBeGreaterThan(0); + expect(screen.getByRole('status').textContent).toMatch(/refreshed/i); + }); + + it('shows why when the server refuses (the 30 second limit) and keeps the list', async () => { + refreshGuildList.mockRejectedValue(new Error('The server list was just refreshed. Wait a few seconds.')); + render( + + {}} onRefresh={async () => { + await refreshGuildList(); + }} /> + + ); + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Refresh server list' })); + }); + expect(screen.getByRole('status').textContent).toMatch(/just refreshed/); + expect(screen.getAllByText('Home').length).toBeGreaterThan(0); + }); + + it('disables the button while it works', async () => { + let finish; + const onRefresh = () => new Promise((resolve) => (finish = resolve)); + render( + + {}} onRefresh={onRefresh} /> + + ); + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Refresh server list' })); + }); + const busy = screen.getByRole('button', { name: 'Refreshing…' }); + expect(busy.disabled).toBe(true); + await act(async () => finish()); + expect(screen.getByRole('button', { name: 'Refresh server list' }).disabled).toBe(false); + }); +}); diff --git a/web-v2/src/api.js b/web-v2/src/api.js index e93b45e1..ffde6df1 100644 --- a/web-v2/src/api.js +++ b/web-v2/src/api.js @@ -93,6 +93,8 @@ const postJson = (path, body) => }); export const getGuilds = () => apiFetch('/api/v2/guilds').then((d) => d.guilds); +// Look again for servers the bot joined since sign-in (the server switcher's "Refresh server list"). +export const refreshGuildList = () => postJson('/api/v2/account/refresh-guilds', {}); export const getOverview = (guildId) => apiFetch(`/api/v2/guilds/${gid(guildId)}/overview`); // The permission and role-hierarchy health check; `refresh` asks the server to look again now. export const getGuildHealth = (guildId, { refresh = false } = {}) => diff --git a/web-v2/src/components/ServerSwitcher.jsx b/web-v2/src/components/ServerSwitcher.jsx index c0be89b3..d159ad3a 100644 --- a/web-v2/src/components/ServerSwitcher.jsx +++ b/web-v2/src/components/ServerSwitcher.jsx @@ -1,4 +1,4 @@ -import { useEffect, useRef } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { Link, useLocation } from 'react-router-dom'; import PlatformBadge from './PlatformBadge.jsx'; import { getInvites } from '../api.js'; @@ -14,7 +14,8 @@ const GUILD_PAGE = /^\/guilds\/[^/]+(\/.*)?$/; // the FAQ accordion on sylobot.com. `activeGuildId` is Shell's "sticky" // selection (persists onto guild-agnostic pages like Personalizer/Health), // not necessarily the URL's own :guildId. -export default function ServerSwitcher({ guilds, activeGuildId, onSelectGuild }) { +export default function ServerSwitcher({ guilds, activeGuildId, onSelectGuild, onRefresh }) { + const [refresh, setRefresh] = useState({ busy: false, message: '' }); const current = guilds.find((g) => g.id === activeGuildId) ?? null; const multiPlatform = new Set(guilds.map((g) => g.platform)).size > 1; const { data: invites } = useApiData(() => getInvites(), []); @@ -32,6 +33,17 @@ export default function ServerSwitcher({ guilds, activeGuildId, onSelectGuild }) if (detailsRef.current) detailsRef.current.open = false; } + // A server the bot joined after sign-in is not in the list yet: ask the server to look again, then reload it. + async function refreshList() { + setRefresh({ busy: true, message: '' }); + try { + await onRefresh(); + setRefresh({ busy: false, message: 'Server list refreshed.' }); + } catch (err) { + setRefresh({ busy: false, message: err?.message || 'Could not refresh the server list.' }); + } + } + useEffect(() => { function onDocClick(e) { if (detailsRef.current?.open && !detailsRef.current.contains(e.target)) closeMenu(); @@ -115,6 +127,18 @@ export default function ServerSwitcher({ guilds, activeGuildId, onSelectGuild }) {addLinks.length > 1 ? `Add a server on ${inv.label}` : 'Add new server'} ))} + {onRefresh ? ( +
+ + {refresh.message ? ( +

+ {refresh.message} +

+ ) : null} +
+ ) : null} ); diff --git a/web-v2/src/components/Shell.jsx b/web-v2/src/components/Shell.jsx index e856c0f0..2d1b6112 100644 --- a/web-v2/src/components/Shell.jsx +++ b/web-v2/src/components/Shell.jsx @@ -1,6 +1,6 @@ import { Suspense, useEffect, useRef, useState } from 'react'; import { Link, Outlet, ScrollRestoration, useLocation, useParams } from 'react-router-dom'; -import { getGuilds, getPublicSession } from '../api.js'; +import { getGuilds, getPublicSession, refreshGuildList } from '../api.js'; import { readLastGuildId, writeLastGuildId } from '../util.js'; import { isPublicPath } from '../publicRoutes.js'; import { OverviewProvider } from '../OverviewContext.jsx'; @@ -70,6 +70,12 @@ function SignedInShell() { .catch((error) => setState({ loading: false, guilds: [], error })); }, []); + // The switcher's "Refresh server list": the server looks again for servers the bot joined, then the list is read again. + async function refreshGuilds() { + await refreshGuildList(); + setState({ loading: false, guilds: await getGuilds(), error: null }); + } + useEffect(() => { if (guildId) { setLastGuildId(guildId); @@ -114,7 +120,12 @@ function SignedInShell() { Sylo - +