From 1072ce995e878e43332ef2eec7dfd127b3360b0d Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Mon, 16 Nov 2026 22:47:50 +0100
Subject: [PATCH 01/17] feat(bridge): link a Discord channel to a Fluxer
channel
A new Bridge module shares one conversation between a Discord channel and a
Fluxer channel. Both servers agree: one asks for a link and gets a one-time
code (hashed, valid 15 minutes), someone with Edit access in the other server
uses it. Either side can pause or unlink at any time.
Messages cross through webhooks Sylo makes in each channel, with the author's
name and picture. Replies are quoted, files are re-uploaded within limits
(otherwise a link), custom emoji map by name, stickers become a picture link,
rich embeds cross, polls become text and joins are optional. Edits and deletes
follow through a message map that keeps a message for 30 days.
Safety: no ping crosses (allowed mentions none, mentions turned into names),
Sylo's own bridge messages are never relayed again, bots are off by default,
an age-restricted channel only links to an age-restricted channel (checked on
every message), a notice shows in both channels, each webhook has its own
rate-limited queue with back-off, and a failing link is stopped, shown in
Health and not retried.
Adds migration 83 (versions 81 and 82 stay empty placeholders until the
other 5.3 changes land), the Bridge page in the dashboard, the `bridge`
feature string in /api/mobile/info and a docs page.
---
README.md | 4 +-
docs/dashboard-v2.md | 2 +-
docs/fluxer.md | 1 +
docs/mobile-app.md | 3 +-
docs/modules/README.md | 1 +
docs/modules/bridge.md | 85 ++
src/db/bridge.js | 469 +++++++++++
src/db/index.js | 63 ++
src/db/purge.js | 25 +
src/db/retention.js | 7 +
src/modules/bridge.js | 1087 ++++++++++++++++++++++++++
src/modules/index.js | 1 +
src/modules/lib/bridgeQueue.js | 161 ++++
src/modules/lib/bridgeText.js | 285 +++++++
src/modules/registry.js | 11 +
src/platform/modulePlatformNotes.js | 2 +
src/platform/webhooks.js | 146 ++++
src/web/lib/cardSummary.js | 5 +
src/web/lib/configImport.js | 2 +
src/web/lib/moduleIcons.js | 1 +
src/web/lib/overviewSummary.js | 10 +
src/web/lib/permissionHealth.js | 27 +-
src/web/lib/routeAccess.js | 10 +
src/web/routes/mobile.js | 3 +
src/web/routes/v2Api.js | 3 +
src/web/routes/v2Bridge.js | 169 ++++
test/bridge.db.test.js | 381 +++++++++
test/bridge.engine.test.js | 1045 +++++++++++++++++++++++++
test/bridge.postgres.test.js | 125 +++
test/bridgeHealth.test.js | 73 ++
test/bridgeQueue.test.js | 208 +++++
test/bridgeText.test.js | 219 ++++++
test/bridgeTransport.test.js | 88 +++
test/helpers/fakeBridge.js | 173 ++++
test/mobileInfo.test.js | 4 +
test/v2Bridge.test.js | 381 +++++++++
web-v2/src/__tests__/Bridge.test.jsx | 296 +++++++
web-v2/src/api.js | 13 +
web-v2/src/main.jsx | 1 +
web-v2/src/moduleForms/Bridge.jsx | 410 ++++++++++
web-v2/src/moduleForms/index.js | 2 +
web-v2/src/pages/ModulePage.jsx | 2 +-
web-v2/src/styles/bridge.css | 45 ++
43 files changed, 6043 insertions(+), 6 deletions(-)
create mode 100644 docs/modules/bridge.md
create mode 100644 src/db/bridge.js
create mode 100644 src/modules/bridge.js
create mode 100644 src/modules/lib/bridgeQueue.js
create mode 100644 src/modules/lib/bridgeText.js
create mode 100644 src/platform/webhooks.js
create mode 100644 src/web/routes/v2Bridge.js
create mode 100644 test/bridge.db.test.js
create mode 100644 test/bridge.engine.test.js
create mode 100644 test/bridge.postgres.test.js
create mode 100644 test/bridgeHealth.test.js
create mode 100644 test/bridgeQueue.test.js
create mode 100644 test/bridgeText.test.js
create mode 100644 test/bridgeTransport.test.js
create mode 100644 test/helpers/fakeBridge.js
create mode 100644 test/v2Bridge.test.js
create mode 100644 web-v2/src/__tests__/Bridge.test.jsx
create mode 100644 web-v2/src/moduleForms/Bridge.jsx
create mode 100644 web-v2/src/styles/bridge.css
diff --git a/README.md b/README.md
index b85a430f..8a243c3b 100644
--- a/README.md
+++ b/README.md
@@ -89,14 +89,14 @@ tier.
iOS app with push notifications for new tickets.
-All 43 modules
+All 44 modules
| Area | Modules |
|---|---|
| **Moderation & safety** | [Moderation](docs/modules/moderation.md) (case log, warnings, auto-actions) · [Auto-moderation](docs/modules/automod.md) (can sync to Discord's native AutoMod) · [Server logging](docs/modules/logging.md) · [Verification](docs/modules/verification.md) (button or Turnstile captcha) · [Ban appeals](docs/modules/appeals.md) · [Tickets / modmail](docs/modules/tickets.md) · [Applications](docs/modules/applications.md) (forms for staff to accept or deny) · [Channel cleanup](docs/modules/channel-cleanup.md) · Honeypot (beta) |
| **Welcome & roles** | [Welcome & leave](docs/modules/welcome.md) · [Welcome channel](docs/modules/welcome-channel.md) · [Introductions](docs/modules/introductions.md) (membership cards) · [Reaction roles & autoroles](docs/modules/roles.md) (emoji, buttons or dropdown) · [Temporary roles](docs/modules/temp-roles.md) (beta) · [Birthdays](docs/modules/birthdays.md) |
| **Engagement** | [Leveling](docs/modules/leveling.md) (image rank cards, public leaderboard) · [Economy](docs/modules/economy.md) (currency and shop, beta) · [Invite tracker](docs/modules/invite-tracker.md) · [Starboard](docs/modules/starboard.md) · [Quote board](docs/modules/quote-board.md) (beta, optional public page) · [Polls](docs/modules/polls.md) · [Giveaways](docs/modules/giveaways.md) · [Events](docs/modules/events.md) (beta) · [Suggestions](docs/modules/suggestions.md) (beta) · [Counting](docs/modules/counting.md) · [Game stats](docs/modules/game-stats.md) (Battlefield, OSRS, RS3) |
-| **Automation** | [Custom commands](docs/modules/custom-commands.md) · [Autoresponder](docs/modules/autoresponder.md) · [Auto-react](docs/modules/auto-react.md) · [Auto threads](docs/modules/auto-threads.md) (beta, Discord only) · [Reminders](docs/modules/reminders.md) · [Sticky messages](docs/modules/sticky.md) · [AFK](docs/modules/afk.md) · [Temporary voice channels](docs/modules/temp-voice.md) |
+| **Automation** | [Custom commands](docs/modules/custom-commands.md) · [Autoresponder](docs/modules/autoresponder.md) · [Auto-react](docs/modules/auto-react.md) · [Auto threads](docs/modules/auto-threads.md) (beta, Discord only) · [Bridge](docs/modules/bridge.md) (Discord ↔ Fluxer, beta) · [Reminders](docs/modules/reminders.md) · [Sticky messages](docs/modules/sticky.md) · [AFK](docs/modules/afk.md) · [Temporary voice channels](docs/modules/temp-voice.md) |
| **Alerts** | [Twitch](docs/modules/twitch-alerts.md) · [YouTube](docs/modules/youtube-alerts.md) · [Kick](docs/modules/kick-alerts.md) · [RSS / Atom](docs/modules/rss.md) (also Reddit, Mastodon, Bluesky) · [GitHub](docs/modules/github.md) · [Free games](docs/modules/free-games.md) · [App Store Connect](docs/modules/apple-connect.md) (instance operator only) |
| **Insights** | [Server statistics](docs/modules/server-stats.md) (live counter channels) · [Server insights](docs/modules/insights.md) (activity charts, aggregate counts only) |
diff --git a/docs/dashboard-v2.md b/docs/dashboard-v2.md
index 3c55bf9f..09c6515f 100644
--- a/docs/dashboard-v2.md
+++ b/docs/dashboard-v2.md
@@ -26,7 +26,7 @@ note.
## What the dashboard shows
-- **Sidebar shows only what's turned on.** Instead of listing all 43 modules
+- **Sidebar shows only what's turned on.** Instead of listing all 44 modules
with an on/off dot, the sidebar lists just the modules enabled for whichever
server you're looking at, grouped the same way the Dashboard/Overview page
groups them. Turn a module on from Overview and it appears in the sidebar
diff --git a/docs/fluxer.md b/docs/fluxer.md
index b9625071..bb2fb9ff 100644
--- a/docs/fluxer.md
+++ b/docs/fluxer.md
@@ -238,6 +238,7 @@ does not register anything with Fluxer for these.
| `/intro create` and the **Create my intro** button | **Introductions** uses `!intro create`, then asks the questions in DM, as on Discord. Sylo answers "Check your DMs" in the channel and removes that message after about 15 seconds. The **Create my intro** button of the prompt message, and **Post** and **Start over** under the preview in DM, are shown as reactions. |
| `/apply start` and the **Applications** panel | **Applications** uses `!apply start
- Both servers agree. One asks for a link and gets a code that works for 15 minutes; someone with Edit
- access in the other server uses it and picks a channel. Sylo has to be in both servers. Either side
- can unlink at any time.
+ Both servers agree. One asks for a link and gets a code that works for 15 minutes; the owner of the
+ other server uses it and picks a channel. Sylo has to be in both servers. Either side can unlink at
+ any time.
What crosses: messages, replies (as a short quote), files up to 8 MB (otherwise a link), custom
@@ -244,6 +245,7 @@ export default function Bridge() {
/>
{link.problem ?
{link.problem.text}
: null}
+ {link.pauseNote ?
{link.pauseNote}
: null}
{link.pausedByThem ? (
{link.theirs.server} paused this bridge. Only they can resume it.
@@ -251,14 +253,14 @@ export default function Bridge() {
) : null}
What this server shares
-
+
+
+ Only the server owner can ask for a link, use a code, change what this server shares, or pause,
+ resume and unlink a bridge. You can see the status here.
+
+ ) : null}
+
+
);
}
@@ -253,8 +352,8 @@ function AgreeStep({ guildId, pair, onState, code }) {
Waiting for the Fluxer server
- Nothing is created until someone with Edit access on the Fluxer server has agreed. Ask them to open
- Sylo's dashboard for that server, go to Mirror to Fluxer and enter the code.
+ Nothing is created until the owner of the Fluxer server has agreed. Ask them to open Sylo's dashboard
+ for that server, go to Mirror to Fluxer and enter the code.
{left ? `The code works for another ${left}.` : 'The code has expired.'} Asking again gives a new one.
- If you have Edit access on the Fluxer server yourself, sign in with Fluxer too (Account) and ask
- again: both sides agree at once.
+ If you own the Fluxer server yourself, sign in with Fluxer too (Account) and ask again: both sides
+ agree at once.
+ ) : null}
))}
@@ -354,14 +457,14 @@ function PreviewStep({ guildId, state, onState }) {
Both servers agreed. The preview shows what the copy would do and what cannot be carried over. It
creates nothing.
-
+
-
+
-
+
-
+
{problem ?
{problem}
: null}
{loading ?
Reading both servers…
: null}
@@ -425,7 +528,7 @@ function PreviewResult({ preview, onStart, working }) {
))}
-
+
-
+
);
}
@@ -446,7 +549,6 @@ function RunningStep({ guildId, state, onState }) {
const { working, act } = useAct(onState);
const [reported, setReported] = useState(null);
const [again, setAgain] = useState(null);
- const { can } = useAccess();
// A finished or running copy changes the report: an older one is not shown.
const reportKey = `${pair.copyRun}:${pair.status}`;
@@ -465,11 +567,7 @@ function RunningStep({ guildId, state, onState }) {
The mirror was stopped. What Sylo made on Fluxer is still there. To mirror again, ask for a new
@@ -494,7 +592,7 @@ function RunningStep({ guildId, state, onState }) {
) : null}
Changes on Fluxer to mirrored channels and roles are overwritten the next time that item changes on
Discord. Sylo never deletes something on Fluxer that it did not create.
@@ -687,7 +769,7 @@ function TargetView({ guildId, state, onState }) {
emoji here, and keep them in step with Discord. Nothing is deleted. If you agree, enter the code
they gave you.
-
+
-
+
>
) : (
<>
The Discord server is the source: what changes there is applied here. Changes made here to
mirrored channels and roles are overwritten the next time that item changes on Discord. Sylo never
- deletes something here that it did not create. Anyone with Edit access can pause or stop the
+ deletes something here that it did not create, and by default does not delete here when something
+ is deleted on Discord: the copy is locked and marked as removed. Changing a mirrored category also
+ changes the channels here that are synced with it. Only the server owner can pause or stop the
mirror.
-
+
>
)}
diff --git a/web-v2/src/styles/mirror.css b/web-v2/src/styles/mirror.css
index 93c8bdd5..dbcc2fb9 100644
--- a/web-v2/src/styles/mirror.css
+++ b/web-v2/src/styles/mirror.css
@@ -124,3 +124,18 @@
align-items: flex-start;
}
}
+
+.v2-mirror-option {
+ flex-wrap: wrap;
+}
+.v2-mirror-option-hint {
+ flex-basis: 100%;
+ margin: 0 0 6px;
+}
+.v2-mirror-removed ul {
+ margin: 4px 0 8px;
+ padding-left: 22px;
+ display: grid;
+ gap: 4px;
+ overflow-wrap: anywhere;
+}
From 926c8ff9d2a2184a33a3d0201261a4199977a6dd Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Tue, 17 Nov 2026 00:29:30 +0100
Subject: [PATCH 06/17] fix(mirror): compare Sylo's role rank, grant powerful
permissions after ordering, Fluxer owner allows deletion
Review round 2 for the server mirror.
- The role-hierarchy check compares Sylo's rank on Fluxer (position, then the
older id), not its position number: a fresh server with Sylo at position 1 is
fine, a role above or level with Sylo's blocks the copy with advice naming the
roles and how the Fluxer owner moves Sylo's role. The same test pauses a
continuous reorder.
- A new role is made without its powerful permissions and gets them only after
the role order is set (the order step also runs for a single role); if the
order cannot be set the role stays without them.
- Real deletion ("Mirror deletions") is only asked for by the Discord owner and
takes effect when the Fluxer owner allows it; resuming with deletes waiting
lists them for confirmation, and with real deletion on only the Fluxer owner
can confirm.
- A 5xx whose status is only in the SDK error's cause is retried, a copied
economy comes over switched off, and the docs note which channels carry the
age flag.
---
docs/mirror.md | 33 ++--
docs/mobile-app.md | 2 +-
src/db/mirror.js | 14 ++
src/mirror/engine.js | 184 +++++++++++++++++----
src/mirror/errors.js | 3 +-
src/mirror/plan.js | 16 +-
src/mirror/spec.js | 3 +
src/mirror/target.js | 39 ++++-
src/web/lib/routeAccess.js | 1 +
src/web/routes/v2Mirror.js | 56 ++++++-
test/helpers/mirrorFakes.js | 44 ++++-
test/mirrorGuards.test.js | 197 ++++++++++++++++++-----
test/mirrorSpec.test.js | 1 +
test/mirrorTarget.test.js | 39 ++++-
test/v2Mirror.test.js | 33 +++-
web-v2/src/__tests__/Mirror.test.jsx | 99 +++++++++++-
web-v2/src/__tests__/mirrorModel.test.js | 11 ++
web-v2/src/api.js | 6 +
web-v2/src/mirrorModel.js | 10 +-
web-v2/src/pages/Mirror.jsx | 85 +++++++++-
20 files changed, 763 insertions(+), 113 deletions(-)
diff --git a/docs/mirror.md b/docs/mirror.md
index 64dd961a..096fb80d 100644
--- a/docs/mirror.md
+++ b/docs/mirror.md
@@ -25,10 +25,13 @@ the new owner has confirmed it on that server's page.
1. A Fluxer server for the copy. Create an empty one: Sylo never deletes anything it did not make itself, so an
empty server gives the cleanest result.
-2. Sylo in that server, with a role that has the **Administrator** permission, **moved to the top of the role list**.
- Sylo can only order roles below its own, and Fluxer ranks a new role at the bottom and breaks ties by age, so the
- preview refuses to start while Sylo's role is too low to give every copied role its own place. (Without this, a
- mirrored role with Manage Roles could end up above the mirrored Administrator role.)
+2. Sylo in that server, with a role that has the **Administrator** permission, **at the very top of the role list**.
+ Sylo can only order the roles below its own. Fluxer ranks roles by position and then by age, and every new role (a
+ bot's too) starts at position 1, so a position number says nothing: what counts is the rank. On a fresh server where
+ Sylo has just been invited, its role is already the top one and nothing needs doing. If another role ranks above or
+ level with Sylo's, the preview refuses to start and names those roles: the Fluxer server's owner opens Server
+ 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 steps
@@ -60,7 +63,7 @@ still finishes.
| Server name, icon, banner | The same (each can be switched off). A missing icon or banner is left as it is on Fluxer. |
| Roles | Name, colour, hoist, mentionable, order and permissions. Managed roles (a bot's, an integration's) are not copied. |
| @everyone | Its permissions are set on the Fluxer @everyone role, without powerful permissions (Administrator, Manage Roles and the like are never copied onto @everyone). The role itself is never created or deleted. |
-| Categories and channels | Text, voice, announcement, forum and media channels: name, topic, order, category, slowmode, age restriction (a server marked age-restricted gives every copied channel the flag), bitrate, user limit, and the permission overwrites. A stage channel becomes a voice channel. Threads are not copied. |
+| Categories and channels | Text, voice, announcement, forum and media channels: name, topic, order, category, slowmode, age restriction (a server marked age-restricted gives every copied text, announcement, forum and media channel the flag; voice channels and categories carry no flag), bitrate, user limit, and the permission overwrites. A stage channel becomes a voice channel. Threads are not copied. |
| Emoji and stickers | Up to 500 of each, within 512 KB per emoji and per sticker. Lottie stickers are not copied. |
| Sylo's own settings | The settings and on/off state of each module (not the operator's own modules, and not the bridge), with channels and roles pointing at the new ones. See the checks below. A module that already has settings on the Fluxer server is left alone. |
@@ -79,7 +82,8 @@ whatever else is copied: with roles switched off, or if the @everyone step fails
The copied settings pass the same rules as saving them in the dashboard. A role with powerful permissions is not
handed out by the copied settings (autoroles, reaction roles, level rewards, the verified role, the birthday role,
command actions): that part is left out and the report says so. A giveaway that pings @here or @everyone is copied
-with the ping off. Other ids that mean nothing on Fluxer (the ids of people, of messages, of things that were not
+with the ping off. The economy module comes over switched off (its settings are copied, so you can look at the income and the shop
+first). Other ids that mean nothing on Fluxer (the ids of people, of messages, of things that were not
copied) are cleared, and the report counts them. Set them again on the Fluxer server if you need them.
### Permissions, bit by bit
@@ -109,10 +113,14 @@ update, and a drag that moves many channels becomes one reorder.
from @everyone and made read-only (its messages are kept: deleting a Fluxer channel deletes its messages), a
role loses its permissions, and it is listed on the Mirror page as "Removed on Discord" for the Fluxer owner to
look at and delete. Only with **Delete on Fluxer what is deleted on Discord** switched on is the copy really
- deleted (with its messages). The option is off by default and carries a warning.
+ deleted (with its messages). The option is off by default and carries a warning. The Discord owner can only *ask* for
+ it: it stays off until the owner of the Fluxer server allows it on their Mirror page, because deleting a Fluxer channel
+ destroys messages that exist only there. The Fluxer owner can switch it off again, and so can the Discord owner.
- **A burst of deletions pauses the mirror.** More than five deletions on Discord within ten minutes (a nuke, a
mistaken clean-up) pause the mirror, with the reason in Health on both servers. The deletions wait in the queue and
- are applied only when the owner presses **Apply the deletions** in the dashboard and confirms.
+ are applied only when the owner confirms in the dashboard, in a dialog that lists what will be locked or deleted
+ (with real deletion on, only the Fluxer owner can confirm). The same confirmation is asked when a paused mirror is
+ resumed with more than five deletions waiting.
- Sylo **never deletes something on Fluxer that it did not create.** A Fluxer channel that was there before the
mirror stays, even with the same name as a copied one. Only what Sylo made (and what Sylo's id map shows as made
by Sylo) is ever locked or deleted, and only when its Discord original is deleted.
@@ -136,9 +144,12 @@ update, and a drag that moves many channels becomes one reorder.
- **A failing mirror pauses itself** after a few failures in a row, with the reason, and shows up in
[Health](dashboard-v2.md). Fix the cause (for example give Sylo's role the missing permission on Fluxer), then
press **Resume**. A single item Fluxer refuses (a name it does not accept) is reported and the copy goes on.
-- **The role order is exact.** Sylo sends a distinct position to every mirrored role, in Discord's order, all under
- Sylo's own role. If they do not fit (a new role was added and Sylo's role is too low) the mirror pauses instead of
- squeezing roles together.
+- **The role order is exact, and powerful permissions come last.** Sylo sends a distinct position to every mirrored
+ role, in Discord's order, all under its own role. A new role is first made without its powerful permissions
+ (Administrator, Manage Roles and the like), because a new role starts at the bottom where a member with Manage Roles
+ could hand it out; only after the order is set does Sylo give it its permissions. If a role ranks above Sylo's (the
+ order cannot be set) the mirror pauses with the roles named, and the new role stays without its permissions until the
+ Fluxer owner has fixed it and the mirror is resumed.
- **Limits.** Sylo plans with Fluxer's defaults (500 emoji and 500 stickers per server, 512 KB per emoji and per
sticker). If Fluxer refuses more because of its own limit, Sylo stops that kind and lists the rest in the report.
diff --git a/docs/mobile-app.md b/docs/mobile-app.md
index 9c997791..44559c56 100644
--- a/docs/mobile-app.md
+++ b/docs/mobile-app.md
@@ -338,7 +338,7 @@ The feature strings:
- `duplicate`: the `duplicate` routes for reminders, embed messages, reaction-role sets, custom commands and shop items.
- `message-templates`: the built-in message templates and the raw message JSON import and export.
- `message-move`: when the channel of a posted **embed message**, the **Welcome channel** message or a **role panel** changes and is published, the server posts a fresh message in the new channel, stores it and then deletes the old one, so the app must not unpublish first. Other bot posts (verification, honeypot traps, applications and so on) are not covered. A publish that loses a race with another publish of the same embed message answers `409` with the current record.
-- `mirror`: the [Mirror to Fluxer](mirror.md) routes under `/api/v2/guilds/:id/mirror`: `GET` the state (the pair, its progress and the Fluxer servers the person manages), `GET …/preview` (the dry run) and `GET …/report`, and `POST …/request`, `…/accept`, `…/options`, `…/start`, `…/pause`, `…/resume`, `…/stop` and `…/remove`. Reading needs View; changing anything needs Edit and, on top of that, the owner of the server the call is made on (an Administrator is not enough): any other person gets `403` with `code: "owner-only"`. The state answer carries `isOwner`, so the app can disable the controls.
+- `mirror`: the [Mirror to Fluxer](mirror.md) routes under `/api/v2/guilds/:id/mirror`: `GET` the state (the pair, its progress and the Fluxer servers the person manages), `GET …/preview` (the dry run) and `GET …/report`, and `POST …/request`, `…/accept`, `…/options`, `…/deletes` (the Fluxer server's owner allows real deletion that the Discord owner asked for), `…/start`, `…/pause`, `…/resume`, `…/stop` and `…/remove`. Reading needs View; changing anything needs Edit and, on top of that, the owner of the server the call is made on (an Administrator is not enough): any other person gets `403` with `code: "owner-only"`. The state answer carries `isOwner`, so the app can disable the controls.
- `app-connect`: [adding the other login](#adding-the-other-login). Only where sign-in is on and both Discord and Fluxer logins are set up.
- `push`, `push-pigeon`: this instance can send notifications to signed-in apps.
diff --git a/src/db/mirror.js b/src/db/mirror.js
index 9c9fb9e8..c26af229 100644
--- a/src/db/mirror.js
+++ b/src/db/mirror.js
@@ -198,6 +198,12 @@ const s = {
recentDeletes: prepare(
"SELECT COUNT(*) AS n FROM mirror_jobs WHERE pair_id = ? AND op = 'delete' AND created_at >= ?"
),
+ pendingDeletes: prepare(
+ "SELECT * FROM mirror_jobs WHERE pair_id = ? AND op = 'delete' AND status = 'pending' ORDER BY id LIMIT ?"
+ ),
+ countPendingDeletes: prepare(
+ "SELECT COUNT(*) AS n FROM mirror_jobs WHERE pair_id = ? AND op = 'delete' AND status = 'pending'"
+ ),
deleteId: prepare('DELETE FROM mirror_ids WHERE pair_id = ? AND kind = ? AND source_id = ?'),
insertJob: prepare(
@@ -543,3 +549,11 @@ export async function pruneMirrorJobs({ before, pairId, keepRun }) {
if (before) await s.pruneJobs.run(before);
if (pairId && keepRun) await s.pruneOldRuns.run(pairId, keepRun);
}
+
+/** The deletes still waiting in a pair's queue: how many, and the first `limit` of them. */
+export async function listPendingDeletes(pairId, limit = 50) {
+ return {
+ count: num((await s.countPendingDeletes.get(pairId))?.n),
+ jobs: (await s.pendingDeletes.all(pairId, limit)).map(toJob),
+ };
+}
diff --git a/src/mirror/engine.js b/src/mirror/engine.js
index bda64bd8..07308533 100644
--- a/src/mirror/engine.js
+++ b/src/mirror/engine.js
@@ -46,7 +46,7 @@ import {
roleSkipReason,
specHash,
} from './spec.js';
-import { keepFluxerOnly } from './permissions.js';
+import { ELEVATED_FLUXER_MASK, keepFluxerOnly } from './permissions.js';
const { PAIR_STATUS } = store;
const KINDS_WITH_MAP = ['role', 'channel', 'emoji', 'sticker', 'guild', 'order', 'module'];
@@ -170,6 +170,39 @@ export function createEngine(overrides = {}) {
};
}
+ /**
+ * What to tell the person when Sylo's role is not above the roles it has to order. Sylo cannot move its own role: the
+ * owner of the Fluxer server drags it (Server Settings, Roles).
+ * @param {Array<{ name: string }> | null} above the roles that rank above or level with Sylo's, or null when unknown
+ */
+ function hierarchyAdvice(above) {
+ if (above === null) {
+ return "Sylo's own role on the Fluxer server could not be read. Check that Sylo is in the server with a role, then look again.";
+ }
+ const names = above.slice(0, 5).map((r) => r.name || r.id);
+ const more = above.length > names.length ? ` and ${above.length - names.length} more` : '';
+ return `Sylo's role has to be the highest role on the Fluxer server (above every role except @everyone), or it cannot order the copied roles. These roles rank above or level with it: ${names.join(', ')}${more}. On Fluxer, the server owner opens Server Settings, then Roles, and drags Sylo's role to the very top (Sylo cannot move its own role); then look again here.`;
+ }
+
+ /** The roles on Fluxer that rank above Sylo's (ignoring the roles the mirror made, which are ordered under it). */
+ async function rolesAboveSylo(pairId, target) {
+ const own = (await store.listMappings(pairId, 'role')).filter((m) => m.owned).map((m) => m.targetId);
+ return target.rolesAboveSylo(own);
+ }
+
+ /** The copied roles in Discord's order, lowest first: the order they are sent to Fluxer in. */
+ const roleOrderOf = (ctx) =>
+ ctx.source.roles
+ .filter((r) => ctx.sets.copiedRoles.has(r.id))
+ .sort((a, b) => a.position - b.position || (a.id < b.id ? -1 : 1))
+ .map((r) => r.id);
+
+ /** Has the current order of the copied roles been set on Fluxer? */
+ async function rolesOrdered(ctx) {
+ const m = await store.getMapping(ctx.pair.id, 'order', 'roles');
+ return Boolean(m && m.specHash === specHash(roleOrderOf(ctx)));
+ }
+
// --- the dry run -----------------------------------------------------------------------------------
/**
@@ -207,14 +240,12 @@ export function createEngine(overrides = {}) {
const targetSnap = snapshotFluxerGuild(tg);
const sets = copiedSets(source, options);
if (options.roles && sets.copiedRoles.size > 0) {
- // Fluxer ranks a new role at the bottom and ties by age, so the order only comes out right when every
- // mirrored role has its own place under Sylo's role. Otherwise a lower role could outrank a higher one.
- const top = target.topPosition();
- if (top === null || top - 1 < sets.copiedRoles.size) {
- blockers.push({
- code: 'role-hierarchy',
- message: `Sylo's role on the Fluxer server is too low to order the ${sets.copiedRoles.size} roles that would be copied: move Sylo's role to the top of the role list there, then look again.`,
- });
+ // Fluxer ranks roles by position and then by age, and a new role starts at the bottom. Sylo can only order the
+ // roles below its own, so its role has to outrank every other role there. A position number is not a rank (a
+ // fresh server has Sylo at position 1 and is fine), so the rank is compared, not the number.
+ const above = await rolesAboveSylo(pair.id, target);
+ if (above === null || above.length > 0) {
+ blockers.push({ code: 'role-hierarchy', message: hierarchyAdvice(above) });
}
}
const plan = buildPlan({
@@ -227,7 +258,7 @@ export function createEngine(overrides = {}) {
});
const existing = [
[targetSnap.channels.length, 'channel(s)'],
- [targetSnap.roles.filter((r) => !r.isEveryone).length, 'role(s)'],
+ [targetSnap.roles.filter((r) => !r.isEveryone && !r.managed).length, 'role(s)'],
[targetSnap.emojiCount, 'emoji'],
[targetSnap.stickerCount, 'sticker(s)'],
].filter(([n]) => n > 0);
@@ -466,7 +497,14 @@ export function createEngine(overrides = {}) {
if (!ctx.sets.copiedRoles.has(roleId)) return skipped(roleSkipReason(role) ?? 'roles are not copied');
const { spec, notes } = buildRoleSpec(role);
const hash = specHash(spec);
+ // A role is made without its powerful permissions and gets them only once its place in the order is set: a new
+ // role starts at the bottom of the list, where a member with Manage Roles could hand it out. `specHash ''` marks
+ // a role that still waits for them (the role-order job asks for them again once the order is set).
+ const stripped = { ...spec, permissions: String(BigInt(spec.permissions) & ~ELEVATED_FLUXER_MASK) };
+ const elevated = stripped.permissions !== spec.permissions;
const m = await store.getMapping(ctx.pair.id, 'role', roleId);
+ const waiting = elevated && (!m || m.specHash === '') && !(await rolesOrdered(ctx));
+ const sent = waiting ? stripped : spec;
const put = (targetId, owned) =>
store.putMapping({
pairId: ctx.pair.id,
@@ -474,21 +512,26 @@ export function createEngine(overrides = {}) {
sourceId: roleId,
targetId,
owned,
- specHash: hash,
+ specHash: waiting ? '' : hash,
label: role.name,
now: deps.now(),
});
if (m) {
if (m.specHash === hash) return done('unchanged', { notes });
try {
- await ctx.target.editRole(m.targetId, spec);
+ await ctx.target.editRole(m.targetId, sent);
await put(m.targetId, m.owned);
- return done('updated', { notes, remote: true });
+ return done(waiting ? 'updated, powerful permissions wait for the role order' : 'updated', {
+ notes,
+ remote: true,
+ });
} catch (err) {
if (classifyError(err).kind !== 'gone') throw err;
await store.deleteMapping(ctx.pair.id, 'role', roleId); // deleted on Fluxer: make it again
}
}
+ const fresh = elevated && !(await rolesOrdered(ctx));
+ const createSpec = fresh ? stripped : spec;
if (ctx.job?.recovering) {
const found = await adoptable(
ctx,
@@ -496,13 +539,32 @@ export function createEngine(overrides = {}) {
(r) => r.name === spec.name && !r.managed && r.id !== ctx.target.id
);
if (found) {
- await ctx.target.editRole(found.id, spec);
- await put(found.id, false);
+ await ctx.target.editRole(found.id, createSpec);
+ await store.putMapping({
+ pairId: ctx.pair.id,
+ kind: 'role',
+ sourceId: roleId,
+ targetId: found.id,
+ owned: false,
+ specHash: fresh ? '' : hash,
+ label: role.name,
+ now: deps.now(),
+ });
return done('adopted what an interrupted run made', { notes, remote: true });
}
}
try {
- await put(await ctx.target.createRole(spec), true);
+ const id = await ctx.target.createRole(createSpec);
+ await store.putMapping({
+ pairId: ctx.pair.id,
+ kind: 'role',
+ sourceId: roleId,
+ targetId: id,
+ owned: true,
+ specHash: fresh ? '' : hash,
+ label: role.name,
+ now: deps.now(),
+ });
} catch (err) {
// The role was made but a second call failed: track it (with no fingerprint, so the next run updates it)
// instead of leaving it untracked and making another.
@@ -520,7 +582,30 @@ export function createEngine(overrides = {}) {
}
throw err;
}
- return done('created', { notes, remote: true });
+ return done(fresh ? 'created, powerful permissions wait for the role order' : 'created', {
+ notes,
+ remote: true,
+ });
+ }
+
+ /** After the role order is set: ask again for every role that was made without its powerful permissions. */
+ async function enqueueGrants(ctx) {
+ const pending = (await store.listMappings(ctx.pair.id, 'role')).filter(
+ (m) => m.owned && m.specHash === ''
+ );
+ for (const m of pending) {
+ await store.enqueueJob({
+ pairId: ctx.pair.id,
+ run: ctx.job?.run ?? 0,
+ phase: ctx.job?.phase ?? 'sync',
+ op: 'sync',
+ kind: 'role',
+ sourceId: m.sourceId,
+ stepKey: `grant:role:${m.sourceId}`,
+ payload: { name: m.label, planned: 'update' },
+ now: deps.now(),
+ });
+ }
}
async function syncChannel(ctx, channelId, depth = 0) {
@@ -745,23 +830,17 @@ export function createEngine(overrides = {}) {
async function reorder(ctx, which) {
if (which === 'roles') {
- const order = ctx.source.roles
- .filter((r) => ctx.sets.copiedRoles.has(r.id))
- .sort((a, b) => a.position - b.position || (a.id < b.id ? -1 : 1))
- .map((r) => r.id);
+ const order = roleOrderOf(ctx);
const hash = specHash(order);
const m = await store.getMapping(ctx.pair.id, 'order', 'roles');
- if (m && m.specHash === hash) return done('unchanged');
- // Distinct places, in Discord's order, all under Sylo's role: Fluxer ranks equal positions by age, so a tie
- // (or squeezing roles together) could put a lower Discord role above a higher one. If they do not fit,
- // nothing is sent and the mirror pauses until Sylo's role is moved up on Fluxer.
- const top = ctx.target.topPosition();
- if (top === null || order.length > top - 1) {
- throw new MirrorPause(
- `Sylo's role on the Fluxer server is too low to order the ${order.length} mirrored roles as on Discord. Move Sylo's role to the top of the role list there, then resume.`,
- 'hierarchy'
- );
+ if (m && m.specHash === hash) {
+ await enqueueGrants(ctx);
+ return done('unchanged');
}
+ // Sylo has to outrank every other role to order the copied ones (see hierarchyAdvice). If it does not, nothing
+ // is sent and the mirror pauses until the Fluxer owner has moved Sylo's role up.
+ const above = await rolesAboveSylo(ctx.pair.id, ctx.target);
+ if (above === null || above.length > 0) throw new MirrorPause(hierarchyAdvice(above), 'hierarchy');
const updates = [];
for (const [i, id] of order.entries()) {
const mapping = await store.getMapping(ctx.pair.id, 'role', id);
@@ -769,7 +848,7 @@ export function createEngine(overrides = {}) {
updates.push({ id: mapping.targetId, position: i + 1 });
}
const notes = [];
- if (updates.length > 1) await ctx.target.setRolePositions(updates);
+ if (updates.length > 0) await ctx.target.setRolePositions(updates);
await store.putMapping({
pairId: ctx.pair.id,
kind: 'order',
@@ -779,7 +858,8 @@ export function createEngine(overrides = {}) {
specHash: hash,
now: deps.now(),
});
- return done(`${updates.length} roles ordered`, { notes, remote: updates.length > 1 });
+ await enqueueGrants(ctx);
+ return done(`${updates.length} roles ordered`, { notes, remote: updates.length > 0 });
}
const layout = channelOrder(ctx.source, ctx.sets.copiedChannels);
const hash = specHash(layout);
@@ -1126,9 +1206,31 @@ export function createEngine(overrides = {}) {
'item'
);
}
- if (pair.pauseKind === 'deletes' && !confirm) {
+ // Deletes that wait (after a burst, or while the mirror was paused) are applied only after a confirmation that shows
+ // what they are. With real deletion on, only the owner of the Fluxer server can confirm: it destroys messages that
+ // exist only there.
+ const waiting = await pendingDeletes(pair);
+ if (waiting.count > 0 && (pair.pauseKind === 'deletes' || waiting.count > deps.deleteBurst.max)) {
+ if (normaliseOptions(pair.options).mirrorDeletes && side === 'source') {
+ throw Object.assign(
+ new MirrorError(
+ 'Deleting on Fluxer is switched on, so only the owner of the Fluxer server can confirm these deletions.',
+ 'item'
+ ),
+ { code: 'fluxer-owner-only', deletes: waiting.items }
+ );
+ }
+ if (!confirm) {
+ throw Object.assign(new MirrorError('Confirm the deletions first.', 'item'), {
+ code: 'confirm-needed',
+ deletes: waiting.items,
+ deleteCount: waiting.count,
+ });
+ }
+ } else if (pair.pauseKind === 'deletes' && !confirm) {
throw Object.assign(new MirrorError('Confirm the deletions first.', 'item'), {
code: 'confirm-needed',
+ deletes: [],
});
}
const { sg, tg } = guildsOf(pair);
@@ -1221,6 +1323,19 @@ export function createEngine(overrides = {}) {
return true;
}
+ /** The deletes waiting in a pair's queue, as what the person is asked to confirm: the item and what will happen to it. */
+ async function pendingDeletes(pair) {
+ const { count, jobs } = await store.listPendingDeletes(pair.id, 50);
+ const really = normaliseOptions(pair.options).mirrorDeletes;
+ const items = [];
+ for (const j of jobs) {
+ const m = await store.getMapping(pair.id, j.kind, j.sourceId);
+ if (!m || !m.owned) continue; // nothing of Sylo's to touch
+ items.push({ kind: j.kind, name: m.label || j.sourceId, action: really ? 'delete' : 'lock' });
+ }
+ return { count, items };
+ }
+
// --- what the dashboard shows ------------------------------------------------------------------------
/** How far a pair is: the copy's jobs by state, and the changes still waiting. */
@@ -1237,6 +1352,7 @@ export function createEngine(overrides = {}) {
waiting: counts.pending + counts.running,
percent: total === 0 ? 0 : Math.round((finished / total) * 100),
waitingChanges: await store.openSyncCount(pair.id),
+ pendingDeletes: (await pendingDeletes(pair)).items,
// Copies left on Fluxer whose Discord original was deleted (locked, not deleted): for the Fluxer owner to look at.
removed: (await store.listRemoved(pair.id))
.slice(0, 100)
diff --git a/src/mirror/errors.js b/src/mirror/errors.js
index 6166c856..9ecccca5 100644
--- a/src/mirror/errors.js
+++ b/src/mirror/errors.js
@@ -47,7 +47,8 @@ export function isNotFound(err) {
export function classifyError(err) {
const message = String(err?.message ?? err ?? 'Unknown error').slice(0, 300);
if (err instanceof MirrorError) return { kind: err.kind, message };
- const status = Number(err?.statusCode ?? err?.status ?? 0);
+ // The SDK wraps a failed look-up in an error that keeps the HTTP status only in `cause`.
+ const status = Number(err?.statusCode ?? err?.status ?? err?.cause?.statusCode ?? err?.cause?.status ?? 0);
if (status === 429 || typeof err?.retryAfter === 'number') {
const seconds = Number(err?.retryAfter ?? 1);
return {
diff --git a/src/mirror/plan.js b/src/mirror/plan.js
index 3b26d073..fee223c2 100644
--- a/src/mirror/plan.js
+++ b/src/mirror/plan.js
@@ -82,7 +82,19 @@ export function buildModuleSpec(mod, sets, source) {
message: `${mod.name}: ${out.dropped} channel or role setting(s) point at something that is not copied and ${out.cleared} other id(s) (messages, members) are cleared; set them again on the Fluxer server.`,
});
}
- return { spec: { enabled: mod.enabled, config }, notes, remapped: out.remapped };
+ // The dashboard's funding guard (a copied economy that raises income from nothing) is not reproduced, so the economy
+ // comes over switched off: its owner looks at the shop and the income settings, then turns it on.
+ let enabled = mod.enabled;
+ if (mod.id === 'economy' && enabled) {
+ enabled = false;
+ notes.push({
+ code: 'module-economy-off',
+ scope: 'module',
+ ref,
+ message: `${mod.name}: it is copied switched off. Look at the income settings and the shop on the Fluxer server, then switch it on.`,
+ });
+ }
+ return { spec: { enabled, config }, notes, remapped: out.remapped };
}
/** The kinds of step, in the order the copy runs them. */
@@ -249,7 +261,7 @@ export function buildPlan({
const rb = source.roles.find((r) => r.id === b);
return byPosition(ra, rb);
});
- if (roleOrder.length > 1) {
+ if (roleOrder.length > 0) {
const hash = specHash(roleOrder);
push({
key: 'order-roles:roles',
diff --git a/src/mirror/spec.js b/src/mirror/spec.js
index 98650b40..f32db24d 100644
--- a/src/mirror/spec.js
+++ b/src/mirror/spec.js
@@ -26,6 +26,9 @@ export const DEFAULT_OPTIONS = Object.freeze({
continuous: true,
// Off: a Discord delete locks the Fluxer copy instead of deleting it. On: it is deleted (only what Sylo made).
mirrorDeletes: false,
+ // The Discord owner asked for deletions to be mirrored; they only take effect (`mirrorDeletes`) once the owner of the
+ // Fluxer server has confirmed, because deleting a Fluxer channel deletes messages that exist only on Fluxer.
+ mirrorDeletesRequested: false,
});
/** The options as stored: only the known switches, each a boolean, the rest at their default. */
diff --git a/src/mirror/target.js b/src/mirror/target.js
index b4042c49..f4d7b307 100644
--- a/src/mirror/target.js
+++ b/src/mirror/target.js
@@ -22,6 +22,23 @@ export const NEEDED_PERMISSIONS = Object.freeze([
'ManageGuild',
]);
+/**
+ * Fluxer ranks roles by position, highest first, and by id (the older, smaller one first) when positions are equal;
+ * every role starts at position 1 and positions are only renumbered when someone reorders. So a position number says
+ * nothing by itself: what counts is the rank. The roles of `roles` that rank above `sylo` (not `ignore`d, not Sylo's
+ * own), in rank order.
+ * @param {{ id: string, position: number }} sylo Sylo's highest role
+ * @param {Array<{ id: string, name: string, position: number }>} roles
+ * @param {Set} ignore
+ */
+export function rolesAbove(sylo, roles, ignore = new Set()) {
+ const outranks = (a, b) =>
+ a.position > b.position || (a.position === b.position && BigInt(a.id) < BigInt(b.id));
+ return roles
+ .filter((r) => r.id !== sylo.id && !ignore.has(r.id) && outranks(r, sylo))
+ .sort((a, b) => b.position - a.position || (BigInt(a.id) < BigInt(b.id) ? -1 : 1));
+}
+
/** @param {{ mime: string, bytes: Buffer }} image */
export const toDataUri = (image) => `data:${image.mime};base64,${image.bytes.toString('base64')}`;
@@ -81,10 +98,23 @@ export function createFluxerTarget(guild) {
if (perms.has('Administrator')) return [];
return NEEDED_PERMISSIONS.filter((p) => !perms.has(p));
},
- /** The highest position a role can sit at for Sylo to manage it, or null when unknown. */
- topPosition() {
- const top = guild.members?.me?.roles?.highest?.position;
- return typeof top === 'number' ? top : null;
+ /**
+ * The roles on the Fluxer server that rank above Sylo's own (see rolesAbove), apart from `ignore` (the ids of roles
+ * the mirror made itself: they are ordered under Sylo). Null when Sylo's own role is not known.
+ */
+ rolesAboveSylo(ignore = []) {
+ const highest = guild.members?.me?.roles?.highest;
+ if (!highest?.id) return null;
+ const roles = list(guild.roles).map((r) => ({
+ id: String(r.id),
+ name: String(r.name ?? ''),
+ position: Number(r.position ?? 0),
+ }));
+ return rolesAbove(
+ { id: String(highest.id), position: Number(highest.position ?? 0) },
+ roles,
+ new Set([guild.id, ...ignore])
+ );
},
// --- what is there now (for adoption after a crash, and the preview's counts) ---
@@ -100,6 +130,7 @@ export function createFluxerTarget(guild) {
id: String(r.id),
name: String(r.name ?? ''),
managed: Boolean(r.managed),
+ position: Number(r.position ?? 0),
})),
listEmojis: () => list(guild.emojis).map((e) => ({ id: String(e.id), name: String(e.name ?? '') })),
listStickers: () => list(guild.stickers).map((e) => ({ id: String(e.id), name: String(e.name ?? '') })),
diff --git a/src/web/lib/routeAccess.js b/src/web/lib/routeAccess.js
index 63014e05..fbb80b8a 100644
--- a/src/web/lib/routeAccess.js
+++ b/src/web/lib/routeAccess.js
@@ -322,6 +322,7 @@ export const ROUTE_ACCESS = Object.freeze({
'POST /guilds/:guildId/mirror/request': 'edit',
'POST /guilds/:guildId/mirror/accept': 'edit',
'POST /guilds/:guildId/mirror/options': 'edit',
+ 'POST /guilds/:guildId/mirror/deletes': 'edit',
'POST /guilds/:guildId/mirror/start': 'edit',
'POST /guilds/:guildId/mirror/pause': 'edit',
'POST /guilds/:guildId/mirror/resume': 'edit',
diff --git a/src/web/routes/v2Mirror.js b/src/web/routes/v2Mirror.js
index d54dcbb1..97b3a70d 100644
--- a/src/web/routes/v2Mirror.js
+++ b/src/web/routes/v2Mirror.js
@@ -275,6 +275,20 @@ router.post(
const pair = await sourcePair(req, res);
if (!pair) return;
const options = normaliseOptions({ ...pair.options, ...req.body });
+ // Real deletion on Fluxer takes the owner of the Fluxer server: from here it can only be asked for, never switched
+ // on (POST /mirror/deletes on the Fluxer server does that). Switching it off is always allowed.
+ if (req.body?.mirrorDeletes === true) {
+ options.mirrorDeletes = pair.options?.mirrorDeletes === true;
+ options.mirrorDeletesRequested = true;
+ } else if (req.body?.mirrorDeletes === false) {
+ options.mirrorDeletes = false;
+ options.mirrorDeletesRequested = false;
+ } else {
+ options.mirrorDeletes = pair.options?.mirrorDeletes === true;
+ }
+ if (req.body?.mirrorDeletesRequested === undefined && req.body?.mirrorDeletes === undefined) {
+ options.mirrorDeletesRequested = pair.options?.mirrorDeletesRequested === true;
+ }
await updatePair(pair.id, { options });
await recordAudit(req.guild.id, {
actor: actor(req),
@@ -285,6 +299,41 @@ router.post(
})
);
+// The owner of the Fluxer server allows (or stops) real deletion: only after the Discord side asked for it, and
+// only from the Fluxer server's own page.
+router.post(
+ '/mirror/deletes',
+ controlLimit,
+ asyncHandler(async (req, res) => {
+ if (!needOwner(req, res, 'allow deleting on this server')) return;
+ const found = await pairOf(req);
+ if (!found || found.side !== 'target') {
+ return fail(res, 'This server is not the target of a mirror.', 404);
+ }
+ const options = normaliseOptions(found.pair.options);
+ if (req.body?.allow === true) {
+ if (!options.mirrorDeletesRequested) {
+ return fail(res, 'The Discord server has not asked for deletions to be mirrored.', 409);
+ }
+ options.mirrorDeletes = true;
+ } else {
+ options.mirrorDeletes = false;
+ options.mirrorDeletesRequested = false;
+ }
+ await updatePair(found.pair.id, { options });
+ for (const key of [found.pair.sourceGuild, found.pair.targetGuild]) {
+ await recordAudit(key, {
+ actor: actor(req),
+ action: 'mirror:deletes',
+ detail: options.mirrorDeletes
+ ? 'deleting on Fluxer was allowed'
+ : 'deleting on Fluxer was switched off',
+ });
+ }
+ res.json(await stateOf(req));
+ })
+);
+
// The dry run: what a copy would do now, and everything that cannot be carried over. Creates nothing.
router.get(
'/mirror/preview',
@@ -369,7 +418,12 @@ function control(name, run, detail) {
await run(found.pair, found.side, req.body);
} catch (err) {
if (err instanceof MirrorError || err instanceof ConsentError) {
- return fail(res, err.message, 409, err.code ? { code: err.code } : {});
+ return fail(res, err.message, 409, {
+ ...(err.code ? { code: err.code } : {}),
+ ...(err.deletes
+ ? { deletes: err.deletes, deleteCount: err.deleteCount ?? err.deletes.length }
+ : {}),
+ });
}
throw err;
}
diff --git a/test/helpers/mirrorFakes.js b/test/helpers/mirrorFakes.js
index 5f5ae853..3d392bea 100644
--- a/test/helpers/mirrorFakes.js
+++ b/test/helpers/mirrorFakes.js
@@ -1,10 +1,13 @@
// Doubles for the server mirror tests: a Discord server in the shape of discord.js (read by snapshot.js), and a
// Fluxer server with the adapter the engine writes through (target.js), which records every call it gets.
import { createEngine } from '../../src/mirror/engine.js';
+import { rolesAbove } from '../../src/mirror/target.js';
export const SRC = '900000000000000301';
export const DST_RAW = '800000000000000001';
export const DST = `fluxer:${DST_RAW}`;
+/** Sylo's own role on a fake Fluxer server: older than anything the mirror makes. */
+export const SYLO_ROLE = '810000000000000000';
let seq = 700000000000000000n;
export const nextId = () => String(++seq);
@@ -97,7 +100,10 @@ export function fakeFluxer({
name = 'Target',
existingChannels = [],
missing = [],
- top = 1000,
+ // The roles that already exist on the server, as Fluxer numbers them: { id, name, position }. A new server has only
+ // Sylo's own role, at position 1 (every role starts at position 1 on Fluxer; positions change only when reordered).
+ extraRoles = [],
+ syloPosition = 1,
emojiLimit = null,
ownerId = 'fluxer-owner',
clock = null,
@@ -115,6 +121,8 @@ export function fakeFluxer({
channels: new Map(existingChannels.map((c) => [c.id, c])),
roles: new Map([
[id, { id, name: '@everyone', position: 0, _permissions: String(flag(53) | flag(10)), managed: false }],
+ [SYLO_ROLE, { id: SYLO_ROLE, name: 'Sylo', position: syloPosition, _permissions: '8', managed: true }],
+ ...extraRoles.map((r) => [r.id, { _permissions: '0', managed: false, ...r }]),
]),
emojis: new Map(),
stickers: new Map(),
@@ -152,7 +160,9 @@ export function fakeFluxer({
bitrateMax: 96000,
}),
missingPermissions: () => missing,
- topPosition: () => top,
+ // The roles that rank above Sylo's own (Fluxer's order: position, then the older id), like the real adapter.
+ rolesAboveSylo: (ignore = []) =>
+ rolesAbove(guild.roles.get(SYLO_ROLE), [...guild.roles.values()], new Set([id, ...ignore])),
listChannels: () =>
[...guild.channels.values()].map((c) => ({
id: c.id,
@@ -161,7 +171,12 @@ export function fakeFluxer({
parentId: c.parentId ?? null,
})),
listRoles: () =>
- [...guild.roles.values()].map((r) => ({ id: r.id, name: r.name, managed: Boolean(r.managed) })),
+ [...guild.roles.values()].map((r) => ({
+ id: r.id,
+ name: r.name,
+ managed: Boolean(r.managed),
+ position: r.position,
+ })),
listEmojis: () => [...guild.emojis.values()],
listStickers: () => [...guild.stickers.values()],
async editGuild(body) {
@@ -193,8 +208,31 @@ export function fakeFluxer({
if (!guild.roles.delete(rid)) throw gone('role');
done('deleteRole', { id: rid });
},
+ // Like Fluxer: only the roles below Sylo's own are rearranged, into the slots they already hold, by the positions
+ // sent (ties keep their order); then every role is renumbered. Sylo's role never moves.
async setRolePositions(updates) {
begin('setRolePositions');
+ const older = (a, b) => (BigInt(a.id) < BigInt(b.id) ? -1 : 1);
+ const current = [...guild.roles.values()]
+ .filter((r) => r.id !== id)
+ .sort((a, b) => b.position - a.position || older(a, b));
+ const sylo = current.findIndex((r) => r.id === SYLO_ROLE);
+ const explicit = new Map(updates.map((u) => [u.id, u.position]));
+ const slots = current.map((_, i) => i).filter((i) => i > sylo);
+ const movable = slots
+ .map((i) => ({ role: current[i], i }))
+ .sort(
+ (a, b) =>
+ (explicit.get(b.role.id) ?? b.role.position) - (explicit.get(a.role.id) ?? a.role.position) ||
+ a.i - b.i
+ );
+ const order = [...current];
+ slots.forEach((slot, k) => {
+ order[slot] = movable[k].role;
+ });
+ order.forEach((r, i) => {
+ r.position = order.length - i;
+ });
done('setRolePositions', { updates });
},
async createChannel(spec) {
diff --git a/test/mirrorGuards.test.js b/test/mirrorGuards.test.js
index 4c735c95..34bd4ee7 100644
--- a/test/mirrorGuards.test.js
+++ b/test/mirrorGuards.test.js
@@ -7,7 +7,7 @@ import assert from 'node:assert/strict';
import * as db from '../src/db/mirror.js';
import { getGuildModule, setGuildModule } from '../src/db/modules.js';
import { createEngine } from '../src/mirror/engine.js';
-import { BIT, engineFor } from './helpers/mirrorFakes.js';
+import { BIT, SYLO_ROLE, engineFor } from './helpers/mirrorFakes.js';
import { drain, scenario } from './helpers/mirrorScenario.js';
const OWNERS = { enforceOwnership: () => true };
@@ -151,9 +151,21 @@ test('a burst of deletes pauses the mirror, and only the owner confirming applie
assert.equal(s.fluxer.ops('deleteChannel').length, 0, 'nothing is deleted while the mirror waits');
assert.equal(await db.openSyncCount(s.pair.id), 6, 'the deletes wait in the queue');
- await assert.rejects(s.engine.resume(s.pair.id, { side: 'source' }), (e) => e.code === 'confirm-needed');
+ // Real deletion is on, so the owner of the Discord server cannot confirm it: only the Fluxer owner can, and only after
+ // being shown what will be deleted.
+ await assert.rejects(
+ s.engine.resume(s.pair.id, { side: 'source', confirm: true }),
+ (e) => e.code === 'fluxer-owner-only'
+ );
+ await assert.rejects(s.engine.resume(s.pair.id, { side: 'target' }), (e) => {
+ assert.equal(e.code, 'confirm-needed');
+ assert.equal(e.deleteCount, 6);
+ assert.ok(e.deletes.every((d) => d.action === 'delete'));
+ assert.ok(e.deletes.some((d) => d.kind === 'channel' && d.name === 'chat'));
+ return true;
+ });
assert.equal((await db.getPair(s.pair.id)).status, 'paused');
- const resumed = await s.engine.resume(s.pair.id, { side: 'source', confirm: true });
+ const resumed = await s.engine.resume(s.pair.id, { side: 'target', confirm: true });
assert.equal(resumed.status, 'live');
await s.engine.runPair(s.pair.id);
assert.deepEqual(
@@ -166,79 +178,178 @@ test('a burst of deletes pauses the mirror, and only the owner confirming applie
assert.equal(s.fluxer.ops('deleteEmoji').length, 1);
});
-test("the copy waits until Sylo's role is high enough on Fluxer to order every role", async () => {
- const low = await scenario({ withExpressions: false, fluxerOpts: { top: 2 } });
- const preview = await low.engine.previewPair(low.pair);
+const BOSS = { id: '810000000000000005', name: 'Admins', position: 5 };
+const roleBits = (s, id) => BigInt(s.fluxer.guild.roles.get(id)._permissions);
+const ADMIN = 1n << 3n;
+const MANAGE_ROLES = 1n << 28n;
+
+test('a fresh Fluxer server (only Sylo at position 1) is fine: Sylo outranks what it makes, by id', async () => {
+ const s = await scenario({ withExpressions: false });
+ const preview = await s.engine.previewPair(s.pair);
+ assert.equal(preview.ok, true, 'position 1 is not a problem: it is the top role');
+ assert.equal(preview.blockers.length, 0);
+ await s.engine.startCopy(s.pair.id);
+ assert.equal((await drain(s)).status, 'live');
+ const sylo = s.fluxer.guild.roles.get(SYLO_ROLE);
+ for (const sourceId of [s.k.member, s.k.mod]) {
+ const role = s.fluxer.guild.roles.get(await mapped(s, 'role', sourceId));
+ assert.ok(sylo.position > role.position, 'Sylo stays above every role it made');
+ }
+});
+
+test("the copy is refused, with advice, while a role ranks above or level with Sylo's", async () => {
+ const above = await scenario({ withExpressions: false, fluxerOpts: { extraRoles: [BOSS] } });
+ const preview = await above.engine.previewPair(above.pair);
assert.equal(preview.ok, false);
assert.equal(preview.blockers[0].code, 'role-hierarchy');
- assert.match(preview.blockers[0].message, /move Sylo's role to the top/i);
- await assert.rejects(low.engine.startCopy(low.pair.id), /too low/);
- assert.equal(low.fluxer.calls.length, 0);
+ assert.match(preview.blockers[0].message, /Admins/);
+ assert.match(preview.blockers[0].message, /Server Settings, then Roles/);
+ assert.match(preview.blockers[0].message, /Sylo cannot move its own role/);
+ await assert.rejects(above.engine.startCopy(above.pair.id), /Admins/);
+ assert.equal(above.fluxer.calls.length, 0);
- const unknown = await scenario({ withExpressions: false, fluxerOpts: { top: null } });
- assert.equal((await unknown.engine.previewPair(unknown.pair)).blockers[0].code, 'role-hierarchy');
+ // Level with Sylo (same position) but older: it ranks above, so it blocks; a newer one does not.
+ const older = await scenario({
+ withExpressions: false,
+ fluxerOpts: { extraRoles: [{ id: '800000000000000001', name: 'Older', position: 1 }] },
+ });
+ assert.equal((await older.engine.previewPair(older.pair)).blockers[0].code, 'role-hierarchy');
+ const newer = await scenario({
+ withExpressions: false,
+ fluxerOpts: { extraRoles: [{ id: '820000000000000001', name: 'Newer', position: 1 }] },
+ });
+ assert.equal((await newer.engine.previewPair(newer.pair)).ok, true);
- const fits = await scenario({ withExpressions: false, fluxerOpts: { top: 3 } });
- assert.equal((await fits.engine.previewPair(fits.pair)).ok, true);
- const noRoles = await scenario({
+ // Sylo's own role unknown: also refused, with the advice to check it.
+ const unknown = await scenario({ withExpressions: false });
+ unknown.fluxer.target.rolesAboveSylo = () => null;
+ assert.match((await unknown.engine.previewPair(unknown.pair)).blockers[0].message, /could not be read/);
+
+ // Roles the mirror made itself do not count, and with roles switched off there is nothing to order.
+ const off = await scenario({
withExpressions: false,
- fluxerOpts: { top: 0 },
+ fluxerOpts: { extraRoles: [BOSS] },
options: { roles: false },
});
- assert.equal((await noRoles.engine.previewPair(noRoles.pair)).ok, true, 'no roles, no order to keep');
+ assert.equal((await off.engine.previewPair(off.pair)).ok, true);
});
-test('role positions are distinct and follow Discord, even for a tie, and a lower role never outranks a higher one', async () => {
- const s = await scenario({ withExpressions: false, fluxerOpts: { top: 3 } });
+test('role ranks on Fluxer follow Discord, even for a tie, and a Manage Roles role never outranks the Administrator role', async () => {
+ const s = await scenario({ withExpressions: false });
s.discord.roles.cache.get(s.k.mod).rawPosition = 1; // a tie with Member
- s.discord.roles.cache.get(s.k.member).permissions = { bitfield: 1n << 28n }; // Manage Roles
+ s.discord.roles.cache.get(s.k.member).permissions = { bitfield: MANAGE_ROLES };
s.discord.roles.cache.get(s.k.mod).permissions = { bitfield: BIT.Administrator };
await s.engine.startCopy(s.pair.id);
await drain(s);
const [sent] = s.fluxer.ops('setRolePositions');
- const positions = Object.fromEntries(sent.updates.map((u) => [u.id, u.position]));
+ assert.equal(new Set(sent.updates.map((u) => u.position)).size, 2, 'no two roles share a position');
+ const member = s.fluxer.guild.roles.get(await mapped(s, 'role', s.k.member));
+ const mod = s.fluxer.guild.roles.get(await mapped(s, 'role', s.k.mod));
+ assert.ok(mod.position > member.position, 'the Administrator role ranks above the Manage Roles role');
+ assert.ok(s.fluxer.guild.roles.get(SYLO_ROLE).position > mod.position);
+});
+
+test('a role gets its powerful permissions only after its place in the order is set', async () => {
+ const s = await scenario({ withExpressions: false });
+ s.discord.roles.cache.get(s.k.member).permissions = { bitfield: MANAGE_ROLES | BIT.ViewChannel };
+ s.discord.roles.cache.get(s.k.mod).permissions = { bitfield: BIT.Administrator | BIT.ViewChannel };
+ await s.engine.startCopy(s.pair.id);
+ const end = await drain(s);
+ assert.equal(end.status, 'live');
+ const calls = s.fluxer.calls;
const member = await mapped(s, 'role', s.k.member);
const mod = await mapped(s, 'role', s.k.mod);
- assert.equal(new Set(Object.values(positions)).size, 2, 'no two roles share a position');
- assert.ok(positions[mod] > positions[member], 'the Administrator role ranks above the Manage Roles role');
+ const made = (id) => calls.findIndex((c) => c.op === 'createRole' && c.id === id);
+ const ordered = calls.findIndex((c) => c.op === 'setRolePositions');
+ const granted = (id) => calls.findIndex((c) => c.op === 'editRole' && c.id === id);
+ for (const id of [member, mod]) {
+ const created = calls[made(id)].spec;
+ assert.equal(
+ BigInt(created.permissions) & (ADMIN | MANAGE_ROLES),
+ 0n,
+ 'made without powerful permissions'
+ );
+ assert.ok(made(id) < ordered && ordered < granted(id), 'created, then ordered, then granted');
+ }
+ assert.equal(roleBits(s, member) & MANAGE_ROLES, MANAGE_ROLES);
+ assert.equal(roleBits(s, mod) & ADMIN, ADMIN);
assert.ok(
- Object.values(positions).every((p) => p >= 1 && p <= 2),
- "all under Sylo's role"
+ (await db.getMapping(s.pair.id, 'role', s.k.mod)).specHash,
+ 'and the role is fingerprinted when final'
);
});
-test("with a new role and Sylo's role too low, the mirror pauses instead of squeezing positions together", async () => {
- const s = await scenario({ withExpressions: false, fluxerOpts: { top: 3 } });
+test('a single role is ordered too, so that it gets its permissions', async () => {
+ const s = await scenario({ withExpressions: false });
+ for (const id of [s.k.member, s.k.bot]) s.discord.roles.cache.delete(id);
+ s.discord.roles.cache.get(s.k.mod).permissions = { bitfield: BIT.Administrator };
+ await s.engine.startCopy(s.pair.id);
+ await drain(s);
+ assert.equal(s.fluxer.ops('setRolePositions').length, 1);
+ assert.equal(roleBits(s, await mapped(s, 'role', s.k.mod)) & ADMIN, ADMIN);
+});
+
+test('with a new powerful role and a role above Sylo, the mirror pauses and the role stays without its permissions', async () => {
+ const s = await scenario({ withExpressions: false });
await s.engine.startCopy(s.pair.id);
await drain(s);
s.fluxer.calls.length = 0;
+ s.fluxer.guild.roles.set(BOSS.id, { _permissions: '0', managed: false, ...BOSS }); // someone moved a role above Sylo
const id = '780000000000000001';
s.discord.roles.cache.set(id, {
id,
- name: 'New',
+ name: 'New admin',
color: 0,
rawPosition: 5,
hoist: false,
mentionable: false,
managed: false,
- permissions: { bitfield: 0n },
+ permissions: { bitfield: BIT.Administrator },
});
await s.engine.noteSourceChange(s.k.src, { kind: 'role', op: 'sync', id, reorder: 'roles' });
s.clock.now += 4000;
await s.engine.runPair(s.pair.id);
const pair = await db.getPair(s.pair.id);
assert.deepEqual([pair.status, pair.pauseKind], ['paused', 'hierarchy']);
- assert.match(pair.lastError, /Move Sylo's role to the top/);
- assert.equal(s.fluxer.ops('createRole').length, 1, 'the role itself was made');
- assert.equal(s.fluxer.ops('setRolePositions').length, 0, 'and no positions were sent');
- s.fluxer.target.topPosition = () => 10;
+ assert.match(pair.lastError, /Admins/);
+ assert.equal(s.fluxer.ops('setRolePositions').length, 0, 'nothing was reordered');
+ const made = s.fluxer.ops('createRole')[0];
+ assert.equal(BigInt(made.spec.permissions) & ADMIN, 0n);
+ assert.equal(roleBits(s, made.id) & ADMIN, 0n, 'it stays without Administrator while the order is not set');
+
+ // The Fluxer owner moves Sylo's role to the top; the mirror resumes, orders, and only then grants.
+ s.fluxer.guild.roles.delete(BOSS.id);
await s.engine.resume(s.pair.id, { side: 'source' });
await s.engine.runPair(s.pair.id);
- const [sent] = s.fluxer.ops('setRolePositions');
- assert.deepEqual(
- sent.updates.map((u) => u.position),
- [1, 2, 3]
+ assert.equal(s.fluxer.ops('setRolePositions').length, 1);
+ assert.equal(roleBits(s, made.id) & ADMIN, ADMIN);
+});
+
+test('asking for real deletion needs the Fluxer owner; resuming with deletes waiting shows what they are', async () => {
+ const s = await scenario({ options: { mirrorDeletes: true } });
+ await s.engine.startCopy(s.pair.id);
+ await drain(s);
+ await s.engine.pause(s.pair.id); // paused by hand, not by the brake
+ const note = (kind, id) => s.engine.noteSourceChange(s.k.src, { kind, op: 'delete', id });
+ for (const id of [s.k.chat, s.k.rules, s.k.voice, s.k.cat, s.k.cat2]) {
+ s.discord.channels.cache.delete(id);
+ await note('channel', id);
+ }
+ s.discord.emojis.cache.delete(s.k.emoji1);
+ await note('emoji', s.k.emoji1);
+ assert.equal(
+ (await db.getPair(s.pair.id)).pauseKind,
+ 'owner',
+ 'deletes while paused do not change the pause'
);
+ await assert.rejects(s.engine.resume(s.pair.id, { side: 'target' }), (e) => {
+ assert.equal(e.code, 'confirm-needed');
+ assert.equal(e.deleteCount, 6);
+ return true;
+ });
+ const progress = await s.engine.progress(await db.getPair(s.pair.id));
+ assert.equal(progress.pendingDeletes.length, 6, 'the page can show what will be deleted');
+ assert.equal((await s.engine.resume(s.pair.id, { side: 'target', confirm: true })).status, 'live');
});
test('with roles off, a channel @everyone cannot see on Discord is still private on Fluxer', async () => {
@@ -334,7 +445,7 @@ test('a role whose second call fails is tracked, and the retry updates it instea
s.fluxer.failAfterCreate('createRole', Object.assign(new Error('timed out'), { statusCode: 503 }));
assert.equal((await drain(s)).status, 'live');
assert.equal(s.fluxer.ops('createRole').length, 2, 'Member and Mod: one create each');
- assert.equal([...s.fluxer.guild.roles.values()].length, 3, 'and so three roles with @everyone');
+ assert.equal([...s.fluxer.guild.roles.values()].length, 4, 'and so four roles with @everyone and Sylo');
const member = await db.getMapping(s.pair.id, 'role', s.k.member);
assert.equal(member.owned, true);
assert.ok(member.specHash, 'the retry updated it, so it is fingerprinted now');
@@ -471,3 +582,15 @@ test('a Discord emoji or sticker delete that arrives while its copy is still bei
await drain(s);
assert.equal(s.fluxer.ops('createEmoji').length, 1, 'the deleted emoji was never made');
});
+
+test('a copied economy comes over switched off, with a note', async () => {
+ const s = await scenario({ withExpressions: false });
+ await setGuildModule(s.k.src, 'economy', { enabled: true, config: { startingBalance: 100 } });
+ const preview = await s.engine.previewPair(s.pair);
+ assert.ok(preview.notes.some((n) => n.code === 'module-economy-off'));
+ await s.engine.startCopy(s.pair.id);
+ await drain(s);
+ const there = await getGuildModule(`fluxer:${s.k.dst}`, 'economy');
+ assert.equal(there.enabled, false);
+ assert.equal(there.config.startingBalance, 100, 'the settings are there for its owner to look at');
+});
diff --git a/test/mirrorSpec.test.js b/test/mirrorSpec.test.js
index 7f21ce11..73ec04db 100644
--- a/test/mirrorSpec.test.js
+++ b/test/mirrorSpec.test.js
@@ -262,6 +262,7 @@ test('options: only known switches, only booleans, the rest on', () => {
modules: true,
continuous: true,
mirrorDeletes: false,
+ mirrorDeletesRequested: false,
});
assert.equal(normaliseOptions(null).continuous, true);
});
diff --git a/test/mirrorTarget.test.js b/test/mirrorTarget.test.js
index 63b46318..1476700f 100644
--- a/test/mirrorTarget.test.js
+++ b/test/mirrorTarget.test.js
@@ -2,7 +2,7 @@
// SDK (bigint permissions, data URIs, the overwrites) and how a thing that is gone shows up (a 404).
import test from 'node:test';
import assert from 'node:assert/strict';
-import { createFluxerTarget, toDataUri } from '../src/mirror/target.js';
+import { createFluxerTarget, rolesAbove, toDataUri } from '../src/mirror/target.js';
import { classifyError, isNotFound } from '../src/mirror/errors.js';
import { snapshotFluxerGuild } from '../src/mirror/snapshot.js';
@@ -23,7 +23,7 @@ function sdkGuild({ perms = [], admin = false, top = 7 } = {}) {
members: {
me: {
permissions: { has: (p) => admin || perms.includes(p) },
- roles: { highest: { position: top } },
+ roles: { highest: { id: '810000000000000000', position: top } },
},
},
client: { channels: { fetch: async () => null } },
@@ -60,13 +60,35 @@ function sdkGuild({ perms = [], admin = false, top = 7 } = {}) {
return { guild, log };
}
+test("Sylo's rank is compared with the roles on the server: position first, then the older id", () => {
+ const { guild } = sdkGuild({ top: 1 });
+ const add = (id, name, position) => guild.roles.set(id, { id, name, position });
+ add('810000000000000000', 'Sylo', 1);
+ add('810000000000000007', 'Newer', 1); // the same position but a newer id: ranks below Sylo
+ add('800000000000000001', 'Older', 1); // the same position and older: ranks above
+ add('820000000000000002', 'High', 4);
+ const target = createFluxerTarget(guild);
+ assert.deepEqual(
+ target.rolesAboveSylo().map((r) => r.name),
+ ['High', 'Older']
+ );
+ assert.deepEqual(
+ target.rolesAboveSylo(['820000000000000002']).map((r) => r.name),
+ ['Older'],
+ "the mirror's own roles are ignored"
+ );
+ assert.deepEqual(rolesAbove({ id: '5', position: 3 }, [{ id: '9', name: 'x', position: 2 }]), []);
+ delete guild.members.me.roles.highest;
+ assert.equal(target.rolesAboveSylo(), null, "unknown when Sylo's own role cannot be read");
+ assert.equal(createFluxerTarget({ id: '1' }).rolesAboveSylo(), null);
+});
+
test('what Sylo needs on the Fluxer server: Administrator covers it, otherwise the four permissions', () => {
assert.deepEqual(createFluxerTarget(sdkGuild({ admin: true }).guild).missingPermissions(), []);
assert.deepEqual(
createFluxerTarget(sdkGuild({ perms: ['ManageChannels', 'ManageGuild'] }).guild).missingPermissions(),
['ManageRoles', 'ManageExpressions']
);
- assert.equal(createFluxerTarget(sdkGuild({ top: 12 }).guild).topPosition(), 12);
assert.deepEqual(
createFluxerTarget({ id: '1' }).missingPermissions(),
[],
@@ -296,3 +318,14 @@ test("the SDK's own codes: not-found codes are gone, Fluxer's limit codes are li
assert.equal(isNotFound(Object.assign(new Error('x'), { cause: { statusCode: 404 } })), true);
assert.equal(isNotFound(Object.assign(new Error('x'), { statusCode: 503 })), false);
});
+
+test('a 5xx that only the SDK wrapper error carries in its cause is still retried, not failed', () => {
+ const wrapped = Object.assign(new Error('Failed to fetch role'), { cause: { statusCode: 503 } });
+ assert.equal(classifyError(wrapped).kind, 'transient');
+ const limited = Object.assign(new Error('x'), { cause: { statusCode: 429 }, retryAfter: 2 });
+ assert.equal(classifyError(limited).kind, 'rate-limit');
+ assert.equal(
+ classifyError(Object.assign(new Error('x'), { cause: { statusCode: 403 } })).kind,
+ 'permission'
+ );
+});
diff --git a/test/v2Mirror.test.js b/test/v2Mirror.test.js
index 9668962d..9f33a414 100644
--- a/test/v2Mirror.test.js
+++ b/test/v2Mirror.test.js
@@ -147,14 +147,44 @@ test('the owner of the Discord server asks; the owner of the Fluxer server agree
report.items.map((i) => i.kind),
['guild', 'bridge']
);
+ // Real deletion: the Discord owner can only ask; the owner of the Fluxer server decides.
+ assert.equal(
+ (await bo.post(`/guilds/${F_KEY}/mirror/deletes`, { allow: true })).status,
+ 409,
+ 'nothing has been asked for yet'
+ );
const opts = await anna.post(`/guilds/${D_GUILD}/mirror/options`, {
continuous: false,
mirrorDeletes: true,
bogus: 1,
});
const optionsNow = (await opts.json()).pair.options;
- assert.deepEqual([optionsNow.continuous, optionsNow.mirrorDeletes], [false, true]);
+ assert.deepEqual(
+ [optionsNow.continuous, optionsNow.mirrorDeletes, optionsNow.mirrorDeletesRequested],
+ [false, false, true],
+ 'asking is not switching on'
+ );
assert.equal(optionsNow.bogus, undefined);
+ assert.equal(
+ (await anna.post(`/guilds/${D_GUILD}/mirror/deletes`, { allow: true })).status,
+ 404,
+ 'not from the Discord side'
+ );
+ const seenByBo = await (await bo.get(`/guilds/${F_KEY}/mirror`)).json();
+ assert.equal(seenByBo.pair.options.mirrorDeletesRequested, true, 'the Fluxer owner sees the request');
+ const allowed = await (await bo.post(`/guilds/${F_KEY}/mirror/deletes`, { allow: true })).json();
+ assert.equal(allowed.pair.options.mirrorDeletes, true, 'the Fluxer owner switched it on');
+ const again = await (
+ await anna.post(`/guilds/${D_GUILD}/mirror/options`, { mirrorDeletes: true, continuous: false })
+ ).json();
+ assert.equal(again.pair.options.mirrorDeletes, true, 'asking again does not change it');
+ const off = await (await anna.post(`/guilds/${D_GUILD}/mirror/options`, { mirrorDeletes: false })).json();
+ assert.deepEqual(
+ [off.pair.options.mirrorDeletes, off.pair.options.mirrorDeletesRequested],
+ [false, false],
+ 'either side can switch it off'
+ );
+ assert.ok((await listAudit(F_KEY, 20)).some((e) => e.action === 'mirror:deletes'));
// Either owner can pause; only the owner that paused can resume it.
assert.equal((await bo.post(`/guilds/${F_KEY}/mirror/resume`)).status, 409, 'only a paused mirror resumes');
@@ -235,6 +265,7 @@ test('an Administrator who is not the owner can look, but cannot ask, agree, cha
for (const [path, body] of [
['request', { targetGuildId: F_KEY }],
['options', { continuous: false }],
+ ['deletes', { allow: true }],
['start', { confirm: true }],
['pause', {}],
['resume', {}],
diff --git a/web-v2/src/__tests__/Mirror.test.jsx b/web-v2/src/__tests__/Mirror.test.jsx
index 16a39db9..b10d9236 100644
--- a/web-v2/src/__tests__/Mirror.test.jsx
+++ b/web-v2/src/__tests__/Mirror.test.jsx
@@ -6,6 +6,7 @@ import { renderAtGuild } from './routerHarness.jsx';
vi.mock('../api.js', () => ({
ApiError: class ApiError extends Error {},
getMirror: vi.fn(),
+ allowMirrorDeletes: vi.fn(),
getMirrorPreview: vi.fn(),
getMirrorReport: vi.fn(),
requestMirror: vi.fn(),
@@ -31,6 +32,8 @@ const OPTIONS = {
stickers: true,
modules: true,
continuous: true,
+ mirrorDeletes: false,
+ mirrorDeletesRequested: false,
};
const pair = (over = {}) => ({
@@ -283,7 +286,7 @@ describe('Mirror: only the owner, and the pauses', () => {
expect(screen.getByText('Mirroring')).toBeTruthy();
});
- it('asks the owner to confirm a burst of deletions before they are applied', async () => {
+ it('asks the owner to confirm a burst of deletions, with the list, before they are applied', async () => {
api.getMirror.mockResolvedValue(
state({
pair: pair({
@@ -296,15 +299,27 @@ describe('Mirror: only the owner, and the pauses', () => {
progress: progress({ total: 2, done: 2, waiting: 0, percent: 100 }),
})
);
- api.mirrorAction.mockResolvedValue(state({ pair: pair({ status: 'live', copyRun: 1 }) }));
+ const needs = () =>
+ Object.assign(new api.ApiError('Confirm the deletions first.'), {
+ code: 'confirm-needed',
+ deleteCount: 6,
+ deletes: [{ kind: 'channel', name: 'chat', action: 'lock' }],
+ });
+ api.mirrorAction
+ .mockRejectedValueOnce(needs())
+ .mockRejectedValueOnce(needs())
+ .mockResolvedValueOnce(state({ pair: pair({ status: 'live', copyRun: 1 }) }));
confirmDialog.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
renderAtGuild(, GUILD);
- const apply = await screen.findByRole('button', { name: 'Apply the deletions' });
- fireEvent.click(apply);
+ const review = await screen.findByRole('button', { name: 'Review the deletions' });
+ fireEvent.click(review);
await waitFor(() => expect(confirmDialog).toHaveBeenCalledTimes(1));
- expect(api.mirrorAction).not.toHaveBeenCalled();
- fireEvent.click(apply);
- await waitFor(() => expect(api.mirrorAction).toHaveBeenCalledWith(GUILD, 'resume', { confirm: true }));
+ expect(confirmDialog.mock.calls[0][0].body).toMatch(/lock channel chat, and 5 more/);
+ expect(api.mirrorAction).toHaveBeenCalledTimes(1);
+ fireEvent.click(review);
+ await waitFor(() =>
+ expect(api.mirrorAction).toHaveBeenLastCalledWith(GUILD, 'resume', { confirm: true })
+ );
});
it('asks a new owner to confirm the mirror after a server changed hands', async () => {
@@ -365,3 +380,73 @@ describe('Mirror: only the owner, and the pauses', () => {
expect(screen.getByText('Delete on Fluxer what is deleted on Discord')).toBeTruthy();
});
});
+
+describe('Mirror: real deletion needs the Fluxer owner', () => {
+ it('shows the Discord owner that the request waits for the Fluxer owner', async () => {
+ api.getMirror.mockResolvedValue(
+ state({ pair: pair({ options: { ...OPTIONS, mirrorDeletesRequested: true } }) })
+ );
+ renderAtGuild(, GUILD);
+ expect(await screen.findByText(/Waiting for the owner of the Fluxer server to allow it/)).toBeTruthy();
+ });
+
+ it('lets the Fluxer owner allow deleting after a confirmation that says what it does', async () => {
+ const asked = pair({
+ side: 'target',
+ status: 'live',
+ otherName: 'Home Discord',
+ otherId: GUILD,
+ options: { ...OPTIONS, mirrorDeletesRequested: true },
+ });
+ api.getMirror.mockResolvedValue(fluxerState(asked));
+ api.allowMirrorDeletes.mockResolvedValue(
+ fluxerState({ ...asked, options: { ...asked.options, mirrorDeletes: true } })
+ );
+ confirmDialog.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+ renderAtGuild(, FLUXER);
+ const allow = await screen.findByRole('button', { name: 'Allow deleting' });
+ fireEvent.click(allow);
+ await waitFor(() => expect(confirmDialog).toHaveBeenCalledTimes(1));
+ expect(confirmDialog.mock.calls[0][0].body).toMatch(/loses all its messages/);
+ expect(api.allowMirrorDeletes).not.toHaveBeenCalled();
+ fireEvent.click(allow);
+ await waitFor(() => expect(api.allowMirrorDeletes).toHaveBeenCalledWith(FLUXER, true));
+ expect(await screen.findByRole('button', { name: 'Stop deleting here' })).toBeTruthy();
+ });
+
+ it('shows what will be deleted before deletions that waited are applied', async () => {
+ api.getMirror.mockResolvedValue(
+ state({
+ pair: pair({
+ status: 'paused',
+ pauseKind: 'owner',
+ pausedBy: 'system',
+ copyRun: 1,
+ lastError: '',
+ }),
+ progress: progress({ total: 2, done: 2, waiting: 0, percent: 100 }),
+ })
+ );
+ const { ApiError } = api;
+ api.mirrorAction
+ .mockRejectedValueOnce(
+ Object.assign(new ApiError('Confirm the deletions first.'), {
+ code: 'confirm-needed',
+ deleteCount: 7,
+ deletes: [
+ { kind: 'channel', name: 'chat', action: 'delete' },
+ { kind: 'role', name: 'Mod', action: 'lock' },
+ ],
+ })
+ )
+ .mockResolvedValueOnce(state({ pair: pair({ status: 'live', copyRun: 1 }) }));
+ confirmDialog.mockResolvedValueOnce(true);
+ renderAtGuild(, GUILD);
+ fireEvent.click(await screen.findByRole('button', { name: 'Resume' }));
+ await waitFor(() => expect(confirmDialog).toHaveBeenCalledTimes(1));
+ expect(confirmDialog.mock.calls[0][0].body).toMatch(/delete channel chat, lock role Mod, and 5 more/);
+ await waitFor(() =>
+ expect(api.mirrorAction).toHaveBeenLastCalledWith(GUILD, 'resume', { confirm: true })
+ );
+ });
+});
diff --git a/web-v2/src/__tests__/mirrorModel.test.js b/web-v2/src/__tests__/mirrorModel.test.js
index d307c345..5a746de5 100644
--- a/web-v2/src/__tests__/mirrorModel.test.js
+++ b/web-v2/src/__tests__/mirrorModel.test.js
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
canResume,
codeLeft,
+ deleteSummary,
groupNotes,
isBusy,
progressText,
@@ -94,4 +95,14 @@ describe('mirrorModel', () => {
expect(canResume({ side: 'source', pausedBy: 'source' })).toBe(true);
expect(canResume({ side: 'target', pausedBy: 'source' })).toBe(false);
});
+
+ it('says what a confirmation is about: the first deletions, then how many more', () => {
+ const items = [
+ { kind: 'channel', name: 'chat', action: 'delete' },
+ { kind: 'role', name: 'Mod', action: 'lock' },
+ ];
+ expect(deleteSummary(items)).toBe('delete channel chat, lock role Mod');
+ expect(deleteSummary(items, 7)).toBe('delete channel chat, lock role Mod, and 5 more');
+ expect(deleteSummary([], 0)).toBe('');
+ });
});
diff --git a/web-v2/src/api.js b/web-v2/src/api.js
index eb8739b7..223f7f56 100644
--- a/web-v2/src/api.js
+++ b/web-v2/src/api.js
@@ -15,6 +15,9 @@ export class ApiError extends Error {
// A refusal the page can act on (the settings changed since an audit entry: confirm to undo anyway).
this.code = body?.code;
this.laterChanges = body?.laterChanges;
+ // What a mirror resume asks to confirm: the deletions that wait (src/web/routes/v2Mirror.js).
+ this.deletes = body?.deletes;
+ this.deleteCount = body?.deleteCount;
this.token = body?.token;
}
}
@@ -492,6 +495,9 @@ export const acceptMirror = (guildId, code) =>
postJson(`/api/v2/guilds/${gid(guildId)}/mirror/accept`, { code });
export const setMirrorOptions = (guildId, options) =>
postJson(`/api/v2/guilds/${gid(guildId)}/mirror/options`, options);
+// The owner of the Fluxer server allows, or stops, real deletion (the Discord owner can only ask for it).
+export const allowMirrorDeletes = (guildId, allow) =>
+ postJson(`/api/v2/guilds/${gid(guildId)}/mirror/deletes`, { allow });
export const startMirror = (guildId) =>
postJson(`/api/v2/guilds/${gid(guildId)}/mirror/start`, { confirm: true });
export const mirrorAction = (guildId, action, body = {}) =>
diff --git a/web-v2/src/mirrorModel.js b/web-v2/src/mirrorModel.js
index 1f0e10c0..873f1998 100644
--- a/web-v2/src/mirrorModel.js
+++ b/web-v2/src/mirrorModel.js
@@ -109,10 +109,18 @@ export const OPTION_ROWS = [
['mirrorDeletes', 'Delete on Fluxer what is deleted on Discord'],
];
+/** The deletions that wait, as a short text for a confirmation: "lock channel #chat, delete role Mod, and 3 more". */
+export function deleteSummary(items = [], count = items.length) {
+ const verb = { lock: 'lock', delete: 'delete' };
+ const shown = items.slice(0, 10).map((i) => `${verb[i.action] ?? i.action} ${i.kind} ${i.name}`);
+ const more = count - shown.length;
+ return shown.join(', ') + (more > 0 ? `, and ${more} more` : '');
+}
+
/** What sits under an option row, when it needs a word of warning. */
export const OPTION_HINTS = {
mirrorDeletes:
- 'Off (the default): a channel or role deleted on Discord stays on Fluxer, locked and marked as removed, and its messages are kept. On: it is deleted on Fluxer too, with all its messages. Only what Sylo made is ever deleted.',
+ 'Off (the default): a channel or role deleted on Discord stays on Fluxer, locked and marked as removed, and its messages are kept. On: it is deleted on Fluxer too, with all its messages. Only what Sylo made is ever deleted. Turning it on only asks: the owner of the Fluxer server has to allow it in their dashboard.',
};
/** May this side resume a paused mirror? Only the side whose owner paused it can; a pause Sylo made is open to both. */
diff --git a/web-v2/src/pages/Mirror.jsx b/web-v2/src/pages/Mirror.jsx
index 4c991b38..d442f4fa 100644
--- a/web-v2/src/pages/Mirror.jsx
+++ b/web-v2/src/pages/Mirror.jsx
@@ -2,6 +2,7 @@ import { createContext, useCallback, useContext, useEffect, useState } from 'rea
import { useParams } from 'react-router-dom';
import {
acceptMirror,
+ allowMirrorDeletes,
getMirror,
getMirrorPreview,
getMirrorReport,
@@ -26,6 +27,7 @@ import {
STEPS,
canResume,
codeLeft,
+ deleteSummary,
groupNotes,
isBusy,
progressText,
@@ -194,22 +196,29 @@ function PauseBlock({ guildId, pair, onState }) {
const kind = pair.pauseKind;
const label =
kind === 'deletes'
- ? 'Apply the deletions'
+ ? 'Review the deletions'
: kind === 'ownership'
? 'Confirm the mirror as the owner'
: 'Resume';
- const body = kind === 'deletes' ? { confirm: true } : {};
async function go() {
- if (kind === 'deletes') {
+ // Ask without a confirmation first: the server says when deletions wait and what they are, and the person
+ // confirms that list (or the mirror simply resumes when none wait).
+ try {
+ onState(await mirrorAction(guildId, 'resume', {}));
+ notify('The mirror goes on.', 'info');
+ } catch (err) {
+ if (err.code !== 'confirm-needed') {
+ notify(err.message || 'That did not work.');
+ return;
+ }
const ok = await confirmDialog({
title: 'Apply the deletions on Fluxer?',
- body: 'Many things were deleted on Discord in a short time. If you go on, Sylo applies them on Fluxer: a channel or role is locked there, or deleted with its messages if you turned on deleting. Stop the mirror instead if this was a mistake.',
+ body: `These were deleted on Discord and wait to be applied on Fluxer: ${deleteSummary(err.deletes, err.deleteCount)}. A locked channel or role stays on Fluxer; a deleted channel loses its messages. Stop the mirror instead if this was a mistake.`,
confirmLabel: 'Apply the deletions',
tone: 'danger',
});
- if (!ok) return;
+ if (ok) await act(() => mirrorAction(guildId, 'resume', { confirm: true }), 'The mirror goes on.');
}
- await act(() => mirrorAction(guildId, 'resume', body), 'The mirror goes on.');
}
return (
<>
@@ -401,12 +410,22 @@ function OptionsForm({ guildId, pair, onState, only }) {
+ Waiting for the owner of the Fluxer server to allow it in their dashboard. Until then deleted
+ items are locked, not deleted.
+
+ ) : null}
{OPTION_HINTS[key] ? (
{OPTION_HINTS[key]}
) : null}
@@ -736,6 +755,57 @@ function Report({ report }) {
);
}
+/** On the Fluxer server: the Discord side asks to delete here too, and only the owner here can allow it. */
+function DeletesPanel({ guildId, pair, onState }) {
+ const { working, act } = useAct(onState);
+ const asked = pair.options.mirrorDeletesRequested;
+ const allowed = pair.options.mirrorDeletes;
+ if (!asked && !allowed) return null;
+ async function allow() {
+ const ok = await confirmDialog({
+ title: 'Allow deleting on this server?',
+ body: 'From now on, what is deleted on Discord is deleted here too: a channel loses all its messages, including ones that only exist here. Only what Sylo made is ever deleted. Without this, deleted items are only locked and listed for you to look at.',
+ confirmLabel: 'Allow deleting',
+ tone: 'danger',
+ });
+ if (ok) await act(() => allowMirrorDeletes(guildId, true), 'Deleting is allowed.');
+ }
+ return (
+
+
Deleting on this server
+ {allowed ? (
+
+ Deleting is allowed: what is deleted on Discord is deleted here, with its messages. Only what Sylo
+ made is deleted.
+
+ ) : (
+
+ The Discord server asks to delete here too, when something is deleted on Discord. Until you allow
+ it, those items are locked and listed, and nothing is deleted.
+
+ );
+}
+
// ---------------------------------------------------------------------------------------------------
// The Fluxer server
@@ -811,6 +881,7 @@ function TargetView({ guildId, state, onState }) {
+
{['copying', 'live'].includes(pair.status) ? (
From 58e781a409b92c11423b550e82373e38b9a1a74c Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Tue, 17 Nov 2026 00:48:16 +0100
Subject: [PATCH 07/17] fix(mirror): every role starts without powerful
permissions; deletion asked for at request time is only a request
Review round 3 for the server mirror.
- A role made, adopted or made again (a mirrored role deleted on Fluxer, then
edited on Discord) is created without its powerful permissions, the order
step runs (continuous mode asks for it at once), and only then are the
permissions granted: one path for the first copy and for continuous mode.
Adopted roles are queued for the same grant step.
- "Mirror deletions" in a mirror request only takes effect when the same person
owns both servers; otherwise it is stored as a request that the owner of the
Fluxer server turns on with their own switch.
---
src/mirror/consent.js | 17 +++++++++--
src/mirror/engine.js | 34 ++++++++++++++++++---
test/mirrorConsent.test.js | 17 +++++++++++
test/mirrorGuards.test.js | 62 ++++++++++++++++++++++++++++++++++++++
test/v2Mirror.test.js | 20 ++++++++++--
5 files changed, 141 insertions(+), 9 deletions(-)
diff --git a/src/mirror/consent.js b/src/mirror/consent.js
index 8665cc31..e3dfb73c 100644
--- a/src/mirror/consent.js
+++ b/src/mirror/consent.js
@@ -91,6 +91,19 @@ export async function requirePairConsent(pairOrId) {
return pair;
}
+/**
+ * The options of a request. Real deletion on Fluxer only takes effect when the same person owns both servers; for
+ * anyone else it is kept as a request that the owner of the Fluxer server has to turn on with their own switch.
+ */
+function askedOptions(options, targetOwner) {
+ const out = normaliseOptions(options);
+ if (out.mirrorDeletes || out.mirrorDeletesRequested) {
+ out.mirrorDeletesRequested = true;
+ out.mirrorDeletes = Boolean(targetOwner) && out.mirrorDeletes;
+ }
+ return out;
+}
+
/** A pair that has never copied anything may be replaced by a new request; one that has, may not. */
const replaceable = (pair) =>
pair.status === PAIR_STATUS.PENDING ||
@@ -162,12 +175,12 @@ export async function requestMirror({
codeAttempts: 0,
lastError: '',
failures: 0,
- ...(options ? { options: normaliseOptions(options) } : {}),
+ ...(options ? { options: askedOptions(options, targetOwner) } : {}),
};
if (pair) {
pair = await updatePair(pair.id, fields, now);
} else {
- pair = await createPair({ sourceGuild, targetGuild, options: normaliseOptions(options), now });
+ pair = await createPair({ sourceGuild, targetGuild, options: askedOptions(options, targetOwner), now });
pair = await updatePair(pair.id, fields, now);
}
return { pair, code };
diff --git a/src/mirror/engine.js b/src/mirror/engine.js
index 07308533..ead198fe 100644
--- a/src/mirror/engine.js
+++ b/src/mirror/engine.js
@@ -186,7 +186,7 @@ export function createEngine(overrides = {}) {
/** The roles on Fluxer that rank above Sylo's (ignoring the roles the mirror made, which are ordered under it). */
async function rolesAboveSylo(pairId, target) {
- const own = (await store.listMappings(pairId, 'role')).filter((m) => m.owned).map((m) => m.targetId);
+ const own = (await store.listMappings(pairId, 'role')).map((m) => m.targetId);
return target.rolesAboveSylo(own);
}
@@ -530,8 +530,12 @@ export function createEngine(overrides = {}) {
await store.deleteMapping(ctx.pair.id, 'role', roleId); // deleted on Fluxer: make it again
}
}
- const fresh = elevated && !(await rolesOrdered(ctx));
+ // Every creation or adoption, in the first copy and in continuous mode alike (also a role that was deleted on Fluxer
+ // and is made again), starts without the powerful permissions. The order step then runs, and only after it do the
+ // grant jobs give them back. `newRole` makes sure the order is set again and asked for.
+ const fresh = elevated;
const createSpec = fresh ? stripped : spec;
+ const newRole = () => roleMadeOnFluxer(ctx);
if (ctx.job?.recovering) {
const found = await adoptable(
ctx,
@@ -550,6 +554,7 @@ export function createEngine(overrides = {}) {
label: role.name,
now: deps.now(),
});
+ await newRole();
return done('adopted what an interrupted run made', { notes, remote: true });
}
}
@@ -565,6 +570,7 @@ export function createEngine(overrides = {}) {
label: role.name,
now: deps.now(),
});
+ await newRole();
} catch (err) {
// The role was made but a second call failed: track it (with no fingerprint, so the next run updates it)
// instead of leaving it untracked and making another.
@@ -579,6 +585,7 @@ export function createEngine(overrides = {}) {
label: role.name,
now: deps.now(),
});
+ await newRole();
}
throw err;
}
@@ -588,11 +595,28 @@ export function createEngine(overrides = {}) {
});
}
+ /**
+ * A role was made (or adopted, or made again) on Fluxer: its place in the order is not set yet. Forget that the order
+ * was set, so the order step really runs; in continuous mode, ask for it now (in a copy the plan's order step follows).
+ */
+ async function roleMadeOnFluxer(ctx) {
+ await store.deleteMapping(ctx.pair.id, 'order', 'roles');
+ if (ctx.job?.phase === 'copy') return;
+ await store.enqueueJob({
+ pairId: ctx.pair.id,
+ phase: 'sync',
+ op: 'reorder',
+ kind: 'roles',
+ sourceId: 'roles',
+ stepKey: 'reorder:roles',
+ now: deps.now(),
+ });
+ }
+
/** After the role order is set: ask again for every role that was made without its powerful permissions. */
async function enqueueGrants(ctx) {
- const pending = (await store.listMappings(ctx.pair.id, 'role')).filter(
- (m) => m.owned && m.specHash === ''
- );
+ // Adopted roles wait too (they are not Sylo's to delete, but an interrupted run made them and they are ordered).
+ const pending = (await store.listMappings(ctx.pair.id, 'role')).filter((m) => m.specHash === '');
for (const m of pending) {
await store.enqueueJob({
pairId: ctx.pair.id,
diff --git a/test/mirrorConsent.test.js b/test/mirrorConsent.test.js
index 84902792..05452646 100644
--- a/test/mirrorConsent.test.js
+++ b/test/mirrorConsent.test.js
@@ -166,3 +166,20 @@ test('the consent check can be replaced (the bridge can plug its link codes in)'
assert.equal((await requirePairConsent(pair.id)).id, pair.id);
await rejects(requirePairConsent(999_999), 'no-consent');
});
+
+test('real deletion asked for in a request takes effect only when the same person owns both servers', async () => {
+ await db.deletePair((await db.getPairBySource(D1))?.id ?? 0).catch(() => {});
+ const other = await ask({ targetOwner: false, options: { mirrorDeletes: true } });
+ assert.deepEqual(
+ [other.pair.options.mirrorDeletes, other.pair.options.mirrorDeletesRequested],
+ [false, true],
+ 'a request only, until the Fluxer owner turns it on'
+ );
+ const own = await ask({ targetOwner: true, options: { mirrorDeletes: true } });
+ assert.deepEqual([own.pair.options.mirrorDeletes, own.pair.options.mirrorDeletesRequested], [true, true]);
+ const plain = await ask({ targetOwner: false, options: { roles: false } });
+ assert.deepEqual(
+ [plain.pair.options.mirrorDeletes, plain.pair.options.mirrorDeletesRequested],
+ [false, false]
+ );
+});
diff --git a/test/mirrorGuards.test.js b/test/mirrorGuards.test.js
index 34bd4ee7..7c0f5bc7 100644
--- a/test/mirrorGuards.test.js
+++ b/test/mirrorGuards.test.js
@@ -594,3 +594,65 @@ test('a copied economy comes over switched off, with a note', async () => {
assert.equal(there.enabled, false);
assert.equal(there.config.startingBalance, 100, 'the settings are there for its owner to look at');
});
+
+test('a mirrored Administrator role deleted on Fluxer is made again without its permissions, ordered, then granted', async () => {
+ const s = await scenario({ withExpressions: false });
+ s.discord.roles.cache.get(s.k.mod).permissions = { bitfield: BIT.Administrator | BIT.ViewChannel };
+ await s.engine.startCopy(s.pair.id);
+ await drain(s);
+ const first = await mapped(s, 'role', s.k.mod);
+ assert.equal(roleBits(s, first) & ADMIN, ADMIN, 'the first copy granted it');
+
+ // Somebody deletes the role on Fluxer; it is edited on Discord, so the mirror syncs it.
+ s.fluxer.guild.roles.delete(first);
+ s.discord.roles.cache.get(s.k.mod).name = 'Moderators';
+ s.fluxer.calls.length = 0;
+ await s.engine.noteSourceChange(s.k.src, { kind: 'role', op: 'sync', id: s.k.mod });
+ await s.engine.runPair(s.pair.id);
+
+ const again = await mapped(s, 'role', s.k.mod);
+ assert.notEqual(again, first, 'a new role was made');
+ const calls = s.fluxer.calls;
+ const made = calls.findIndex((c) => c.op === 'createRole');
+ const ordered = calls.findIndex((c) => c.op === 'setRolePositions');
+ const granted = calls.findIndex((c) => c.op === 'editRole' && c.id === again);
+ assert.ok(made >= 0 && made < ordered && ordered < granted, 'made, then ordered, then granted');
+ assert.equal(BigInt(calls[made].spec.permissions) & ADMIN, 0n, 'made without Administrator');
+ assert.equal(roleBits(s, again) & ADMIN, ADMIN, 'and granted at the end');
+ assert.ok((await db.getMapping(s.pair.id, 'role', s.k.mod)).specHash, 'final');
+ assert.ok(s.fluxer.guild.roles.get(SYLO_ROLE).position > s.fluxer.guild.roles.get(again).position);
+});
+
+test('a role adopted after a crash waits for the order too, and gets its permissions after it', async () => {
+ const s = await scenario({ withExpressions: false });
+ s.discord.roles.cache.get(s.k.mod).permissions = { bitfield: BIT.Administrator };
+ await s.engine.startCopy(s.pair.id);
+ for (;;) {
+ const job = await db.nextDueJob(s.pair.id, s.clock.now);
+ if (job.kind === 'role' && job.sourceId === s.k.mod) break;
+ await s.engine.runPair(s.pair.id, { maxJobs: 1 });
+ }
+ const job = await db.nextDueJob(s.pair.id, s.clock.now);
+ assert.equal(await db.claimJob(job.id, s.clock.now), true);
+ // The dead run made the role with everything it asked for, but never wrote it down.
+ const madeId = await s.fluxer.target.createRole({
+ name: 'Mod',
+ color: 0,
+ hoist: false,
+ mentionable: true,
+ permissions: String(ADMIN),
+ });
+ const { engine } = engineFor({ discord: s.discord, fluxer: s.fluxer, clock: s.clock });
+ await engine.resumeAfterRestart();
+ s.engine = engine;
+ s.fluxer.calls.length = 0;
+ assert.equal((await drain(s)).status, 'live');
+ const adopted = await db.getMapping(s.pair.id, 'role', s.k.mod);
+ assert.deepEqual([adopted.targetId, adopted.owned], [madeId, false]);
+ const edits = s.fluxer.ops('editRole').filter((c) => c.id === madeId);
+ const ordered = s.fluxer.calls.findIndex((c) => c.op === 'setRolePositions');
+ assert.equal(BigInt(edits[0].spec.permissions) & ADMIN, 0n, 'first stripped');
+ assert.equal(roleBits(s, madeId) & ADMIN, ADMIN, 'and granted after the order');
+ assert.ok(s.fluxer.calls.indexOf(edits.at(-1)) > ordered);
+ assert.ok(adopted.specHash || (await db.getMapping(s.pair.id, 'role', s.k.mod)).specHash);
+});
diff --git a/test/v2Mirror.test.js b/test/v2Mirror.test.js
index 9f33a414..32bc6bb4 100644
--- a/test/v2Mirror.test.js
+++ b/test/v2Mirror.test.js
@@ -222,8 +222,16 @@ test('the same person who owns both servers agrees on both sides at once', async
[F_KEY],
'the Fluxer servers this person owns are offered'
);
- const res = await both.post(`/guilds/${D_GUILD}/mirror/request`, { targetGuildId: F_KEY });
+ const res = await both.post(`/guilds/${D_GUILD}/mirror/request`, {
+ targetGuildId: F_KEY,
+ options: { mirrorDeletes: true },
+ });
const body = await res.json();
+ assert.equal(
+ body.pair.options.mirrorDeletes,
+ true,
+ 'the owner of both servers can switch deletion on at once'
+ );
assert.equal(body.code, null);
assert.equal(body.agreed, true);
assert.equal(body.pair.status, 'ready');
@@ -238,10 +246,18 @@ test('an owner of one server who is only an Administrator of the other is not en
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 res = await mixed.post(`/guilds/${D_GUILD}/mirror/request`, { targetGuildId: F_KEY });
+ const res = await mixed.post(`/guilds/${D_GUILD}/mirror/request`, {
+ targetGuildId: F_KEY,
+ options: { mirrorDeletes: true },
+ });
const body = await res.json();
assert.equal(res.status, 200);
assert.equal(body.agreed, false, 'no automatic agreement for a server they do not own');
+ assert.deepEqual(
+ [body.pair.options.mirrorDeletes, body.pair.options.mirrorDeletesRequested],
+ [false, true],
+ 'deletion is only asked for: the Fluxer owner has to turn it on'
+ );
assert.ok(body.code, 'the Fluxer owner has to agree with the code');
assert.equal((await mixed.post(`/guilds/${F_KEY}/mirror/accept`, { code: body.code })).status, 403);
assert.equal((await db.getPairBySource(D_GUILD)).status, 'pending');
From 408aa36ad684f43707d5e4a5bb290fc4a8b18f2b Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Tue, 17 Nov 2026 01:09:16 +0100
Subject: [PATCH 08/17] feat(mirror): link mirrored channels through the bridge
---
src/db/index.js | 14 +-
src/db/mirror.js | 50 ++++
src/mirror/bridgeLink.js | 217 +++++++++++++-
src/mirror/consent.js | 22 +-
src/mirror/engine.js | 133 +++++++--
src/modules/bridge.js | 266 +++++++++++++++--
test/mirrorBridgeEngine.test.js | 310 ++++++++++++++++++++
test/mirrorBridgeLink.test.js | 503 ++++++++++++++++++++++++++++++++
test/mirrorEngine.test.js | 4 +-
9 files changed, 1460 insertions(+), 59 deletions(-)
create mode 100644 test/mirrorBridgeEngine.test.js
create mode 100644 test/mirrorBridgeLink.test.js
diff --git a/src/db/index.js b/src/db/index.js
index 375dfb07..4310a0b9 100644
--- a/src/db/index.js
+++ b/src/db/index.js
@@ -1661,8 +1661,8 @@ export const MIGRATIONS = [
`);
},
- // Migration 84 of the 5.3 line (it follows the bridge's 83 once both are merged; the entry is the next one
- // in this list whichever migrations sit before it): the server mirror (src/db/mirror.js, which bootstraps
+ // Migration 84 of the 5.3 line (it follows the bridge's 83; the entry is the next one in this list whichever
+ // migrations sit before it): the server mirror (src/db/mirror.js, which bootstraps
// the same tables on Postgres). Pairs of a Discord and a Fluxer server, the id map between their channels,
// roles, emoji and stickers, and the queue of work that makes a copy resumable.
(database) => {
@@ -1733,6 +1733,16 @@ export const MIGRATIONS = [
);
CREATE INDEX IF NOT EXISTS idx_mirror_jobs_pair ON mirror_jobs (pair_id, status, id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_mirror_jobs_open ON mirror_jobs (pair_id, step_key) WHERE status = 'pending';
+
+ CREATE TABLE IF NOT EXISTS mirror_links (
+ pair_id INTEGER NOT NULL,
+ source_channel TEXT NOT NULL,
+ target_channel TEXT NOT NULL,
+ link_id INTEGER NOT NULL,
+ created_at INTEGER NOT NULL,
+ PRIMARY KEY (pair_id, source_channel)
+ );
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_mirror_links_link ON mirror_links (link_id);
`);
},
];
diff --git a/src/db/mirror.js b/src/db/mirror.js
index c26af229..1d0d0328 100644
--- a/src/db/mirror.js
+++ b/src/db/mirror.js
@@ -7,6 +7,10 @@
// mirror_ids the id map of a pair: for each source id the id Sylo made (or adopted) on the target.
// `owned` is 1 for what Sylo created, and only owned items are ever deleted on the target.
// `spec_hash` is a fingerprint of what was last sent, so an unchanged item is not sent again.
+// mirror_links the bridge links the mirror made for the channel pairs of a pair (see src/mirror/bridgeLink.js):
+// which Discord channel and Fluxer channel, and the id of the bridge link. A row that stays after
+// its link is gone means somebody unlinked that channel on purpose, so the mirror does not link
+// it again.
// mirror_jobs the queue: one row per piece of work (copy one channel, update one role, delete one
// emoji ...). The queue is what makes a copy resumable: after a restart the unfinished rows
// are still there. Event rows coalesce: one open row per item.
@@ -82,6 +86,16 @@ registerPostgresBootstrap(`
);
CREATE INDEX IF NOT EXISTS idx_mirror_jobs_pair ON mirror_jobs (pair_id, status, id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_mirror_jobs_open ON mirror_jobs (pair_id, step_key) WHERE status = 'pending';
+
+ CREATE TABLE IF NOT EXISTS mirror_links (
+ pair_id INTEGER NOT NULL,
+ source_channel TEXT NOT NULL,
+ target_channel TEXT NOT NULL,
+ link_id INTEGER NOT NULL,
+ created_at BIGINT NOT NULL,
+ PRIMARY KEY (pair_id, source_channel)
+ );
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_mirror_links_link ON mirror_links (link_id);
`);
/** Pair states. `pending`: waiting for both servers to agree. `ready`: agreed, not copied yet. */
@@ -177,6 +191,15 @@ const s = {
deletePair: prepare('DELETE FROM mirror_pairs WHERE id = ?'),
deleteIds: prepare('DELETE FROM mirror_ids WHERE pair_id = ?'),
deleteJobs: prepare('DELETE FROM mirror_jobs WHERE pair_id = ?'),
+ deleteLinks: prepare('DELETE FROM mirror_links WHERE pair_id = ?'),
+ linksOfPair: prepare('SELECT * FROM mirror_links WHERE pair_id = ? ORDER BY source_channel'),
+ linkRow: prepare('SELECT * FROM mirror_links WHERE pair_id = ? AND source_channel = ?'),
+ putLink: prepare(
+ `INSERT INTO mirror_links (pair_id, source_channel, target_channel, link_id, created_at)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT (pair_id, source_channel) DO NOTHING`
+ ),
+ pairOfLink: prepare('SELECT pair_id FROM mirror_links WHERE link_id = ?'),
getId: prepare('SELECT * FROM mirror_ids WHERE pair_id = ? AND kind = ? AND source_id = ?'),
getIdByTarget: prepare('SELECT * FROM mirror_ids WHERE pair_id = ? AND kind = ? AND target_id = ?'),
@@ -341,6 +364,7 @@ export async function updatePair(id, patch, now = Date.now()) {
export async function deletePair(id) {
await s.deleteIds.run(id);
await s.deleteJobs.run(id);
+ await s.deleteLinks.run(id);
await s.deletePair.run(id);
}
@@ -351,6 +375,32 @@ export async function purgeMirrorOf(key) {
return pairs;
}
+// --- the bridge links of a pair ---------------------------------------------------------------------
+
+const toMirrorLink = (row) =>
+ row
+ ? {
+ pairId: num(row.pair_id),
+ sourceChannel: row.source_channel,
+ targetChannel: row.target_channel,
+ linkId: num(row.link_id),
+ createdAt: num(row.created_at),
+ }
+ : null;
+
+/** The bridge links the mirror of a pair made (or tried to make and then lost: see the file header). */
+export const listMirrorLinks = async (pairId) => (await s.linksOfPair.all(pairId)).map(toMirrorLink);
+export const getMirrorLink = async (pairId, sourceChannel) =>
+ toMirrorLink(await s.linkRow.get(pairId, sourceChannel));
+/** Remember that a bridge link belongs to a pair's mirror. A channel that already has a row keeps it. */
+export const putMirrorLink = (pairId, sourceChannel, targetChannel, linkId, now = Date.now()) =>
+ s.putLink.run(pairId, sourceChannel, targetChannel, Number(linkId), now);
+/** The pair a bridge link was made for, or null (a link somebody made by hand). */
+export async function mirrorPairOfLink(linkId) {
+ const row = await s.pairOfLink.get(Number(linkId));
+ return row ? num(row.pair_id) : null;
+}
+
// --- the id map -----------------------------------------------------------------------------------
const toMapping = (row) =>
diff --git a/src/mirror/bridgeLink.js b/src/mirror/bridgeLink.js
index bfd878ce..4aa14d86 100644
--- a/src/mirror/bridgeLink.js
+++ b/src/mirror/bridgeLink.js
@@ -1,22 +1,209 @@
-// The last step of a copy: link every mirrored channel through the bridge, so a message written in a
+// The last step of a copy: link every mirrored text channel through the bridge, so a message written in a
// Discord channel appears in its Fluxer copy and the other way round.
//
-// The bridge (its link model, webhooks and relay) is a separate package. Until it is wired in, this function is
-// what the copy calls at the end, and it does nothing: it reports that no channel was linked and why. The
-// copy shows that in its report ("Bridge linking: not available yet") and still finishes.
+// What this does, and what it leaves to the bridge (src/modules/bridge.js):
+// - It looks at the channel map of a pair (the id map says which Discord channel is which Fluxer channel) and
+// links every pair of text and announcement channels, through the bridge's own link model and relay.
+// - No link code is used. Both server owners already agreed to the mirror, and the pair keeps who and when;
+// the link records those two people (as " (server mirror)") as the ones who agreed to it.
+// - Every rule of the bridge holds for such a link (see createMirrorLink): age restriction, the two channels
+// being as private as each other, the owners' and Sylo's own rights in the channels, a visible notice in
+// both channels, bots off, a webhook per channel. A channel pair that fails a rule is skipped and reported,
+// and the rest go on. The Bridge module is switched on in both servers (it has to be on for a link to carry
+// anything) and both servers' audit logs say so.
+// - It is safe to run again: a pair that already has its link (made by the mirror, or found already linked
+// as this very pair) is left alone, and only missing pairs are linked. A pair that was unlinked on purpose
+// afterwards (on the Bridge page) is not linked again; that decision belongs to the owners.
+// - The links are held with the mirror: a mirror that is paused, stopped or removed pauses them, and they run
+// again when the mirror does (syncMirrorLinks, releaseMirrorLinks; the engine calls both).
//
-// The contract a real implementation keeps:
-// - input: the id of a mirror pair (src/db/mirror.js); the id map of that pair says which Discord channel is
-// which Fluxer channel;
-// - it links only text and announcement channels that both sides have, and skips a channel that is already
-// linked, so running it twice is safe;
-// - it returns how many channels it linked, and `reason` when it linked none on purpose;
-// - it throws only for a failure the copy should retry (the queue retries it with a delay).
+// Linking is done in batches of LINKS_PER_RUN; `remaining` says more are waiting, and the engine queues another
+// run. It throws only for a failure the copy should retry (the queue retries it with a delay).
+import { ChannelType } from 'discord.js';
+import { config } from '../config.js';
+import { log } from '../lib/log.js';
+import { runtime } from '../runtime.js';
+import { guildByKey } from '../platform/platformOf.js';
+import {
+ PAIR_STATUS,
+ getMirrorLink,
+ getPair,
+ listMappings,
+ listMirrorLinks,
+ putMirrorLink,
+} from '../db/mirror.js';
+import { linkForChannel } from '../db/bridge.js';
+import {
+ BridgeError,
+ createMirrorLink,
+ enableBridgeForMirror,
+ holdMirrorLink,
+ releaseMirrorLink,
+ resumeMirrorLink,
+} from '../modules/bridge.js';
+
+/** How many pairs one run links (each makes two webhooks and posts two notices). */
+export const LINKS_PER_RUN = 25;
+const PAUSE_BETWEEN_MS = 500;
+
+const TEXT_TYPES = new Set([ChannelType.GuildText, ChannelType.GuildAnnouncement]);
+const isText = (channel) => Boolean(channel) && TEXT_TYPES.has(channel.type);
+const channelOf = (guild, id) => guild?.channels?.cache?.get?.(String(id)) ?? null;
+
+/** The states in which the mirror runs, and so do the links it made. */
+const RUNNING = new Set([PAIR_STATUS.COPYING, PAIR_STATUS.LIVE, PAIR_STATUS.DONE]);
+export const mirrorRuns = (pair) => Boolean(pair) && RUNNING.has(pair.status);
+
+const sleepReal = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/** An owner's member in their own server (null when it cannot be had). */
+async function memberOf(guild, userId) {
+ if (!guild || !userId) return null;
+ try {
+ return (
+ guild.members?.cache?.get?.(String(userId)) ?? (await guild.members?.fetch?.(String(userId))) ?? null
+ );
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Put a pair's links in step with the mirror: while it runs, the links it holds run again; otherwise they are
+ * paused. Only links the mirror made are touched, and only those it paused itself are resumed.
+ * @returns {Promise<{ held: number, resumed: number, waiting: string[] }>}
+ */
+export async function syncMirrorLinks(pairOrId) {
+ const pair = typeof pairOrId === 'object' ? pairOrId : await getPair(Number(pairOrId));
+ const out = { held: 0, resumed: 0, waiting: [] };
+ if (!pair) return out;
+ for (const row of await listMirrorLinks(pair.id)) {
+ if (mirrorRuns(pair)) {
+ const res = await resumeMirrorLink(row.linkId);
+ if (res.resumed) out.resumed += 1;
+ else if (res.reason) out.waiting.push(res.reason);
+ } else if (await holdMirrorLink(row.linkId)) {
+ out.held += 1;
+ }
+ }
+ return out;
+}
+
+/** The mirror is being removed: its links stay, paused, and either owner can resume or unlink them on the Bridge page. */
+export async function releaseMirrorLinks(pairId) {
+ let released = 0;
+ for (const row of await listMirrorLinks(pairId)) {
+ if (await releaseMirrorLink(row.linkId)) released += 1;
+ }
+ return released;
+}
/**
- * @param {number} _pairId
- * @returns {Promise<{ linked: number, reason?: string }>}
+ * Link every mirrored text channel pair that is not linked yet.
+ * @param {number} pairId
+ * @param {{ sleep?: (ms: number) => Promise, limit?: number, skip?: Set, open?: boolean }} [opts]
+ * `skip`: channels (Discord ids) an earlier run of the same step already tried, so a batch does not try them again;
+ * `open`: sign-in is off (the default follows the configuration), so there are no owners to check
+ * @returns {Promise<{ linked: number, already: number, remaining: number, tried: string[], skipped: { sourceId: string, name: string, code: string, message: string }[], reason?: string }>}
*/
-export async function linkMirroredChannels(_pairId) {
- return { linked: 0, reason: 'bridge-not-available' };
+export async function linkMirroredChannels(
+ pairId,
+ { sleep = sleepReal, limit = LINKS_PER_RUN, skip = new Set(), open = !config.authEnabled } = {}
+) {
+ const none = (reason) => ({ linked: 0, already: 0, remaining: 0, tried: [], skipped: [], reason });
+ const pair = await getPair(Number(pairId));
+ if (!pair) return none('no-such-mirror');
+ if (!mirrorRuns(pair)) return none('mirror-not-running');
+ if (!runtime.clients.discord || !runtime.clients.fluxer) return none('bridge-not-available');
+
+ const sg = guildByKey(pair.sourceGuild);
+ const tg = guildByKey(pair.targetGuild);
+ if (!sg || !tg) return none('server-missing');
+
+ // The links the mirror holds go on again first (this is also how a "copy again" wakes them after a pause).
+ await syncMirrorLinks(pair);
+
+ const todo = [];
+ const skipped = [];
+ let already = 0;
+ for (const m of await listMappings(pair.id, 'channel')) {
+ if (m.removedAt > 0) continue;
+ const src = channelOf(sg, m.sourceId);
+ const dst = channelOf(tg, m.targetId);
+ if (!isText(src) || !isText(dst)) continue; // voice, category, forum and the like are not bridged
+ if (await getMirrorLink(pair.id, m.sourceId)) {
+ already += 1;
+ continue;
+ }
+ if (skip.has(m.sourceId)) continue;
+ const found = await linkForChannel(pair.sourceGuild, m.sourceId);
+ if (found) {
+ const same = found.side === 'a' && found.link.guildB === pair.targetGuild && found.link.channelB === m.targetId;
+ if (same) {
+ // A link of exactly this pair whose record was lost (a restart between the two writes): take it over.
+ await putMirrorLink(pair.id, m.sourceId, m.targetId, found.link.id);
+ already += 1;
+ } else {
+ skipped.push({
+ sourceId: m.sourceId,
+ name: m.label || src.name,
+ code: 'exists',
+ message: 'this channel is already bridged to another channel',
+ });
+ }
+ continue;
+ }
+ todo.push({ sourceId: m.sourceId, targetId: m.targetId, name: m.label || src.name });
+ }
+ if (todo.length === 0) {
+ const out = { linked: 0, already, remaining: 0, tried: [], skipped };
+ return already || skipped.length ? out : { ...out, reason: 'nothing-to-link' };
+ }
+
+ await enableBridgeForMirror(pair.sourceGuild);
+ await enableBridgeForMirror(pair.targetGuild);
+
+ // The owners who agreed must be able to see, read and send in each channel themselves (as for a link made by
+ // hand). With sign-in off there is no one to check.
+ const members = {
+ source: open ? null : await memberOf(sg, pair.sourceConsentUser),
+ target: open ? null : await memberOf(tg, pair.targetConsentUser),
+ };
+ const consent = {
+ sourceBy: pair.sourceConsentBy,
+ targetBy: pair.targetConsentBy,
+ sourceOwner: String(sg.ownerId ?? ''),
+ targetOwner: String(tg.ownerId ?? ''),
+ };
+
+ let linked = 0;
+ let attempted = 0;
+ const tried = [];
+ for (const item of todo) {
+ if (attempted >= limit) break;
+ attempted += 1;
+ tried.push(item.sourceId);
+ try {
+ const link = await createMirrorLink({
+ source: { guildKey: pair.sourceGuild, channelId: item.sourceId },
+ target: { guildKey: pair.targetGuild, channelId: item.targetId },
+ members,
+ open,
+ consent,
+ });
+ await putMirrorLink(pair.id, item.sourceId, item.targetId, link.id);
+ linked += 1;
+ } catch (err) {
+ if (!(err instanceof BridgeError)) throw err;
+ log.info('mirror', `pair ${pair.id}: ${item.name} not linked (${err.code || err.status}): ${err.message}`);
+ skipped.push({
+ sourceId: item.sourceId,
+ name: item.name,
+ code: err.code || 'refused',
+ message: err.message,
+ });
+ }
+ if (attempted < limit && attempted < todo.length) await sleep(PAUSE_BETWEEN_MS);
+ }
+ return { linked, already, remaining: Math.max(0, todo.length - attempted), tried, skipped };
}
diff --git a/src/mirror/consent.js b/src/mirror/consent.js
index e3dfb73c..f2b06471 100644
--- a/src/mirror/consent.js
+++ b/src/mirror/consent.js
@@ -104,6 +104,22 @@ function askedOptions(options, targetOwner) {
return out;
}
+/**
+ * The options a new request keeps when it brings none of its own. Real deletion on Fluxer is the Fluxer owner's own
+ * switch, so it is kept only when the same person who switched it on (the Fluxer owner recorded on the pair) now owns
+ * both servers; a new Fluxer owner, or a request from someone who is not the Fluxer owner, starts with it off (the
+ * request for it stays, so the owner can switch it on themselves).
+ */
+function inheritedOptions(pair, targetOwner, targetUser) {
+ const out = normaliseOptions(pair.options);
+ out.mirrorDeletes =
+ out.mirrorDeletes &&
+ Boolean(targetOwner) &&
+ Boolean(pair.targetConsentUser) &&
+ pair.targetConsentUser === targetUser;
+ return out;
+}
+
/** A pair that has never copied anything may be replaced by a new request; one that has, may not. */
const replaceable = (pair) =>
pair.status === PAIR_STATUS.PENDING ||
@@ -175,7 +191,11 @@ export async function requestMirror({
codeAttempts: 0,
lastError: '',
failures: 0,
- ...(options ? { options: askedOptions(options, targetOwner) } : {}),
+ ...(options
+ ? { options: askedOptions(options, targetOwner) }
+ : pair
+ ? { options: inheritedOptions(pair, targetOwner, targetUser) }
+ : {}),
};
if (pair) {
pair = await updatePair(pair.id, fields, now);
diff --git a/src/mirror/engine.js b/src/mirror/engine.js
index ead198fe..42ca87ad 100644
--- a/src/mirror/engine.js
+++ b/src/mirror/engine.js
@@ -27,7 +27,11 @@ import { log } from '../lib/log.js';
import { allClientsReady, guildByKey } from '../platform/platformOf.js';
import { safeFetch } from '../lib/safeFetch.js';
import { requirePairConsent } from './consent.js';
-import { linkMirroredChannels as defaultLink } from './bridgeLink.js';
+import {
+ linkMirroredChannels as defaultLink,
+ releaseMirrorLinks as defaultRelease,
+ syncMirrorLinks as defaultSync,
+} from './bridgeLink.js';
import { MirrorError, MirrorPause, classifyError } from './errors.js';
import { checkOwnership } from './ownership.js';
import { NOT_COPIED_MODULES, buildModuleSpec, buildPlan, channelOrder, copiedSets } from './plan.js';
@@ -54,6 +58,7 @@ const SOURCE_LIST = { role: 'roles', channel: 'channels', emoji: 'emojis', stick
/** After a reorder-worthy change, wait a little so one drag of many channels is one reorder. */
const REORDER_DELAY_MS = 3000;
const PRUNE_EVERY_MS = 60 * 60_000;
+const LINK_SWEEP_MS = 60_000;
const KEEP_FINISHED_MS = 7 * 86_400_000;
const ADOPT_SKEW_MS = 5000;
// Fluxer ids are snowflakes: the time they were made is in the high bits.
@@ -110,6 +115,9 @@ export function createEngine(overrides = {}) {
fetchImage: fetchImageReal,
clientsReady: allClientsReady,
linkMirroredChannels: defaultLink,
+ // The bridge links a mirror made follow its state: paused with it, running again with it, released when it goes.
+ syncLinks: defaultSync,
+ releaseLinks: defaultRelease,
// Only a server's owner may run a mirror: with sign-in on, the owners who agreed must still own the servers.
enforceOwnership: () => config.authEnabled,
// More than this many deletes on Discord in this many ms pause the mirror until its owner confirms them.
@@ -123,6 +131,7 @@ export function createEngine(overrides = {}) {
/** Per pair: kinds Fluxer refused as over a limit this run, and when it asked to wait. */
const state = new Map();
let lastPrune = 0;
+ let lastLinkSweep = 0;
let stopped = false;
const stateOf = (pairId) => {
@@ -597,18 +606,23 @@ export function createEngine(overrides = {}) {
/**
* A role was made (or adopted, or made again) on Fluxer: its place in the order is not set yet. Forget that the order
- * was set, so the order step really runs; in continuous mode, ask for it now (in a copy the plan's order step follows).
+ * was set, so the order step really runs, and ask for it now. Inside a copy run the request is a copy job with the key
+ * of the plan's own order step, so it joins that step when it is still waiting; "copy again" leaves the step out when
+ * the order did not change on Discord, and a role that was deleted on Fluxer and is made again would otherwise stay at
+ * the bottom without its powerful permissions. An order that is already set is a no-op.
*/
async function roleMadeOnFluxer(ctx) {
await store.deleteMapping(ctx.pair.id, 'order', 'roles');
- if (ctx.job?.phase === 'copy') return;
+ const inCopy = ctx.job?.phase === 'copy';
await store.enqueueJob({
pairId: ctx.pair.id,
- phase: 'sync',
+ run: inCopy ? ctx.job.run : 0,
+ phase: inCopy ? 'copy' : 'sync',
op: 'reorder',
kind: 'roles',
sourceId: 'roles',
- stepKey: 'reorder:roles',
+ stepKey: inCopy ? `copy:${ctx.job.run}:order-roles:roles` : 'reorder:roles',
+ payload: inCopy ? { name: 'Role order', planned: 'update' } : {},
now: deps.now(),
});
}
@@ -689,9 +703,25 @@ export function createEngine(overrides = {}) {
}
}
await put(await ctx.target.createChannel(value), true);
+ // A channel made while the mirror runs is linked through the bridge too (the step links only what is missing).
+ if (ctx.job?.phase !== 'copy') await enqueueLinkStep(ctx.pair.id);
return done('created', { notes, remote: true });
}
+ /** Ask for the bridge step: link the mirrored channels that have no link yet. One open request at a time. */
+ async function enqueueLinkStep(pairId) {
+ await store.enqueueJob({
+ pairId,
+ phase: 'sync',
+ op: 'link',
+ kind: 'bridge',
+ sourceId: 'link',
+ stepKey: 'bridge:link',
+ payload: { name: 'Link new channels through the bridge', planned: 'create' },
+ now: deps.now(),
+ });
+ }
+
/** Download an image for an emoji or sticker; null (with a note) when it is too big. */
async function download(ctx, item, maxBytes, code, kind) {
if (!item.url) return { note: noteFor(code, kind, item, 'it has no image to copy') };
@@ -972,6 +1002,44 @@ export function createEngine(overrides = {}) {
});
}
+ /**
+ * The last step of a copy: link the mirrored text channels through the bridge (src/mirror/bridgeLink.js). A pair the
+ * bridge refuses is skipped and listed in the notes; when more pairs wait than one run links, another run is queued.
+ */
+ async function linkChannels(ctx, job) {
+ const tried = new Set(job.payload?.tried ?? []);
+ const res = await deps.linkMirroredChannels(ctx.pair.id, { skip: tried });
+ const skippedPairs = res.skipped ?? [];
+ const notes = skippedPairs.map((s) => ({
+ code: `bridge-${s.code}`,
+ scope: 'channel',
+ ref: { kind: 'channel', id: s.sourceId, name: s.name },
+ message: `${s.name}: not linked through the bridge, ${s.message}`,
+ }));
+ if ((res.remaining ?? 0) > 0) {
+ await store.enqueueJob({
+ pairId: ctx.pair.id,
+ run: job.run,
+ phase: job.phase,
+ op: 'link',
+ kind: 'bridge',
+ sourceId: job.sourceId,
+ stepKey: job.stepKey,
+ payload: { ...job.payload, tried: [...tried, ...(res.tried ?? [])] },
+ now: deps.now(),
+ });
+ }
+ const parts = [];
+ if (res.linked > 0) parts.push(`${res.linked} channels linked`);
+ if ((res.already ?? 0) > 0) parts.push(`${res.already} already linked`);
+ if (skippedPairs.length > 0) parts.push(`${skippedPairs.length} not linked (see the notes)`);
+ if ((res.remaining ?? 0) > 0) parts.push(`${res.remaining} more follow`);
+ return done(parts.length ? parts.join(', ') : `not linked: ${res.reason ?? 'nothing to link'}`, {
+ notes,
+ remote: res.linked > 0,
+ });
+ }
+
async function perform(ctx, job) {
if (job.payload?.skip) return skipped(String(job.payload.skip), { notes: job.payload.notes ?? [] });
if (job.op === 'delete') {
@@ -980,12 +1048,7 @@ export function createEngine(overrides = {}) {
: lockCopy(ctx, job.kind, job.sourceId);
}
if (job.op === 'reorder') return reorder(ctx, job.kind);
- if (job.op === 'link') {
- const res = await deps.linkMirroredChannels(ctx.pair.id);
- return done(
- res.linked > 0 ? `${res.linked} channels linked` : `not linked: ${res.reason ?? 'nothing to link'}`
- );
- }
+ if (job.op === 'link') return linkChannels(ctx, job);
switch (job.kind) {
case 'guild':
return syncIdentity(ctx);
@@ -1023,9 +1086,19 @@ export function createEngine(overrides = {}) {
);
touchHealth(next);
log.warn('mirror', `pair ${pair.id} paused: ${message}`);
+ await linksFollow(next);
return next;
}
+ /** The bridge links of a pair follow its state. A failure is logged and put right by the next sweep of the timer. */
+ async function linksFollow(pair) {
+ try {
+ await deps.syncLinks(pair);
+ } catch (err) {
+ log.warn('mirror', `could not update the bridge links of pair ${pair.id}: ${err?.message ?? err}`);
+ }
+ }
+
const backoffMs = (attempts) =>
Math.min(deps.maxBackoffMs, deps.backoffBaseMs * 2 ** Math.max(0, attempts - 1));
@@ -1166,6 +1239,11 @@ export function createEngine(overrides = {}) {
lastPrune = now;
await store.pruneMirrorJobs({ before: now - KEEP_FINISHED_MS });
}
+ // Keep the bridge links in step with their mirrors: a pause or resume that could not reach them is put right here.
+ if (now - lastLinkSweep > LINK_SWEEP_MS) {
+ lastLinkSweep = now;
+ for (const pair of await store.listAllPairs()) await linksFollow(pair);
+ }
for (const status of [PAIR_STATUS.COPYING, PAIR_STATUS.LIVE]) {
for (const pair of await store.listPairsIn(status)) {
if (active.has(pair.id)) continue;
@@ -1209,6 +1287,7 @@ export function createEngine(overrides = {}) {
deps.now()
);
touchHealth(next);
+ await linksFollow(next);
return next;
}
@@ -1261,13 +1340,16 @@ export function createEngine(overrides = {}) {
if (pair.pauseKind === 'ownership' && ['source', 'target'].includes(side)) {
const guild = side === 'source' ? sg : tg;
if (guild?.ownerId) {
- pair = await store.updatePair(
- pairId,
+ const patch =
side === 'source'
? { sourceConsentUser: String(guild.ownerId) }
- : { targetConsentUser: String(guild.ownerId) },
- deps.now()
- );
+ : { targetConsentUser: String(guild.ownerId) };
+ // Real deletion on Fluxer is the Fluxer owner's own switch: a new owner starts with it off (the request stays,
+ // so they can switch it on themselves).
+ if (side === 'target' && String(guild.ownerId) !== pair.targetConsentUser) {
+ patch.options = { ...normaliseOptions(pair.options), mirrorDeletes: false };
+ }
+ pair = await store.updatePair(pairId, patch, deps.now());
}
}
await requirePairConsent(pair);
@@ -1303,6 +1385,7 @@ export function createEngine(overrides = {}) {
deps.now()
);
touchHealth(next);
+ await linksFollow(next);
return next;
}
@@ -1331,6 +1414,7 @@ export function createEngine(overrides = {}) {
);
state.delete(pairId);
touchHealth(next);
+ await linksFollow(next);
return next;
}
@@ -1341,6 +1425,8 @@ export function createEngine(overrides = {}) {
if ([PAIR_STATUS.COPYING, PAIR_STATUS.LIVE].includes(pair.status)) {
throw new MirrorError('Stop the mirror before removing it.', 'item');
}
+ // The bridge links it made stay, paused: the owners decide on the Bridge page whether to resume or unlink them.
+ await deps.releaseLinks(pairId);
await store.deletePair(pairId);
state.delete(pairId);
touchHealth(pair);
@@ -1397,13 +1483,24 @@ export function createEngine(overrides = {}) {
detail: j.detail,
}));
const notes = jobs.flatMap((j) => j.notes);
- const link = jobs.find((j) => j.op === 'link');
+ // The bridge step can take several runs (a batch of channels each): show them as one.
+ const links = jobs.filter((j) => j.op === 'link');
+ const open = links.find((j) => ['pending', 'running', 'failed'].includes(j.status));
+ const bridge = links.length
+ ? {
+ status: open ? open.status : links[links.length - 1].status,
+ detail: links
+ .map((j) => j.detail)
+ .filter(Boolean)
+ .join('; '),
+ }
+ : null;
return {
run: pair.copyRun,
items,
notes,
failed: items.filter((i) => i.status === 'failed'),
- bridge: link ? { status: link.status, detail: link.detail } : null,
+ bridge,
summary: summariseJobs(jobs),
};
}
diff --git a/src/modules/bridge.js b/src/modules/bridge.js
index a3998e2b..08818e00 100644
--- a/src/modules/bridge.js
+++ b/src/modules/bridge.js
@@ -24,7 +24,7 @@
import { ChannelType } from 'discord.js';
import { on } from './dispatch.js';
import { every } from './schedule.js';
-import { getGuildModule, isModuleEnabled } from '../db/modules.js';
+import { getGuildModule, isModuleEnabled, setGuildModule } from '../db/modules.js';
import { recordAudit } from '../db/audit.js';
import { onBeforePurge } from '../db/purge.js';
import * as store from '../db/bridge.js';
@@ -62,6 +62,8 @@ import {
/** The most links a server can have, and the most requests it can have waiting. */
export const MAX_LINKS = 10;
export const MAX_REQUESTS = 5;
+/** The ceiling for a server that is mirrored (src/mirror/bridgeLink.js links every copied text channel). */
+export const MAX_MIRROR_LINKS = 50;
/** How many failed deliveries in a row stop a link. */
export const FAIL_THRESHOLD = 5;
@@ -70,10 +72,12 @@ const CACHE_MS = 60_000;
/** A refusal the dashboard shows as it is. `status` is the HTTP answer. */
export class BridgeError extends Error {
- constructor(message, status = 400) {
+ /** `code` names the refusal for code that has to tell them apart (the server mirror's report). */
+ constructor(message, status = 400, code = '') {
super(message);
this.name = 'BridgeError';
this.status = status;
+ this.code = code;
}
}
@@ -250,6 +254,10 @@ const REASONS = {
'The owner of one of the servers changed. The bridge is paused until the new owner confirms it: as the owner, open the Bridge page and press Resume.',
'age-restriction':
'One channel changed its age restriction, so the two no longer match. An age-restricted channel can only be bridged with an age-restricted one.',
+ mirror:
+ 'This bridge was made by the server mirror and is paused with it. It runs again when the mirror does.',
+ 'mirror-ended':
+ 'The server mirror that made this bridge ended. Either server owner can resume the bridge on the Bridge page, or unlink it.',
};
/** The text a link's stored failure reason stands for. */
export const reasonText = (code) => REASONS[code] ?? 'The bridge stopped working.';
@@ -279,7 +287,8 @@ export function assertActorMayUse(key, channelId, member, { open = false } = {})
if (!perms || missing.length) {
throw new BridgeError(
`You need to be able to view, read and send in #${channel?.name ?? 'that channel'} yourself to bridge it.`,
- 403
+ 403,
+ 'visibility'
);
}
}
@@ -291,15 +300,19 @@ export function assertActorMayUse(key, channelId, member, { open = false } = {})
*/
function checkChannel(key, channelId) {
const guild = guildByKey(key);
- if (!guild) throw new BridgeError('Sylo is not in that server.', 404);
+ if (!guild) throw new BridgeError('Sylo is not in that server.', 404, 'no-guild');
const channel = guild.channels?.cache?.get?.(channelId);
- if (!isTextChannel(channel)) throw new BridgeError('Pick a normal text channel of this server.');
+ if (!isTextChannel(channel)) {
+ throw new BridgeError('Pick a normal text channel of this server.', 400, 'not-text');
+ }
const perms = channel.permissionsFor?.(guild.members?.me);
// Sylo's own rights: when they cannot be read, they count as missing.
const missing = ['ViewChannel', 'SendMessages', 'ManageWebhooks'].filter((p) => lacks(perms, p));
if (missing.length) {
throw new BridgeError(
- `Sylo needs ${missing.join(', ')} in #${channel.name}. Give Sylo's role those permissions there first.`
+ `Sylo needs ${missing.join(', ')} in #${channel.name}. Give Sylo's role those permissions there first.`,
+ 400,
+ 'permissions'
);
}
return { guild, channel };
@@ -315,7 +328,8 @@ function requireBothPlatforms() {
if (!runtime.clients.discord || !runtime.clients.fluxer) {
throw new BridgeError(
'A bridge needs this Sylo to be connected to both Discord and Fluxer, and it is not.',
- 409
+ 409,
+ 'platform'
);
}
}
@@ -324,7 +338,9 @@ function requireBothPlatforms() {
function checkAge(keyA, a, keyB, b) {
if (ageRestricted(keyA, a) !== ageRestricted(keyB, b)) {
throw new BridgeError(
- 'An age-restricted channel can only be bridged with another age-restricted channel.'
+ 'An age-restricted channel can only be bridged with another age-restricted channel.',
+ 400,
+ 'age-restriction'
);
}
}
@@ -538,19 +554,10 @@ export async function pauseLink({ guildKey, id, actor }) {
}
/**
- * Resume a link. A link a server paused can only be resumed by that server; one Sylo stopped (a failure)
- * can be resumed by either, after the cause is fixed: the channels, permissions, webhooks and the age rule
- * are checked again first.
+ * Everything that has to hold before a stopped or paused link runs again: both platforms connected, the module on
+ * on both servers, both channels usable by Sylo, the age rule, and a working webhook on each side.
*/
-export async function resumeLink({ guildKey, id, actor }) {
- const { link, side } = await ownLink(guildKey, id);
- if (link.status === 'active') throw new BridgeError('That bridge is already running.', 409);
- if (link.status === 'paused' && link.pausedSide !== side) {
- throw new BridgeError('The other server paused this bridge, so only they can resume it.', 403);
- }
- // The one pressing Resume is the owner of this server (the route checks): this is the confirmation a new owner gives.
- await store.setLinkOwner(link.id, side, ownerOf(guildKey));
- link[side === 'a' ? 'ownerA' : 'ownerB'] = ownerOf(guildKey);
+async function revalidate(link) {
requireBothPlatforms();
await requireModule(link.guildA);
await requireModule(link.guildB);
@@ -577,6 +584,27 @@ export async function resumeLink({ guildKey, id, actor }) {
}
}
failures.delete(link.id);
+}
+
+/**
+ * Resume a link. A link a server paused can only be resumed by that server; one Sylo stopped (a failure)
+ * can be resumed by either, after the cause is fixed: the channels, permissions, webhooks and the age rule
+ * are checked again first.
+ */
+export async function resumeLink({ guildKey, id, actor }) {
+ const { link, side } = await ownLink(guildKey, id);
+ if (link.status === 'active') throw new BridgeError('That bridge is already running.', 409);
+ if (link.status === 'paused' && link.failReason === 'mirror') {
+ throw new BridgeError('The server mirror made this bridge and paused it. It runs again when the mirror does.', 409);
+ }
+ // A link nobody owns the pause of (the mirror that made it ended) can be resumed by either server.
+ if (link.status === 'paused' && link.pausedSide && link.pausedSide !== side) {
+ throw new BridgeError('The other server paused this bridge, so only they can resume it.', 403);
+ }
+ // The one pressing Resume is the owner of this server (the route checks): this is the confirmation a new owner gives.
+ await store.setLinkOwner(link.id, side, ownerOf(guildKey));
+ link[side === 'a' ? 'ownerA' : 'ownerB'] = ownerOf(guildKey);
+ await revalidate(link);
// The other server's owner may have changed too: it has to confirm as well before anything is shared.
const stillChanged = ownerChangedSide(link);
if (stillChanged) {
@@ -607,6 +635,201 @@ export async function resumeLink({ guildKey, id, actor }) {
return { active: true };
}
+// --- links made by the server mirror ------------------------------------------------------------------
+//
+// The server mirror (src/mirror/) copies a Discord server's channels onto a Fluxer server and then links each
+// pair of text channels through the bridge, so one conversation runs through both. Both server owners agreed
+// to the mirror, which is the consent a link code carries for a link made by hand, so these links are made
+// without a code. Everything else of the bridge holds for them: the age rule, the visibility rules, Sylo's and
+// the owners' own rights in the channels, a visible notice in both channels, bots off by default, the owners
+// recorded for the ownership check, and either owner can unlink a channel at any time. A link the mirror made
+// is held with the mirror: while the mirror is paused or stopped, its links are paused (reason `mirror`), and
+// they run again when the mirror does.
+
+/** What a mirror-made link records as the people who agreed to it. */
+const mirrorBy = (name) => `${String(name || 'server owner').slice(0, 60)} (server mirror)`.slice(0, 100);
+
+/** Can @everyone see this channel? null when that cannot be worked out (it then counts as not matching). */
+function everyoneSees(key, channel) {
+ const guild = guildByKey(key);
+ try {
+ const perms = channel?.permissionsFor?.(String(guild?.id ?? ''));
+ if (!perms || typeof perms.has !== 'function') return null;
+ return perms.has('ViewChannel') === true;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Turn the Bridge module on in a server the mirror links channels in. The owner agreed to the mirror, which
+ * links every copied channel, and the module has to be on for the links to carry anything.
+ * @returns {Promise} whether it was switched on now
+ */
+export async function enableBridgeForMirror(key, actor = 'Server mirror') {
+ if (await isModuleEnabled(key, 'bridge')) return false;
+ await setGuildModule(key, 'bridge', { enabled: true });
+ await recordAudit(key, {
+ actor,
+ action: 'bridge:module',
+ detail: 'turned the Bridge module on because the server mirror links the channels of this server',
+ change: null,
+ });
+ return true;
+}
+
+/**
+ * Link a mirrored channel pair (the Discord channel is side a, the Fluxer copy side b). Throws a BridgeError
+ * with a `code` when the pair cannot be linked (`not-text`, `permissions`, `age-restriction`, `visibility`,
+ * `exists`, `limit`, `webhook`, `no-guild`, `platform`); the caller reports it and goes on with the next pair.
+ * `members` are the two owners' members in their own servers, to check that each can see, read and send in
+ * the channel; `open` says sign-in is off, so there is no one to check.
+ * @param {{
+ * source: { guildKey: string, channelId: string }, target: { guildKey: string, channelId: string },
+ * members?: { source?: any, target?: any }, open?: boolean,
+ * consent?: { sourceBy?: string, targetBy?: string, sourceOwner?: string, targetOwner?: string }
+ * }} req
+ */
+export async function createMirrorLink({ source, target, members = {}, open = false, consent = {} }) {
+ requireBothPlatforms();
+ const a = checkChannel(source.guildKey, source.channelId);
+ const b = checkChannel(target.guildKey, target.channelId);
+ if (
+ (await store.linkForChannel(source.guildKey, source.channelId)) ||
+ (await store.linkForChannel(target.guildKey, target.channelId))
+ ) {
+ throw new BridgeError('One of the channels is already bridged.', 409, 'exists');
+ }
+ for (const key of [source.guildKey, target.guildKey]) {
+ if ((await store.linkCount(key)) >= MAX_MIRROR_LINKS) {
+ throw new BridgeError(`A server can have at most ${MAX_MIRROR_LINKS} bridged channels.`, 409, 'limit');
+ }
+ }
+ checkAge(source.guildKey, a.channel, target.guildKey, b.channel);
+ // A channel only some members can see is linked only to a channel that is as closed: nothing private is
+ // shared with a channel everyone can read, in either direction.
+ const seenA = everyoneSees(source.guildKey, a.channel);
+ const seenB = everyoneSees(target.guildKey, b.channel);
+ if (seenA === null || seenB === null || seenA !== seenB) {
+ throw new BridgeError(
+ 'The two channels are not open to the same people (one is private, or it cannot be told), so they are not bridged.',
+ 409,
+ 'visibility'
+ );
+ }
+ assertActorMayUse(source.guildKey, source.channelId, members.source, { open });
+ assertActorMayUse(target.guildKey, target.channelId, members.target, { open });
+
+ const made = [];
+ const dropMade = async () => {
+ for (const [key, hook] of made) await transport.deleteHook(key, hook).catch(() => {});
+ };
+ let hookA;
+ let hookB;
+ try {
+ hookA = await transport.createHook(source.guildKey, source.channelId, HOOK_NAME);
+ made.push([source.guildKey, hookA]);
+ hookB = await transport.createHook(target.guildKey, target.channelId, HOOK_NAME);
+ made.push([target.guildKey, hookB]);
+ } catch (err) {
+ await dropMade();
+ log.warn('bridge', `could not make the webhooks for a mirrored link: ${err?.message ?? err}`);
+ throw new BridgeError('Sylo could not make a webhook in one of the channels.', 502, 'webhook');
+ }
+ const id = await store.createLink({
+ guildA: source.guildKey,
+ channelA: source.channelId,
+ guildB: target.guildKey,
+ channelB: target.channelId,
+ optionsA: normaliseOptions({}),
+ optionsB: normaliseOptions({}),
+ hookA,
+ hookB,
+ requestedBy: mirrorBy(consent.sourceBy),
+ acceptedBy: mirrorBy(consent.targetBy),
+ ownerA: consent.sourceOwner || ownerOf(source.guildKey),
+ ownerB: consent.targetOwner || ownerOf(target.guildKey),
+ });
+ if (!id) {
+ await dropMade();
+ throw new BridgeError('One of the channels was bridged in the meantime.', 409, 'exists');
+ }
+ dropBridgeCache();
+ const link = await store.getLink(id);
+ for (const [mine, theirs, by] of [
+ [source, target, consent.sourceBy],
+ [target, source, consent.targetBy],
+ ]) {
+ await recordAudit(mine.guildKey, {
+ actor: by || 'Server mirror',
+ action: 'bridge:link',
+ detail: `bridged #${channelName(mine.guildKey, mine.channelId)} with #${channelName(theirs.guildKey, theirs.channelId)} in ${serverName(theirs.guildKey)} (${platformName(theirs.guildKey)}) through the server mirror`,
+ change: null,
+ });
+ }
+ const note = ' This link was made by the server mirror that both servers’ owners agreed to.';
+ await say(
+ source.guildKey,
+ source.channelId,
+ onNotice(source.guildKey, target.guildKey, target.channelId) + note
+ );
+ await say(
+ target.guildKey,
+ target.channelId,
+ onNotice(target.guildKey, source.guildKey, source.channelId) + note
+ );
+ return link;
+}
+
+/** Pause a running link because its mirror is not running. No notice per channel: nothing is shared while it is paused. */
+export async function holdMirrorLink(linkId) {
+ const link = await store.getLink(linkId);
+ if (!link || link.status !== 'active') return false;
+ await store.setLinkStatus(link.id, { status: 'paused', pausedSide: '', reason: 'mirror' });
+ dropBridgeCache();
+ queue.clear(laneKey(link, 'a'));
+ queue.clear(laneKey(link, 'b'));
+ return true;
+}
+
+/**
+ * Run a link again that is paused with its mirror. The checks of a resume are made again (channels, rights, age
+ * rule, webhooks), and a server that changed hands since keeps the link paused until its new owner confirms.
+ * @returns {Promise<{ resumed: boolean, reason?: string }>}
+ */
+export async function resumeMirrorLink(linkId) {
+ const link = await store.getLink(linkId);
+ if (!link || link.status !== 'paused' || link.failReason !== 'mirror') return { resumed: false };
+ try {
+ await revalidate(link);
+ } catch (err) {
+ if (err instanceof BridgeError) return { resumed: false, reason: err.message };
+ throw err;
+ }
+ const changed = ownerChangedSide(link);
+ if (changed) {
+ await store.setLinkStatus(link.id, { status: 'paused', pausedSide: changed, reason: 'owner-changed' });
+ dropBridgeCache();
+ return { resumed: false, reason: 'owner-changed' };
+ }
+ await store.setLinkStatus(link.id, { status: 'active' });
+ dropBridgeCache();
+ return { resumed: true };
+}
+
+/** The mirror that made a link ended: the link stays, paused, and either server owner can resume or unlink it. */
+export async function releaseMirrorLink(linkId) {
+ const link = await store.getLink(linkId);
+ if (!link) return false;
+ const mine = link.status === 'active' || (link.status === 'paused' && link.failReason === 'mirror');
+ if (!mine) return false;
+ await store.setLinkStatus(link.id, { status: 'paused', pausedSide: '', reason: 'mirror-ended' });
+ dropBridgeCache();
+ queue.clear(laneKey(link, 'a'));
+ queue.clear(laneKey(link, 'b'));
+ return true;
+}
+
/** Unlink: either side may, at any time. The webhooks are deleted and the message map with the link. */
export async function unlinkLink({ guildKey, id, actor }) {
const { link, side } = await ownLink(guildKey, id);
@@ -1368,7 +1591,8 @@ export async function bridgeOverview(key) {
*/
export async function bridgeProblems(key) {
return (await store.linksOfGuild(key))
- .filter((l) => l.status === 'failed' || (l.status === 'paused' && l.failReason))
+ // A link the server mirror holds is covered by the mirror's own Health entry.
+ .filter((l) => l.status === 'failed' || (l.status === 'paused' && l.failReason && l.failReason !== 'mirror'))
.map((l) => {
const side = sideOf(l, key);
return {
diff --git a/test/mirrorBridgeEngine.test.js b/test/mirrorBridgeEngine.test.js
new file mode 100644
index 00000000..bba600a5
--- /dev/null
+++ b/test/mirrorBridgeEngine.test.js
@@ -0,0 +1,310 @@
+// How the mirror engine uses the bridge step and keeps its links in step, and the two small mirror fixes that came
+// with the wiring: a role made again during "copy again" is ordered before it gets its powerful permissions, and a
+// change of Fluxer owner turns "Mirror deletions" off until the new owner switches it on.
+import './helpers/tmpDb.js';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import * as db from '../src/db/mirror.js';
+import { requestMirror } from '../src/mirror/consent.js';
+import { BIT, SYLO_ROLE, dChannel } from './helpers/mirrorFakes.js';
+import { drain, scenario } from './helpers/mirrorScenario.js';
+
+const ADMIN = 1n << 3n;
+const roleBits = (s, id) => BigInt(s.fluxer.guild.roles.get(id)._permissions);
+
+// --- the bridge step ---------------------------------------------------------------------------------------
+
+test('the bridge step is the last step of a copy, and its result shows in the report', async () => {
+ const calls = [];
+ const s = await scenario({
+ withExpressions: false,
+ engineOpts: {
+ linkMirroredChannels: async (id, opts) => {
+ calls.push([id, [...opts.skip]]);
+ return {
+ linked: 3,
+ already: 0,
+ remaining: 0,
+ tried: [],
+ skipped: [
+ { sourceId: '11', name: 'adult', code: 'age-restriction', message: 'the ages do not match' },
+ ],
+ };
+ },
+ },
+ });
+ await s.engine.startCopy(s.pair.id);
+ assert.equal((await drain(s)).status, 'live');
+ assert.deepEqual(calls, [[s.pair.id, []]]);
+ const report = await s.engine.report(await db.getPair(s.pair.id));
+ assert.equal(report.bridge.status, 'done');
+ assert.equal(report.bridge.detail, '3 channels linked, 1 not linked (see the notes)');
+ const note = report.notes.find((n) => n.code === 'bridge-age-restriction');
+ assert.deepEqual(note.ref, { kind: 'channel', id: '11', name: 'adult' });
+ assert.match(note.message, /adult: not linked through the bridge, the ages do not match/);
+});
+
+test('when more channels wait than one run links, another run follows and does not try the same ones again', async () => {
+ const calls = [];
+ const answers = [
+ {
+ linked: 2,
+ already: 1,
+ remaining: 2,
+ tried: ['a', 'b', 'c'],
+ skipped: [{ sourceId: 'c', name: 'c', code: 'permissions', message: 'Sylo lacks a permission' }],
+ },
+ { linked: 2, already: 3, remaining: 0, tried: ['d', 'e'], skipped: [] },
+ ];
+ const s = await scenario({
+ withExpressions: false,
+ engineOpts: {
+ linkMirroredChannels: async (id, opts) => {
+ calls.push([...opts.skip]);
+ return answers[calls.length - 1];
+ },
+ },
+ });
+ await s.engine.startCopy(s.pair.id);
+ assert.equal((await drain(s)).status, 'live', 'the copy waits for the whole bridge step');
+ assert.deepEqual(calls, [[], ['a', 'b', 'c']]);
+ const report = await s.engine.report(await db.getPair(s.pair.id));
+ assert.equal(report.bridge.status, 'done');
+ assert.equal(
+ report.bridge.detail,
+ '2 channels linked, 1 already linked, 1 not linked (see the notes), 2 more follow; 2 channels linked, 3 already linked'
+ );
+});
+
+test('a step that links nothing says why', async () => {
+ const s = await scenario({
+ withExpressions: false,
+ engineOpts: { linkMirroredChannels: async () => ({ linked: 0, reason: 'nothing-to-link' }) },
+ });
+ await s.engine.startCopy(s.pair.id);
+ await drain(s);
+ assert.equal((await s.engine.report(await db.getPair(s.pair.id))).bridge.detail, 'not linked: nothing-to-link');
+});
+
+test('a channel made on Discord later is linked too: the bridge step is asked for again', async () => {
+ const calls = [];
+ const s = await scenario({
+ withExpressions: false,
+ engineOpts: {
+ linkMirroredChannels: async (id) => {
+ calls.push(id);
+ return { linked: 1, already: 0, remaining: 0, tried: [], skipped: [] };
+ },
+ },
+ });
+ await s.engine.startCopy(s.pair.id);
+ await drain(s);
+ assert.equal(calls.length, 1);
+ const newId = '750000000000000077';
+ s.discord.channels.cache.set(newId, dChannel({ id: newId, name: 'fresh', type: 0, rawPosition: 9 }));
+ await s.engine.noteSourceChange(s.k.src, { kind: 'channel', op: 'sync', id: newId });
+ await s.engine.runPair(s.pair.id);
+ assert.equal(calls.length, 2, 'linked after the channel was made');
+ // an edit of an existing channel does not ask again
+ s.discord.channels.cache.get(s.k.chat).name = 'chatter';
+ await s.engine.noteSourceChange(s.k.src, { kind: 'channel', op: 'sync', id: s.k.chat });
+ await s.engine.runPair(s.pair.id);
+ assert.equal(calls.length, 2);
+});
+
+// --- links follow the mirror ---------------------------------------------------------------------------------
+
+test('the links of a mirror follow its state: paused, resumed, stopped and released when removed', async () => {
+ const states = [];
+ const released = [];
+ const s = await scenario({
+ withExpressions: false,
+ engineOpts: {
+ linkMirroredChannels: async () => ({ linked: 0, reason: 'nothing-to-link' }),
+ syncLinks: async (pair) => {
+ states.push(pair.status);
+ },
+ releaseLinks: async (id) => {
+ released.push(id);
+ },
+ },
+ });
+ await s.engine.startCopy(s.pair.id);
+ await drain(s);
+ states.length = 0;
+ await s.engine.pause(s.pair.id, 'source');
+ await s.engine.resume(s.pair.id, { side: 'source' });
+ await s.engine.stopPair(s.pair.id);
+ assert.deepEqual(states, ['paused', 'live', 'stopped']);
+ assert.deepEqual(released, []);
+ await s.engine.removePair(s.pair.id);
+ assert.deepEqual(released, [s.pair.id], 'released before the pair and its record are gone');
+ assert.equal(await db.getPair(s.pair.id), null);
+});
+
+test('a pause the mirror makes itself (a failure) pauses the links too', async () => {
+ const states = [];
+ const s = await scenario({
+ withExpressions: false,
+ engineOpts: {
+ linkMirroredChannels: async () => ({ linked: 0, reason: 'nothing-to-link' }),
+ syncLinks: async (pair) => {
+ states.push(pair.status);
+ },
+ enforceOwnership: () => true,
+ },
+ });
+ await s.engine.startCopy(s.pair.id);
+ s.fluxer.guild.ownerId = 'new-fluxer-owner';
+ await s.engine.runPair(s.pair.id);
+ assert.equal((await db.getPair(s.pair.id)).pauseKind, 'ownership');
+ assert.ok(states.includes('paused'));
+});
+
+test('a link that cannot be put right does not break the mirror; the timer tries again', async () => {
+ let fail = true;
+ let sweeps = 0;
+ const s = await scenario({
+ withExpressions: false,
+ engineOpts: {
+ linkMirroredChannels: async () => ({ linked: 0, reason: 'nothing-to-link' }),
+ syncLinks: async () => {
+ sweeps += 1;
+ if (fail) throw new Error('database is busy');
+ },
+ },
+ });
+ await s.engine.startCopy(s.pair.id);
+ await drain(s);
+ const paused = await s.engine.pause(s.pair.id, 'source');
+ assert.equal(paused.status, 'paused', 'the pause itself went through');
+ const before = sweeps;
+ fail = false;
+ s.clock.now += 120_000;
+ await s.engine.tick();
+ assert.ok(sweeps > before, 'the sweep of the timer ran again');
+});
+
+// --- minor: a role made again in "copy again" ------------------------------------------------------------------
+
+test('a role deleted on Fluxer and made again by "copy again" is ordered, then gets its powerful permissions', async () => {
+ const s = await scenario({ withExpressions: false });
+ s.discord.roles.cache.get(s.k.mod).permissions = { bitfield: BIT.Administrator | BIT.ViewChannel };
+ await s.engine.startCopy(s.pair.id);
+ await drain(s);
+ const first = (await db.getMapping(s.pair.id, 'role', s.k.mod)).targetId;
+ assert.equal(roleBits(s, first) & ADMIN, ADMIN, 'the first copy granted it');
+
+ // Somebody deletes the role on Fluxer, and the role changes on Discord (so the copy sends it again), but the order
+ // of the roles does not change, so the plan has no order step.
+ s.fluxer.guild.roles.delete(first);
+ s.discord.roles.cache.get(s.k.mod).name = 'Moderators';
+ const preview = await s.engine.previewPair(await db.getPair(s.pair.id));
+ assert.equal(preview.steps.find((x) => x.key === 'order-roles:roles').op, 'unchanged');
+ s.fluxer.calls.length = 0;
+ await s.engine.startCopy(s.pair.id);
+ assert.equal((await drain(s)).status, 'live');
+
+ const again = (await db.getMapping(s.pair.id, 'role', s.k.mod)).targetId;
+ assert.notEqual(again, first, 'a new role was made');
+ const calls = s.fluxer.calls;
+ const made = calls.findIndex((c) => c.op === 'createRole');
+ const ordered = calls.findIndex((c) => c.op === 'setRolePositions');
+ const granted = calls.findIndex((c) => c.op === 'editRole' && c.id === again);
+ assert.ok(made >= 0 && made < ordered && ordered < granted, 'made, then ordered, then granted');
+ assert.equal(BigInt(calls[made].spec.permissions) & ADMIN, 0n, 'made without Administrator');
+ assert.equal(roleBits(s, again) & ADMIN, ADMIN, 'and granted at the end');
+ assert.ok((await db.getMapping(s.pair.id, 'role', s.k.mod)).specHash, 'and the fingerprint is final');
+ assert.ok(s.fluxer.guild.roles.get(SYLO_ROLE).position > s.fluxer.guild.roles.get(again).position);
+});
+
+test('a first copy still sets the role order once for all its roles', async () => {
+ const s = await scenario({ withExpressions: false });
+ s.discord.roles.cache.get(s.k.mod).permissions = { bitfield: BIT.Administrator };
+ await s.engine.startCopy(s.pair.id);
+ await drain(s);
+ assert.equal(s.fluxer.ops('setRolePositions').length, 1);
+ assert.equal(roleBits(s, (await db.getMapping(s.pair.id, 'role', s.k.mod)).targetId) & ADMIN, ADMIN);
+});
+
+// --- minor: a new Fluxer owner starts with "Mirror deletions" off ------------------------------------------------
+
+test('a change of Fluxer owner turns "Mirror deletions" off until the new owner switches it on', async () => {
+ const s = await scenario({
+ withExpressions: false,
+ options: { mirrorDeletes: true },
+ engineOpts: { enforceOwnership: () => true },
+ });
+ assert.deepEqual(
+ [s.pair.options.mirrorDeletes, s.pair.options.mirrorDeletesRequested],
+ [true, true],
+ 'the owner of both servers had it on'
+ );
+ await s.engine.startCopy(s.pair.id);
+ await s.engine.runPair(s.pair.id, { maxJobs: 2 });
+ s.fluxer.guild.ownerId = 'new-fluxer-owner';
+ await s.engine.runPair(s.pair.id);
+ assert.equal((await db.getPair(s.pair.id)).pauseKind, 'ownership');
+ assert.equal((await db.getPair(s.pair.id)).options.mirrorDeletes, true, 'still on until somebody confirms');
+
+ // The Discord owner confirming does not change who the Fluxer owner is.
+ await s.engine.resume(s.pair.id, { side: 'source' });
+ assert.equal((await db.getPair(s.pair.id)).options.mirrorDeletes, true);
+
+ const pair = await s.engine.resume(s.pair.id, { side: 'target' });
+ assert.equal(pair.status, 'copying');
+ assert.equal(pair.targetConsentUser, 'new-fluxer-owner');
+ assert.deepEqual(
+ [pair.options.mirrorDeletes, pair.options.mirrorDeletesRequested],
+ [false, true],
+ 'off for the new owner, with the request still there for them to answer'
+ );
+ await drain(s);
+ // A delete on Discord now only locks the Fluxer copy.
+ s.discord.channels.cache.delete(s.k.chat);
+ await s.engine.noteSourceChange(s.k.src, { kind: 'channel', op: 'delete', id: s.k.chat });
+ await s.engine.runPair(s.pair.id);
+ assert.equal(s.fluxer.ops('deleteChannel').length, 0, 'nothing is deleted on Fluxer');
+ assert.ok((await db.getMapping(s.pair.id, 'channel', s.k.chat)).removedAt > 0);
+});
+
+test('a new request keeps real deletion only for the same Fluxer owner who owns both servers', async () => {
+ const D1 = '921000000000000001';
+ const F1 = 'fluxer:821000000000000001';
+ const ask = (over) =>
+ requestMirror({
+ sourceGuild: D1,
+ targetGuild: F1,
+ actor: 'Anna',
+ sourceUser: 'dc-owner',
+ targetUser: 'fx-owner',
+ targetOwner: true,
+ ...over,
+ });
+ const first = await ask({ options: { mirrorDeletes: true } });
+ assert.equal(first.pair.options.mirrorDeletes, true);
+
+ const same = await ask({});
+ assert.deepEqual(
+ [same.pair.options.mirrorDeletes, same.pair.options.mirrorDeletesRequested],
+ [true, true],
+ 'the same owner of both servers asking again keeps it'
+ );
+ const newOwner = await ask({ targetUser: 'fx-new-owner' });
+ assert.deepEqual(
+ [newOwner.pair.options.mirrorDeletes, newOwner.pair.options.mirrorDeletesRequested],
+ [false, true],
+ 'a new Fluxer owner starts with it off'
+ );
+ await ask({ targetUser: 'fx-owner', options: { mirrorDeletes: true } });
+ const stranger = await ask({ targetOwner: false });
+ assert.deepEqual(
+ [stranger.pair.options.mirrorDeletes, stranger.pair.options.mirrorDeletesRequested],
+ [false, true],
+ 'a request from someone who is not the Fluxer owner never carries it'
+ );
+ // The request brings its own options: the existing rules for them apply (asked, not on).
+ const explicit = await ask({ targetOwner: false, options: { mirrorDeletes: true } });
+ assert.deepEqual([explicit.pair.options.mirrorDeletes, explicit.pair.options.mirrorDeletesRequested], [false, true]);
+ await db.deletePair(explicit.pair.id);
+});
diff --git a/test/mirrorBridgeLink.test.js b/test/mirrorBridgeLink.test.js
new file mode 100644
index 00000000..fd854393
--- /dev/null
+++ b/test/mirrorBridgeLink.test.js
@@ -0,0 +1,503 @@
+// A mirror links its channels through the bridge (src/mirror/bridgeLink.js, createMirrorLink and the held-link helpers in
+// src/modules/bridge.js): which channels, what is recorded, every safety rule of the bridge, running it again, and
+// links that follow the state of their mirror. Platforms and webhooks are the bridge tests' fakes.
+import './helpers/tmpDb.js';
+import test, { afterEach, beforeEach } from 'node:test';
+import assert from 'node:assert/strict';
+import { ChannelType } from 'discord.js';
+import * as mdb from '../src/db/mirror.js';
+import * as bridgeDb from '../src/db/bridge.js';
+import { listAudit } from '../src/db/audit.js';
+import { getGuildModule, setGuildModule } from '../src/db/modules.js';
+import { purgeGuild } from '../src/db/purge.js';
+import { requestMirror } from '../src/mirror/consent.js';
+import {
+ LINKS_PER_RUN,
+ linkMirroredChannels,
+ releaseMirrorLinks,
+ syncMirrorLinks,
+} from '../src/mirror/bridgeLink.js';
+import {
+ BridgeError,
+ MAX_MIRROR_LINKS,
+ bridgeIdle,
+ bridgeProblems,
+ dropBridgeCache,
+ handleMessage,
+ linkView,
+ resumeLink,
+ unlinkLink,
+ useBridgeParts,
+} from '../src/modules/bridge.js';
+import {
+ D,
+ F,
+ installPlatforms,
+ message,
+ removePlatforms,
+ useFakes,
+} from './helpers/fakeBridge.js';
+
+let p;
+let fakes;
+const noSleep = async () => {};
+
+beforeEach(async () => {
+ p = installPlatforms();
+ useFakes();
+ dropBridgeCache();
+ for (const key of [D, F]) await purgeGuild(key);
+ fakes = useFakes();
+ await setGuildModule(D, 'bridge', { enabled: false });
+ await setGuildModule(F, 'bridge', { enabled: false });
+});
+afterEach(() => {
+ useBridgeParts();
+ removePlatforms();
+});
+
+/** A live mirror of the Discord server onto the Fluxer server, agreed by both owners. */
+async function livePair(over = {}) {
+ const { pair } = await requestMirror({
+ sourceGuild: D,
+ targetGuild: F,
+ actor: 'Anna',
+ sourceUser: p.dGuild.ownerId,
+ targetUser: p.fGuild.ownerId,
+ targetOwner: true,
+ ...over,
+ });
+ return mdb.updatePair(pair.id, { status: 'live', targetConsentBy: 'Bo' });
+}
+/** A Discord channel and its Fluxer copy, in the pair's channel map. */
+async function mirrored(pair, name, { type = ChannelType.GuildText, dOpts = {}, fOpts = {} } = {}) {
+ const d = p.channel(p.dGuild, { name, type, ...dOpts });
+ const f = p.channel(p.fGuild, { name, type, ...fOpts });
+ await mdb.putMapping({
+ pairId: pair.id,
+ kind: 'channel',
+ sourceId: d.id,
+ targetId: f.id,
+ owned: true,
+ specHash: 'h',
+ label: name,
+ });
+ return { d, f };
+}
+const run = (pair, opts = {}) => linkMirroredChannels(pair.id, { sleep: noSleep, ...opts });
+const send = async (channel, key, over = {}) => {
+ await handleMessage(
+ message({ channelId: channel.id, client: key === D ? p.discord : p.fluxer, ...over }),
+ {},
+ key
+ );
+ await bridgeIdle();
+};
+
+test('every mirrored text channel pair is linked, voice channels and categories are left alone', async () => {
+ const pair = await livePair();
+ const chat = await mirrored(pair, 'chat');
+ const news = await mirrored(pair, 'news', { type: ChannelType.GuildAnnouncement });
+ await mirrored(pair, 'lounge', { type: ChannelType.GuildVoice });
+ await mirrored(pair, 'Info', { type: ChannelType.GuildCategory });
+
+ const res = await run(pair);
+ assert.deepEqual([res.linked, res.already, res.remaining, res.skipped.length], [2, 0, 0, 0]);
+ for (const { d, f } of [chat, news]) {
+ const found = await bridgeDb.linkForChannel(D, d.id);
+ assert.ok(found, 'the Discord channel is linked');
+ assert.deepEqual(
+ [found.link.guildA, found.link.channelA, found.link.guildB, found.link.channelB, found.link.status],
+ [D, d.id, F, f.id, 'active']
+ );
+ assert.equal((await mdb.getMirrorLink(pair.id, d.id)).linkId, found.link.id);
+ }
+ assert.equal((await bridgeDb.linkCount(D)), 2);
+ assert.equal(fakes.transport.hooks.length, 4, 'a webhook in each of the four channels, none for voice');
+});
+
+test('no link code is used: the link records the two owners who agreed to the mirror and their ids', async () => {
+ const pair = await livePair();
+ const { d, f } = await mirrored(pair, 'chat');
+ await run(pair);
+ const link = (await bridgeDb.linkForChannel(D, d.id)).link;
+ assert.equal(link.requestedBy, 'Anna (server mirror)');
+ assert.equal(link.acceptedBy, 'Bo (server mirror)');
+ assert.deepEqual([link.ownerA, link.ownerB], [p.dGuild.ownerId, p.fGuild.ownerId]);
+ assert.equal((await bridgeDb.pendingCodes(D)).length, 0, 'no request or code was made');
+ assert.deepEqual([link.optionsA.bots, link.optionsB.bots], [false, false], 'bots are off on both sides');
+ // the owners' own side of it, as the dashboard of each server shows it
+ assert.equal(linkView(link, D).by, 'Anna (server mirror)');
+ assert.equal(linkView(link, F).by, 'Bo (server mirror)');
+ // visible notice in both channels, naming the mirror
+ for (const channel of [d, f]) {
+ assert.equal(channel.said.length, 1);
+ assert.match(channel.said[0].content, /Bridge on/);
+ assert.match(channel.said[0].content, /server mirror/);
+ assert.deepEqual(channel.said[0].allowedMentions, { parse: [] });
+ }
+ for (const key of [D, F]) {
+ const entry = (await listAudit(key)).find((e) => e.action === 'bridge:link');
+ assert.ok(entry, 'both servers record it');
+ assert.match(entry.detail, /through the server mirror/);
+ }
+});
+
+test('the Bridge module is switched on in both servers, and both audit logs say so', async () => {
+ const pair = await livePair();
+ await mirrored(pair, 'chat');
+ assert.equal((await getGuildModule(D, 'bridge')).enabled, false);
+ await run(pair);
+ for (const key of [D, F]) {
+ assert.equal((await getGuildModule(key, 'bridge')).enabled, true);
+ assert.ok((await listAudit(key)).some((e) => e.action === 'bridge:module'));
+ }
+});
+
+test('a linked pair relays messages both ways, with nobody pinged', async () => {
+ const pair = await livePair();
+ const { d, f } = await mirrored(pair, 'chat');
+ await run(pair);
+ await send(d, D, { content: 'hello from Discord @everyone' });
+ await send(f, F, { content: 'hello from Fluxer' });
+ assert.equal(fakes.transport.sends.length, 2);
+ assert.equal(fakes.transport.sends[0].guildKey, F);
+ assert.deepEqual(fakes.transport.sends[0].payload.allowedMentions ?? { parse: [] }, { parse: [] });
+ assert.equal(fakes.transport.sends[1].guildKey, D);
+ // a bot's message stays on its side (bots are off)
+ await send(d, D, { content: 'beep', author: { bot: true } });
+ assert.equal(fakes.transport.sends.length, 2);
+});
+
+test('running it again links only what is missing', async () => {
+ const pair = await livePair();
+ await mirrored(pair, 'chat');
+ await mirrored(pair, 'rules');
+ assert.equal((await run(pair)).linked, 2);
+ const again = await run(pair);
+ assert.deepEqual([again.linked, again.already, again.reason], [0, 2, undefined]);
+ assert.equal(fakes.transport.hooks.length, 4, 'nothing was made twice');
+
+ await mirrored(pair, 'offers');
+ const third = await run(pair);
+ assert.deepEqual([third.linked, third.already], [1, 2], 'only the new pair is linked');
+ assert.equal(fakes.transport.hooks.length, 6);
+ assert.equal((await mdb.listMirrorLinks(pair.id)).length, 3);
+});
+
+test('a pair that has nothing to link says so', async () => {
+ const pair = await livePair();
+ await mirrored(pair, 'lounge', { type: ChannelType.GuildVoice });
+ assert.equal((await run(pair)).reason, 'nothing-to-link');
+ assert.equal((await getGuildModule(D, 'bridge')).enabled, false, 'and the module is left alone');
+});
+
+test('a channel somebody unlinked on purpose is not linked again', async () => {
+ const pair = await livePair();
+ const { d } = await mirrored(pair, 'chat');
+ await mirrored(pair, 'rules');
+ await run(pair);
+ const link = (await bridgeDb.linkForChannel(D, d.id)).link;
+ await unlinkLink({ guildKey: D, id: link.id, actor: 'Anna' });
+ assert.equal(await bridgeDb.linkForChannel(D, d.id), null);
+ const again = await run(pair);
+ assert.deepEqual([again.linked, again.already], [0, 2]);
+ assert.equal(await bridgeDb.linkForChannel(D, d.id), null, 'it stays unlinked');
+});
+
+test('the age rule: an age-restricted channel is linked only to an age-restricted one', async () => {
+ const pair = await livePair();
+ const plain = await mirrored(pair, 'chat');
+ const mismatch = await mirrored(pair, 'adult', { dOpts: { nsfw: true } });
+ const both = await mirrored(pair, 'adult-too', { dOpts: { nsfw: true }, fOpts: { nsfw: true } });
+ const res = await run(pair);
+ assert.equal(res.linked, 2);
+ assert.deepEqual(
+ res.skipped.map((s) => [s.sourceId, s.code]),
+ [[mismatch.d.id, 'age-restriction']]
+ );
+ assert.ok(await bridgeDb.linkForChannel(D, plain.d.id));
+ assert.ok(await bridgeDb.linkForChannel(D, both.d.id));
+ assert.equal(await bridgeDb.linkForChannel(D, mismatch.d.id), null);
+ assert.equal(mismatch.d.said.length + mismatch.f.said.length, 0, 'no notice, no webhook');
+});
+
+test('a private channel is not linked to an open one, and two private channels are linked', async () => {
+ const pair = await livePair();
+ const closed = (guild) => (target) => ({
+ has: (perm) => !(perm === 'ViewChannel' && target === String(guild.id)),
+ });
+ const leak = await mirrored(pair, 'staff');
+ leak.d.permissionsFor = closed(p.dGuild); // private on Discord, open on Fluxer
+ const pulled = await mirrored(pair, 'staff-too');
+ pulled.f.permissionsFor = closed(p.fGuild); // open on Discord, private on Fluxer
+ const same = await mirrored(pair, 'mods');
+ same.d.permissionsFor = closed(p.dGuild);
+ same.f.permissionsFor = closed(p.fGuild);
+ const res = await run(pair);
+ assert.equal(res.linked, 1);
+ assert.deepEqual(
+ res.skipped.map((s) => s.code),
+ ['visibility', 'visibility']
+ );
+ assert.ok(await bridgeDb.linkForChannel(D, same.d.id));
+ assert.equal(await bridgeDb.linkForChannel(D, leak.d.id), null);
+ assert.equal(await bridgeDb.linkForChannel(D, pulled.d.id), null);
+});
+
+test('with sign-in on, each owner must be able to see, read and send in the channel themselves', async () => {
+ const pair = await livePair();
+ const ok = await mirrored(pair, 'chat');
+ const hidden = await mirrored(pair, 'hidden');
+ const owner = { id: p.dGuild.ownerId };
+ p.dGuild.members.cache.set(owner.id, owner);
+ const fluxerOwner = { id: p.fGuild.ownerId };
+ p.fGuild.members.cache.set(fluxerOwner.id, fluxerOwner);
+ // the Fluxer owner cannot read the history of one channel
+ const real = hidden.f.permissionsFor;
+ hidden.f.permissionsFor = (t) =>
+ t?.id === fluxerOwner.id
+ ? { has: (perm) => perm !== 'ReadMessageHistory' }
+ : real(t);
+ const res = await run(pair, { open: false });
+ assert.equal(res.linked, 1);
+ assert.deepEqual(
+ res.skipped.map((s) => [s.sourceId, s.code]),
+ [[hidden.d.id, 'visibility']]
+ );
+ assert.ok(await bridgeDb.linkForChannel(D, ok.d.id));
+});
+
+test('with sign-in on, an owner who cannot be found fails closed: nothing is linked', async () => {
+ const pair = await livePair();
+ await mirrored(pair, 'chat');
+ const res = await run(pair, { open: false });
+ assert.equal(res.linked, 0);
+ assert.deepEqual(
+ res.skipped.map((s) => s.code),
+ ['visibility']
+ );
+});
+
+test('Sylo missing a permission in one channel skips only that pair', async () => {
+ const pair = await livePair();
+ const fine = await mirrored(pair, 'chat');
+ const broken = await mirrored(pair, 'locked');
+ broken.f.permissionsFor = () => ({ has: (perm) => perm !== 'ManageWebhooks' });
+ const res = await run(pair);
+ assert.equal(res.linked, 1);
+ assert.deepEqual(
+ res.skipped.map((s) => [s.sourceId, s.code]),
+ [[broken.d.id, 'permissions']]
+ );
+ assert.ok(await bridgeDb.linkForChannel(D, fine.d.id));
+});
+
+test('a channel already bridged by hand to another channel is left as it is; the pair itself is taken over', async () => {
+ const pair = await livePair();
+ const other = await mirrored(pair, 'other');
+ const lost = await mirrored(pair, 'lost');
+ // somebody linked "other" to an unrelated Fluxer channel through the bridge page
+ const stray = p.channel(p.fGuild, { name: 'stray' });
+ await bridgeDb.createLink({
+ guildA: D,
+ channelA: other.d.id,
+ guildB: F,
+ channelB: stray.id,
+ hookA: { id: '1', token: 'a' },
+ hookB: { id: '2', token: 'b' },
+ });
+ // and a link of exactly the pair "lost" exists whose record was never written
+ const made = await bridgeDb.createLink({
+ guildA: D,
+ channelA: lost.d.id,
+ guildB: F,
+ channelB: lost.f.id,
+ hookA: { id: '3', token: 'c' },
+ hookB: { id: '4', token: 'd' },
+ });
+ const res = await run(pair);
+ assert.deepEqual([res.linked, res.already], [0, 1]);
+ assert.deepEqual(
+ res.skipped.map((s) => [s.sourceId, s.code]),
+ [[other.d.id, 'exists']]
+ );
+ assert.equal((await mdb.getMirrorLink(pair.id, lost.d.id)).linkId, made, 'taken over');
+ assert.equal(fakes.transport.hooks.length, 0, 'no new webhook');
+});
+
+test('a batch links at most the limit, and the next run carries on without trying the same pairs again', async () => {
+ assert.ok(LINKS_PER_RUN >= 10);
+ const pair = await livePair();
+ for (let i = 0; i < 5; i += 1) await mirrored(pair, `c${i}`);
+ const bad = await mirrored(pair, 'adult', { dOpts: { nsfw: true } }); // the sixth is refused
+ const first = await run(pair, { limit: 3 });
+ assert.deepEqual([first.linked, first.remaining, first.tried.length], [3, 3, 3]);
+ const second = await run(pair, { limit: 3, skip: new Set(first.tried) });
+ assert.deepEqual([second.linked, second.remaining], [2, 0]);
+ assert.deepEqual(
+ second.skipped.map((s) => s.sourceId),
+ [bad.d.id]
+ );
+ // a third run that skips what was tried has nothing left
+ const third = await run(pair, { limit: 3, skip: new Set([...first.tried, ...second.tried]) });
+ assert.deepEqual([third.linked, third.remaining, third.skipped.length], [0, 0, 0]);
+});
+
+test('the ceiling of links per server is respected and reported', async () => {
+ const pair = await livePair();
+ const one = await mirrored(pair, 'chat');
+ for (let i = 0; i < MAX_MIRROR_LINKS; i += 1) {
+ await bridgeDb.createLink({
+ guildA: D,
+ channelA: `filler-${i}`,
+ guildB: F,
+ channelB: `filler-f-${i}`,
+ hookA: { id: `a${i}`, token: 'a' },
+ hookB: { id: `b${i}`, token: 'b' },
+ });
+ }
+ const res = await run(pair);
+ assert.equal(res.linked, 0);
+ assert.deepEqual(
+ res.skipped.map((s) => [s.sourceId, s.code]),
+ [[one.d.id, 'limit']]
+ );
+});
+
+test('a webhook that cannot be made skips the pair and leaves nothing half made', async () => {
+ const pair = await livePair();
+ const a = await mirrored(pair, 'chat');
+ fakes.transport.hookFailures.push(new Error('boom'), new Error('boom'));
+ const res = await run(pair);
+ assert.equal(res.linked, 0);
+ assert.deepEqual(
+ res.skipped.map((s) => s.code),
+ ['webhook']
+ );
+ assert.equal(await bridgeDb.linkForChannel(D, a.d.id), null);
+ assert.equal(await mdb.getMirrorLink(pair.id, a.d.id), null, 'so a later run tries it again');
+ const later = await run(pair);
+ assert.equal(later.linked, 1);
+});
+
+test('when the clients are not both connected, nothing is linked and the reason says so', async () => {
+ const pair = await livePair();
+ await mirrored(pair, 'chat');
+ p.fluxer.user = p.fluxer.user; // still there
+ removePlatforms();
+ assert.equal((await run(pair)).reason, 'bridge-not-available');
+ assert.equal((await linkMirroredChannels(999_999, { sleep: noSleep })).reason, 'no-such-mirror');
+});
+
+test('a mirror that is not running links nothing', async () => {
+ const pair = await livePair();
+ await mirrored(pair, 'chat');
+ await mdb.updatePair(pair.id, { status: 'paused' });
+ assert.equal((await run(pair)).reason, 'mirror-not-running');
+});
+
+// --- links follow the state of their mirror ---------------------------------------------------------------
+
+test('a paused mirror pauses its links, nothing crosses, and they run again with the mirror', async () => {
+ const pair = await livePair();
+ const { d, f } = await mirrored(pair, 'chat');
+ await run(pair);
+ await send(d, D, { content: 'one' });
+ assert.equal(fakes.transport.sends.length, 1);
+
+ await mdb.updatePair(pair.id, { status: 'paused' });
+ assert.deepEqual(await syncMirrorLinks(pair.id), { held: 1, resumed: 0, waiting: [] });
+ const held = (await bridgeDb.linkForChannel(D, d.id)).link;
+ assert.deepEqual([held.status, held.failReason], ['paused', 'mirror']);
+ await send(d, D, { content: 'two' });
+ await send(f, F, { content: 'three' });
+ assert.equal(fakes.transport.sends.length, 1, 'nothing crosses while the mirror is paused');
+ assert.deepEqual(await bridgeProblems(D), [], 'the mirror has its own Health entry');
+ assert.match(linkView(held, D).pauseNote, /server mirror/);
+
+ // the bridge page cannot resume it on its own
+ await assert.rejects(
+ resumeLink({ guildKey: D, id: held.id, actor: 'Anna' }),
+ (err) => err instanceof BridgeError && err.status === 409 && /mirror/.test(err.message)
+ );
+
+ await mdb.updatePair(pair.id, { status: 'live' });
+ assert.deepEqual(await syncMirrorLinks(pair.id), { held: 0, resumed: 1, waiting: [] });
+ assert.equal((await bridgeDb.getLink(held.id)).status, 'active');
+ await send(d, D, { content: 'four' });
+ assert.equal(fakes.transport.sends.length, 2, 'and it carries messages again');
+});
+
+test('a stopped mirror pauses its links too, and only the ones the mirror paused come back', async () => {
+ const pair = await livePair();
+ const a = await mirrored(pair, 'chat');
+ const b = await mirrored(pair, 'rules');
+ await run(pair);
+ const own = (await bridgeDb.linkForChannel(D, b.d.id)).link;
+ await bridgeDb.setLinkStatus(own.id, { status: 'paused', pausedSide: 'b' }); // the Fluxer server paused this one
+ await mdb.updatePair(pair.id, { status: 'stopped' });
+ assert.equal((await syncMirrorLinks(pair.id)).held, 1);
+ await mdb.updatePair(pair.id, { status: 'live' });
+ assert.equal((await syncMirrorLinks(pair.id)).resumed, 1);
+ assert.equal((await bridgeDb.linkForChannel(D, a.d.id)).link.status, 'active');
+ const still = (await bridgeDb.linkForChannel(D, b.d.id)).link;
+ assert.deepEqual([still.status, still.pausedSide], ['paused', 'b'], "a server's own pause is left alone");
+});
+
+test('a server that changed hands while the mirror was paused keeps the link paused until its new owner confirms', async () => {
+ const pair = await livePair();
+ const { d } = await mirrored(pair, 'chat');
+ await run(pair);
+ await mdb.updatePair(pair.id, { status: 'paused' });
+ await syncMirrorLinks(pair.id);
+ p.fGuild.ownerId = 'new-owner';
+ await mdb.updatePair(pair.id, { status: 'live' });
+ const res = await syncMirrorLinks(pair.id);
+ assert.deepEqual([res.resumed, res.waiting], [0, ['owner-changed']]);
+ const link = (await bridgeDb.linkForChannel(D, d.id)).link;
+ assert.deepEqual([link.status, link.pausedSide, link.failReason], ['paused', 'b', 'owner-changed']);
+});
+
+test('a link whose channel can no longer be used stays paused with the mirror and is reported', async () => {
+ const pair = await livePair();
+ const { d, f } = await mirrored(pair, 'chat');
+ await run(pair);
+ await mdb.updatePair(pair.id, { status: 'paused' });
+ await syncMirrorLinks(pair.id);
+ f.permissionsFor = () => ({ has: (perm) => perm !== 'ManageWebhooks' });
+ await mdb.updatePair(pair.id, { status: 'live' });
+ const res = await syncMirrorLinks(pair.id);
+ assert.equal(res.resumed, 0);
+ assert.match(res.waiting[0], /ManageWebhooks/);
+ assert.equal((await bridgeDb.linkForChannel(D, d.id)).link.failReason, 'mirror');
+});
+
+test('removing a mirror releases its links: they stay, paused, and either owner can resume or unlink them', async () => {
+ const pair = await livePair();
+ const { d } = await mirrored(pair, 'chat');
+ await run(pair);
+ assert.equal(await releaseMirrorLinks(pair.id), 1);
+ const link = (await bridgeDb.linkForChannel(D, d.id)).link;
+ assert.deepEqual([link.status, link.pausedSide, link.failReason], ['paused', '', 'mirror-ended']);
+ assert.match(linkView(link, F).pauseNote, /mirror that made this bridge ended/);
+ await mdb.deletePair(pair.id);
+ assert.equal((await mdb.listMirrorLinks(pair.id)).length, 0, 'the record goes with the pair');
+ // the Fluxer owner resumes it on the Bridge page
+ await resumeLink({ guildKey: F, id: link.id, actor: 'Bo' });
+ assert.equal((await bridgeDb.getLink(link.id)).status, 'active');
+ // a second release does nothing to a link that is no longer the mirror's to hold
+ assert.equal(await releaseMirrorLinks(pair.id), 0);
+});
+
+test('a link the mirror made can be unlinked by either owner, and leaving the server purges it with the pair', async () => {
+ const pair = await livePair();
+ const { d } = await mirrored(pair, 'chat');
+ await run(pair);
+ const link = (await bridgeDb.linkForChannel(D, d.id)).link;
+ await unlinkLink({ guildKey: F, id: link.id, actor: 'Bo' });
+ assert.equal(await bridgeDb.getLink(link.id), null);
+ await purgeGuild(F);
+ assert.equal(await mdb.getPair(pair.id), null);
+ assert.equal((await mdb.listMirrorLinks(pair.id)).length, 0);
+});
diff --git a/test/mirrorEngine.test.js b/test/mirrorEngine.test.js
index 945038fd..44f18b30 100644
--- a/test/mirrorEngine.test.js
+++ b/test/mirrorEngine.test.js
@@ -166,8 +166,8 @@ test('a copy sends what the server has: ids remapped, @everyone adopted, setting
assert.equal(s.fluxer.ops('setChannelPositions').length, 1);
});
-test('the last step, linking through the bridge, reports that the bridge is not there yet', async () => {
- assert.deepEqual(await linkMirroredChannels(1), { linked: 0, reason: 'bridge-not-available' });
+test('the last step, linking through the bridge, says why it linked nothing when the platforms are not both up', async () => {
+ assert.equal((await linkMirroredChannels(999_999)).reason, 'no-such-mirror');
const s = await scenario({ withExpressions: false });
await s.engine.startCopy(s.pair.id);
const end = await drain(s);
From 7e7748ef284d534cd160307bcb5ce26edaeedb3c Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Tue, 17 Nov 2026 01:09:55 +0100
Subject: [PATCH 09/17] test(mirror): one webhook failure
---
test/mirrorBridgeLink.test.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/test/mirrorBridgeLink.test.js b/test/mirrorBridgeLink.test.js
index fd854393..787e23d7 100644
--- a/test/mirrorBridgeLink.test.js
+++ b/test/mirrorBridgeLink.test.js
@@ -368,7 +368,7 @@ test('the ceiling of links per server is respected and reported', async () => {
test('a webhook that cannot be made skips the pair and leaves nothing half made', async () => {
const pair = await livePair();
const a = await mirrored(pair, 'chat');
- fakes.transport.hookFailures.push(new Error('boom'), new Error('boom'));
+ fakes.transport.hookFailures.push(new Error('boom'));
const res = await run(pair);
assert.equal(res.linked, 0);
assert.deepEqual(
From a2faa16cf56606d0060fcd178434d64dc873a5c9 Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Tue, 17 Nov 2026 01:11:00 +0100
Subject: [PATCH 10/17] feat(mirror): mirror links in the docs and the report
---
docs/mirror.md | 27 ++++++++++++++++++++++++---
docs/modules/bridge.md | 7 +++++++
test/mirror.db.test.js | 24 +++++++++++++++++++++++-
test/mirror.postgres.test.js | 20 ++++++++++++++++++++
web-v2/src/pages/Mirror.jsx | 5 ++++-
5 files changed, 78 insertions(+), 5 deletions(-)
diff --git a/docs/mirror.md b/docs/mirror.md
index 096fb80d..3191e5b8 100644
--- a/docs/mirror.md
+++ b/docs/mirror.md
@@ -52,9 +52,30 @@ the new owner has confirmed it on that server's page.
5. **Report.** Every step and what became of it, the items that failed, and the list of what could not be
carried over.
-The last step of a copy is linking every copied channel through the bridge, so a message written on one side
-shows up on the other. Until the bridge module is installed that step reports "not available yet" and the copy
-still finishes.
+## Linking the channels through the bridge
+
+The last step of a copy links every copied text and announcement channel through the [Bridge](modules/bridge.md),
+so a message written on one side shows up on the other. Voice channels, categories and forums are not linked.
+
+- **Both owners already agreed.** The mirror is the consent: no link code is used. Each link records the two
+ people who agreed to the mirror (shown as "Name (server mirror)" on the Bridge page and in both audit logs), and
+ both channels get the usual notice, which says the link was made by the server mirror.
+- **The Bridge module is switched on in both servers** if it was off (it has to be on for a link to carry
+ anything). Both audit logs say so. You can switch it off again; the links then carry nothing.
+- **Every rule of the bridge holds.** An age-restricted channel is linked only to an age-restricted channel; a
+ private channel only to a private one (a channel everyone can read is never linked to one that only some can);
+ each owner must be able to see, read and send in the channel, and Sylo needs Manage Webhooks, View Channel and
+ Send Messages in both; bots are off; nobody is pinged across. A pair that fails a rule is skipped, the reason
+ is in the report ("Linking channels through the bridge" and the notes), and the rest are linked.
+- **Safe to run again.** "Copy again" links only the pairs that have no link yet. A channel that an owner
+ unlinked on the Bridge page stays unlinked. A server can have at most 50 bridged channels this way (10 when
+ linking by hand), and a copy links 25 channels at a time. A channel made on Discord later (continuous mirroring)
+ is linked too.
+- **The links follow the mirror.** While the mirror is paused (by an owner, by Sylo after a failure, or because a
+ server changed owner) or stopped, its links are paused, with no notice in each channel, and they run again when
+ the mirror does. If a server changed owner, its link stays paused until the new owner confirms it on the Bridge
+ page. **Removing** a mirror pauses its links and leaves them: either owner can resume or unlink each one on the
+ Bridge page.
## What is copied
diff --git a/docs/modules/bridge.md b/docs/modules/bridge.md
index eef40076..37d03ab7 100644
--- a/docs/modules/bridge.md
+++ b/docs/modules/bridge.md
@@ -44,6 +44,13 @@ servers. Wrong codes are rate limited, and a few wrong ones in a row lock the at
both channels are told. If Sylo is removed from a server, the server on the other end loses its webhook and
is told too.
+**Links made by the server mirror.** A [server mirror](../mirror.md) links its copied text channels through the
+bridge without codes, because both owners already agreed to the mirror. Those links show "Name (server mirror)"
+as who made them, follow the mirror (paused with it, running again with it; the Bridge page cannot resume one on
+its own while the mirror is paused) and follow every rule on this page. A server can have 50 of them (10 when you
+link by hand). Unlink works for them as for any other link, and an unlinked channel is not linked again. If the
+mirror is removed, its links stay, paused, and either owner can resume or unlink them.
+
**Pause** stops the bridge from either side. Only the server that paused it can resume it. A link that Sylo
stopped itself (see below) can be resumed by either server once the cause is fixed.
diff --git a/test/mirror.db.test.js b/test/mirror.db.test.js
index 32356d64..3e3e2edf 100644
--- a/test/mirror.db.test.js
+++ b/test/mirror.db.test.js
@@ -249,5 +249,27 @@ test('the SQLite migration can run twice without failing (IF NOT EXISTS)', () =>
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'mirror_%' ORDER BY name")
.all()
.map((r) => r.name);
- assert.deepEqual(tables, ['mirror_ids', 'mirror_jobs', 'mirror_pairs']);
+ assert.deepEqual(tables, ['mirror_ids', 'mirror_jobs', 'mirror_links', 'mirror_pairs']);
+});
+
+test('the bridge links of a pair: one per Discord channel, found again by link, gone with the pair', async () => {
+ const pair = await db.createPair({ sourceGuild: C, targetGuild: D, now: 1000 });
+ await db.putMirrorLink(pair.id, 'c1', 't1', 11, 2000);
+ await db.putMirrorLink(pair.id, 'c2', 't2', 12, 2100);
+ await db.putMirrorLink(pair.id, 'c1', 'other', 99, 2200); // the first record of a channel stays
+ const links = await db.listMirrorLinks(pair.id);
+ assert.deepEqual(
+ links.map((l) => [l.sourceChannel, l.targetChannel, l.linkId, l.createdAt]),
+ [
+ ['c1', 't1', 11, 2000],
+ ['c2', 't2', 12, 2100],
+ ]
+ );
+ assert.equal((await db.getMirrorLink(pair.id, 'c2')).linkId, 12);
+ assert.equal(await db.getMirrorLink(pair.id, 'nope'), null);
+ assert.equal(await db.mirrorPairOfLink(12), pair.id);
+ assert.equal(await db.mirrorPairOfLink(404), null, 'a link made by hand belongs to no mirror');
+ await db.deletePair(pair.id);
+ assert.deepEqual(await db.listMirrorLinks(pair.id), []);
+ assert.equal(await db.mirrorPairOfLink(12), null);
});
diff --git a/test/mirror.postgres.test.js b/test/mirror.postgres.test.js
index 6dd03b46..aeaf3a78 100644
--- a/test/mirror.postgres.test.js
+++ b/test/mirror.postgres.test.js
@@ -142,6 +142,26 @@ test(
assert.deepEqual([next.pauseKind, next.pausedBy, next.sourceConsentUser], ['deletes', 'system', 'u1']);
});
+ await t.test('the bridge links of a pair are kept once per channel and go with the pair', async () => {
+ const pair = await db.createPair({ sourceGuild: C, targetGuild: `${B}5`, now: 1_800_000_000_000 });
+ await db.putMirrorLink(pair.id, 'c1', 't1', 11, 1_800_000_000_100);
+ await db.putMirrorLink(pair.id, 'c1', 'x', 12);
+ await db.putMirrorLink(pair.id, 'c2', 't2', 13);
+ const links = await db.listMirrorLinks(pair.id);
+ assert.deepEqual(
+ links.map((l) => [l.sourceChannel, l.targetChannel, l.linkId]),
+ [
+ ['c1', 't1', 11],
+ ['c2', 't2', 13],
+ ]
+ );
+ assert.equal(typeof links[0].createdAt, 'number');
+ assert.equal(await db.mirrorPairOfLink(13), pair.id);
+ await assert.rejects(db.putMirrorLink(pair.id, 'c3', 't3', 13), 'a link belongs to one record');
+ await db.deletePair(pair.id);
+ assert.deepEqual(await db.listMirrorLinks(pair.id), []);
+ });
+
await t.test('purging a server removes its pair, map and queue', async () => {
const pair = await db.getPairBySource(A);
await db.putMapping({ pairId: pair.id, kind: 'role', sourceId: '2', targetId: 't2' });
diff --git a/web-v2/src/pages/Mirror.jsx b/web-v2/src/pages/Mirror.jsx
index d442f4fa..a6de8906 100644
--- a/web-v2/src/pages/Mirror.jsx
+++ b/web-v2/src/pages/Mirror.jsx
@@ -521,7 +521,10 @@ function PreviewResult({ preview, onStart, working }) {
{lines.map((l) => (
{l.text}
))}
-
Last, every copied channel is linked through the bridge (when the bridge is installed).
+
+ Last, every copied text channel is linked through the bridge, if the channels allow it (the reasons are in the
+ report).
+
What cannot be carried over{groups.length ? '' : ': nothing'}
{groups.map((g) => (
From f3e98f238b702dd0ba79c41352055a9863148d53 Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Tue, 17 Nov 2026 01:11:31 +0100
Subject: [PATCH 11/17] fix(mirror): lint
---
src/modules/bridge.js | 1 +
test/mirrorBridgeLink.test.js | 1 -
2 files changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/modules/bridge.js b/src/modules/bridge.js
index 08818e00..df56389d 100644
--- a/src/modules/bridge.js
+++ b/src/modules/bridge.js
@@ -653,6 +653,7 @@ const mirrorBy = (name) => `${String(name || 'server owner').slice(0, 60)} (serv
function everyoneSees(key, channel) {
const guild = guildByKey(key);
try {
+ // eslint-disable-next-line no-restricted-syntax -- the @everyone role id is the platform guild id
const perms = channel?.permissionsFor?.(String(guild?.id ?? ''));
if (!perms || typeof perms.has !== 'function') return null;
return perms.has('ViewChannel') === true;
diff --git a/test/mirrorBridgeLink.test.js b/test/mirrorBridgeLink.test.js
index 787e23d7..fb8f41c6 100644
--- a/test/mirrorBridgeLink.test.js
+++ b/test/mirrorBridgeLink.test.js
@@ -384,7 +384,6 @@ test('a webhook that cannot be made skips the pair and leaves nothing half made'
test('when the clients are not both connected, nothing is linked and the reason says so', async () => {
const pair = await livePair();
await mirrored(pair, 'chat');
- p.fluxer.user = p.fluxer.user; // still there
removePlatforms();
assert.equal((await run(pair)).reason, 'bridge-not-available');
assert.equal((await linkMirroredChannels(999_999, { sleep: noSleep })).reason, 'no-such-mirror');
From 3c1ab6646672c9c8f1d27faee6247225ce73649f Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Tue, 17 Nov 2026 01:12:45 +0100
Subject: [PATCH 12/17] style(mirror): prettier
---
src/mirror/bridgeLink.js | 8 ++++++--
src/modules/bridge.js | 33 ++++++++++++++++++++-------------
test/mirrorBridgeEngine.test.js | 10 ++++++++--
test/mirrorBridgeLink.test.js | 15 +++------------
web-v2/src/pages/Mirror.jsx | 4 ++--
5 files changed, 39 insertions(+), 31 deletions(-)
diff --git a/src/mirror/bridgeLink.js b/src/mirror/bridgeLink.js
index 4aa14d86..789309a6 100644
--- a/src/mirror/bridgeLink.js
+++ b/src/mirror/bridgeLink.js
@@ -138,7 +138,8 @@ export async function linkMirroredChannels(
if (skip.has(m.sourceId)) continue;
const found = await linkForChannel(pair.sourceGuild, m.sourceId);
if (found) {
- const same = found.side === 'a' && found.link.guildB === pair.targetGuild && found.link.channelB === m.targetId;
+ const same =
+ found.side === 'a' && found.link.guildB === pair.targetGuild && found.link.channelB === m.targetId;
if (same) {
// A link of exactly this pair whose record was lost (a restart between the two writes): take it over.
await putMirrorLink(pair.id, m.sourceId, m.targetId, found.link.id);
@@ -195,7 +196,10 @@ export async function linkMirroredChannels(
linked += 1;
} catch (err) {
if (!(err instanceof BridgeError)) throw err;
- log.info('mirror', `pair ${pair.id}: ${item.name} not linked (${err.code || err.status}): ${err.message}`);
+ log.info(
+ 'mirror',
+ `pair ${pair.id}: ${item.name} not linked (${err.code || err.status}): ${err.message}`
+ );
skipped.push({
sourceId: item.sourceId,
name: item.name,
diff --git a/src/modules/bridge.js b/src/modules/bridge.js
index df56389d..cc42c3c2 100644
--- a/src/modules/bridge.js
+++ b/src/modules/bridge.js
@@ -595,7 +595,10 @@ export async function resumeLink({ guildKey, id, actor }) {
const { link, side } = await ownLink(guildKey, id);
if (link.status === 'active') throw new BridgeError('That bridge is already running.', 409);
if (link.status === 'paused' && link.failReason === 'mirror') {
- throw new BridgeError('The server mirror made this bridge and paused it. It runs again when the mirror does.', 409);
+ throw new BridgeError(
+ 'The server mirror made this bridge and paused it. It runs again when the mirror does.',
+ 409
+ );
}
// A link nobody owns the pause of (the mirror that made it ended) can be resumed by either server.
if (link.status === 'paused' && link.pausedSide && link.pausedSide !== side) {
@@ -1591,18 +1594,22 @@ export async function bridgeOverview(key) {
* the bridge needs in its channels are checked by the generic channel check there.
*/
export async function bridgeProblems(key) {
- return (await store.linksOfGuild(key))
- // A link the server mirror holds is covered by the mirror's own Health entry.
- .filter((l) => l.status === 'failed' || (l.status === 'paused' && l.failReason && l.failReason !== 'mirror'))
- .map((l) => {
- const side = sideOf(l, key);
- return {
- linkId: l.id,
- channelId: channelOf(l, side),
- code: l.failReason,
- text: reasonText(l.failReason),
- };
- });
+ return (
+ (await store.linksOfGuild(key))
+ // A link the server mirror holds is covered by the mirror's own Health entry.
+ .filter(
+ (l) => l.status === 'failed' || (l.status === 'paused' && l.failReason && l.failReason !== 'mirror')
+ )
+ .map((l) => {
+ const side = sideOf(l, key);
+ return {
+ linkId: l.id,
+ channelId: channelOf(l, side),
+ code: l.failReason,
+ text: reasonText(l.failReason),
+ };
+ })
+ );
}
/** The bridged channels of a server, with the permissions the bridge needs in each. */
diff --git a/test/mirrorBridgeEngine.test.js b/test/mirrorBridgeEngine.test.js
index bba600a5..33f6d46b 100644
--- a/test/mirrorBridgeEngine.test.js
+++ b/test/mirrorBridgeEngine.test.js
@@ -83,7 +83,10 @@ test('a step that links nothing says why', async () => {
});
await s.engine.startCopy(s.pair.id);
await drain(s);
- assert.equal((await s.engine.report(await db.getPair(s.pair.id))).bridge.detail, 'not linked: nothing-to-link');
+ assert.equal(
+ (await s.engine.report(await db.getPair(s.pair.id))).bridge.detail,
+ 'not linked: nothing-to-link'
+ );
});
test('a channel made on Discord later is linked too: the bridge step is asked for again', async () => {
@@ -305,6 +308,9 @@ test('a new request keeps real deletion only for the same Fluxer owner who owns
);
// The request brings its own options: the existing rules for them apply (asked, not on).
const explicit = await ask({ targetOwner: false, options: { mirrorDeletes: true } });
- assert.deepEqual([explicit.pair.options.mirrorDeletes, explicit.pair.options.mirrorDeletesRequested], [false, true]);
+ assert.deepEqual(
+ [explicit.pair.options.mirrorDeletes, explicit.pair.options.mirrorDeletesRequested],
+ [false, true]
+ );
await db.deletePair(explicit.pair.id);
});
diff --git a/test/mirrorBridgeLink.test.js b/test/mirrorBridgeLink.test.js
index fb8f41c6..09b19992 100644
--- a/test/mirrorBridgeLink.test.js
+++ b/test/mirrorBridgeLink.test.js
@@ -29,14 +29,7 @@ import {
unlinkLink,
useBridgeParts,
} from '../src/modules/bridge.js';
-import {
- D,
- F,
- installPlatforms,
- message,
- removePlatforms,
- useFakes,
-} from './helpers/fakeBridge.js';
+import { D, F, installPlatforms, message, removePlatforms, useFakes } from './helpers/fakeBridge.js';
let p;
let fakes;
@@ -112,7 +105,7 @@ test('every mirrored text channel pair is linked, voice channels and categories
);
assert.equal((await mdb.getMirrorLink(pair.id, d.id)).linkId, found.link.id);
}
- assert.equal((await bridgeDb.linkCount(D)), 2);
+ assert.equal(await bridgeDb.linkCount(D), 2);
assert.equal(fakes.transport.hooks.length, 4, 'a webhook in each of the four channels, none for voice');
});
@@ -256,9 +249,7 @@ test('with sign-in on, each owner must be able to see, read and send in the chan
// the Fluxer owner cannot read the history of one channel
const real = hidden.f.permissionsFor;
hidden.f.permissionsFor = (t) =>
- t?.id === fluxerOwner.id
- ? { has: (perm) => perm !== 'ReadMessageHistory' }
- : real(t);
+ t?.id === fluxerOwner.id ? { has: (perm) => perm !== 'ReadMessageHistory' } : real(t);
const res = await run(pair, { open: false });
assert.equal(res.linked, 1);
assert.deepEqual(
diff --git a/web-v2/src/pages/Mirror.jsx b/web-v2/src/pages/Mirror.jsx
index a6de8906..6048eaf9 100644
--- a/web-v2/src/pages/Mirror.jsx
+++ b/web-v2/src/pages/Mirror.jsx
@@ -522,8 +522,8 @@ function PreviewResult({ preview, onStart, working }) {
{l.text}
))}
- Last, every copied text channel is linked through the bridge, if the channels allow it (the reasons are in the
- report).
+ Last, every copied text channel is linked through the bridge, if the channels allow it (the reasons
+ are in the report).
What cannot be carried over{groups.length ? '' : ': nothing'}
From 80118a5b97ffbe7d6e270e734389e1a816b73aa7 Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Tue, 17 Nov 2026 01:17:06 +0100
Subject: [PATCH 13/17] feat(bridge): a link held by its mirror has no Resume
button; one whose mirror ended has
---
src/modules/bridge.js | 6 ++++++
test/mirrorBridgeLink.test.js | 2 ++
web-v2/src/__tests__/Bridge.test.jsx | 25 +++++++++++++++++++++++++
web-v2/src/moduleForms/Bridge.jsx | 2 +-
4 files changed, 34 insertions(+), 1 deletion(-)
diff --git a/src/modules/bridge.js b/src/modules/bridge.js
index cc42c3c2..5cb60bc4 100644
--- a/src/modules/bridge.js
+++ b/src/modules/bridge.js
@@ -1545,6 +1545,12 @@ export function linkView(link, key) {
status: link.status,
pausedByMe: link.status === 'paused' && link.pausedSide === side,
pausedByThem: link.status === 'paused' && link.pausedSide === theirs,
+ // Whether this server's owner can press Resume: a stopped link, one this server paused, or one nobody holds
+ // (its server mirror ended). A link held by a running-state mirror comes back with the mirror.
+ resumable:
+ link.status === 'failed' ||
+ (link.status === 'paused' &&
+ (link.pausedSide === side || (!link.pausedSide && link.failReason !== 'mirror'))),
problem: link.status === 'failed' ? { code: link.failReason, text: reasonText(link.failReason) } : null,
// Why a paused link is paused beyond "a server paused it": its owner changed, or its channel is gone.
pauseNote: link.status === 'paused' && link.failReason ? reasonText(link.failReason) : null,
diff --git a/test/mirrorBridgeLink.test.js b/test/mirrorBridgeLink.test.js
index 09b19992..9862dacd 100644
--- a/test/mirrorBridgeLink.test.js
+++ b/test/mirrorBridgeLink.test.js
@@ -405,6 +405,7 @@ test('a paused mirror pauses its links, nothing crosses, and they run again with
assert.equal(fakes.transport.sends.length, 1, 'nothing crosses while the mirror is paused');
assert.deepEqual(await bridgeProblems(D), [], 'the mirror has its own Health entry');
assert.match(linkView(held, D).pauseNote, /server mirror/);
+ assert.equal(linkView(held, D).resumable, false, 'it comes back with the mirror, not by a button');
// the bridge page cannot resume it on its own
await assert.rejects(
@@ -471,6 +472,7 @@ test('removing a mirror releases its links: they stay, paused, and either owner
const link = (await bridgeDb.linkForChannel(D, d.id)).link;
assert.deepEqual([link.status, link.pausedSide, link.failReason], ['paused', '', 'mirror-ended']);
assert.match(linkView(link, F).pauseNote, /mirror that made this bridge ended/);
+ assert.deepEqual([linkView(link, D).resumable, linkView(link, F).resumable], [true, true]);
await mdb.deletePair(pair.id);
assert.equal((await mdb.listMirrorLinks(pair.id)).length, 0, 'the record goes with the pair');
// the Fluxer owner resumes it on the Bridge page
diff --git a/web-v2/src/__tests__/Bridge.test.jsx b/web-v2/src/__tests__/Bridge.test.jsx
index afbed9f9..13400283 100644
--- a/web-v2/src/__tests__/Bridge.test.jsx
+++ b/web-v2/src/__tests__/Bridge.test.jsx
@@ -180,6 +180,31 @@ describe('Bridge page', () => {
expect(screen.getByRole('button', { name: 'Resume' })).toBeTruthy();
});
+ it('a bridge the server mirror holds has no Resume button; one whose mirror ended has', async () => {
+ api.getBridge.mockResolvedValue(
+ overview({
+ links: [
+ link({
+ id: 7,
+ status: 'paused',
+ resumable: false,
+ pauseNote: 'This bridge was made by the server mirror and is paused with it.',
+ }),
+ link({
+ id: 8,
+ status: 'paused',
+ resumable: true,
+ mine: { channelId: TWO, platform: 'discord', server: 'Home', channel: 'rules', ageRestricted: false },
+ pauseNote: 'The server mirror that made this bridge ended.',
+ }),
+ ],
+ })
+ );
+ renderAtGuild(, GUILD);
+ expect(await screen.findByText(/paused with it/)).toBeTruthy();
+ expect(screen.getAllByRole('button', { name: 'Resume' })).toHaveLength(1);
+ });
+
it('changes a switch of this side through the server', async () => {
api.getBridge.mockResolvedValue(overview({ links: [link()] }));
api.setBridgeOptions.mockResolvedValue({
diff --git a/web-v2/src/moduleForms/Bridge.jsx b/web-v2/src/moduleForms/Bridge.jsx
index e9988b5e..6e87bc89 100644
--- a/web-v2/src/moduleForms/Bridge.jsx
+++ b/web-v2/src/moduleForms/Bridge.jsx
@@ -226,7 +226,7 @@ export default function Bridge() {
From 2aaa0807f6f9e90e379c1870b497d500533fafa6 Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Tue, 17 Nov 2026 01:21:19 +0100
Subject: [PATCH 14/17] style: prettier
---
web-v2/src/__tests__/Bridge.test.jsx | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/web-v2/src/__tests__/Bridge.test.jsx b/web-v2/src/__tests__/Bridge.test.jsx
index 13400283..f9f1e907 100644
--- a/web-v2/src/__tests__/Bridge.test.jsx
+++ b/web-v2/src/__tests__/Bridge.test.jsx
@@ -194,7 +194,13 @@ describe('Bridge page', () => {
id: 8,
status: 'paused',
resumable: true,
- mine: { channelId: TWO, platform: 'discord', server: 'Home', channel: 'rules', ageRestricted: false },
+ mine: {
+ channelId: TWO,
+ platform: 'discord',
+ server: 'Home',
+ channel: 'rules',
+ ageRestricted: false,
+ },
pauseNote: 'The server mirror that made this bridge ended.',
}),
],
From 4c52322c83e4b75e135da97c797af49c2f309f56 Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Tue, 17 Nov 2026 05:03:37 +0100
Subject: [PATCH 15/17] fix(mirror): review round for the bridge wiring (module
switch, remover side, held links, privacy over time)
---
docs/mirror.md | 18 ++-
docs/modules/bridge.md | 4 +-
src/db/mirror.js | 3 +
src/mirror/bridgeLink.js | 63 ++++++++--
src/mirror/engine.js | 4 +-
src/modules/bridge.js | 87 +++++++++++---
src/web/routes/v2Mirror.js | 2 +-
test/mirrorBridgeEngine.test.js | 8 +-
test/mirrorBridgeLink.test.js | 196 +++++++++++++++++++++++++++++---
9 files changed, 331 insertions(+), 54 deletions(-)
diff --git a/docs/mirror.md b/docs/mirror.md
index 3191e5b8..7387ebe9 100644
--- a/docs/mirror.md
+++ b/docs/mirror.md
@@ -60,22 +60,28 @@ so a message written on one side shows up on the other. Voice channels, categori
- **Both owners already agreed.** The mirror is the consent: no link code is used. Each link records the two
people who agreed to the mirror (shown as "Name (server mirror)" on the Bridge page and in both audit logs), and
both channels get the usual notice, which says the link was made by the server mirror.
-- **The Bridge module is switched on in both servers** if it was off (it has to be on for a link to carry
- anything). Both audit logs say so. You can switch it off again; the links then carry nothing.
+- **The Bridge module is switched on in both servers** if it was off, but only the first time the mirror links
+ channels (it has to be on for a link to carry anything). Both audit logs say so. If a server's owner switches it
+ off afterwards, that stays off: the mirror reports the pairs it could not link ("the Bridge module is switched
+ off") and does not switch it on again, and the links carry nothing.
- **Every rule of the bridge holds.** An age-restricted channel is linked only to an age-restricted channel; a
private channel only to a private one (a channel everyone can read is never linked to one that only some can);
each owner must be able to see, read and send in the channel, and Sylo needs Manage Webhooks, View Channel and
- Send Messages in both; bots are off; nobody is pinged across. A pair that fails a rule is skipped, the reason
+ Send Messages in both; bots are off; nobody is pinged across. The privacy rule is checked again whenever a
+ paused link resumes and on every message: a channel that turns private later stops the link ("no longer open
+ to the same people"). A pair that fails a rule is skipped, the reason
is in the report ("Linking channels through the bridge" and the notes), and the rest are linked.
- **Safe to run again.** "Copy again" links only the pairs that have no link yet. A channel that an owner
- unlinked on the Bridge page stays unlinked. A server can have at most 50 bridged channels this way (10 when
+ unlinked on the Bridge page stays unlinked, and a pair the owners bridged by hand is never taken over or
+ changed (it is reported as skipped). A server can have at most 50 bridged channels this way (10 when
linking by hand), and a copy links 25 channels at a time. A channel made on Discord later (continuous mirroring)
is linked too.
- **The links follow the mirror.** While the mirror is paused (by an owner, by Sylo after a failure, or because a
server changed owner) or stopped, its links are paused, with no notice in each channel, and they run again when
the mirror does. If a server changed owner, its link stays paused until the new owner confirms it on the Bridge
- page. **Removing** a mirror pauses its links and leaves them: either owner can resume or unlink each one on the
- Bridge page.
+ page. **Removing** a mirror pauses its links and leaves them, paused by the server that removed it: only that
+ server's owner can resume them on the Bridge page, and the other server's owner can unlink them. While the
+ mirror is not running, none of its links can be resumed on the Bridge page.
## What is copied
diff --git a/docs/modules/bridge.md b/docs/modules/bridge.md
index 37d03ab7..f49d3e65 100644
--- a/docs/modules/bridge.md
+++ b/docs/modules/bridge.md
@@ -49,7 +49,9 @@ bridge without codes, because both owners already agreed to the mirror. Those li
as who made them, follow the mirror (paused with it, running again with it; the Bridge page cannot resume one on
its own while the mirror is paused) and follow every rule on this page. A server can have 50 of them (10 when you
link by hand). Unlink works for them as for any other link, and an unlinked channel is not linked again. If the
-mirror is removed, its links stay, paused, and either owner can resume or unlink them.
+mirror is removed, its links stay, paused by the server that removed it: only that server's owner can resume
+them, and either owner can unlink them. The mirror switches this module on only the first time it links, and a
+server that switches it off keeps it off.
**Pause** stops the bridge from either side. Only the server that paused it can resume it. A link that Sylo
stopped itself (see below) can be resumed by either server once the cause is fixed.
diff --git a/src/db/mirror.js b/src/db/mirror.js
index 1d0d0328..1a4d17ac 100644
--- a/src/db/mirror.js
+++ b/src/db/mirror.js
@@ -109,6 +109,9 @@ export const PAIR_STATUS = Object.freeze({
STOPPED: 'stopped',
});
+/** The states in which a mirror runs, and so do the bridge links it made. */
+export const PAIR_RUNNING = Object.freeze([PAIR_STATUS.COPYING, PAIR_STATUS.LIVE, PAIR_STATUS.DONE]);
+
const num = (v) => Number(v ?? 0);
const parseJson = (text, fallback) => {
diff --git a/src/mirror/bridgeLink.js b/src/mirror/bridgeLink.js
index 789309a6..de1cacca 100644
--- a/src/mirror/bridgeLink.js
+++ b/src/mirror/bridgeLink.js
@@ -26,13 +26,16 @@ import { runtime } from '../runtime.js';
import { guildByKey } from '../platform/platformOf.js';
import {
PAIR_STATUS,
+ getMapping,
getMirrorLink,
getPair,
listMappings,
listMirrorLinks,
+ putMapping,
putMirrorLink,
} from '../db/mirror.js';
import { linkForChannel } from '../db/bridge.js';
+import { isModuleEnabled } from '../db/modules.js';
import {
BridgeError,
createMirrorLink,
@@ -54,6 +57,9 @@ const channelOf = (guild, id) => guild?.channels?.cache?.get?.(String(id)) ?? nu
const RUNNING = new Set([PAIR_STATUS.COPYING, PAIR_STATUS.LIVE, PAIR_STATUS.DONE]);
export const mirrorRuns = (pair) => Boolean(pair) && RUNNING.has(pair.status);
+/** The first linking of a pair is the one that may switch the Bridge module on; this id map entry says it happened. */
+const MODULE_MARKER = ['bridge', 'module'];
+
const sleepReal = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/** An owner's member in their own server (null when it cannot be had). */
@@ -89,11 +95,16 @@ export async function syncMirrorLinks(pairOrId) {
return out;
}
-/** The mirror is being removed: its links stay, paused, and either owner can resume or unlink them on the Bridge page. */
-export async function releaseMirrorLinks(pairId) {
+/**
+ * The mirror is being removed by `side` ('source' the Discord server, 'target' the Fluxer server): its links stay,
+ * paused by that server, so only its owner can resume them on the Bridge page and the other server's owner can
+ * unlink them.
+ */
+export async function releaseMirrorLinks(pairId, side = '') {
+ const linkSide = side === 'source' ? 'a' : side === 'target' ? 'b' : '';
let released = 0;
for (const row of await listMirrorLinks(pairId)) {
- if (await releaseMirrorLink(row.linkId)) released += 1;
+ if (await releaseMirrorLink(row.linkId, linkSide)) released += 1;
}
return released;
}
@@ -140,16 +151,19 @@ export async function linkMirroredChannels(
if (found) {
const same =
found.side === 'a' && found.link.guildB === pair.targetGuild && found.link.channelB === m.targetId;
- if (same) {
- // A link of exactly this pair whose record was lost (a restart between the two writes): take it over.
+ if (same && String(found.link.requestedBy).endsWith('(server mirror)')) {
+ // A link this mirror made whose record was lost (a restart between the two writes): take it over.
await putMirrorLink(pair.id, m.sourceId, m.targetId, found.link.id);
already += 1;
} else {
+ // A link the owners made themselves is theirs: it is never taken over, and never changed.
skipped.push({
sourceId: m.sourceId,
name: m.label || src.name,
code: 'exists',
- message: 'this channel is already bridged to another channel',
+ message: same
+ ? 'this pair is already bridged by hand, and the mirror leaves it as it is'
+ : 'this channel is already bridged to another channel',
});
}
continue;
@@ -161,8 +175,36 @@ export async function linkMirroredChannels(
return already || skipped.length ? out : { ...out, reason: 'nothing-to-link' };
}
- await enableBridgeForMirror(pair.sourceGuild);
- await enableBridgeForMirror(pair.targetGuild);
+ // Only the first linking of a pair switches the Bridge module on. After that, a server that switched it off has
+ // decided so (it is the switch for every bridge in that server), and the mirror does not switch it on again.
+ if (await getMapping(pair.id, ...MODULE_MARKER)) {
+ const off = [];
+ for (const key of [pair.sourceGuild, pair.targetGuild]) {
+ if (!(await isModuleEnabled(key, 'bridge'))) off.push(key);
+ }
+ if (off.length > 0) {
+ for (const item of todo) {
+ skipped.push({
+ sourceId: item.sourceId,
+ name: item.name,
+ code: 'bridge-off',
+ message: 'the Bridge module is switched off in one of the servers, and the mirror does not switch it on again',
+ });
+ }
+ return { linked: 0, already, remaining: 0, tried: [], skipped, reason: 'bridge-off' };
+ }
+ } else {
+ await enableBridgeForMirror(pair.sourceGuild);
+ await enableBridgeForMirror(pair.targetGuild);
+ await putMapping({
+ pairId: pair.id,
+ kind: MODULE_MARKER[0],
+ sourceId: MODULE_MARKER[1],
+ targetId: '',
+ owned: false,
+ specHash: '',
+ });
+ }
// The owners who agreed must be able to see, read and send in each channel themselves (as for a link made by
// hand). With sign-in off there is no one to check.
@@ -173,8 +215,9 @@ export async function linkMirroredChannels(
const consent = {
sourceBy: pair.sourceConsentBy,
targetBy: pair.targetConsentBy,
- sourceOwner: String(sg.ownerId ?? ''),
- targetOwner: String(tg.ownerId ?? ''),
+ // The people who agreed to the mirror (the bridge's own owner check then pauses the link if a server changes hands).
+ sourceOwner: pair.sourceConsentUser || String(sg.ownerId ?? ''),
+ targetOwner: pair.targetConsentUser || String(tg.ownerId ?? ''),
};
let linked = 0;
diff --git a/src/mirror/engine.js b/src/mirror/engine.js
index 42ca87ad..4816a141 100644
--- a/src/mirror/engine.js
+++ b/src/mirror/engine.js
@@ -1419,14 +1419,14 @@ export function createEngine(overrides = {}) {
}
/** Forget the mirror altogether: the pair, its id map and its queue. Nothing on either server is touched. */
- async function removePair(pairId) {
+ async function removePair(pairId, side = '') {
const pair = await store.getPair(pairId);
if (!pair) return false;
if ([PAIR_STATUS.COPYING, PAIR_STATUS.LIVE].includes(pair.status)) {
throw new MirrorError('Stop the mirror before removing it.', 'item');
}
// The bridge links it made stay, paused: the owners decide on the Bridge page whether to resume or unlink them.
- await deps.releaseLinks(pairId);
+ await deps.releaseLinks(pairId, side);
await store.deletePair(pairId);
state.delete(pairId);
touchHealth(pair);
diff --git a/src/modules/bridge.js b/src/modules/bridge.js
index 5cb60bc4..8f4f3215 100644
--- a/src/modules/bridge.js
+++ b/src/modules/bridge.js
@@ -27,6 +27,7 @@ import { every } from './schedule.js';
import { getGuildModule, isModuleEnabled, setGuildModule } from '../db/modules.js';
import { recordAudit } from '../db/audit.js';
import { onBeforePurge } from '../db/purge.js';
+import { PAIR_RUNNING, getPair as getMirrorPair, mirrorPairOfLink } from '../db/mirror.js';
import * as store from '../db/bridge.js';
import { runtime } from '../runtime.js';
import { splitPlatformGuildId } from '../lib/platformId.js';
@@ -257,7 +258,9 @@ const REASONS = {
mirror:
'This bridge was made by the server mirror and is paused with it. It runs again when the mirror does.',
'mirror-ended':
- 'The server mirror that made this bridge ended. Either server owner can resume the bridge on the Bridge page, or unlink it.',
+ 'The server mirror that made this bridge was removed, and the bridge was paused. Only the server that removed the mirror can resume it; either server can unlink it.',
+ visibility:
+ 'The two channels are no longer open to the same people (one became private). A channel everyone can read is never bridged to a private one.',
};
/** The text a link's stored failure reason stands for. */
export const reasonText = (code) => REASONS[code] ?? 'The bridge stopped working.';
@@ -594,13 +597,13 @@ async function revalidate(link) {
export async function resumeLink({ guildKey, id, actor }) {
const { link, side } = await ownLink(guildKey, id);
if (link.status === 'active') throw new BridgeError('That bridge is already running.', 409);
- if (link.status === 'paused' && link.failReason === 'mirror') {
+ if ((await mirrorHold(link)) === 'held') {
throw new BridgeError(
- 'The server mirror made this bridge and paused it. It runs again when the mirror does.',
+ 'The server mirror made this bridge and holds it while the mirror is not running. It runs again when the mirror does.',
409
);
}
- // A link nobody owns the pause of (the mirror that made it ended) can be resumed by either server.
+ // A link nobody owns the pause of (its mirror was removed by nobody in particular) can be resumed by either server.
if (link.status === 'paused' && link.pausedSide && link.pausedSide !== side) {
throw new BridgeError('The other server paused this bridge, so only they can resume it.', 403);
}
@@ -665,6 +668,31 @@ function everyoneSees(key, channel) {
}
}
+/** Are the two channels equally open: both visible to @everyone or both not? Unknown counts as different. */
+function samePrivacy(keyA, channelA, keyB, channelB) {
+ const a = everyoneSees(keyA, channelA);
+ const b = everyoneSees(keyB, channelB);
+ return a !== null && b !== null && a === b;
+}
+
+/** A link the server mirror made records its two owners as " (server mirror)". */
+const MIRROR_TAG = '(server mirror)';
+const madeByMirror = (link) => String(link?.requestedBy ?? '').endsWith(MIRROR_TAG);
+
+/**
+ * Who holds a link: 'held' while its server mirror is not running (or the link is paused by it), 'ended' when it
+ * says the mirror holds it but that mirror is gone (the pair was replaced), otherwise 'none'. A held link cannot
+ * be resumed on the Bridge page: it comes back with the mirror.
+ */
+export async function mirrorHold(link) {
+ const pairId = await mirrorPairOfLink(link.id);
+ if (!pairId) return link.status === 'paused' && link.failReason === 'mirror' ? 'ended' : 'none';
+ const pair = await getMirrorPair(pairId);
+ if (!pair) return link.status === 'paused' && link.failReason === 'mirror' ? 'ended' : 'none';
+ if (!PAIR_RUNNING.includes(pair.status)) return 'held';
+ return link.status === 'paused' && link.failReason === 'mirror' ? 'held' : 'none';
+}
+
/**
* Turn the Bridge module on in a server the mirror links channels in. The owner agreed to the mirror, which
* links every copied channel, and the module has to be on for the links to carry anything.
@@ -712,9 +740,7 @@ export async function createMirrorLink({ source, target, members = {}, open = fa
checkAge(source.guildKey, a.channel, target.guildKey, b.channel);
// A channel only some members can see is linked only to a channel that is as closed: nothing private is
// shared with a channel everyone can read, in either direction.
- const seenA = everyoneSees(source.guildKey, a.channel);
- const seenB = everyoneSees(target.guildKey, b.channel);
- if (seenA === null || seenB === null || seenA !== seenB) {
+ if (!samePrivacy(source.guildKey, a.channel, target.guildKey, b.channel)) {
throw new BridgeError(
'The two channels are not open to the same people (one is private, or it cannot be told), so they are not bridged.',
409,
@@ -810,6 +836,17 @@ export async function resumeMirrorLink(linkId) {
if (err instanceof BridgeError) return { resumed: false, reason: err.message };
throw err;
}
+ // The channels must still be equally open: a channel can have turned private since the link was made.
+ if (
+ !samePrivacy(
+ link.guildA,
+ channelIn(link.guildA, link.channelA),
+ link.guildB,
+ channelIn(link.guildB, link.channelB)
+ )
+ ) {
+ return { resumed: false, reason: reasonText('visibility') };
+ }
const changed = ownerChangedSide(link);
if (changed) {
await store.setLinkStatus(link.id, { status: 'paused', pausedSide: changed, reason: 'owner-changed' });
@@ -821,13 +858,21 @@ export async function resumeMirrorLink(linkId) {
return { resumed: true };
}
-/** The mirror that made a link ended: the link stays, paused, and either server owner can resume or unlink it. */
-export async function releaseMirrorLink(linkId) {
+/**
+ * The mirror that made a link was removed by `side` ('a' the Discord server, 'b' the Fluxer server): the link stays,
+ * paused by that server, so only its owner can resume it and the other server's owner can unlink it. Without a side
+ * (a removal nobody owns) either owner can resume it.
+ */
+export async function releaseMirrorLink(linkId, side = '') {
const link = await store.getLink(linkId);
if (!link) return false;
const mine = link.status === 'active' || (link.status === 'paused' && link.failReason === 'mirror');
if (!mine) return false;
- await store.setLinkStatus(link.id, { status: 'paused', pausedSide: '', reason: 'mirror-ended' });
+ await store.setLinkStatus(link.id, {
+ status: 'paused',
+ pausedSide: side === 'a' || side === 'b' ? side : '',
+ reason: 'mirror-ended',
+ });
dropBridgeCache();
queue.clear(laneKey(link, 'a'));
queue.clear(laneKey(link, 'b'));
@@ -1269,6 +1314,11 @@ async function allowed(message, link, side, key) {
await failLink(link.id, 'age-restriction');
return false;
}
+ // A link the server mirror made also keeps the two channels equally open (a channel can turn private later).
+ if (madeByMirror(link) && !samePrivacy(key, mine, theirKey, theirs)) {
+ await failLink(link.id, 'visibility');
+ return false;
+ }
return true;
}
@@ -1537,7 +1587,7 @@ function endView(key, channelId) {
}
/** One link as the server `key` sees it (never a webhook token). */
-export function linkView(link, key) {
+export function linkView(link, key, hold = 'none') {
const side = sideOf(link, key);
const theirs = other(side);
return {
@@ -1548,12 +1598,17 @@ export function linkView(link, key) {
// Whether this server's owner can press Resume: a stopped link, one this server paused, or one nobody holds
// (its server mirror ended). A link held by a running-state mirror comes back with the mirror.
resumable:
- link.status === 'failed' ||
- (link.status === 'paused' &&
- (link.pausedSide === side || (!link.pausedSide && link.failReason !== 'mirror'))),
+ hold !== 'held' &&
+ (link.status === 'failed' ||
+ (link.status === 'paused' && (link.pausedSide === side || !link.pausedSide))),
problem: link.status === 'failed' ? { code: link.failReason, text: reasonText(link.failReason) } : null,
// Why a paused link is paused beyond "a server paused it": its owner changed, or its channel is gone.
- pauseNote: link.status === 'paused' && link.failReason ? reasonText(link.failReason) : null,
+ pauseNote:
+ hold === 'held' && link.status !== 'active'
+ ? reasonText('mirror')
+ : link.status === 'paused' && link.failReason
+ ? reasonText(hold === 'ended' ? 'mirror-ended' : link.failReason)
+ : null,
mine: { channelId: channelOf(link, side), ...endView(key, channelOf(link, side)) },
theirs: endView(guildOf(link, theirs), channelOf(link, theirs)),
options: optionsOf(link, side),
@@ -1580,7 +1635,7 @@ export async function bridgeOverview(key) {
bothPlatforms: Boolean(runtime.clients.discord && runtime.clients.fluxer),
enabled: (await getGuildModule(key, 'bridge')).enabled,
limits: { links: MAX_LINKS, requests: MAX_REQUESTS },
- links: links.map((l) => linkView(l, key)),
+ links: await Promise.all(links.map(async (l) => linkView(l, key, await mirrorHold(l)))),
requests: requests.map((r) => ({
id: r.id,
channelId: r.channelId,
diff --git a/src/web/routes/v2Mirror.js b/src/web/routes/v2Mirror.js
index 97b3a70d..defe7b93 100644
--- a/src/web/routes/v2Mirror.js
+++ b/src/web/routes/v2Mirror.js
@@ -441,6 +441,6 @@ control(
'mirror resumed'
);
control('stop', (pair) => mirror.stopPair(pair.id), 'mirror stopped');
-control('remove', (pair) => mirror.removePair(pair.id), 'mirror removed');
+control('remove', (pair, side) => mirror.removePair(pair.id, side), 'mirror removed');
export default router;
diff --git a/test/mirrorBridgeEngine.test.js b/test/mirrorBridgeEngine.test.js
index 33f6d46b..b1d415c4 100644
--- a/test/mirrorBridgeEngine.test.js
+++ b/test/mirrorBridgeEngine.test.js
@@ -127,8 +127,8 @@ test('the links of a mirror follow its state: paused, resumed, stopped and relea
syncLinks: async (pair) => {
states.push(pair.status);
},
- releaseLinks: async (id) => {
- released.push(id);
+ releaseLinks: async (id, side) => {
+ released.push([id, side]);
},
},
});
@@ -140,8 +140,8 @@ test('the links of a mirror follow its state: paused, resumed, stopped and relea
await s.engine.stopPair(s.pair.id);
assert.deepEqual(states, ['paused', 'live', 'stopped']);
assert.deepEqual(released, []);
- await s.engine.removePair(s.pair.id);
- assert.deepEqual(released, [s.pair.id], 'released before the pair and its record are gone');
+ await s.engine.removePair(s.pair.id, 'target');
+ assert.deepEqual(released, [[s.pair.id, 'target']], 'released, with the remover side, before the pair is gone');
assert.equal(await db.getPair(s.pair.id), null);
});
diff --git a/test/mirrorBridgeLink.test.js b/test/mirrorBridgeLink.test.js
index 9862dacd..395f8030 100644
--- a/test/mirrorBridgeLink.test.js
+++ b/test/mirrorBridgeLink.test.js
@@ -25,6 +25,7 @@ import {
dropBridgeCache,
handleMessage,
linkView,
+ mirrorHold,
resumeLink,
unlinkLink,
useBridgeParts,
@@ -284,10 +285,11 @@ test('Sylo missing a permission in one channel skips only that pair', async () =
assert.ok(await bridgeDb.linkForChannel(D, fine.d.id));
});
-test('a channel already bridged by hand to another channel is left as it is; the pair itself is taken over', async () => {
+test('a channel already bridged by hand is left as it is, and a lost record of a mirror link is taken over', async () => {
const pair = await livePair();
const other = await mirrored(pair, 'other');
const lost = await mirrored(pair, 'lost');
+ const handmade = await mirrored(pair, 'handmade');
// somebody linked "other" to an unrelated Fluxer channel through the bridge page
const stray = p.channel(p.fGuild, { name: 'stray' });
await bridgeDb.createLink({
@@ -298,7 +300,7 @@ test('a channel already bridged by hand to another channel is left as it is; the
hookA: { id: '1', token: 'a' },
hookB: { id: '2', token: 'b' },
});
- // and a link of exactly the pair "lost" exists whose record was never written
+ // a link of exactly the pair "lost" that the mirror made exists, but its record was never written
const made = await bridgeDb.createLink({
guildA: D,
channelA: lost.d.id,
@@ -306,14 +308,37 @@ test('a channel already bridged by hand to another channel is left as it is; the
channelB: lost.f.id,
hookA: { id: '3', token: 'c' },
hookB: { id: '4', token: 'd' },
+ requestedBy: 'Anna (server mirror)',
+ acceptedBy: 'Bo (server mirror)',
+ });
+ // and the owners linked exactly the pair "handmade" themselves, with a code
+ const byHand = await bridgeDb.createLink({
+ guildA: D,
+ channelA: handmade.d.id,
+ guildB: F,
+ channelB: handmade.f.id,
+ hookA: { id: '5', token: 'e' },
+ hookB: { id: '6', token: 'f' },
+ requestedBy: 'Anna (dashboard)',
+ acceptedBy: 'Bo (dashboard)',
});
const res = await run(pair);
assert.deepEqual([res.linked, res.already], [0, 1]);
assert.deepEqual(
res.skipped.map((s) => [s.sourceId, s.code]),
- [[other.d.id, 'exists']]
+ [
+ [other.d.id, 'exists'],
+ [handmade.d.id, 'exists'],
+ ]
);
- assert.equal((await mdb.getMirrorLink(pair.id, lost.d.id)).linkId, made, 'taken over');
+ assert.match(res.skipped[1].message, /already bridged by hand/);
+ assert.equal((await mdb.getMirrorLink(pair.id, lost.d.id)).linkId, made, 'a lost mirror record is taken over');
+ assert.equal(await mdb.getMirrorLink(pair.id, handmade.d.id), null, 'a hand-made link is never taken over');
+ // so pausing the mirror leaves it alone
+ await mdb.updatePair(pair.id, { status: 'paused' });
+ await syncMirrorLinks(pair.id);
+ assert.equal((await bridgeDb.getLink(byHand)).status, 'active');
+ assert.equal((await bridgeDb.getLink(made)).status, 'paused');
assert.equal(fakes.transport.hooks.length, 0, 'no new webhook');
});
@@ -404,8 +429,9 @@ test('a paused mirror pauses its links, nothing crosses, and they run again with
await send(f, F, { content: 'three' });
assert.equal(fakes.transport.sends.length, 1, 'nothing crosses while the mirror is paused');
assert.deepEqual(await bridgeProblems(D), [], 'the mirror has its own Health entry');
- assert.match(linkView(held, D).pauseNote, /server mirror/);
- assert.equal(linkView(held, D).resumable, false, 'it comes back with the mirror, not by a button');
+ assert.equal(await mirrorHold(held), 'held');
+ assert.match(linkView(held, D, 'held').pauseNote, /server mirror/);
+ assert.equal(linkView(held, D, 'held').resumable, false, 'it comes back with the mirror, not by a button');
// the bridge page cannot resume it on its own
await assert.rejects(
@@ -464,22 +490,164 @@ test('a link whose channel can no longer be used stays paused with the mirror an
assert.equal((await bridgeDb.linkForChannel(D, d.id)).link.failReason, 'mirror');
});
-test('removing a mirror releases its links: they stay, paused, and either owner can resume or unlink them', async () => {
+test('removing a mirror releases its links, paused by the server that removed it: only that owner can resume, the other can unlink', async () => {
const pair = await livePair();
const { d } = await mirrored(pair, 'chat');
+ const other = await mirrored(pair, 'rules');
await run(pair);
- assert.equal(await releaseMirrorLinks(pair.id), 1);
+ assert.equal(await releaseMirrorLinks(pair.id, 'target'), 2, 'removed from the Fluxer server');
const link = (await bridgeDb.linkForChannel(D, d.id)).link;
- assert.deepEqual([link.status, link.pausedSide, link.failReason], ['paused', '', 'mirror-ended']);
- assert.match(linkView(link, F).pauseNote, /mirror that made this bridge ended/);
- assert.deepEqual([linkView(link, D).resumable, linkView(link, F).resumable], [true, true]);
+ assert.deepEqual([link.status, link.pausedSide, link.failReason], ['paused', 'b', 'mirror-ended']);
await mdb.deletePair(pair.id);
assert.equal((await mdb.listMirrorLinks(pair.id)).length, 0, 'the record goes with the pair');
- // the Fluxer owner resumes it on the Bridge page
+ const view = async (key) => linkView(link, key, await mirrorHold(link));
+ assert.equal((await mirrorHold(link)), 'ended');
+ assert.match((await view(F)).pauseNote, /mirror that made this bridge was removed/);
+ assert.deepEqual([(await view(D)).resumable, (await view(F)).resumable], [false, true]);
+ assert.equal((await view(D)).pausedByThem, true);
+ // the Discord owner cannot start sharing again on their own...
+ await assert.rejects(
+ resumeLink({ guildKey: D, id: link.id, actor: 'Anna' }),
+ (err) => err instanceof BridgeError && err.status === 403
+ );
+ assert.equal((await bridgeDb.getLink(link.id)).status, 'paused');
+ // ...but can unlink; the Fluxer owner who removed the mirror can resume
+ await unlinkLink({ guildKey: D, id: (await bridgeDb.linkForChannel(D, other.d.id)).link.id, actor: 'Anna' });
await resumeLink({ guildKey: F, id: link.id, actor: 'Bo' });
assert.equal((await bridgeDb.getLink(link.id)).status, 'active');
- // a second release does nothing to a link that is no longer the mirror's to hold
- assert.equal(await releaseMirrorLinks(pair.id), 0);
+ // a second release does nothing to links that are no longer the mirror's to hold
+ assert.equal(await releaseMirrorLinks(pair.id, 'target'), 0);
+});
+
+test('a removal nobody owns (no side) leaves the links to either owner', async () => {
+ const pair = await livePair();
+ const { d } = await mirrored(pair, 'chat');
+ await run(pair);
+ assert.equal(await releaseMirrorLinks(pair.id), 1);
+ const link = (await bridgeDb.linkForChannel(D, d.id)).link;
+ assert.deepEqual([link.status, link.pausedSide], ['paused', '']);
+ await resumeLink({ guildKey: D, id: link.id, actor: 'Anna' });
+ assert.equal((await bridgeDb.getLink(link.id)).status, 'active');
+});
+
+test('a link whose mirror pair was replaced is not stranded: it counts as ended and can be resumed', async () => {
+ const pair = await livePair();
+ const { d } = await mirrored(pair, 'chat');
+ await run(pair);
+ await mdb.updatePair(pair.id, { status: 'stopped' });
+ await syncMirrorLinks(pair.id);
+ const held = (await bridgeDb.linkForChannel(D, d.id)).link;
+ assert.deepEqual([held.failReason, await mirrorHold(held)], ['mirror', 'held']);
+ await mdb.deletePair(pair.id); // a new request for another Fluxer server replaced the stopped pair
+ assert.equal(await mirrorHold(held), 'ended');
+ assert.equal(linkView(held, D, 'ended').resumable, true);
+ assert.match(linkView(held, D, 'ended').pauseNote, /was removed/);
+ await resumeLink({ guildKey: D, id: held.id, actor: 'Anna' });
+ assert.equal((await bridgeDb.getLink(held.id)).status, 'active');
+});
+
+test('while the mirror is not running, even a stopped or hand-paused link of it cannot be resumed on the Bridge page', async () => {
+ const pair = await livePair();
+ const a = await mirrored(pair, 'chat');
+ const b = await mirrored(pair, 'rules');
+ await run(pair);
+ const failed = (await bridgeDb.linkForChannel(D, a.d.id)).link;
+ const byHand = (await bridgeDb.linkForChannel(D, b.d.id)).link;
+ await bridgeDb.setLinkStatus(failed.id, { status: 'failed', reason: 'permissions' });
+ await bridgeDb.setLinkStatus(byHand.id, { status: 'paused', pausedSide: 'a' });
+ await mdb.updatePair(pair.id, { status: 'stopped' });
+ for (const [guildKey, link] of [
+ [D, failed],
+ [D, byHand],
+ ]) {
+ await assert.rejects(
+ resumeLink({ guildKey, id: link.id, actor: 'Anna' }),
+ (err) => err instanceof BridgeError && err.status === 409 && /mirror/.test(err.message)
+ );
+ }
+ assert.equal(linkView(failed, D, await mirrorHold(failed)).resumable, false);
+ assert.equal(linkView(byHand, D, await mirrorHold(byHand)).resumable, false);
+ // once the mirror runs again they are the owners' to resume
+ await mdb.updatePair(pair.id, { status: 'live' });
+ assert.equal(linkView(byHand, D, await mirrorHold(byHand)).resumable, true);
+ await resumeLink({ guildKey: D, id: byHand.id, actor: 'Anna' });
+ assert.equal((await bridgeDb.getLink(byHand.id)).status, 'active');
+});
+
+// --- the module switch, privacy over time, recorded owners ---------------------------------------------------
+
+test('only the first linking switches the Bridge module on: a server that turned it off keeps it off', async () => {
+ const pair = await livePair();
+ await mirrored(pair, 'chat');
+ assert.equal((await run(pair)).linked, 1);
+ assert.equal((await getGuildModule(F, 'bridge')).enabled, true);
+
+ // the Fluxer server's owner switches the module off; a channel is made on Discord and the mirror copies it
+ await setGuildModule(F, 'bridge', { enabled: false });
+ const later = await mirrored(pair, 'offers');
+ const res = await run(pair);
+ assert.deepEqual([res.linked, res.reason], [0, 'bridge-off']);
+ assert.deepEqual(
+ res.skipped.map((s) => [s.sourceId, s.code]),
+ [[later.d.id, 'bridge-off']]
+ );
+ assert.equal((await getGuildModule(F, 'bridge')).enabled, false, 'still off');
+ assert.equal(await bridgeDb.linkForChannel(D, later.d.id), null);
+ assert.equal((await listAudit(F)).filter((e) => e.action === 'bridge:module').length, 1, 'switched on once');
+ // when the owner switches it on again, the missing pair is linked
+ await setGuildModule(F, 'bridge', { enabled: true });
+ assert.equal((await run(pair)).linked, 1);
+});
+
+test('a first linking where every pair is refused still counts: the module is not switched on again later', async () => {
+ const pair = await livePair();
+ await mirrored(pair, 'adult', { dOpts: { nsfw: true } });
+ assert.equal((await run(pair)).linked, 0);
+ assert.equal((await getGuildModule(D, 'bridge')).enabled, true);
+ await setGuildModule(D, 'bridge', { enabled: false });
+ assert.equal((await run(pair)).reason, 'bridge-off');
+ assert.equal((await getGuildModule(D, 'bridge')).enabled, false);
+});
+
+test('a channel that turns private later pauses the mirror link instead of leaking: on resume and on the next message', async () => {
+ const pair = await livePair();
+ const a = await mirrored(pair, 'chat');
+ const b = await mirrored(pair, 'rules');
+ await run(pair);
+ const closed = (guild) => (target) => ({
+ has: (perm) => !(perm === 'ViewChannel' && target === String(guild.id)),
+ });
+ // on the next message: the Discord channel became private while the Fluxer copy is still open
+ a.d.permissionsFor = closed(p.dGuild);
+ await send(a.d, D, { content: 'secret' });
+ assert.equal(fakes.transport.sends.length, 0, 'nothing crosses');
+ const stopped = (await bridgeDb.linkForChannel(D, a.d.id)).link;
+ assert.deepEqual([stopped.status, stopped.failReason], ['failed', 'visibility']);
+ assert.match((await bridgeProblems(D))[0].text, /no longer open to the same people/);
+
+ // on resume of a link held with the mirror
+ await mdb.updatePair(pair.id, { status: 'paused' });
+ await syncMirrorLinks(pair.id);
+ b.f.permissionsFor = closed(p.fGuild);
+ await mdb.updatePair(pair.id, { status: 'live' });
+ const res = await syncMirrorLinks(pair.id);
+ assert.equal(res.resumed, 0);
+ assert.match(res.waiting[0], /no longer open to the same people/);
+ assert.equal((await bridgeDb.linkForChannel(D, b.d.id)).link.status, 'paused');
+});
+
+test('the links record the people who agreed to the mirror as the owners the bridge checks', async () => {
+ const pair = await livePair();
+ const { d } = await mirrored(pair, 'chat');
+ await run(pair);
+ const link = (await bridgeDb.linkForChannel(D, d.id)).link;
+ assert.deepEqual([link.ownerA, link.ownerB], [pair.sourceConsentUser, pair.targetConsentUser]);
+ // when the Fluxer server has changed hands since, the bridge pauses the link by itself
+ p.fGuild.ownerId = 'someone-new';
+ await handleMessage(message({ channelId: d.id, client: p.discord, content: 'hi' }), {}, D);
+ await bridgeIdle();
+ assert.equal(fakes.transport.sends.length, 0);
+ assert.equal((await bridgeDb.linkForChannel(D, d.id)).link.failReason, 'owner-changed');
});
test('a link the mirror made can be unlinked by either owner, and leaving the server purges it with the pair', async () => {
From efec5d85d6e259c52d49802f453224f35f930787 Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Tue, 17 Nov 2026 05:04:19 +0100
Subject: [PATCH 16/17] test: review round
---
test/mirrorBridgeLink.test.js | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)
diff --git a/test/mirrorBridgeLink.test.js b/test/mirrorBridgeLink.test.js
index 395f8030..ede8f451 100644
--- a/test/mirrorBridgeLink.test.js
+++ b/test/mirrorBridgeLink.test.js
@@ -501,7 +501,7 @@ test('removing a mirror releases its links, paused by the server that removed it
await mdb.deletePair(pair.id);
assert.equal((await mdb.listMirrorLinks(pair.id)).length, 0, 'the record goes with the pair');
const view = async (key) => linkView(link, key, await mirrorHold(link));
- assert.equal((await mirrorHold(link)), 'ended');
+ assert.equal(await mirrorHold(link), 'none', 'it is an ordinary paused link now');
assert.match((await view(F)).pauseNote, /mirror that made this bridge was removed/);
assert.deepEqual([(await view(D)).resumable, (await view(F)).resumable], [false, true]);
assert.equal((await view(D)).pausedByThem, true);
@@ -565,11 +565,13 @@ test('while the mirror is not running, even a stopped or hand-paused link of it
(err) => err instanceof BridgeError && err.status === 409 && /mirror/.test(err.message)
);
}
- assert.equal(linkView(failed, D, await mirrorHold(failed)).resumable, false);
- assert.equal(linkView(byHand, D, await mirrorHold(byHand)).resumable, false);
+ const failedNow = await bridgeDb.getLink(failed.id);
+ const byHandNow = await bridgeDb.getLink(byHand.id);
+ assert.equal(linkView(failedNow, D, await mirrorHold(failedNow)).resumable, false);
+ assert.equal(linkView(byHandNow, D, await mirrorHold(byHandNow)).resumable, false);
// once the mirror runs again they are the owners' to resume
await mdb.updatePair(pair.id, { status: 'live' });
- assert.equal(linkView(byHand, D, await mirrorHold(byHand)).resumable, true);
+ assert.equal(linkView(byHandNow, D, await mirrorHold(byHandNow)).resumable, true);
await resumeLink({ guildKey: D, id: byHand.id, actor: 'Anna' });
assert.equal((await bridgeDb.getLink(byHand.id)).status, 'active');
});
From 678444ed410e79796d525fd0dd84e8aa4a4376e4 Mon Sep 17 00:00:00 2001
From: Ferdinand99
Date: Tue, 17 Nov 2026 05:05:41 +0100
Subject: [PATCH 17/17] style: prettier
---
src/mirror/bridgeLink.js | 3 ++-
test/mirrorBridgeEngine.test.js | 6 +++++-
test/mirrorBridgeLink.test.js | 18 +++++++++++++++---
3 files changed, 22 insertions(+), 5 deletions(-)
diff --git a/src/mirror/bridgeLink.js b/src/mirror/bridgeLink.js
index de1cacca..43cd8c07 100644
--- a/src/mirror/bridgeLink.js
+++ b/src/mirror/bridgeLink.js
@@ -188,7 +188,8 @@ export async function linkMirroredChannels(
sourceId: item.sourceId,
name: item.name,
code: 'bridge-off',
- message: 'the Bridge module is switched off in one of the servers, and the mirror does not switch it on again',
+ message:
+ 'the Bridge module is switched off in one of the servers, and the mirror does not switch it on again',
});
}
return { linked: 0, already, remaining: 0, tried: [], skipped, reason: 'bridge-off' };
diff --git a/test/mirrorBridgeEngine.test.js b/test/mirrorBridgeEngine.test.js
index b1d415c4..ed3a2760 100644
--- a/test/mirrorBridgeEngine.test.js
+++ b/test/mirrorBridgeEngine.test.js
@@ -141,7 +141,11 @@ test('the links of a mirror follow its state: paused, resumed, stopped and relea
assert.deepEqual(states, ['paused', 'live', 'stopped']);
assert.deepEqual(released, []);
await s.engine.removePair(s.pair.id, 'target');
- assert.deepEqual(released, [[s.pair.id, 'target']], 'released, with the remover side, before the pair is gone');
+ assert.deepEqual(
+ released,
+ [[s.pair.id, 'target']],
+ 'released, with the remover side, before the pair is gone'
+ );
assert.equal(await db.getPair(s.pair.id), null);
});
diff --git a/test/mirrorBridgeLink.test.js b/test/mirrorBridgeLink.test.js
index ede8f451..caa45c1b 100644
--- a/test/mirrorBridgeLink.test.js
+++ b/test/mirrorBridgeLink.test.js
@@ -332,7 +332,11 @@ test('a channel already bridged by hand is left as it is, and a lost record of a
]
);
assert.match(res.skipped[1].message, /already bridged by hand/);
- assert.equal((await mdb.getMirrorLink(pair.id, lost.d.id)).linkId, made, 'a lost mirror record is taken over');
+ assert.equal(
+ (await mdb.getMirrorLink(pair.id, lost.d.id)).linkId,
+ made,
+ 'a lost mirror record is taken over'
+ );
assert.equal(await mdb.getMirrorLink(pair.id, handmade.d.id), null, 'a hand-made link is never taken over');
// so pausing the mirror leaves it alone
await mdb.updatePair(pair.id, { status: 'paused' });
@@ -512,7 +516,11 @@ test('removing a mirror releases its links, paused by the server that removed it
);
assert.equal((await bridgeDb.getLink(link.id)).status, 'paused');
// ...but can unlink; the Fluxer owner who removed the mirror can resume
- await unlinkLink({ guildKey: D, id: (await bridgeDb.linkForChannel(D, other.d.id)).link.id, actor: 'Anna' });
+ await unlinkLink({
+ guildKey: D,
+ id: (await bridgeDb.linkForChannel(D, other.d.id)).link.id,
+ actor: 'Anna',
+ });
await resumeLink({ guildKey: F, id: link.id, actor: 'Bo' });
assert.equal((await bridgeDb.getLink(link.id)).status, 'active');
// a second release does nothing to links that are no longer the mirror's to hold
@@ -595,7 +603,11 @@ test('only the first linking switches the Bridge module on: a server that turned
);
assert.equal((await getGuildModule(F, 'bridge')).enabled, false, 'still off');
assert.equal(await bridgeDb.linkForChannel(D, later.d.id), null);
- assert.equal((await listAudit(F)).filter((e) => e.action === 'bridge:module').length, 1, 'switched on once');
+ assert.equal(
+ (await listAudit(F)).filter((e) => e.action === 'bridge:module').length,
+ 1,
+ 'switched on once'
+ );
// when the owner switches it on again, the missing pair is linked
await setGuildModule(F, 'bridge', { enabled: true });
assert.equal((await run(pair)).linked, 1);