Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion docs/mirror.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,21 @@ the new owner has confirmed it on that server's page.
Settings, then Roles, and drags Sylo's role to the very top (Sylo cannot move its own role), and you look again.
(Without this, a mirrored role with Manage Roles could end up above the mirrored Administrator role.)
3. To be the owner of the Discord server, and the owner of the Fluxer server to agree (or to own both).
The Fluxer server shows up in the picker only if you are its owner.

## The steps

1. **Ask.** The Discord server's owner opens the Mirror page and enters the id of the Fluxer server.
1. **Ask.** The Discord server's owner opens the Mirror page and **picks the Fluxer server from a list**. The
list holds the Fluxer servers where Sylo is a member and where you are the owner, going by the Fluxer login
you connected under Account. Each entry shows the server's name, icon and member count, and a note when Sylo's
role there lacks the Administrator permission or is not the top role (the same checks the preview makes; they
do not stop you from picking, the preview does). A server that is already part of a mirror is shown but cannot
be picked. Picking one fills in the request. If you own the Fluxer server too, both sides agree at once (next
step).
- **No Fluxer login connected?** The page says "Connect Fluxer under Account to pick your Fluxer servers" and
links to Account.
- **The Fluxer server belongs to someone else?** Choose **Enter an id instead** and paste the server's id
(copy it on Fluxer with Developer Mode on). Its owner then agrees with the code, as below.
2. **Agree.** Nothing is created until the owner of the Fluxer server has agreed:
- If you own both servers with your own account (you signed in with Discord and also connected Fluxer under
Account), both sides agree at once.
Expand Down Expand Up @@ -186,6 +197,12 @@ Looking at the page, the preview and the report needs View access. Everything th
server's owner (see the top), on the server the action is made on. Every action looks only at the mirror the server
is part of, so a code or an id of another server reaches nothing.

The list of Fluxer servers on the Ask step (`GET /api/v2/guilds/<id>/mirror/fluxer-servers`) is asked for only by
the owner of the Discord server, is rate limited, and names only Fluxer servers that the caller's own Fluxer login
lists and that Fluxer reports the caller as the owner of. A server somebody else owns is never named, even to its
Administrators. On an instance with sign-in switched off there is no account to compare, so every Fluxer server Sylo
is in is listed, as with the other access checks.

## For the app

A Sylo that has the mirror lists `mirror` in the `features` of `GET /api/mobile/info`. See the
Expand Down
6 changes: 6 additions & 0 deletions docs/modules/bridge.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ Sylo is) and that is a member of both servers.
**Dashboard:** `/v2/guilds/<id>/m/bridge` - the linked channels, a form to ask for a link, a form to use a
code, what this server shares, and pause, resume and unlink.

**Setting up a whole Fluxer server?** Linking channels one by one is for single conversations. To copy a
Discord server's channels, roles and emoji to a Fluxer server and bridge every channel at once, use
[Mirror to Fluxer](../mirror.md). The Bridge page of a Discord server points to it with a short note and a
link; the note is shown only to the server's owner and only when Sylo is connected to both platforms. It is not
shown on a Fluxer server: the mirror's target is chosen from the Discord side.

## Who can use it: the server owner

