# Introduction

This book describes how to use the Matrix IRC bridge, giving an overview of functions for users and server administrators. If you believe there are errors or omissions in the book, please open an issue on GitHub or create a PR.

For an overview of the bridge, see the README.md

A community maintained wiki also exists which can be found here

The documentation is built from source and can be found in the GitHub repo

# Using the bridge

This chapter describes how to use the bridge and is intended for new or experienced Matrix users.

## Getting connected

The IRC bridge will dynamically connect you to IRC when you start interacting with an IRC bridged room. Some bridges, such as matrix.org, will connect you to IRC and join you to a channel the moment you join the Matrix room. Others will only connect you to IRC when you attempt to send a message to a Matrix channel.

Once you are connected to IRC, any joins you make to rooms connected to IRC will be replicated as joins to the IRC channel. By default your nickname will be `YourDisplayname-M`, but some bridges may alter this default by using a `[m]` suffix instead.

### Joining a channel

Joining a public channel over the bridge is as easy as joining an alias, for instance:

`#freenode_#python:matrix.org` maps to the `#python` channel on Freenode.

### Private Messaging

Sending a Private Message (PM) to an IRC user means starting a conversation with `@freenode_Alice:matrix.org`, which maps to the nickname `Alice` on Freenode.

If a PM is sent from the IRC side, it will either appear in your existing PM room or you will be invited to a new room.

The room alias and user formats may differ depending on the bridge you are using, so be sure to check with the server administrator if the above defaults are not working for you. Server administrators can check config.sample.yaml for instructions on how to change the templates for users and channels.

The wiki contains a list of public IRC networks including alias and user_id formats.

### Customising your experience

You may also want to customise your nickname or set a password to authenticate with services, you can do this by PMing the bridge bot user. E.g. the matrix.org freenode bridge user is `@appservice-irc:matrix.org`.

    !nick Alice
    !storepass MySecretPassword

More commands can be found in the Admin Room section.

## Authentication

Most networks provide a mechanism for one to authenticate themselves. You can do this manually by messaging NickServ or by providing a password to the bridge itself. See the Admin Room section for help.

### SASL authentication

SASL authentication is a new mechanism to authenticate with certain bridges, which requires you to also set a `!username` as well as password before authenticating. Bridges such as the libera.chat bridge require this authentication type. If you fail to authenticate, the bridge will notify you in the admin room.

## Message behaviours

Messages from IRC to Matrix appear in roughly as you'd expect them to. Emotes (`/me` text) are applied as Matrix supports it, and mIRC format colours are applied too. The IRC bridge makes an attempt to replace nicknames in sent messages with user mention "pills".

### Matrix -> IRC formatting

Messages from Matrix are often richer than their IRC counterparts, as Matrix has support for sending HTML, files, edits and replies.

Basic formatting is supported such as bolding and italics but other formats are discarded. Messages that exceed the maximum size of an IRC message or a message that contains newlines will be split into two or more messages. The configuration value `lineLimit` sets the maximum permittied number of messages to be sent before the whole message is stored as a file and sent as a link.

For example:

    > Half-Shot sent a long message: <https://matrix.org/_matrix/media/r0/download/matrix.org/fooobar/message.txt>

Files are sent as textual links such as:

    > Half-Shot uploaded an image: meme.gif (1358KiB) < https://matrix.org/_matrix/media/r0/download/half-shot.uk/fooobar/meme.gif >

Edits are sent with a fallback star:

    > Half-Shot: foo
    > Half-Shot: * foobar

Replies are sent with context:

    > Half-Shot: foo
    > <Half-Shot "foo"> bar

Reactions or other non-message events are not sent presently.

## Encryption

Presently, the bridge cannot work in an E2EE room. The bridge will leave any room that has encryption enabled. This is because the bridge does not know how to read encrypted events and so far no work has been started to support this. IRC is not capable of relaying E2E messages to IRC clients and as such the bridge would have to decrypt messages from Matrix and encrypt messages from IRC. As such, the team has chosen not to support encrypted Matrix rooms at this time.

