gomatrixserverlib

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 2, 2023 License: Apache-2.0 Imports: 35 Imported by: 0

README

gomatrixserverlib

GoDoc

Go library for common functions needed by matrix servers. This library assumes Go 1.10+.

Documentation

Index

Examples

Constants

View Source
const (
	// Join is the string constant "join"
	Join = "join"
	// Ban is the string constant "ban"
	Ban = "ban"
	// Leave is the string constant "leave"
	Leave = "leave"
	// Invite is the string constant "invite"
	Invite = "invite"
	// Knock is the string constant "knock"
	Knock = "knock"
	// Restricted is the string constant "restricted"
	Restricted = "restricted"
	// NOTSPEC: Peek is the string constant "peek" (MSC2753, used as the label in the sync block)
	Peek = "peek"
	// Public is the string constant "public"
	Public = "public"
	// WorldReadable is the string constant "world_readable"
	WorldReadable = "world_readable"
	// MRoomCreate https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-create
	MRoomCreate = "m.room.create"
	// MRoomJoinRules https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-join-rules
	MRoomJoinRules = "m.room.join_rules"
	// MRoomPowerLevels https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-power-levels
	MRoomPowerLevels = "m.room.power_levels"
	// MRoomName https://matrix.org/docs/spec/client_server/r0.6.0#m-room-name
	MRoomName = "m.room.name"
	// MRoomTopic https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-topic
	MRoomTopic = "m.room.topic"
	// MRoomAvatar https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-avatar
	MRoomAvatar = "m.room.avatar"
	// MRoomMember https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-member
	MRoomMember = "m.room.member"
	// MRoomThirdPartyInvite https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-third-party-invite
	MRoomThirdPartyInvite = "m.room.third_party_invite"
	// MRoomAliases https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-aliases
	MRoomAliases = "m.room.aliases"
	// MRoomCanonicalAlias https://matrix.org/docs/spec/client_server/r0.6.0#m-room-canonical-alias
	MRoomCanonicalAlias = "m.room.canonical_alias"
	// MRoomHistoryVisibility https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-history-visibility
	MRoomHistoryVisibility = "m.room.history_visibility"
	// MRoomGuestAccess https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-guest-access
	MRoomGuestAccess = "m.room.guest_access"
	// MRoomEncryption https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-encryption
	MRoomEncryption = "m.room.encryption"
	// MRoomRedaction https://matrix.org/docs/spec/client_server/r0.2.0.html#id21
	MRoomRedaction = "m.room.redaction"
	// MTyping https://matrix.org/docs/spec/client_server/r0.3.0.html#m-typing
	MTyping = "m.typing"
	// MDirectToDevice https://matrix.org/docs/spec/server_server/r0.1.3#send-to-device-messaging
	MDirectToDevice = "m.direct_to_device"
	// MDeviceListUpdate https://matrix.org/docs/spec/server_server/latest#m-device-list-update-schema
	MDeviceListUpdate = "m.device_list_update"
	// MReceipt https://matrix.org/docs/spec/server_server/r0.1.4#receipts
	MReceipt = "m.receipt"
	// MPresence https://matrix.org/docs/spec/server_server/latest#m-presence-schema
	MPresence = "m.presence"
	// MRoomMembership https://github.com/matrix-org/matrix-doc/blob/clokep/restricted-rooms/proposals/3083-restricted-rooms.md
	MRoomMembership = "m.room_membership"
)
View Source
const (
	EventValidationTooLarge int = 1
)

Event validation errors

View Source
const PublicKeyNotExpired = Timestamp(0)

PublicKeyNotExpired is a magic value for PublicKeyLookupResult.ExpiredTS: it indicates that this is an active key which has not yet expired

View Source
const PublicKeyNotValid = Timestamp(0)

PublicKeyNotValid is a magic value for PublicKeyLookupResult.ValidUntilTS: it is used when we don't have a validity period for this key. Most likely it is an old key with an expiry date.

View Source
const WellKnownMaxSize = 50 * 1024 // 50KB

Variables

View Source
var ErrCanonicalJSON = errors.New("value is outside of safe range")

Functions

func Allowed

func Allowed(event *Event, authEvents AuthEventProvider, skipRoomIdCheck bool) error

Allowed checks whether an event is allowed by the auth events. It returns a NotAllowed error if the event is not allowed. If there was an error loading the auth events then it returns that error.

func CanonicalJSON

func CanonicalJSON(input []byte) ([]byte, error)

CanonicalJSON re-encodes the JSON in a canonical encoding. The encoding is the shortest possible encoding using integer values with sorted object keys. At present this function performs:

Returns a gomatrixserverlib.BadJSONError if JSON validation fails.

func CanonicalJSONAssumeValid

func CanonicalJSONAssumeValid(input []byte) []byte

CanonicalJSONAssumeValid is the same as CanonicalJSON, but assumes the input is valid JSON

func CompactJSON

func CompactJSON(input, output []byte) []byte

CompactJSON makes the encoded JSON as small as possible by removing whitespace and unneeded unicode escapes

func EnforcedCanonicalJSON

func EnforcedCanonicalJSON(input []byte, roomVersion RoomVersion) ([]byte, error)

Returns a gomatrixserverlib.BadJSONError if the canonical JSON fails enforced checks or if JSON validation fails. At present this function performs:

Returns a gomatrixserverlib.BadJSONError if JSON validation fails.

func IsValidCertificate

func IsValidCertificate(serverName ServerName, c *x509.Certificate, intermediates *x509.CertPool) (valid bool, err error)

IsValidCertificate checks if the given x509 certificate can be verified using system root CAs and an optional pool of intermediate CAs.

func ParseAndValidateServerName

func ParseAndValidateServerName(serverName ServerName) (host string, port int, valid bool)

ParseAndValidateServerName splits a ServerName into a host and port part, and checks that it is a valid server name according to the spec.

if there is no explicit port, returns '-1' as the port.

func ParseAuthorization

func ParseAuthorization(header string) (scheme string, origin, destination ServerName, key KeyID, sig string)

func RawJSONFromResult

func RawJSONFromResult(result gjson.Result, _ []byte) []byte

RawJSONFromResult extracts the raw JSON bytes pointed to by result. input must be the json bytes that were used to generate result TODO: Why do we do this?

func RoomVersions

func RoomVersions() map[RoomVersion]RoomVersionDescription

RoomVersions returns information about room versions currently implemented by this commit of gomatrixserverlib.

func SignJSON

func SignJSON(signingName string, keyID KeyID, privateKey ed25519.PrivateKey, message []byte) (signed []byte, err error)

SignJSON signs a JSON object returning a copy signed with the given key. https://matrix.org/docs/spec/server_server/unstable.html#signing-json

func SortJSON

func SortJSON(input, output []byte) []byte

SortJSON reencodes the JSON with the object keys sorted by lexicographically by codepoint. The input must be valid JSON.

func StableRoomVersions

func StableRoomVersions() map[RoomVersion]RoomVersionDescription

StableRoomVersions returns a map of descriptions for room versions that are marked as stable.

func SupportedRoomVersions

func SupportedRoomVersions() map[RoomVersion]RoomVersionDescription

SupportedRoomVersions returns a map of descriptions for room versions that are marked as supported.

func VerifyAllEventSignatures

func VerifyAllEventSignatures(ctx context.Context, events []*Event, verifier JSONVerifier) []error

func VerifyAuthRulesAtState

func VerifyAuthRulesAtState(ctx context.Context, sp StateProvider, eventToVerify *HeaderedEvent, allowValidation bool) error

VerifyAuthRulesAtState will check that the auth_events in the given event are valid at the state of the room before that event.

This implements Step 5 of https://matrix.org/docs/spec/server_server/latest#checks-performed-on-receipt-of-a-pdu "Passes authorization rules based on the state at the event, otherwise it is rejected."

If `allowValidation` is true: This check initially attempts to validate that the auth_events are in the target room state, and if they are it will short-circuit and succeed early. THIS IS ONLY VALID IF STEP 4 HAS BEEN PREVIOUSLY APPLIED. Otherwise, a malicious server could lie and say that no auth_events are required and this function will short-circuit and allow it.

func VerifyEventAuthChain

func VerifyEventAuthChain(ctx context.Context, eventToVerify *HeaderedEvent, provideEvents AuthChainProvider) error

VerifyEventAuthChain will verify that the event is allowed according to its auth_events, and then recursively verify each of those auth_events.

This function implements Step 4 of https://matrix.org/docs/spec/server_server/latest#checks-performed-on-receipt-of-a-pdu "Passes authorization rules based on the event's auth events, otherwise it is rejected." If an event passes this function without error, the caller should make sure that all the auth_events were actually for a valid room state, and not referencing random bits of room state from different positions in time (Step 5).

The `provideEvents` function will only be called for *new* events rather than for everything as it is assumed that this function is costly. Failing to provide all the requested events will fail this function. Returning an error from `provideEvents` will also fail this function.

func VerifyJSON

func VerifyJSON(signingName string, keyID KeyID, publicKey ed25519.PublicKey, message []byte) error

VerifyJSON checks that the entity has signed the message using a particular key.

Types

type ApplicationServiceTransaction

type ApplicationServiceTransaction struct {
	Events []ClientEvent `json:"events"`
}

ApplicationServiceTransaction is the transaction that is sent off to an application service.

type AuthChainProvider

type AuthChainProvider func(roomVer RoomVersion, eventIDs []string) ([]*Event, error)

AuthChainProvider returns the requested list of auth events.

type AuthEventProvider

type AuthEventProvider interface {
	// Create returns the m.room.create event for the room or nil if there isn't a m.room.create event.
	Create() (*Event, error)
	// JoinRules returns the m.room.join_rules event for the room or nil if there isn't a m.room.join_rules event.
	JoinRules() (*Event, error)
	// PowerLevels returns the m.room.power_levels event for the room or nil if there isn't a m.room.power_levels event.
	PowerLevels() (*Event, error)
	// Member returns the m.room.member event for the given user_id state_key or nil if there isn't a m.room.member event.
	Member(stateKey string) (*Event, error)
	// ThirdPartyInvite returns the m.room.third_party_invite event for the
	// given state_key or nil if there isn't a m.room.third_party_invite event
	ThirdPartyInvite(stateKey string) (*Event, error)
}

AuthEventProvider provides auth_events for the authentication checks.

type AuthEvents

type AuthEvents struct {
	// contains filtered or unexported fields
}

AuthEvents is an implementation of AuthEventProvider backed by a map.

func NewAuthEvents

func NewAuthEvents(events []*Event) AuthEvents

NewAuthEvents returns an AuthEventProvider backed by the given events. New events can be added by calling AddEvent().

func (*AuthEvents) AddEvent

func (a *AuthEvents) AddEvent(event *Event) error

AddEvent adds an event to the provider. If an event already existed for the (type, state_key) then the event is replaced with the new event. Only returns an error if the event is not a state event.

func (*AuthEvents) Create

func (a *AuthEvents) Create() (*Event, error)

Create implements AuthEventProvider

func (*AuthEvents) JoinRules

func (a *AuthEvents) JoinRules() (*Event, error)

JoinRules implements AuthEventProvider

func (*AuthEvents) Member

func (a *AuthEvents) Member(stateKey string) (*Event, error)

Member implements AuthEventProvider

func (*AuthEvents) PowerLevels

func (a *AuthEvents) PowerLevels() (*Event, error)

PowerLevels implements AuthEventProvider

func (*AuthEvents) ThirdPartyInvite

func (a *AuthEvents) ThirdPartyInvite(stateKey string) (*Event, error)

ThirdPartyInvite implements AuthEventProvider

type BackfillClient

type BackfillClient interface {
	// Backfill performs a backfill request to the given server.
	// https://matrix.org/docs/spec/server_server/latest#get-matrix-federation-v1-backfill-roomid
	Backfill(ctx context.Context, server ServerName, roomID string, limit int, fromEventIDs []string) (Transaction, error)
}

BackfillClient contains the necessary functions from the federation client to perform a backfill request from another homeserver.

type BackfillRequester

type BackfillRequester interface {
	StateProvider
	BackfillClient
	// ServersAtEvent is called when trying to determine which server to request from.
	// It returns a list of servers which can be queried for backfill requests. These servers
	// will be servers that are in the room already. The entries at the beginning are preferred servers
	// and will be tried first. An empty list will fail the request.
	ServersAtEvent(ctx context.Context, roomID, eventID string) []ServerName
	ProvideEvents(roomVer RoomVersion, eventIDs []string) ([]*Event, error)
}

BackfillRequester contains the necessary functions to perform backfill requests from one server to another.

It requires a StateProvider in order to perform PDU checks on received events, notably the step "Passes authorization rules based on the state at the event, otherwise it is rejected.". The BackfillRequester will always call functions on the StateProvider in topological order, starting with the earliest event and rolling forwards. This allows implementations to make optimisations for subsequent events, rather than constantly deferring to federation requests.

type BadJSONError

type BadJSONError struct {
	// contains filtered or unexported fields
}

func (BadJSONError) Error

func (e BadJSONError) Error() string

func (BadJSONError) Unwrap

func (e BadJSONError) Unwrap() error

type Base64Bytes

type Base64Bytes []byte

A Base64Bytes is a string of bytes (not base64 encoded) that are base64 encoded when used in JSON.

The bytes encoded using base64 when marshalled as JSON. When the bytes are unmarshalled from JSON they are decoded from base64.

When scanning directly from a database, a string column will be decoded from base64 automatically whereas a bytes column will be copied as-is.

