Building a Bridge
@colibri-social/bridge-core does the Colibri half of a bridge. It signs requests, follows the channels admins link or open to it, maps messages between the two services, retries failed writes, and skips its own echoes. You write a connector, which does the other service’s half.
The Colibri bridge for Discord is built this way. Its connector lives in packages/bridge-discord and makes a good reference for a full implementation.
How bridged messages are written
Section titled “How bridged messages are written”A bridge is a separate process with its own DID and signing key. It talks to the AppView over the network and has no account on a PDS.
When someone posts on the other service, the bridge calls social.colibri.beta.bridge.postMessage. The AppView checks that the registration belongs to the calling bridge, is enabled, and links or opens the channel. It then writes the message into the channel as the Space, through the same writer the Space uses for its own records.
Every bridged record carries a bridged attribution with the author’s name, avatar and id on the other service:
{ "text": "Hello from the other side", "bridged": { "registration": "3lzy2ji4nms2k", "platform": "discord", "remoteId": "80351110224678912", "name": "Nelly", "remoteMessage": "1276183740532310057" }}The AppView honours bridged only on records the Space itself wrote. It ignores the field on a record from any other author, so a member can’t pose as someone on another service.
Reactions and threads from the other service are written the same way, with addReaction and createThread. Avatars and attachments are uploaded to the Space’s repo with uploadBlob. When an author’s avatar changes or disappears on the other service, bridge-core calls replaceAvatar, which swaps the avatar on that author’s earlier messages and threads.
Messages going the other way arrive at the bridge over social.colibri.beta.sync.subscribeEvents, the same WebSocket stream clients use. The bridge posts them on the other service under the Colibri author’s name and avatar. Events for its own writes come back on that stream with its registration in the attribution, and the bridge skips them.
The Bridge Reference lists every field of the attribution.
Requirements
Section titled “Requirements”- Node.js 22.13 or later. The mapping store uses the built-in
node:sqlitemodule. - A DID for the bridge, with a secp256k1 signing key in its DID document.
- A place to run a long-lived process. The bridge keeps a WebSocket open to the AppView.
Install the package
Section titled “Install the package”npm install @colibri-social/bridge-coreCreate an identity
Section titled “Create an identity”The bridge signs every request to the AppView with service auth, using its own DID as the issuer. Both did:web and did:plc work.
-
Generate a signing key:
import { generateSigningKey } from "@colibri-social/bridge-core";const { privateKeyHex, publicDidKey } = await generateSigningKey();Store
privateKeyHexas a secret. Anyone who has it can act as your bridge. -
Publish a DID document with the public key. For a
did:web, serve the output ofbridgeDidDocument()at/.well-known/did.jsonon the bridge’s domain:import { bridgeDidDocument } from "@colibri-social/bridge-core";const document = bridgeDidDocument("did:web:bridge.example.com", publicDidKey);For a
did:plc, addpublicDidKeyas theatprotoverification method.
Write a connector
Section titled “Write a connector”Every connector implements Connector. The bridge calls start() once with a BridgeContext, which the connector keeps for the rest of its life.
A connector that relays rooms on the other service to linked Colibri channels implements RelayConnector, which adds two methods:
interface Connector { readonly platform: string; start(context: BridgeContext): Promise<void>; stop(): Promise<void>;}
interface RelayConnector extends Connector { listRooms(remoteSpace: string): Promise<RemoteRoomInfo[]>; sendMessage(message: OutboundMessage): Promise<string>;}A connector that works through commands in Colibri channels implements OpenChannelConnector instead, or as well. See Command-driven bridges.
platform is a short, lowercase name for the service (e.g. discord). It’s stored on every record the bridge writes.
listRooms() returns the rooms in a remote space that admins can link. A remote space is whatever groups rooms on the other service, such as a Discord server or a Slack workspace. Both are identified by strings that only your connector interprets.
sendMessage() posts a Colibri message on the other service and returns its id there. The bridge stores that id and passes it back for later edits, deletions and replies.
An OutboundMessage carries the message’s attachments and its link previews as embeds. Each attachment has a url, mimeType, and optionally a name, size, alt, spoiler, width and height. The URLs are signed for your bridge and stay valid for at least an hour. Each embed has a url, and optionally a title, description, siteName, imageUrl and themeColor. Previews the author removed are left out. An OutboundEdit carries the edited markdown and embeds.
Receiving messages
Section titled “Receiving messages”When something happens on the other service, pass it to context.emit():
context.emit({ type: "message", remoteSpace: "workspace-1", remoteRoom: "general", id: "msg-42", author: { id: "user-7", name: "Nelly", avatarUrl: "https://example.com/nelly.png" }, markdown: "Hello **Colibri**",});A message event can carry attachments, each with a url the bridge can download, and optionally a name, size, alt and spoiler. The bridge uploads them to the Space’s repo. A file it can’t download, or one over the size limit, is left out of the message and logged as bridge.attachment.dropped.
The other event types are messageEdit, messageDelete, reactionAdd, reactionRemove, threadCreate, threadUpdate and threadDelete. Emit roomsChanged when rooms are created, renamed or deleted, so the room list admins see stays current.
Text crosses the bridge as Markdown. The bridge converts it to and from Colibri facets. Convert the other service’s own formatting to Markdown before emitting, and back again in sendMessage().
Emit every event, including ones in rooms nobody linked. The bridge drops events for unlinked rooms and events it has already relayed. Your connector must drop its own posts, though. Filter out anything the connector itself sent before calling emit().
Threads
Section titled “Threads”Events in a thread carry the thread’s id as remoteThread, and remoteRoom stays the room the thread belongs to. A message event can also carry thread, with the thread’s id, its name, and the id of the message it was opened from as anchor:
context.emit({ type: "message", remoteSpace: "workspace-1", remoteRoom: "general", remoteThread: "thread-9", thread: { id: "thread-9", name: "Launch plans", anchor: "msg-42" }, id: "msg-43", author: { id: "user-7", name: "Nelly" }, markdown: "First!",});The bridge opens the thread in Colibri the first time it sees it, so threads that existed before a room was linked are picked up too. A message event with a remoteThread and no thread is dropped until the thread is known.
Everything the bridge sends your connector for a thread carries the same remoteThread.
References
Section titled “References”Mentions of people and rooms cross the bridge as Markdown links with a bridge: scheme:
[@Nelly](bridge:user/user-7) posted in [#general](bridge:room/general)The bridge turns a bridge:user link into a mention of that person, and a bridge:room link into a mention of the Colibri channel linked to that room. A reference it can’t resolve keeps its text and loses the link. Mentions of people on your service and of linked channels reach your connector in the same form. Convert both to and from your service’s own mention syntax.
Forwards
Section titled “Forwards”A message event can carry forward, with the forwarded message’s markdown, attachments and createdAt, and its id as remoteMessage. When the bridge relayed that message earlier, it posts a Colibri forward. Otherwise it quotes the forwarded text below the message.
An OutboundMessage for a Colibri forward carries forward too, with the copied markdown and attachments, plus source when the original was relayed.
History
Section titled “History”Implement HistoryConnector to let admins import a room’s earlier messages. The bridge starts an import when a link carries a backfill request it hasn’t finished, and calls three methods:
roomCreatedAt(room)returns when the room was created, as the start of an import with nosince.listThreads({ remoteSpace, remoteRoom, since, until })returns the room’s public threads opened in that range, archived ones included. Each has anid,name,anchor,authorandcreatedAt.fetchHistory({ remoteSpace, remoteRoom, remoteThread, since, until, after })returns the next messages, oldest first.afteris the id of the last message the bridge handled. Return an empty array when there are no more.
async fetchHistory(request: HistoryRequest): Promise<HistoryMessage[]> { const messages = await this.api.messages(request.remoteThread ?? request.remoteRoom, { after: request.after, since: request.since, limit: 100, }); return messages.map((message) => ({ remoteSpace: request.remoteSpace, remoteRoom: request.remoteRoom, id: message.id, author: { id: message.userId, name: message.userName }, markdown: message.text, createdAt: message.sentAt, }));}A HistoryMessage has the same fields as a message event, with createdAt required. Leave out messages your connector wrote itself.
The bridge imports each thread when its walk through the room reaches the thread’s createdAt, then carries on with the room. It saves its place in the store after every batch, and resumes from there after a restart. Progress goes back to the AppView as it runs, so admins can follow it.
Optional capabilities
Section titled “Optional capabilities”Implement these methods to relay more than new messages. The bridge detects each one and skips that kind of event when it’s missing.
| Interface | Methods | Relays |
|---|---|---|
EditingConnector |
editMessage() |
Edits |
DeletingConnector |
deleteMessage() |
Deletions |
ReactingConnector |
addReaction(), removeReaction() |
Reactions |
ThreadingConnector |
createThread(), renameThread(), archiveThread() |
Threads opened, renamed and deleted in Colibri |
ModeratingConnector |
removeMessage() |
Hidden messages from your service, when an admin turns on moderation mirroring |
HistoryConnector |
fetchHistory(), listThreads(), roomCreatedAt() |
Earlier messages, when an admin imports history |
Pairing
Section titled “Pairing”Pairing starts on the other service. Give admins there a way to ask for a code, such as a command, and call context.pair():
const { code, expiresAt } = await context.pair({ remoteSpace: "workspace-1", remoteSpaceName: "Nelly's Workspace",});Show the code only to the admin who asked for it. Check that they’re an admin on the other service first. Anyone who can get a code can offer to relay that remote space to a Space.
context.linkedRooms(remoteSpace) lists the Colibri channels currently linked to a remote space, for a status command.
Disconnecting
Section titled “Disconnecting”Give admins on the other service a way to disconnect as well. context.connections(remoteSpace) lists the Spaces a remote space is connected to, each with its community DID, communityName and registration. Pass one of those DIDs to context.disconnect() to leave that Space, or leave it out to disconnect the remote space from every Space:
const left = await context.disconnect("workspace-1", "did:plc:4z3bq7rjmuyqfdeslq7vfwdk");disconnect() returns how many registrations it deleted. A registration that an admin in Colibri revoked in the meantime counts as deleted.
When your bridge is removed from a remote space, emit a spaceLeft event. It disconnects the remote space from every Space:
context.emit({ type: "spaceLeft", remoteSpace: "workspace-1" });Command-driven bridges
Section titled “Command-driven bridges”A command-driven bridge has no remote rooms and no pairing code. It keeps its own mapping between channels, and admins set it up with commands typed in a Colibri channel. A bridge that joins several services into one conversation works this way.
Installing
Section titled “Installing”Admins add the bridge to a Space by its handle or DID, which calls install. The bridge’s DID document only needs the atproto signing key that bridgeDidDocument() writes. The bridge receives a bridgeEvent and finds the registration in getConfiguration. Its remoteSpace is the Space’s DID, and its platform is external.
Admins then pick the channels the bridge can use under Let the bridge read and reply. These are the registration’s open channels, stored in channels. Threads beside an open channel are open to the bridge too, unless they’re limited to some roles or members. Tell admins in your setup instructions which channels to pick before they run your commands.
The connector
Section titled “The connector”A command-driven connector implements OpenChannelConnector. It needs no listRooms() or sendMessage():
interface OpenChannelConnector extends Connector { openMessage(message: OpenChannelMessage): Promise<void>;}A connector can implement RelayConnector and OpenChannelConnector together. A channel that is both linked and open then relays as usual and also reaches openMessage().
Receiving messages
Section titled “Receiving messages”The bridge calls openMessage() for every new message in an open channel or a thread beside one. Imported history and messages your bridge posted itself don’t reach it. An OpenChannelMessage has these fields:
community,registrationandchannel: the Space, the registration, and the open channel.thread: the thread’s space, when the message was posted in a thread beside the channel.didandrkey: the message’s record. Pass both back to reply to the message, react to it, or look it up.author: the author’sdid,name,handleandavatarUrl, plus theirstandingin the Space.markdown: the text, converted from Colibri facets.replyTo: thedidandrkeyof the message this one replies to.attachmentsandembeds: the files and link previews, in the same shape as on anOutboundMessage.forward: the forwarded message’smarkdownandattachments, plus itssource(channel,didandrkey).createdAtandupdatedAt.
author.standing indicates whether the author is a member of the Space and its owner, which roles they hold, highest first, and their effective permissions in the open channel. An owner holds every permission. Check it before running an admin command:
async openMessage(message: OpenChannelMessage) { if (message.markdown.trim() !== "!bridge setup") return;
if (!message.author.standing.permissions.includes("community.manage")) return;
await this.setUp(message.community, message.registration, message.channel);}The bridge caches each standing for 60 seconds. When the lookup fails, the message still arrives, with a standing that holds no roles or permissions.
Other events
Section titled “Other events”Implement any of these methods to receive more than new messages. The bridge detects each one and skips that kind of event when it’s missing.
| Method | Called when |
|---|---|
openEditMessage(edit) |
A message is edited. edit has the same fields as an OpenChannelMessage. |
openDeleteMessage(target) |
A message is deleted. target has the location fields, did and rkey. |
openRemoveMessage(target) |
A moderator hides a message. target has the same fields as for a deletion. |
openAddReaction(reaction), openRemoveReaction(reaction) |
A reaction is added or removed. reaction names the reacted message with did and rkey, plus the emoji, the reacting actor’s DID, and customEmoji for a custom emoji. |
openCreateThread(thread), openUpdateThread(thread), openDeleteThread(thread) |
A thread beside an open channel is opened, renamed or deleted. thread has the thread’s space as thread, its name, and the anchor message it was opened from. A deleted thread has no name or anchor. The bridge follows new threads by itself. |
openChannelsChanged(change) |
The bridge was installed in a Space or removed from it, or admins updated its open channels. change holds the current channels and the added and removed ones. |
Events caused by your own openEmit() calls don’t come back to your connector. openChannelsChanged() isn’t called for the registrations the bridge finds when it starts. Call context.openChannels(community, registration) in start() to read those.
Writing to open channels
Section titled “Writing to open channels”Pass writes to context.openEmit(). Every event names the community, registration and channel, plus thread to write into a thread beside the channel. Unlike emit(), it returns a promise, which rejects when the channel isn’t open to the registration or the AppView refuses the write:
const { rkey, dropped } = await context.openEmit({ type: "message", community: message.community, registration: message.registration, channel: message.channel, author: { id: "bridge", name: "Bridge", avatarUrl: "https://bridge.example.com/avatar.png" }, markdown: "This channel is connected.", replyTo: { did: message.did, rkey: message.rkey },});The author’s avatar is uploaded to the Space’s repo and reused while avatarUrl stays the same. dropped lists the attachments that couldn’t be uploaded, each with a reason of tooLarge, fetchFailed or uploadFailed, so your connector can tell the sender.
| Event type | Fields | Result |
|---|---|---|
message |
author, markdown, replyTo, attachments, forward |
rkey of the new message and dropped |
messageEdit |
rkey, markdown |
|
messageDelete |
rkey |
|
messageRemove |
did, rkey, reason |
|
reactionAdd |
did and rkey of the message, author, emoji |
rkey of the reaction |
reactionRemove |
rkey of the reaction |
|
threadCreate |
name, author, anchor |
thread, the new thread’s space |
threadUpdate |
thread, name |
|
threadDelete |
thread |
messageEdit and messageDelete only work on messages your bridge posted. messageRemove hides someone else’s message after a moderator removed its copy on another service, and only works while an admin has turned on moderation mirroring. A forward holds the forwarded markdown, its attachments and createdAt, and the source message’s channel, did and rkey when it’s in Colibri. Without a source, the bridge quotes the forwarded text below the message.
openEmit() calls don’t wait for the events queued for your connector. Await them inside openMessage() without blocking the bridge.
Reading the Space
Section titled “Reading the Space”The context has these methods for command-driven bridges:
context.channels(community, registration)lists the Space’s text channels that every member can read, aschannelViewobjects, including ones that aren’t open to the bridge. Call it to show a list of channels in a setup command or to check a channel’s name.context.openChannels(community, registration)returns the registration’s open channels.context.message({ community, registration, channel, thread, did, rkey })fetches one message as anOpenChannelMessage, ornullwhen it’s gone.context.history({ community, registration, channel, thread, before, limit })returns earlier messages, newest first.beforeis therkeyof a message to start below.limitdefaults to 50 and stops at 100.context.member({ community, registration, channel, did })returns the standing of any account in the Space.
Run the bridge
Section titled “Run the bridge”Create a Bridge with a client, your connector, and a store, then start it:
import { Bridge, ColibriClient, createServiceAuthSigner, resolveAppviewDid, SqliteBridgeStore,} from "@colibri-social/bridge-core";import { ConsoleConnector } from "./connector.js";
const appviewUrl = "https://spaces-api.colibri.social";
const bridge = new Bridge({ client: new ColibriClient({ appviewUrl, appviewDid: await resolveAppviewDid(appviewUrl), signer: await createServiceAuthSigner(process.env.BRIDGE_DID!, process.env.BRIDGE_SIGNING_KEY!), }), connector: new ConsoleConnector(), store: new SqliteBridgeStore("./bridge.sqlite"),});
await bridge.start();process.once("SIGTERM", () => bridge.stop());The store maps message ids between the two services and remembers uploaded avatars. Keep its file on persistent storage. A bridge that loses it cannot edit or delete the messages it relayed before.
Pass a log option to receive structured log lines. The bridge is silent without one.
The bridge opens its event socket on the fastest Colibri node and moves to another node when that one goes offline for an update. While the network is read-only, it holds writes and sends them once Colibri takes writes again. See Nodes for the details.
Example: a console connector
Section titled “Example: a console connector”The connector below relays a single linked room to the terminal. Every line typed becomes a message from console, and every Colibri message is printed. It’s enough to pair a Space and watch messages flow in both directions.
import { createInterface } from "node:readline";import type { BridgeContext, OutboundMessage, RelayConnector, RemoteRoomInfo,} from "@colibri-social/bridge-core";
const SPACE = "console";const ROOM = "terminal";
export class ConsoleConnector implements RelayConnector { readonly platform = "console"; private input = createInterface({ input: process.stdin }); private sent = 0;
async start(context: BridgeContext): Promise<void> { this.input.on("line", async (line) => { if (line === "/pair") { const { code } = await context.pair({ remoteSpace: SPACE, remoteSpaceName: "Terminal" }); console.log(`Pairing code: ${code}`); return; } context.emit({ type: "message", remoteSpace: SPACE, remoteRoom: ROOM, id: `line-${Date.now()}`, author: { id: "console", name: "Console" }, markdown: line, }); }); }
async stop(): Promise<void> { this.input.close(); }
async listRooms(): Promise<RemoteRoomInfo[]> { return [{ id: ROOM, name: "terminal", kind: "text" }]; }
async sendMessage(message: OutboundMessage): Promise<string> { console.log(`${message.author.name}: ${message.markdown}`); this.sent += 1; return `sent-${this.sent}`; }}Type /pair, redeem the code in your Space’s settings, and link a channel to terminal. Pairing a Bridge covers the Colibri side.
Limits
Section titled “Limits”- The AppView accepts about 5 writes per second from each registration, with bursts up to 30.
bridge-corewaits and retries when it’s rate limited. - History imports have their own limit of 20 messages per second, with bursts up to 100.
- Attachments and avatars are uploaded to the Space’s repo. Each file can be up to 20 MB, and avatars up to 1 MB.
- Message text is capped at 2048 characters.
bridge-coretruncates longer text.
The Bridge Reference lists every method and error.