# Admin Room

Most bridges will send you an invite to an admin room once you connectto control your connection to IRC, but larger bridges like matrix.org's Freenode bridge will not (you will need to start a conversation with the bot manually).

## Bot Commands

The admin room allows you to send commands to a room to manipulate your IRC session.

Some commands take a `[irc.example.net]` which lets you choose which IRC network to direct the request to, as some bridges host multiple IRC networks. Typically matrix.org bridges only host one network.

### `!join`

`!join [irc.example.net] #channel [key]`

Joins a channel on the IRC side and invites you to the Matrix room. This command will create a new portal room if a room doesn't exist. This is useful where you cannot with the alias syntax (e.g. the channel requires a key).

### `!cmd`

`!cmd [irc.example.net] COMMAND [arg0 [arg1 [...]]]`

Send a raw command through the IRC connection. This is useful for making MODE changes to yourself or to a channel if you have operator priviledges. Note that this command will not produce any response text, so commands will happen silently.

### `!whois`

`!whois [irc.example.net] NickName|@alice:matrix.org`

A powerful command to either lookup a nickname or a Matrix UserID and return information about that user.

### `!username`

`!username [irc.example.net] username`

Store the username you wish to identify with on the bridge. Please note that this must abide by the rules of RFC2812 which means the username should be lowercase, and contain only some special characters.

### `!storepass`

`!storepass [irc.example.net] passw0rd`

Store a password, or a `username:password` combination to be sent as a PASS command on connection to the server.

This action will store your password in encrypted form on the IRC bridge, so be sure to use a unique password for the IRC service.

If you are authenticating with a SASL enable bridge (such as libera.chat), you MUST specify a `!username` before you can authenticate.

To authenticate with your new settings, use `!reconnect`.

### `!reconnect`

`!reconnect [irc.example.net]`

This command will reconnect you to IRC without kicking you from rooms. This is useful if you need to authenticate after setting your password (and username).

### `!removepass`

`!removepass [irc.example.net]`

Remove your stored password, will NOT reconnect you.

### `!listrooms`

`!listrooms [irc.example.net]`

List all the Matrix rooms that you are joined to which are also connected to IRC.

### `!quit`

QUITs you from all connected networks AND kicks you from all IRC rooms (except DMs). This is to avoid leaking history to your Matrix account while not being visible to IRC users. This command will not remove your password or stored data with the bridge. Ask the owner of the bridge to remove that data for you.

### `!nick`

`!nick [irc.example.net] nick`

Set your nickname for your IRC conenction and persist it across restarts. If the nickname clashes with another user's nickname, this will fail.

### `!feature`

`!feature feature-name [true/false/default]`

Enable or disable a feature for your account. Set it to `true` to enable the feature, `false` to disable it, or `default` to use the default based upon the bridge config.

Currently, the features you can use are:

- `mentions` - Determine whether IRC users can mention you on the IRC bridge. Note, that this will only stop mention text being turned into pills. See this section for an explanation of this feature.

### `!bridgeversion`

Prints the current version of the bridge.

The bridge bot allows you to control your IRC connection through various bot commands. Some commands are reserved for bridge administrators, which can be configured in the config file.

### `!plumb`

`!plumb !room:example.com irc.network.net #channel`

This command only works for bridge administrators

This command allows you to plumb a IRC channel into a room without using the HTTP provisioning API. This command does NOT validate that you have permission to do this on the IRC channel so please take care to ensure that the IRC channel is aware of your actions.

You must invite the bridge bot into the Matrix room for this to work.

### `!unlink`

`!unlink !room:example.com irc.network.net #channel`

This command only works for moderators of a bridged Matrix room and bridge administrators