func (*Base64Bytes) Decode

func (b64 *Base64Bytes) Decode(str string) error

Decode decodes the given input into this Base64Bytes

func (Base64Bytes) Encode

func (b64 Base64Bytes) Encode() string

Encode encodes the bytes as base64

func (Base64Bytes) MarshalJSON

func (b64 Base64Bytes) MarshalJSON() ([]byte, error)

MarshalJSON encodes the bytes as base64 and then encodes the base64 as a JSON string. This takes a value receiver so that maps and slices of Base64Bytes encode correctly.

func (Base64Bytes) MarshalYAML

func (b64 Base64Bytes) MarshalYAML() (interface{}, error)

MarshalYAML implements yaml.Marshaller It just encodes the bytes as base64, which is a valid YAML string

func (*Base64Bytes) Scan

func (b64 *Base64Bytes) Scan(src interface{}) error

Implements sql.Scanner

func (*Base64Bytes) UnmarshalJSON

func (b64 *Base64Bytes) UnmarshalJSON(raw []byte) (err error)

UnmarshalJSON decodes a JSON string and then decodes the resulting base64. This takes a pointer receiver because it needs to write the result of decoding.

func (*Base64Bytes) UnmarshalYAML

func (b64 *Base64Bytes) UnmarshalYAML(unmarshal func(interface{}) error) (err error)

UnmarshalYAML implements yaml.Unmarshaller it unmarshals the input as a yaml string and then base64-decodes the result

func (Base64Bytes) Value

func (b64 Base64Bytes) Value() (driver.Value, error)

Implements sql.Valuer

type Client

type Client struct {
	// contains filtered or unexported fields
}

A Client makes request to the federation listeners of matrix homeservers

func NewClient

func NewClient(options ...ClientOption) *Client

NewClient makes a new Client. You can supply zero or more ClientOptions which control the transport, timeout, TLS validation etc - see WithTransport, WithTimeout, WithSkipVerify, WithDNSCache etc.

func (*Client) CreateMediaDownloadRequest

func (fc *Client) CreateMediaDownloadRequest(
	ctx context.Context, matrixServer ServerName, mediaID string,
) (*http.Response, error)

CreateMediaDownloadRequest creates a request for media on a homeserver and returns the http.Response or an error

func (*Client) DoHTTPRequest

func (fc *Client) DoHTTPRequest(ctx context.Context, req *http.Request) (*http.Response, error)

DoHTTPRequest creates an outgoing request ID and adds it to the context before sending off the request and awaiting a response.

If the returned error is nil, the Response will contain a non-nil Body which the caller is expected to close.

func (*Client) DoRequestAndParseResponse

func (fc *Client) DoRequestAndParseResponse(
	ctx context.Context,
	req *http.Request,
	result interface{},
) error

DoRequestAndParseResponse calls DoHTTPRequest and then decodes the response.

If the HTTP response is not a 200, an attempt is made to parse the response body into a gomatrix.RespError. In any case, a non-200 response will result in a gomatrix.HTTPError.

func (*Client) GetServerKeys

func (fc *Client) GetServerKeys(
	ctx context.Context, matrixServer ServerName,
) (ServerKeys, error)

GetServerKeys asks a matrix server for its signing keys and TLS cert

func (*Client) GetVersion

func (fc *Client) GetVersion(
	ctx context.Context, s ServerName,
) (res Version, err error)

GetVersion gets the version information of a homeserver. See https://matrix.org/docs/spec/server_server/r0.1.1.html#get-matrix-federation-v1-version

func (*Client) LookupServerKeys

func (fc *Client) LookupServerKeys(
	ctx context.Context, matrixServer ServerName, keyRequests map[PublicKeyLookupRequest]Timestamp,
) ([]ServerKeys, error)

LookupServerKeys looks up the keys for a matrix server from a matrix server. The first argument is the name of the matrix server to download the keys from. The second argument is a map from (server name, key ID) pairs to timestamps. The (server name, key ID) pair identifies the key to download. The timestamps tell the server when the keys need to be valid until. Perspective servers can use that timestamp to determine whether they can return a cached copy of the keys or whether they will need to retrieve a fresh copy of the keys. Returns the keys returned by the server, or an error if there was a problem talking to the server.

func (*Client) LookupUserInfo

func (fc *Client) LookupUserInfo(
	ctx context.Context, matrixServer ServerName, token string,
) (u UserInfo, err error)

LookupUserInfo gets information about a user from a given matrix homeserver using a bearer access token.

func (*Client) SetUserAgent

func (fc *Client) SetUserAgent(ua string)

SetUserAgent sets the user agent string that is sent in the headers of outbound HTTP requests.

type ClientEvent

type ClientEvent struct {
	Content        RawJSON   `json:"content"`
	EventID        string    `json:"event_id,omitempty"`         // EventID is omitted on receipt events
	OriginServerTS Timestamp `json:"origin_server_ts,omitempty"` // OriginServerTS is omitted on receipt events
	RoomID         string    `json:"room_id,omitempty"`          // RoomID is omitted on /sync responses
	Sender         string    `json:"sender,omitempty"`           // Sender is omitted on receipt events
	StateKey       *string   `json:"state_key,omitempty"`
	Type           string    `json:"type"`
	Unsigned       RawJSON   `json:"unsigned,omitempty"`
	Redacts        string    `json:"redacts,omitempty"`
}

ClientEvent is an event which is fit for consumption by clients, in accordance with the specification.

func HeaderedToClientEvent

func HeaderedToClientEvent(se *HeaderedEvent, format ClientEventFormat) ClientEvent

ToClientEvent converts a single server event to a client event.

func HeaderedToClientEvents

func HeaderedToClientEvents(serverEvs []*HeaderedEvent, format ClientEventFormat) []ClientEvent

ToClientEvents converts server events to client events.

func ToClientEvent

func ToClientEvent(se *Event, format ClientEventFormat) ClientEvent

ToClientEvent converts a single server event to a client event.

func ToClientEvents

func ToClientEvents(serverEvs []*Event, format ClientEventFormat) []ClientEvent

ToClientEvents converts server events to client events.

type ClientEventFormat

type ClientEventFormat int
const (
	// FormatAll will include all client event keys
	FormatAll ClientEventFormat = iota
	// FormatSync will include only the event keys required by the /sync API. Notably, this
	// means the 'room_id' will be missing from the events.
	FormatSync
)

type ClientOption

type ClientOption func(*clientOptions)

ClientOption are supplied to NewClient or NewFederationClient.

func WithDNSCache

func WithDNSCache(cache *DNSCache) ClientOption

WithDNSCache is an option that can be supplied to either NewClient or NewFederationClient. This option will be ineffective if WithTransport has already been supplied.

func WithKeepAlives

func WithKeepAlives(keepAlives bool) ClientOption

WithKeepAlives is an option that can be supplied to either NewClient or NewFederationClient. This option will be ineffective if WithTransport has already been supplied.

func WithSkipVerify

func WithSkipVerify(skipVerify bool) ClientOption

WithSkipVerify is an option that can be supplied to either NewClient or NewFederationClient. This option will be ineffective if WithTransport has already been supplied.

func WithTimeout

func WithTimeout(duration time.Duration) ClientOption

WithTimeout is an option that can be supplied to either NewClient or NewFederationClient.

func WithTransport

func WithTransport(transport http.RoundTripper) ClientOption

WithTransport is an option that can be supplied to either NewClient or NewFederationClient. Supplying this option will render WithDNSCache and WithSkipVerify ineffective.

type CreateContent

type CreateContent struct {

	// The "m.federate" flag tells us whether the room can be federated to other servers.
	Federate *bool `json:"m.federate,omitempty"`
	// The creator of the room tells us what the default power levels are.
	Creator string `json:"creator"`
	// The version of the room. Should be treated as "1" when the key doesn't exist.
	RoomVersion *RoomVersion `json:"room_version,omitempty"`
	// The predecessor of the room.
	Predecessor PreviousRoom `json:"predecessor,omitempty"`
	// contains filtered or unexported fields
}

CreateContent is the JSON content of a m.room.create event along with the top level keys needed for auth. See https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-create for descriptions of the fields.

func NewCreateContentFromAuthEvents

func NewCreateContentFromAuthEvents(authEvents AuthEventProvider) (c CreateContent, err error)

NewCreateContentFromAuthEvents loads the create event content from the create event in the auth events.

func (*CreateContent) DomainAllowed

func (c *CreateContent) DomainAllowed(domain string) error

DomainAllowed checks whether the domain is allowed in the room by the "m.federate" flag.

func (*CreateContent) UserIDAllowed

func (c *CreateContent) UserIDAllowed(id string) error

UserIDAllowed checks whether the domain part of the user ID is allowed in the room by the "m.federate" flag.

type CrossSigningBody

type CrossSigningBody interface {
	// contains filtered or unexported methods
}

type CrossSigningForKeyOrDevice

type CrossSigningForKeyOrDevice struct {
	CrossSigningBody
}

func (CrossSigningForKeyOrDevice) MarshalJSON

func (c CrossSigningForKeyOrDevice) MarshalJSON() ([]byte, error)

Implements json.Marshaler

func (*CrossSigningForKeyOrDevice) UnmarshalJSON

func (c *CrossSigningForKeyOrDevice) UnmarshalJSON(b []byte) error

Implements json.Unmarshaler

type CrossSigningKey

type CrossSigningKey struct {
	Signatures map[string]map[KeyID]Base64Bytes `json:"signatures,omitempty"`
	Keys       map[KeyID]Base64Bytes            `json:"keys"`
	Usage      []CrossSigningKeyPurpose         `json:"usage"`
	UserID     string                           `json:"user_id"`
}

https://spec.matrix.org/unstable/client-server-api/#post_matrixclientr0keysdevice_signingupload

type CrossSigningKeyPurpose

type CrossSigningKeyPurpose string
const (
	CrossSigningKeyPurposeMaster      CrossSigningKeyPurpose = "master"
	CrossSigningKeyPurposeSelfSigning CrossSigningKeyPurpose = "self_signing"
	CrossSigningKeyPurposeUserSigning CrossSigningKeyPurpose = "user_signing"
)

type CrossSigningKeys

type CrossSigningKeys struct {
	MasterKey      CrossSigningKey `json:"master_key"`
	SelfSigningKey CrossSigningKey `json:"self_signing_key"`
	UserSigningKey CrossSigningKey `json:"user_signing_key"`
}

type DNSCache

type DNSCache struct {
	// contains filtered or unexported fields
}

func NewDNSCache

func NewDNSCache(size int, duration time.Duration) *DNSCache

func (*DNSCache) DialContext

func (c *DNSCache) DialContext(ctx context.Context, network, address string) (net.Conn, error)

type DeviceKeys

type DeviceKeys struct {
	RespUserDeviceKeys
	// Additional data added to the device key information by intermediate servers, and not covered by the signatures.
	// E.g { "device_display_name": "Alice's mobile phone" }
	Unsigned map[string]interface{} `json:"unsigned"`
}

DeviceKeys as per https://matrix.org/docs/spec/server_server/latest#post-matrix-federation-v1-user-keys-query

func (*DeviceKeys) Scan

func (s *DeviceKeys) Scan(src interface{}) error

func (DeviceKeys) Value

func (s DeviceKeys) Value() (driver.Value, error)

type DeviceListUpdateEvent

type DeviceListUpdateEvent struct {
	UserID            string          `json:"user_id"`
	DeviceID          string          `json:"device_id"`
	DeviceDisplayName string          `json:"device_display_name"`
	StreamID          int64           `json:"stream_id"`
	PrevID            []int64         `json:"prev_id"`
	Deleted           bool            `json:"deleted"`
	Keys              json.RawMessage `json:"keys"`
}

DeviceListUpdateEvent is https://matrix.org/docs/spec/server_server/latest#m-device-list-update-schema

type DirectKeyFetcher

type DirectKeyFetcher struct {
	// The federation client to use to fetch keys with.
	Client KeyClient
}

A DirectKeyFetcher fetches keys directly from a server. This may be suitable for local deployments that are firewalled from the public internet where DNS can be trusted.

func (*DirectKeyFetcher) FetchKeys

FetchKeys implements KeyFetcher

func (DirectKeyFetcher) FetcherName

func (d DirectKeyFetcher) FetcherName() string

FetcherName implements KeyFetcher

type EDU

type EDU struct {
	Type        string  `json:"edu_type"`
	Origin      string  `json:"origin"`
	Destination string  `json:"destination,omitempty"`
	Content     RawJSON `json:"content,omitempty"`
}

EDU represents a EDU received via federation https://matrix.org/docs/spec/server_server/unstable.html#edus

type Ed25519Checks

type Ed25519Checks struct {
	ValidEd25519      bool // The verify key is valid Ed25519 keys.
	MatchingSignature bool // The verify key has a valid signature.
}

Ed25519Checks are the checks that are applied to Ed25519 keys in ServerKey responses.

type Event

type Event struct {
	// contains filtered or unexported fields
}

An Event is a matrix event. The event should always contain valid JSON. If the event content hash is invalid then the event is redacted. Redacted events contain only the fields covered by the event signature. The fields have different formats depending on the room version - see eventFormatV1Fields, eventFormatV2Fields.

func NewEventFromTrustedJSON

func NewEventFromTrustedJSON(eventJSON []byte, redacted bool, roomVersion RoomVersion) (result *Event, err error)

