Documentation ¶
Index ¶
- Constants
- func AddSkipItem(patten string, isReg bool)
- func Allowed(event Event, authEvents AuthEventProvider) error
- func CanonicalJSON(input []byte) ([]byte, error)
- func CanonicalJSONAssumeValid(input []byte) []byte
- func CheckKeys(serverName ServerName, now time.Time, keys ServerKeys, ...) (checks KeyChecks, ed25519Keys map[KeyID]Base64String, ...)
- func CompactJSON(input, output []byte) []byte
- func SignJSON(signingName string, keyID KeyID, privateKey ed25519.PrivateKey, message []byte) ([]byte, error)
- func SortJSON(input, output []byte) []byte
- func ToContent(se Event, format EventFormat) rawJSON
- func VerifyAllEventSignatures(ctx context.Context, events []Event, keyRing JSONVerifier) error
- func VerifyEventSignatures(ctx context.Context, events []Event, keyRing JSONVerifier) ([]error, error)
- func VerifyJSON(signingName string, keyID KeyID, publicKey ed25519.PublicKey, message []byte) error
- type ApplicationServiceTransaction
- type AuthEventProvider
- type AuthEvents
- func (a *AuthEvents) AddEvent(event *Event) error
- func (a *AuthEvents) Create() (*Event, error)
- func (a *AuthEvents) JoinRules() (*Event, error)
- func (a *AuthEvents) Member(stateKey string) (*Event, error)
- func (a *AuthEvents) PowerLevels() (*Event, error)
- func (a *AuthEvents) ThirdPartyInvite(stateKey string) (*Event, error)
- type BackfillRequest
- type BackfillResponse
- type Base64String
- func (b64 *Base64String) Decode(str string) error
- func (b64 Base64String) Encode() string
- func (b64 Base64String) MarshalJSON() ([]byte, error)
- func (b64 Base64String) MarshalYAML() (interface{}, error)
- func (b64 *Base64String) UnmarshalJSON(raw []byte) (err error)
- func (b64 *Base64String) UnmarshalYAML(unmarshal func(interface{}) error) (err error)
- type ClaimRequest
- type ClaimResponse
- type Client
- func (fc *Client) CreateMediaDownloadRequest(ctx context.Context, matrixServer ServerName, mediaID string) (*http.Response, error)
- func (fc *Client) DoHTTPRequest(ctx context.Context, req *http.Request, noTimeout bool) (*http.Response, error)
- func (fc *Client) DoRequestAndParseResponse(ctx context.Context, req *http.Request, result interface{}) error
- func (fc *Client) GetServerKeys(ctx context.Context, matrixServer ServerName) (ServerKeys, error)
- func (fc *Client) LookupServerKeys(ctx context.Context, matrixServer ServerName, ...) ([]ServerKeys, error)
- func (fc *Client) LookupUserInfo(ctx context.Context, matrixServer ServerName, token string) (u UserInfo, err error)
- type ClientEvent
- type DNSResult
- type DeviceKeysQuery
- type DirectKeyFetcher
- type EDU
- type Ed25519Checks
- type Event
- func (e Event) CheckFields() error
- func (e Event) Content() []byte
- func (e Event) Depth() int64
- func (e Event) DomainOffset() int64
- func (e Event) EventID() string
- func (e Event) EventNID() int64
- func (e Event) EventReference() EventReference
- func (e Event) External() bool
- func (e Event) JSON() []byte
- func (e Event) MarshalJSON() ([]byte, error)
- func (e Event) Membership() (string, error)
- func (e Event) Origin() ServerName
- func (e Event) OriginServerTS() Timestamp
- func (e *Event) RedactEventSender() string
- func (e Event) Redacted() bool
- func (e Event) Redacts() string
- func (e Event) RoomID() string
- func (e Event) Sender() string
- func (e *Event) SetDepth(depth int64)
- func (e *Event) SetDomainOffset(offset int64)
- func (e Event) SetExternal(external bool)
- func (e *Event) SetOriginServerTS(ts Timestamp)
- func (e *Event) SetRedactEventSender(sender string)
- func (e Event) SetUnsigned(unsigned interface{}, resetContent bool) (Event, error)
- func (e *Event) SetUnsignedField(path string, value interface{}) error
- func (e Event) StateKey() *string
- func (e Event) StateKeyEquals(stateKey string) bool
- func (e Event) Type() string
- func (e *Event) UnmarshalJSON(data []byte) (err error)
- func (e Event) Unsigned() []byte
- type EventBuilder
- type EventFormat
- type EventReference
- type FederationClient
- func (ac *FederationClient) Backfill(ctx context.Context, s ServerName, domain, roomID string, limit int, ...) (res BackfillResponse, err error)
- func (ac *FederationClient) Download(ctx context.Context, s ServerName, ...) (err error)
- func (ac *FederationClient) ExchangeThirdPartyInvite(ctx context.Context, s ServerName, builder EventBuilder) (err error)
- func (ac *FederationClient) GetMissingEvents(ctx context.Context, s ServerName, roomID string, ...) (res RespGetMissingEvents, err error)
- func (ac *FederationClient) LookupAvatarURL(ctx context.Context, s ServerName, userID string) (res RespAvatarURL, err error)
- func (ac *FederationClient) LookupDeviceKeys(ctx context.Context, s ServerName, content *QueryRequest) (res QueryResponse, err error)
- func (ac *FederationClient) LookupDisplayname(ctx context.Context, s ServerName, userID string) (res RespDisplayname, err error)
- func (ac *FederationClient) LookupMediaInfo(ctx context.Context, s ServerName, mediaID, userID string) (res RespMediaInfo, err error)
- func (ac *FederationClient) LookupOneTimeKeys(ctx context.Context, s ServerName, roomID string, content *ClaimRequest) (res ClaimResponse, err error)
- func (ac *FederationClient) LookupProfile(ctx context.Context, s ServerName, userID string) (res RespProfile, err error)
- func (ac *FederationClient) LookupRoomAlias(ctx context.Context, s ServerName, roomAlias string) (res RespDirectory, err error)
- func (ac *FederationClient) LookupState(ctx context.Context, s ServerName, roomID, eventID string) (res RespState, err error)
- func (ac *FederationClient) LookupStateIDs(ctx context.Context, s ServerName, roomID, eventID string) (res RespStateIDs, err error)
- func (ac *FederationClient) LookupUserInfo(ctx context.Context, s ServerName, userID string) (res RespUserInfo, err error)
- func (ac *FederationClient) MakeJoin(ctx context.Context, s ServerName, roomID, userID string, ver []string) (res RespMakeJoin, err error)
- func (ac *FederationClient) MakeLeave(ctx context.Context, s ServerName, roomID, userID string) (res RespMakeLeave, err error)
- func (ac *FederationClient) SendEvent(ctx context.Context, destination ServerName, e interface{}) (res RespSend, err error)
- func (ac *FederationClient) SendInvite(ctx context.Context, s ServerName, event Event) (res RespInvite, err error)
- func (ac *FederationClient) SendInviteRaw(ctx context.Context, s ServerName, roomID, eventID string, event interface{}) (res RespInvite, err error)
- func (ac *FederationClient) SendJoin(ctx context.Context, s ServerName, roomID, eventID string, event Event) (res RespSendJoin, err error)
- func (ac *FederationClient) SendLeave(ctx context.Context, s ServerName, roomID, eventID string, event Event) (res RespSendLeave, err error)
- func (ac *FederationClient) SendTransaction(ctx context.Context, t Transaction) (res RespSend, err error)
- type FederationRequest
- func (r *FederationRequest) Content() []byte
- func (r *FederationRequest) HTTPRequest(proto string) (*http.Request, error)
- func (r *FederationRequest) Method() string
- func (r *FederationRequest) Origin() ServerName
- func (r *FederationRequest) RequestURI() string
- func (r *FederationRequest) SetContent(content interface{}) error
- func (r *FederationRequest) Sign(serverName ServerName, keyID KeyID, privateKey ed25519.PrivateKey) error
- type Filter
- type FilterPart
- type HexString
- type HostResult
- type JSONVerifier
- type KeyChecks
- type KeyDatabase
- type KeyFetcher
- type KeyID
- type KeyRing
- type MessageContent
- type NotAllowed
- type OldVerifyKey
- type PDUResult
- type PerspectiveKeyFetcher
- type PublicKeyLookupRequest
- type PublicKeyLookupResult
- type QueryRequest
- type QueryResponse
- type RawPDU
- type ReqGetMissingEventContent
- type RespAvatarURL
- type RespDirectory
- type RespDisplayname
- type RespEventAuth
- type RespGetMissingEvents
- type RespInvite
- type RespMakeJoin
- type RespMakeLeave
- type RespMediaInfo
- type RespProfile
- type RespSend
- type RespSendJoin
- type RespSendLeave
- type RespState
- type RespStateIDs
- type RespUserInfo
- type RoomFilter
- type ServerKeyFields
- type ServerKeys
- type ServerName
- type StateKeyTuple
- type StateNeeded
- type TLSFingerprint
- type TLSFingerprintChecks
- type Timestamp
- type Transaction
- type TransactionID
- type UnsignedDeviceInfo
- type UserInfo
- type VerifyJSONRequest
- type VerifyJSONResult
- type VerifyKey
Examples ¶
Constants ¶
const ( // 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" // 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" // MRoomHistoryVisibility https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-history-visibility MRoomHistoryVisibility = "m.room.history_visibility" // 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" // customized for room meeting MModular = "m.modular." // channel archive MRoomArchive = "m.room.archive" MRoomUpdate = "m.room.update" )
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
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.
Variables ¶
This section is empty.
Functions ¶
func AddSkipItem ¶
func Allowed ¶
func Allowed(event Event, authEvents AuthEventProvider) 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 ¶
CanonicalJSON re-encodes the JSON in a canonical encoding. The encoding is the shortest possible encoding using integer values with sorted object keys. https://matrix.org/docs/spec/server_server/unstable.html#canonical-json
func CanonicalJSONAssumeValid ¶
CanonicalJSONAssumeValid is the same as CanonicalJSON, but assumes the input is valid JSON
func CheckKeys ¶
func CheckKeys(serverName ServerName, now time.Time, keys ServerKeys, connState *tls.ConnectionState) ( checks KeyChecks, ed25519Keys map[KeyID]Base64String, sha256Fingerprints []Base64String, )
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 and a list of SHA256 TLS fingerprints.
func CompactJSON ¶
CompactJSON makes the encoded JSON as small as possible by removing whitespace and unneeded unicode escapes
func SignJSON ¶
func SignJSON(signingName string, keyID KeyID, privateKey ed25519.PrivateKey, message []byte) ([]byte, 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 ¶
SortJSON reencodes the JSON with the object keys sorted by lexicographically by codepoint. The input must be valid JSON.
func ToContent ¶
func ToContent(se Event, format EventFormat) rawJSON
ToContent converts a single server event to a client event.
func VerifyAllEventSignatures ¶
func VerifyAllEventSignatures(ctx context.Context, events []Event, keyRing JSONVerifier) error
VerifyAllEventSignatures checks that each event in a list of events has valid signatures from the server that sent it.
returns an error if any event fails verifications
func VerifyEventSignatures ¶
func VerifyEventSignatures(ctx context.Context, events []Event, keyRing JSONVerifier) ([]error, error)
VerifyEventSignatures checks that each event in a list of events has valid signatures from the server that sent it.
returns an array with either an error or nil for each event.
Types ¶
type ApplicationServiceTransaction ¶
type ApplicationServiceTransaction struct {
Events []ClientEvent `json:"events"`
}
ApplicationServiceTransaction is the transaction that is sent off to an application service.
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 BackfillRequest ¶
type BackfillResponse ¶
type Base64String ¶
type Base64String []byte
A Base64String is a string of bytes 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.
func (*Base64String) Decode ¶
func (b64 *Base64String) Decode(str string) error
Decode decodes the given input into this Base64String
func (Base64String) Encode ¶
func (b64 Base64String) Encode() string
Encode encodes the bytes as base64
func (Base64String) MarshalJSON ¶
func (b64 Base64String) 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 Base64String encode correctly.
func (Base64String) MarshalYAML ¶
func (b64 Base64String) MarshalYAML() (interface{}, error)
MarshalYAML implements yaml.Marshaller It just encodes the bytes as base64, which is a valid YAML string
func (*Base64String) UnmarshalJSON ¶
func (b64 *Base64String) 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 (*Base64String) UnmarshalYAML ¶
func (b64 *Base64String) 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
type ClaimRequest ¶
type ClaimRequest struct { Timeout int64 `json:"timeout"` ClaimDetail map[string]map[string]string `json:"one_time_keys"` }
ClaimRequest structure
type ClaimResponse ¶
type ClaimResponse struct { Failures map[string]interface{} `json:"failures"` ClaimBody map[string]map[string]map[string]interface{} `json:"one_time_keys"` }
ClaimResponse structure
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
A Client makes request to the federation listeners of matrix homeservers
func NewClientWithTimeout ¶
NewClientWithTimeout makes a new Client with a specified request timeout
func NewHttpsClient ¶
NewHttpClient makes a new Client (with default timeout)
func NewHttpsClientWithTimeout ¶
NewHttpClientWithTimeout makes a new Client with a specified request timeout
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, noTimeout bool) (*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) 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.
type ClientEvent ¶
type ClientEvent struct { Content rawJSON `json:"content,omitempty"` EventID string `json:"event_id,omitempty"` EventNID int64 `json:"event_nid,omitempty"` DomainOffset int64 `json:"domain_offset"` Depth int64 `json:"depth"` OriginServerTS Timestamp `json:"origin_server_ts,omitempty"` // RoomID is omitted on /sync responses RoomID string `json:"room_id,omitempty"` Sender string `json:"sender,omitempty"` StateKey *string `json:"state_key,omitempty"` Type string `json:"type,omitempty"` Redacts string `json:"redacts,omitempty"` Hint string `json:"hint,omitempty"` Visible bool `json:"visible,omitempty"` Unsigned rawJSON `json:"unsigned,omitempty"` EventOffset int64 `json:"event_offset,omitempty"` }
ClientEvent is an event which is fit for consumption by clients, in accordance with the specification.
func ToClientEvent ¶
func ToClientEvent(se Event, format EventFormat) ClientEvent
ToClientEvent converts a single server event to a client event.
func ToClientEvents ¶
func ToClientEvents(serverEvs []Event, format EventFormat) []ClientEvent
ToClientEvents converts server events to client events.
func (*ClientEvent) InitFromEvent ¶
func (cliEv *ClientEvent) InitFromEvent(e *Event)
func (*ClientEvent) Membership ¶
func (cliEv *ClientEvent) Membership() (string, error)
func (*ClientEvent) SetExtra ¶
func (cliEv *ClientEvent) SetExtra(visible bool, hint string)
type DNSResult ¶
type DNSResult struct { SRVCName string // The canonical name for the SRV record in DNS SRVRecords []*net.SRV // List of SRV record for the matrix server. SRVError error // If there was an error getting the SRV records. Hosts map[string]HostResult // The results of looking up the SRV record targets. Addrs []string // List of "<ip>:<port>" strings that the server is listening on. These strings can be passed to `net.Dial()`. }
A DNSResult is the result of looking up a matrix server in DNS.
func LookupServer ¶
func LookupServer(serverName ServerName) (*DNSResult, error)
LookupServer looks up a matrix server in DNS.
type DeviceKeysQuery ¶
type DeviceKeysQuery struct { UserID string `json:"user_id"` DeviceID string `json:"device_id"` Algorithm []string `json:"algorithms"` Keys map[string]string `json:"keys"` Signature map[string]map[string]string `json:"signatures"` Unsigned UnsignedDeviceInfo `json:"unsigned"` }
DeviceKeysQuery structure
type DirectKeyFetcher ¶
type DirectKeyFetcher struct { // The federation client to use to fetch keys with. Client Client }
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 ¶
func (d *DirectKeyFetcher) FetchKeys( ctx context.Context, requests map[PublicKeyLookupRequest]Timestamp, ) (map[PublicKeyLookupRequest]PublicKeyLookupResult, error)
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"` Content rawJSON `json:"content"` }
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.
func NewEventFromTrustedJSON ¶
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 NewEventFromUntrustedJSON ¶
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 ResolveStateConflicts ¶
ResolveStateConflicts takes a list of state events with conflicting state keys and works out which event should be used for each state event.
func (Event) CheckFields ¶
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) DomainOffset ¶
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) MarshalJSON ¶
MarshalJSON implements json.Marshaller
func (Event) Membership ¶
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 ¶
OriginServerTS returns the unix timestamp when this event was created on the origin server, with millisecond resolution.
func (*Event) RedactEventSender ¶
func (*Event) SetDomainOffset ¶
func (Event) SetExternal ¶
func (*Event) SetOriginServerTS ¶
func (*Event) SetRedactEventSender ¶
func (Event) SetUnsigned ¶
SetUnsigned sets the unsigned key of the event. Returns a copy of the event with the "unsigned" key set.
func (*Event) SetUnsignedField ¶
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) StateKey ¶
StateKey returns the "state_key" of the event, or the nil if the event is not a state event.
func (Event) StateKeyEquals ¶
StateKeyEquals returns true if the event is a state event and the "state_key" matches.
func (*Event) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaller assuming the Event is from an untrusted source. This will cause more checks than might be necessary but is probably better to be safe than sorry.
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 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"` DomainOffset int64 `json:"domain_offset"` // 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"` RedactsSender string `json:"redacts_sender,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(eventNID int64, now time.Time, origin ServerName) (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 EventFormat ¶
type EventFormat int
EventFormat specifies the format of a client event
const ( // FormatAll will include all client event keys FormatAll EventFormat = 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 EventReference ¶
type EventReference struct { // The event ID of the event. EventID string // The sha256 of the redacted event. EventSHA256 Base64String }
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 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, rootCA, certPem, keyPem string, ) *FederationClient
NewFederationClient makes a new FederationClient
func (*FederationClient) Backfill ¶
func (ac *FederationClient) Backfill( ctx context.Context, s ServerName, domain, roomID string, limit int, eventIDs []string, dir string, ) (res BackfillResponse, 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) Download ¶
func (ac *FederationClient) Download( ctx context.Context, s ServerName, domain, mediaID, width, method, fileType string, cb func(response *http.Response) error, ) (err error)
Download download media which is used to encryption chatting session set up
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) GetMissingEvents ¶
func (ac *FederationClient) GetMissingEvents( ctx context.Context, s ServerName, roomID string, content *ReqGetMissingEventContent, ) (res RespGetMissingEvents, err error)
func (*FederationClient) LookupAvatarURL ¶
func (ac *FederationClient) LookupAvatarURL( ctx context.Context, s ServerName, userID string, ) (res RespAvatarURL, err error)
func (*FederationClient) LookupDeviceKeys ¶
func (ac *FederationClient) LookupDeviceKeys( ctx context.Context, s ServerName, content *QueryRequest, ) (res QueryResponse, err error)
LookupDeviceKeys looks up a batch of keys which are the counterpart of request body It gives a key per device in request body If the device is in wrong val it won't appear in response body
func (*FederationClient) LookupDisplayname ¶
func (ac *FederationClient) LookupDisplayname( ctx context.Context, s ServerName, userID string, ) (res RespDisplayname, err error)
func (*FederationClient) LookupMediaInfo ¶
func (ac *FederationClient) LookupMediaInfo( ctx context.Context, s ServerName, mediaID, userID string, ) (res RespMediaInfo, err error)
func (*FederationClient) LookupOneTimeKeys ¶
func (ac *FederationClient) LookupOneTimeKeys( ctx context.Context, s ServerName, roomID string, content *ClaimRequest, ) (res ClaimResponse, err error)
LookupOneTimeKeys lookup a key for certain device which is used to encryption chatting session set up
func (*FederationClient) LookupProfile ¶
func (ac *FederationClient) LookupProfile( ctx context.Context, s ServerName, userID string, ) (res RespProfile, err error)
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, ) (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) LookupUserInfo ¶
func (ac *FederationClient) LookupUserInfo( ctx context.Context, s ServerName, userID string, ) (res RespUserInfo, err error)
func (*FederationClient) MakeJoin ¶
func (ac *FederationClient) MakeJoin( ctx context.Context, s ServerName, roomID, userID string, ver []string, ) (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)
func (*FederationClient) SendEvent ¶
func (ac *FederationClient) SendEvent( ctx context.Context, destination ServerName, e interface{}, ) (res RespSend, err error)
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) SendInviteRaw ¶
func (ac *FederationClient) SendInviteRaw( ctx context.Context, s ServerName, roomID, eventID string, event interface{}, ) (res RespInvite, err error)
func (*FederationClient) SendJoin ¶
func (ac *FederationClient) SendJoin( ctx context.Context, s ServerName, roomID, eventID string, 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) SendLeave ¶
func (ac *FederationClient) SendLeave( ctx context.Context, s ServerName, roomID, eventID string, event Event, ) (res RespSendLeave, err error)
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) HTTPRequest ¶
func (r *FederationRequest) HTTPRequest(proto string) (*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 { AccountData FilterPart `json:"account_data,omitempty"` EventFields []string `json:"event_fields,omitempty"` EventFormat string `json:"event_format,omitempty"` Presence FilterPart `json:"presence,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.2.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
type FilterPart ¶
type FilterPart struct { NotRooms []string `json:"not_rooms,omitempty"` Rooms []string `json:"rooms,omitempty"` 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"` ContainsURL *bool `json:"contains_url,omitempty"` }
FilterPart is used to define filtering rules for specific categories of events
func DefaultFilterPart ¶
func DefaultFilterPart() FilterPart
DefaultFilterPart returns the default filter part used by the Matrix server if no filter is provided in the request
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 ¶
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 ¶
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 HostResult ¶
type HostResult struct { CName string // The canonical name for the host. Addrs []string // The IP addresses for the host. Error error // If there was an error getting the IP addresses. }
A HostResult is the result of looking up the IP addresses for a host.
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 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. HasTLSFingerprint bool // The server has at least one fingerprint. 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. AllTLSFingerprintChecksOK *bool // All the fingerprint checks are ok. TLSFingerprintChecks []TLSFingerprintChecks // Checks for TLS fingerprints. MatchingTLSFingerprint *bool // The TLS fingerprint for the connection matches one of the listed fingerprints. }
KeyChecks are the checks that should be applied to ServerKey responses.
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.
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 MessageContent ¶
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 Client }
A PerspectiveKeyFetcher fetches server keys from a single perspective server.
func (*PerspectiveKeyFetcher) FetchKeys ¶
func (p *PerspectiveKeyFetcher) FetchKeys( ctx context.Context, requests map[PublicKeyLookupRequest]Timestamp, ) (map[PublicKeyLookupRequest]PublicKeyLookupResult, error)
FetchKeys implements KeyFetcher
func (PerspectiveKeyFetcher) FetcherName ¶
func (p PerspectiveKeyFetcher) FetcherName() string
FetcherName implements KeyFetcher
type PublicKeyLookupRequest ¶
type PublicKeyLookupRequest struct { // The server to fetch a key for. ServerName ServerName // The ID of the key to fetch. KeyID KeyID }
A PublicKeyLookupRequest is a request for a public key with a particular key ID.
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 // When this result is valid until in milliseconds. // if the key has expired, the magic value PublicKeyNotValid. ValidUntilTS Timestamp }
A PublicKeyLookupResult is the result of looking up a server signing key.
func (PublicKeyLookupResult) WasValidAt ¶
func (r PublicKeyLookupResult) WasValidAt(atTs Timestamp) bool
WasValidAt checks if this signing key is valid for an event signed at the given timestamp.
type QueryRequest ¶
QueryRequest structure
type QueryResponse ¶
type QueryResponse struct {
DeviceKeys map[string]map[string]DeviceKeysQuery `json:"device_keys"`
}
QueryResponse structure
type RespAvatarURL ¶
type RespAvatarURL struct {
AvatarURL string `json:"avatar_url"`
}
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 RespDisplayname ¶
type RespDisplayname struct {
DisplayName string `json:"displayname"`
}
type RespEventAuth ¶
type RespEventAuth struct { // A list of events needed to authenticate the state events. AuthEvents []Event `json:"auth_chain"` }
A RespEventAuth is the content of a response to GET /_matrix/federation/v1/event_auth/{roomID}/{eventID}
type RespGetMissingEvents ¶
type RespGetMissingEvents struct { // Missing events, arbritrary order. Events []Event `json:"events"` }
type RespInvite ¶
RespInvite is the content of a response to PUT /_matrix/federation/v1/invite/{roomID}/{eventID}
func (*RespInvite) Decode ¶
func (r *RespInvite) Decode(data []byte) error
func (*RespInvite) Encode ¶
func (r *RespInvite) Encode() ([]byte, error)
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 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"` }
A RespMakeJoin is the content of a response to GET /_matrix/federation/v1/make_join/{roomID}/{userID}
func (*RespMakeJoin) Decode ¶
func (r *RespMakeJoin) Decode(data []byte) error
func (*RespMakeJoin) Encode ¶
func (r *RespMakeJoin) Encode() ([]byte, error)
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/unstable#leaving-rooms-rejecting-invites Event EventBuilder `json:"event"` }
A RespMakeLeave is the content of a response to GET /_matrix/federation/v1/make_leave/{roomID}/{userID}
func (*RespMakeLeave) Decode ¶
func (r *RespMakeLeave) Decode(data []byte) error
func (*RespMakeLeave) Encode ¶
func (r *RespMakeLeave) Encode() ([]byte, error)
type RespMediaInfo ¶
type RespProfile ¶
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 RespState
A RespSendJoin is the content of a response to PUT /_matrix/federation/v1/send_join/{roomID}/{eventID} It has the same data as a response to /state, but in a slightly different wire format.
func (RespSendJoin) Check ¶
func (r RespSendJoin) Check(ctx context.Context, keyRing JSONVerifier, joinEvent Event) error
Check that a response to /send_join is valid. This checks that it would be valid as a response to /state This also checks that the join event is allowed by the state.
func (*RespSendJoin) Decode ¶
func (r *RespSendJoin) Decode(data []byte) error
func (*RespSendJoin) Encode ¶
func (r *RespSendJoin) Encode() ([]byte, error)
func (RespSendJoin) MarshalJSON ¶
func (r RespSendJoin) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaller
func (*RespSendJoin) UnmarshalJSON ¶
func (r *RespSendJoin) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaller
type RespSendLeave ¶
type RespSendLeave struct {
Code int
}
A RespSendLeave is the content of a response to PUT /_matrix/federation/v1/send_leave/{roomID}/{eventID} It has the same data as a response to /state, but in a slightly different wire format.
func (*RespSendLeave) Decode ¶
func (r *RespSendLeave) Decode(data []byte) error
func (*RespSendLeave) Encode ¶
func (r *RespSendLeave) Encode() ([]byte, error)
func (RespSendLeave) MarshalJSON ¶
func (r RespSendLeave) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaller
func (*RespSendLeave) UnmarshalJSON ¶
func (r *RespSendLeave) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaller
type RespState ¶
type RespState struct { // A list of events giving the state of the room before the request event. StateEvents []Event `json:"pdus"` // A list of events needed to authenticate the state events. AuthEvents []Event `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, keyRing JSONVerifier) error
Check that a response to /state is valid.
func (RespState) Events ¶
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. Returns an error if there are missing auth events or if there is a cycle in the auth events.
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 RespUserInfo ¶
type RoomFilter ¶
type RoomFilter struct { AccountData FilterPart `json:"account_data,omitempty"` Ephemeral FilterPart `json:"ephemeral,omitempty"` IncludeLeave bool `json:"include_leave,omitempty"` NotRooms []string `json:"not_rooms,omitempty"` Rooms []string `json:"rooms,omitempty"` State FilterPart `json:"state,omitempty"` Timeline FilterPart `json:"timeline,omitempty"` }
RoomFilter is used to define filtering rules for room events
type ServerKeyFields ¶
type ServerKeyFields struct { // The name of the server ServerName ServerName `json:"server_name"` // List of SHA256 fingerprints of X509 certificates used by this server. TLSFingerprints []TLSFingerprint `json:"tls_fingerprints"` // 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 FetchKeysDirect ¶
func FetchKeysDirect(serverName ServerName, addr, sni string) (*ServerKeys, *tls.ConnectionState, error)
FetchKeysDirect fetches the matrix keys directly from the given address. Optionally sets a SNI header if “sni“ is not empty. Returns the server keys and the state of the TLS connection used to retrieve them.
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 without a trailing dot optionally followed by a port. So it has the format: "[0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*(:[0-9]+)?"
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 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 TLSFingerprint ¶
type TLSFingerprint struct {
SHA256 Base64String `json:"sha256"`
}
A TLSFingerprint is a SHA256 hash of an X509 certificate.
type TLSFingerprintChecks ¶
type TLSFingerprintChecks struct {
ValidSHA256 bool // The TLS fingerprint includes a valid SHA-256 hash.
}
TLSFingerprintChecks are the checks that are applied to TLS fingerprints in ServerKey responses.
type Timestamp ¶
type Timestamp uint64
A Timestamp is a millisecond posix timestamp.
func AsTimestamp ¶
AsTimestamp turns a time.Time into a millisecond posix timestamp.
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 []Event `json:"pdus"` RawPDUs []RawPDU `json:"raw_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 UnsignedDeviceInfo ¶
type UnsignedDeviceInfo struct {
Info string `json:"device_display_name"`
}
UnsignedDeviceInfo structure
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 }
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 Base64String `json:"key"` }
A VerifyKey is a ed25519 public key for a server.