**Only the owner of a server can use the bridge** (the Discord server owner, the Fluxer server owner), on
Expand Down
2 changes: 2 additions & 0 deletions src/web/lib/routeAccess.js
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,8 @@ export const ROUTE_ACCESS = Object.freeze({
'GET /guilds/:guildId/mirror': 'view',
'GET /guilds/:guildId/mirror/preview': 'view',
'GET /guilds/:guildId/mirror/report': 'view',
// The picker of the Fluxer servers the person owns is part of asking: Edit, and the server owner (checked in the route).
'GET /guilds/:guildId/mirror/fluxer-servers': 'edit',
'POST /guilds/:guildId/mirror/request': 'edit',
'POST /guilds/:guildId/mirror/accept': 'edit',
'POST /guilds/:guildId/mirror/options': 'edit',
Expand Down
88 changes: 80 additions & 8 deletions src/web/routes/v2Mirror.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { PAIR_STATUS, pairsOfGuild, updatePair } from '../../db/mirror.js';
import { recordAudit } from '../../db/audit.js';
import { accessRouter } from '../middleware/access.js';
import { adminGuildIds, currentUser, userIdForGuild } from '../middleware/auth.js';
import { identityFor } from '../lib/accountAuth.js';
import { isGuildOwner } from '../lib/guildOwner.js';
import { platformActionKey, rateLimit } from '../middleware/rateLimit.js';
import { asyncHandler } from '../lib/asyncHandler.js';
Expand All @@ -25,6 +26,7 @@ import { mirror } from '../../mirror/index.js';
import { ConsentError, acceptMirror, requestMirror } from '../../mirror/consent.js';
import { MirrorError } from '../../mirror/errors.js';
import { DEFAULT_OPTIONS, FLUXER_LIMITS, normaliseOptions } from '../../mirror/spec.js';
import { createFluxerTarget } from '../../mirror/target.js';
import { invalidateHealth } from '../../lib/healthCache.js';

const router = accessRouter('/guilds/:guildId', { mergeParams: true });
Expand Down Expand Up @@ -54,6 +56,13 @@ const startLimit = rateLimit({
message: 'The copy was started several times just now. Wait a few minutes.',
keyFn: (req) => `mirror-start|${platformActionKey(req)}`,
});
// The list of the person's Fluxer servers reads each one's roles; it is asked for when the page opens.
const listLimit = rateLimit({
windowMs: 60_000,
max: 12,
message: 'The list of Fluxer servers was asked for too often. Wait a minute.',
keyFn: (req) => `mirror-servers|${platformActionKey(req)}`,
});
const controlLimit = rateLimit({
windowMs: 60_000,
max: 20,
Expand Down Expand Up @@ -118,13 +127,6 @@ function pairView(pair, side) {
async function stateOf(req) {
const platform = platformOfGuild(req.guild);
const found = await pairOf(req);
const candidates =
platform === 'discord' && isGuildOwner(req, req.guild.id)
? [...adminGuildIds(req)]
.filter((k) => splitPlatformGuildId(k)?.platform === 'fluxer')
.filter((k) => isGuildOwner(req, k))
.map((k) => ({ id: k, name: guildByKey(k)?.name ?? k }))
: [];
return {
platform,
canMirror: platform === 'discord',
Expand All @@ -133,7 +135,6 @@ async function stateOf(req) {
isOwner: isGuildOwner(req, req.guild.id),
pair: found ? pairView(found.pair, found.side) : null,
progress: found ? await mirror.progress(found.pair) : null,
candidates,
defaults: DEFAULT_OPTIONS,
limits: { emoji: FLUXER_LIMITS.emoji, stickers: FLUXER_LIMITS.stickers },
};
Expand All @@ -147,6 +148,77 @@ router.get(
})
);

/** How many of a person's Fluxer servers the list names at most. */
const MAX_FLUXER_CHOICES = 100;

/**
* What the picker says about one Fluxer server, checked as the preview checks it (src/mirror/engine.js): Sylo's role
* needs Administrator there (or the four permissions the copy uses) and has to be the highest role. These are
* notes, not blockers: the preview is where they stop a copy.
*/
async function choiceOf(key, guild) {
const notes = [];
try {
const target = createFluxerTarget(guild);
if (target.missingPermissions().length) {
notes.push({
code: 'target-permissions',
message: "Sylo's role needs the Administrator permission on this server.",
});
}
const above = target.rolesAboveSylo([]);
if (above === null) {
notes.push({ code: 'role-hierarchy', message: "Sylo's own role on this server could not be read." });
} else if (above.length > 0) {
notes.push({
code: 'role-hierarchy',
message: `Sylo's role is not the highest on this server (${above.length} ${above.length === 1 ? 'role ranks' : 'roles rank'} above or level with it). Drag it to the top under Server Settings, then Roles.`,
});
}
} catch {
notes.push({ code: 'unreadable', message: 'Sylo could not read the roles on this server just now.' });
}
const busy = (await pairsOfGuild(key)).length > 0;
const members = Number(guild.memberCount ?? guild.members?.cache?.size ?? 0);
return {
id: key,
name: String(guild.name ?? key),
icon: guild.iconURL?.({ size: 64 }) ?? null,
memberCount: Number.isFinite(members) && members > 0 ? members : null,
inUse: busy,
notes,
};
}

// The Fluxer servers to pick the mirror's target from: those Sylo is a member of and the signed-in person owns
// according to their own connected Fluxer login (the owner id Fluxer reports, never a list the browser sends). A
// server they do not own is never named. Only the owner of this Discord server may ask, as for the request itself.
router.get(
'/mirror/fluxer-servers',
listLimit,
asyncHandler(async (req, res) => {
res.set('Cache-Control', 'no-store');
if (platformOfGuild(req.guild) !== 'discord') {
return fail(res, 'Only a Discord server can be mirrored. Ask for the mirror on the Discord server.');
}
if (!needOwner(req, res, 'pick a Fluxer server for a mirror')) return;
// Open mode has no logins, so there is no identity to look for (and every server counts as the caller's).
const connected = !config.authEnabled || Boolean(identityFor(req.account, 'fluxer'));
const servers = [];
if (config.fluxerEnabled && connected) {
const keys = [...adminGuildIds(req)]
.filter((k) => splitPlatformGuildId(k)?.platform === 'fluxer')
.filter((k) => isGuildOwner(req, k));
for (const key of keys.slice(0, MAX_FLUXER_CHOICES)) {
const guild = guildByKey(key);
if (guild) servers.push(await choiceOf(key, guild));
}
servers.sort((a, b) => a.name.localeCompare(b.name));
}
res.json({ fluxerConnected: config.fluxerEnabled, connected, servers });
})
);

/** A raw Fluxer id, or "fluxer:<id>", as a key. Null when it is neither. */
function fluxerKeyOf(raw) {
const text = String(raw ?? '').trim();
Expand Down
1 change: 1 addition & 0 deletions test/v2.accessLevels.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ const GETS_ABOVE_VIEW = {
'GET /guilds/:guildId/applications/submissions/:id': 'inbox',
'GET /guilds/:guildId/applications/export': 'inbox',
'GET /guilds/:guildId/export': 'edit',
'GET /guilds/:guildId/mirror/fluxer-servers': 'edit',
};

test('every /api/v2 route declares its access level, and every declaration has a route', () => {
Expand Down
173 changes: 168 additions & 5 deletions test/v2Mirror.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ test('the owner of the Discord server asks; the owner of the Fluxer server agree
[empty.platform, empty.canMirror, empty.pair, empty.isOwner],
['discord', true, null, true]
);
assert.equal(empty.candidates.length, 0, 'this person owns no Fluxer server');
assert.ok(!('candidates' in empty), 'the Fluxer servers come from their own route');

const res = await anna.post(`/guilds/${D_GUILD}/mirror/request`, { targetGuildId: F_GUILD });
assert.equal(res.status, 200);
Expand Down Expand Up @@ -216,9 +216,9 @@ test('the same person who owns both servers agrees on both sides at once', async
await reset();
const both = await person({ discord: true, fluxer: true });
owners({ discord: both.ids.discord, fluxer: both.ids.fluxer });
const state = await (await both.get(`/guilds/${D_GUILD}/mirror`)).json();
const list = await (await both.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).json();
assert.deepEqual(
state.candidates.map((c) => c.id),
list.servers.map((c) => c.id),
[F_KEY],
'the Fluxer servers this person owns are offered'
);
Expand All @@ -244,8 +244,8 @@ test('an owner of one server who is only an Administrator of the other is not en
await reset();
const mixed = await person({ discord: true, fluxer: true });
owners({ discord: mixed.ids.discord, fluxer: 'someone-else' }); // owns Discord, is not the Fluxer owner
const state = await (await mixed.get(`/guilds/${D_GUILD}/mirror`)).json();
assert.deepEqual(state.candidates, [], 'a Fluxer server they do not own is not offered');
const list = await (await mixed.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).json();
assert.deepEqual(list.servers, [], 'a Fluxer server they do not own is not offered');
const res = await mixed.post(`/guilds/${D_GUILD}/mirror/request`, {
targetGuildId: F_KEY,
options: { mirrorDeletes: true },
Expand Down Expand Up @@ -418,3 +418,166 @@ test('signed out and without a CSRF token, nothing works', async () => {
assert.ok([401, 403].includes(noToken.status));
assert.equal((await anna.get(`/guilds/${D_GUILD}/mirror`)).status, 200);
});

// ---- the picker of the Fluxer servers ------------------------------------------------------------------

const F_OTHER_OWNER = '900000000000000204'; // Fluxer says it is theirs (OAuth), the gateway says it is somebody else's
const F_NOT_LISTED = '900000000000000205'; // the gateway says they own it, their login does not list it
const SYLO_ROLE = '900000000000000301';

/** Add servers to the fake Fluxer bot, run `fn`, and take them away again. */
async function withFluxerGuilds(extra, fn) {
const cache = runtime.clients.fluxer.guilds.cache;
for (const g of extra) cache.set(g.id, g);
try {
return await fn();
} finally {
for (const g of extra) cache.delete(g.id);
}
}
const copyOfF = (id, name, ownerId) => ({ ...fGuild, id, name, ownerId });

/** Sylo's own member on a fake Fluxer server: its permissions and where its role stands among `roles`. */
function syloIs(guild, { administrator = true, roles = [] } = {}) {
guild.members = {
...guild.members,
me: {
permissions: { has: () => administrator },
roles: { highest: { id: SYLO_ROLE, position: 5 } },
},
};
guild.roles = { cache: new Map(roles.map((r) => [r.id, r])) };
}

test('the picker lists the Fluxer servers the person owns and Sylo is in, with a note for what Sylo lacks there', async () => {
await reset();
const both = await person({ discord: true, fluxer: true });
owners({ discord: both.ids.discord, fluxer: both.ids.fluxer });
const saved = { members: fGuild.members, roles: fGuild.roles, memberCount: fGuild.memberCount };
try {
// Sylo is not the top role, and lacks Administrator.
syloIs(fGuild, {
administrator: false,
roles: [
{ id: SYLO_ROLE, name: 'Sylo', position: 5 },
{ id: '900000000000000302', name: 'Admins', position: 9 },
],
});
fGuild.memberCount = 42;
const res = await both.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`);
assert.equal(res.status, 200);
assert.equal(res.headers.get('cache-control'), 'no-store');
const body = await res.json();
assert.equal(body.connected, true);
assert.equal(body.servers.length, 1);
const [one] = body.servers;
assert.deepEqual(
[one.id, one.name, one.memberCount, one.inUse, one.icon],
[F_KEY, 'F-main', 42, false, null]
);
assert.deepEqual(one.notes.map((n) => n.code).sort(), ['role-hierarchy', 'target-permissions']);

// Sylo is the top role with Administrator: no notes.
syloIs(fGuild, { roles: [{ id: SYLO_ROLE, name: 'Sylo', position: 5 }] });
const clean = (await (await both.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).json()).servers[0];
assert.deepEqual(clean.notes, []);

// A server that is already part of a mirror says so.
await both.post(`/guilds/${D_GUILD}/mirror/request`, { targetGuildId: F_KEY });
const taken = (await (await both.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).json()).servers[0];
assert.equal(taken.inUse, true);
} finally {
Object.assign(fGuild, saved);
await reset();
}
});

test('the picker never names a Fluxer server the person does not own', async () => {
await reset();
const other = copyOfF(F_OTHER_OWNER, 'Secret-other-server', 'somebody-else');
const unlisted = copyOfF(F_NOT_LISTED, 'Secret-unlisted-server', 'placeholder');
await withFluxerGuilds([other, unlisted], async () => {
setProfiles();
profiles.fluxer.guilds = [
{ id: F_GUILD, owner: true },
{ id: F_OTHER_OWNER, owner: true },
];
const b = own();
await signIn(b, 'discord');
await signIn(b, 'fluxer', { connect: true });
const get = (path) => b.get(`/api/v2${path}`, { headers: { accept: 'application/json' } });
dGuild.ownerId = profiles.discord.id;
fGuild.ownerId = 'somebody-else';
other.ownerId = 'somebody-else';
unlisted.ownerId = profiles.fluxer.id;

const text = await (await get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).text();
const body = JSON.parse(text);
assert.deepEqual(body.servers, [], 'no server they own: an empty list');
for (const secret of [
'F-main',
'Secret-other-server',
'Secret-unlisted-server',
F_GUILD,
F_OTHER_OWNER,
F_NOT_LISTED,
]) {
assert.ok(!text.includes(secret), `${secret} is not in the answer`);
}

// Now they own the first one only: the other two stay out.
fGuild.ownerId = profiles.fluxer.id;
const mine = await (await get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).json();
assert.deepEqual(
mine.servers.map((x) => x.id),
[F_KEY]
);
});
});

test('the picker says when no Fluxer login is connected, and only the owner of the Discord server may ask', async () => {
await reset();
const discordOnly = await person({ discord: true });
owners({ discord: discordOnly.ids.discord, fluxer: discordOnly.ids.fluxer });
const none = await (await discordOnly.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).json();
assert.deepEqual([none.connected, none.servers], [false, []]);

const admin = await person({ discord: true, fluxer: true, admin: true });
owners({ discord: 'somebody-else', fluxer: admin.ids.fluxer });
const refused = await admin.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`);
assert.equal(refused.status, 403);
const refusedBody = await refused.json();
assert.equal(refusedBody.code, 'owner-only');
assert.ok(!JSON.stringify(refusedBody).includes('F-main'));

const onFluxer = await person({ discord: true, fluxer: true });
owners({ discord: onFluxer.ids.discord, fluxer: onFluxer.ids.fluxer });
assert.equal((await onFluxer.get(`/guilds/${F_KEY}/mirror/fluxer-servers`)).status, 400);

const out = own();
assert.ok(
[401, 403].includes(
(
await out.get(`/api/v2/guilds/${D_GUILD}/mirror/fluxer-servers`, {
headers: { accept: 'application/json' },
})
).status
),
'signed out'
);
});

test('the picker is rate limited and classified in the access table', async () => {
await reset();
const { ROUTE_ACCESS } = await import('../src/web/lib/routeAccess.js');
assert.equal(ROUTE_ACCESS['GET /guilds/:guildId/mirror/fluxer-servers'], 'edit');
const both = await person({ discord: true, fluxer: true });
owners({ discord: both.ids.discord, fluxer: both.ids.fluxer });
let last = 0;
for (let i = 0; i < 14; i++) last = (await both.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).status;
assert.equal(last, 429);
// Another person has a budget of their own.
const next = await person({ discord: true, fluxer: true });
owners({ discord: next.ids.discord, fluxer: next.ids.fluxer });
assert.equal((await next.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).status, 200);
});
Loading
Loading