NewEventFromTrustedJSON loads a new event from some JSON that must be valid. This will be more efficient than NewEventFromUntrustedJSON since it can skip cryptographic checks. This can be used when loading matrix events from a local database.

func NewEventFromTrustedJSONWithEventID

func NewEventFromTrustedJSONWithEventID(eventID string, eventJSON []byte, redacted bool, roomVersion RoomVersion) (result *Event, err error)

NewEventFromTrustedJSONWithEventID loads a new event from some JSON that must be valid and that the event ID is already known. This must ONLY be used when retrieving an event from the database and NEVER when accepting an event over federation. This will be more efficient than NewEventFromTrustedJSON since, if the event ID is known, we skip all the reference hash and canonicalisation work.

func NewEventFromUntrustedJSON

func NewEventFromUntrustedJSON(eventJSON []byte, roomVersion RoomVersion) (result *Event, err error)

NewEventFromUntrustedJSON loads a new event from some JSON that may be invalid. This checks that the event is valid JSON. It also checks the content hashes to ensure the event has not been tampered with. This should be used when receiving new events from remote servers.

func ResolveConflicts

func ResolveConflicts(
	version RoomVersion,
	events []*Event,
	authEvents []*Event,
) ([]*Event, error)

ResolveConflicts performs state resolution on the input events, returning the resolved state. It will automatically decide which state resolution algorithm to use, depending on the room version. `events` should be all the state events to resolve. `authEvents` should be the entire set of auth_events for these `events`. Returns an error if the state resolution algorithm cannot be determined.

func ResolveStateConflicts

func ResolveStateConflicts(conflicted []*Event, authEvents []*Event) []*Event

ResolveStateConflicts takes a list of state events with conflicting state keys and works out which event should be used for each state event.

func ResolveStateConflictsV2

func ResolveStateConflictsV2(
	conflicted, unconflicted []*Event,
	authEvents, authDifference []*Event,
) []*Event

ResolveStateConflicts takes a list of state events with conflicting state keys and works out which event should be used for each state event. This function returns the resolved state, including unconflicted state events.

func ReverseTopologicalOrdering

func ReverseTopologicalOrdering(input []*Event, order TopologicalOrder) []*Event

ReverseTopologicalOrdering takes a set of input events and sorts them using Kahn's algorithm in order to topologically order them. The result array of events will be sorted so that "earlier" events appear first.

func UnwrapEventHeaders

func UnwrapEventHeaders(in []*HeaderedEvent) []*Event

UnwrapEventHeaders unwraps an array of headered events.

func (*Event) AuthEventIDs

func (e *Event) AuthEventIDs() []string

AuthEventIDs returns the event IDs of the events needed to auth the event.

func (*Event) AuthEvents

func (e *Event) AuthEvents() []EventReference

AuthEvents returns references to the events needed to auth the event.

func (*Event) CheckFields

func (e *Event) CheckFields() error

CheckFields checks that the event fields are valid. Returns an error if the IDs have the wrong format or too long. Returns an error if the total length of the event JSON is too long. Returns an error if the event ID doesn't match the origin of the event. https://matrix.org/docs/spec/client_server/r0.2.0.html#size-limits

func (*Event) Content

func (e *Event) Content() []byte

Content returns the content JSON of the event.

func (*Event) Depth

func (e *Event) Depth() int64

Depth returns the depth of the event.

func (*Event) EventID

func (e *Event) EventID() string

EventID returns the event ID of the event.

func (*Event) EventReference

func (e *Event) EventReference() EventReference

EventReference returns an EventReference for the event. The reference can be used to refer to this event from other events.

func (*Event) Headered

func (e *Event) Headered(roomVersion RoomVersion) *HeaderedEvent

Headered returns a HeaderedEvent encapsulating the original event, with the supplied headers.

func (*Event) HistoryVisibility

func (e *Event) HistoryVisibility() (string, error)

HistoryVisibility returns the value of the content.history_visibility field if this event is an "m.room.history_visibility" event. Returns an error if the event is not a m.room.history_visibility event or if the content is not valid m.room.history_visibility content.

func (*Event) JSON

func (e *Event) JSON() []byte

JSON returns the JSON bytes for the event.

func (*Event) JoinRule

func (e *Event) JoinRule() (string, error)

JoinRule returns the value of the content.join_rule field if this event is an "m.room.join_rules" event. Returns an error if the event is not a m.room.join_rules event or if the content is not valid m.room.join_rules content.

func (*Event) KeyIDs

func (e *Event) KeyIDs(signingName string) []KeyID

KeyIDs returns a list of key IDs that the named entity has signed the event with.

func (Event) MarshalJSON

func (e Event) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

func (*Event) Membership

func (e *Event) Membership() (string, error)

Membership returns the value of the content.membership field if this event is an "m.room.member" event. Returns an error if the event is not a m.room.member event or if the content is not valid m.room.member content.

func (*Event) Origin

func (e *Event) Origin() ServerName

Origin returns the name of the server that sent the event

func (*Event) OriginServerTS

func (e *Event) OriginServerTS() Timestamp

OriginServerTS returns the unix timestamp when this event was created on the origin server, with millisecond resolution.

func (*Event) PowerLevels

func (e *Event) PowerLevels() (*PowerLevelContent, error)

PowerLevels returns the power levels content if this event is an "m.room.power_levels" event. Returns an error if the event is not a m.room.power_levels event or if the content is not valid m.room.power_levels content.

func (*Event) PrevEventIDs

func (e *Event) PrevEventIDs() []string

PrevEventIDs returns the event IDs of the direct ancestors of the event.

func (*Event) PrevEvents

func (e *Event) PrevEvents() []EventReference

PrevEvents returns references to the direct ancestors of the event.

func (*Event) Redact

func (e *Event) Redact() *Event

Redact returns a redacted copy of the event.

func (*Event) Redacted

func (e *Event) Redacted() bool

Redacted returns whether the event is redacted.

func (*Event) Redacts

func (e *Event) Redacts() string

Redacts returns the event ID of the event this event redacts.

func (*Event) RoomID

func (e *Event) RoomID() string

RoomID returns the room ID of the room the event is in.

func (*Event) RootRoomAuthEventIDs added in v1.1.0

func (e *Event) RootRoomAuthEventIDs() []string

func (*Event) RootRoomAuthEvents added in v1.1.0

func (e *Event) RootRoomAuthEvents() []EventReference

func (*Event) RootRoomID added in v1.1.0

func (e *Event) RootRoomID() *string

func (*Event) Sender

func (e *Event) Sender() string

Sender returns the user ID of the sender of the event.

func (*Event) SetUnsigned

func (e *Event) SetUnsigned(unsigned interface{}) (*Event, error)

SetUnsigned sets the unsigned key of the event. Returns a copy of the event with the "unsigned" key set.

func (*Event) SetUnsignedField

func (e *Event) SetUnsignedField(path string, value interface{}) error

SetUnsignedField takes a path and value to insert into the unsigned dict of the event. path is a dot separated path into the unsigned dict (see gjson package for details on format). In particular some characters like '.' and '*' must be escaped.

func (*Event) Sign

func (e *Event) Sign(signingName string, keyID KeyID, privateKey ed25519.PrivateKey) Event

Sign returns a copy of the event with an additional signature.

func (*Event) StateKey

func (e *Event) StateKey() *string

StateKey returns the "state_key" of the event, or the nil if the event is not a state event.

func (*Event) StateKeyEquals

func (e *Event) StateKeyEquals(stateKey string) bool

StateKeyEquals returns true if the event is a state event and the "state_key" matches.

func (*Event) Type

func (e *Event) Type() string

Type returns the type of the event.

func (*Event) Unsigned

func (e *Event) Unsigned() []byte

Unsigned returns the object under the 'unsigned' key of the event.

func (*Event) VerifyEventSignatures

func (e *Event) VerifyEventSignatures(ctx context.Context, verifier JSONVerifier) error

func (*Event) Version

func (e *Event) Version() RoomVersion

Version returns the version of this event

type EventBuilder

type EventBuilder struct {
	// The user ID of the user sending the event.
	Sender string `json:"sender"`
	// The room ID of the room this event is in.
	RoomID string `json:"room_id"`
	// The type of the event.
	Type string `json:"type"`
	// The state_key of the event if the event is a state event or nil if the event is not a state event.
	StateKey *string `json:"state_key,omitempty"`
	// The events that immediately preceded this event in the room history. This can be
	// either []EventReference for room v1/v2, and []string for room v3 onwards.
	PrevEvents interface{} `json:"prev_events"`
	// The events needed to authenticate this event. This can be
	// either []EventReference for room v1/v2, and []string for room v3 onwards.
	AuthEvents interface{} `json:"auth_events"`
	// AuthEvents from the root room (if any)
	RootRoomAuthEvents interface{} `json:"root_room_auth_events,omitempty"`
	// The event ID of the event being redacted if this event is a "m.room.redaction".
	Redacts string `json:"redacts,omitempty"`
	// The depth of the event, This should be one greater than the maximum depth of the previous events.
	// The create event has a depth of 1.
	Depth int64 `json:"depth"`
	// The JSON object for "signatures" key of the event.
	Signature RawJSON `json:"signatures,omitempty"`
	// The JSON object for "content" key of the event.
	Content RawJSON `json:"content"`
	// The JSON object for the "unsigned" key
	Unsigned RawJSON `json:"unsigned,omitempty"`
	// Root room id
	RootRoomId *string `json:"root_room_id,omitempty"`
}

An EventBuilder is used to build a new event. These can be exchanged between matrix servers in the federation APIs when joining or leaving a room.

func (*EventBuilder) Build

func (eb *EventBuilder) Build(
	now time.Time, origin ServerName, keyID KeyID,
	privateKey ed25519.PrivateKey, roomVersion RoomVersion,
) (result *Event, err error)

Build a new Event. This is used when a local event is created on this server. Call this after filling out the necessary fields. This can be called multiple times on the same builder. A different event ID must be supplied each time this is called.

func (*EventBuilder) SetContent

func (eb *EventBuilder) SetContent(content interface{}) (err error)

SetContent sets the JSON content key of the event.

func (*EventBuilder) SetUnsigned

func (eb *EventBuilder) SetUnsigned(unsigned interface{}) (err error)

SetUnsigned sets the JSON unsigned key of the event.

type EventFilter

type EventFilter struct {
	Limit      int       `json:"limit,omitempty"`
	NotSenders *[]string `json:"not_senders,omitempty"`
	NotTypes   *[]string `json:"not_types,omitempty"`
	Senders    *[]string `json:"senders,omitempty"`
	Types      *[]string `json:"types,omitempty"`
}

EventFilter is used to define filtering rules for events

func DefaultEventFilter

func DefaultEventFilter() EventFilter

DefaultEventFilter returns the default event filter used by the Matrix server if no filter is provided in the request

type EventFormat

type EventFormat int

EventFormat refers to the formatting of the event fields struct.

const (
	EventFormatV1 EventFormat = iota + 1 // prev_events and auth_events as event references
	EventFormatV2                        // prev_events and auth_events as string array of event IDs
)

Event format constants.

type EventIDFormat

type EventIDFormat int

EventIDFormat refers to the formatting used to generate new event IDs.

const (
	EventIDFormatV1 EventIDFormat = iota + 1 // randomised
	EventIDFormatV2                          // base64-encoded hash of event
	EventIDFormatV3                          // URL-safe base64-encoded hash of event
)

Event ID format constants.

type EventJSONs

type EventJSONs []RawJSON

func NewEventJSONsFromEvents

func NewEventJSONsFromEvents(he []*Event) EventJSONs

func NewEventJSONsFromHeaderedEvents

func NewEventJSONsFromHeaderedEvents(he []*HeaderedEvent) EventJSONs

func (EventJSONs) TrustedEvents

func (e EventJSONs) TrustedEvents(roomVersion RoomVersion, redacted bool) []*Event

func (EventJSONs) UntrustedEvents

func (e EventJSONs) UntrustedEvents(roomVersion RoomVersion) []*Event

type EventLoadResult

type EventLoadResult struct {
	Event    *HeaderedEvent
	Error    error
	SoftFail bool
}

EventLoadResult is the result of loading and verifying an event in the EventsLoader.

type EventReference

type EventReference struct {
	// The event ID of the event.
	EventID string
	// The sha256 of the redacted event.
	EventSHA256 Base64Bytes
}

An EventReference is a reference to a matrix event.

func (EventReference) MarshalJSON

func (er EventReference) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

func (*EventReference) UnmarshalJSON

func (er *EventReference) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaller

type EventValidationError

type EventValidationError struct {
	Message string
	Code    int
}

EventValidationError is returned if there is a problem validating an event

func (EventValidationError) Error

func (e EventValidationError) Error() string

type EventsLoader

type EventsLoader struct {
	// contains filtered or unexported fields
}

EventsLoader loads untrusted events and verifies them.

func NewEventsLoader

func NewEventsLoader(roomVer RoomVersion, keyRing JSONVerifier, stateProvider StateProvider, provider AuthChainProvider, performSoftFailCheck bool) *EventsLoader

NewEventsLoader returns a new events loader

func (*EventsLoader) LoadAndVerify

func (l *EventsLoader) LoadAndVerify(ctx context.Context, rawEvents []json.RawMessage, sortOrder TopologicalOrder) ([]EventLoadResult, error)

LoadAndVerify loads untrusted events and verifies them. Checks performed are outlined at https://matrix.org/docs/spec/server_server/latest#checks-performed-on-receipt-of-a-pdu The length of the returned slice will always equal the length of rawEvents. The order of the returned events depends on `sortOrder`. The events are reverse topologically sorted by the ordering specified. However in order to sort the events the events must be loaded which could fail. For those events which fail to be loaded, they will be put at the end of the returned slice.