This command allows you to unlink a IRC channel from a room. Users are only able to remove links for rooms they are a moderator in (power level of 50 or greater). Administrators of the bridge are able to remove links from any room.

### `!help`

Prints a list of commands for the bridge.

## Room Commands

Some commands to the IRC bridge can be sent inline into any bridged Matrix room. This is handy if you are also bridging to Telegram or Slack and do not have the ability to DM the bridge bot in order to make changes to your session.

## `!irc nick $nickname`

Change your nickname on the IRC server that the room is connected to.

# Room Configuration

You can now configure certain options on a per-room basis from within your Matrix client. Currently this requires a bit of technical know-how as no clients expose an interface to changing the bridge configuration.

## The `org.matrix.appservice-irc.config` event

Not all bridges support all configuration options listed. Check with the bridge administrator before creating an issue.

The bridge allows room moderators to create a state event in the room to change the way the bridge behaves in that room.

In Element you can modify the room state by:

- Opening the room you wish to configure.
- Typing `/devtools`.
- Click Explore Room State.
- Look for the `org.matrix.appservice-irc.config` event.
- You should be able to click Edit to edit the content, and then hit Send to adjust the config.

If an event does not exist yet, you can instead do:

- Typing `/devtools`.
- Click Send Custom Event.
- Click the Event button to change the type to a State Event.
- The event type must be `org.matrix.appservice-irc.config`
- The state key can be left blank.
- Enter the `Event Content` as a JSON object. The schema is described in the following section.
- You may now hit Send to apply the config.

## Configuration Options

### `lineLimit`

Type: `number`

This allows you to modify the minimum number of lines permitted in a room before the message is pastebinned. The setting is analogous to the `lineLimit` config option in the bridge config file.

### `allowUnconnectedMatrixUsers`

Type: `boolean`

Some IRC networks require that Matrix users must be joined to the IRC channel before any messages can bridge into the room. You can override this by setting this key to `true`.

# IRC Modes

This chapter explains how various IRC channel modes are interpteted by the bridge, and how you can best configure your channels to work well with the bridge.

Note: While the bridge tries to follow the RFCs where possible, due to the somewhat fragmented nature of IRC the bridge is designed for maximum compatibility with Freenode's IRCd.

## User modes to power levels

User modes are mapped to certain power levels on Matrix. For those unaware, Matrix power levels typically range between 0-100 where zero represents a user that may only speak and 100 is an admin of the room (although these are modifiable).

By default the bridge maps users like so

    # taken from config.sample.yaml
    modePowerMap:
        o: 50
        v: 1

An operator on the IRC side of the bridge will be given moderator privileges (PL50) and a voiced user will be given PL1. In `+m` (moderated) rooms, users who are not voiced cannot speak and so the Matrix room will not allow users with PL0 (that is, without +v) to speak.

The IRC bridge admin can customise this power level mapping to however they see fit.

## Bans, Invite only and Registered only (+b / +i / +r)

The IRC bridge will kick a Matrix user on join if they are not able to join the IRC channel. This means if the IRC user is banned, the room is invite only (and the user has not been invited) or the channel is registered only then the user will not be able to join it. A reason is given in the Matrix ban, and a more verbose error is given in the user's admin room.

### Invite exemption (+I)

Some communties prefer to keep their channels closed but allow the bridge to access the channel. It is trivial to do this by using the `+I` channel mode. The format is the same as an extban.

For example to allow matrix.org bridge users to access your invite-only channel, you would do:

    /mode #the-secret-cookies +I !@gateway/shell/matrix.org/*

## +s (Secret)

By default the IRC bridge will automatically insert any newly joined rooms into the homeserver's room directory. The +s mode will mark the channel as secret and the bridge will not show it in the directory. The room will still be joinable however.

## Key protected (+k)

If a channel is protected by a key, it cannot be entered by joining via an alias. Instead you may join by using the `!join` command. Be aware that the bridge purposefully does not store channel keys in the database as a security precaution so you should be expected to do this again on bridge restart.

