matrix-js-sdk 42.2.0 → 42.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/lib/client.d.ts +1 -2
  3. package/lib/client.d.ts.map +1 -1
  4. package/lib/client.js +16 -8
  5. package/lib/client.js.map +1 -1
  6. package/lib/http-api/errors.d.ts +8 -0
  7. package/lib/http-api/errors.d.ts.map +1 -1
  8. package/lib/http-api/errors.js +12 -0
  9. package/lib/http-api/errors.js.map +1 -1
  10. package/lib/matrixrtc/MatrixRTCSession.d.ts +5 -0
  11. package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
  12. package/lib/matrixrtc/MatrixRTCSession.js +2 -1
  13. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  14. package/lib/oauth/authorize.d.ts +2 -4
  15. package/lib/oauth/authorize.d.ts.map +1 -1
  16. package/lib/oauth/authorize.js.map +1 -1
  17. package/lib/oauth/error.d.ts +44 -0
  18. package/lib/oauth/error.d.ts.map +1 -1
  19. package/lib/oauth/error.js +53 -0
  20. package/lib/oauth/error.js.map +1 -1
  21. package/lib/oauth/index.d.ts.map +1 -1
  22. package/lib/oauth/index.js +19 -2
  23. package/lib/oauth/index.js.map +1 -1
  24. package/lib/oauth/tokenRefresher.d.ts.map +1 -1
  25. package/lib/oauth/tokenRefresher.js +4 -2
  26. package/lib/oauth/tokenRefresher.js.map +1 -1
  27. package/lib/secret-storage.d.ts +1 -1
  28. package/lib/secret-storage.d.ts.map +1 -1
  29. package/lib/secret-storage.js +9 -32
  30. package/lib/secret-storage.js.map +1 -1
  31. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  32. package/lib/sliding-sync-sdk.js +54 -1
  33. package/lib/sliding-sync-sdk.js.map +1 -1
  34. package/package.json +2 -2
  35. package/src/client.ts +19 -11
  36. package/src/http-api/errors.ts +16 -0
  37. package/src/matrixrtc/MatrixRTCSession.ts +8 -1
  38. package/src/oauth/authorize.ts +2 -5
  39. package/src/oauth/error.ts +69 -0
  40. package/src/oauth/index.ts +19 -2
  41. package/src/oauth/tokenRefresher.ts +9 -2
  42. package/src/secret-storage.ts +8 -31
  43. package/src/sliding-sync-sdk.ts +74 -0
