UNPKG

matrix-js-sdk

Version:
1,284 lines (1,282 loc) 177 kB
/// <reference types="node" /> /** * This is an internal module. See {@link MatrixClient} for the public class. * @module client */ import { EventEmitter } from "events"; import { ISyncStateData, SyncApi } from "./sync"; import { IContent, IDecryptOptions, IEvent, MatrixEvent } from "./models/event"; import { MatrixCall } from "./webrtc/call"; import { Filter, IFilterDefinition } from "./filter"; import { CallEventHandler } from './webrtc/callEventHandler'; import { Group } from "./models/group"; import { Direction, EventTimeline } from "./models/event-timeline"; import { PushAction } from "./pushprocessor"; import { ReEmitter } from './ReEmitter'; import { IRoomEncryption, RoomList } from './crypto/RoomList'; import { SERVICE_TYPES } from './service-types'; import { MatrixError, MatrixHttpApi } from "./http-api"; import { Crypto, IBootstrapCrossSigningOpts, ICheckOwnCrossSigningTrustOpts, IMegolmSessionData, VerificationMethod } from './crypto'; import { DeviceInfo, IDevice } from "./crypto/deviceinfo"; import { User } from "./models/user"; import { IDehydratedDevice, IDehydratedDeviceKeyInfo, IDeviceKeys, IOneTimeKey } from "./crypto/dehydration"; import { IKeyBackupInfo, IKeyBackupPrepareOpts, IKeyBackupRestoreOpts, IKeyBackupRestoreResult, IKeyBackupSession } from "./crypto/keybackup"; import { IIdentityServerProvider } from "./@types/IIdentityServerProvider"; import { MatrixScheduler } from "./scheduler"; import { ICryptoCallbacks, IMinimalEvent, IRoomEvent, IStateEvent } from "./matrix"; import { CrossSigningKey, IAddSecretStorageKeyOpts, ICreateSecretStorageOpts, IEncryptedEventInfo, IImportRoomKeysOpts, IRecoveryKey, ISecretStorageKeyInfo } from "./crypto/api"; import { MemoryCryptoStore } from "./crypto/store/memory-crypto-store"; import { LocalStorageCryptoStore } from "./crypto/store/localStorage-crypto-store"; import { IndexedDBCryptoStore } from "./crypto/store/indexeddb-crypto-store"; import { SyncState } from "./sync.api"; import { EventTimelineSet } from "./models/event-timeline-set"; import { VerificationRequest } from "./crypto/verification/request/VerificationRequest"; import { Base as Verification } from "./crypto/verification/Base"; import { CrossSigningInfo, DeviceTrustLevel, ICacheCallbacks, UserTrustLevel } from "./crypto/CrossSigning"; import { Room } from "./models/room"; import { IAddThreePidOnlyBody, IBindThreePidBody, ICreateRoomOpts, IEventSearchOpts, IGuestAccessOpts, IJoinRoomOpts, IPaginateOpts, IPresenceOpts, IRedactOpts, IRoomDirectoryOptions, ISearchOpts, ISendEventResponse, IUploadOpts } from "./@types/requests"; import { EventType } from "./@types/event"; import { IAbortablePromise, IdServerUnbindResult, IImageInfo, Preset, Visibility } from "./@types/partials"; import { EventMapper, MapperOpts } from "./event-mapper"; import { ReadStream } from "fs"; import { WebStorageSessionStore } from "./store/session/webstorage"; import { IKeyBackup, IKeyBackupCheck, IPreparedKeyBackupVersion, TrustInfo } from "./crypto/backup"; import { MSC3089TreeSpace } from "./models/MSC3089TreeSpace"; import { ISignatures } from "./@types/signed"; import { IStore } from "./store"; import { ISecretRequest } from "./crypto/SecretStorage"; import { IEventWithRoomId, ISearchRequestBody, ISearchResponse, ISearchResults, IStateEventWithRoomId } from "./@types/search"; import { ISynapseAdminDeactivateResponse, ISynapseAdminWhoisResponse } from "./@types/synapse"; import { ISpaceSummaryEvent, ISpaceSummaryRoom } from "./@types/spaces"; import { IPusher, IPusherRequest, IPushRules, PushRuleAction, PushRuleKind, RuleId } from "./@types/PushRules"; import { IThreepid } from "./@types/threepids"; export declare type Store = IStore; export declare type SessionStore = WebStorageSessionStore; export declare type CryptoStore = MemoryCryptoStore | LocalStorageCryptoStore | IndexedDBCryptoStore; export declare type Callback = (err: Error | any | null, data?: any) => void; export declare type ResetTimelineCallback = (roomId: string) => boolean; export declare const CRYPTO_ENABLED: boolean; interface IOlmDevice { pickledAccount: string; sessions: Array<Record<string, IKeyBackupSession>>; pickleKey: string; } interface IExportedDevice { olmDevice: IOlmDevice; userId: string; deviceId: string; } export interface IKeysUploadResponse { one_time_key_counts: { [algorithm: string]: number; }; } export interface ICreateClientOpts { baseUrl: string; idBaseUrl?: string; /** * The data store used for sync data from the homeserver. If not specified, * this client will not store any HTTP responses. The `createClient` helper * will create a default store if needed. */ store?: Store; /** * A store to be used for end-to-end crypto session data. If not specified, * end-to-end crypto will be disabled. The `createClient` helper will create * a default store if needed. */ cryptoStore?: CryptoStore; /** * The scheduler to use. If not * specified, this client will not retry requests on failure. This client * will supply its own processing function to * {@link module:scheduler~MatrixScheduler#setProcessFunction}. */ scheduler?: MatrixScheduler; /** * The function to invoke for HTTP * requests. The value of this property is typically <code>require("request") * </code> as it returns a function which meets the required interface. See * {@link requestFunction} for more information. */ request?: Request; userId?: string; /** * A unique identifier for this device; used for tracking things like crypto * keys and access tokens. If not specified, end-to-end encryption will be * disabled. */ deviceId?: string; accessToken?: string; /** * Identity server provider to retrieve the user's access token when accessing * the identity server. See also https://github.com/vector-im/element-web/issues/10615 * which seeks to replace the previous approach of manual access tokens params * with this callback throughout the SDK. */ identityServer?: IIdentityServerProvider; /** * The default maximum amount of * time to wait before timing out HTTP requests. If not specified, there is no timeout. */ localTimeoutMs?: number; /** * Set to true to use * Authorization header instead of query param to send the access token to the server. * * Default false. */ useAuthorizationHeader?: boolean; /** * Set to true to enable * improved timeline support ({@link module:client~MatrixClient#getEventTimeline getEventTimeline}). It is * disabled by default for compatibility with older clients - in particular to * maintain support for back-paginating the live timeline after a '/sync' * result with a gap. */ timelineSupport?: boolean; /** * Extra query parameters to append * to all requests with this client. Useful for application services which require * <code>?user_id=</code>. */ queryParams?: Record<string, unknown>; /** * Device data exported with * "exportDevice" method that must be imported to recreate this device. * Should only be useful for devices with end-to-end crypto enabled. * If provided, deviceId and userId should **NOT** be provided at the top * level (they are present in the exported data). */ deviceToImport?: IExportedDevice; /** * Key used to pickle olm objects or other sensitive data. */ pickleKey?: string; /** * A store to be used for end-to-end crypto session data. Most data has been * migrated out of here to `cryptoStore` instead. If not specified, * end-to-end crypto will be disabled. The `createClient` helper * _will not_ create this store at the moment. */ sessionStore?: SessionStore; /** * Set to true to enable client-side aggregation of event relations * via `EventTimelineSet#getRelationsForEvent`. * This feature is currently unstable and the API may change without notice. */ unstableClientRelationAggregation?: boolean; verificationMethods?: Array<VerificationMethod>; /** * Whether relaying calls through a TURN server should be forced. Default false. */ forceTURN?: boolean; /** * Up to this many ICE candidates will be gathered when an incoming call arrives. * Gathering does not send data to the caller, but will communicate with the configured TURN * server. Default 0. */ iceCandidatePoolSize?: number; /** * True to advertise support for call transfers to other parties on Matrix calls. Default false. */ supportsCallTransfer?: boolean; /** * Whether to allow a fallback ICE server should be used for negotiating a * WebRTC connection if the homeserver doesn't provide any servers. Defaults to false. */ fallbackICEServerAllowed?: boolean; cryptoCallbacks?: ICryptoCallbacks; } export interface IMatrixClientCreateOpts extends ICreateClientOpts { /** * Whether to allow sending messages to encrypted rooms when encryption * is not available internally within this SDK. This is useful if you are using an external * E2E proxy, for example. Defaults to false. */ usingExternalCrypto?: boolean; } export declare enum PendingEventOrdering { Chronological = "chronological", Detached = "detached" } export interface IStartClientOpts { /** * The event <code>limit=</code> to apply to initial sync. Default: 8. */ initialSyncLimit?: number; /** * True to put <code>archived=true</code> on the <code>/initialSync</code> request. Default: false. */ includeArchivedRooms?: boolean; /** * True to do /profile requests on every invite event if the displayname/avatar_url is not known for this user ID. Default: false. */ resolveInvitesToProfiles?: boolean; /** * Controls where pending messages appear in a room's timeline. If "<b>chronological</b>", messages will * appear in the timeline when the call to <code>sendEvent</code> was made. If "<b>detached</b>", * pending messages will appear in a separate list, accessbile via {@link module:models/room#getPendingEvents}. * Default: "chronological". */ pendingEventOrdering?: PendingEventOrdering; /** * The number of milliseconds to wait on /sync. Default: 30000 (30 seconds). */ pollTimeout?: number; /** * The filter to apply to /sync calls. This will override the opts.initialSyncLimit, which would * normally result in a timeline limit filter. */ filter?: Filter; /** * True to perform syncing without automatically updating presence. */ disablePresence?: boolean; /** * True to not load all membership events during initial sync but fetch them when needed by calling * `loadOutOfBandMembers` This will override the filter option at this moment. */ lazyLoadMembers?: boolean; /** * The number of seconds between polls to /.well-known/matrix/client, undefined to disable. * This should be in the order of hours. Default: undefined. */ clientWellKnownPollPeriod?: number; } export interface IStoredClientOpts extends IStartClientOpts { crypto: Crypto; canResetEntireTimeline: ResetTimelineCallback; } export declare enum RoomVersionStability { Stable = "stable", Unstable = "unstable" } export interface IRoomCapability { preferred: string | null; support: string[]; } export interface IRoomVersionsCapability { default: string; available: Record<string, RoomVersionStability>; "org.matrix.msc3244.room_capabilities"?: Record<string, IRoomCapability>; } export interface IChangePasswordCapability { enabled: boolean; } interface ICapabilities { [key: string]: any; "m.change_password"?: IChangePasswordCapability; "m.room_versions"?: IRoomVersionsCapability; } export interface ICrossSigningKey { keys: { [algorithm: string]: string; }; signatures?: ISignatures; usage: string[]; user_id: string; } declare enum CrossSigningKeyType { MasterKey = "master_key", SelfSigningKey = "self_signing_key", UserSigningKey = "user_signing_key" } export declare type CrossSigningKeys = Record<CrossSigningKeyType, ICrossSigningKey>; export interface ISignedKey { keys: Record<string, string>; signatures: ISignatures; user_id: string; algorithms: string[]; device_id: string; } export declare type KeySignatures = Record<string, Record<string, ICrossSigningKey | ISignedKey>>; interface IUploadKeySignaturesResponse { failures: Record<string, Record<string, { errcode: string; error: string; }>>; } export interface IPreviewUrlResponse { [key: string]: string | number; "og:title": string; "og:type": string; "og:url": string; "og:image"?: string; "og:image:type"?: string; "og:image:height"?: number; "og:image:width"?: number; "og:description"?: string; "matrix:image:size"?: number; } interface ITurnServerResponse { uris: string[]; username: string; password: string; ttl: number; } interface ITurnServer { urls: string[]; username: string; credential: string; } interface IServerVersions { versions: string; unstable_features: Record<string, boolean>; } interface IClientWellKnown { [key: string]: any; "m.homeserver": { base_url: string; }; "m.identity_server"?: { base_url: string; }; } interface IMediaConfig { [key: string]: any; "m.upload.size"?: number; } interface ITagMetadata { [key: string]: any; order: number; } interface IMessagesResponse { start: string; end: string; chunk: IRoomEvent[]; state: IStateEvent[]; } interface IRequestTokenResponse { sid: string; submit_url?: string; } interface IRequestMsisdnTokenResponse extends IRequestTokenResponse { msisdn: string; success: boolean; intl_fmt: string; } interface IUploadKeysRequest { device_keys?: Required<IDeviceKeys>; one_time_keys?: { [userId: string]: { [deviceId: string]: number; }; }; "org.matrix.msc2732.fallback_keys"?: Record<string, IOneTimeKey>; } interface IOpenIDToken { access_token: string; token_type: "Bearer" | string; matrix_server_name: string; expires_in: number; } interface IRoomInitialSyncResponse { room_id: string; membership: "invite" | "join" | "leave" | "ban"; messages?: { start?: string; end?: string; chunk: IEventWithRoomId[]; }; state?: IStateEventWithRoomId[]; visibility: Visibility; account_data?: IMinimalEvent[]; presence: Partial<IEvent>; } interface IJoinedMembersResponse { joined: { [userId: string]: { display_name: string; avatar_url: string; }; }; } export interface IPublicRoomsChunkRoom { room_id: string; name?: string; avatar_url?: string; topic?: string; canonical_alias?: string; aliases?: string[]; world_readable: boolean; guest_can_join: boolean; num_joined_members: number; } interface IPublicRoomsResponse { chunk: IPublicRoomsChunkRoom[]; next_batch?: string; prev_batch?: string; total_room_count_estimate?: number; } interface IUserDirectoryResponse { results: { user_id: string; display_name?: string; avatar_url?: string; }[]; limited: boolean; } interface IMyDevice { device_id: string; display_name?: string; last_seen_ip?: string; last_seen_ts?: number; } interface IDownloadKeyResult { failures: { [serverName: string]: object; }; device_keys: { [userId: string]: { [deviceId: string]: IDeviceKeys & { unsigned?: { device_display_name: string; }; }; }; }; } interface IClaimOTKsResult { failures: { [serverName: string]: object; }; one_time_keys: { [userId: string]: { [deviceId: string]: string; }; }; } export interface IFieldType { regexp: string; placeholder: string; } export interface IInstance { desc: string; icon?: string; fields: object; network_id: string; instance_id: string; } export interface IProtocol { user_fields: string[]; location_fields: string[]; icon: string; field_types: Record<string, IFieldType>; instances: IInstance[]; } interface IThirdPartyLocation { alias: string; protocol: string; fields: object; } interface IThirdPartyUser { userid: string; protocol: string; fields: object; } /** * Represents a Matrix Client. Only directly construct this if you want to use * custom modules. Normally, {@link createClient} should be used * as it specifies 'sensible' defaults for these modules. */ export declare class MatrixClient extends EventEmitter { static readonly RESTORE_BACKUP_ERROR_BAD_KEY = "RESTORE_BACKUP_ERROR_BAD_KEY"; reEmitter: ReEmitter; olmVersion: string; usingExternalCrypto: boolean; store: Store; deviceId?: string; credentials: { userId?: string; }; pickleKey: string; scheduler: MatrixScheduler; clientRunning: boolean; timelineSupport: boolean; urlPreviewCache: { [key: string]: Promise<IPreviewUrlResponse>; }; unstableClientRelationAggregation: boolean; identityServer: IIdentityServerProvider; sessionStore: SessionStore; http: MatrixHttpApi; crypto: Crypto; cryptoCallbacks: ICryptoCallbacks; callEventHandler: CallEventHandler; supportsCallTransfer: boolean; forceTURN: boolean; iceCandidatePoolSize: number; idBaseUrl: string; baseUrl: string; protected canSupportVoip: boolean; protected peekSync: SyncApi; protected isGuestAccount: boolean; protected ongoingScrollbacks: { [roomId: string]: { promise?: Promise<Room>; errorTs?: number; }; }; protected notifTimelineSet: EventTimelineSet; protected cryptoStore: CryptoStore; protected verificationMethods: VerificationMethod[]; protected fallbackICEServerAllowed: boolean; protected roomList: RoomList; protected syncApi: SyncApi; pushRules: any; protected syncLeftRoomsPromise: Promise<Room[]>; protected syncedLeftRooms: boolean; protected clientOpts: IStoredClientOpts; protected clientWellKnownIntervalID: number; protected canResetTimelineCallback: ResetTimelineCallback; protected pushProcessor: any; protected serverVersionsPromise: Promise<IServerVersions>; protected cachedCapabilities: { capabilities: ICapabilities; expiration: number; }; protected clientWellKnown: IClientWellKnown; protected clientWellKnownPromise: Promise<IClientWellKnown>; protected turnServers: ITurnServer[]; protected turnServersExpiry: number; protected checkTurnServersIntervalID: number; protected exportedOlmDeviceToImport: IOlmDevice; protected txnCtr: number; constructor(opts: IMatrixClientCreateOpts); /** * High level helper method to begin syncing and poll for new events. To listen for these * events, add a listener for {@link module:client~MatrixClient#event:"event"} * via {@link module:client~MatrixClient#on}. Alternatively, listen for specific * state change events. * @param {Object=} opts Options to apply when syncing. */ startClient(opts: IStartClientOpts): Promise<void>; /** * High level helper method to stop the client from polling and allow a * clean shutdown. */ stopClient(): void; /** * Try to rehydrate a device if available. The client must have been * initialized with a `cryptoCallback.getDehydrationKey` option, and this * function must be called before initCrypto and startClient are called. * * @return {Promise<string>} Resolves to undefined if a device could not be dehydrated, or * to the new device ID if the dehydration was successful. * @return {module:http-api.MatrixError} Rejects: with an error response. */ rehydrateDevice(): Promise<string>; /** * Get the current dehydrated device, if any * @return {Promise} A promise of an object containing the dehydrated device */ getDehydratedDevice(): Promise<IDehydratedDevice>; /** * Set the dehydration key. This will also periodically dehydrate devices to * the server. * * @param {Uint8Array} key the dehydration key * @param {IDehydratedDeviceKeyInfo} [keyInfo] Information about the key. Primarily for * information about how to generate the key from a passphrase. * @param {string} [deviceDisplayName] The device display name for the * dehydrated device. * @return {Promise} A promise that resolves when the dehydrated device is stored. */ setDehydrationKey(key: Uint8Array, keyInfo: IDehydratedDeviceKeyInfo, deviceDisplayName?: string): Promise<void>; /** * Creates a new dehydrated device (without queuing periodic dehydration) * @param {Uint8Array} key the dehydration key * @param {IDehydratedDeviceKeyInfo} [keyInfo] Information about the key. Primarily for * information about how to generate the key from a passphrase. * @param {string} [deviceDisplayName] The device display name for the * dehydrated device. * @return {Promise<String>} the device id of the newly created dehydrated device */ createDehydratedDevice(key: Uint8Array, keyInfo: IDehydratedDeviceKeyInfo, deviceDisplayName?: string): Promise<string>; exportDevice(): Promise<IExportedDevice>; /** * Clear any data out of the persistent stores used by the client. * * @returns {Promise} Promise which resolves when the stores have been cleared. */ clearStores(): Promise<void>; /** * Get the user-id of the logged-in user * * @return {?string} MXID for the logged-in user, or null if not logged in */ getUserId(): string; /** * Get the domain for this client's MXID * @return {?string} Domain of this MXID */ getDomain(): string; /** * Get the local part of the current user ID e.g. "foo" in "@foo:bar". * @return {?string} The user ID localpart or null. */ getUserIdLocalpart(): string; /** * Get the device ID of this client * @return {?string} device ID */ getDeviceId(): string; /** * Check if the runtime environment supports VoIP calling. * @return {boolean} True if VoIP is supported. */ supportsVoip(): boolean; /** * Set whether VoIP calls are forced to use only TURN * candidates. This is the same as the forceTURN option * when creating the client. * @param {boolean} force True to force use of TURN servers */ setForceTURN(force: boolean): void; /** * Set whether to advertise transfer support to other parties on Matrix calls. * @param {boolean} support True to advertise the 'm.call.transferee' capability */ setSupportsCallTransfer(support: boolean): void; /** * Creates a new call. * The place*Call methods on the returned call can be used to actually place a call * * @param {string} roomId The room the call is to be placed in. * @return {MatrixCall} the call or null if the browser doesn't support calling. */ createCall(roomId: string): MatrixCall; /** * Get the current sync state. * @return {?SyncState} the sync state, which may be null. * @see module:client~MatrixClient#event:"sync" */ getSyncState(): SyncState; /** * Returns the additional data object associated with * the current sync state, or null if there is no * such data. * Sync errors, if available, are put in the 'error' key of * this object. * @return {?Object} */ getSyncStateData(): ISyncStateData | null; /** * Whether the initial sync has completed. * @return {boolean} True if at least one sync has happened. */ isInitialSyncComplete(): boolean; /** * Return whether the client is configured for a guest account. * @return {boolean} True if this is a guest access_token (or no token is supplied). */ isGuest(): boolean; /** * Set whether this client is a guest account. <b>This method is experimental * and may change without warning.</b> * @param {boolean} guest True if this is a guest account. */ setGuest(guest: boolean): void; /** * Return the provided scheduler, if any. * @return {?module:scheduler~MatrixScheduler} The scheduler or null */ getScheduler(): MatrixScheduler; /** * Retry a backed off syncing request immediately. This should only be used when * the user <b>explicitly</b> attempts to retry their lost connection. * @return {boolean} True if this resulted in a request being retried. */ retryImmediately(): boolean; /** * Return the global notification EventTimelineSet, if any * * @return {EventTimelineSet} the globl notification EventTimelineSet */ getNotifTimelineSet(): EventTimelineSet; /** * Set the global notification EventTimelineSet * * @param {EventTimelineSet} set */ setNotifTimelineSet(set: EventTimelineSet): void; /** * Gets the capabilities of the homeserver. Always returns an object of * capability keys and their options, which may be empty. * @param {boolean} fresh True to ignore any cached values. * @return {Promise} Resolves to the capabilities of the homeserver * @return {module:http-api.MatrixError} Rejects: with an error response. */ getCapabilities(fresh?: boolean): Promise<ICapabilities>; /** * Initialise support for end-to-end encryption in this client * * You should call this method after creating the matrixclient, but *before* * calling `startClient`, if you want to support end-to-end encryption. * * It will return a Promise which will resolve when the crypto layer has been * successfully initialised. */ initCrypto(): Promise<void>; /** * Is end-to-end crypto enabled for this client. * @return {boolean} True if end-to-end is enabled. */ isCryptoEnabled(): boolean; /** * Get the Ed25519 key for this device * * @return {?string} base64-encoded ed25519 key. Null if crypto is * disabled. */ getDeviceEd25519Key(): string; /** * Get the Curve25519 key for this device * * @return {?string} base64-encoded curve25519 key. Null if crypto is * disabled. */ getDeviceCurve25519Key(): string; /** * Upload the device keys to the homeserver. * @return {Promise<void>} A promise that will resolve when the keys are uploaded. */ uploadKeys(): Promise<void>; /** * Download the keys for a list of users and stores the keys in the session * store. * @param {Array} userIds The users to fetch. * @param {boolean} forceDownload Always download the keys even if cached. * * @return {Promise} A promise which resolves to a map userId->deviceId->{@link * module:crypto~DeviceInfo|DeviceInfo}. */ downloadKeys(userIds: string[], forceDownload?: boolean): Promise<Record<string, Record<string, IDevice>>>; /** * Get the stored device keys for a user id * * @param {string} userId the user to list keys for. * * @return {module:crypto/deviceinfo[]} list of devices */ getStoredDevicesForUser(userId: string): DeviceInfo[]; /** * Get the stored device key for a user id and device id * * @param {string} userId the user to list keys for. * @param {string} deviceId unique identifier for the device * * @return {module:crypto/deviceinfo} device or null */ getStoredDevice(userId: string, deviceId: string): DeviceInfo; /** * Mark the given device as verified * * @param {string} userId owner of the device * @param {string} deviceId unique identifier for the device or user's * cross-signing public key ID. * * @param {boolean=} verified whether to mark the device as verified. defaults * to 'true'. * * @returns {Promise} * * @fires module:client~event:MatrixClient"deviceVerificationChanged" */ setDeviceVerified(userId: string, deviceId: string, verified?: boolean): Promise<void>; /** * Mark the given device as blocked/unblocked * * @param {string} userId owner of the device * @param {string} deviceId unique identifier for the device or user's * cross-signing public key ID. * * @param {boolean=} blocked whether to mark the device as blocked. defaults * to 'true'. * * @returns {Promise} * * @fires module:client~event:MatrixClient"deviceVerificationChanged" */ setDeviceBlocked(userId: string, deviceId: string, blocked?: boolean): Promise<void>; /** * Mark the given device as known/unknown * * @param {string} userId owner of the device * @param {string} deviceId unique identifier for the device or user's * cross-signing public key ID. * * @param {boolean=} known whether to mark the device as known. defaults * to 'true'. * * @returns {Promise} * * @fires module:client~event:MatrixClient"deviceVerificationChanged" */ setDeviceKnown(userId: string, deviceId: string, known?: boolean): Promise<void>; private setDeviceVerification; /** * Request a key verification from another user, using a DM. * * @param {string} userId the user to request verification with * @param {string} roomId the room to use for verification * * @returns {Promise<module:crypto/verification/request/VerificationRequest>} resolves to a VerificationRequest * when the request has been sent to the other party. */ requestVerificationDM(userId: string, roomId: string): Promise<VerificationRequest>; /** * Finds a DM verification request that is already in progress for the given room id * * @param {string} roomId the room to use for verification * * @returns {module:crypto/verification/request/VerificationRequest?} the VerificationRequest that is in progress, if any */ findVerificationRequestDMInProgress(roomId: string): VerificationRequest; /** * Returns all to-device verification requests that are already in progress for the given user id * * @param {string} userId the ID of the user to query * * @returns {module:crypto/verification/request/VerificationRequest[]} the VerificationRequests that are in progress */ getVerificationRequestsToDeviceInProgress(userId: string): VerificationRequest[]; /** * Request a key verification from another user. * * @param {string} userId the user to request verification with * @param {Array} devices array of device IDs to send requests to. Defaults to * all devices owned by the user * * @returns {Promise<module:crypto/verification/request/VerificationRequest>} resolves to a VerificationRequest * when the request has been sent to the other party. */ requestVerification(userId: string, devices?: string[]): Promise<VerificationRequest>; /** * Begin a key verification. * * @param {string} method the verification method to use * @param {string} userId the user to verify keys with * @param {string} deviceId the device to verify * * @returns {Verification} a verification object */ beginKeyVerification(method: string, userId: string, deviceId: string): Verification; checkSecretStorageKey(key: Uint8Array, info: ISecretStorageKeyInfo): Promise<boolean>; /** * Set the global override for whether the client should ever send encrypted * messages to unverified devices. This provides the default for rooms which * do not specify a value. * * @param {boolean} value whether to blacklist all unverified devices by default */ setGlobalBlacklistUnverifiedDevices(value: boolean): void; /** * @return {boolean} whether to blacklist all unverified devices by default */ getGlobalBlacklistUnverifiedDevices(): boolean; /** * Set whether sendMessage in a room with unknown and unverified devices * should throw an error and not send them message. This has 'Global' for * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently * no room-level equivalent for this setting. * * This API is currently UNSTABLE and may change or be removed without notice. * * @param {boolean} value whether error on unknown devices */ setGlobalErrorOnUnknownDevices(value: boolean): void; /** * @return {boolean} whether to error on unknown devices * * This API is currently UNSTABLE and may change or be removed without notice. */ getGlobalErrorOnUnknownDevices(): boolean; /** * Get the user's cross-signing key ID. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @param {CrossSigningKey} [type=master] The type of key to get the ID of. One of * "master", "self_signing", or "user_signing". Defaults to "master". * * @returns {string} the key ID */ getCrossSigningId(type?: CrossSigningKey | string): string; /** * Get the cross signing information for a given user. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @param {string} userId the user ID to get the cross-signing info for. * * @returns {CrossSigningInfo} the cross signing information for the user. */ getStoredCrossSigningForUser(userId: string): CrossSigningInfo; /** * Check whether a given user is trusted. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @param {string} userId The ID of the user to check. * * @returns {UserTrustLevel} */ checkUserTrust(userId: string): UserTrustLevel; /** * Check whether a given device is trusted. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#checkDeviceTrust * @param {string} userId The ID of the user whose devices is to be checked. * @param {string} deviceId The ID of the device to check * * @returns {DeviceTrustLevel} */ checkDeviceTrust(userId: string, deviceId: string): DeviceTrustLevel; /** * Check the copy of our cross-signing key that we have in the device list and * see if we can get the private key. If so, mark it as trusted. * @param {Object} opts ICheckOwnCrossSigningTrustOpts object */ checkOwnCrossSigningTrust(opts?: ICheckOwnCrossSigningTrustOpts): Promise<void>; /** * Checks that a given cross-signing private key matches a given public key. * This can be used by the getCrossSigningKey callback to verify that the * private key it is about to supply is the one that was requested. * @param {Uint8Array} privateKey The private key * @param {string} expectedPublicKey The public key * @returns {boolean} true if the key matches, otherwise false */ checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean; legacyDeviceVerification(userId: string, deviceId: string, method: VerificationMethod): Promise<VerificationRequest>; /** * Perform any background tasks that can be done before a message is ready to * send, in order to speed up sending of the message. * @param {module:models/room} room the room the event is in */ prepareToEncrypt(room: Room): void; /** * Checks whether cross signing: * - is enabled on this account and trusted by this device * - has private keys either cached locally or stored in secret storage * * If this function returns false, bootstrapCrossSigning() can be used * to fix things such that it returns true. That is to say, after * bootstrapCrossSigning() completes successfully, this function should * return true. * @return {boolean} True if cross-signing is ready to be used on this device */ isCrossSigningReady(): Promise<boolean>; /** * Bootstrap cross-signing by creating keys if needed. If everything is already * set up, then no changes are made, so this is safe to run to ensure * cross-signing is ready for use. * * This function: * - creates new cross-signing keys if they are not found locally cached nor in * secret storage (if it has been setup) * * The cross-signing API is currently UNSTABLE and may change without notice. * * @param {function} opts.authUploadDeviceSigningKeys Function * called to await an interactive auth flow when uploading device signing keys. * @param {boolean} [opts.setupNewCrossSigning] Optional. Reset even if keys * already exist. * Args: * {function} A function that makes the request requiring auth. Receives the * auth data as an object. Can be called multiple times, first with an empty * authDict, to obtain the flows. */ bootstrapCrossSigning(opts: IBootstrapCrossSigningOpts): Promise<void>; /** * Whether to trust a others users signatures of their devices. * If false, devices will only be considered 'verified' if we have * verified that device individually (effectively disabling cross-signing). * * Default: true * * @return {boolean} True if trusting cross-signed devices */ getCryptoTrustCrossSignedDevices(): boolean; /** * See getCryptoTrustCrossSignedDevices * This may be set before initCrypto() is called to ensure no races occur. * * @param {boolean} val True to trust cross-signed devices */ setCryptoTrustCrossSignedDevices(val: boolean): void; /** * Counts the number of end to end session keys that are waiting to be backed up * @returns {Promise<int>} Resolves to the number of sessions requiring backup */ countSessionsNeedingBackup(): Promise<number>; /** * Get information about the encryption of an event * * @param {module:models/event.MatrixEvent} event event to be checked * @returns {IEncryptedEventInfo} The event information. */ getEventEncryptionInfo(event: MatrixEvent): IEncryptedEventInfo; /** * Create a recovery key from a user-supplied passphrase. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @param {string} password Passphrase string that can be entered by the user * when restoring the backup as an alternative to entering the recovery key. * Optional. * @returns {Promise<Object>} Object with public key metadata, encoded private * recovery key which should be disposed of after displaying to the user, * and raw private key to avoid round tripping if needed. */ createRecoveryKeyFromPassphrase(password: string): Promise<IRecoveryKey>; /** * Checks whether secret storage: * - is enabled on this account * - is storing cross-signing private keys * - is storing session backup key (if enabled) * * If this function returns false, bootstrapSecretStorage() can be used * to fix things such that it returns true. That is to say, after * bootstrapSecretStorage() completes successfully, this function should * return true. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @return {boolean} True if secret storage is ready to be used on this device */ isSecretStorageReady(): Promise<boolean>; /** * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is * already set up, then no changes are made, so this is safe to run to ensure secret * storage is ready for use. * * This function * - creates a new Secure Secret Storage key if no default key exists * - if a key backup exists, it is migrated to store the key in the Secret * Storage * - creates a backup if none exists, and one is requested * - migrates Secure Secret Storage to use the latest algorithm, if an outdated * algorithm is found * * @param opts */ bootstrapSecretStorage(opts: ICreateSecretStorageOpts): Promise<void>; /** * Add a key for encrypting secrets. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @param {string} algorithm the algorithm used by the key * @param {object} opts the options for the algorithm. The properties used * depend on the algorithm given. * @param {string} [keyName] the name of the key. If not given, a random name will be generated. * * @return {object} An object with: * keyId: {string} the ID of the key * keyInfo: {object} details about the key (iv, mac, passphrase) */ addSecretStorageKey(algorithm: string, opts: IAddSecretStorageKeyOpts, keyName?: string): Promise<{ keyId: string; keyInfo: ISecretStorageKeyInfo; }>; /** * Check whether we have a key with a given ID. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @param {string} [keyId = default key's ID] The ID of the key to check * for. Defaults to the default key ID if not provided. * @return {boolean} Whether we have the key. */ hasSecretStorageKey(keyId?: string): Promise<boolean>; /** * Store an encrypted secret on the server. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @param {string} name The name of the secret * @param {string} secret The secret contents. * @param {Array} keys The IDs of the keys to use to encrypt the secret or null/undefined * to use the default (will throw if no default key is set). */ storeSecret(name: string, secret: string, keys?: string[]): Promise<void>; /** * Get a secret from storage. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @param {string} name the name of the secret * * @return {string} the contents of the secret */ getSecret(name: string): Promise<string>; /** * Check if a secret is stored on the server. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @param {string} name the name of the secret * @param {boolean} checkKey check if the secret is encrypted by a trusted * key * * @return {object?} map of key name to key info the secret is encrypted * with, or null if it is not present or not encrypted with a trusted * key */ isSecretStored(name: string, checkKey: boolean): Promise<Record<string, ISecretStorageKeyInfo>>; /** * Request a secret from another device. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @param {string} name the name of the secret to request * @param {string[]} devices the devices to request the secret from * * @return {ISecretRequest} the secret request object */ requestSecret(name: string, devices: string[]): ISecretRequest; /** * Get the current default key ID for encrypting secrets. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @return {string} The default key ID or null if no default key ID is set */ getDefaultSecretStorageKeyId(): Promise<string>; /** * Set the current default key ID for encrypting secrets. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @param {string} keyId The new default key ID */ setDefaultSecretStorageKeyId(keyId: string): Promise<void>; /** * Checks that a given secret storage private key matches a given public key. * This can be used by the getSecretStorageKey callback to verify that the * private key it is about to supply is the one that was requested. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @param {Uint8Array} privateKey The private key * @param {string} expectedPublicKey The public key * @returns {boolean} true if the key matches, otherwise false */ checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean; /** * Get e2e information on the device that sent an event * * @param {MatrixEvent} event event to be checked * * @return {Promise<module:crypto/deviceinfo?>} */ getEventSenderDeviceInfo(event: MatrixEvent): Promise<DeviceInfo>; /** * Check if the sender of an event is verified * * @param {MatrixEvent} event event to be checked * * @return {boolean} true if the sender of this event has been verified using * {@link module:client~MatrixClient#setDeviceVerified|setDeviceVerified}. */ isEventSenderVerified(event: MatrixEvent): Promise<boolean>; /** * Cancel a room key request for this event if one is ongoing and resend the * request. * @param {MatrixEvent} event event of which to cancel and resend the room * key request. * @return {Promise} A promise that will resolve when the key request is queued */ cancelAndResendEventRoomKeyRequest(event: MatrixEvent): Promise<void>; /** * Enable end-to-end encryption for a room. This does not modify room state. * Any messages sent before the returned promise resolves will be sent unencrypted. * @param {string} roomId The room ID to enable encryption in. * @param {object} config The encryption config for the room. * @return {Promise} A promise that will resolve when encryption is set up. */ setRoomEncryption(roomId: string, config: IRoomEncryption): Promise<void>; /** * Whether encryption is enabled for a room. * @param {string} roomId the room id to query. * @return {boolean} whether encryption is enabled. */ isRoomEncrypted(roomId: string): boolean; /** * Forces the current outbound group session to be discarded such * that another one will be created next time an event is sent. * * @param {string} roomId The ID of the room to discard the session for * * This should not normally be necessary. */ forceDiscardSession(roomId: string): void; /** * Get a list containing all of the room keys * * This should be encrypted before returning it to the user. * * @return {Promise} a promise which resolves to a list of * session export objects */ exportRoomKeys(): Promise<IMegolmSessionData[]>; /** * Import a list of room keys previously exported by exportRoomKeys * * @param {Object[]} keys a list of session export objects * @param {Object} opts * @param {Function} opts.progressCallback called with an object that has a "stage" param * * @return {Promise} a promise which resolves when the keys * have been imported */ importRoomKeys(keys: IMegolmSessionData[], opts: IImportRoomKeysOpts): Promise<void>; /** * Force a re-check of the local key backup status against * what's on the server. * * @returns {Object} Object with backup info (as returned by * getKeyBackupVersion) in backupInfo and * trust information (as returned by isKeyBackupTrusted) * in trustInfo. */ checkKeyBackup(): Promise<IKeyBackupCheck>; /** * Get information about the current key backup. * @returns {Promise} Information object from API or null */ getKeyBackupVersion(): Promise<IKeyBackupInfo>; /** * @param {object} info key backup info dict from getKeyBackupVersion() * @return {object} { * usable: [bool], // is the backup trusted, true iff there is a sig that is valid & from a trusted device * sigs: [ * valid: [bool], * device: [DeviceInfo], * ] * } */ isKeyBackupTrusted(info: IKeyBackupInfo): Promise<TrustInfo>; /** * @returns {boolean} true if the client is configured to back up keys to * the server, otherwise false. If we haven't completed a successful check * of key backup status yet, returns null. */ getKeyBackupEnabled(): boolean; /** * Enable backing up of keys, using data previously returned from * getKeyBackupVersion. * * @param {object} info Backup information object as returned by getKeyBackupVersion * @returns {Promise<void>} Resolves when complete. */ enableKeyBackup(info: IKeyBackupInfo): Promise<void>; /** * Disable backing up of keys. */ disableKeyBackup(): void; /**