## Channel Forwarding (+f)

Channel forwarding is presently unsupported, see https://github.com/matrix-org/matrix-appservice-irc/issues/214 for information and updates.

# Bridge Setup

This guide is written for server administrators who would like to set up their own IRC bridge to one or more networks.

## Before setting up

We recommend using Node.JS `v14` or greater when setting up the bridge, as we use `worker_threads` to handle some of the traffic for larger bridges.

If you wish to use Node.JS v10, you should enable the `--experimental-worker` on the commandline. Please note that we offer no support for Node 10.

You should also ensure you have a recent Matrix homeserver that you have permission to bridge to. This can either be your own, or one that you have the ability to setup Application Services with.

Finally you should seek permission from the operator of the bridged IRC network before running this bridge. Bridging may be against the IRC network's Terms of Use.. Failure to do so may get your bridge banned and your IP address blocked by the IRC network. Networks like Freenode will only allow 3 IRC connections from a single IP, so you should ask them for permission before bridging.

## 1. Installation

### Install from git (preferred)

    git clone https://github.com/matrix-org/matrix-appservice-irc.git
    cd matrix-appservice-irc
    git checkout master # or 0.x.x to pin to a version
    npm i

The bridge can now be started by: `node app.js`

### Global Install

    # --global requires super user on most systems
    $ npm install matrix-appservice-irc --global

### Docker

The bridge has a Docker image.

## 2. Configuration

The bridge must be configured before it can be run. This tells the bridge where to find the homeserver and how to bridge IRC channels/users.

- Copy `config.sample.yaml` to `config.yaml`.
  - For Docker, you will want to make a directory called `data` and store the `config.yaml` inside.
- Modify `config.yaml` to point to your homeserver and IRC network of choice.

The sample config has detailed information about each option. Please read them carefully.

## 3. Database

The bridge comes with support for either PostgreSQL or NEDB. PostgreSQL is preferred as it is faster, easier to handle than flat files and allows you to inspect the state of it while the bridge is running.

Setting up PostgresSQL for the bridge is as easy as doing:

    -- Authenticate with postgres, then
    psql 'postgres://dbstring'
    CREATE DATABASE ircbridge;
    CREATE USER ircbridge WITH PASSWORD 's3cr3t';
    GRANT ALL ON DATABASE ircbridge TO ircbridge;
    -- Then modify your config.yaml to include the database connection string.

## 4. Registration

The bridge needs to generate a registration file which can be passed to the homeserver to tell the homeserver which Matrix events the bridge should receive.

Execute the following command:

    node app.js -r -f appservice-registration-irc.yaml -u "http://where.the.appservice.listens:9999" -c config.yaml -l my_bot

Change `-u "http://localhost:8090"` to whereever your Matrix server can contact this IRC bridge. By changing the option `-l my_bot` you can modify the localpart of the bridge bot user. It contacts Matrix users of your bridge to control their usage of the bridge (e.g. to change their nickname).

You should get something like:

    id: irc
    hs_token: 82c7a893d020b5f28eaf7ba31e1d1091b12ebafc5ceb1b6beac2b93defc1b301
    as_token: a66ae41f82b05bebfc9c259135ce1ce35c856000d542ab5d1f01e0212439d534
    namespaces:
      users:
        - exclusive: true
          regex: '@irc_.*:yourhomeserverdomain'
      aliases:
        - exclusive: true
          regex: '#irc_.*:yourhomeserverdomain'
    url: 'http://localhost:9999'
    sender_localpart: appservice-irc
    rate_limited: false
    protocols:
      - irc

For Docker, copy the above to `data/appservice-registration-irc.yaml` and replace as necessary.

More information on the CLI args can be found by running `$ node app.js --help`