type FederatedStateClient

type FederatedStateClient interface {
	LookupState(
		ctx context.Context, s ServerName, roomID, eventID string, roomVersion RoomVersion,
	) (res RespState, err error)
	LookupStateIDs(
		ctx context.Context, s ServerName, roomID, eventID string,
	) (res RespStateIDs, err error)
}

type FederatedStateProvider

type FederatedStateProvider struct {
	FedClient FederatedStateClient
	// The remote server to ask.
	Server ServerName
	// Set to true to remember the auth event IDs for the room at various states
	RememberAuthEvents bool
	// Maps which are populated if AuthEvents is true, so you know which events are required to do PDU checks.
	EventToAuthEventIDs map[string][]string
	AuthEventMap        map[string]*Event
}

FederatedStateProvider is an implementation of StateProvider which solely uses federation requests to retrieve events.

func (*FederatedStateProvider) StateBeforeEvent

func (p *FederatedStateProvider) StateBeforeEvent(ctx context.Context, roomVer RoomVersion, event *HeaderedEvent, eventIDs []string) (map[string]*Event, error)

StateBeforeEvent implements StateProvider

func (*FederatedStateProvider) StateIDsBeforeEvent

func (p *FederatedStateProvider) StateIDsBeforeEvent(ctx context.Context, event *HeaderedEvent) ([]string, error)

StateIDsBeforeEvent implements StateProvider

type FederationClient

type FederationClient struct {
	Client
	// contains filtered or unexported fields
}

A FederationClient is a matrix federation client that adds "Authorization: X-Matrix" headers to requests that need ed25519 signatures

func NewFederationClient

func NewFederationClient(
	serverName ServerName, keyID KeyID, privateKey ed25519.PrivateKey,
	options ...ClientOption,
) *FederationClient

NewFederationClient makes a new FederationClient. You can supply zero or more ClientOptions which control the transport, timeout, TLS validation etc - see WithTransport, WithTimeout, WithSkipVerify, WithDNSCache etc.

func (*FederationClient) Backfill

func (ac *FederationClient) Backfill(
	ctx context.Context, s ServerName, roomID string, limit int, eventIDs []string,
) (res Transaction, err error)

Backfill asks a homeserver for events early enough for them to not be in the local database. See https://matrix.org/docs/spec/server_server/unstable.html#get-matrix-federation-v1-backfill-roomid

func (*FederationClient) ClaimKeys

func (ac *FederationClient) ClaimKeys(ctx context.Context, s ServerName, oneTimeKeys map[string]map[string]string) (res RespClaimKeys, err error)

ClaimKeys claims E2E one-time keys from a remote server. `oneTimeKeys` are the keys to be claimed. A map from user ID, to a map from device ID to algorithm name. E.g:

{
  "@alice:example.com": {
    "JLAFKJWSCS": "signed_curve25519"
  }
}

https://matrix.org/docs/spec/server_server/latest#post-matrix-federation-v1-user-keys-claim

func (*FederationClient) ExchangeThirdPartyInvite

func (ac *FederationClient) ExchangeThirdPartyInvite(
	ctx context.Context, s ServerName, builder EventBuilder,
) (err error)

ExchangeThirdPartyInvite sends the builder of a m.room.member event of "invite" membership derived from a response from invites sent by an identity server. This is used to exchange a m.room.third_party_invite event for a m.room.member one in a room the local server isn't a member of.

func (*FederationClient) GetEvent

func (ac *FederationClient) GetEvent(
	ctx context.Context, s ServerName, eventID string,
) (res Transaction, err error)

GetEvent gets an event by ID from a remote server. See https://matrix.org/docs/spec/server_server/r0.1.1.html#get-matrix-federation-v1-event-eventid

func (*FederationClient) GetEventAuth

func (ac *FederationClient) GetEventAuth(
	ctx context.Context, s ServerName, roomVersion RoomVersion, roomID, eventID string,
) (res RespEventAuth, err error)

GetEventAuth gets an event auth chain from a remote server. See https://matrix.org/docs/spec/server_server/latest#get-matrix-federation-v1-event-auth-roomid-eventid

func (*FederationClient) GetPublicRooms

func (ac *FederationClient) GetPublicRooms(
	ctx context.Context, s ServerName, limit int, since string,
	includeAllNetworks bool, thirdPartyInstanceID string,
) (res RespPublicRooms, err error)

GetPublicRooms gets all public rooms listed on the target homeserver's directory. Spec: https://matrix.org/docs/spec/server_server/r0.1.1.html#get-matrix-federation-v1-publicrooms thirdPartyInstanceID can only be non-empty if includeAllNetworks is false.

func (*FederationClient) GetPublicRoomsFiltered

func (ac *FederationClient) GetPublicRoomsFiltered(
	ctx context.Context, s ServerName, limit int, since, filter string,
	includeAllNetworks bool, thirdPartyInstanceID string,
) (res RespPublicRooms, err error)

GetPublicRoomsFiltered gets a filtered public rooms list from the target homeserver's directory. Spec: https://spec.matrix.org/v1.1/server-server-api/#post_matrixfederationv1publicrooms thirdPartyInstanceID can only be non-empty if includeAllNetworks is false.

func (*FederationClient) GetUserDevices

func (ac *FederationClient) GetUserDevices(
	ctx context.Context, s ServerName, userID string,
) (res RespUserDevices, err error)

GetUserDevices returns a list of the user's devices from a remote server. See https://matrix.org/docs/spec/server_server/latest#get-matrix-federation-v1-user-devices-userid

func (*FederationClient) LookupMissingEvents

func (ac *FederationClient) LookupMissingEvents(
	ctx context.Context, s ServerName, roomID string,
	missing MissingEvents, roomVersion RoomVersion,
) (res RespMissingEvents, err error)

LookupMissingEvents asks a remote server for missing events within a given bracket. https://matrix.org/docs/spec/server_server/r0.1.3#post-matrix-federation-v1-get-missing-events-roomid

func (*FederationClient) LookupProfile

func (ac *FederationClient) LookupProfile(
	ctx context.Context, s ServerName, userID string, field string,
) (res RespProfile, err error)

LookupProfile queries the profile of a user. If field is empty, the server returns the full profile of the user. Otherwise, it must be one of: ["displayname", "avatar_url"], indicating which field of the profile should be returned. Spec: https://matrix.org/docs/spec/server_server/r0.1.1.html#get-matrix-federation-v1-query-profile

func (*FederationClient) LookupRoomAlias

func (ac *FederationClient) LookupRoomAlias(
	ctx context.Context, s ServerName, roomAlias string,
) (res RespDirectory, err error)

LookupRoomAlias looks up a room alias hosted on the remote server. The domain part of the roomAlias must match the name of the server it is being looked up on. If the room alias doesn't exist on the remote server then a 404 gomatrix.HTTPError is returned.

func (*FederationClient) LookupState

func (ac *FederationClient) LookupState(
	ctx context.Context, s ServerName, roomID, eventID string, roomVersion RoomVersion,
) (res RespState, err error)

LookupState retrieves the room state for a room at an event from a remote matrix server as full matrix events.

func (*FederationClient) LookupStateIDs

func (ac *FederationClient) LookupStateIDs(
	ctx context.Context, s ServerName, roomID, eventID string,
) (res RespStateIDs, err error)

LookupStateIDs retrieves the room state for a room at an event from a remote matrix server as lists of matrix event IDs.

func (*FederationClient) MSC2836EventRelationships

func (ac *FederationClient) MSC2836EventRelationships(
	ctx context.Context, dst ServerName, r MSC2836EventRelationshipsRequest, roomVersion RoomVersion,
) (res MSC2836EventRelationshipsResponse, err error)

MSC2836EventRelationships performs an MSC2836 /event_relationships request.

func (*FederationClient) MSC2946Spaces

func (ac *FederationClient) MSC2946Spaces(
	ctx context.Context, dst ServerName, roomID string, suggestedOnly bool,
) (res MSC2946SpacesResponse, err error)

func (*FederationClient) MakeJoin

func (ac *FederationClient) MakeJoin(
	ctx context.Context, s ServerName, roomID, userID string,
	roomVersions []RoomVersion,
) (res RespMakeJoin, err error)

MakeJoin makes a join m.room.member event for a room on a remote matrix server. This is used to join a room the local server isn't a member of. We need to query a remote server because if we aren't in the room we don't know what to use for the "prev_events" in the join event. The remote server should return us a m.room.member event for our local user with the "prev_events" filled out. If this successfully returns an acceptable event we will sign it with our server's key and pass it to SendJoin. See https://matrix.org/docs/spec/server_server/unstable.html#joining-rooms

func (*FederationClient) MakeLeave

func (ac *FederationClient) MakeLeave(
	ctx context.Context, s ServerName, roomID, userID string,
) (res RespMakeLeave, err error)

MakeLeave makes a leave m.room.member event for a room on a remote matrix server. This is used to reject a remote invite and is similar to MakeJoin. If this successfully returns an acceptable event we will sign it, replace the event_id with our own, and pass it to SendLeave. See https://matrix.org/docs/spec/server_server/r0.1.1.html#get-matrix-federation-v1-make-leave-roomid-userid

func (*FederationClient) Peek

func (ac *FederationClient) Peek(
	ctx context.Context, s ServerName, roomID, peekID string,
	roomVersions []RoomVersion,
) (res RespPeek, err error)

Peek starts a peek on a remote server: see MSC2753

func (*FederationClient) QueryKeys

func (ac *FederationClient) QueryKeys(ctx context.Context, s ServerName, keys map[string][]string) (res RespQueryKeys, err error)

QueryKeys queries E2E device keys from a remote server. https://matrix.org/docs/spec/server_server/latest#post-matrix-federation-v1-user-keys-query

func (*FederationClient) SendInvite

func (ac *FederationClient) SendInvite(
	ctx context.Context, s ServerName, event *Event,
) (res RespInvite, err error)

SendInvite sends an invite m.room.member event to an invited server to be signed by it. This is used to invite a user that is not on the local server.

func (*FederationClient) SendInviteV2

func (ac *FederationClient) SendInviteV2(
	ctx context.Context, s ServerName, request InviteV2Request,
) (res RespInviteV2, err error)

SendInviteV2 sends an invite m.room.member event to an invited server to be signed by it. This is used to invite a user that is not on the local server.

func (*FederationClient) SendJoin

func (ac *FederationClient) SendJoin(
	ctx context.Context, s ServerName, event *Event,
) (res RespSendJoin, err error)

SendJoin sends a join m.room.member event obtained using MakeJoin via a remote matrix server. This is used to join a room the local server isn't a member of. See https://matrix.org/docs/spec/server_server/unstable.html#joining-rooms

func (*FederationClient) SendJoinPartialState

func (ac *FederationClient) SendJoinPartialState(
	ctx context.Context, s ServerName, event *Event,
) (res RespSendJoin, err error)

SendJoinPartialState sends a join m.room.member event obtained using MakeJoin via a remote matrix server, with a parameter indicating we support partial state in the response. This is used to join a room the local server isn't a member of. See https://matrix.org/docs/spec/server_server/unstable.html#joining-rooms

func (*FederationClient) SendLeave

func (ac *FederationClient) SendLeave(
	ctx context.Context, s ServerName, event *Event,
) (err error)

SendLeave sends a leave m.room.member event obtained using MakeLeave via a remote matrix server. This is used to reject a remote invite. See https://matrix.org/docs/spec/server_server/r0.1.1.html#put-matrix-federation-v1-send-leave-roomid-eventid

func (*FederationClient) SendTransaction

func (ac *FederationClient) SendTransaction(
	ctx context.Context, t Transaction,
) (res RespSend, err error)

SendTransaction sends a transaction

type FederationRequest

type FederationRequest struct {
	// contains filtered or unexported fields
}

A FederationRequest is a request to send to a remote server or a request received from a remote server. Federation requests are signed by building a JSON object and signing it

func NewFederationRequest

func NewFederationRequest(method string, destination ServerName, requestURI string) FederationRequest

NewFederationRequest creates a matrix request. Takes an HTTP method, a destination homeserver and a request path which can have a query string. The destination is the name of a matrix homeserver. The request path must begin with a slash. Eg. NewFederationRequest("GET", "matrix.org", "/_matrix/federation/v1/send/123")

func VerifyHTTPRequest

func VerifyHTTPRequest(
	req *http.Request, now time.Time, destination ServerName, keys JSONVerifier,
) (*FederationRequest, util.JSONResponse)

VerifyHTTPRequest extracts and verifies the contents of a net/http.Request. It consumes the body of the request. The JSON content can be accessed using FederationRequest.Content() Returns an 400 error if there was a problem parsing the request. It authenticates the request using an ed25519 signature using the JSONVerifier. The origin server can be accessed using FederationRequest.Origin() Returns a 401 error if there was a problem authenticating the request. HTTP handlers using this should be careful that they only use the parts of the request that have been authenticated: the method, the request path, the query parameters, and the JSON content. In particular the version of HTTP and the headers aren't protected by the signature.

func (*FederationRequest) Content

func (r *FederationRequest) Content() []byte

Content returns the JSON content for the request.

func (*FederationRequest) Destination

func (r *FederationRequest) Destination() ServerName

Destination returns the server that the request was targeted to.

func (*FederationRequest) HTTPRequest

func (r *FederationRequest) HTTPRequest() (*http.Request, error)

HTTPRequest constructs an net/http.Request for this matrix request. The request can be passed to net/http.Client.Do().

func (*FederationRequest) Method

func (r *FederationRequest) Method() string

Method returns the JSON method for the request.

func (*FederationRequest) Origin

func (r *FederationRequest) Origin() ServerName

Origin returns the server that the request originated on.

func (*FederationRequest) RequestURI

func (r *FederationRequest) RequestURI() string

RequestURI returns the path and query sections of the HTTP request URL.

func (*FederationRequest) SetContent

func (r *FederationRequest) SetContent(content interface{}) error

SetContent sets the JSON content for the request. Returns an error if there already is JSON content present on the request.

func (*FederationRequest) Sign

func (r *FederationRequest) Sign(serverName ServerName, keyID KeyID, privateKey ed25519.PrivateKey) error

Sign the matrix request with an ed25519 key. Uses the algorithm specified https://matrix.org/docs/spec/server_server/unstable.html#request-authentication Updates the request with the signature in place. Returns an error if there was a problem signing the request.

type Filter

type Filter struct {
	EventFields []string    `json:"event_fields,omitempty"`
	EventFormat string      `json:"event_format,omitempty"`
	Presence    EventFilter `json:"presence,omitempty"`
	AccountData EventFilter `json:"account_data,omitempty"`
	Room        RoomFilter  `json:"room,omitempty"`
}

Filter is used by clients to specify how the server should filter responses to e.g. sync requests Specified by: https://matrix.org/docs/spec/client_server/r0.5.0.html#filtering

func DefaultFilter

func DefaultFilter() Filter

DefaultFilter returns the default filter used by the Matrix server if no filter is provided in the request

func (*Filter) Validate

func (filter *Filter) Validate() error

Validate checks if the filter contains valid property values

type HeaderedEvent

type HeaderedEvent struct {
	RoomVersion RoomVersion `json:"-"`
	*Event
}

HeaderedEvent is a wrapper around an Event that contains information about the room version. All header fields will be added into the event when marshalling into JSON and will be separated out when unmarshalling.

func HeaderedReverseTopologicalOrdering

func HeaderedReverseTopologicalOrdering(events []*HeaderedEvent, order TopologicalOrder) []*HeaderedEvent

HeaderedReverseTopologicalOrdering takes a set of input events and sorts them using Kahn's algorithm in order to topologically order them. The result array of events will be sorted so that "earlier" events appear first.

func RequestBackfill

func RequestBackfill(ctx context.Context, b BackfillRequester, keyRing JSONVerifier,
	roomID string, ver RoomVersion, fromEventIDs []string, limit int) ([]*HeaderedEvent, error)

RequestBackfill implements the server logic for making backfill requests to other servers. This handles server selection, fetching up to the request limit and verifying the received events. Event validation also includes authorisation checks, which may require additional state to be fetched.

The returned events are safe to be inserted into a database for later retrieval. It's possible for the number of returned events to be less than the limit, even if there exists more events. It's also possible for the number of returned events to be greater than the limit, if fromEventIDs > 1 and we need to ask multiple servers. We don't drop events greater than the limit because we've already done all the work to verify them, so it's up to the caller to decide what to do with them.

TODO: We should be able to make some guarantees for the caller about the returned events position in the DAG, but to verify it we need to know the prev_events of fromEventIDs.

TODO: When does it make sense to return errors?

func (HeaderedEvent) MarshalJSON

func (e HeaderedEvent) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

func (*HeaderedEvent) UnmarshalJSON

func (e *HeaderedEvent) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaller

func (*HeaderedEvent) UnmarshalJSONWithEventID

func (e *HeaderedEvent) UnmarshalJSONWithEventID(data []byte, eventID string) error

UnmarshalJSONWithEventID allows lighter unmarshalling when the event ID is already known, rather than burning CPU cycles calculating it again. If it isn't, supply "" instead.

func (*HeaderedEvent) Unwrap

func (e *HeaderedEvent) Unwrap() *Event

Unwrap extracts the event object from the headered event.

type HexString

type HexString []byte

A HexString is a string of bytes that are hex encoded when used in JSON. The bytes encoded using hex when marshalled as JSON. When the bytes are unmarshalled from JSON they are decoded from hex.

func (HexString) MarshalJSON

func (h HexString) MarshalJSON() ([]byte, error)

MarshalJSON encodes the bytes as hex and then encodes the hex as a JSON string. This takes a value receiver so that maps and slices of HexString encode correctly.

func (*HexString) UnmarshalJSON

func (h *HexString) UnmarshalJSON(raw []byte) (err error)

UnmarshalJSON decodes a JSON string and then decodes the resulting hex. This takes a pointer receiver because it needs to write the result of decoding.

type HistoryVisibilityContent

type HistoryVisibilityContent struct {
	HistoryVisibility string `json:"history_visibility"`
}

HistoryVisibilityContent is the JSON content of a m.room.history_visibility event. See https://matrix.org/docs/spec/client_server/r0.6.0#room-history-visibility for descriptions of the fields.

type InviteV2Request

type InviteV2Request struct {
	// contains filtered or unexported fields
}

InviteV2Request is used in the body of a /_matrix/federation/v2/invite request.

func NewInviteV2Request

func NewInviteV2Request(event *HeaderedEvent, state []InviteV2StrippedState) (
	request InviteV2Request, err error,
)

func (*InviteV2Request) Event

func (i *InviteV2Request) Event() *Event

Event returns the invite event.

func (*InviteV2Request) InviteRoomState

func (i *InviteV2Request) InviteRoomState() []InviteV2StrippedState

InviteRoomState returns stripped state events for the room, containing enough information for the client to identify the room.

func (InviteV2Request) MarshalJSON

func (i InviteV2Request) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

func (*InviteV2Request) RoomVersion

func (i *InviteV2Request) RoomVersion() RoomVersion

RoomVersion returns the room version of the invited room.

func (*InviteV2Request) UnmarshalJSON

func (i *InviteV2Request) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaller

type InviteV2StrippedState

type InviteV2StrippedState struct {
	// contains filtered or unexported fields
}

InviteV2StrippedState is a cut-down set of fields from room state events that allow the invited server to identify the room.

func NewInviteV2StrippedState

func NewInviteV2StrippedState(event *Event) (ss InviteV2StrippedState)

NewInviteV2StrippedState creates a stripped state event from a regular state event.

func (*InviteV2StrippedState) Content

func (i *InviteV2StrippedState) Content() RawJSON

Content returns the content of the stripped state.

func (InviteV2StrippedState) MarshalJSON

func (i InviteV2StrippedState) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

func (*InviteV2StrippedState) Sender

func (i *InviteV2StrippedState) Sender() string

Sender returns the sender of the stripped state.

func (*InviteV2StrippedState) StateKey

func (i *InviteV2StrippedState) StateKey() *string

StateKey returns the state key of the stripped state.

func (*InviteV2StrippedState) Type

func (i *InviteV2StrippedState) Type() string

Type returns the type of the stripped state.

func (*InviteV2StrippedState) UnmarshalJSON

func (i *InviteV2StrippedState) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaller

type JSONVerifier

type JSONVerifier interface {
	// VerifyJSONs performs bulk JSON signature verification for a list of VerifyJSONRequests.
	// Returns a list of VerifyJSONResults with the same length and order as the request list.
	// The caller should check the Result field for each entry to see if it was valid.
	// Returns an error if there was a problem talking to the database or one of the other methods
	// of fetching the public keys.
	VerifyJSONs(ctx context.Context, requests []VerifyJSONRequest) ([]VerifyJSONResult, error)
}

A JSONVerifier is an object which can verify the signatures of JSON messages.

type JoinRuleContent

type JoinRuleContent struct {
	// We use the join_rule key to check whether join m.room.member events are allowed.
	JoinRule string                     `json:"join_rule"`
	Allow    []JoinRuleContentAllowRule `json:"allow,omitempty"`
}

JoinRuleContent is the JSON content of a m.room.join_rules event needed for auth checks. See https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-join-rules for descriptions of the fields.

func NewJoinRuleContentFromAuthEvents

func NewJoinRuleContentFromAuthEvents(authEvents AuthEventProvider) (c JoinRuleContent, err error)

NewJoinRuleContentFromAuthEvents loads the join rule content from the join rules event in the auth event. Returns an error if there was an error loading the join rule event or parsing the content.

type JoinRuleContentAllowRule

type JoinRuleContentAllowRule struct {
	Type   string `json:"type"`
	RoomID string `json:"room_id"`
}

type KeyChecks

type KeyChecks struct {
	AllChecksOK        bool                    // Did all the checks pass?
	MatchingServerName bool                    // Does the server name match what was requested.
	FutureValidUntilTS bool                    // The valid until TS is in the future.
	HasEd25519Key      bool                    // The server has at least one ed25519 key.
	AllEd25519ChecksOK *bool                   // All the Ed25519 checks are ok. or null if there weren't any to check.
	Ed25519Checks      map[KeyID]Ed25519Checks // Checks for Ed25519 keys.
}

KeyChecks are the checks that should be applied to ServerKey responses.

func CheckKeys

func CheckKeys(
	serverName ServerName,
	now time.Time,
	keys ServerKeys,
) (
	checks KeyChecks,
	ed25519Keys map[KeyID]Base64Bytes,
)

CheckKeys checks the keys returned from a server to make sure they are valid. If the checks pass then also return a map of key_id to Ed25519 public key

type KeyClient

type KeyClient interface {
	GetServerKeys(ctx context.Context, matrixServer ServerName) (ServerKeys, error)
	LookupServerKeys(ctx context.Context, matrixServer ServerName, keyRequests map[PublicKeyLookupRequest]Timestamp) ([]ServerKeys, error)
}

type KeyDatabase

type KeyDatabase interface {
	KeyFetcher
	// Add a block of public keys to the database.
	// Returns an error if there was a problem storing the keys.
	// A database is not required to rollback storing the all keys if some of
	// the keys aren't stored, and an in-progess store may be partially visible
	// to a concurrent FetchKeys(). This is acceptable since the database is
	// only used as a cache for the keys, so if a FetchKeys() races with a
	// StoreKeys() and some of the keys are missing they will be just be refetched.
	StoreKeys(ctx context.Context, results map[PublicKeyLookupRequest]PublicKeyLookupResult) error
}

A KeyDatabase is a store for caching public keys.

type KeyFetcher

type KeyFetcher interface {
	// Lookup a batch of public keys.
	// Takes a map from (server name, key ID) pairs to timestamp.
	// The timestamp is when the keys need to be vaild up to.
	// Returns a map from (server name, key ID) pairs to server key objects for
	// that server name containing that key ID
	// The result may have fewer (server name, key ID) pairs than were in the request.
	// The result may have more (server name, key ID) pairs than were in the request.
	// Returns an error if there was a problem fetching the keys.
	FetchKeys(ctx context.Context, requests map[PublicKeyLookupRequest]Timestamp) (map[PublicKeyLookupRequest]PublicKeyLookupResult, error)

	// FetcherName returns the name of this fetcher, which can then be used for
	// logging errors etc.
	FetcherName() string
}

A KeyFetcher is a way of fetching public keys in bulk.

type KeyID

type KeyID string

A KeyID is the ID of a ed25519 key used to sign JSON. The key IDs have a format of "ed25519:[0-9A-Za-z]+" If we switch to using a different signing algorithm then we will change the prefix used.

func ListKeyIDs

func ListKeyIDs(signingName string, message []byte) ([]KeyID, error)

ListKeyIDs lists the key IDs a given entity has signed a message with.

type KeyRing

type KeyRing struct {
	KeyFetchers []KeyFetcher
	KeyDatabase KeyDatabase
}

A KeyRing stores keys for matrix servers and provides methods for verifying JSON messages.

func (KeyRing) VerifyJSONs

func (k KeyRing) VerifyJSONs(ctx context.Context, requests []VerifyJSONRequest) ([]VerifyJSONResult, error)

VerifyJSONs implements JSONVerifier.

type MSC2836EventRelationshipsRequest

type MSC2836EventRelationshipsRequest struct {
	EventID         string `json:"event_id"`
	MaxDepth        int    `json:"max_depth"`
	MaxBreadth      int    `json:"max_breadth"`
	Limit           int    `json:"limit"`
	DepthFirst      bool   `json:"depth_first"`
	RecentFirst     bool   `json:"recent_first"`
	IncludeParent   bool   `json:"include_parent"`
	IncludeChildren bool   `json:"include_children"`
	Direction       string `json:"direction"`
	Batch           string `json:"batch"`
	AutoJoin        bool   `json:"auto_join"`
}

MSC2836EventRelationshipsRequest is a request to /event_relationships from https://github.com/matrix-org/matrix-doc/blob/kegan/msc/threading/proposals/2836-threading.md nolint:maligned

func NewMSC2836EventRelationshipsRequest

func NewMSC2836EventRelationshipsRequest(body io.Reader) (*MSC2836EventRelationshipsRequest, error)

NewMSC2836EventRelationshipsRequest creates a new MSC2836 /event_relationships request with defaults set. https://github.com/matrix-org/matrix-doc/blob/kegan/msc/threading/proposals/2836-threading.md

func (*MSC2836EventRelationshipsRequest) Defaults

func (r *MSC2836EventRelationshipsRequest) Defaults()

Defaults sets default values.

type MSC2836EventRelationshipsResponse

