Class: Bridge

Bridge(opts)

new Bridge(opts)

Parameters:
Name Type Description
opts Object Options to pass to the bridge
Properties
Name Type Attributes Description
registration AppServiceRegistration | string Application service registration object or path to the registration file.
homeserverUrl string The base HS url
domain string The domain part for user_ids and room aliases e.g. "bar" in "@foo:bar".
networkName string A human readable string that will be used when the bridge signals errors to the client. Will not include in error events if ommited.
controller Object The controller logic for the bridge.
Properties
Name Type Attributes Description
onEvent Bridge~onEvent Function. Called when an event has been received from the HS.
onUserQuery Bridge~onUserQuery <optional>
Function. If supplied, the bridge will invoke this function when queried via onUserQuery. If not supplied, no users will be provisioned on user queries. Provisioned users will automatically be stored in the associated userStore.
onAliasQuery Bridge~onAliasQuery <optional>
Function. If supplied, the bridge will invoke this function when queried via onAliasQuery. If not supplied, no rooms will be provisioned on alias queries. Provisioned rooms will automatically be stored in the associated roomStore.
onAliasQueried Bridge~onAliasQueried <optional>
Function. If supplied, the bridge will invoke this function when a room has been created via onAliasQuery.
onLog Bridge~onLog <optional>
Function. Invoked when logging. Defaults to a function which logs to the console.
thirdPartyLookup Bridge~thirdPartyLookup <optional>
Object. If supplied, the bridge will respond to third-party entity lookups using the contained helper functions.
onRoomUpgrade Bridge~onRoomUpgrade <optional>
Function. If supplied, the bridge will invoke this function when it sees an upgrade event for a room.
roomStore RoomBridgeStore | string <optional>
The room store instance to use, or the path to the room .db file to load. A database will be created if this is not specified.
userStore UserBridgeStore | string <optional>
The user store instance to use, or the path to the user .db file to load. A database will be created if this is not specified.
eventStore EventBridgeStore | string <optional>
The event store instance to use, or the path to the event .db file to load. This will NOT be created if it isn't specified.
membershipCache MembershipCache <optional>
The membership cache instance to use, which can be manually created by a bridge for greater control over caching. By default a membership cache will be created internally.
suppressEcho boolean <optional>
True to stop receiving onEvent callbacks for events which were sent by a bridge user. Default: true.
clientFactory ClientFactory <optional>
The client factory instance to use. If not supplied, one will be created.
logRequestOutcome boolean True to enable SUCCESS/FAILED log lines to be sent to onLog. Default: true.
intentOptions Object <optional>
Options to supply to created Intent instances.
Properties
Name Type Attributes Description
bot Object <optional>
Options to supply to the bot intent.
clients Object <optional>
Options to supply to the client intents.
escapeUserIds Object <optional>
Escape userIds for non-bot intents with MatrixUser~escapeUserId Default: true
queue Object <optional>
Options for the onEvent queue. When the bridge receives an incoming transaction, it needs to asyncly query the data store for contextual info before calling onEvent. A queue is used to keep the onEvent calls consistent with the arrival order from the incoming transactions.
Properties
Name Type Attributes Description
type string <optional>
The type of queue to use when feeding through to Bridge~onEvent. One of: "none", single", "per_room". If "none", events are fed through as soon as contextual info is obtained, which may result in out of order events but stops HOL blocking. If "single", onEvent calls will be in order but may be slower due to HOL blocking. If "per_room", a queue per room ID is made which reduces the impact of HOL blocking to be scoped to a room. Default: "single".
perRequest boolean <optional>
True to only feed through the next event after the request object in the previous call succeeds or fails. It is vital that you consistently resolve/reject the request if this is 'true', else you will not get any further events from this queue. To aid debugging this, consider setting a delayed listener on the request factory. If false, the mere invockation of onEvent is enough to trigger the next event in the queue. You probably want to set this to 'true' if your Bridge~onEvent is performing async operations where ordering matters (e.g. messages). Default: false.
disableContext boolean <optional>
True to disable Bridge~BridgeContext parameters in Bridge~onEvent. Disabling the context makes the bridge do fewer database lookups, but prevents there from being a context parameter. Default: false.
disableStores boolean <optional>
True to disable enabling of stores. This should be used by bridges that use their own database instances and do not need any of the included store objects. This implies setting disableContext to True. Default: false.
roomLinkValidation Object <optional>
Options to supply to the room link validator. If not defined then all room links are accepted.
Properties
Name Type Attributes Description
ruleFile string A file containing rules on which matrix rooms can be bridged.
rules Object <optional>
A object containing rules on which matrix rooms can be bridged. This is used if ruleFile is undefined.
triggerEndpoint boolean <optional>
Enable the endpoint to trigger a reload of the rules file. Default: false
authenticateThirdpartyEndpoints string Should the bridge authenticate requests to third party endpoints. This is false by default to be backwards-compatible with Synapse.
roomUpgradeOpts RoomUpgradeHandler~Options Options to supply to the room upgrade handler. If not defined then upgrades are NOT handled by the bridge.
Source:

Methods

_customiseAppservice()

Apply any customisations required on the appService object.
Source:

_getUserRegex() → {string}

Returns a regex matching all users of the bridge.
Source:
Returns:
Super regex composed of all user regexes.
Type
string

_limited()

Restricts the promise according to the bridges `perRequest` setting. `perRequest` enabled: Returns a promise similar to `promise`, with the addition of it only resolving after `request`. `perRequest` disabled: Returns the promise unchanged.
Source:

addAppServicePath(opts)

Install a custom handler for an incoming HTTP API request. This allows callers to add extra functionality, implement new APIs, etc...
Parameters:
Name Type Description
opts Object Named options
Properties
Name Type Description
method string The HTTP method name.
path string Path to the endpoint.
checkToken string Should the token be automatically checked. Defaults to true.
handler Bridge~appServicePathHandler Function to handle requests to this endpoint.
Source:

canProvisionRoom(roomId, cache) → {Promise}

Determines whether a room should be provisoned based on user provided rules and the room state. Will default to true if no rules have been provided.
Parameters:
Name Type Description
roomId string The room to check.
cache boolean Should the validator check it's cache.
Source:
Returns:
resolves if can and rejects if it cannot. A status code is returned on both.
Type
Promise

getBot() → {AppServiceBot}

Get the AS bot instance.
Source:
Returns:
Type
AppServiceBot

getClientFactory() → {ClientFactory}

Retrieve the matrix client factory used when sending matrix requests.
Source:
Returns:
Type
ClientFactory

getEventStore() → (nullable) {EventBridgeStore}

Retrieve the connected event store instance, if one was configured.
Source:
Returns:
The connected instance ready for querying.
Type
EventBridgeStore

getIntent(userIdnullable, requestopt) → {Intent}

Retrieve an Intent instance for the specified user ID. If no ID is given, an instance for the bot itself is returned.
Parameters:
Name Type Attributes Description
userId string <nullable>
The user ID to get an Intent for.
request Request <optional>
Optional. The request instance to tie the MatrixClient instance to. Useful for logging contextual request IDs.
Source:
Returns:
The intent instance
Type
Intent

getIntentFromLocalpart(localpartnullable, requestopt) → {Intent}

Retrieve an Intent instance for the specified user ID localpart. This must be the complete user localpart.
Parameters:
Name Type Attributes Description
localpart string <nullable>
The user ID localpart to get an Intent for.
request Request <optional>
Optional. The request instance to tie the MatrixClient instance to. Useful for logging contextual request IDs.
Source:
Returns:
The intent instance
Type
Intent

getPrometheusMetrics(registerEndpoint, registrynullable)

Returns a PrometheusMetrics instance stored on the bridge, creating it first if required. The instance will be registered with the HTTP server so it can serve the "/metrics" page in the usual way. The instance will automatically register the Matrix SDK metrics by calling {PrometheusMetrics~registerMatrixSdkMetrics}.
Parameters:
Name Type Attributes Description
registerEndpoint boolean Register the /metrics endpoint on the appservice HTTP server. Defaults to true.
registry Registry <nullable>
Optionally provide an alternative registry for metrics.
Source:

getRequestFactory() → {RequestFactory}

Retrieve the request factory used to create incoming requests.
Source:
Returns:
Type
RequestFactory

getRoomStore() → (nullable) {RoomBridgeStore}

Retrieve the connected room store instance.
Source:
Returns:
The connected instance ready for querying.
Type
RoomBridgeStore

getUserStore() → (nullable) {UserBridgeStore}

Retrieve the connected user store instance.
Source:
Returns:
The connected instance ready for querying.
Type
UserBridgeStore

loadDatabases() → {Promise}