This will create a registration YAML file. Edit your homeserver config file (e.g. `homeserver.yaml`) to point to this registration file:

    # homeserver.yaml
    app_service_config_files: ["appservice-registration-irc.yaml"]

## 5. Running

Finally, the bridge can be run using the following command:

    $ node app.js -c config.yaml -f appservice-registration-irc.yaml -p 9999

Or for Docker:

    # Remember to expose ports for metrics, debug API if you need to.
    docker run --volume $PWD/data:/data --publish 9999 matrixdotorg/matrix-appservice-irc

# Administrators Guide

This document describes useful information when administering a bridge.

## Advanced Configuration

Typically the information given in Bridge Setup is good enough for small to medium sized bridges, but if you expect to handle extremely heavy IRC or Matrix traffic then it might be looking at tweaking some of these options.

It should be noted that often the homeserver you have connected to the bridge will play a greater role in the percieved performance of your bridge, as it is usually the bottleneck in either handing (federated) traffic towards the bridge, or persisting and federating traffic from the bridge to users.

It is strongly advised that if you are suffering from performance issues, you should identify if there are problems with your homeserver first.

### Quit Debouncing

Setting documentation

This setting handles the "debouncing" of quits when the server sees an extreme amount of QUIT events from the IRC server. IRC servers often suffer from netsplits which manifest as many QUITs. The IRC bridge will handle one QUIT per room, so 5 users quitting from 5 rooms would manifest as 25 events. This can quickly overwhelm the bridge.

The quit debouner is often overkill for smaller bridges, but if you find that the bridge becomes overwhelmed and unresponsive after a netsplit then it enabled.

### Membership syncing

Setting documentation

Typically it's wise to leave this setting on by default, as populating the memberlists on both sides of the bridge leads to a more pleasant experience for users. However as the setting requires the constant adjustment of the member lists on both sides of the bridge it can be more intensive on homeserver resources. You can also adjust the membership settings of individual rooms or channels to lessen the effect.

## Hot Reloading

The bridge supports hot-reloading of the configuration file by sending a `SIGHUP` signal. Some configuration keys will not be reloaded as they are required to be static to avoid bridge instability. Unsupported keys are marked in config.sample.yaml. Hot reloading is useful as restarting the bridge will drop all IRC connections, so it's worth using this method to avoid disruption.

Typically the process is as follows.

    $ ps -A | grep 'node'
    31960 pts/7    00:00:13 node
    # and then send the SIGHUP signal
    $ kill -SIGHUP 31960

The logs will then mention `Bridge config was reloaded, applying changes` which confirms that the reload has taken place.

## Enforcing Matrix users to be connected to IRC

When configured to do so, the IRC bridge typically tries to join all Matrix users to the IRC channels to avoid Matrix users being able to read a conversation without being visible to IRC users. However since it is not always possible to ensure this happens in a timely manner, there is a safety net feature.

Administatators can choose the default behaviour of allowing messages to continue to be bridged to the room (potentially leaking history) or enforcing strict rules to ensure that all Matrix users are joined before anyone can read messages. This can be enabled by setting

    ...
    membershipLists:
      global:
        ircToMatrix:
          requireMatrixJoined: true

in the config. Users can choose to disable this on a per-room basis by modfiying their room config options, if the bridge permits it.

## Metrics / Grafana

The bridge includes a prometheus compatible metrics endpoint which can be used to inspect the state of the bridge. The repository also includes a grafana dashboard; more information can be found in GRAFANA.md.

## The Debug API

The Debug API allows you to perform administrative actions on the bridge such as killing a IRC connection, inspecting connected users or unbridging a room. The API is currently loosely documented over in the GitHub wiki.

This is not enabled by default.

# IRC Operators

This chapter describes useful information about the bridge for IRC operators or IRC users.

The IRC bridge provides each Matrix user with one IRC connection in order to bridge them "natively" into the IRC network, as so they can largely be treated as real users. Due to the 1:1 connection system, it is often useful that the IRCD network provides the bridge host with a more relaxed ILINE limit depending on the number of Matrix users they'd expect to use the bridge.