type MSC2836EventRelationshipsResponse struct {
	Events    EventJSONs `json:"events"`
	NextBatch string     `json:"next_batch"`
	Limited   bool       `json:"limited"`
	AuthChain EventJSONs `json:"auth_chain"`
}

MSC2836EventRelationshipsResponse is a response to /event_relationships from https://github.com/matrix-org/matrix-doc/blob/kegan/msc/threading/proposals/2836-threading.md

type MSC2946Room

type MSC2946Room struct {
	PublicRoom
	ChildrenState  []MSC2946StrippedEvent `json:"children_state"`
	AllowedRoomIDs []string               `json:"allowed_room_ids,omitempty"`
	RoomType       string                 `json:"room_type"`
}

MSC2946Room represents a public room with additional metadata on the space directory

type MSC2946SpacesResponse

type MSC2946SpacesResponse struct {
	Room                 MSC2946Room   `json:"room"`
	Children             []MSC2946Room `json:"children"`
	InaccessibleChildren []string      `json:"inaccessible_children"`
}

MSC2946SpacesResponse is the HTTP response body for the federation /unstable/spaces/{roomID} endpoint See https://github.com/matrix-org/matrix-doc/pull/2946

type MSC2946StrippedEvent

type MSC2946StrippedEvent struct {
	Type           string          `json:"type"`
	StateKey       string          `json:"state_key"`
	Content        json.RawMessage `json:"content"`
	Sender         string          `json:"sender"`
	RoomID         string          `json:"room_id"`
	OriginServerTS Timestamp       `json:"origin_server_ts"`
}

MSC2946StrippedEvent is the format of events returned in the HTTP response body

type MemberContent

type MemberContent struct {
	// We use the membership key in order to check if the user is in the room.
	Membership  string `json:"membership"`
	DisplayName string `json:"displayname,omitempty"`
	AvatarURL   string `json:"avatar_url,omitempty"`
	Reason      string `json:"reason,omitempty"`
	IsDirect    bool   `json:"is_direct,omitempty"`
	// We use the third_party_invite key to special case thirdparty invites.
	ThirdPartyInvite *MemberThirdPartyInvite `json:"third_party_invite,omitempty"`
	// Restricted join rules require a user with invite permission to be nominated,
	// so that their membership can be included in the auth events.
	AuthorisedVia string `json:"join_authorised_via_users_server,omitempty"`
}

MemberContent is the JSON content of a m.room.member event needed for auth checks. See https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-member for descriptions of the fields.

func NewMemberContentFromAuthEvents

func NewMemberContentFromAuthEvents(authEvents AuthEventProvider, userID string) (c MemberContent, err error)

NewMemberContentFromAuthEvents loads the member content from the member event for the user ID in the auth events. Returns an error if there was an error loading the member event or parsing the event content.

func NewMemberContentFromEvent

func NewMemberContentFromEvent(event *Event) (c MemberContent, err error)

NewMemberContentFromEvent parse the member content from an event. Returns an error if the content couldn't be parsed.

type MemberThirdPartyInvite

type MemberThirdPartyInvite struct {
	DisplayName string                       `json:"display_name"`
	Signed      MemberThirdPartyInviteSigned `json:"signed"`
}

MemberThirdPartyInvite is the "Invite" structure defined at http://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-member

type MemberThirdPartyInviteSigned

type MemberThirdPartyInviteSigned struct {
	MXID       string                       `json:"mxid"`
	Signatures map[string]map[string]string `json:"signatures"`
	Token      string                       `json:"token"`
}

MemberThirdPartyInviteSigned is the "signed" structure defined at http://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-member

type MissingAuthEventError

type MissingAuthEventError struct {
	AuthEventID string
	ForEventID  string
}

MissingAuthEventError refers to a situation where one of the auth event for a given event was not found.

func (MissingAuthEventError) Error

func (e MissingAuthEventError) Error() string

type MissingEvents

type MissingEvents struct {
	// The maximum number of events to retrieve.
	Limit int `json:"limit"`
	// The minimum depth of events to retrieve.
	MinDepth int `json:"min_depth"`
	// The latest event IDs that the sender already has.
	EarliestEvents []string `json:"earliest_events"`
	// The event IDs to retrieve the previous events for.
	LatestEvents []string `json:"latest_events"`
}

MissingEvents represents a request for missing events. https://matrix.org/docs/spec/server_server/r0.1.3#post-matrix-federation-v1-get-missing-events-roomid

type NotAllowed

type NotAllowed struct {
	Message string
}

A NotAllowed error is returned if an event does not pass the auth checks.

func (*NotAllowed) Error

func (a *NotAllowed) Error() string

type OldVerifyKey

type OldVerifyKey struct {
	VerifyKey
	// When this key stopped being valid for event signing in milliseconds.
	ExpiredTS Timestamp `json:"expired_ts"`
}

An OldVerifyKey is an old ed25519 public key that is no longer valid.

type PDUResult

type PDUResult struct {
	// If not empty then this is a human readable description of a problem
	// encountered processing an event.
	Error string `json:"error,omitempty"`
}

A PDUResult is the result of processing a matrix room event.

type PerspectiveKeyFetcher

type PerspectiveKeyFetcher struct {
	// The name of the perspective server to fetch keys from.
	PerspectiveServerName ServerName
	// The ed25519 public keys the perspective server must sign responses with.
	PerspectiveServerKeys map[KeyID]ed25519.PublicKey
	// The federation client to use to fetch keys with.
	Client KeyClient
}

A PerspectiveKeyFetcher fetches server keys from a single perspective server.

func (*PerspectiveKeyFetcher) FetchKeys

FetchKeys implements KeyFetcher

func (PerspectiveKeyFetcher) FetcherName

func (p PerspectiveKeyFetcher) FetcherName() string

FetcherName implements KeyFetcher

type PowerLevelContent

type PowerLevelContent struct {
	Ban           int64            `json:"ban"`
	Invite        int64            `json:"invite"`
	Kick          int64            `json:"kick"`
	Redact        int64            `json:"redact"`
	Users         map[string]int64 `json:"users"`
	UsersDefault  int64            `json:"users_default"`
	Events        map[string]int64 `json:"events"`
	EventsDefault int64            `json:"events_default"`
	StateDefault  int64            `json:"state_default"`
	Notifications map[string]int64 `json:"notifications"`
}

PowerLevelContent is the JSON content of a m.room.power_levels event needed for auth checks. Typically the user calls NewPowerLevelContentFromAuthEvents instead of unmarshalling the content directly from JSON so defaults can be applied. However, the JSON key names are still preserved so it's possible to marshal the struct into JSON easily. See https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-power-levels for descriptions of the fields.

func NewPowerLevelContentFromAuthEvents

func NewPowerLevelContentFromAuthEvents(authEvents AuthEventProvider, creatorUserID string) (c PowerLevelContent, err error)

NewPowerLevelContentFromAuthEvents loads the power level content from the power level event in the auth events or returns the default values if there is no power level event.

func NewPowerLevelContentFromEvent

func NewPowerLevelContentFromEvent(event *Event) (c PowerLevelContent, err error)

NewPowerLevelContentFromEvent loads the power level content from an event.

func (*PowerLevelContent) Defaults

func (c *PowerLevelContent) Defaults()

Defaults sets the power levels to their default values. See https://spec.matrix.org/v1.1/client-server-api/#mroompower_levels for defaults.

func (*PowerLevelContent) EventLevel

func (c *PowerLevelContent) EventLevel(eventType string, isState bool) int64

EventLevel returns the power level needed to send an event in the room.

func (*PowerLevelContent) NotificationLevel

func (c *PowerLevelContent) NotificationLevel(notification string) int64

UserLevel returns the power level a user has in the room.

func (*PowerLevelContent) UserLevel

func (c *PowerLevelContent) UserLevel(userID string) int64

UserLevel returns the power level a user has in the room.

type PreviousRoom

type PreviousRoom struct {
	RoomID  string `json:"room_id"`
	EventID string `json:"event_id"`
}

PreviousRoom is the "Previous Room" structure defined at https://matrix.org/docs/spec/client_server/r0.5.0#m-room-create

type PublicKey

type PublicKey struct {
	PublicKey      Base64Bytes `json:"public_key"`
	KeyValidityURL string      `json:"key_validity_url"`
}

PublicKey is the "PublicKeys" structure defined at https://matrix.org/docs/spec/client_server/r0.5.0#m-room-third-party-invite

type PublicKeyLookupRequest

type PublicKeyLookupRequest struct {
	// The server to fetch a key for.
	ServerName ServerName `json:"server_name"`
	// The ID of the key to fetch.
	KeyID KeyID `json:"key_id"`
}

A PublicKeyLookupRequest is a request for a public key with a particular key ID.

func (PublicKeyLookupRequest) MarshalText

func (r PublicKeyLookupRequest) MarshalText() ([]byte, error)

MarshalText turns the public key lookup request into a string format, which allows us to use it as a JSON map key.

func (*PublicKeyLookupRequest) UnmarshalText

func (r *PublicKeyLookupRequest) UnmarshalText(text []byte) error

UnmarshalText turns the string format back into a public key lookup request, from a JSON map key.

type PublicKeyLookupResult

type PublicKeyLookupResult struct {
	VerifyKey
	// if this key has expired, the time it stopped being valid for event signing in milliseconds.
	// if the key has not expired, the magic value PublicKeyNotExpired.
	ExpiredTS Timestamp `json:"expired_ts"`
	// When this result is valid until in milliseconds.
	// if the key has expired, the magic value PublicKeyNotValid.
	ValidUntilTS Timestamp `json:"valid_until_ts"`
}

A PublicKeyLookupResult is the result of looking up a server signing key.

func (PublicKeyLookupResult) WasValidAt

func (r PublicKeyLookupResult) WasValidAt(atTs Timestamp, strictValidityChecking bool) bool

WasValidAt checks if this signing key is valid for an event signed at the given timestamp.

type PublicKeyNotaryLookupRequest

type PublicKeyNotaryLookupRequest struct {
	ServerKeys map[ServerName]map[KeyID]PublicKeyNotaryQueryCriteria `json:"server_keys"`
}

type PublicKeyNotaryQueryCriteria

type PublicKeyNotaryQueryCriteria struct {
	MinimumValidUntilTS Timestamp `json:"minimum_valid_until_ts"`
}

type PublicRoom

type PublicRoom struct {
	// Aliases of the room. May be empty.
	Aliases []string `json:"aliases,omitempty"`
	// The canonical alias of the room, if any.
	CanonicalAlias string `json:"canonical_alias,omitempty"`
	// The name of the room, if any.
	Name string `json:"name,omitempty"`
	// The number of members joined to the room.
	JoinedMembersCount int `json:"num_joined_members"`
	// The ID of the room.
	RoomID string `json:"room_id"`
	// The topic of the room, if any.
	Topic string `json:"topic,omitempty"`
	// Whether the room may be viewed by guest users without joining.
	WorldReadable bool `json:"world_readable"`
	// Whether guest users may join the room and participate in it. If they can, they will be subject to ordinary power level rules like any other user.
	GuestCanJoin bool `json:"guest_can_join"`
	// The URL for the room's avatar, if one is set.
	AvatarURL string `json:"avatar_url,omitempty"`
}

PublicRoom stores the info of a room returned by GET /_matrix/federation/v1/publicRooms

type RawJSON

type RawJSON []byte

RawJSON is a reimplementation of json.RawMessage that supports being used as a value type

For example:

 jsonBytes, _ := json.Marshal(struct{
		RawMessage json.RawMessage
		RawJSON RawJSON
	}{
		json.RawMessage(`"Hello"`),
		RawJSON(`"World"`),
	})

Results in:

{"RawMessage":"IkhlbGxvIg==","RawJSON":"World"}

See https://play.golang.org/p/FzhKIJP8-I for a full example.

func (RawJSON) MarshalJSON

func (r RawJSON) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface using a value receiver. This means that RawJSON used as an embedded value will still encode correctly.

func (RawJSON) TrustedEvent

func (e RawJSON) TrustedEvent(roomVersion RoomVersion, redacted bool) (*Event, error)

func (*RawJSON) UnmarshalJSON

func (r *RawJSON) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaller interface using a pointer receiver.

func (RawJSON) UntrustedEvent

func (e RawJSON) UntrustedEvent(roomVersion RoomVersion) (*Event, error)

type RedactionAlgorithm

type RedactionAlgorithm int

RedactionAlgorithm refers to the redaction algorithm used in a room version.

const (
	RedactionAlgorithmV1 RedactionAlgorithm = iota + 1 // default algorithm
	RedactionAlgorithmV2                               // no special meaning for m.room.aliases
	RedactionAlgorithmV3                               // protects join rules 'allow' key
	RedactionAlgorithmV4                               // protects membership 'join_authorised_via_users_server' key
)

Redaction algorithm.

type ResolutionResult

type ResolutionResult struct {
	Destination   string     // The hostname and port to send federation requests to.
	Host          ServerName // The value of the Host headers.
	TLSServerName string     // The TLS server name to request a certificate for.
}

ResolutionResult is a result of looking up a Matrix homeserver according to the federation specification.

func ResolveServer

func ResolveServer(ctx context.Context, serverName ServerName) (results []ResolutionResult, err error)

ResolveServer implements the server name resolution algorithm described at https://matrix.org/docs/spec/server_server/r0.1.1.html#resolving-server-names Returns a slice of ResolutionResult that can be used to send a federation request to the server using a given server name. Returns an error if the server name isn't valid.

type RespClaimKeys

type RespClaimKeys struct {
	// Required. One-time keys for the queried devices. A map from user ID, to a map from devices to a map
	// from <algorithm>:<key_id> to the key object or a string.
	OneTimeKeys map[string]map[string]map[string]json.RawMessage `json:"one_time_keys"`
}

RespClaimKeys is the response for https://matrix.org/docs/spec/server_server/latest#post-matrix-federation-v1-user-keys-claim

type RespDirectory

type RespDirectory struct {
	// The matrix room ID the room alias corresponds to.
	RoomID string `json:"room_id"`
	// A list of matrix servers that the directory server thinks could be used
	// to join the room. The joining server may need to try multiple servers
	// before it finds one that it can use to join the room.
	Servers []ServerName `json:"servers"`
}

A RespDirectory is the content of a response to GET /_matrix/federation/v1/query/directory This is returned when looking up a room alias from a remote server. See https://matrix.org/docs/spec/server_server/unstable.html#directory

type RespEventAuth

type RespEventAuth struct {
	// A list of events needed to authenticate the state events.
	AuthEvents EventJSONs `json:"auth_chain"`
}

A RespEventAuth is the content of a response to GET /_matrix/federation/v1/event_auth/{roomID}/{eventID}

type RespInvite

type RespInvite struct {
	// The invite event signed by recipient server.
	Event RawJSON `json:"event"`
}

RespInvite is the content of a response to PUT /_matrix/federation/v1/invite/{roomID}/{eventID}

func (RespInvite) MarshalJSON

func (r RespInvite) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

func (*RespInvite) UnmarshalJSON

func (r *RespInvite) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaller

type RespInviteV2

type RespInviteV2 struct {
	// The invite event signed by recipient server.
	Event RawJSON `json:"event"`
}

RespInvite is the content of a response to PUT /_matrix/federation/v2/invite/{roomID}/{eventID}

type RespMakeJoin

type RespMakeJoin struct {
	// An incomplete m.room.member event for a user on the requesting server
	// generated by the responding server.
	// See https://matrix.org/docs/spec/server_server/unstable.html#joining-rooms
	JoinEvent   EventBuilder `json:"event"`
	RoomVersion RoomVersion  `json:"room_version"`
}

A RespMakeJoin is the content of a response to GET /_matrix/federation/v2/make_join/{roomID}/{userID}

type RespMakeLeave

type RespMakeLeave struct {
	// An incomplete m.room.member event for a user on the requesting server
	// generated by the responding server.
	// See https://matrix.org/docs/spec/server_server/r0.1.1.html#get-matrix-federation-v1-make-leave-roomid-userid
	LeaveEvent EventBuilder `json:"event"`
	// The room version that we're trying to leave.
	RoomVersion RoomVersion `json:"room_version"`
}

A RespMakeLeave is the content of a response to GET /_matrix/federation/v2/make_leave/{roomID}/{userID}

type RespMissingEvents

type RespMissingEvents struct {
	// The returned set of missing events.
	Events EventJSONs `json:"events"`
}

A RespMissingEvents is the content of a response to GET /_matrix/federation/v1/get_missing_events/{roomID}

type RespPeek

type RespPeek struct {
	// How often should we renew the peek?
	RenewalInterval int64 `json:"renewal_interval"`
	// A list of events giving the state of the room at the point of the request
	StateEvents EventJSONs `json:"state"`
	// A list of events needed to authenticate the state events.
	AuthEvents EventJSONs `json:"auth_chain"`
	// The room version that we're trying to peek.
	RoomVersion RoomVersion `json:"room_version"`
	// The ID of the event whose state snapshot this is - i.e. the
	// most recent forward extremity in the room.
	LatestEvent *Event `json:"latest_event"`
}

A RespPeek is the content of a response to GET /_matrix/federation/v1/peek/{roomID}/{peekID}

func (RespPeek) MarshalJSON

func (r RespPeek) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

func (RespPeek) ToRespState

func (r RespPeek) ToRespState() RespState

ToRespState returns a new RespState with the same data from the given RespPeek

type RespProfile

type RespProfile struct {
	DisplayName string `json:"displayname,omitempty"`
	AvatarURL   string `json:"avatar_url,omitempty"`
}

RespProfile is the content of a response to GET /_matrix/federation/v1/query/profile

type RespPublicRooms

type RespPublicRooms struct {
	// A paginated chunk of public rooms.
	Chunk []PublicRoom `json:"chunk"`
	// A pagination token for the response. The absence of this token means there are no more results to fetch and the client should stop paginating.
	NextBatch string `json:"next_batch,omitempty"`
	// A pagination token that allows fetching previous results. The absence of this token means there are no results before this batch, i.e. this is the first batch.
	PrevBatch string `json:"prev_batch,omitempty"`
	// An estimate on the total number of public rooms, if the server has an estimate.
	TotalRoomCountEstimate int `json:"total_room_count_estimate,omitempty"`
}

RespPublicRooms is the content of a response to GET /_matrix/federation/v1/publicRooms

type RespQueryKeys

type RespQueryKeys struct {
	DeviceKeys      map[string]map[string]DeviceKeys `json:"device_keys"`
	MasterKeys      map[string]CrossSigningKey       `json:"master_keys"`
	SelfSigningKeys map[string]CrossSigningKey       `json:"self_signing_keys"`
}

RespQueryKeys is the response for https://matrix.org/docs/spec/server_server/latest#post-matrix-federation-v1-user-keys-query

type RespSend

type RespSend struct {
	// Map of event ID to the result of processing that event.
	PDUs map[string]PDUResult `json:"pdus"`
}

A RespSend is the content of a response to PUT /_matrix/federation/v1/send/{txnID}/

type RespSendJoin

type RespSendJoin struct {
	// A list of events giving the state of the room before the request event.
	StateEvents EventJSONs `json:"state"`
	// A list of events needed to authenticate the state events.
	AuthEvents EventJSONs `json:"auth_chain"`
	// The server that originated the event.
	Origin ServerName `json:"origin"`
	// The returned join event from the remote server. Used for restricted joins,
	// but not guaranteed to be present as it's only since MSC3083.
	Event *Event `json:"event,omitempty"`
	// true if the state is incomplete
	PartialState bool `json:"org.matrix.msc3706.partial_state"`
	// a list of servers in the room. Only returned if partial_state is set.
	ServersInRoom []string `json:"org.matrix.msc3706.servers_in_room"`
}

A RespSendJoin is the content of a response to PUT /_matrix/federation/v2/send_join/{roomID}/{eventID}

func (*RespSendJoin) Check

func (r *RespSendJoin) Check(ctx context.Context, roomVersion RoomVersion, keyRing JSONVerifier, joinEvent *Event, missingAuth AuthChainProvider) (*RespState, error)

Check that a response to /send_join is valid. If it is then it returns a reference to the RespState that contains the room state excluding any events that failed signature checks. This checks that it would be valid as a response to /state. This also checks that the join event is allowed by the state. This function mutates the RespSendJoin to remove any events from AuthEvents or StateEvents that do not have valid signatures.

func (RespSendJoin) MarshalJSON

func (r RespSendJoin) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

func (RespSendJoin) ToRespState

func (r RespSendJoin) ToRespState() RespState

ToRespState returns a new RespState with the same data from the given RespSendJoin

type RespState

type RespState struct {
	// A list of events giving the state of the room before the request event.
	StateEvents EventJSONs `json:"pdus"`
	// A list of events needed to authenticate the state events.
	AuthEvents EventJSONs `json:"auth_chain"`
}

A RespState is the content of a response to GET /_matrix/federation/v1/state/{roomID}/{eventID}

func (*RespState) Check

func (r *RespState) Check(ctx context.Context, roomVersion RoomVersion, keyRing JSONVerifier, missingAuth AuthChainProvider) ([]*Event, []*Event, error)

Check that a response to /state is valid. This function mutates the RespState to remove any events from AuthEvents or StateEvents that do not have valid signatures, and also returns the unmarshalled auth events (first return parameter) and state events (second return parameter).

func (RespState) Events

func (r RespState) Events(roomVersion RoomVersion) []*Event

Events combines the auth events and the state events and returns them in an order where every event comes after its auth events. Each event will only appear once in the output list.

func (RespState) MarshalJSON

func (r RespState) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

type RespStateIDs

type RespStateIDs struct {
	// A list of state event IDs for the state of the room before the requested event.
	StateEventIDs []string `json:"pdu_ids"`
	// A list of event IDs needed to authenticate the state events.
	AuthEventIDs []string `json:"auth_chain_ids"`
}

A RespStateIDs is the content of a response to GET /_matrix/federation/v1/state_ids/{roomID}/{eventID}

type RespUserDevice

type RespUserDevice struct {
	DeviceID    string             `json:"device_id"`
	DisplayName string             `json:"device_display_name"`
	Keys        RespUserDeviceKeys `json:"keys"`
}

RespUserDevice are embedded in RespUserDevices https://matrix.org/docs/spec/server_server/latest#get-matrix-federation-v1-user-devices-userid

type RespUserDeviceKeys

type RespUserDeviceKeys struct {
	UserID     string   `json:"user_id"`
	DeviceID   string   `json:"device_id"`
	Algorithms []string `json:"algorithms"`
	// E.g "curve25519:JLAFKJWSCS": "3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI"
	Keys map[KeyID]Base64Bytes `json:"keys"`
	// E.g "@alice:example.com": {
	//	"ed25519:JLAFKJWSCS": "dSO80A01XiigH3uBiDVx/EjzaoycHcjq9lfQX0uWsqxl2giMIiSPR8a4d291W1ihKJL/a+myXS367WT6NAIcBA"
	// }
	Signatures map[string]map[KeyID]Base64Bytes `json:"signatures"`
}

RespUserDeviceKeys are embedded in RespUserDevice https://matrix.org/docs/spec/server_server/latest#get-matrix-federation-v1-user-devices-userid

type RespUserDevices

type RespUserDevices struct {
	UserID         string           `json:"user_id"`
	StreamID       int64            `json:"stream_id"`
	Devices        []RespUserDevice `json:"devices"`
	MasterKey      *CrossSigningKey `json:"master_key"`
	SelfSigningKey *CrossSigningKey `json:"self_signing_key"`
}

RespUserDevices contains a response to /_matrix/federation/v1/user/devices/{userID} https://matrix.org/docs/spec/server_server/latest#get-matrix-federation-v1-user-devices-userid

type RoomEventFilter

type RoomEventFilter struct {
	Limit                   int       `json:"limit,omitempty"`
	NotSenders              *[]string `json:"not_senders,omitempty"`
	NotTypes                *[]string `json:"not_types,omitempty"`
	Senders                 *[]string `json:"senders,omitempty"`
	Types                   *[]string `json:"types,omitempty"`
	LazyLoadMembers         bool      `json:"lazy_load_members,omitempty"`
	IncludeRedundantMembers bool      `json:"include_redundant_members,omitempty"`
	NotRooms                *[]string `json:"not_rooms,omitempty"`
	Rooms                   *[]string `json:"rooms,omitempty"`
	ContainsURL             *bool     `json:"contains_url,omitempty"`
}

RoomEventFilter is used to define filtering rules for events in rooms

func DefaultRoomEventFilter

func DefaultRoomEventFilter() RoomEventFilter

DefaultRoomEventFilter returns the default room event filter used by the Matrix server if no filter is provided in the request

type RoomFilter

type RoomFilter struct {
	NotRooms     *[]string       `json:"not_rooms,omitempty"`
	Rooms        *[]string       `json:"rooms,omitempty"`
	Ephemeral    RoomEventFilter `json:"ephemeral,omitempty"`
	IncludeLeave bool            `json:"include_leave,omitempty"`
	State        StateFilter     `json:"state,omitempty"`
	Timeline     RoomEventFilter `json:"timeline,omitempty"`
	AccountData  RoomEventFilter `json:"account_data,omitempty"`
}

RoomFilter is used to define filtering rules for room-related events

type RoomVersion

type RoomVersion string

RoomVersion refers to the room version for a specific room.

const (
	RoomVersionV1 RoomVersion = "1"
	RoomVersionV2 RoomVersion = "2"
	RoomVersionV3 RoomVersion = "3"
	RoomVersionV4 RoomVersion = "4"
	RoomVersionV5 RoomVersion = "5"
	RoomVersionV6 RoomVersion = "6"
	RoomVersionV7 RoomVersion = "7"
	RoomVersionV8 RoomVersion = "8"
	RoomVersionV9 RoomVersion = "9"
)

Room version constants. These are strings because the version grammar allows for future expansion. https://matrix.org/docs/spec/#room-version-grammar

func (RoomVersion) AllowKnockingInEventAuth

func (v RoomVersion) AllowKnockingInEventAuth() (bool, error)

AllowKnockingInEventAuth returns true if the given room version allows for the `knock` membership state or false otherwise.

func (RoomVersion) AllowRestrictedJoinsInEventAuth

func (v RoomVersion) AllowRestrictedJoinsInEventAuth() (bool, error)

AllowRestrictedJoinsInEventAuth returns true if the given room version allows for memberships signed by servers in the restricted join rules.

func (RoomVersion) EnforceCanonicalJSON

func (v RoomVersion) EnforceCanonicalJSON() (bool, error)

PowerLevelsIncludeNotifications returns true if the given room version calls for the power level checks to cover the `notifications` key or false otherwise.

func (RoomVersion) EventFormat

func (v RoomVersion) EventFormat() (EventFormat, error)

EventFormat returns the event format for the given room version.

func (RoomVersion) EventIDFormat

func (v RoomVersion) EventIDFormat() (EventIDFormat, error)

EventIDFormat returns the event ID format for the given room version.

func (RoomVersion) PowerLevelsIncludeNotifications

func (v RoomVersion) PowerLevelsIncludeNotifications() (bool, error)

PowerLevelsIncludeNotifications returns true if the given room version calls for the power level checks to cover the `notifications` key or false otherwise.

func (RoomVersion) RedactionAlgorithm

func (v RoomVersion) RedactionAlgorithm() (RedactionAlgorithm, error)

RedactionAlgorithm returns the redaction algorithm for the given room version.

func (RoomVersion) RequireIntegerPowerLevels

func (v RoomVersion) RequireIntegerPowerLevels() (bool, error)

RequireIntegerPowerLevels returns true if the given room version calls for power levels as integers only, false otherwise.

func (RoomVersion) StateResAlgorithm

func (v RoomVersion) StateResAlgorithm() (StateResAlgorithm, error)

StateResAlgorithm returns the state resolution for the given room version.

func (RoomVersion) StrictValidityChecking

func (v RoomVersion) StrictValidityChecking() (bool, error)

StrictValidityChecking returns true if the given room version calls for strict signature checking (room version 5 and onward) or false otherwise.

type RoomVersionDescription

type RoomVersionDescription struct {
	Supported bool
	Stable    bool
	// contains filtered or unexported fields
}

RoomVersionDescription contains information about a given room version, e.g. which state resolution algorithm or event ID format to use. RoomVersionDescription contains information about a room version, namely whether it is marked as supported or stable in this server version, along with the state resolution algorithm, event ID etc formats used.

A version is supported if the server has some support for rooms that are this version. A version is marked as stable or unstable in order to hint whether the version should be used to clients calling the /capabilities endpoint. https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-capabilities

type SendToDeviceEvent

type SendToDeviceEvent struct {
	Sender  string          `json:"sender"`
	Type    string          `json:"type"`
	Content json.RawMessage `json:"content"`
}

type ServerKeyFields

type ServerKeyFields struct {
	// The name of the server
	ServerName ServerName `json:"server_name"`
	// The current signing keys in use on this server.
	// The keys of the map are the IDs of the keys.
	// These are valid while this response is valid.
	VerifyKeys map[KeyID]VerifyKey `json:"verify_keys"`
	// When this result is valid until in milliseconds.
	ValidUntilTS Timestamp `json:"valid_until_ts"`
	// Old keys that are now only valid for checking historic events.
	// The keys of the map are the IDs of the keys.
	OldVerifyKeys map[KeyID]OldVerifyKey `json:"old_verify_keys"`
}

ServerKeyFields are the parsed JSON contents of the ed25519 signing keys published by a matrix server.

type ServerKeys

type ServerKeys struct {
	// Copy of the raw JSON for signature checking.
	Raw []byte
	// The decoded JSON fields.
	ServerKeyFields
}

ServerKeys are the ed25519 signing keys published by a matrix server. Contains SHA256 fingerprints of the TLS X509 certificates used by the server.

func (ServerKeys) MarshalJSON

func (keys ServerKeys) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (ServerKeys) PublicKey

func (keys ServerKeys) PublicKey(keyID KeyID, atTS Timestamp) []byte

PublicKey returns a public key with the given ID valid at the given TS or nil if no such key exists.

func (*ServerKeys) UnmarshalJSON

func (keys *ServerKeys) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler

type ServerName

type ServerName string

A ServerName is the name a matrix homeserver is identified by. It is a DNS name or IP address optionally followed by a port.

https://matrix.org/docs/spec/appendices.html#server-name

func SplitID

func SplitID(sigil byte, id string) (local string, domain ServerName, err error)

SplitID splits a matrix ID into a local part and a server name.

Example
localpart, domain, err := SplitID('@', "@alice:localhost:8080")
if err != nil {
	panic(err)
}
fmt.Println(localpart, domain)
Output:

alice localhost:8080

type StateFilter

type StateFilter struct {
	Limit                   int       `json:"limit,omitempty"`
	NotSenders              *[]string `json:"not_senders,omitempty"`
	NotTypes                *[]string `json:"not_types,omitempty"`
	Senders                 *[]string `json:"senders,omitempty"`
	Types                   *[]string `json:"types,omitempty"`
	LazyLoadMembers         bool      `json:"lazy_load_members,omitempty"`
	IncludeRedundantMembers bool      `json:"include_redundant_members,omitempty"`
	NotRooms                *[]string `json:"not_rooms,omitempty"`
	Rooms                   *[]string `json:"rooms,omitempty"`
	ContainsURL             *bool     `json:"contains_url,omitempty"`
}

StateFilter is used to define filtering rules for state events

func DefaultStateFilter

func DefaultStateFilter() StateFilter

DefaultStateFilter returns the default state event filter used by the Matrix server if no filter is provided in the request

type StateKeyTuple

type StateKeyTuple struct {
	// The "type" key of a matrix event.
	EventType string
	// The "state_key" of a matrix event.
	// The empty string is a legitimate value for the "state_key" in matrix
	// so take care to initialise this field lest you accidentally request a
	// "state_key" with the go default of the empty string.
	StateKey string
}

A StateKeyTuple is the combination of an event type and an event state key. It is often used as a key in maps.

type StateNeeded

type StateNeeded struct {
	// Is the m.room.create event needed to auth the event.
	Create bool
	// Is the m.room.join_rules event needed to auth the event.
	JoinRules bool
	// Is the m.room.power_levels event needed to auth the event.
	PowerLevels bool
	// List of m.room.member state_keys needed to auth the event
	Member []string
	// List of m.room.third_party_invite state_keys
	ThirdPartyInvite []string
}

StateNeeded lists the event types and state_keys needed to authenticate an event.

func StateNeededForAuth

func StateNeededForAuth(events []*Event) (result StateNeeded)

StateNeededForAuth returns the event types and state_keys needed to authenticate an event. This takes a list of events to facilitate bulk processing when doing auth checks as part of state conflict resolution.

func StateNeededForEventBuilder

func StateNeededForEventBuilder(builder *EventBuilder) (result StateNeeded, err error)

StateNeededForEventBuilder returns the event types and state_keys needed to authenticate the event being built. These events should be put under 'auth_events' for the event being built. Returns an error if the state needed could not be calculated with the given builder, e.g if there is a m.room.member without a membership key.

func (StateNeeded) AuthEventReferences

func (s StateNeeded) AuthEventReferences(provider AuthEventProvider) (refs []EventReference, err error)

AuthEventReferences returns the auth_events references for the StateNeeded. Returns an error if the provider returns an error. If an event is missing from the provider but is required in StateNeeded, it is skipped over: no error is returned.

func (StateNeeded) Tuples

func (s StateNeeded) Tuples() (res []StateKeyTuple)

Tuples returns the needed state key tuples for performing auth on an event.

type StateProvider

type StateProvider interface {
	// StateIDsBeforeEvent returns a list of state event IDs for the event ID provided, which represent the entire
	// room state before that event.
	StateIDsBeforeEvent(ctx context.Context, event *HeaderedEvent) ([]string, error)
	// StateBeforeEvent returns the state of the room before the given event. `eventIDs` will be populated with the output
	// of StateIDsAtEvent to aid in event retrieval.
	StateBeforeEvent(ctx context.Context, roomVer RoomVersion, event *HeaderedEvent, eventIDs []string) (map[string]*Event, error)
}

StateProvider is capable of returning the room state at any point in time.

type StateResAlgorithm

type StateResAlgorithm int

StateResAlgorithm refers to a version of the state resolution algorithm.

const (
	StateResV1 StateResAlgorithm = iota + 1 // state resolution v1
	StateResV2                              // state resolution v2
)

State resolution constants.

type ThirdPartyInviteContent

type ThirdPartyInviteContent struct {
	DisplayName    string `json:"display_name"`
	KeyValidityURL string `json:"key_validity_url"`
	PublicKey      string `json:"public_key"`
	// Public keys are used to verify the signature of a m.room.member event that
	// came from a m.room.third_party_invite event
	PublicKeys []PublicKey `json:"public_keys"`
}

ThirdPartyInviteContent is the JSON content of a m.room.third_party_invite event needed for auth checks. See https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-third-party-invite for descriptions of the fields.

func NewThirdPartyInviteContentFromAuthEvents

func NewThirdPartyInviteContentFromAuthEvents(authEvents AuthEventProvider, token string) (t ThirdPartyInviteContent, err error)

NewThirdPartyInviteContentFromAuthEvents loads the third party invite content from the third party invite event for the state key (token) in the auth events. Returns an error if there was an error loading the third party invite event or parsing the event content.

type Timestamp

type Timestamp uint64

A Timestamp is a millisecond posix timestamp.

func AsTimestamp

func AsTimestamp(t time.Time) Timestamp

AsTimestamp turns a time.Time into a millisecond posix timestamp.

func (Timestamp) Time

func (t Timestamp) Time() time.Time

Time turns a millisecond posix timestamp into a UTC time.Time

type ToDeviceMessage

type ToDeviceMessage struct {
	Sender    string                                `json:"sender"`
	Type      string                                `json:"type"`
	MessageID string                                `json:"message_id"`
	Messages  map[string]map[string]json.RawMessage `json:"messages"`
}

type TopologicalOrder

type TopologicalOrder int

TopologicalOrder represents how to sort a list of events, used primarily in ReverseTopologicalOrdering

const (
	TopologicalOrderByPrevEvents TopologicalOrder = iota + 1
	TopologicalOrderByAuthEvents
)

Sort events by prev_events or auth_events

type Transaction

type Transaction struct {
	// The ID of the transaction.
	TransactionID TransactionID `json:"transaction_id"`
	// The server that sent the transaction.
	Origin ServerName `json:"origin"`
	// The server that should receive the transaction.
	Destination ServerName `json:"destination"`
	// The millisecond posix timestamp on the origin server when the
	// transaction was created.
	OriginServerTS Timestamp `json:"origin_server_ts"`
	// The IDs of the most recent transactions sent by the origin server to
	// the destination server. Multiple transactions can be sent by the origin
	// server to the destination server in parallel so there may be more than
	// one previous transaction.
	PreviousIDs []TransactionID `json:"previous_ids,omitempty"`
	// The room events pushed from the origin server to the destination server
	// by this transaction. The events should either be events that originate
	// on the origin server or be join m.room.member events.
	PDUs []json.RawMessage `json:"pdus"`
	// The ephemeral events pushed from origin server to destination server
	// by this transaction. The events must orginate at the origin server.
	EDUs []EDU `json:"edus,omitempty"`
}

A Transaction is used to push data from one matrix server to another matrix server.

type TransactionID

type TransactionID string

A TransactionID identifies a transaction sent by a matrix server to another matrix server. The ID must be unique amongst the transactions sent from the origin server to the destination, but doesn't have to be globally unique. The ID must be safe to insert into a URL path segment. The ID should have a format matching '^[0-9A-Za-z\-_]*$'

type UnexpectedHeaderedEvent

type UnexpectedHeaderedEvent struct{}

func (UnexpectedHeaderedEvent) Error

func (u UnexpectedHeaderedEvent) Error() string

type UnsupportedRoomVersionError

type UnsupportedRoomVersionError struct {
	Version RoomVersion
}

UnsupportedRoomVersionError occurs when a call has been made with a room version that is not supported by this version of gomatrixserverlib.

func (UnsupportedRoomVersionError) Error

type UserInfo

type UserInfo struct {
	Sub string `json:"sub"`
}

UserInfo represents information about a user.

type VerifyJSONRequest

type VerifyJSONRequest struct {
	// The name of the matrix server to check for a signature for.
	ServerName ServerName
	// The millisecond posix timestamp the message needs to be valid at.
	AtTS Timestamp
	// The JSON bytes.
	Message []byte
	// Should validity signature checking be enabled? (Room version >= 5)
	StrictValidityChecking bool
}

A VerifyJSONRequest is a request to check for a signature on a JSON message. A JSON message is valid for a server if the message has at least one valid signature from that server.

type VerifyJSONResult

type VerifyJSONResult struct {
	// Whether the message passed the signature checks.
	// This will be nil if the message passed the checks.
	// This will have an error if the message did not pass the checks.
	Error error
}

A VerifyJSONResult is the result of checking the signature of a JSON message.

type VerifyKey

type VerifyKey struct {
	// The public key.
	Key Base64Bytes `json:"key"`
}

A VerifyKey is a ed25519 public key for a server.

type Version

type Version struct {
	// Server is a struct containing the homserver version values
	Server struct {
		// Name is an arbitrary string that the Matrix server uses to identify itself
		Name string `json:"name"`
		// Version is a string that identifies the Matrix server's version, the format
		// of which depends on the Matrx server implementation
		Version string `json:"version"`
	} `json:"server"`
}

A Version is a struct that matches the version response from a Matrix homeserver. See https://matrix.org/docs/spec/server_server/r0.1.1.html#get-matrix-federation-v1-version

type WellKnownResult

type WellKnownResult struct {
	NewAddress     ServerName `json:"m.server"`
	CacheExpiresAt int64
}

WellKnownResult is the result of looking up a matrix server's well-known file. Located at https://<server_name>/.well-known/matrix/server

func LookupWellKnown

func LookupWellKnown(ctx context.Context, serverNameType ServerName) (*WellKnownResult, error)

LookupWellKnown looks up a well-known record for a matrix server. If one if found, it returns the server to redirect to.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL