Skip to content

Commit

Permalink
Add support for signalv2
Browse files Browse the repository at this point in the history
  • Loading branch information
tulir committed Jun 17, 2024
1 parent 593ad0b commit e2b4b94
Show file tree
Hide file tree
Showing 5 changed files with 273 additions and 5 deletions.
6 changes: 6 additions & 0 deletions api/gitlab/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"os"
"path/filepath"
"runtime"
"strings"

"github.com/fatih/color"
"github.com/schollz/progressbar/v3"
Expand Down Expand Up @@ -173,6 +174,8 @@ func needsLibolmDylib(bridge string) bool {

func DownloadMautrixBridgeBinary(ctx context.Context, bridge, path string, noUpdate bool, branchOverride, currentCommit string) error {
domain := "mau.dev"
v2 := strings.HasSuffix(bridge, "v2")
bridge = strings.TrimSuffix(bridge, "v2")
repo := fmt.Sprintf("mautrix/%s", bridge)
fileName := filepath.Base(path)
ref, err := getRefFromBridge(bridge)
Expand All @@ -186,6 +189,9 @@ func DownloadMautrixBridgeBinary(ctx context.Context, bridge, path string, noUpd
if err != nil {
return err
}
if v2 {
job += " v2"
}

if currentCommit == "" {
log.Printf("Finding latest version of [cyan]%s[reset] from [cyan]%s[reset]", fileName, domain)
Expand Down
239 changes: 239 additions & 0 deletions bridgeconfig/signalv2.tpl.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
# Network-specific config options
network:
# Displayname template for Signal users.
displayname_template: {{ `'{{or .ContactName .ProfileName .PhoneNumber "Unknown user" }}'` }}
# Should avatars from the user's contact list be used? This is not safe on multi-user instances.
use_contact_avatars: true
# Should the bridge sync ghost user info even if profile fetching fails? This is not safe on multi-user instances.
use_outdated_profiles: true
# Should the Signal user's phone number be included in the room topic in private chat portal rooms?
number_in_topic: true
# Default device name that shows up in the Signal app.
device_name: {{ or .Params.device_name "Beeper (self-hosted, v2)" }}
# Avatar image for the Note to Self room.
note_to_self_avatar: mxc://maunium.net/REBIVrqjZwmaWpssCZpBlmlL
# Format for generating URLs from location messages for sending to Signal.
# Google Maps: 'https://www.google.com/maps/place/%[1]s,%[2]s'
# OpenStreetMap: 'https://www.openstreetmap.org/?mlat=%[1]s&mlon=%[2]s'
location_format: 'https://www.google.com/maps/place/%[1]s,%[2]s'

# Config options that affect the central bridge module.
bridge:
# The prefix for commands. Only required in non-management rooms.
command_prefix: '!signal'

# Config for the bridge's database.
database:
# The database type. "sqlite3-fk-wal" and "postgres" are supported.
type: sqlite3-fk-wal
# The database URI.
# SQLite: A raw file path is supported, but `file:<path>?_txlock=immediate` is recommended.
# https://github.com/mattn/go-sqlite3#connection-string
# Postgres: Connection string. For example, postgres://user:password@host/database?sslmode=disable
# To connect via Unix socket, use something like postgres:///dbname?host=/var/run/postgresql
uri: file:{{.DatabasePrefix}}mautrix-signal.db?_txlock=immediate
# Maximum number of connections.
max_open_conns: 5
max_idle_conns: 2
# Maximum connection idle time and lifetime before they're closed. Disabled if null.
# Parsed with https://pkg.go.dev/time#ParseDuration
max_conn_idle_time: null
max_conn_lifetime: null

# Homeserver details.
homeserver:
# The address that this appservice can use to connect to the homeserver.
# Local addresses without HTTPS are generally recommended when the bridge is running on the same machine,
# but https also works if they run on different machines.
address: {{ .HungryAddress }}
# The domain of the homeserver (also known as server_name, used for MXIDs, etc).
domain: beeper.local

# What software is the homeserver running?
# Standard Matrix homeservers like Synapse, Dendrite and Conduit should just use "standard" here.
software: hungry
# The URL to push real-time bridge status to.
# If set, the bridge will make POST requests to this URL whenever a user's remote network connection state changes.
# The bridge will use the appservice as_token to authorize requests.
status_endpoint: null
# Endpoint for reporting per-message status.
# If set, the bridge will make POST requests to this URL when processing a message from Matrix.
# It will make one request when receiving the message (step BRIDGE), one after decrypting if applicable
# (step DECRYPTED) and one after sending to the remote network (step REMOTE). Errors will also be reported.
# The bridge will use the appservice as_token to authorize requests.
message_send_checkpoint_endpoint: null
# Does the homeserver support https://github.com/matrix-org/matrix-spec-proposals/pull/2246?
async_media: true

# Should the bridge use a websocket for connecting to the homeserver?
# The server side is currently not documented anywhere and is only implemented by mautrix-wsproxy,
# mautrix-asmux (deprecated), and hungryserv (proprietary).
websocket: {{ .Websocket }}
# How often should the websocket be pinged? Pinging will be disabled if this is zero.
ping_interval_seconds: 180

# Application service host/registration related details.
# Changing these values requires regeneration of the registration.
appservice:
# The address that the homeserver can use to connect to this appservice.
address: irrelevant

# The hostname and port where this appservice should listen.
# For Docker, you generally have to change the hostname to 0.0.0.0.
hostname: 0.0.0.0
port: 4000

# The unique ID of this appservice.
id: {{ .AppserviceID }}
# Appservice bot details.
bot:
# Username of the appservice bot.
username: {{ .BridgeName }}bot
# Display name and avatar for bot. Set to "remove" to remove display name/avatar, leave empty
# to leave display name/avatar as-is.
displayname: Signal v2 bridge bot
avatar: mxc://maunium.net/wPJgTQbZOtpBFmDNkiNEMDUp

# Whether to receive ephemeral events via appservice transactions.
ephemeral_events: true
# Should incoming events be handled asynchronously?
# This may be necessary for large public instances with lots of messages going through.
# However, messages will not be guaranteed to be bridged in the same order they were sent in.
async_transactions: false

# Authentication tokens for AS <-> HS communication. Autogenerated; do not modify.
as_token: {{ .ASToken }}
hs_token: {{ .HSToken }}

# Localpart template of MXIDs for remote users.
username_template: {{ .BridgeName }}_{{ "{{.}}" }}

# Config options that affect the Matrix connector of the bridge.
matrix:
# Whether the bridge should send the message status as a custom com.beeper.message_send_status event.
message_status_events: true
# Whether the bridge should send a read receipt after successfully bridging a message.
delivery_receipts: false
# Whether the bridge should send error notices via m.notice events when a message fails to bridge.
message_error_notices: false
sync_direct_chat_list: false
# Whether created rooms should have federation enabled. If false, created portal rooms
# will never be federated. Changing this option requires recreating rooms.
federate_rooms: false

# Settings for provisioning API
provisioning:
# Prefix for the provisioning API paths.
prefix: /_matrix/provision
# Shared secret for authentication. If set to "generate" or null, a random secret will be generated,
# or if set to "disable", the provisioning API will be disabled.
shared_secret: {{ .ProvisioningSecret }}
# Whether to allow provisioning API requests to be authed using Matrix access tokens.
# This follows the same rules as double puppeting to determine which server to contact to check the token,
# which means that by default, it only works for users on the same server as the bridge.
allow_matrix_auth: true
# Enable debug API at /debug with provisioning authentication.
debug_endpoints: true

# Settings for enabling double puppeting
double_puppet:
# Servers to always allow double puppeting from.
# This is only for other servers and should NOT contain the server the bridge is on.
servers:
{{ .BeeperDomain }}: {{ .HungryAddress }}
# Whether to allow client API URL discovery for other servers. When using this option,
# users on other servers can use double puppeting even if their server URLs aren't
# explicitly added to the servers map above.
allow_discovery: false
# Shared secrets for automatic double puppeting.
# See https://docs.mau.fi/bridges/general/double-puppeting.html for instructions.
secrets:
{{ .BeeperDomain }}: "as_token:{{ .ASToken }}"

# End-to-bridge encryption support options.
#
# See https://docs.mau.fi/bridges/general/end-to-bridge-encryption.html for more info.
encryption:
# Whether to enable encryption at all. If false, the bridge will not function in encrypted rooms.
allow: true
# Whether to force-enable encryption in all bridged rooms.
default: true
# Whether to require all messages to be encrypted and drop any unencrypted messages.
require: true
# Whether to use MSC2409/MSC3202 instead of /sync long polling for receiving encryption-related data.
# This option is not yet compatible with standard Matrix servers like Synapse and should not be used.
appservice: true
# Enable key sharing? If enabled, key requests for rooms where users are in will be fulfilled.
# You must use a client that supports requesting keys from other users to use this feature.
allow_key_sharing: true
# Pickle key for encrypting encryption keys in the bridge database.
# If set to generate, a random key will be generated.
pickle_key: {{ .ASToken }}
# Options for deleting megolm sessions from the bridge.
delete_keys:
# Beeper-specific: delete outbound sessions when hungryserv confirms
# that the user has uploaded the key to key backup.
delete_outbound_on_ack: true
# Don't store outbound sessions in the inbound table.
dont_store_outbound: false
# Ratchet megolm sessions forward after decrypting messages.
ratchet_on_decrypt: true
# Delete fully used keys (index >= max_messages) after decrypting messages.
delete_fully_used_on_decrypt: true
# Delete previous megolm sessions from same device when receiving a new one.
delete_prev_on_new_session: true
# Delete megolm sessions received from a device when the device is deleted.
delete_on_device_delete: true
# Periodically delete megolm sessions when 2x max_age has passed since receiving the session.
periodically_delete_expired: true
# Delete inbound megolm sessions that don't have the received_at field used for
# automatic ratcheting and expired session deletion. This is meant as a migration
# to delete old keys prior to the bridge update.
delete_outdated_inbound: false
# What level of device verification should be required from users?
#
# Valid levels:
# unverified - Send keys to all device in the room.
# cross-signed-untrusted - Require valid cross-signing, but trust all cross-signing keys.
# cross-signed-tofu - Require valid cross-signing, trust cross-signing keys on first use (and reject changes).
# cross-signed-verified - Require valid cross-signing, plus a valid user signature from the bridge bot.
# Note that creating user signatures from the bridge bot is not currently possible.
# verified - Require manual per-device verification
# (currently only possible by modifying the `trust` column in the `crypto_device` database table).
verification_levels:
# Minimum level for which the bridge should send keys to when bridging messages from the remote network to Matrix.
receive: cross-signed-tofu
# Minimum level that the bridge should accept for incoming Matrix messages.
send: cross-signed-tofu
# Minimum level that the bridge should require for accepting key requests.
share: cross-signed-tofu
# Options for Megolm room key rotation. These options allow you to configure the m.room.encryption event content.
# See https://spec.matrix.org/v1.10/client-server-api/#mroomencryption for more information about that event.
rotation:
# Enable custom Megolm room key rotation settings. Note that these
# settings will only apply to rooms created after this option is set.
enable_custom: true
# The maximum number of milliseconds a session should be used
# before changing it. The Matrix spec recommends 604800000 (a week)
# as the default.
milliseconds: 2592000000
# The maximum number of messages that should be sent with a given a
# session before changing it. The Matrix spec recommends 100 as the
# default.
messages: 10000
# Disable rotating keys when a user's devices change?
# You should not enable this option unless you understand all the implications.
disable_device_change_key_rotation: true

# Logging config. See https://github.com/tulir/zeroconfig for details.
logging:
min_level: debug
writers:
- type: stdout
format: pretty-colored
- type: file
format: json
filename: ./logs/mautrix-signal.log
max_size: 100
max_backups: 10
compress: false
1 change: 1 addition & 0 deletions cmd/bbctl/bridgeutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ var officialBridges = []bridgeTypeToNames{
{"imessagego", []string{"imessagego"}},
{"imessage", []string{"imessage"}},
{"linkedin", []string{"linkedin"}},
{"signalv2", []string{"signalv2"}},
{"signal", []string{"signal"}},
{"slack", []string{"slack"}},
{"telegram", []string{"telegram"}},
Expand Down
6 changes: 6 additions & 0 deletions cmd/bbctl/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ var bridgeIPSuffix = map[string]string{
"googlechat": "20",
"twitter": "27",
"signal": "28",
"signalv2": "28",
"discord": "34",
"slack": "35",
"gmessages": "36",
Expand Down Expand Up @@ -355,6 +356,11 @@ func generateBridgeConfig(ctx *cli.Context) error {
startupCommand += " -c " + outputPath
}
installInstructions = fmt.Sprintf("https://docs.mau.fi/bridges/go/setup.html?bridge=%s#installation", cfg.BridgeType)
case "signalv2":
startupCommand = fmt.Sprintf("mautrix-%s-v2", strings.TrimSuffix(cfg.BridgeType, "v2"))
if outputPath != "config.yaml" && outputPath != "<config file>" {
startupCommand += " -c " + outputPath
}
case "imessagego":
startupCommand = "beeper-imessage"
if outputPath != "config.yaml" && outputPath != "<config file>" {
Expand Down
26 changes: 21 additions & 5 deletions cmd/bbctl/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ func updateGoBridge(ctx context.Context, binaryPath, bridgeType string, noUpdate
}

func compileGoBridge(ctx context.Context, buildDir, binaryPath, bridgeType string, noUpdate bool) error {
v2 := strings.HasSuffix(bridgeType, "v2")
bridgeType = strings.TrimSuffix(bridgeType, "v2")
buildDirParent := filepath.Dir(buildDir)
err := os.MkdirAll(buildDirParent, 0700)
if err != nil {
Expand Down Expand Up @@ -155,8 +157,12 @@ func compileGoBridge(ctx context.Context, buildDir, binaryPath, bridgeType strin
return fmt.Errorf("failed to pull repo: %w", err)
}
}
log.Printf("Compiling bridge with ./build.sh")
err = makeCmd(ctx, buildDir, "./build.sh").Run()
buildScript := "./build.sh"
if v2 {
buildScript = "./build-v2.sh"
}
log.Printf("Compiling bridge with %s", buildScript)
err = makeCmd(ctx, buildDir, buildScript).Run()
if err != nil {
return fmt.Errorf("failed to compile bridge: %w", err)
}
Expand Down Expand Up @@ -311,16 +317,26 @@ func runBridge(ctx *cli.Context) error {
var bridgeArgs []string
var needsWebsocketProxy bool
switch cfg.BridgeType {
case "imessage", "imessagego", "whatsapp", "discord", "slack", "gmessages", "signal", "meta":
case "imessage", "imessagego", "whatsapp", "discord", "slack", "gmessages", "signal", "signalv2", "meta":
binaryName := fmt.Sprintf("mautrix-%s", cfg.BridgeType)
v2 := false
if strings.HasSuffix(cfg.BridgeType, "v2") {
needsWebsocketProxy = true
binaryName = fmt.Sprintf("mautrix-%s-v2", strings.TrimSuffix(cfg.BridgeType, "v2"))
v2 = true
}
if cfg.BridgeType == "imessagego" {
binaryName = "beeper-imessage"
}
bridgeCmd = filepath.Join(dataDir, "binaries", binaryName)
if localDev && overrideBridgeCmd == "" {
bridgeCmd = filepath.Join(bridgeDir, binaryName)
log.Printf("Compiling [cyan]%s[reset] with ./build.sh", binaryName)
err = makeCmd(ctx.Context, bridgeDir, "./build.sh").Run()
buildScript := "./build.sh"
if v2 {
buildScript = "./build-v2.sh"
}
log.Printf("Compiling [cyan]%s[reset] with %s", binaryName, buildScript)
err = makeCmd(ctx.Context, bridgeDir, buildScript).Run()
if err != nil {
return fmt.Errorf("failed to compile bridge: %w", err)
}
Expand Down

0 comments on commit e2b4b94

Please sign in to comment.