### The Matrix experience

When a Matrix room is bridged to IRC, all users (by default) on the Matrix side will be provided with a connection to the room and will show up in the user list on IRC. The IRC users will also appear as "ghosts" on the Matrix side, bearing a Matrix ID like `@irc_alice:matrix.org`. This allows a "native" feeling so that users do not have to worry about the complexities of the protocols.

However as with all bridges, the native feeling can catch IRC or Matrix users unaware when things do not bridge well (such as replies/threading or reactions).

### The [m]/-M suffix

By default, the IRC bridge will append a `-M` to nicks for Matrix users. This is to avoid clashes with a users real identity on IRC as well as to highlight that the users are on the bridge (and may not even know the conversation is bridged to IRC). The user has the option to change this by going to the bot and sending a `!nick` command, so the suffix should not be used as a blanket detection method.

### Whois information

The bridge sets various bits of information about users:

The realname of a user will be their MxID. By default this will look like:

    * [Half-Shot] (half-shoth@gateway/shell/matrix.org/x-foo): @Half-Shot:half-shot.uk
    * [Half-Shot] moon.freenode.net :Atlanta, GA, US
    * [Half-Shot] is using a secure connection
    * [Half-Shot] is logged in as Half-Shot
    * [Half-Shot] End of WHOIS list.

### Portals and Plumbed

A Matrix room can be connected to a IRC network in one of two ways:

- A portal room, which is a Matrix room created by the bridge on demand when a Matrix user attempts to join an alias that does not yet exist. E.g. `#freenode_#myproject:matrix.org`. The bridge will hold power over this room and grant moderator status (half-power) to any IRC operators or Matrix users with IRC ops in the room.
- A plumbed room (also known as provisioning). A Matrix user may create a room ahead of time for their community and later on decide to "plumb in" IRC users to that room. They can do this via an interative UI in Element, via the `!plumb` command or even via a HTTP endpoint. If done interatively, the bridge has a verification process to ensure the user on the Matrix side has the blessing of the IRC ops first. However, it's possible for the IRC bot to lack kick abilities in the room so kicks and bans may not be bridged both ways.

(This is explained in more depth at matrix.org)

Additionally, a channel may be connected to one portal and multiple plumbed rooms without issue as the messages from Matrix users are replicated to the other rooms for them. We typically do not recommend multiple points of entry to the channel due to the obvious confusion this causes.

### Connection failure

If a Matrix user fails to join a channel due to a ban, they are kicked from it. If the Matrix user fails to get a connection to IRC at all, they are also kicked from any rooms they are part of. The exception to this rule is if the bridge bot (which does the kicking) lacks permission to kick members of the room.

### Line limits

The IRC bridge allows admins to configure a maximum amount of lines that can be sent at a time to a channel by a Matrix user. The Matrix spec allows events to be sent by users up to 65k in size, so with some margin for event padding, a message could feasibly be over 64k in size. The Matrix spec has no limit on how many lines a single message can have so to avoid this issue the bridge will "pastebin" any overly large message rather than send the message line by line.

This can be confusing for IRC users, so we typically try to have a sensible limit to line count. By default the bridge only pastebins a message that is over 3 lines in length to avoid problems, but this can be increased at the discretion of the bridge admin.

### History protection

Matrix is naturally history preserving, so that any message sent to a Matrix room is sent to all participating users/servers. They will be able to read these messsages for as long as they are joined to the room.

Bridged IRC rooms do not share history to Matrix users from before they have joined by default, but history visibility can be changed by users with the correct power level on Matrix.

The bridge can also be configured to stop bridging all traffic from a channel to Matrix if it cannot garuntee that a Matrix user is joined to the IRC channel, which is usually a step of last resort should the bridge have failed to connect them. See the administrators guide.