@@ -1 +1 @@
1
- {"version":3,"file":"secret-storage.js","names":[],"sources":["../src/secret-storage.ts"],"sourcesContent":["/*\nCopyright 2021-2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Implementation of server-side secret storage\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#storage\n */\n\nimport { type TypedEventEmitter } from \"./models/typed-event-emitter.ts\";\nimport { ClientEvent, type ClientEventHandlerMap } from \"./client.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\nimport { secureRandomString } from \"./randomstring.ts\";\nimport { logger } from \"./logger.ts\";\nimport encryptAESSecretStorageItem from \"./utils/encryptAESSecretStorageItem.ts\";\nimport decryptAESSecretStorageItem from \"./utils/decryptAESSecretStorageItem.ts\";\nimport { type AESEncryptedSecretStoragePayload } from \"./@types/AESEncryptedSecretStoragePayload.ts\";\nimport { type AccountDataEvents, type SecretStorageAccountDataEvents } from \"./@types/event.ts\";\nimport { type EmptyObject } from \"./@types/common.ts\";\n\nexport const SECRET_STORAGE_ALGORITHM_V1_AES = \"m.secret_storage.v1.aes-hmac-sha2\";\n\n/**\n * Common base interface for Secret Storage Keys.\n *\n * The common properties for all encryption keys used in server-side secret storage.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#key-storage\n */\nexport interface SecretStorageKeyDescriptionCommon {\n /** A human-readable name for this key. */\n // XXX: according to the spec, this is optional\n name: string;\n\n /** The encryption algorithm used with this key. */\n algorithm: string;\n\n /** Information for deriving this key from a passphrase. */\n // XXX: according to the spec, this is optional\n passphrase: PassphraseInfo;\n}\n\n/**\n * Properties for a SSSS key using the `m.secret_storage.v1.aes-hmac-sha2` algorithm.\n *\n * Corresponds to `AesHmacSha2KeyDescription` in the specification.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#msecret_storagev1aes-hmac-sha2\n */\nexport interface SecretStorageKeyDescriptionAesV1 extends SecretStorageKeyDescriptionCommon {\n // XXX: strictly speaking, we should be able to enforce the algorithm here. But\n // this interface ends up being incorrectly used where other algorithms are in use (notably\n // in device-dehydration support), and unpicking that is too much like hard work\n // at the moment.\n // algorithm: \"m.secret_storage.v1.aes-hmac-sha2\";\n\n /** The 16-byte AES initialization vector, encoded as base64. */\n iv: string;\n\n /** The MAC of the result of encrypting 32 bytes of 0, encoded as base64. */\n mac: string;\n}\n\n/**\n * Union type for secret storage keys.\n *\n * For now, this is only {@link SecretStorageKeyDescriptionAesV1}, but other interfaces may be added in future.\n */\nexport type SecretStorageKeyDescription = SecretStorageKeyDescriptionAesV1;\n\n/**\n * Information on how to generate the key from a passphrase.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#deriving-keys-from-passphrases\n */\nexport interface PassphraseInfo {\n /** The algorithm to be used to derive the key. */\n algorithm: \"m.pbkdf2\";\n\n /** The number of PBKDF2 iterations to use. */\n iterations: number;\n\n /** The salt to be used for PBKDF2. */\n salt: string;\n\n /** The number of bits to generate. Defaults to 256. */\n bits?: number;\n}\n\n/**\n * Options for {@link ServerSideSecretStorageImpl#addKey}.\n */\nexport interface AddSecretStorageKeyOpts {\n /** Information for deriving the key from a passphrase if any. */\n passphrase?: PassphraseInfo;\n /** Optional name of the key. */\n name?: string;\n /** The private key. Will be used to generate the key check values in the key info; it will not be stored on the server */\n key: Uint8Array<ArrayBuffer>;\n}\n\n/**\n * Return type for {@link ServerSideSecretStorageImpl#getKey}.\n */\nexport type SecretStorageKeyTuple = [keyId: string, keyInfo: SecretStorageKeyDescription];\n\n/**\n * Return type for {@link ServerSideSecretStorageImpl#addKey}.\n */\nexport type SecretStorageKeyObject = {\n /** The ID of the key */\n keyId: string;\n /** details about the key */\n keyInfo: SecretStorageKeyDescription;\n};\n\n/** Interface for managing account data on the server.\n *\n * A subset of {@link MatrixClient}.\n */\nexport interface AccountDataClient extends TypedEventEmitter<ClientEvent.AccountData, ClientEventHandlerMap> {\n /**\n * Get account data event of given type for the current user. This variant\n * gets account data directly from the homeserver if the local store is not\n * ready, which can be useful very early in startup before the initial sync.\n *\n * @param eventType - The type of account data\n * @returns The contents of the given account data event, or `null` if the event is not found\n */\n getAccountDataFromServer: <K extends keyof AccountDataEvents>(eventType: K) => Promise<AccountDataEvents[K] | null>;\n\n /**\n * Set account data event for the current user, with retries\n *\n * @param eventType - The type of account data\n * @param content - the content object to be set\n * @returns an empty object\n */\n setAccountData: <K extends keyof AccountDataEvents>(\n eventType: K,\n content: AccountDataEvents[K] | Record<string, never>,\n ) => Promise<EmptyObject>;\n}\n\n/**\n * Application callbacks for use with {@link SecretStorage.ServerSideSecretStorageImpl}\n */\nexport interface SecretStorageCallbacks {\n /**\n * Called to retrieve a secret storage encryption key\n *\n * Before a secret can be stored in server-side storage, it must be encrypted with one or more\n * keys. Similarly, after it has been retrieved from storage, it must be decrypted with one of\n * the keys it was encrypted with. These encryption keys are known as \"secret storage keys\".\n *\n * Descriptions of the secret storage keys are also stored in server-side storage, per the\n * [matrix specification](https://spec.matrix.org/v1.6/client-server-api/#key-storage), so\n * before a key can be used in this way, it must have been stored on the server. This is\n * done via {@link ServerSideSecretStorage#addKey}.\n *\n * Obviously the keys themselves are not stored server-side, so the js-sdk calls this callback\n * in order to retrieve a secret storage key from the application.\n *\n * @param keys - An options object, containing only the property `keys`.\n *\n * @param name - the name of the *secret* (NB: not the encryption key) being stored or retrieved.\n * This is the \"event type\" stored in account data.\n *\n * @returns a pair [`keyId`, `privateKey`], where `keyId` is one of the keys from the `keys` parameter,\n * and `privateKey` is the raw private encryption key, as appropriate for the encryption algorithm.\n * (For `m.secret_storage.v1.aes-hmac-sha2`, it is the input to an HKDF as defined in the\n * [specification](https://spec.matrix.org/v1.6/client-server-api/#msecret_storagev1aes-hmac-sha2).)\n *\n * Alternatively, if none of the keys are known, may return `null` — in which case the original\n * storage/retrieval operation will fail with an exception.\n */\n getSecretStorageKey?: (\n keys: {\n /**\n * details of the secret storage keys required: a map from the key ID\n * (excluding the `m.secret_storage.key.` prefix) to details of the key.\n *\n * When storing a secret, `keys` will contain exactly one entry; this method will be called\n * once for each secret storage key to be used for encryption.\n *\n * For secret retrieval, `keys` may contain several entries, and the application can return\n * any one of the requested keys.\n */\n keys: Record<string, SecretStorageKeyDescription>;\n },\n name: string,\n ) => Promise<[string, Uint8Array<ArrayBuffer>] | null>;\n}\n\n/**\n * Account Data event types which can store secret-storage-encrypted information.\n */\nexport type SecretStorageKey = keyof SecretStorageAccountDataEvents;\n\n/**\n * Account Data event content type for storing secret-storage-encrypted information.\n *\n * See https://spec.matrix.org/v1.13/client-server-api/#msecret_storagev1aes-hmac-sha2-1\n */\nexport interface SecretInfo {\n encrypted: {\n [keyId: string]: AESEncryptedSecretStoragePayload;\n };\n}\n\ninterface Decryptors {\n encrypt: (plaintext: string) => Promise<AESEncryptedSecretStoragePayload>;\n decrypt: (ciphertext: AESEncryptedSecretStoragePayload) => Promise<string>;\n}\n\n/**\n * Interface provided by SecretStorage implementations\n *\n * Normally this will just be an {@link ServerSideSecretStorageImpl}, but for backwards\n * compatibility some methods allow other implementations.\n */\nexport interface ServerSideSecretStorage {\n /**\n * Add a key for encrypting secrets.\n *\n * @param algorithm - the algorithm used by the key.\n * @param opts - the options for the algorithm. The properties used\n * depend on the algorithm given.\n * @param keyId - the ID of the key. If not given, a random\n * ID will be generated.\n *\n * @returns details about the key.\n */\n addKey(algorithm: string, opts: AddSecretStorageKeyOpts, keyId?: string): Promise<SecretStorageKeyObject>;\n\n /**\n * Get the key information for a given ID.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns If the key was found, the return value is an array of\n * the form [keyId, keyInfo]. Otherwise, null is returned.\n * XXX: why is this an array when addKey returns an object?\n */\n getKey(keyId?: string | null): Promise<SecretStorageKeyTuple | null>;\n\n /**\n * Check whether we have a key with a given ID.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns Whether we have the key.\n */\n hasKey(keyId?: string): Promise<boolean>;\n\n /**\n * Check whether a key matches what we expect based on the key info\n *\n * @param key - the key to check\n * @param info - the key info\n *\n * @returns whether or not the key matches\n */\n checkKey(key: Uint8Array, info: SecretStorageKeyDescriptionAesV1): Promise<boolean>;\n\n /**\n * Store an encrypted secret on the server.\n *\n * Details of the encryption keys to be used must previously have been stored in account data\n * (for example, via {@link ServerSideSecretStorageImpl#addKey}. {@link SecretStorageCallbacks#getSecretStorageKey} will be called to obtain a secret storage\n * key to decrypt the secret.\n *\n * If the secret is `null`, the secret value in the account data will be set to an empty object.\n * This is considered as \"removing\" the secret.\n *\n * @param name - The name of the secret - i.e., the \"event type\" to be stored in the account data\n * @param secret - The secret contents.\n * @param keys - The IDs of the keys to use to encrypt the secret, or null/undefined to use the default key\n * (will throw if no default key is set).\n */\n store(name: string, secret: string | null, keys?: string[] | null): Promise<void>;\n\n /**\n * Get a secret from storage, and decrypt it.\n *\n * @param name - the name of the secret - i.e., the \"event type\" stored in the account data\n *\n * @returns the decrypted contents of the secret, or \"undefined\" if `name` is not found in\n * the user's account data.\n */\n get(name: string): Promise<string | undefined>;\n\n /**\n * Check if a secret is stored on the server.\n *\n * @param name - the name of the secret\n *\n * @returns map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n */\n isStored(name: SecretStorageKey): Promise<Record<string, SecretStorageKeyDescriptionAesV1> | null>;\n\n /**\n * Get the current default key ID for encrypting secrets.\n *\n * @returns The default key ID or null if no default key ID is set\n */\n getDefaultKeyId(): Promise<string | null>;\n\n /**\n * Set the default key ID for encrypting secrets.\n *\n * If keyId is `null`, the default key id value in the account data will be set to an empty object.\n * This is considered as \"disabling\" the default key.\n *\n * @param keyId - The new default key ID\n */\n setDefaultKeyId(keyId: string | null): Promise<void>;\n}\n\n/**\n * Implementation of Server-side secret storage.\n *\n * Secret *sharing* is *not* implemented here: this class is strictly about the storage component of\n * SSSS.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#storage\n */\nexport class ServerSideSecretStorageImpl implements ServerSideSecretStorage {\n /**\n * Construct a new `SecretStorage`.\n *\n * Normally, it is unnecessary to call this directly, since MatrixClient automatically constructs one.\n * However, it may be useful to construct a new `SecretStorage`, if custom `callbacks` are required, for example.\n *\n * @param accountDataAdapter - interface for fetching and setting account data on the server. Normally an instance\n * of {@link MatrixClient}.\n * @param callbacks - application level callbacks for retrieving secret keys\n */\n public constructor(\n private readonly accountDataAdapter: AccountDataClient,\n private readonly callbacks: SecretStorageCallbacks,\n ) {}\n\n /**\n * Get the current default key ID for encrypting secrets.\n *\n * @returns The default key ID or null if no default key ID is set\n */\n public async getDefaultKeyId(): Promise<string | null> {\n const defaultKey = await this.accountDataAdapter.getAccountDataFromServer(\"m.secret_storage.default_key\");\n if (!defaultKey) return null;\n return defaultKey.key ?? null;\n }\n\n /**\n * Implementation of {@link ServerSideSecretStorage#setDefaultKeyId}.\n */\n public setDefaultKeyId(keyId: string | null): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const listener = (ev: MatrixEvent): void => {\n if (ev.getType() !== \"m.secret_storage.default_key\") {\n // Different account data item\n return;\n }\n\n // If keyId === null, the content should be an empty object.\n // Otherwise, the `key` in the content object should match keyId.\n const content = ev.getContent();\n const isSameKey = keyId === null ? Object.keys(content).length === 0 : content.key === keyId;\n if (isSameKey) {\n this.accountDataAdapter.removeListener(ClientEvent.AccountData, listener);\n resolve();\n }\n };\n this.accountDataAdapter.on(ClientEvent.AccountData, listener);\n\n // The spec [1] says that the value of the account data entry should be an object with a `key` property.\n // It doesn't specify how to delete the default key; we do it by setting the account data to an empty object.\n //\n // [1]: https://spec.matrix.org/v1.13/client-server-api/#key-storage\n const newValue: Record<string, never> | { key: string } = keyId === null ? {} : { key: keyId };\n this.accountDataAdapter.setAccountData(\"m.secret_storage.default_key\", newValue).catch((e) => {\n this.accountDataAdapter.removeListener(ClientEvent.AccountData, listener);\n reject(e);\n });\n });\n }\n\n /**\n * Add a key for encrypting secrets.\n *\n * @param algorithm - the algorithm used by the key.\n * @param opts - the options for the algorithm. The properties used\n * depend on the algorithm given.\n * @param keyId - the ID of the key. If not given, a random\n * ID will be generated.\n *\n * @returns An object with:\n * keyId: the ID of the key\n * keyInfo: details about the key (iv, mac, passphrase)\n */\n public async addKey(\n algorithm: string,\n opts: AddSecretStorageKeyOpts,\n keyId?: string,\n ): Promise<SecretStorageKeyObject> {\n if (algorithm !== SECRET_STORAGE_ALGORITHM_V1_AES) {\n throw new Error(`Unknown key algorithm ${algorithm}`);\n }\n\n const keyInfo = { algorithm } as SecretStorageKeyDescriptionAesV1;\n\n if (opts.name) {\n keyInfo.name = opts.name;\n }\n\n if (opts.passphrase) {\n keyInfo.passphrase = opts.passphrase;\n }\n\n const { iv, mac } = await calculateKeyCheck(opts.key);\n keyInfo.iv = iv;\n keyInfo.mac = mac;\n\n // Create a unique key id. XXX: this is racey.\n if (!keyId) {\n do {\n keyId = secureRandomString(32);\n } while (await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${keyId}`));\n }\n\n await this.accountDataAdapter.setAccountData(`m.secret_storage.key.${keyId}`, keyInfo);\n\n return {\n keyId,\n keyInfo,\n };\n }\n\n /**\n * Get the key information for a given ID.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns If the key was found, the return value is an array of\n * the form [keyId, keyInfo]. Otherwise, null is returned.\n * XXX: why is this an array when addKey returns an object?\n */\n public async getKey(keyId?: string | null): Promise<SecretStorageKeyTuple | null> {\n if (!keyId) {\n keyId = await this.getDefaultKeyId();\n }\n if (!keyId) {\n return null;\n }\n\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${keyId}`);\n return keyInfo ? [keyId, keyInfo] : null;\n }\n\n /**\n * Check whether we have a key with a given ID.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns Whether we have the key.\n */\n public async hasKey(keyId?: string): Promise<boolean> {\n const key = await this.getKey(keyId);\n return Boolean(key);\n }\n\n /**\n * Check whether a key matches what we expect based on the key info\n *\n * @param key - the key to check\n * @param info - the key info\n *\n * @returns whether or not the key matches\n */\n public async checkKey(key: Uint8Array<ArrayBuffer>, info: SecretStorageKeyDescriptionAesV1): Promise<boolean> {\n if (info.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (info.mac) {\n const { mac } = await calculateKeyCheck(key, info.iv);\n return trimTrailingEquals(info.mac) === trimTrailingEquals(mac);\n } else {\n // if we have no information, we have to assume the key is right\n return true;\n }\n } else {\n throw new Error(\"Unknown algorithm\");\n }\n }\n\n /**\n * Implementation of {@link ServerSideSecretStorage#store}.\n */\n public async store(name: SecretStorageKey, secret: string | null, keys?: string[] | null): Promise<void> {\n if (secret === null) {\n // remove secret\n await this.accountDataAdapter.setAccountData(name, {});\n return;\n }\n\n const encrypted: Record<string, AESEncryptedSecretStoragePayload> = {};\n\n if (!keys) {\n const defaultKeyId = await this.getDefaultKeyId();\n if (!defaultKeyId) {\n throw new Error(\"No keys specified and no default key present\");\n }\n keys = [defaultKeyId];\n }\n\n if (keys.length === 0) {\n throw new Error(\"Zero keys given to encrypt with!\");\n }\n\n for (const keyId of keys) {\n // get key information from key storage\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${keyId}`);\n if (!keyInfo) {\n throw new Error(\"Unknown key: \" + keyId);\n }\n\n // encrypt secret, based on the algorithm\n if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n const keys = { [keyId]: keyInfo };\n const [, encryption] = await this.getSecretStorageKey(keys, name);\n encrypted[keyId] = await encryption.encrypt(secret);\n } else {\n logger.warn(\"unknown algorithm for secret storage key \" + keyId + \": \" + keyInfo.algorithm);\n // do nothing if we don't understand the encryption algorithm\n }\n }\n\n // save encrypted secret\n await this.accountDataAdapter.setAccountData(name, { encrypted });\n }\n\n /**\n * Get a secret from storage, and decrypt it.\n *\n * {@link SecretStorageCallbacks#getSecretStorageKey} will be called to obtain a secret storage\n * key to decrypt the secret.\n *\n * @param name - the name of the secret - i.e., the \"event type\" stored in the account data\n *\n * @returns the decrypted contents of the secret, or \"undefined\" if `name` is not found in\n * the user's account data.\n */\n public async get(name: SecretStorageKey): Promise<string | undefined> {\n const secretInfo = await this.accountDataAdapter.getAccountDataFromServer(name);\n if (!secretInfo) {\n return;\n }\n if (!secretInfo.encrypted) {\n throw new Error(\"Content is not encrypted!\");\n }\n\n // get possible keys to decrypt\n const keys: Record<string, SecretStorageKeyDescriptionAesV1> = {};\n for (const keyId of Object.keys(secretInfo.encrypted)) {\n // get key information from key storage\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${keyId}`);\n const encInfo = secretInfo.encrypted[keyId];\n // only use keys we understand the encryption algorithm of\n if (keyInfo?.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {\n keys[keyId] = keyInfo;\n }\n }\n }\n\n if (Object.keys(keys).length === 0) {\n throw new Error(\n `Could not decrypt ${name} because none of ` +\n `the keys it is encrypted with are for a supported algorithm`,\n );\n }\n\n // fetch private key from app\n const [keyId, decryption] = await this.getSecretStorageKey(keys, name);\n const encInfo = secretInfo.encrypted[keyId];\n\n return decryption.decrypt(encInfo);\n }\n\n /**\n * Check if a secret is stored on the server.\n *\n * @param name - the name of the secret\n *\n * @returns map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n */\n public async isStored(name: SecretStorageKey): Promise<Record<string, SecretStorageKeyDescriptionAesV1> | null> {\n // check if secret exists\n const secretInfo = await this.accountDataAdapter.getAccountDataFromServer(name);\n if (!secretInfo?.encrypted) return null;\n\n const ret: Record<string, SecretStorageKeyDescriptionAesV1> = {};\n\n // filter secret encryption keys with supported algorithm\n for (const keyId of Object.keys(secretInfo.encrypted)) {\n // get key information from key storage\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${keyId}`);\n if (!keyInfo) continue;\n const encInfo = secretInfo.encrypted[keyId];\n\n // only use keys we understand the encryption algorithm of\n if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {\n ret[keyId] = keyInfo;\n }\n }\n }\n return Object.keys(ret).length ? ret : null;\n }\n\n private async getSecretStorageKey(\n keys: Record<string, SecretStorageKeyDescriptionAesV1>,\n name: string,\n ): Promise<[string, Decryptors]> {\n if (!this.callbacks.getSecretStorageKey) {\n throw new Error(\"No getSecretStorageKey callback supplied\");\n }\n\n const returned = await this.callbacks.getSecretStorageKey({ keys }, name);\n\n if (!returned) {\n throw new Error(\"getSecretStorageKey callback returned falsey\");\n }\n if (returned.length < 2) {\n throw new Error(\"getSecretStorageKey callback returned invalid data\");\n }\n\n const [keyId, privateKey] = returned;\n if (!keys[keyId]) {\n throw new Error(\"App returned unknown key from getSecretStorageKey!\");\n }\n\n if (keys[keyId].algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n const decryption = {\n encrypt: function (secret: string): Promise<AESEncryptedSecretStoragePayload> {\n return encryptAESSecretStorageItem(secret, privateKey, name);\n },\n decrypt: function (encInfo: AESEncryptedSecretStoragePayload): Promise<string> {\n return decryptAESSecretStorageItem(encInfo, privateKey, name);\n },\n };\n return [keyId, decryption];\n } else {\n throw new Error(\"Unknown key type: \" + keys[keyId].algorithm);\n }\n }\n}\n\n/** trim trailing instances of '=' from a string\n *\n * @internal\n *\n * @param input - input string\n */\nexport function trimTrailingEquals(input: string): string {\n // according to Sonar and CodeQL, a regex such as /=+$/ is superlinear.\n // Not sure I believe it, but it's easy enough to work around.\n\n // find the number of characters before the trailing =\n let i = input.length;\n while (i >= 1 && input.charCodeAt(i - 1) == 0x3d) i--;\n\n // trim to the calculated length\n if (i < input.length) {\n return input.substring(0, i);\n } else {\n return input;\n }\n}\n\n// string of zeroes, for calculating the key check\nconst ZERO_STR = \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Calculate the MAC for checking the key.\n * See https://spec.matrix.org/v1.11/client-server-api/#msecret_storagev1aes-hmac-sha2, steps 3 and 4.\n *\n * @param key - the key to use\n * @param iv - The initialization vector as a base64-encoded string.\n * If omitted, a random initialization vector will be created.\n * @returns An object that contains, `mac` and `iv` properties.\n */\nexport function calculateKeyCheck(\n key: Uint8Array<ArrayBuffer>,\n iv?: string,\n): Promise<AESEncryptedSecretStoragePayload> {\n return encryptAESSecretStorageItem(ZERO_STR, key, \"\", iv);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAGA,SAAS,WAAW,QAAoC,aAAa;AAErE,SAAS,kBAAkB,QAAQ,mBAAmB;AACtD,SAAS,MAAM,QAAQ,aAAa;AACpC,OAAO,2BAA2B,MAAM,wCAAwC;AAChF,OAAO,2BAA2B,MAAM,wCAAwC;AAKhF,OAAO,MAAM,+BAA+B,GAAG,mCAAmC;;AAElF;AACA;AACA;AACA;AACA;AACA;AACA;;AAcA;AACA;AACA;AACA;AACA;AACA;AACA;;AAeA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;;AAeA;AACA;AACA;;AAUA;AACA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C8B;EACzC,OAAO,2BAA2B,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC;AAC7D","ignoreList":[]}
1
+ {"version":3,"file":"secret-storage.js","names":[],"sources":["../src/secret-storage.ts"],"sourcesContent":["/*\nCopyright 2021-2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Implementation of server-side secret storage\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#storage\n */\n\nimport { type TypedEventEmitter } from \"./models/typed-event-emitter.ts\";\nimport { type ClientEvent, type ClientEventHandlerMap } from \"./client.ts\";\nimport { secureRandomString } from \"./randomstring.ts\";\nimport { logger } from \"./logger.ts\";\nimport encryptAESSecretStorageItem from \"./utils/encryptAESSecretStorageItem.ts\";\nimport decryptAESSecretStorageItem from \"./utils/decryptAESSecretStorageItem.ts\";\nimport { type AESEncryptedSecretStoragePayload } from \"./@types/AESEncryptedSecretStoragePayload.ts\";\nimport { type AccountDataEvents, type SecretStorageAccountDataEvents } from \"./@types/event.ts\";\nimport { type EmptyObject } from \"./@types/common.ts\";\n\nexport const SECRET_STORAGE_ALGORITHM_V1_AES = \"m.secret_storage.v1.aes-hmac-sha2\";\n\n/**\n * Common base interface for Secret Storage Keys.\n *\n * The common properties for all encryption keys used in server-side secret storage.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#key-storage\n */\nexport interface SecretStorageKeyDescriptionCommon {\n /** A human-readable name for this key. */\n // XXX: according to the spec, this is optional\n name: string;\n\n /** The encryption algorithm used with this key. */\n algorithm: string;\n\n /** Information for deriving this key from a passphrase. */\n // XXX: according to the spec, this is optional\n passphrase: PassphraseInfo;\n}\n\n/**\n * Properties for a SSSS key using the `m.secret_storage.v1.aes-hmac-sha2` algorithm.\n *\n * Corresponds to `AesHmacSha2KeyDescription` in the specification.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#msecret_storagev1aes-hmac-sha2\n */\nexport interface SecretStorageKeyDescriptionAesV1 extends SecretStorageKeyDescriptionCommon {\n // XXX: strictly speaking, we should be able to enforce the algorithm here. But\n // this interface ends up being incorrectly used where other algorithms are in use (notably\n // in device-dehydration support), and unpicking that is too much like hard work\n // at the moment.\n // algorithm: \"m.secret_storage.v1.aes-hmac-sha2\";\n\n /** The 16-byte AES initialization vector, encoded as base64. */\n iv: string;\n\n /** The MAC of the result of encrypting 32 bytes of 0, encoded as base64. */\n mac: string;\n}\n\n/**\n * Union type for secret storage keys.\n *\n * For now, this is only {@link SecretStorageKeyDescriptionAesV1}, but other interfaces may be added in future.\n */\nexport type SecretStorageKeyDescription = SecretStorageKeyDescriptionAesV1;\n\n/**\n * Information on how to generate the key from a passphrase.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#deriving-keys-from-passphrases\n */\nexport interface PassphraseInfo {\n /** The algorithm to be used to derive the key. */\n algorithm: \"m.pbkdf2\";\n\n /** The number of PBKDF2 iterations to use. */\n iterations: number;\n\n /** The salt to be used for PBKDF2. */\n salt: string;\n\n /** The number of bits to generate. Defaults to 256. */\n bits?: number;\n}\n\n/**\n * Options for {@link ServerSideSecretStorageImpl#addKey}.\n */\nexport interface AddSecretStorageKeyOpts {\n /** Information for deriving the key from a passphrase if any. */\n passphrase?: PassphraseInfo;\n /** Optional name of the key. */\n name?: string;\n /** The private key. Will be used to generate the key check values in the key info; it will not be stored on the server */\n key: Uint8Array<ArrayBuffer>;\n}\n\n/**\n * Return type for {@link ServerSideSecretStorageImpl#getKey}.\n */\nexport type SecretStorageKeyTuple = [keyId: string, keyInfo: SecretStorageKeyDescription];\n\n/**\n * Return type for {@link ServerSideSecretStorageImpl#addKey}.\n */\nexport type SecretStorageKeyObject = {\n /** The ID of the key */\n keyId: string;\n /** details about the key */\n keyInfo: SecretStorageKeyDescription;\n};\n\n/** Interface for managing account data on the server.\n *\n * A subset of {@link MatrixClient}.\n */\nexport interface AccountDataClient extends TypedEventEmitter<ClientEvent.AccountData, ClientEventHandlerMap> {\n /**\n * Get account data event of given type for the current user. This variant\n * gets account data directly from the homeserver if the local store is not\n * ready, which can be useful very early in startup before the initial sync.\n *\n * @param eventType - The type of account data\n * @returns The contents of the given account data event, or `null` if the event is not found\n */\n getAccountDataFromServer: <K extends keyof AccountDataEvents>(eventType: K) => Promise<AccountDataEvents[K] | null>;\n\n /**\n * Set account data event for the current user, with retries\n *\n * @param eventType - The type of account data\n * @param content - the content object to be set\n * @returns an empty object\n */\n setAccountData: <K extends keyof AccountDataEvents>(\n eventType: K,\n content: AccountDataEvents[K] | Record<string, never>,\n ) => Promise<EmptyObject>;\n}\n\n/**\n * Application callbacks for use with {@link SecretStorage.ServerSideSecretStorageImpl}\n */\nexport interface SecretStorageCallbacks {\n /**\n * Called to retrieve a secret storage encryption key\n *\n * Before a secret can be stored in server-side storage, it must be encrypted with one or more\n * keys. Similarly, after it has been retrieved from storage, it must be decrypted with one of\n * the keys it was encrypted with. These encryption keys are known as \"secret storage keys\".\n *\n * Descriptions of the secret storage keys are also stored in server-side storage, per the\n * [matrix specification](https://spec.matrix.org/v1.6/client-server-api/#key-storage), so\n * before a key can be used in this way, it must have been stored on the server. This is\n * done via {@link ServerSideSecretStorage#addKey}.\n *\n * Obviously the keys themselves are not stored server-side, so the js-sdk calls this callback\n * in order to retrieve a secret storage key from the application.\n *\n * @param keys - An options object, containing only the property `keys`.\n *\n * @param name - the name of the *secret* (NB: not the encryption key) being stored or retrieved.\n * This is the \"event type\" stored in account data.\n *\n * @returns a pair [`keyId`, `privateKey`], where `keyId` is one of the keys from the `keys` parameter,\n * and `privateKey` is the raw private encryption key, as appropriate for the encryption algorithm.\n * (For `m.secret_storage.v1.aes-hmac-sha2`, it is the input to an HKDF as defined in the\n * [specification](https://spec.matrix.org/v1.6/client-server-api/#msecret_storagev1aes-hmac-sha2).)\n *\n * Alternatively, if none of the keys are known, may return `null` — in which case the original\n * storage/retrieval operation will fail with an exception.\n */\n getSecretStorageKey?: (\n keys: {\n /**\n * details of the secret storage keys required: a map from the key ID\n * (excluding the `m.secret_storage.key.` prefix) to details of the key.\n *\n * When storing a secret, `keys` will contain exactly one entry; this method will be called\n * once for each secret storage key to be used for encryption.\n *\n * For secret retrieval, `keys` may contain several entries, and the application can return\n * any one of the requested keys.\n */\n keys: Record<string, SecretStorageKeyDescription>;\n },\n name: string,\n ) => Promise<[string, Uint8Array<ArrayBuffer>] | null>;\n}\n\n/**\n * Account Data event types which can store secret-storage-encrypted information.\n */\nexport type SecretStorageKey = keyof SecretStorageAccountDataEvents;\n\n/**\n * Account Data event content type for storing secret-storage-encrypted information.\n *\n * See https://spec.matrix.org/v1.13/client-server-api/#msecret_storagev1aes-hmac-sha2-1\n */\nexport interface SecretInfo {\n encrypted: {\n [keyId: string]: AESEncryptedSecretStoragePayload;\n };\n}\n\ninterface Decryptors {\n encrypt: (plaintext: string) => Promise<AESEncryptedSecretStoragePayload>;\n decrypt: (ciphertext: AESEncryptedSecretStoragePayload) => Promise<string>;\n}\n\n/**\n * Interface provided by SecretStorage implementations\n *\n * Normally this will just be an {@link ServerSideSecretStorageImpl}, but for backwards\n * compatibility some methods allow other implementations.\n */\nexport interface ServerSideSecretStorage {\n /**\n * Add a key for encrypting secrets.\n *\n * @param algorithm - the algorithm used by the key.\n * @param opts - the options for the algorithm. The properties used\n * depend on the algorithm given.\n * @param keyId - the ID of the key. If not given, a random\n * ID will be generated.\n *\n * @returns details about the key.\n */\n addKey(algorithm: string, opts: AddSecretStorageKeyOpts, keyId?: string): Promise<SecretStorageKeyObject>;\n\n /**\n * Get the key information for a given ID.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns If the key was found, the return value is an array of\n * the form [keyId, keyInfo]. Otherwise, null is returned.\n * XXX: why is this an array when addKey returns an object?\n */\n getKey(keyId?: string | null): Promise<SecretStorageKeyTuple | null>;\n\n /**\n * Check whether we have a key with a given ID.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns Whether we have the key.\n */\n hasKey(keyId?: string): Promise<boolean>;\n\n /**\n * Check whether a key matches what we expect based on the key info\n *\n * @param key - the key to check\n * @param info - the key info\n *\n * @returns whether or not the key matches\n */\n checkKey(key: Uint8Array, info: SecretStorageKeyDescriptionAesV1): Promise<boolean>;\n\n /**\n * Store an encrypted secret on the server.\n *\n * Details of the encryption keys to be used must previously have been stored in account data\n * (for example, via {@link ServerSideSecretStorageImpl#addKey}. {@link SecretStorageCallbacks#getSecretStorageKey} will be called to obtain a secret storage\n * key to decrypt the secret.\n *\n * If the secret is `null`, the secret value in the account data will be set to an empty object.\n * This is considered as \"removing\" the secret.\n *\n * @param name - The name of the secret - i.e., the \"event type\" to be stored in the account data\n * @param secret - The secret contents.\n * @param keys - The IDs of the keys to use to encrypt the secret, or null/undefined to use the default key\n * (will throw if no default key is set).\n */\n store(name: string, secret: string | null, keys?: string[] | null): Promise<void>;\n\n /**\n * Get a secret from storage, and decrypt it.\n *\n * @param name - the name of the secret - i.e., the \"event type\" stored in the account data\n *\n * @returns the decrypted contents of the secret, or \"undefined\" if `name` is not found in\n * the user's account data.\n */\n get(name: string): Promise<string | undefined>;\n\n /**\n * Check if a secret is stored on the server.\n *\n * @param name - the name of the secret\n *\n * @returns map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n */\n isStored(name: SecretStorageKey): Promise<Record<string, SecretStorageKeyDescriptionAesV1> | null>;\n\n /**\n * Get the current default key ID for encrypting secrets.\n *\n * @returns The default key ID or null if no default key ID is set\n */\n getDefaultKeyId(): Promise<string | null>;\n\n /**\n * Set the default key ID for encrypting secrets.\n *\n * If keyId is `null`, the default key id value in the account data will be set to an empty object.\n * This is considered as \"disabling\" the default key.\n *\n * @param keyId - The new default key ID\n */\n setDefaultKeyId(keyId: string | null): Promise<void>;\n}\n\n/**\n * Implementation of Server-side secret storage.\n *\n * Secret *sharing* is *not* implemented here: this class is strictly about the storage component of\n * SSSS.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#storage\n */\nexport class ServerSideSecretStorageImpl implements ServerSideSecretStorage {\n /**\n * Construct a new `SecretStorage`.\n *\n * Normally, it is unnecessary to call this directly, since MatrixClient automatically constructs one.\n * However, it may be useful to construct a new `SecretStorage`, if custom `callbacks` are required, for example.\n *\n * @param accountDataAdapter - interface for fetching and setting account data on the server. Normally an instance\n * of {@link MatrixClient}.\n * @param callbacks - application level callbacks for retrieving secret keys\n */\n public constructor(\n private readonly accountDataAdapter: AccountDataClient,\n private readonly callbacks: SecretStorageCallbacks,\n ) {}\n\n /**\n * Get the current default key ID for encrypting secrets.\n *\n * @returns The default key ID or null if no default key ID is set\n */\n public async getDefaultKeyId(): Promise<string | null> {\n const defaultKey = await this.accountDataAdapter.getAccountDataFromServer(\"m.secret_storage.default_key\");\n if (!defaultKey) return null;\n return defaultKey.key ?? null;\n }\n\n /**\n * Implementation of {@link ServerSideSecretStorage#setDefaultKeyId}.\n */\n public async setDefaultKeyId(keyId: string | null): Promise<void> {\n // The spec [1] says that the value of the account data entry should be an object with a `key` property.\n // It doesn't specify how to delete the default key; we do it by setting the account data to an empty object.\n //\n // [1]: https://spec.matrix.org/v1.13/client-server-api/#key-storage\n const newValue: Record<string, never> | { key: string } = keyId === null ? {} : { key: keyId };\n await this.accountDataAdapter.setAccountData(\"m.secret_storage.default_key\", newValue);\n }\n\n /**\n * Add a key for encrypting secrets.\n *\n * @param algorithm - the algorithm used by the key.\n * @param opts - the options for the algorithm. The properties used\n * depend on the algorithm given.\n * @param keyId - the ID of the key. If not given, a random\n * ID will be generated.\n *\n * @returns An object with:\n * keyId: the ID of the key\n * keyInfo: details about the key (iv, mac, passphrase)\n */\n public async addKey(\n algorithm: string,\n opts: AddSecretStorageKeyOpts,\n keyId?: string,\n ): Promise<SecretStorageKeyObject> {\n if (algorithm !== SECRET_STORAGE_ALGORITHM_V1_AES) {\n throw new Error(`Unknown key algorithm ${algorithm}`);\n }\n\n const keyInfo = { algorithm } as SecretStorageKeyDescriptionAesV1;\n\n if (opts.name) {\n keyInfo.name = opts.name;\n }\n\n if (opts.passphrase) {\n keyInfo.passphrase = opts.passphrase;\n }\n\n const { iv, mac } = await calculateKeyCheck(opts.key);\n keyInfo.iv = iv;\n keyInfo.mac = mac;\n\n // Create a unique key id. XXX: this is racey.\n if (!keyId) {\n do {\n keyId = secureRandomString(32);\n } while (await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${keyId}`));\n }\n\n await this.accountDataAdapter.setAccountData(`m.secret_storage.key.${keyId}`, keyInfo);\n\n return {\n keyId,\n keyInfo,\n };\n }\n\n /**\n * Get the key information for a given ID.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns If the key was found, the return value is an array of\n * the form [keyId, keyInfo]. Otherwise, null is returned.\n * XXX: why is this an array when addKey returns an object?\n */\n public async getKey(keyId?: string | null): Promise<SecretStorageKeyTuple | null> {\n if (!keyId) {\n keyId = await this.getDefaultKeyId();\n }\n if (!keyId) {\n return null;\n }\n\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${keyId}`);\n return keyInfo ? [keyId, keyInfo] : null;\n }\n\n /**\n * Check whether we have a key with a given ID.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns Whether we have the key.\n */\n public async hasKey(keyId?: string): Promise<boolean> {\n const key = await this.getKey(keyId);\n return Boolean(key);\n }\n\n /**\n * Check whether a key matches what we expect based on the key info\n *\n * @param key - the key to check\n * @param info - the key info\n *\n * @returns whether or not the key matches\n */\n public async checkKey(key: Uint8Array<ArrayBuffer>, info: SecretStorageKeyDescriptionAesV1): Promise<boolean> {\n if (info.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (info.mac) {\n const { mac } = await calculateKeyCheck(key, info.iv);\n return trimTrailingEquals(info.mac) === trimTrailingEquals(mac);\n } else {\n // if we have no information, we have to assume the key is right\n return true;\n }\n } else {\n throw new Error(\"Unknown algorithm\");\n }\n }\n\n /**\n * Implementation of {@link ServerSideSecretStorage#store}.\n */\n public async store(name: SecretStorageKey, secret: string | null, keys?: string[] | null): Promise<void> {\n if (secret === null) {\n // remove secret\n await this.accountDataAdapter.setAccountData(name, {});\n return;\n }\n\n const encrypted: Record<string, AESEncryptedSecretStoragePayload> = {};\n\n if (!keys) {\n const defaultKeyId = await this.getDefaultKeyId();\n if (!defaultKeyId) {\n throw new Error(\"No keys specified and no default key present\");\n }\n keys = [defaultKeyId];\n }\n\n if (keys.length === 0) {\n throw new Error(\"Zero keys given to encrypt with!\");\n }\n\n for (const keyId of keys) {\n // get key information from key storage\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${keyId}`);\n if (!keyInfo) {\n throw new Error(\"Unknown key: \" + keyId);\n }\n\n // encrypt secret, based on the algorithm\n if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n const keys = { [keyId]: keyInfo };\n const [, encryption] = await this.getSecretStorageKey(keys, name);\n encrypted[keyId] = await encryption.encrypt(secret);\n } else {\n logger.warn(\"unknown algorithm for secret storage key \" + keyId + \": \" + keyInfo.algorithm);\n // do nothing if we don't understand the encryption algorithm\n }\n }\n\n // save encrypted secret\n await this.accountDataAdapter.setAccountData(name, { encrypted });\n }\n\n /**\n * Get a secret from storage, and decrypt it.\n *\n * {@link SecretStorageCallbacks#getSecretStorageKey} will be called to obtain a secret storage\n * key to decrypt the secret.\n *\n * @param name - the name of the secret - i.e., the \"event type\" stored in the account data\n *\n * @returns the decrypted contents of the secret, or \"undefined\" if `name` is not found in\n * the user's account data.\n */\n public async get(name: SecretStorageKey): Promise<string | undefined> {\n const secretInfo = await this.accountDataAdapter.getAccountDataFromServer(name);\n if (!secretInfo) {\n return;\n }\n if (!secretInfo.encrypted) {\n throw new Error(\"Content is not encrypted!\");\n }\n\n // get possible keys to decrypt\n const keys: Record<string, SecretStorageKeyDescriptionAesV1> = {};\n for (const keyId of Object.keys(secretInfo.encrypted)) {\n // get key information from key storage\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${keyId}`);\n const encInfo = secretInfo.encrypted[keyId];\n // only use keys we understand the encryption algorithm of\n if (keyInfo?.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {\n keys[keyId] = keyInfo;\n }\n }\n }\n\n if (Object.keys(keys).length === 0) {\n throw new Error(\n `Could not decrypt ${name} because none of ` +\n `the keys it is encrypted with are for a supported algorithm`,\n );\n }\n\n // fetch private key from app\n const [keyId, decryption] = await this.getSecretStorageKey(keys, name);\n const encInfo = secretInfo.encrypted[keyId];\n\n return decryption.decrypt(encInfo);\n }\n\n /**\n * Check if a secret is stored on the server.\n *\n * @param name - the name of the secret\n *\n * @returns map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n */\n public async isStored(name: SecretStorageKey): Promise<Record<string, SecretStorageKeyDescriptionAesV1> | null> {\n // check if secret exists\n const secretInfo = await this.accountDataAdapter.getAccountDataFromServer(name);\n if (!secretInfo?.encrypted) return null;\n\n const ret: Record<string, SecretStorageKeyDescriptionAesV1> = {};\n\n // filter secret encryption keys with supported algorithm\n for (const keyId of Object.keys(secretInfo.encrypted)) {\n // get key information from key storage\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${keyId}`);\n if (!keyInfo) continue;\n const encInfo = secretInfo.encrypted[keyId];\n\n // only use keys we understand the encryption algorithm of\n if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {\n ret[keyId] = keyInfo;\n }\n }\n }\n return Object.keys(ret).length ? ret : null;\n }\n\n private async getSecretStorageKey(\n keys: Record<string, SecretStorageKeyDescriptionAesV1>,\n name: string,\n ): Promise<[string, Decryptors]> {\n if (!this.callbacks.getSecretStorageKey) {\n throw new Error(\"No getSecretStorageKey callback supplied\");\n }\n\n const returned = await this.callbacks.getSecretStorageKey({ keys }, name);\n\n if (!returned) {\n throw new Error(\"getSecretStorageKey callback returned falsey\");\n }\n if (returned.length < 2) {\n throw new Error(\"getSecretStorageKey callback returned invalid data\");\n }\n\n const [keyId, privateKey] = returned;\n if (!keys[keyId]) {\n throw new Error(\"App returned unknown key from getSecretStorageKey!\");\n }\n\n if (keys[keyId].algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n const decryption = {\n encrypt: function (secret: string): Promise<AESEncryptedSecretStoragePayload> {\n return encryptAESSecretStorageItem(secret, privateKey, name);\n },\n decrypt: function (encInfo: AESEncryptedSecretStoragePayload): Promise<string> {\n return decryptAESSecretStorageItem(encInfo, privateKey, name);\n },\n };\n return [keyId, decryption];\n } else {\n throw new Error(\"Unknown key type: \" + keys[keyId].algorithm);\n }\n }\n}\n\n/** trim trailing instances of '=' from a string\n *\n * @internal\n *\n * @param input - input string\n */\nexport function trimTrailingEquals(input: string): string {\n // according to Sonar and CodeQL, a regex such as /=+$/ is superlinear.\n // Not sure I believe it, but it's easy enough to work around.\n\n // find the number of characters before the trailing =\n let i = input.length;\n while (i >= 1 && input.charCodeAt(i - 1) == 0x3d) i--;\n\n // trim to the calculated length\n if (i < input.length) {\n return input.substring(0, i);\n } else {\n return input;\n }\n}\n\n// string of zeroes, for calculating the key check\nconst ZERO_STR = \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Calculate the MAC for checking the key.\n * See https://spec.matrix.org/v1.11/client-server-api/#msecret_storagev1aes-hmac-sha2, steps 3 and 4.\n *\n * @param key - the key to use\n * @param iv - The initialization vector as a base64-encoded string.\n * If omitted, a random initialization vector will be created.\n * @returns An object that contains, `mac` and `iv` properties.\n */\nexport function calculateKeyCheck(\n key: Uint8Array<ArrayBuffer>,\n iv?: string,\n): Promise<AESEncryptedSecretStoragePayload> {\n return encryptAESSecretStorageItem(ZERO_STR, key, \"\", iv);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAIA,SAAS,kBAAkB,QAAQ,mBAAmB;AACtD,SAAS,MAAM,QAAQ,aAAa;AACpC,OAAO,2BAA2B,MAAM,wCAAwC;AAChF,OAAO,2BAA2B,MAAM,wCAAwC;AAKhF,OAAO,MAAM,+BAA+B,GAAG,mCAAmC;;AAElF;AACA;AACA;AACA;AACA;AACA;AACA;;AAcA;AACA;AACA;AACA;AACA;AACA;AACA;;AAeA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;;AAeA;AACA;AACA;;AAUA;AACA;AACA;;AAGA;AACA;AACA;;AAQA;AACA;AACA;AACA;;AAyBA;AACA;AACA;;AAgDA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;;AAYA;AACA;AACA;AACA;AACA;AACA;;AAqGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,2BAA2B,CAAoC;EACxE;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACW,WAAW,CACG,kBAAqC,EACrC,SAAiC,EACpD;IAAA,KAFmB,kBAAqC,GAArC,kBAAqC;IAAA,KACrC,SAAiC,GAAjC,SAAiC;EACnD;;EAEH;AACJ;AACA;AACA;AACA;EACI,MAAa,eAAe,GAA2B;IACnD,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,kBAAkB,CAAC,wBAAwB,CAAC,8BAA8B,CAAC;IACzG,IAAI,CA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gB,IAAI,OAAO,CAEjC;IAED;;OAEG;IACU,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAsBjC;IAED;;OAEG;IACI,IAAI,IAAI,IAAI,CAGlB;IAED;;;;OAIG;IACH,OAAO,CAAC,eAAe;IAOvB;;;;;;;OAOG;IACH,OAAO,CAAC,gBAAgB;IAaxB;;;;;;OAMG;IACH,OAAO,CAAC,kBAAkB;CAS7B"}
@@ -211,6 +211,55 @@ class ExtensionReceipts {
211
211
  }
212
212
  }
213
213
  }
214
+ /**
215
+ * Delivers sticky events (MSC4354) over sliding sync.
216
+ * https://github.com/matrix-org/matrix-spec-proposals/pull/4480
217
+ *
218
+ * Sticky events expire after a duration instead of living in the timeline forever, and the server
219
+ * re-sends the unexpired ones (e.g. on join) so late joiners still see them.
220
+ *
221
+ * The server sends them for every room matched by a list or subscription, even rooms currently
222
+ * outside the list window. Sticky events already in a room's timeline are excluded here, so
223
+ * `processRoomData` picks those up separately.
224
+ */
225
+ class ExtensionStickyEvents {
226
+ constructor(client) {
227
+ _defineProperty(this, "nextBatch", void 0);
228
+ this.client = client;
229
+ }
230
+ name() {
231
+ // Keeps MSC4354's number, as the extension was originally specified there.
232
+ return "org.matrix.msc4354.sticky_events";
233
+ }
234
+ when() {
235
+ // Sticky events are stored on a Room, so the room has to exist first.
236
+ return ExtensionState.PostProcess;
237
+ }
238
+ async onRequest(isInitial) {
239
+ return {
240
+ enabled: true,
241
+ limit: 100,
242
+ // Undefined until the first response, which asks for all unexpired sticky events.
243
+ since: this.nextBatch
244
+ };
245
+ }
246
+ async onResponse(data) {
247
+ for (const [roomId, roomData] of Object.entries(data?.rooms ?? {})) {
248
+ const room = this.client.getRoom(roomId);
249
+ if (!room) {
250
+ // Dropping is safe: unexpired sticky events are re-sent once we know the room.
251
+ logger.debug(`Ignoring sticky events for unknown room ${roomId}`);
252
+ continue;
253
+ }
254
+ room._unstable_addStickyEvents(mapEvents(this.client, roomId, roomData.events ?? []));
255
+ }
256
+
257
+ // next_batch is only returned when there were changes, and must be echoed back as `since`.
258
+ if (data?.next_batch) {
259
+ this.nextBatch = data.next_batch;
260
+ }
261
+ }
262
+ }
214
263
 
215
264
  /**
216
265
  * A copy of SyncApi such that it can be used as a drop-in replacement for sync v2. For the actual
@@ -236,7 +285,7 @@ export class SlidingSyncSdk {
236
285
  }
237
286
  this.slidingSync.on(SlidingSyncEvent.Lifecycle, this.onLifecycle.bind(this));
238
287
  this.slidingSync.on(SlidingSyncEvent.RoomData, this.onRoomData.bind(this));
239
- const extensions = [new ExtensionToDevice(this.client, this.syncOpts.cryptoCallbacks), new ExtensionAccountData(this.client), new ExtensionTyping(this.client), new ExtensionReceipts(this.client)];
288
+ const extensions = [new ExtensionToDevice(this.client, this.syncOpts.cryptoCallbacks), new ExtensionAccountData(this.client), new ExtensionTyping(this.client), new ExtensionReceipts(this.client), new ExtensionStickyEvents(this.client)];
240
289
  if (this.syncOpts.cryptoCallbacks) {
241
290
  extensions.push(new ExtensionE2EE(this.syncOpts.cryptoCallbacks));
242
291
  }
@@ -552,6 +601,10 @@ export class SlidingSyncSdk {
552
601
  // synchronous execution prior to emitting SlidingSyncState.Complete
553
602
  room.updateMyMembership(KnownMembership.Join);
554
603
  room.setMSC4186SummaryData(roomData.heroes, roomData.joined_count, roomData.invited_count);
604
+
605
+ // The MSC4480 extension excludes sticky events already present in the timeline, so we have
606
+ // to pick those up here. See ExtensionStickyEvents for the rest.
607
+ room._unstable_addStickyEvents(timelineEvents.filter(e => e.unstableStickyInfo !== undefined));
555
608
  room.recalculate();
556
609
  if (roomData.initial) {
557
610
  client.store.storeRoom(room);
@@ -1 +1 @@
1
- {"version":3,"file":"sliding-sync-sdk.js","names":[],"sources":["../src/sliding-sync-sdk.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type { SyncCryptoCallbacks } from \"./common-crypto/CryptoBackend.ts\";\nimport { NotificationCountType, Room, RoomEvent } from \"./models/room.ts\";\nimport { logger } from \"./logger.ts\";\nimport { promiseMapSeries } from \"./utils.ts\";\nimport { EventTimeline } from \"./models/event-timeline.ts\";\nimport { ClientEvent, type IStoredClientOpts, type MatrixClient } from \"./client.ts\";\nimport {\n type ISyncStateData,\n SyncState,\n _createAndReEmitRoom,\n type SyncApiOptions,\n defaultClientOpts,\n defaultSyncApiOpts,\n type SetPresence,\n processToDeviceMessages,\n} from \"./sync.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\nimport {\n type IMinimalEvent,\n type IRoomEvent,\n type IStateEvent,\n type IStrippedState,\n type ISyncResponse,\n type ReceivedToDeviceMessage,\n} from \"./sync-accumulator.ts\";\nimport { MatrixError } from \"./http-api/index.ts\";\nimport {\n type Extension,\n ExtensionState,\n type MSC3575RoomData,\n type MSC3575SlidingSyncResponse,\n type SlidingSync,\n SlidingSyncEvent,\n SlidingSyncState,\n} from \"./sliding-sync.ts\";\nimport { EventType } from \"./@types/event.ts\";\nimport { type IPushRules } from \"./@types/PushRules.ts\";\nimport { RoomStateEvent } from \"./models/room-state.ts\";\nimport { RoomMemberEvent } from \"./models/room-member.ts\";\nimport { KnownMembership } from \"./@types/membership.ts\";\n\n// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed\n// to RECONNECTING. This is needed to inform the client of server issues when the\n// keepAlive is successful but the server /sync fails.\nconst FAILED_SYNC_ERROR_THRESHOLD = 3;\n\ntype ExtensionE2EERequest = {\n enabled: boolean;\n};\n\ntype ExtensionE2EEResponse = Pick<\n ISyncResponse,\n | \"device_lists\"\n | \"device_one_time_keys_count\"\n | \"device_unused_fallback_key_types\"\n | \"org.matrix.msc2732.device_unused_fallback_key_types\"\n>;\n\nclass ExtensionE2EE implements Extension<ExtensionE2EERequest, ExtensionE2EEResponse> {\n public constructor(private readonly crypto: SyncCryptoCallbacks) {}\n\n public name(): string {\n return \"e2ee\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PreProcess;\n }\n\n public async onRequest(isInitial: boolean): Promise<ExtensionE2EERequest> {\n if (isInitial) {\n // In SSS, the `?pos=` contains the stream position for device list updates.\n // If we do not have a `?pos=` (e.g because we forgot it, or because the server\n // invalidated our connection) then we MUST invlaidate all device lists because\n // the server will not tell us the delta. This will then cause UTDs as we will fail\n // to encrypt for new devices. This is an expensive call, so we should\n // really really remember `?pos=` wherever possible.\n logger.log(\"ExtensionE2EE: invalidating all device lists due to missing 'pos'\");\n await this.crypto.markAllTrackedUsersAsDirty();\n }\n return {\n enabled: true, // this is sticky so only send it on the initial request\n };\n }\n\n public async onResponse(data: ExtensionE2EEResponse): Promise<void> {\n // Handle device list updates\n if (data.device_lists) {\n await this.crypto.processDeviceLists(data.device_lists);\n }\n\n // Handle one_time_keys_count and unused_fallback_key_types\n await this.crypto.processKeyCounts(\n data.device_one_time_keys_count,\n data[\"device_unused_fallback_key_types\"] || data[\"org.matrix.msc2732.device_unused_fallback_key_types\"],\n );\n\n this.crypto.onSyncCompleted({});\n }\n}\n\ntype ExtensionToDeviceRequest = {\n since?: string;\n limit?: number;\n enabled?: boolean;\n};\n\ntype ExtensionToDeviceResponse = {\n events: Required<ISyncResponse>[\"to_device\"][\"events\"];\n next_batch: string | null;\n};\n\nclass ExtensionToDevice implements Extension<ExtensionToDeviceRequest, ExtensionToDeviceResponse> {\n private nextBatch: string | null = null;\n\n public constructor(\n private readonly client: MatrixClient,\n private readonly cryptoCallbacks?: SyncCryptoCallbacks,\n ) {}\n\n public name(): string {\n return \"to_device\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PreProcess;\n }\n\n public async onRequest(isInitial: boolean): Promise<ExtensionToDeviceRequest> {\n return {\n since: this.nextBatch !== null ? this.nextBatch : undefined,\n limit: 100,\n enabled: true,\n };\n }\n\n public async onResponse(data: ExtensionToDeviceResponse): Promise<void> {\n const events = data[\"events\"] || [];\n let receivedToDeviceMessages: ReceivedToDeviceMessage[];\n if (this.cryptoCallbacks) {\n receivedToDeviceMessages = await this.cryptoCallbacks.preprocessToDeviceMessages(events);\n } else {\n // Crypto is not enabled, so we just return the events.\n receivedToDeviceMessages = events.map((rawEvent) => ({\n message: rawEvent,\n encryptionInfo: null,\n }));\n }\n processToDeviceMessages(receivedToDeviceMessages, this.client);\n\n this.nextBatch = data.next_batch;\n }\n}\n\ntype ExtensionAccountDataRequest = {\n enabled: boolean;\n};\n\ntype ExtensionAccountDataResponse = {\n global: IMinimalEvent[];\n rooms: Record<string, IMinimalEvent[]>;\n};\n\nclass ExtensionAccountData implements Extension<ExtensionAccountDataRequest, ExtensionAccountDataResponse> {\n public constructor(private readonly client: MatrixClient) {}\n\n public name(): string {\n return \"account_data\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PostProcess;\n }\n\n public async onRequest(isInitial: boolean): Promise<ExtensionAccountDataRequest> {\n return {\n enabled: true,\n };\n }\n\n public async onResponse(data: ExtensionAccountDataResponse): Promise<void> {\n if (data.global && data.global.length > 0) {\n this.processGlobalAccountData(data.global);\n }\n\n // oxlint-disable-next-line guard-for-in\n for (const roomId in data.rooms) {\n const accountDataEvents = mapEvents(this.client, roomId, data.rooms[roomId]);\n const room = this.client.getRoom(roomId);\n if (!room) {\n logger.warn(\"got account data for room but room doesn't exist on client:\", roomId);\n continue;\n }\n room.addAccountData(accountDataEvents);\n accountDataEvents.forEach((e) => {\n this.client.emit(ClientEvent.Event, e);\n });\n }\n }\n\n private processGlobalAccountData(globalAccountData: IMinimalEvent[]): void {\n const events = mapEvents(this.client, undefined, globalAccountData);\n const prevEventsMap = events.reduce<Record<string, MatrixEvent | undefined>>((m, c) => {\n m[c.getType()] = this.client.store.getAccountData(c.getType());\n return m;\n }, {});\n this.client.store.storeAccountDataEvents(events);\n events.forEach((accountDataEvent) => {\n // Honour push rules that come down the sync stream but also\n // honour push rules that were previously cached. Base rules\n // will be updated when we receive push rules via getPushRules\n // (see sync) before syncing over the network.\n if (accountDataEvent.getType() === EventType.PushRules) {\n const rules = accountDataEvent.getContent<IPushRules>();\n this.client.setPushRules(rules);\n }\n const prevEvent = prevEventsMap[accountDataEvent.getType()];\n this.client.emit(ClientEvent.AccountData, accountDataEvent, prevEvent);\n return accountDataEvent;\n });\n }\n}\n\ntype ExtensionTypingRequest = {\n enabled: boolean;\n};\n\ntype ExtensionTypingResponse = {\n rooms: Record<string, IMinimalEvent>;\n};\n\nclass ExtensionTyping implements Extension<ExtensionTypingRequest, ExtensionTypingResponse> {\n public constructor(private readonly client: MatrixClient) {}\n\n public name(): string {\n return \"typing\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PostProcess;\n }\n\n public async onRequest(isInitial: boolean): Promise<ExtensionTypingRequest> {\n return {\n enabled: true,\n };\n }\n\n public async onResponse(data: ExtensionTypingResponse): Promise<void> {\n if (!data?.rooms) {\n return;\n }\n\n // oxlint-disable-next-line guard-for-in\n for (const roomId in data.rooms) {\n processEphemeralEvents(this.client, roomId, [data.rooms[roomId]]);\n }\n }\n}\n\ntype ExtensionReceiptsRequest = {\n enabled: boolean;\n};\n\ntype ExtensionReceiptsResponse = {\n rooms: Record<string, IMinimalEvent>;\n};\n\nclass ExtensionReceipts implements Extension<ExtensionReceiptsRequest, ExtensionReceiptsResponse> {\n public constructor(private readonly client: MatrixClient) {}\n\n public name(): string {\n return \"receipts\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PostProcess;\n }\n\n public async onRequest(isInitial: boolean): Promise<ExtensionReceiptsRequest> {\n return {\n enabled: true,\n };\n }\n\n public async onResponse(data: ExtensionReceiptsResponse): Promise<void> {\n if (!data?.rooms) {\n return;\n }\n\n // oxlint-disable-next-line guard-for-in\n for (const roomId in data.rooms) {\n processEphemeralEvents(this.client, roomId, [data.rooms[roomId]]);\n }\n }\n}\n\n/**\n * A copy of SyncApi such that it can be used as a drop-in replacement for sync v2. For the actual\n * sliding sync API, see sliding-sync.ts or the class SlidingSync.\n */\nexport class SlidingSyncSdk {\n private readonly opts: IStoredClientOpts;\n private readonly syncOpts: SyncApiOptions;\n private syncState: SyncState | null = null;\n private syncStateData?: ISyncStateData;\n private lastPos: string | null = null;\n private failCount = 0;\n private notifEvents: MatrixEvent[] = []; // accumulator of sync events in the current sync response\n\n public constructor(\n private readonly slidingSync: SlidingSync,\n private readonly client: MatrixClient,\n opts: IStoredClientOpts | undefined,\n syncOpts: SyncApiOptions,\n ) {\n this.opts = defaultClientOpts(opts);\n this.syncOpts = defaultSyncApiOpts(syncOpts);\n\n if (client.getNotifTimelineSet()) {\n client.reEmitter.reEmit(client.getNotifTimelineSet()!, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n }\n\n this.slidingSync.on(SlidingSyncEvent.Lifecycle, this.onLifecycle.bind(this));\n this.slidingSync.on(SlidingSyncEvent.RoomData, this.onRoomData.bind(this));\n const extensions: Extension<any, any>[] = [\n new ExtensionToDevice(this.client, this.syncOpts.cryptoCallbacks),\n new ExtensionAccountData(this.client),\n new ExtensionTyping(this.client),\n new ExtensionReceipts(this.client),\n ];\n if (this.syncOpts.cryptoCallbacks) {\n extensions.push(new ExtensionE2EE(this.syncOpts.cryptoCallbacks));\n }\n extensions.forEach((ext) => {\n this.slidingSync.registerExtension(ext);\n });\n }\n\n private async onRoomData(roomId: string, roomData: MSC3575RoomData): Promise<void> {\n let room = this.client.store.getRoom(roomId);\n if (!room) {\n if (!roomData.initial) {\n this.syncOpts.logger.debug(\n \"initial flag not set but no stored room exists for room \",\n roomId,\n roomData,\n );\n return;\n }\n room = _createAndReEmitRoom(this.client, roomId, this.opts);\n }\n await this.processRoomData(this.client, room, roomData);\n }\n\n private onLifecycle(state: SlidingSyncState, resp: MSC3575SlidingSyncResponse | null, err?: Error): void {\n if (err) {\n this.syncOpts.logger.debug(\"onLifecycle\", state, err);\n }\n switch (state) {\n case SlidingSyncState.Complete:\n this.purgeNotifications();\n if (!resp) {\n break;\n }\n // Element won't stop showing the initial loading spinner unless we fire SyncState.Prepared\n if (!this.lastPos) {\n this.updateSyncState(SyncState.Prepared, {\n oldSyncToken: undefined,\n nextSyncToken: resp.pos,\n catchingUp: false,\n fromCache: false,\n });\n }\n // Conversely, Element won't show the room list unless there is at least 1x SyncState.Syncing\n // so hence for the very first sync we will fire prepared then immediately syncing.\n this.updateSyncState(SyncState.Syncing, {\n oldSyncToken: this.lastPos!,\n nextSyncToken: resp.pos,\n catchingUp: false,\n fromCache: false,\n });\n this.lastPos = resp.pos;\n break;\n case SlidingSyncState.RequestFinished:\n if (err) {\n this.failCount += 1;\n this.updateSyncState(\n this.failCount > FAILED_SYNC_ERROR_THRESHOLD ? SyncState.Error : SyncState.Reconnecting,\n {\n error: new MatrixError(err),\n },\n );\n if (this.shouldAbortSync(new MatrixError(err))) {\n return; // shouldAbortSync actually stops syncing too so we don't need to do anything.\n }\n } else {\n this.failCount = 0;\n this.syncOpts.logger.debug(\n `SlidingSyncState.RequestFinished with ${Object.keys(resp?.rooms || []).length} rooms`,\n );\n }\n break;\n }\n }\n\n /**\n * Sync rooms the user has left.\n * @returns Resolved when they've been added to the store.\n */\n public async syncLeftRooms(): Promise<Room[]> {\n return []; // TODO\n }\n\n /**\n * Peek into a room. This will result in the room in question being synced so it\n * is accessible via getRooms(). Live updates for the room will be provided.\n * @param roomId - The room ID to peek into.\n * @returns A promise which resolves once the room has been added to the\n * store.\n */\n public async peek(roomId: string): Promise<Room> {\n return null!; // TODO\n }\n\n /**\n * Stop polling for updates in the peeked room. NOPs if there is no room being\n * peeked.\n */\n public stopPeeking(): void {\n // TODO\n }\n\n /**\n * Specify the set_presence value to be used for subsequent calls to the Sync API.\n * @param presence - the presence to specify to set_presence of sync calls\n */\n public setPresence(presence?: SetPresence): void {\n // TODO not possible in sliding sync yet\n }\n\n /**\n * Returns the current state of this sync object\n * @see MatrixClient#event:\"sync\"\n */\n public getSyncState(): SyncState | null {\n return this.syncState;\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n */\n public getSyncStateData(): ISyncStateData | null {\n return this.syncStateData ?? null;\n }\n\n // Helper functions which set up JS SDK structs are below and are identical to the sync v2 counterparts\n\n public createRoom(roomId: string): Room {\n // XXX cargoculted from sync.ts\n const { timelineSupport } = this.client;\n const room = new Room(roomId, this.client, this.client.getUserId()!, {\n lazyLoadMembers: this.opts.lazyLoadMembers,\n pendingEventOrdering: this.opts.pendingEventOrdering,\n timelineSupport,\n });\n this.client.reEmitter.reEmit(room, [\n RoomEvent.Name,\n RoomEvent.Redaction,\n RoomEvent.RedactionCancelled,\n RoomEvent.Receipt,\n RoomEvent.Tags,\n RoomEvent.LocalEchoUpdated,\n RoomEvent.AccountData,\n RoomEvent.MyMembership,\n RoomEvent.Timeline,\n RoomEvent.TimelineReset,\n ]);\n this.registerStateListeners(room);\n return room;\n }\n\n private registerStateListeners(room: Room): void {\n // XXX cargoculted from sync.ts\n // we need to also re-emit room state and room member events, so hook it up\n // to the client now. We need to add a listener for RoomState.members in\n // order to hook them correctly.\n this.client.reEmitter.reEmit(room.currentState, [\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n ]);\n room.currentState.on(RoomStateEvent.NewMember, (event, state, member) => {\n member.user = this.client.getUser(member.userId) ?? undefined;\n this.client.reEmitter.reEmit(member, [\n RoomMemberEvent.Name,\n RoomMemberEvent.Typing,\n RoomMemberEvent.PowerLevel,\n RoomMemberEvent.Membership,\n ]);\n });\n }\n\n /*\n private deregisterStateListeners(room: Room): void { // XXX cargoculted from sync.ts\n // could do with a better way of achieving this.\n room.currentState.removeAllListeners(RoomStateEvent.Events);\n room.currentState.removeAllListeners(RoomStateEvent.Members);\n room.currentState.removeAllListeners(RoomStateEvent.NewMember);\n } */\n\n private shouldAbortSync(error: MatrixError): boolean {\n if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n // The logout already happened, we just need to stop.\n this.syncOpts.logger.warn(\"Token no longer valid - assuming logout\");\n this.stop();\n this.updateSyncState(SyncState.Error, { error });\n return true;\n }\n return false;\n }\n\n private async processRoomData(client: MatrixClient, room: Room, roomData: MSC3575RoomData): Promise<void> {\n roomData = ensureNameEvent(client, room.roomId, roomData);\n const stateEvents = mapEvents(this.client, room.roomId, roomData.required_state);\n // Prevent events from being decrypted ahead of time\n // this helps large account to speed up faster\n // room::decryptCriticalEvent is in charge of decrypting all the events\n // required for a client to function properly\n let timelineEvents = mapEvents(this.client, room.roomId, roomData.timeline, false);\n const ephemeralEvents: MatrixEvent[] = []; // TODO this.mapSyncEventsFormat(joinObj.ephemeral);\n\n // TODO: handle threaded / beacon events\n\n if (roomData.limited || roomData.initial) {\n // we should not know about any of these timeline entries if this is a genuinely new room.\n // If we do, then we've effectively done scrollback (e.g requesting timeline_limit: 1 for\n // this room, then timeline_limit: 50).\n const knownEvents = new Set<string>();\n room.getLiveTimeline()\n .getEvents()\n .forEach((e) => {\n knownEvents.add(e.getId()!);\n });\n // all unknown events BEFORE a known event must be scrollback e.g:\n // D E <-- what we know\n // A B C D E F <-- what we just received\n // means:\n // A B C <-- scrollback\n // D E <-- dupes\n // F <-- new event\n // We bucket events based on if we have seen a known event yet.\n const oldEvents: MatrixEvent[] = [];\n const newEvents: MatrixEvent[] = [];\n let seenKnownEvent = false;\n for (let i = timelineEvents.length - 1; i >= 0; i--) {\n const recvEvent = timelineEvents[i];\n if (knownEvents.has(recvEvent.getId()!)) {\n seenKnownEvent = true;\n continue; // don't include this event, it's a dupe\n }\n if (seenKnownEvent) {\n // old -> new\n oldEvents.push(recvEvent);\n } else {\n // old -> new\n newEvents.unshift(recvEvent);\n }\n }\n timelineEvents = newEvents;\n if (oldEvents.length > 0) {\n // old events are scrollback, insert them now\n room.addEventsToTimeline(oldEvents, true, false, room.getLiveTimeline(), roomData.prev_batch);\n }\n }\n\n const encrypted = room.hasEncryptionStateEvent();\n // we do this first so it's correct when any of the events fire\n if (roomData.notification_count != null) {\n room.setUnreadNotificationCount(NotificationCountType.Total, roomData.notification_count);\n }\n\n if (roomData.highlight_count != null) {\n // We track unread notifications ourselves in encrypted rooms, so don't\n // bother setting it here. We trust our calculations better than the\n // server's for this case, and therefore will assume that our non-zero\n // count is accurate.\n if (!encrypted || (encrypted && room.getUnreadNotificationCount(NotificationCountType.Highlight) <= 0)) {\n room.setUnreadNotificationCount(NotificationCountType.Highlight, roomData.highlight_count);\n }\n }\n if (roomData.bump_stamp) {\n room.setBumpStamp(roomData.bump_stamp);\n }\n\n if (Number.isInteger(roomData.invited_count)) {\n room.currentState.setInvitedMemberCount(roomData.invited_count!);\n }\n if (Number.isInteger(roomData.joined_count)) {\n room.currentState.setJoinedMemberCount(roomData.joined_count!);\n }\n\n if (roomData.invite_state) {\n const inviteStateEvents = mapEvents(this.client, room.roomId, roomData.invite_state);\n await this.injectRoomEvents(room, inviteStateEvents);\n if (roomData.initial) {\n room.recalculate();\n this.client.store.storeRoom(room);\n this.client.emit(ClientEvent.Room, room);\n }\n inviteStateEvents.forEach((e) => {\n this.client.emit(ClientEvent.Event, e);\n });\n return;\n }\n\n if (roomData.limited) {\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n room.getLiveTimeline().setPaginationToken(roomData.prev_batch ?? null, EventTimeline.BACKWARDS);\n }\n\n /* TODO\n else if (roomData.limited) {\n\n let limited = true;\n\n // we've got a limited sync, so we *probably* have a gap in the\n // timeline, so should reset. But we might have been peeking or\n // paginating and already have some of the events, in which\n // case we just want to append any subsequent events to the end\n // of the existing timeline.\n //\n // This is particularly important in the case that we already have\n // *all* of the events in the timeline - in that case, if we reset\n // the timeline, we'll end up with an entirely empty timeline,\n // which we'll try to paginate but not get any new events (which\n // will stop us linking the empty timeline into the chain).\n //\n for (let i = timelineEvents.length - 1; i >= 0; i--) {\n const eventId = timelineEvents[i].getId();\n if (room.getTimelineForEvent(eventId)) {\n this.syncOpts.logger.debug(\"Already have event \" + eventId + \" in limited \" +\n \"sync - not resetting\");\n limited = false;\n\n // we might still be missing some of the events before i;\n // we don't want to be adding them to the end of the\n // timeline because that would put them out of order.\n timelineEvents.splice(0, i);\n\n // XXX: there's a problem here if the skipped part of the\n // timeline modifies the state set in stateEvents, because\n // we'll end up using the state from stateEvents rather\n // than the later state from timelineEvents. We probably\n // need to wind stateEvents forward over the events we're\n // skipping.\n break;\n }\n }\n\n if (limited) {\n room.resetLiveTimeline(\n roomData.prev_batch,\n null, // TODO this.syncOpts.canResetEntireTimeline(room.roomId) ? null : syncEventData.oldSyncToken,\n );\n\n // We have to assume any gap in any timeline is\n // reason to stop incrementally tracking notifications and\n // reset the timeline.\n this.client.resetNotifTimelineSet();\n this.registerStateListeners(room);\n }\n } */\n\n await this.injectRoomEvents(room, stateEvents, timelineEvents, roomData.num_live);\n\n // we deliberately don't add ephemeral events to the timeline\n room.addEphemeralEvents(ephemeralEvents);\n\n // local fields must be set before any async calls because call site assumes\n // synchronous execution prior to emitting SlidingSyncState.Complete\n room.updateMyMembership(KnownMembership.Join);\n\n room.setMSC4186SummaryData(roomData.heroes, roomData.joined_count, roomData.invited_count);\n\n room.recalculate();\n if (roomData.initial) {\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n }\n\n // check if any timeline events should bing and add them to the notifEvents array:\n // we'll purge this once we've fully processed the sync response\n this.addNotifications(timelineEvents);\n\n const processRoomEvent = async (e: MatrixEvent): Promise<void> => {\n client.emit(ClientEvent.Event, e);\n if (e.isState() && e.getType() == EventType.RoomEncryption && this.syncOpts.cryptoCallbacks) {\n await this.syncOpts.cryptoCallbacks.onCryptoEvent(room, e);\n }\n };\n\n await promiseMapSeries(stateEvents, processRoomEvent);\n await promiseMapSeries(timelineEvents, processRoomEvent);\n ephemeralEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n\n // Decrypt only the last message in all rooms to make sure we can generate a preview\n // And decrypt all events after the recorded read receipt to ensure an accurate\n // notification count\n room.decryptCriticalEvents();\n }\n\n /**\n * Injects events into a room's model.\n * @param stateEventList - A list of state events. This is the state\n * at the *END* of the timeline list if it is supplied.\n * @param timelineEventList - A list of timeline events. Lower index\n * is earlier in time. Higher index is later.\n * @param numLive - the number of events in timelineEventList which just happened,\n * supplied from the server.\n */\n public async injectRoomEvents(\n room: Room,\n stateEventList: MatrixEvent[],\n timelineEventList: MatrixEvent[] = [],\n numLive: number = 0,\n ): Promise<void> {\n // If there are no events in the timeline yet, initialise it with\n // the given state events\n const liveTimeline = room.getLiveTimeline();\n const timelineWasEmpty = liveTimeline.getEvents().length == 0;\n if (timelineWasEmpty) {\n // Passing these events into initialiseState will freeze them, so we need\n // to compute and cache the push actions for them now, otherwise sync dies\n // with an attempt to assign to read only property.\n // XXX: This is pretty horrible and is assuming all sorts of behaviour from\n // these functions that it shouldn't be. We should probably either store the\n // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise\n // find some solution where MatrixEvents are immutable but allow for a cache\n // field.\n for (const ev of stateEventList) {\n this.client.getPushActionsForEvent(ev);\n }\n liveTimeline.initialiseState(stateEventList);\n }\n\n // If the timeline wasn't empty, we process the state events here: they're\n // defined as updates to the state before the start of the timeline, so this\n // starts to roll the state forward.\n // XXX: That's what we *should* do, but this can happen if we were previously\n // peeking in a room, in which case we obviously do *not* want to add the\n // state events here onto the end of the timeline. Historically, the js-sdk\n // has just set these new state events on the old and new state. This seems\n // very wrong because there could be events in the timeline that diverge the\n // state, in which case this is going to leave things out of sync. However,\n // for now I think it;s best to behave the same as the code has done previously.\n if (!timelineWasEmpty) {\n // XXX: As above, don't do this...\n //room.addLiveEvents(stateEventList || []);\n // Do this instead...\n room.oldState.setStateEvents(stateEventList);\n room.currentState.setStateEvents(stateEventList);\n }\n\n // the timeline is broken into 'live' events which just happened and normal timeline events\n // which are still to be appended to the end of the live timeline but happened a while ago.\n // The live events are marked as fromCache=false to ensure that downstream components know\n // this is a live event, not historical (from a remote server cache).\n\n let liveTimelineEvents: MatrixEvent[] = [];\n if (numLive > 0) {\n // last numLive events are live\n liveTimelineEvents = timelineEventList.slice(-1 * numLive);\n // everything else is not live\n timelineEventList = timelineEventList.slice(0, -1 * liveTimelineEvents.length);\n }\n\n // Execute the timeline events.\n // This also needs to be done before running push rules on the events as they need\n // to be decorated with sender etc.\n await room.addLiveEvents(timelineEventList, {\n fromCache: true,\n addToState: false,\n });\n if (liveTimelineEvents.length > 0) {\n await room.addLiveEvents(liveTimelineEvents, {\n fromCache: false,\n addToState: false,\n });\n }\n\n room.recalculate();\n\n // resolve invites now we have set the latest state\n this.resolveInvites(room);\n }\n\n private resolveInvites(room: Room): void {\n if (!room || !this.opts.resolveInvitesToProfiles) {\n return;\n }\n const client = this.client;\n // For each invited room member we want to give them a displayname/avatar url\n // if they have one (the m.room.member invites don't contain this).\n room.getMembersWithMembership(KnownMembership.Invite).forEach(function (member) {\n if (member.requestedProfileInfo) return;\n member.requestedProfileInfo = true;\n // try to get a cached copy first.\n const user = client.getUser(member.userId);\n let promise: ReturnType<MatrixClient[\"getProfileInfo\"]>;\n if (user) {\n promise = Promise.resolve({\n avatar_url: user.avatarUrl,\n displayname: user.displayName,\n });\n } else {\n promise = client.getProfileInfo(member.userId);\n }\n promise.then(\n function (info) {\n // slightly naughty by doctoring the invite event but this means all\n // the code paths remain the same between invite/join display name stuff\n // which is a worthy trade-off for some minor pollution.\n const inviteEvent = member.events.member!;\n if (inviteEvent.getContent().membership !== KnownMembership.Invite) {\n // between resolving and now they have since joined, so don't clobber\n return;\n }\n inviteEvent.getContent().avatar_url = info.avatar_url;\n inviteEvent.getContent().displayname = info.displayname;\n // fire listeners\n member.setMembershipEvent(inviteEvent, room.currentState);\n },\n function (_err) {\n // OH WELL.\n },\n );\n });\n }\n\n public retryImmediately(): boolean {\n return true;\n }\n\n /**\n * Main entry point. Blocks until stop() is called.\n */\n public async sync(): Promise<void> {\n this.syncOpts.logger.debug(\"Sliding sync init loop\");\n\n // 1) We need to get push rules so we can check if events should bing as we get\n // them from /sync.\n while (!this.client.isGuest()) {\n try {\n this.syncOpts.logger.debug(\"Getting push rules...\");\n const result = await this.client.getPushRules();\n this.syncOpts.logger.debug(\"Got push rules\");\n this.client.pushRules = result;\n break;\n } catch (err) {\n this.syncOpts.logger.error(\"Getting push rules failed\", err);\n if (this.shouldAbortSync(<MatrixError>err)) {\n return;\n }\n }\n }\n\n // start syncing\n await this.slidingSync.start();\n }\n\n /**\n * Stops the sync object from syncing.\n */\n public stop(): void {\n this.syncOpts.logger.debug(\"SyncApi.stop\");\n this.slidingSync.stop();\n }\n\n /**\n * Sets the sync state and emits an event to say so\n * @param newState - The new state string\n * @param data - Object of additional data to emit in the event\n */\n private updateSyncState(newState: SyncState, data?: ISyncStateData): void {\n const old = this.syncState;\n this.syncState = newState;\n this.syncStateData = data;\n this.client.emit(ClientEvent.Sync, this.syncState, old, data);\n }\n\n /**\n * Takes a list of timelineEvents and adds and adds to notifEvents\n * as appropriate.\n * This must be called after the room the events belong to has been stored.\n *\n * @param timelineEventList - A list of timeline events. Lower index\n * is earlier in time. Higher index is later.\n */\n private addNotifications(timelineEventList: MatrixEvent[]): void {\n // gather our notifications into this.notifEvents\n if (!this.client.getNotifTimelineSet()) {\n return;\n }\n for (const timelineEvent of timelineEventList) {\n const pushActions = this.client.getPushActionsForEvent(timelineEvent);\n if (pushActions && pushActions.notify && pushActions.tweaks && pushActions.tweaks.highlight) {\n this.notifEvents.push(timelineEvent);\n }\n }\n }\n\n /**\n * Purge any events in the notifEvents array. Used after a /sync has been complete.\n * This should not be called at a per-room scope (e.g in onRoomData) because otherwise the ordering\n * will be messed up e.g room A gets a bing, room B gets a newer bing, but both in the same /sync\n * response. If we purge at a per-room scope then we could process room B before room A leading to\n * room B appearing earlier in the notifications timeline, even though it has the higher origin_server_ts.\n */\n private purgeNotifications(): void {\n this.notifEvents.sort(function (a, b) {\n return a.getTs() - b.getTs();\n });\n this.notifEvents.forEach((event) => {\n this.client.getNotifTimelineSet()?.addLiveEvent(event, { addToState: false });\n });\n this.notifEvents = [];\n }\n}\n\nfunction ensureNameEvent(client: MatrixClient, roomId: string, roomData: MSC3575RoomData): MSC3575RoomData {\n // make sure m.room.name is in required_state if there is a name, replacing anything previously\n // there if need be. This ensures clients transparently 'calculate' the right room name. Native\n // sliding sync clients should just read the \"name\" field.\n if (!roomData.name) {\n return roomData;\n }\n for (const stateEvent of roomData.required_state) {\n if (stateEvent.type === EventType.RoomName && stateEvent.state_key === \"\") {\n stateEvent.content = {\n name: roomData.name,\n };\n return roomData;\n }\n }\n roomData.required_state.push({\n event_id: \"$fake-sliding-sync-name-event-\" + roomId,\n state_key: \"\",\n type: EventType.RoomName,\n content: {\n name: roomData.name,\n },\n sender: client.getUserId()!,\n origin_server_ts: new Date().getTime(),\n });\n return roomData;\n}\n\ntype TaggedEvent = (IStrippedState | IRoomEvent | IStateEvent | IMinimalEvent) & { room_id?: string };\n\n// Helper functions which set up JS SDK structs are below and are identical to the sync v2 counterparts,\n// just outside the class.\nfunction mapEvents(client: MatrixClient, roomId: string | undefined, events: object[], decrypt = true): MatrixEvent[] {\n const mapper = client.getEventMapper({ decrypt });\n return (events as TaggedEvent[]).map(function (e) {\n e.room_id = roomId;\n return mapper(e);\n });\n}\n\nfunction processEphemeralEvents(client: MatrixClient, roomId: string, ephEvents: IMinimalEvent[]): void {\n const ephemeralEvents = mapEvents(client, roomId, ephEvents);\n const room = client.getRoom(roomId);\n if (!room) {\n logger.warn(\"got ephemeral events for room but room doesn't exist on client:\", roomId);\n return;\n }\n room.addEphemeralEvents(ephemeralEvents);\n ephemeralEvents.forEach((e) => {\n client.emit(ClientEvent.Event, e);\n });\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAAS,qBAAqB,E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AAC;IACD,MAAM,EAAE,MAAM,CAAC,SAAS,CAAC,CAAE;IAC3B,gBAAgB,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC;EACzC,CAAC,CAAC;EACF,OAAO,QAAQ;AACnB;AAIA;AACA;AACA,SAAS,SAAS,CAAC,MAAoB,EAAE,MAA0B,EAAE,MAAgB,EAAE,OAAO,GAAG,IAAI,EAAiB;EAClH,MAAM,MAAM,GAAG,MAAM,CAAC,cAAc,CAAC;IAAE;EAAQ,CAAC,CAAC;EACjD,OAAQ,MAAM,CAAmB,GAAG,CAAC,UAAU,CAAC,EAAE;IAC9C,CAAC,CAAC,OAAO,GAAG,MAAM;IAClB,OAAO,MAAM,CAAC,CAAC,CAAC;EACpB,CAAC,CAAC;AACN;AAEA,SAAS,sBAAsB,CAAC,MAAoB,EAAE,MAAc,EAAE,SAA0B,EAAQ;EACpG,MAAM,eAAe,GAAG,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC;EAC5D,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;EACnC,IAAI,CAAC,IAAI,EAAE;IACP,MAAM,CAAC,IAAI,CAAC,iEAAiE,EAAE,MAAM,CAAC;IACtF;EACJ;EACA,IAAI,CAAC,kBAAkB,CAAC,eAAe,CAAC;EACxC,eAAe,CAAC,OAAO,CAAE,CAAC,IAAK;IAC3B,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC;EACrC,CAAC,CAAC;AACN","ignoreList":[]}
1
+ {"version":3,"file":"sliding-sync-sdk.js","names":[],"sources":["../src/sliding-sync-sdk.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type { SyncCryptoCallbacks } from \"./common-crypto/CryptoBackend.ts\";\nimport { NotificationCountType, Room, RoomEvent } from \"./models/room.ts\";\nimport { logger } from \"./logger.ts\";\nimport { promiseMapSeries } from \"./utils.ts\";\nimport { EventTimeline } from \"./models/event-timeline.ts\";\nimport { ClientEvent, type IStoredClientOpts, type MatrixClient } from \"./client.ts\";\nimport {\n type ISyncStateData,\n SyncState,\n _createAndReEmitRoom,\n type SyncApiOptions,\n defaultClientOpts,\n defaultSyncApiOpts,\n type SetPresence,\n processToDeviceMessages,\n} from \"./sync.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\nimport {\n type IMinimalEvent,\n type IRoomEvent,\n type IStateEvent,\n type IStickyEvent,\n type IStickyStateEvent,\n type IStrippedState,\n type ISyncResponse,\n type ReceivedToDeviceMessage,\n} from \"./sync-accumulator.ts\";\nimport { MatrixError } from \"./http-api/index.ts\";\nimport {\n type Extension,\n ExtensionState,\n type MSC3575RoomData,\n type MSC3575SlidingSyncResponse,\n type SlidingSync,\n SlidingSyncEvent,\n SlidingSyncState,\n} from \"./sliding-sync.ts\";\nimport { EventType } from \"./@types/event.ts\";\nimport { type IPushRules } from \"./@types/PushRules.ts\";\nimport { RoomStateEvent } from \"./models/room-state.ts\";\nimport { RoomMemberEvent } from \"./models/room-member.ts\";\nimport { KnownMembership } from \"./@types/membership.ts\";\n\n// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed\n// to RECONNECTING. This is needed to inform the client of server issues when the\n// keepAlive is successful but the server /sync fails.\nconst FAILED_SYNC_ERROR_THRESHOLD = 3;\n\ntype ExtensionE2EERequest = {\n enabled: boolean;\n};\n\ntype ExtensionE2EEResponse = Pick<\n ISyncResponse,\n | \"device_lists\"\n | \"device_one_time_keys_count\"\n | \"device_unused_fallback_key_types\"\n | \"org.matrix.msc2732.device_unused_fallback_key_types\"\n>;\n\nclass ExtensionE2EE implements Extension<ExtensionE2EERequest, ExtensionE2EEResponse> {\n public constructor(private readonly crypto: SyncCryptoCallbacks) {}\n\n public name(): string {\n return \"e2ee\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PreProcess;\n }\n\n public async onRequest(isInitial: boolean): Promise<ExtensionE2EERequest> {\n if (isInitial) {\n // In SSS, the `?pos=` contains the stream position for device list updates.\n // If we do not have a `?pos=` (e.g because we forgot it, or because the server\n // invalidated our connection) then we MUST invlaidate all device lists because\n // the server will not tell us the delta. This will then cause UTDs as we will fail\n // to encrypt for new devices. This is an expensive call, so we should\n // really really remember `?pos=` wherever possible.\n logger.log(\"ExtensionE2EE: invalidating all device lists due to missing 'pos'\");\n await this.crypto.markAllTrackedUsersAsDirty();\n }\n return {\n enabled: true, // this is sticky so only send it on the initial request\n };\n }\n\n public async onResponse(data: ExtensionE2EEResponse): Promise<void> {\n // Handle device list updates\n if (data.device_lists) {\n await this.crypto.processDeviceLists(data.device_lists);\n }\n\n // Handle one_time_keys_count and unused_fallback_key_types\n await this.crypto.processKeyCounts(\n data.device_one_time_keys_count,\n data[\"device_unused_fallback_key_types\"] || data[\"org.matrix.msc2732.device_unused_fallback_key_types\"],\n );\n\n this.crypto.onSyncCompleted({});\n }\n}\n\ntype ExtensionToDeviceRequest = {\n since?: string;\n limit?: number;\n enabled?: boolean;\n};\n\ntype ExtensionToDeviceResponse = {\n events: Required<ISyncResponse>[\"to_device\"][\"events\"];\n next_batch: string | null;\n};\n\nclass ExtensionToDevice implements Extension<ExtensionToDeviceRequest, ExtensionToDeviceResponse> {\n private nextBatch: string | null = null;\n\n public constructor(\n private readonly client: MatrixClient,\n private readonly cryptoCallbacks?: SyncCryptoCallbacks,\n ) {}\n\n public name(): string {\n return \"to_device\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PreProcess;\n }\n\n public async onRequest(isInitial: boolean): Promise<ExtensionToDeviceRequest> {\n return {\n since: this.nextBatch !== null ? this.nextBatch : undefined,\n limit: 100,\n enabled: true,\n };\n }\n\n public async onResponse(data: ExtensionToDeviceResponse): Promise<void> {\n const events = data[\"events\"] || [];\n let receivedToDeviceMessages: ReceivedToDeviceMessage[];\n if (this.cryptoCallbacks) {\n receivedToDeviceMessages = await this.cryptoCallbacks.preprocessToDeviceMessages(events);\n } else {\n // Crypto is not enabled, so we just return the events.\n receivedToDeviceMessages = events.map((rawEvent) => ({\n message: rawEvent,\n encryptionInfo: null,\n }));\n }\n processToDeviceMessages(receivedToDeviceMessages, this.client);\n\n this.nextBatch = data.next_batch;\n }\n}\n\ntype ExtensionAccountDataRequest = {\n enabled: boolean;\n};\n\ntype ExtensionAccountDataResponse = {\n global: IMinimalEvent[];\n rooms: Record<string, IMinimalEvent[]>;\n};\n\nclass ExtensionAccountData implements Extension<ExtensionAccountDataRequest, ExtensionAccountDataResponse> {\n public constructor(private readonly client: MatrixClient) {}\n\n public name(): string {\n return \"account_data\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PostProcess;\n }\n\n public async onRequest(isInitial: boolean): Promise<ExtensionAccountDataRequest> {\n return {\n enabled: true,\n };\n }\n\n public async onResponse(data: ExtensionAccountDataResponse): Promise<void> {\n if (data.global && data.global.length > 0) {\n this.processGlobalAccountData(data.global);\n }\n\n // oxlint-disable-next-line guard-for-in\n for (const roomId in data.rooms) {\n const accountDataEvents = mapEvents(this.client, roomId, data.rooms[roomId]);\n const room = this.client.getRoom(roomId);\n if (!room) {\n logger.warn(\"got account data for room but room doesn't exist on client:\", roomId);\n continue;\n }\n room.addAccountData(accountDataEvents);\n accountDataEvents.forEach((e) => {\n this.client.emit(ClientEvent.Event, e);\n });\n }\n }\n\n private processGlobalAccountData(globalAccountData: IMinimalEvent[]): void {\n const events = mapEvents(this.client, undefined, globalAccountData);\n const prevEventsMap = events.reduce<Record<string, MatrixEvent | undefined>>((m, c) => {\n m[c.getType()] = this.client.store.getAccountData(c.getType());\n return m;\n }, {});\n this.client.store.storeAccountDataEvents(events);\n events.forEach((accountDataEvent) => {\n // Honour push rules that come down the sync stream but also\n // honour push rules that were previously cached. Base rules\n // will be updated when we receive push rules via getPushRules\n // (see sync) before syncing over the network.\n if (accountDataEvent.getType() === EventType.PushRules) {\n const rules = accountDataEvent.getContent<IPushRules>();\n this.client.setPushRules(rules);\n }\n const prevEvent = prevEventsMap[accountDataEvent.getType()];\n this.client.emit(ClientEvent.AccountData, accountDataEvent, prevEvent);\n return accountDataEvent;\n });\n }\n}\n\ntype ExtensionTypingRequest = {\n enabled: boolean;\n};\n\ntype ExtensionTypingResponse = {\n rooms: Record<string, IMinimalEvent>;\n};\n\nclass ExtensionTyping implements Extension<ExtensionTypingRequest, ExtensionTypingResponse> {\n public constructor(private readonly client: MatrixClient) {}\n\n public name(): string {\n return \"typing\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PostProcess;\n }\n\n public async onRequest(isInitial: boolean): Promise<ExtensionTypingRequest> {\n return {\n enabled: true,\n };\n }\n\n public async onResponse(data: ExtensionTypingResponse): Promise<void> {\n if (!data?.rooms) {\n return;\n }\n\n // oxlint-disable-next-line guard-for-in\n for (const roomId in data.rooms) {\n processEphemeralEvents(this.client, roomId, [data.rooms[roomId]]);\n }\n }\n}\n\ntype ExtensionReceiptsRequest = {\n enabled: boolean;\n};\n\ntype ExtensionReceiptsResponse = {\n rooms: Record<string, IMinimalEvent>;\n};\n\nclass ExtensionReceipts implements Extension<ExtensionReceiptsRequest, ExtensionReceiptsResponse> {\n public constructor(private readonly client: MatrixClient) {}\n\n public name(): string {\n return \"receipts\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PostProcess;\n }\n\n public async onRequest(isInitial: boolean): Promise<ExtensionReceiptsRequest> {\n return {\n enabled: true,\n };\n }\n\n public async onResponse(data: ExtensionReceiptsResponse): Promise<void> {\n if (!data?.rooms) {\n return;\n }\n\n // oxlint-disable-next-line guard-for-in\n for (const roomId in data.rooms) {\n processEphemeralEvents(this.client, roomId, [data.rooms[roomId]]);\n }\n }\n}\n\ntype ExtensionStickyEventsRequest = {\n enabled: boolean;\n /** Max events per response; the server may return fewer. */\n limit?: number;\n /** The `next_batch` of the previous response. */\n since?: string;\n};\n\ntype ExtensionStickyEventsResponse = {\n /** Only sent when there were changes. */\n next_batch?: string;\n rooms?: Record<string, { events: Array<IStickyEvent | IStickyStateEvent> }>;\n};\n\n/**\n * Delivers sticky events (MSC4354) over sliding sync.\n * https://github.com/matrix-org/matrix-spec-proposals/pull/4480\n *\n * Sticky events expire after a duration instead of living in the timeline forever, and the server\n * re-sends the unexpired ones (e.g. on join) so late joiners still see them.\n *\n * The server sends them for every room matched by a list or subscription, even rooms currently\n * outside the list window. Sticky events already in a room's timeline are excluded here, so\n * `processRoomData` picks those up separately.\n */\nclass ExtensionStickyEvents implements Extension<ExtensionStickyEventsRequest, ExtensionStickyEventsResponse> {\n private nextBatch?: string;\n\n public constructor(private readonly client: MatrixClient) {}\n\n public name(): string {\n // Keeps MSC4354's number, as the extension was originally specified there.\n return \"org.matrix.msc4354.sticky_events\";\n }\n\n public when(): ExtensionState {\n // Sticky events are stored on a Room, so the room has to exist first.\n return ExtensionState.PostProcess;\n }\n\n public async onRequest(isInitial: boolean): Promise<ExtensionStickyEventsRequest> {\n return {\n enabled: true,\n limit: 100,\n // Undefined until the first response, which asks for all unexpired sticky events.\n since: this.nextBatch,\n };\n }\n\n public async onResponse(data: ExtensionStickyEventsResponse): Promise<void> {\n for (const [roomId, roomData] of Object.entries(data?.rooms ?? {})) {\n const room = this.client.getRoom(roomId);\n if (!room) {\n // Dropping is safe: unexpired sticky events are re-sent once we know the room.\n logger.debug(`Ignoring sticky events for unknown room ${roomId}`);\n continue;\n }\n room._unstable_addStickyEvents(mapEvents(this.client, roomId, roomData.events ?? []));\n }\n\n // next_batch is only returned when there were changes, and must be echoed back as `since`.\n if (data?.next_batch) {\n this.nextBatch = data.next_batch;\n }\n }\n}\n\n/**\n * A copy of SyncApi such that it can be used as a drop-in replacement for sync v2. For the actual\n * sliding sync API, see sliding-sync.ts or the class SlidingSync.\n */\nexport class SlidingSyncSdk {\n private readonly opts: IStoredClientOpts;\n private readonly syncOpts: SyncApiOptions;\n private syncState: SyncState | null = null;\n private syncStateData?: ISyncStateData;\n private lastPos: string | null = null;\n private failCount = 0;\n private notifEvents: MatrixEvent[] = []; // accumulator of sync events in the current sync response\n\n public constructor(\n private readonly slidingSync: SlidingSync,\n private readonly client: MatrixClient,\n opts: IStoredClientOpts | undefined,\n syncOpts: SyncApiOptions,\n ) {\n this.opts = defaultClientOpts(opts);\n this.syncOpts = defaultSyncApiOpts(syncOpts);\n\n if (client.getNotifTimelineSet()) {\n client.reEmitter.reEmit(client.getNotifTimelineSet()!, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n }\n\n this.slidingSync.on(SlidingSyncEvent.Lifecycle, this.onLifecycle.bind(this));\n this.slidingSync.on(SlidingSyncEvent.RoomData, this.onRoomData.bind(this));\n const extensions: Extension<any, any>[] = [\n new ExtensionToDevice(this.client, this.syncOpts.cryptoCallbacks),\n new ExtensionAccountData(this.client),\n new ExtensionTyping(this.client),\n new ExtensionReceipts(this.client),\n new ExtensionStickyEvents(this.client),\n ];\n if (this.syncOpts.cryptoCallbacks) {\n extensions.push(new ExtensionE2EE(this.syncOpts.cryptoCallbacks));\n }\n extensions.forEach((ext) => {\n this.slidingSync.registerExtension(ext);\n });\n }\n\n private async onRoomData(roomId: string, roomData: MSC3575RoomData): Promise<void> {\n let room = this.client.store.getRoom(roomId);\n if (!room) {\n if (!roomData.initial) {\n this.syncOpts.logger.debug(\n \"initial flag not set but no stored room exists for room \",\n roomId,\n roomData,\n );\n return;\n }\n room = _createAndReEmitRoom(this.client, roomId, this.opts);\n }\n await this.processRoomData(this.client, room, roomData);\n }\n\n private onLifecycle(state: SlidingSyncState, resp: MSC3575SlidingSyncResponse | null, err?: Error): void {\n if (err) {\n this.syncOpts.logger.debug(\"onLifecycle\", state, err);\n }\n switch (state) {\n case SlidingSyncState.Complete:\n this.purgeNotifications();\n if (!resp) {\n break;\n }\n // Element won't stop showing the initial loading spinner unless we fire SyncState.Prepared\n if (!this.lastPos) {\n this.updateSyncState(SyncState.Prepared, {\n oldSyncToken: undefined,\n nextSyncToken: resp.pos,\n catchingUp: false,\n fromCache: false,\n });\n }\n // Conversely, Element won't show the room list unless there is at least 1x SyncState.Syncing\n // so hence for the very first sync we will fire prepared then immediately syncing.\n this.updateSyncState(SyncState.Syncing, {\n oldSyncToken: this.lastPos!,\n nextSyncToken: resp.pos,\n catchingUp: false,\n fromCache: false,\n });\n this.lastPos = resp.pos;\n break;\n case SlidingSyncState.RequestFinished:\n if (err) {\n this.failCount += 1;\n this.updateSyncState(\n this.failCount > FAILED_SYNC_ERROR_THRESHOLD ? SyncState.Error : SyncState.Reconnecting,\n {\n error: new MatrixError(err),\n },\n );\n if (this.shouldAbortSync(new MatrixError(err))) {\n return; // shouldAbortSync actually stops syncing too so we don't need to do anything.\n }\n } else {\n this.failCount = 0;\n this.syncOpts.logger.debug(\n `SlidingSyncState.RequestFinished with ${Object.keys(resp?.rooms || []).length} rooms`,\n );\n }\n break;\n }\n }\n\n /**\n * Sync rooms the user has left.\n * @returns Resolved when they've been added to the store.\n */\n public async syncLeftRooms(): Promise<Room[]> {\n return []; // TODO\n }\n\n /**\n * Peek into a room. This will result in the room in question being synced so it\n * is accessible via getRooms(). Live updates for the room will be provided.\n * @param roomId - The room ID to peek into.\n * @returns A promise which resolves once the room has been added to the\n * store.\n */\n public async peek(roomId: string): Promise<Room> {\n return null!; // TODO\n }\n\n /**\n * Stop polling for updates in the peeked room. NOPs if there is no room being\n * peeked.\n */\n public stopPeeking(): void {\n // TODO\n }\n\n /**\n * Specify the set_presence value to be used for subsequent calls to the Sync API.\n * @param presence - the presence to specify to set_presence of sync calls\n */\n public setPresence(presence?: SetPresence): void {\n // TODO not possible in sliding sync yet\n }\n\n /**\n * Returns the current state of this sync object\n * @see MatrixClient#event:\"sync\"\n */\n public getSyncState(): SyncState | null {\n return this.syncState;\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n */\n public getSyncStateData(): ISyncStateData | null {\n return this.syncStateData ?? null;\n }\n\n // Helper functions which set up JS SDK structs are below and are identical to the sync v2 counterparts\n\n public createRoom(roomId: string): Room {\n // XXX cargoculted from sync.ts\n const { timelineSupport } = this.client;\n const room = new Room(roomId, this.client, this.client.getUserId()!, {\n lazyLoadMembers: this.opts.lazyLoadMembers,\n pendingEventOrdering: this.opts.pendingEventOrdering,\n timelineSupport,\n });\n this.client.reEmitter.reEmit(room, [\n RoomEvent.Name,\n RoomEvent.Redaction,\n RoomEvent.RedactionCancelled,\n RoomEvent.Receipt,\n RoomEvent.Tags,\n RoomEvent.LocalEchoUpdated,\n RoomEvent.AccountData,\n RoomEvent.MyMembership,\n RoomEvent.Timeline,\n RoomEvent.TimelineReset,\n ]);\n this.registerStateListeners(room);\n return room;\n }\n\n private registerStateListeners(room: Room): void {\n // XXX cargoculted from sync.ts\n // we need to also re-emit room state and room member events, so hook it up\n // to the client now. We need to add a listener for RoomState.members in\n // order to hook them correctly.\n this.client.reEmitter.reEmit(room.currentState, [\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n ]);\n room.currentState.on(RoomStateEvent.NewMember, (event, state, member) => {\n member.user = this.client.getUser(member.userId) ?? undefined;\n this.client.reEmitter.reEmit(member, [\n RoomMemberEvent.Name,\n RoomMemberEvent.Typing,\n RoomMemberEvent.PowerLevel,\n RoomMemberEvent.Membership,\n ]);\n });\n }\n\n /*\n private deregisterStateListeners(room: Room): void { // XXX cargoculted from sync.ts\n // could do with a better way of achieving this.\n room.currentState.removeAllListeners(RoomStateEvent.Events);\n room.currentState.removeAllListeners(RoomStateEvent.Members);\n room.currentState.removeAllListeners(RoomStateEvent.NewMember);\n } */\n\n private shouldAbortSync(error: MatrixError): boolean {\n if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n // The logout already happened, we just need to stop.\n this.syncOpts.logger.warn(\"Token no longer valid - assuming logout\");\n this.stop();\n this.updateSyncState(SyncState.Error, { error });\n return true;\n }\n return false;\n }\n\n private async processRoomData(client: MatrixClient, room: Room, roomData: MSC3575RoomData): Promise<void> {\n roomData = ensureNameEvent(client, room.roomId, roomData);\n const stateEvents = mapEvents(this.client, room.roomId, roomData.required_state);\n // Prevent events from being decrypted ahead of time\n // this helps large account to speed up faster\n // room::decryptCriticalEvent is in charge of decrypting all the events\n // required for a client to function properly\n let timelineEvents = mapEvents(this.client, room.roomId, roomData.timeline, false);\n const ephemeralEvents: MatrixEvent[] = []; // TODO this.mapSyncEventsFormat(joinObj.ephemeral);\n\n // TODO: handle threaded / beacon events\n\n if (roomData.limited || roomData.initial) {\n // we should not know about any of these timeline entries if this is a genuinely new room.\n // If we do, then we've effectively done scrollback (e.g requesting timeline_limit: 1 for\n // this room, then timeline_limit: 50).\n const knownEvents = new Set<string>();\n room.getLiveTimeline()\n .getEvents()\n .forEach((e) => {\n knownEvents.add(e.getId()!);\n });\n // all unknown events BEFORE a known event must be scrollback e.g:\n // D E <-- what we know\n // A B C D E F <-- what we just received\n // means:\n // A B C <-- scrollback\n // D E <-- dupes\n // F <-- new event\n // We bucket events based on if we have seen a known event yet.\n const oldEvents: MatrixEvent[] = [];\n const newEvents: MatrixEvent[] = [];\n let seenKnownEvent = false;\n for (let i = timelineEvents.length - 1; i >= 0; i--) {\n const recvEvent = timelineEvents[i];\n if (knownEvents.has(recvEvent.getId()!)) {\n seenKnownEvent = true;\n continue; // don't include this event, it's a dupe\n }\n if (seenKnownEvent) {\n // old -> new\n oldEvents.push(recvEvent);\n } else {\n // old -> new\n newEvents.unshift(recvEvent);\n }\n }\n timelineEvents = newEvents;\n if (oldEvents.length > 0) {\n // old events are scrollback, insert them now\n room.addEventsToTimeline(oldEvents, true, false, room.getLiveTimeline(), roomData.prev_batch);\n }\n }\n\n const encrypted = room.hasEncryptionStateEvent();\n // we do this first so it's correct when any of the events fire\n if (roomData.notification_count != null) {\n room.setUnreadNotificationCount(NotificationCountType.Total, roomData.notification_count);\n }\n\n if (roomData.highlight_count != null) {\n // We track unread notifications ourselves in encrypted rooms, so don't\n // bother setting it here. We trust our calculations better than the\n // server's for this case, and therefore will assume that our non-zero\n // count is accurate.\n if (!encrypted || (encrypted && room.getUnreadNotificationCount(NotificationCountType.Highlight) <= 0)) {\n room.setUnreadNotificationCount(NotificationCountType.Highlight, roomData.highlight_count);\n }\n }\n if (roomData.bump_stamp) {\n room.setBumpStamp(roomData.bump_stamp);\n }\n\n if (Number.isInteger(roomData.invited_count)) {\n room.currentState.setInvitedMemberCount(roomData.invited_count!);\n }\n if (Number.isInteger(roomData.joined_count)) {\n room.currentState.setJoinedMemberCount(roomData.joined_count!);\n }\n\n if (roomData.invite_state) {\n const inviteStateEvents = mapEvents(this.client, room.roomId, roomData.invite_state);\n await this.injectRoomEvents(room, inviteStateEvents);\n if (roomData.initial) {\n room.recalculate();\n this.client.store.storeRoom(room);\n this.client.emit(ClientEvent.Room, room);\n }\n inviteStateEvents.forEach((e) => {\n this.client.emit(ClientEvent.Event, e);\n });\n return;\n }\n\n if (roomData.limited) {\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n room.getLiveTimeline().setPaginationToken(roomData.prev_batch ?? null, EventTimeline.BACKWARDS);\n }\n\n /* TODO\n else if (roomData.limited) {\n\n let limited = true;\n\n // we've got a limited sync, so we *probably* have a gap in the\n // timeline, so should reset. But we might have been peeking or\n // paginating and already have some of the events, in which\n // case we just want to append any subsequent events to the end\n // of the existing timeline.\n //\n // This is particularly important in the case that we already have\n // *all* of the events in the timeline - in that case, if we reset\n // the timeline, we'll end up with an entirely empty timeline,\n // which we'll try to paginate but not get any new events (which\n // will stop us linking the empty timeline into the chain).\n //\n for (let i = timelineEvents.length - 1; i >= 0; i--) {\n const eventId = timelineEvents[i].getId();\n if (room.getTimelineForEvent(eventId)) {\n this.syncOpts.logger.debug(\"Already have event \" + eventId + \" in limited \" +\n \"sync - not resetting\");\n limited = false;\n\n // we might still be missing some of the events before i;\n // we don't want to be adding them to the end of the\n // timeline because that would put them out of order.\n timelineEvents.splice(0, i);\n\n // XXX: there's a problem here if the skipped part of the\n // timeline modifies the state set in stateEvents, because\n // we'll end up using the state from stateEvents rather\n // than the later state from timelineEvents. We probably\n // need to wind stateEvents forward over the events we're\n // skipping.\n break;\n }\n }\n\n if (limited) {\n room.resetLiveTimeline(\n roomData.prev_batch,\n null, // TODO this.syncOpts.canResetEntireTimeline(room.roomId) ? null : syncEventData.oldSyncToken,\n );\n\n // We have to assume any gap in any timeline is\n // reason to stop incrementally tracking notifications and\n // reset the timeline.\n this.client.resetNotifTimelineSet();\n this.registerStateListeners(room);\n }\n } */\n\n await this.injectRoomEvents(room, stateEvents, timelineEvents, roomData.num_live);\n\n // we deliberately don't add ephemeral events to the timeline\n room.addEphemeralEvents(ephemeralEvents);\n\n // local fields must be set before any async calls because call site assumes\n // synchronous execution prior to emitting SlidingSyncState.Complete\n room.updateMyMembership(KnownMembership.Join);\n\n room.setMSC4186SummaryData(roomData.heroes, roomData.joined_count, roomData.invited_count);\n\n // The MSC4480 extension excludes sticky events already present in the timeline, so we have\n // to pick those up here. See ExtensionStickyEvents for the rest.\n room._unstable_addStickyEvents(timelineEvents.filter((e) => e.unstableStickyInfo !== undefined));\n\n room.recalculate();\n if (roomData.initial) {\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n }\n\n // check if any timeline events should bing and add them to the notifEvents array:\n // we'll purge this once we've fully processed the sync response\n this.addNotifications(timelineEvents);\n\n const processRoomEvent = async (e: MatrixEvent): Promise<void> => {\n client.emit(ClientEvent.Event, e);\n if (e.isState() && e.getType() == EventType.RoomEncryption && this.syncOpts.cryptoCallbacks) {\n await this.syncOpts.cryptoCallbacks.onCryptoEvent(room, e);\n }\n };\n\n await promiseMapSeries(stateEvents, processRoomEvent);\n await promiseMapSeries(timelineEvents, processRoomEvent);\n ephemeralEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n\n // Decrypt only the last message in all rooms to make sure we can generate a preview\n // And decrypt all events after the recorded read receipt to ensure an accurate\n // notification count\n room.decryptCriticalEvents();\n }\n\n /**\n * Injects events into a room's model.\n * @param stateEventList - A list of state events. This is the state\n * at the *END* of the timeline list if it is supplied.\n * @param timelineEventList - A list of timeline events. Lower index\n * is earlier in time. Higher index is later.\n * @param numLive - the number of events in timelineEventList which just happened,\n * supplied from the server.\n */\n public async injectRoomEvents(\n room: Room,\n stateEventList: MatrixEvent[],\n timelineEventList: MatrixEvent[] = [],\n numLive: number = 0,\n ): Promise<void> {\n // If there are no events in the timeline yet, initialise it with\n // the given state events\n const liveTimeline = room.getLiveTimeline();\n const timelineWasEmpty = liveTimeline.getEvents().length == 0;\n if (timelineWasEmpty) {\n // Passing these events into initialiseState will freeze them, so we need\n // to compute and cache the push actions for them now, otherwise sync dies\n // with an attempt to assign to read only property.\n // XXX: This is pretty horrible and is assuming all sorts of behaviour from\n // these functions that it shouldn't be. We should probably either store the\n // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise\n // find some solution where MatrixEvents are immutable but allow for a cache\n // field.\n for (const ev of stateEventList) {\n this.client.getPushActionsForEvent(ev);\n }\n liveTimeline.initialiseState(stateEventList);\n }\n\n // If the timeline wasn't empty, we process the state events here: they're\n // defined as updates to the state before the start of the timeline, so this\n // starts to roll the state forward.\n // XXX: That's what we *should* do, but this can happen if we were previously\n // peeking in a room, in which case we obviously do *not* want to add the\n // state events here onto the end of the timeline. Historically, the js-sdk\n // has just set these new state events on the old and new state. This seems\n // very wrong because there could be events in the timeline that diverge the\n // state, in which case this is going to leave things out of sync. However,\n // for now I think it;s best to behave the same as the code has done previously.\n if (!timelineWasEmpty) {\n // XXX: As above, don't do this...\n //room.addLiveEvents(stateEventList || []);\n // Do this instead...\n room.oldState.setStateEvents(stateEventList);\n room.currentState.setStateEvents(stateEventList);\n }\n\n // the timeline is broken into 'live' events which just happened and normal timeline events\n // which are still to be appended to the end of the live timeline but happened a while ago.\n // The live events are marked as fromCache=false to ensure that downstream components know\n // this is a live event, not historical (from a remote server cache).\n\n let liveTimelineEvents: MatrixEvent[] = [];\n if (numLive > 0) {\n // last numLive events are live\n liveTimelineEvents = timelineEventList.slice(-1 * numLive);\n // everything else is not live\n timelineEventList = timelineEventList.slice(0, -1 * liveTimelineEvents.length);\n }\n\n // Execute the timeline events.\n // This also needs to be done before running push rules on the events as they need\n // to be decorated with sender etc.\n await room.addLiveEvents(timelineEventList, {\n fromCache: true,\n addToState: false,\n });\n if (liveTimelineEvents.length > 0) {\n await room.addLiveEvents(liveTimelineEvents, {\n fromCache: false,\n addToState: false,\n });\n }\n\n room.recalculate();\n\n // resolve invites now we have set the latest state\n this.resolveInvites(room);\n }\n\n private resolveInvites(room: Room): void {\n if (!room || !this.opts.resolveInvitesToProfiles) {\n return;\n }\n const client = this.client;\n // For each invited room member we want to give them a displayname/avatar url\n // if they have one (the m.room.member invites don't contain this).\n room.getMembersWithMembership(KnownMembership.Invite).forEach(function (member) {\n if (member.requestedProfileInfo) return;\n member.requestedProfileInfo = true;\n // try to get a cached copy first.\n const user = client.getUser(member.userId);\n let promise: ReturnType<MatrixClient[\"getProfileInfo\"]>;\n if (user) {\n promise = Promise.resolve({\n avatar_url: user.avatarUrl,\n displayname: user.displayName,\n });\n } else {\n promise = client.getProfileInfo(member.userId);\n }\n promise.then(\n function (info) {\n // slightly naughty by doctoring the invite event but this means all\n // the code paths remain the same between invite/join display name stuff\n // which is a worthy trade-off for some minor pollution.\n const inviteEvent = member.events.member!;\n if (inviteEvent.getContent().membership !== KnownMembership.Invite) {\n // between resolving and now they have since joined, so don't clobber\n return;\n }\n inviteEvent.getContent().avatar_url = info.avatar_url;\n inviteEvent.getContent().displayname = info.displayname;\n // fire listeners\n member.setMembershipEvent(inviteEvent, room.currentState);\n },\n function (_err) {\n // OH WELL.\n },\n );\n });\n }\n\n public retryImmediately(): boolean {\n return true;\n }\n\n /**\n * Main entry point. Blocks until stop() is called.\n */\n public async sync(): Promise<void> {\n this.syncOpts.logger.debug(\"Sliding sync init loop\");\n\n // 1) We need to get push rules so we can check if events should bing as we get\n // them from /sync.\n while (!this.client.isGuest()) {\n try {\n this.syncOpts.logger.debug(\"Getting push rules...\");\n const result = await this.client.getPushRules();\n this.syncOpts.logger.debug(\"Got push rules\");\n this.client.pushRules = result;\n break;\n } catch (err) {\n this.syncOpts.logger.error(\"Getting push rules failed\", err);\n if (this.shouldAbortSync(<MatrixError>err)) {\n return;\n }\n }\n }\n\n // start syncing\n await this.slidingSync.start();\n }\n\n /**\n * Stops the sync object from syncing.\n */\n public stop(): void {\n this.syncOpts.logger.debug(\"SyncApi.stop\");\n this.slidingSync.stop();\n }\n\n /**\n * Sets the sync state and emits an event to say so\n * @param newState - The new state string\n * @param data - Object of additional data to emit in the event\n */\n private updateSyncState(newState: SyncState, data?: ISyncStateData): void {\n const old = this.syncState;\n this.syncState = newState;\n this.syncStateData = data;\n this.client.emit(ClientEvent.Sync, this.syncState, old, data);\n }\n\n /**\n * Takes a list of timelineEvents and adds and adds to notifEvents\n * as appropriate.\n * This must be called after the room the events belong to has been stored.\n *\n * @param timelineEventList - A list of timeline events. Lower index\n * is earlier in time. Higher index is later.\n */\n private addNotifications(timelineEventList: MatrixEvent[]): void {\n // gather our notifications into this.notifEvents\n if (!this.client.getNotifTimelineSet()) {\n return;\n }\n for (const timelineEvent of timelineEventList) {\n const pushActions = this.client.getPushActionsForEvent(timelineEvent);\n if (pushActions && pushActions.notify && pushActions.tweaks && pushActions.tweaks.highlight) {\n this.notifEvents.push(timelineEvent);\n }\n }\n }\n\n /**\n * Purge any events in the notifEvents array. Used after a /sync has been complete.\n * This should not be called at a per-room scope (e.g in onRoomData) because otherwise the ordering\n * will be messed up e.g room A gets a bing, room B gets a newer bing, but both in the same /sync\n * response. If we purge at a per-room scope then we could process room B before room A leading to\n * room B appearing earlier in the notifications timeline, even though it has the higher origin_server_ts.\n */\n private purgeNotifications(): void {\n this.notifEvents.sort(function (a, b) {\n return a.getTs() - b.getTs();\n });\n this.notifEvents.forEach((event) => {\n this.client.getNotifTimelineSet()?.addLiveEvent(event, { addToState: false });\n });\n this.notifEvents = [];\n }\n}\n\nfunction ensureNameEvent(client: MatrixClient, roomId: string, roomData: MSC3575RoomData): MSC3575RoomData {\n // make sure m.room.name is in required_state if there is a name, replacing anything previously\n // there if need be. This ensures clients transparently 'calculate' the right room name. Native\n // sliding sync clients should just read the \"name\" field.\n if (!roomData.name) {\n return roomData;\n }\n for (const stateEvent of roomData.required_state) {\n if (stateEvent.type === EventType.RoomName && stateEvent.state_key === \"\") {\n stateEvent.content = {\n name: roomData.name,\n };\n return roomData;\n }\n }\n roomData.required_state.push({\n event_id: \"$fake-sliding-sync-name-event-\" + roomId,\n state_key: \"\",\n type: EventType.RoomName,\n content: {\n name: roomData.name,\n },\n sender: client.getUserId()!,\n origin_server_ts: new Date().getTime(),\n });\n return roomData;\n}\n\ntype TaggedEvent = (IStrippedState | IRoomEvent | IStateEvent | IMinimalEvent) & { room_id?: string };\n\n// Helper functions which set up JS SDK structs are below and are identical to the sync v2 counterparts,\n// just outside the class.\nfunction mapEvents(client: MatrixClient, roomId: string | undefined, events: object[], decrypt = true): MatrixEvent[] {\n const mapper = client.getEventMapper({ decrypt });\n return (events as TaggedEvent[]).map(function (e) {\n e.room_id = roomId;\n return mapper(e);\n });\n}\n\nfunction processEphemeralEvents(client: MatrixClient, roomId: string, ephEvents: IMinimalEvent[]): void {\n const ephemeralEvents = mapEvents(client, roomId, ephEvents);\n const room = client.getRoom(roomId);\n if (!room) {\n logger.warn(\"got ephemeral events for room but room doesn't exist on client:\", roomId);\n return;\n }\n room.addEphemeralEvents(ephemeralEvents);\n ephemeralEvents.forEach((e) => {\n client.emit(ClientEvent.Event, e);\n });\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;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C;IACnB,CAAC;IACD,MAAM,EAAE,MAAM,CAAC,SAAS,CAAC,CAAE;IAC3B,gBAAgB,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC;EACzC,CAAC,CAAC;EACF,OAAO,QAAQ;AACnB;AAIA;AACA;AACA,SAAS,SAAS,CAAC,MAAoB,EAAE,MAA0B,EAAE,MAAgB,EAAE,OAAO,GAAG,IAAI,EAAiB;EAClH,MAAM,MAAM,GAAG,MAAM,CAAC,cAAc,CAAC;IAAE;EAAQ,CAAC,CAAC;EACjD,OAAQ,MAAM,CAAmB,GAAG,CAAC,UAAU,CAAC,EAAE;IAC9C,CAAC,CAAC,OAAO,GAAG,MAAM;IAClB,OAAO,MAAM,CAAC,CAAC,CAAC;EACpB,CAAC,CAAC;AACN;AAEA,SAAS,sBAAsB,CAAC,MAAoB,EAAE,MAAc,EAAE,SAA0B,EAAQ;EACpG,MAAM,eAAe,GAAG,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC;EAC5D,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;EACnC,IAAI,CAAC,IAAI,EAAE;IACP,MAAM,CAAC,IAAI,CAAC,iEAAiE,EAAE,MAAM,CAAC;IACtF;EACJ;EACA,IAAI,CAAC,kBAAkB,CAAC,eAAe,CAAC;EACxC,eAAe,CAAC,OAAO,CAAE,CAAC,IAAK;IAC3B,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC;EACrC,CAAC,CAAC;AACN","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "matrix-js-sdk",
3
- "version": "42.2.0",
3
+ "version": "42.3.0",
4
4
  "description": "Matrix Client-Server SDK for Javascript",
5
5
  "engines": {
6
6
  "node": ">=22.0.0"
@@ -79,7 +79,7 @@
79
79
  "knip": "^6.0.0",
80
80
  "lint-staged": "^17.0.0",
81
81
  "matrix-mock-request": "^2.5.0",
82
- "oxfmt": "^0.61.0",
82
+ "oxfmt": "^0.63.0",
83
83
  "oxlint": "^1.70.0",
84
84
  "oxlint-tsgolint": "^7.0.0",
85
85
  "typedoc": "^0.28.1",