Load the user and room databases. Access them via getUserStore() and getRoomStore().
Source:
Returns:
Resolved/rejected when the user/room databases have been loaded.
Type
Promise

provisionUser(matrixUser, provisionedUser) → {Promise}

Provision a user on the homeserver.
Parameters:
Name Type Description
matrixUser MatrixUser The virtual user to be provisioned.
provisionedUser Bridge~ProvisionedUser Provisioning information.
Source:
Returns:
Resolved when provisioned.
Type
Promise

registerBridgeGauges(counterFunc)

A convenient shortcut to calling registerBridgeGauges() on the PrometheusMetrics instance directly. This version will supply the value of the matrixGhosts field if the counter function did not return it, for convenience.
Parameters:
Name Type Description
counterFunc PrometheusMetrics~BridgeGaugesCallback A function that when invoked returns the current counts of various items in the bridge.
Source:
Example
bridge.registerBridgeGauges(() => {
    return {
        matrixRoomConfigs: Object.keys(this.matrixRooms).length,
        remoteRoomConfigs: Object.keys(this.remoteRooms).length,

        remoteGhosts: Object.keys(this.remoteGhosts).length,

        ...
    }
})

requestCheckToken() → {Boolean}

Check a express Request to see if it's correctly authenticated (includes the hsToken). The query parameter `access_token` and the `Authorization` header are checked.
Source:
Returns:
True if authenticated, False if not.
Type
Boolean

run(port, config, appServiceInstanceopt, hostname)

Run the bridge (start listening)
Parameters:
Name Type Attributes Description
port Number The port to listen on.
config Object Configuration options
appServiceInstance AppService <optional>
The AppService instance to attach to. If not provided, one will be created.
hostname String Optional hostname to bind to. (e.g. 0.0.0.0)
Source:

Type Definitions

appServicePathHandler(req, res)

Handler function for custom applied HTTP API request paths. This is invoked as defined by expressjs.
Parameters:
Name Type Description
req Request An expressjs Request object the handler can use to inspect the incoming request.
res Response An expressjs Response object the handler can use to send the outgoing response.
Source:

getLocation(protocol, fields) → {Promise.<Array.<Bridge~thirdPartyLocationResult>>}

Returned by getProtocol third-party query metadata requests
Parameters:
Name Type Description
protocol string The name of the 3PE protocol
fields Object The location query field data as specified by the specific protocol.
Properties:
Name Type Attributes Description
location_fields Array.<string> <optional>
Names of the fields required for location lookups if location queries are supported.
user_fields Array.<string> <optional>
Names of the fields required for user lookups if user queries are supported. /** Invoked on requests for 3PLs
Source:
Returns:
A Promise of a list of 3PL lookup results.
Type
Promise.<Array.<Bridge~thirdPartyLocationResult>>

getProtocol(protocol) → {Promise.<Bridge~thirdPartyProtocolResult>}

Invoked on requests for 3PE query metadata
Parameters:
Name Type Description
protocol string The name of the 3PE protocol to query
Source:
Returns:
A Promise of metadata about 3PE queries that can be made for this protocol.
Type
Promise.<Bridge~thirdPartyProtocolResult>

getUser(protocol, fields) → {Promise.<Array.<Bridge~thirdPartyUserResult>>}

Invoked on requests for 3PUs
Parameters:
Name Type Description
protocol string The name of the 3PE protocol
fields Object The user query field data as specified by the specific protocol.
Source:
Returns:
A Promise of a list of 3PU lookup results.
Type
Promise.<Array.<Bridge~thirdPartyUserResult>>

onAliasQueried(alias, roomId)

Invoked when a response is returned from onAliasQuery. Supports both sync return values and async return values via promises.
Parameters:
Name Type Description
alias string The alias queried.
roomId string The parsed localpart of the alias.
Source:

onAliasQuery(alias, aliasLocalpart) → {Bridge~ProvisionedRoom|Promise.<Bridge~ProvisionedRoom, Error>}

Invoked when the bridge receives an alias query from the homeserver. Supports both sync return values and async return values via promises.
Parameters:
Name Type Description
alias string The alias queried.
aliasLocalpart string The parsed localpart of the alias.
Source:
Returns:
Reject the promise / return null to not provision the room. Resolve the promise / return a Bridge~ProvisionedRoom object to provision the room.
Type
Bridge~ProvisionedRoom | Promise.<Bridge~ProvisionedRoom, Error>
Example
new Bridge({
  controller: {
    onAliasQuery: function(alias, aliasLocalpart) {
      return {
        creationOpts: {
          room_alias_name: aliasLocalpart, // IMPORTANT: must be set to make the link
          name: aliasLocalpart,
          topic: "Auto-generated bridged room"
        }
      };
    }
  }
});

onEvent(request, context)

Invoked when the bridge receives an event from the homeserver.
Parameters:
Name Type Description
request Request The request to resolve or reject depending on the outcome of this request. The 'data' attached to this Request is the raw event JSON received (accessed via request.getData())
context Bridge~BridgeContext Context for this event, including instantiated client instances.
Source:

onLog(line, isError)

Invoked when the bridge is attempting to log something.
Parameters:
Name Type Description
line string The text to be logged.
isError boolean True if this line should be treated as an error msg.
Source:

onRoomUpgrade(oldRoomId, newRoomId, newVersion, context)

Parameters:
Name Type Description
oldRoomId string The roomId of the old room.
newRoomId string The roomId of the new room.
newVersion string The new room version.
context Bridge~BridgeContext Context for the upgrade event.
Source:

onUserQuery(matrixUser) → {Bridge~ProvisionedUser|Promise.<Bridge~ProvisionedUser, Error>}

Invoked when the bridge receives a user query from the homeserver. Supports both sync return values and async return values via promises.
Parameters:
Name Type Description
matrixUser MatrixUser The matrix user queried. Use getId() to get the user ID.
Source:
Returns:
Reject the promise / return null to not provision the user. Resolve the promise / return a Bridge~ProvisionedUser object to provision the user.
Type
Bridge~ProvisionedUser | Promise.<Bridge~ProvisionedUser, Error>
Example
new Bridge({
  controller: {
    onUserQuery: function(matrixUser) {
      var remoteUser = new RemoteUser("some_remote_id");
      return {
        name: matrixUser.localpart + " (Bridged)",
        url: "http://someurl.com/pic.jpg",
        user: remoteUser
      };
    }
  }
});

parseLocation(alias) → {Promise.<Array.<Bridge~thirdPartyLocationResult>>}

Invoked on requests to parse 3PL aliases
Parameters:
Name Type Description
alias string The room alias to parse.
Source:
Returns:
A Promise of a list of 3PL lookup results.
Type
Promise.<Array.<Bridge~thirdPartyLocationResult>>

parseUser(userid) → {Promise.<Array.<Bridge~thirdPartyUserResult>>}

Invoked on requests to parse 3PU user IDs
Parameters:
Name Type Description
userid string The user ID to parse.
Source:
Returns:
A Promise of a list of 3PU lookup results.
Type
Promise.<Array.<Bridge~thirdPartyUserResult>>

ProvisionedRoom

Type:
  • Object
Properties:
Name Type Attributes Description
creationOpts Object Room creation options to use when creating the room. Required.
remote RemoteRoom <optional>
The remote room to link to the provisioned room.
Source:

ProvisionedUser

Type:
  • Object
Properties:
Name Type Attributes Description
name string <optional>
The display name to set for the provisioned user.
url string <optional>
The avatar URL to set for the provisioned user.
remote RemoteUser <optional>
The remote user to link to the provisioned user.
Source:

thirdPartyLocationResult

Returned by getLocation and parseLocation third-party location lookups
Type:
  • Object
Properties:
Name Type Description
alias string The Matrix room alias to the portal room representing this 3PL
protocol string The name of the 3PE protocol
fields object The normalised values of the location query field data.
Source:

thirdPartyLookup

Type:
  • Object
Properties:
Name Type Description
protocols Array.<string> Optional list of recognised protocol names. If present, lookups for unrecognised protocols will be automatically rejected.
getProtocol Bridge~getProtocol Function. Called for requests for 3PE query metadata.
getLocation Bridge~getLocation Function. Called for requests for 3PLs.
parseLocation Bridge~parseLocation Function. Called for reverse parse requests on 3PL aliases.
getUser Bridge~getUser Function. Called for requests for 3PUs.
parseUser Bridge~parseUser Function. Called for reverse parse requests on 3PU user IDs.
Source:

thirdPartyUserResult

Returned by getUser and parseUser third-party user lookups
Type:
  • Object
Properties:
Name Type Description
userid string The Matrix user ID for the ghost representing this 3PU
protocol string The name of the 3PE protocol
fields object The normalised values of the user query field data.
Source: