matrix-js-sdk 37.2.0 → 37.3.0-rc.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 (83) hide show
  1. package/git-revision.txt +1 -1
  2. package/lib/client.d.ts +8 -2
  3. package/lib/client.d.ts.map +1 -1
  4. package/lib/client.js +11 -3
  5. package/lib/client.js.map +1 -1
  6. package/lib/common-crypto/CryptoBackend.d.ts +8 -0
  7. package/lib/common-crypto/CryptoBackend.d.ts.map +1 -1
  8. package/lib/common-crypto/CryptoBackend.js.map +1 -1
  9. package/lib/http-api/errors.d.ts +8 -0
  10. package/lib/http-api/errors.d.ts.map +1 -1
  11. package/lib/http-api/errors.js +14 -0
  12. package/lib/http-api/errors.js.map +1 -1
  13. package/lib/http-api/fetch.d.ts.map +1 -1
  14. package/lib/http-api/fetch.js +3 -3
  15. package/lib/http-api/fetch.js.map +1 -1
  16. package/lib/matrixrtc/LegacyMembershipManager.d.ts +9 -1
  17. package/lib/matrixrtc/LegacyMembershipManager.d.ts.map +1 -1
  18. package/lib/matrixrtc/LegacyMembershipManager.js +20 -0
  19. package/lib/matrixrtc/LegacyMembershipManager.js.map +1 -1
  20. package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
  21. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  22. package/lib/matrixrtc/NewMembershipManager.d.ts +7 -58
  23. package/lib/matrixrtc/NewMembershipManager.d.ts.map +1 -1
  24. package/lib/matrixrtc/NewMembershipManager.js +130 -137
  25. package/lib/matrixrtc/NewMembershipManager.js.map +1 -1
  26. package/lib/matrixrtc/NewMembershipManagerActionScheduler.js +3 -3
  27. package/lib/matrixrtc/NewMembershipManagerActionScheduler.js.map +1 -1
  28. package/lib/matrixrtc/index.d.ts +1 -0
  29. package/lib/matrixrtc/index.d.ts.map +1 -1
  30. package/lib/matrixrtc/index.js +1 -0
  31. package/lib/matrixrtc/index.js.map +1 -1
  32. package/lib/matrixrtc/types.d.ts +77 -1
  33. package/lib/matrixrtc/types.d.ts.map +1 -1
  34. package/lib/matrixrtc/types.js +40 -1
  35. package/lib/matrixrtc/types.js.map +1 -1
  36. package/lib/models/room-summary.d.ts +30 -0
  37. package/lib/models/room-summary.d.ts.map +1 -1
  38. package/lib/models/room-summary.js +11 -0
  39. package/lib/models/room-summary.js.map +1 -1
  40. package/lib/models/room.d.ts +37 -1
  41. package/lib/models/room.d.ts.map +1 -1
  42. package/lib/models/room.js +133 -28
  43. package/lib/models/room.js.map +1 -1
  44. package/lib/oidc/tokenRefresher.d.ts.map +1 -1
  45. package/lib/oidc/tokenRefresher.js +8 -1
  46. package/lib/oidc/tokenRefresher.js.map +1 -1
  47. package/lib/pushprocessor.d.ts +10 -1
  48. package/lib/pushprocessor.d.ts.map +1 -1
  49. package/lib/pushprocessor.js +24 -9
  50. package/lib/pushprocessor.js.map +1 -1
  51. package/lib/rust-crypto/OutgoingRequestProcessor.d.ts.map +1 -1
  52. package/lib/rust-crypto/OutgoingRequestProcessor.js +6 -1
  53. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
  54. package/lib/rust-crypto/rust-crypto.d.ts +4 -1
  55. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
  56. package/lib/rust-crypto/rust-crypto.js +55 -46
  57. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  58. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  59. package/lib/sliding-sync-sdk.js +86 -75
  60. package/lib/sliding-sync-sdk.js.map +1 -1
  61. package/lib/sliding-sync.d.ts +23 -60
  62. package/lib/sliding-sync.d.ts.map +1 -1
  63. package/lib/sliding-sync.js +62 -321
  64. package/lib/sliding-sync.js.map +1 -1
  65. package/package.json +6 -6
  66. package/src/client.ts +12 -5
  67. package/src/common-crypto/CryptoBackend.ts +9 -0
  68. package/src/http-api/errors.ts +14 -0
  69. package/src/http-api/fetch.ts +3 -4
  70. package/src/matrixrtc/LegacyMembershipManager.ts +27 -1
  71. package/src/matrixrtc/MatrixRTCSession.ts +2 -1
  72. package/src/matrixrtc/NewMembershipManager.ts +120 -165
  73. package/src/matrixrtc/NewMembershipManagerActionScheduler.ts +3 -3
  74. package/src/matrixrtc/index.ts +1 -0
  75. package/src/matrixrtc/types.ts +84 -1
  76. package/src/models/room-summary.ts +31 -0
  77. package/src/models/room.ts +133 -23
  78. package/src/oidc/tokenRefresher.ts +8 -2
  79. package/src/pushprocessor.ts +25 -16
  80. package/src/rust-crypto/OutgoingRequestProcessor.ts +6 -0
  81. package/src/rust-crypto/rust-crypto.ts +7 -1
  82. package/src/sliding-sync-sdk.ts +28 -28
  83. package/src/sliding-sync.ts +38 -329
@@ -1 +1 @@
1
- {"version":3,"file":"tokenRefresher.d.ts","sourceRoot":"","sources":["../../src/oidc/tokenRefresher.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,aAAa,EAAoC,MAAM,gBAAgB,CAAC;AAEtF,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAKzD;;;;;;GAMG;AACH,qBAAa,kBAAkB;IA4BvB;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAC,aAAa;IA/BlC;;;;;OAKG;IACH,SAAgB,eAAe,EAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,OAAO,CAAC,UAAU,CAAc;IAChC,OAAO,CAAC,sBAAsB,CAAC,CAAwB;;IAGnD;;OAEG;IACH,MAAM,EAAE,MAAM;IACd;;OAEG;IACH,QAAQ,EAAE,MAAM;IAChB;;OAEG;IACH,WAAW,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,EAAE,MAAM;IAChB;;;OAGG;IACc,aAAa,EAAE,aAAa;YAKnC,oBAAoB;IA0BlC;;;;;OAKG;IACU,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAY9E;;;;;;;OAOG;IACU,aAAa,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;YAInF,YAAY;CA0B7B"}
1
+ {"version":3,"file":"tokenRefresher.d.ts","sourceRoot":"","sources":["../../src/oidc/tokenRefresher.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,aAAa,EAAmD,MAAM,gBAAgB,CAAC;AAErG,OAAO,EAAE,KAAK,YAAY,EAA2B,MAAM,sBAAsB,CAAC;AAKlF;;;;;;GAMG;AACH,qBAAa,kBAAkB;IA4BvB;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAC,aAAa;IA/BlC;;;;;OAKG;IACH,SAAgB,eAAe,EAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,OAAO,CAAC,UAAU,CAAc;IAChC,OAAO,CAAC,sBAAsB,CAAC,CAAwB;;IAGnD;;OAEG;IACH,MAAM,EAAE,MAAM;IACd;;OAEG;IACH,QAAQ,EAAE,MAAM;IAChB;;OAEG;IACH,WAAW,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,EAAE,MAAM;IAChB;;;OAGG;IACc,aAAa,EAAE,aAAa;YAKnC,oBAAoB;IA0BlC;;;;;OAKG;IACU,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAkB9E;;;;;;;OAOG;IACU,aAAa,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;YAInF,YAAY;CA0B7B"}
@@ -16,7 +16,8 @@ See the License for the specific language governing permissions and
16
16
  limitations under the License.
17
17
  */
18
18
 
19
- import { OidcClient, WebStorageStateStore } from "oidc-client-ts";
19
+ import { OidcClient, WebStorageStateStore, ErrorResponse } from "oidc-client-ts";
20
+ import { TokenRefreshLogoutError } from "../http-api/index.js";
20
21
  import { generateScope } from "./authorize.js";
21
22
  import { discoverAndValidateOIDCIssuerWellKnown } from "./discovery.js";
22
23
  import { logger } from "../logger.js";
@@ -104,6 +105,12 @@ export class OidcTokenRefresher {
104
105
  try {
105
106
  var tokens = yield _this2.inflightRefreshRequest;
106
107
  return tokens;
108
+ } catch (e) {
109
+ // If we encounter an OIDC error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError
110
+ if (e instanceof ErrorResponse) {
111
+ throw new TokenRefreshLogoutError(e);
112
+ }
113
+ throw e;
107
114
  } finally {
108
115
  _this2.inflightRefreshRequest = undefined;
109
116
  }
@@ -1 +1 @@
1
- {"version":3,"file":"tokenRefresher.js","names":["OidcClient","WebStorageStateStore","generateScope","discoverAndValidateOIDCIssuerWellKnown","logger","OidcTokenRefresher","constructor","issuer","clientId","redirectUri","deviceId","idTokenClaims","_defineProperty","oidcClientReady","initialiseOidcClient","_this","_asyncToGenerator","_config$signingKeys","config","scope","oidcClient","metadata","signingKeys","undefined","client_id","redirect_uri","authority","stateStore","prefix","store","window","sessionStorage","error","Error","doRefreshAccessToken","refreshToken","_this2","inflightRefreshRequest","getNewTokens","tokens","persistTokens","_this3","refreshTokenState","refresh_token","session_state","data","profile","response","useRefreshToken","state","timeoutInSeconds","accessToken","access_token"],"sources":["../../src/oidc/tokenRefresher.ts"],"sourcesContent":["/*\nCopyright 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\nimport { type IdTokenClaims, OidcClient, WebStorageStateStore } from \"oidc-client-ts\";\n\nimport { type AccessTokens } from \"../http-api/index.ts\";\nimport { generateScope } from \"./authorize.ts\";\nimport { discoverAndValidateOIDCIssuerWellKnown } from \"./discovery.ts\";\nimport { logger } from \"../logger.ts\";\n\n/**\n * @experimental\n * Class responsible for refreshing OIDC access tokens\n *\n * Client implementations will likely want to override {@link persistTokens} to persist tokens after successful refresh\n *\n */\nexport class OidcTokenRefresher {\n /**\n * Promise which will complete once the OidcClient has been initialised\n * and is ready to start refreshing tokens.\n *\n * Will reject if the client initialisation fails.\n */\n public readonly oidcClientReady!: Promise<void>;\n private oidcClient!: OidcClient;\n private inflightRefreshRequest?: Promise<AccessTokens>;\n\n public constructor(\n /**\n * The OIDC issuer as returned by the /auth_issuer API\n */\n issuer: string,\n /**\n * id of this client as registered with the OP\n */\n clientId: string,\n /**\n * redirectUri as registered with OP\n */\n redirectUri: string,\n /**\n * Device ID of current session\n */\n deviceId: string,\n /**\n * idTokenClaims as returned from authorization grant\n * used to validate tokens\n */\n private readonly idTokenClaims: IdTokenClaims,\n ) {\n this.oidcClientReady = this.initialiseOidcClient(issuer, clientId, deviceId, redirectUri);\n }\n\n private async initialiseOidcClient(\n issuer: string,\n clientId: string,\n deviceId: string,\n redirectUri: string,\n ): Promise<void> {\n try {\n const config = await discoverAndValidateOIDCIssuerWellKnown(issuer);\n\n const scope = generateScope(deviceId);\n\n this.oidcClient = new OidcClient({\n metadata: config,\n signingKeys: config.signingKeys ?? undefined,\n client_id: clientId,\n scope,\n redirect_uri: redirectUri,\n authority: config.issuer,\n stateStore: new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage }),\n });\n } catch (error) {\n logger.error(\"Failed to initialise OIDC client.\", error);\n throw new Error(\"Failed to initialise OIDC client.\");\n }\n }\n\n /**\n * Attempt token refresh using given refresh token\n * @param refreshToken - refresh token to use in request with token issuer\n * @returns tokens - Promise that resolves with new access and refresh tokens\n * @throws when token refresh fails\n */\n public async doRefreshAccessToken(refreshToken: string): Promise<AccessTokens> {\n if (!this.inflightRefreshRequest) {\n this.inflightRefreshRequest = this.getNewTokens(refreshToken);\n }\n try {\n const tokens = await this.inflightRefreshRequest;\n return tokens;\n } finally {\n this.inflightRefreshRequest = undefined;\n }\n }\n\n /**\n * Persist the new tokens, called after tokens are successfully refreshed.\n *\n * This function is intended to be overriden by the consumer when persistence is necessary.\n *\n * @param tokens.accessToken - new access token\n * @param tokens.refreshToken - OPTIONAL new refresh token\n */\n public async persistTokens(tokens: { accessToken: string; refreshToken?: string }): Promise<void> {\n // NOOP\n }\n\n private async getNewTokens(refreshToken: string): Promise<AccessTokens> {\n if (!this.oidcClient) {\n throw new Error(\"Cannot get new token before OIDC client is initialised.\");\n }\n\n const refreshTokenState = {\n refresh_token: refreshToken,\n session_state: \"test\",\n data: undefined,\n profile: this.idTokenClaims,\n };\n\n const response = await this.oidcClient.useRefreshToken({\n state: refreshTokenState,\n timeoutInSeconds: 300,\n });\n\n const tokens = {\n accessToken: response.access_token,\n refreshToken: response.refresh_token,\n };\n\n await this.persistTokens(tokens);\n\n return tokens;\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAA6BA,UAAU,EAAEC,oBAAoB,QAAQ,gBAAgB;AAGrF,SAASC,aAAa,QAAQ,gBAAgB;AAC9C,SAASC,sCAAsC,QAAQ,gBAAgB;AACvE,SAASC,MAAM,QAAQ,cAAc;;AAErC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,kBAAkB,CAAC;EAWrBC,WAAWA;EACd;AACR;AACA;EACQC,MAAc;EACd;AACR;AACA;EACQC,QAAgB;EAChB;AACR;AACA;EACQC,WAAmB;EACnB;AACR;AACA;EACQC,QAAgB;EAChB;AACR;AACA;AACA;EACyBC,aAA4B,EAC/C;IAAA,KADmBA,aAA4B,GAA5BA,aAA4B;IA/BjD;AACJ;AACA;AACA;AACA;AACA;IALIC,eAAA;IAAAA,eAAA;IAAAA,eAAA;IAiCI,IAAI,CAACC,eAAe,GAAG,IAAI,CAACC,oBAAoB,CAACP,MAAM,EAAEC,Q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B,GAAGd,SAAS;MAC3C;IAAC;EACL;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;EACiBiB,aAAaA,CAACD,MAAsD,EAAiB;IAAA,OAAAvB,iBAAA;EAElG,CAAC,CADG;EAGUsB,YAAYA,CAACH,YAAoB,EAAyB;IAAA,IAAAM,MAAA;IAAA,OAAAzB,iBAAA;MACpE,IAAI,CAACyB,MAAI,CAACrB,UAAU,EAAE;QAClB,MAAM,IAAIa,KAAK,CAAC,yDAAyD,CAAC;MAC9E;MAEA,IAAMS,iBAAiB,GAAG;QACtBC,aAAa,EAAER,YAAY;QAC3BS,aAAa,EAAE,MAAM;QACrBC,IAAI,EAAEtB,SAAS;QACfuB,OAAO,EAAEL,MAAI,CAAC9B;MAClB,CAAC;MAED,IAAMoC,QAAQ,SAASN,MAAI,CAACrB,UAAU,CAAC4B,eAAe,CAAC;QACnDC,KAAK,EAAEP,iBAAiB;QACxBQ,gBAAgB,EAAE;MACtB,CAAC,CAAC;MAEF,IAAMX,MAAM,GAAG;QACXY,WAAW,EAAEJ,QAAQ,CAACK,YAAY;QAClCjB,YAAY,EAAEY,QAAQ,CAACJ;MAC3B,CAAC;MAED,MAAMF,MAAI,CAACD,aAAa,CAACD,MAAM,CAAC;MAEhC,OAAOA,MAAM;IAAC;EAClB;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"tokenRefresher.js","names":["OidcClient","WebStorageStateStore","ErrorResponse","TokenRefreshLogoutError","generateScope","discoverAndValidateOIDCIssuerWellKnown","logger","OidcTokenRefresher","constructor","issuer","clientId","redirectUri","deviceId","idTokenClaims","_defineProperty","oidcClientReady","initialiseOidcClient","_this","_asyncToGenerator","_config$signingKeys","config","scope","oidcClient","metadata","signingKeys","undefined","client_id","redirect_uri","authority","stateStore","prefix","store","window","sessionStorage","error","Error","doRefreshAccessToken","refreshToken","_this2","inflightRefreshRequest","getNewTokens","tokens","e","persistTokens","_this3","refreshTokenState","refresh_token","session_state","data","profile","response","useRefreshToken","state","timeoutInSeconds","accessToken","access_token"],"sources":["../../src/oidc/tokenRefresher.ts"],"sourcesContent":["/*\nCopyright 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\nimport { type IdTokenClaims, OidcClient, WebStorageStateStore, ErrorResponse } from \"oidc-client-ts\";\n\nimport { type AccessTokens, TokenRefreshLogoutError } from \"../http-api/index.ts\";\nimport { generateScope } from \"./authorize.ts\";\nimport { discoverAndValidateOIDCIssuerWellKnown } from \"./discovery.ts\";\nimport { logger } from \"../logger.ts\";\n\n/**\n * @experimental\n * Class responsible for refreshing OIDC access tokens\n *\n * Client implementations will likely want to override {@link persistTokens} to persist tokens after successful refresh\n *\n */\nexport class OidcTokenRefresher {\n /**\n * Promise which will complete once the OidcClient has been initialised\n * and is ready to start refreshing tokens.\n *\n * Will reject if the client initialisation fails.\n */\n public readonly oidcClientReady!: Promise<void>;\n private oidcClient!: OidcClient;\n private inflightRefreshRequest?: Promise<AccessTokens>;\n\n public constructor(\n /**\n * The OIDC issuer as returned by the /auth_issuer API\n */\n issuer: string,\n /**\n * id of this client as registered with the OP\n */\n clientId: string,\n /**\n * redirectUri as registered with OP\n */\n redirectUri: string,\n /**\n * Device ID of current session\n */\n deviceId: string,\n /**\n * idTokenClaims as returned from authorization grant\n * used to validate tokens\n */\n private readonly idTokenClaims: IdTokenClaims,\n ) {\n this.oidcClientReady = this.initialiseOidcClient(issuer, clientId, deviceId, redirectUri);\n }\n\n private async initialiseOidcClient(\n issuer: string,\n clientId: string,\n deviceId: string,\n redirectUri: string,\n ): Promise<void> {\n try {\n const config = await discoverAndValidateOIDCIssuerWellKnown(issuer);\n\n const scope = generateScope(deviceId);\n\n this.oidcClient = new OidcClient({\n metadata: config,\n signingKeys: config.signingKeys ?? undefined,\n client_id: clientId,\n scope,\n redirect_uri: redirectUri,\n authority: config.issuer,\n stateStore: new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage }),\n });\n } catch (error) {\n logger.error(\"Failed to initialise OIDC client.\", error);\n throw new Error(\"Failed to initialise OIDC client.\");\n }\n }\n\n /**\n * Attempt token refresh using given refresh token\n * @param refreshToken - refresh token to use in request with token issuer\n * @returns tokens - Promise that resolves with new access and refresh tokens\n * @throws when token refresh fails\n */\n public async doRefreshAccessToken(refreshToken: string): Promise<AccessTokens> {\n if (!this.inflightRefreshRequest) {\n this.inflightRefreshRequest = this.getNewTokens(refreshToken);\n }\n try {\n const tokens = await this.inflightRefreshRequest;\n return tokens;\n } catch (e) {\n // If we encounter an OIDC error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError\n if (e instanceof ErrorResponse) {\n throw new TokenRefreshLogoutError(e);\n }\n throw e;\n } finally {\n this.inflightRefreshRequest = undefined;\n }\n }\n\n /**\n * Persist the new tokens, called after tokens are successfully refreshed.\n *\n * This function is intended to be overriden by the consumer when persistence is necessary.\n *\n * @param tokens.accessToken - new access token\n * @param tokens.refreshToken - OPTIONAL new refresh token\n */\n public async persistTokens(tokens: { accessToken: string; refreshToken?: string }): Promise<void> {\n // NOOP\n }\n\n private async getNewTokens(refreshToken: string): Promise<AccessTokens> {\n if (!this.oidcClient) {\n throw new Error(\"Cannot get new token before OIDC client is initialised.\");\n }\n\n const refreshTokenState = {\n refresh_token: refreshToken,\n session_state: \"test\",\n data: undefined,\n profile: this.idTokenClaims,\n };\n\n const response = await this.oidcClient.useRefreshToken({\n state: refreshTokenState,\n timeoutInSeconds: 300,\n });\n\n const tokens = {\n accessToken: response.access_token,\n refreshToken: response.refresh_token,\n };\n\n await this.persistTokens(tokens);\n\n return tokens;\n }\n}\n"],"mappings":";;AAA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BU,aAAa,EAAE,MAAM;QACrBC,IAAI,EAAEvB,SAAS;QACfwB,OAAO,EAAEL,MAAI,CAAC/B;MAClB,CAAC;MAED,IAAMqC,QAAQ,SAASN,MAAI,CAACtB,UAAU,CAAC6B,eAAe,CAAC;QACnDC,KAAK,EAAEP,iBAAiB;QACxBQ,gBAAgB,EAAE;MACtB,CAAC,CAAC;MAEF,IAAMZ,MAAM,GAAG;QACXa,WAAW,EAAEJ,QAAQ,CAACK,YAAY;QAClClB,YAAY,EAAEa,QAAQ,CAACJ;MAC3B,CAAC;MAED,MAAMF,MAAI,CAACD,aAAa,CAACF,MAAM,CAAC;MAEhC,OAAOA,MAAM;IAAC;EAClB;AACJ","ignoreList":[]}
@@ -38,6 +38,16 @@ export declare class PushProcessor {
38
38
  * @returns The rewritten rules
39
39
  */
40
40
  static rewriteDefaultRules(incomingRules: IPushRules, userId?: string | undefined): IPushRules;
41
+ /**
42
+ * Create a RegExp object for the given glob pattern with a single capture group around the pattern itself, caching the result.
43
+ * No cache invalidation is present currently,
44
+ * as this will be inherently bounded to the size of the user's own push rules.
45
+ * @param pattern - the glob pattern to convert to a RegExp
46
+ * @param alignToWordBoundary - whether to align the pattern to word boundaries,
47
+ * as specified for `content.body` matches, will use lookaround assertions to ensure the match only includes the pattern
48
+ * @param flags - the flags to pass to the RegExp constructor, defaults to case-insensitive
49
+ */
50
+ static getPushRuleGlobRegex(pattern: string, alignToWordBoundary?: boolean, flags?: string): RegExp;
41
51
  /**
42
52
  * Pre-caches the parsed keys for push rules and cleans out any obsolete cache
43
53
  * entries. Should be called after push rules are updated.
@@ -76,7 +86,6 @@ export declare class PushProcessor {
76
86
  */
77
87
  private eventFulfillsEventPropertyContains;
78
88
  private eventFulfillsCallStartedCondition;
79
- private createCachedRegex;
80
89
  /**
81
90
  * Parse the key into the separate fields to search by splitting on
82
91
  * unescaped ".", and then removing any escape characters.
@@ -1 +1 @@
1
- {"version":3,"file":"pushprocessor.d.ts","sourceRoot":"","sources":["../src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WAAW,GAAG,OAAO;IAe3G;;OAEG;IACI,eAAe,CAAC,EAAE,EAAE,WAAW,GAAG,cAAc;IAKhD,sBAAsB,CAAC,EAAE,EAAE,WAAW,GAAG;QAC5C,OAAO,CAAC,EAAE,cAAc,CAAC;QACzB,IAAI,CAAC,EAAE,kBAAkB,CAAC;KAC7B;IAID;;;;;OAKG;IACI,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;IAKxD;;;;;;OAMG;IACI,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG;QAAE,IAAI,EAAE,SAAS,CAAC;QAAC,IAAI,EAAE,YAAY,CAAA;KAAE,GAAG,IAAI;CAchG"}
@@ -219,6 +219,26 @@ export class PushProcessor {
219
219
  return newRules;
220
220
  }
221
221
 
222
+ /**
223
+ * Create a RegExp object for the given glob pattern with a single capture group around the pattern itself, caching the result.
224
+ * No cache invalidation is present currently,
225
+ * as this will be inherently bounded to the size of the user's own push rules.
226
+ * @param pattern - the glob pattern to convert to a RegExp
227
+ * @param alignToWordBoundary - whether to align the pattern to word boundaries,
228
+ * as specified for `content.body` matches, will use lookaround assertions to ensure the match only includes the pattern
229
+ * @param flags - the flags to pass to the RegExp constructor, defaults to case-insensitive
230
+ */
231
+ static getPushRuleGlobRegex(pattern) {
232
+ var alignToWordBoundary = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
233
+ var flags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "i";
234
+ var [prefix, suffix] = alignToWordBoundary ? ["(?<=^|\\W)", "(?=\\W|$)"] : ["^", "$"];
235
+ var cacheKey = "".concat(alignToWordBoundary, "-").concat(flags, "-").concat(pattern);
236
+ if (!PushProcessor.cachedGlobToRegex[cacheKey]) {
237
+ PushProcessor.cachedGlobToRegex[cacheKey] = new RegExp(prefix + "(" + globToRegexp(pattern) + ")" + suffix, flags);
238
+ }
239
+ return PushProcessor.cachedGlobToRegex[cacheKey];
240
+ }
241
+
222
242
  /**
223
243
  * Pre-caches the parsed keys for push rules and cleans out any obsolete cache
224
244
  * entries. Should be called after push rules are updated.
@@ -448,7 +468,10 @@ export class PushProcessor {
448
468
  if (typeof cond.pattern !== "string") {
449
469
  return false;
450
470
  }
451
- var regex = cond.key === "content.body" ? this.createCachedRegex("(^|\\W)", cond.pattern, "(\\W|$)") : this.createCachedRegex("^", cond.pattern, "$");
471
+
472
+ // Align to word boundary on `content.body` matches, whole string otherwise
473
+ // https://spec.matrix.org/v1.13/client-server-api/#conditions-1
474
+ var regex = PushProcessor.getPushRuleGlobRegex(cond.pattern, cond.key === "content.body");
452
475
  return !!val.match(regex);
453
476
  }
454
477
 
@@ -488,14 +511,6 @@ export class PushProcessor {
488
511
  // about MSC3401 call events, we do the handling ourselves
489
512
  return ["m.ring", "m.prompt"].includes(ev.getContent()["m.intent"]) && !("m.terminated" in ev.getContent()) && (ev.getPrevContent()["m.terminated"] !== ev.getContent()["m.terminated"] || deepCompare(ev.getPrevContent(), {}));
490
513
  }
491
- createCachedRegex(prefix, glob, suffix) {
492
- if (PushProcessor.cachedGlobToRegex[glob]) {
493
- return PushProcessor.cachedGlobToRegex[glob];
494
- }
495
- PushProcessor.cachedGlobToRegex[glob] = new RegExp(prefix + globToRegexp(glob) + suffix, "i") // Case insensitive
496
- ;
497
- return PushProcessor.cachedGlobToRegex[glob];
498
- }
499
514
 
500
515
  /**
501
516
  * Parse the key into the separate fields to search by splitting on
@@ -1 +1 @@
1
- {"version":3,"file":"pushprocessor.js","names":["deepCompare","escapeRegExp","globToRegexp","isNullOrUndefined","logger","ConditionKind","PushRuleActionName","PushRuleKind","RuleId","TweakName","EventType","RULEKINDS_IN_ORDER","Override","ContentSpecific","RoomSpecific","SenderSpecific","Underride","DEFAULT_OVERRIDE_RULES","rule_id","default","enabled","conditions","kind","EventPropertyIs","key","value","SenderNotificationPermission","actions","Notify","set_tweak","Highlight","EventMatch","pattern","DontNotify","RoomServerAcl","UserDefinedRules","Symbol","EXPECTED_DEFAULT_OVERRIDE_RULE_IDS","Master","SuppressNotices","InviteToSelf","MemberEvent","IsUserMention","ContainsDisplayName","IsRoomMention","AtRoomNotification","Tombstone","DEFAULT_UNDERRIDE_RULES","CallStarted","Sound","EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS","IncomingCall","EncryptedDM","DM","Message","EncryptedMessage","mergeRulesWithDefaults","incomingRules","defaultRules","orderedRuleIds","incomingDefaultRules","filter","rule","incomingCustomRules","insertDefaultPushRule","ruleId","newRules","push","warn","concat","nextExpectedRuleIdIndex","ruleIndex","indexOf","defaultRuleId","slice","PushProcessor","constructor","client","_defineProperty","Map","actionListToActionsObject","actionList","actionObj","notify","tweaks","action","undefined","rewriteDefaultRules","userId","arguments","length","JSON","parse","stringify","global","override","underride","updateCachedPushRuleKeys","room","sender","toRemoveKeys","Set","parsedKeys","keys","ruleset","condition","delete","set","partsForDottedKey","forEach","k","matchingRuleFromKindSet","ev","kindset","rawrule","templateRuleToRaw","ruleMatchesEvent","_objectSpread","tprule","eventFulfillsCondition","cond","eventFulfillsEventMatchCondition","eventFulfillsEventPropertyIsCondition","EventPropertyContains","eventFulfillsEventPropertyContains","eventFulfillsDisplayNameCondition","RoomMemberCount","eventFulfillsRoomMemberCountCondition","eventFulfillsSenderNotifPermCondition","CallStartedPrefix","eventFulfillsCallStartedCondition","notifLevelKey","getRoom","getRoomId","currentState","mayTriggerNotifOfType","getSender","is","members","memberCount","getJoinedMemberCount","m","match","ineq","rhs","parseInt","isNaN","_room$currentState","content","getContent","isEncrypted","getClearContent","body","member","getMember","credentials","displayName","name","pat","RegExp","search","val","valueForDottedKey","regex","createCachedRegex","Array","isArray","includes","_cond","getPrevContent","prefix","glob","suffix","cachedGlobToRegex","str","result","part","escaped","c","parts","get","firstPart","currentIndex","getType","event","thisPart","matchingRuleForEventWithRulesets","rulesets","getSafeUserId","pushActionsForEventAndRulesets","highlight","_rule$conditions","supportsIntentionalMentions","ContainsUserName","some","actionsForEvent","pushRules","actionsAndRuleForEvent","getPushRuleById","_result$rule","getPushRuleAndKindById","scope","_this$client$pushRule"],"sources":["../src/pushprocessor.ts"],"sourcesContent":["/*\nCopyright 2015 - 2021 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 { deepCompare, escapeRegExp, globToRegexp, isNullOrUndefined } from \"./utils.ts\";\nimport { logger } from \"./logger.ts\";\nimport { type MatrixClient } from \"./client.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\nimport {\n ConditionKind,\n type IAnnotatedPushRule,\n type ICallStartedCondition,\n type ICallStartedPrefixCondition,\n type IContainsDisplayNameCondition,\n type IEventMatchCondition,\n type IEventPropertyContainsCondition,\n type IEventPropertyIsCondition,\n type IPushRule,\n type IPushRules,\n type IRoomMemberCountCondition,\n type ISenderNotificationPermissionCondition,\n type PushRuleAction,\n PushRuleActionName,\n type PushRuleCondition,\n PushRuleKind,\n type PushRuleSet,\n RuleId,\n TweakName,\n} from \"./@types/PushRules.ts\";\nimport { EventType } from \"./@types/event.ts\";\n\nconst RULEKINDS_IN_ORDER = [\n PushRuleKind.Override,\n PushRuleKind.ContentSpecific,\n PushRuleKind.RoomSpecific,\n PushRuleKind.SenderSpecific,\n PushRuleKind.Underride,\n];\n\n// The default override rules to apply to the push rules that arrive from the server.\n// We do this for two reasons:\n// 1. Synapse is unlikely to send us the push rule in an incremental sync - see\n// https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for\n// more details.\n// 2. We often want to start using push rules ahead of the server supporting them,\n// and so we can put them here.\nconst DEFAULT_OVERRIDE_RULES: Record<string, IPushRule> = {\n \".m.rule.is_room_mention\": {\n // Matrix v1.7\n rule_id: \".m.rule.is_room_mention\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventPropertyIs,\n key: \"content.m\\\\.mentions.room\",\n value: true,\n },\n {\n kind: ConditionKind.SenderNotificationPermission,\n key: \"room\",\n },\n ],\n actions: [\n PushRuleActionName.Notify,\n {\n set_tweak: TweakName.Highlight,\n },\n ],\n },\n \".m.rule.reaction\": {\n // For homeservers which don't support MSC2153 yet\n rule_id: \".m.rule.reaction\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: \"m.reaction\",\n },\n ],\n actions: [PushRuleActionName.DontNotify],\n },\n \".org.matrix.msc3786.rule.room.server_acl\": {\n // For homeservers which don't support MSC3786 yet\n rule_id: \".org.matrix.msc3786.rule.room.server_acl\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: EventType.RoomServerAcl,\n },\n {\n kind: ConditionKind.EventMatch,\n key: \"state_key\",\n pattern: \"\",\n },\n ],\n actions: [],\n },\n};\n\n// A special rule id for `EXPECTED_DEFAULT_OVERRIDE_RULE_IDS` and friends which denotes where user-defined rules live in the order.\nconst UserDefinedRules = Symbol(\"UserDefinedRules\");\n\ntype OrderedRules = Array<string | typeof UserDefinedRules>;\n\nconst EXPECTED_DEFAULT_OVERRIDE_RULE_IDS: OrderedRules = [\n RuleId.Master,\n UserDefinedRules,\n RuleId.SuppressNotices,\n RuleId.InviteToSelf,\n RuleId.MemberEvent,\n RuleId.IsUserMention,\n RuleId.ContainsDisplayName,\n RuleId.IsRoomMention,\n RuleId.AtRoomNotification,\n RuleId.Tombstone,\n \".m.rule.reaction\",\n \".m.rule.room.server_acl\",\n \".org.matrix.msc3786.rule.room.server_acl\",\n \".m.rule.suppress_edits\",\n];\n\nconst DEFAULT_UNDERRIDE_RULES: Record<string, IPushRule> = {\n \".org.matrix.msc3914.rule.room.call\": {\n // For homeservers which don't support MSC3914 yet\n rule_id: \".org.matrix.msc3914.rule.room.call\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: \"org.matrix.msc3401.call\",\n },\n {\n kind: ConditionKind.CallStarted,\n },\n ],\n actions: [PushRuleActionName.Notify, { set_tweak: TweakName.Sound, value: \"default\" }],\n },\n};\n\nconst EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS: OrderedRules = [\n UserDefinedRules,\n RuleId.IncomingCall,\n \".org.matrix.msc3914.rule.room.call\",\n RuleId.EncryptedDM,\n RuleId.DM,\n RuleId.Message,\n RuleId.EncryptedMessage,\n];\n\n/**\n * Make sure that each of the rules listed in `defaultRuleIds` is listed in the given set of push rules.\n *\n * @param kind - the kind of push rule set being merged.\n * @param incomingRules - the existing set of known push rules for the user.\n * @param defaultRules - a lookup table for the default definitions of push rules.\n * @param orderedRuleIds - the IDs of the expected push rules, in order.\n *\n * @returns A copy of `incomingRules`, with any missing default rules inserted in the right place.\n */\nfunction mergeRulesWithDefaults(\n kind: PushRuleKind,\n incomingRules: IPushRule[],\n defaultRules: Record<string, IPushRule>,\n orderedRuleIds: OrderedRules,\n): IPushRule[] {\n // Split the incomingRules into defaults and custom\n const incomingDefaultRules = incomingRules.filter((rule) => rule.default);\n const incomingCustomRules = incomingRules.filter((rule) => !rule.default);\n\n function insertDefaultPushRule(ruleId: OrderedRules[number]): void {\n if (ruleId === UserDefinedRules) {\n // Re-insert any user-defined rules that were in `incomingRules`\n newRules.push(...incomingCustomRules);\n } else if (ruleId in defaultRules) {\n logger.warn(`Adding default global ${kind} push rule ${ruleId}`);\n newRules.push(defaultRules[ruleId]);\n } else {\n logger.warn(`Missing default global ${kind} push rule ${ruleId}`);\n }\n }\n\n let nextExpectedRuleIdIndex = 0;\n const newRules: IPushRule[] = [];\n // Merge our expected rules (including the incoming custom rules) into the incoming default rules.\n for (const rule of incomingDefaultRules) {\n const ruleIndex = orderedRuleIds.indexOf(rule.rule_id);\n if (ruleIndex === -1) {\n // an unrecognised rule; copy it over\n newRules.push(rule);\n continue;\n }\n while (ruleIndex > nextExpectedRuleIdIndex) {\n // insert new rules\n const defaultRuleId = orderedRuleIds[nextExpectedRuleIdIndex];\n insertDefaultPushRule(defaultRuleId);\n nextExpectedRuleIdIndex += 1;\n }\n // copy over the existing rule\n newRules.push(rule);\n nextExpectedRuleIdIndex += 1;\n }\n\n // Now copy over any remaining default rules\n for (const ruleId of orderedRuleIds.slice(nextExpectedRuleIdIndex)) {\n insertDefaultPushRule(ruleId);\n }\n\n return newRules;\n}\n\nexport interface IActionsObject {\n /** Whether this event should notify the user or not. */\n notify: boolean;\n /** How this event should be notified. */\n tweaks: Partial<Record<TweakName, any>>;\n}\n\nexport class PushProcessor {\n /**\n * Construct a Push Processor.\n * @param client - The Matrix client object to use\n */\n public constructor(private readonly client: MatrixClient) {}\n\n /**\n * Maps the original key from the push rules to a list of property names\n * after unescaping.\n */\n private readonly parsedKeys = new Map<string, string[]>();\n\n /**\n * Convert a list of actions into a object with the actions as keys and their values\n * @example\n * eg. `[ 'notify', { set_tweak: 'sound', value: 'default' } ]`\n * becomes `{ notify: true, tweaks: { sound: 'default' } }`\n * @param actionList - The actions list\n *\n * @returns A object with key 'notify' (true or false) and an object of actions\n */\n public static actionListToActionsObject(actionList: PushRuleAction[]): IActionsObject {\n const actionObj: IActionsObject = { notify: false, tweaks: {} };\n for (const action of actionList) {\n if (action === PushRuleActionName.Notify) {\n actionObj.notify = true;\n } else if (typeof action === \"object\") {\n if (action.value === undefined) {\n action.value = true;\n }\n actionObj.tweaks[action.set_tweak] = action.value;\n }\n }\n return actionObj;\n }\n\n /**\n * Rewrites conditions on a client's push rules to match the defaults\n * where applicable. Useful for upgrading push rules to more strict\n * conditions when the server is falling behind on defaults.\n * @param incomingRules - The client's existing push rules\n * @param userId - The Matrix ID of the client.\n * @returns The rewritten rules\n */\n public static rewriteDefaultRules(incomingRules: IPushRules, userId: string | undefined = undefined): IPushRules {\n let newRules: IPushRules = JSON.parse(JSON.stringify(incomingRules)); // deep clone\n\n // These lines are mostly to make the tests happy. We shouldn't run into these\n // properties missing in practice.\n if (!newRules) newRules = {} as IPushRules;\n if (!newRules.global) newRules.global = {} as PushRuleSet;\n if (!newRules.global.override) newRules.global.override = [];\n if (!newRules.global.underride) newRules.global.underride = [];\n\n // Merge the client-level defaults with the ones from the server\n newRules.global.override = mergeRulesWithDefaults(\n PushRuleKind.Override,\n newRules.global.override,\n DEFAULT_OVERRIDE_RULES,\n EXPECTED_DEFAULT_OVERRIDE_RULE_IDS,\n );\n\n newRules.global.underride = mergeRulesWithDefaults(\n PushRuleKind.Underride,\n newRules.global.underride,\n DEFAULT_UNDERRIDE_RULES,\n EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS,\n );\n\n return newRules;\n }\n\n /**\n * Pre-caches the parsed keys for push rules and cleans out any obsolete cache\n * entries. Should be called after push rules are updated.\n * @param newRules - The new push rules.\n */\n public updateCachedPushRuleKeys(newRules: IPushRules): void {\n // These lines are mostly to make the tests happy. We shouldn't run into these\n // properties missing in practice.\n if (!newRules) newRules = {} as IPushRules;\n if (!newRules.global) newRules.global = {} as PushRuleSet;\n if (!newRules.global.override) newRules.global.override = [];\n if (!newRules.global.room) newRules.global.room = [];\n if (!newRules.global.sender) newRules.global.sender = [];\n if (!newRules.global.underride) newRules.global.underride = [];\n\n // Process the 'key' property on event_match conditions pre-cache the\n // values and clean-out any unused values.\n const toRemoveKeys = new Set(this.parsedKeys.keys());\n for (const ruleset of [\n newRules.global.override,\n newRules.global.room,\n newRules.global.sender,\n newRules.global.underride,\n ]) {\n for (const rule of ruleset) {\n if (!rule.conditions) {\n continue;\n }\n\n for (const condition of rule.conditions) {\n if (condition.kind !== ConditionKind.EventMatch) {\n continue;\n }\n\n // Ensure we keep this key.\n toRemoveKeys.delete(condition.key);\n\n // Pre-process the key.\n this.parsedKeys.set(condition.key, PushProcessor.partsForDottedKey(condition.key));\n }\n }\n }\n // Any keys that were previously cached, but are no longer needed should\n // be removed.\n toRemoveKeys.forEach((k) => this.parsedKeys.delete(k));\n }\n\n private static cachedGlobToRegex: Record<string, RegExp> = {}; // $glob: RegExp\n\n private matchingRuleFromKindSet(ev: MatrixEvent, kindset: PushRuleSet): IAnnotatedPushRule | null {\n for (const kind of RULEKINDS_IN_ORDER) {\n const ruleset = kindset[kind];\n if (!ruleset) {\n continue;\n }\n\n for (const rule of ruleset) {\n if (!rule.enabled) {\n continue;\n }\n\n const rawrule = this.templateRuleToRaw(kind, rule);\n if (!rawrule) {\n continue;\n }\n\n if (this.ruleMatchesEvent(rawrule, ev)) {\n return {\n ...rule,\n kind,\n };\n }\n }\n }\n return null;\n }\n\n private templateRuleToRaw(\n kind: PushRuleKind,\n tprule: IPushRule,\n ): Pick<IPushRule, \"rule_id\" | \"actions\" | \"conditions\"> | null {\n const rawrule: Pick<IPushRule, \"rule_id\" | \"actions\" | \"conditions\"> = {\n rule_id: tprule.rule_id,\n actions: tprule.actions,\n conditions: [],\n };\n switch (kind) {\n case PushRuleKind.Underride:\n case PushRuleKind.Override:\n rawrule.conditions = tprule.conditions;\n break;\n case PushRuleKind.RoomSpecific:\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"room_id\",\n value: tprule.rule_id,\n });\n break;\n case PushRuleKind.SenderSpecific:\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"user_id\",\n value: tprule.rule_id,\n });\n break;\n case PushRuleKind.ContentSpecific:\n if (!tprule.pattern) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"content.body\",\n pattern: tprule.pattern,\n });\n break;\n }\n return rawrule;\n }\n\n private eventFulfillsCondition(cond: PushRuleCondition, ev: MatrixEvent): boolean {\n switch (cond.kind) {\n case ConditionKind.EventMatch:\n return this.eventFulfillsEventMatchCondition(cond, ev);\n case ConditionKind.EventPropertyIs:\n return this.eventFulfillsEventPropertyIsCondition(cond, ev);\n case ConditionKind.EventPropertyContains:\n return this.eventFulfillsEventPropertyContains(cond, ev);\n case ConditionKind.ContainsDisplayName:\n return this.eventFulfillsDisplayNameCondition(cond, ev);\n case ConditionKind.RoomMemberCount:\n return this.eventFulfillsRoomMemberCountCondition(cond, ev);\n case ConditionKind.SenderNotificationPermission:\n return this.eventFulfillsSenderNotifPermCondition(cond, ev);\n case ConditionKind.CallStarted:\n case ConditionKind.CallStartedPrefix:\n return this.eventFulfillsCallStartedCondition(cond, ev);\n }\n\n // unknown conditions: we previously matched all unknown conditions,\n // but given that rules can be added to the base rules on a server,\n // it's probably better to not match unknown conditions.\n return false;\n }\n\n private eventFulfillsSenderNotifPermCondition(\n cond: ISenderNotificationPermissionCondition,\n ev: MatrixEvent,\n ): boolean {\n const notifLevelKey = cond[\"key\"];\n if (!notifLevelKey) {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n if (!room?.currentState) {\n return false;\n }\n\n // Note that this should not be the current state of the room but the state at\n // the point the event is in the DAG. Unfortunately the js-sdk does not store\n // this.\n return room.currentState.mayTriggerNotifOfType(notifLevelKey, ev.getSender()!);\n }\n\n private eventFulfillsRoomMemberCountCondition(cond: IRoomMemberCountCondition, ev: MatrixEvent): boolean {\n if (!cond.is) {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n if (!room || !room.currentState || !room.currentState.members) {\n return false;\n }\n\n const memberCount = room.currentState.getJoinedMemberCount();\n\n const m = cond.is.match(/^([=<>]*)(\\d*)$/);\n if (!m) {\n return false;\n }\n const ineq = m[1];\n const rhs = parseInt(m[2]);\n if (isNaN(rhs)) {\n return false;\n }\n switch (ineq) {\n case \"\":\n case \"==\":\n return memberCount == rhs;\n case \"<\":\n return memberCount < rhs;\n case \">\":\n return memberCount > rhs;\n case \"<=\":\n return memberCount <= rhs;\n case \">=\":\n return memberCount >= rhs;\n default:\n return false;\n }\n }\n\n private eventFulfillsDisplayNameCondition(cond: IContainsDisplayNameCondition, ev: MatrixEvent): boolean {\n let content = ev.getContent();\n if (ev.isEncrypted() && ev.getClearContent()) {\n content = ev.getClearContent()!;\n }\n if (!content || !content.body || typeof content.body != \"string\") {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n const member = room?.currentState?.getMember(this.client.credentials.userId!);\n if (!member) {\n return false;\n }\n\n const displayName = member.name;\n\n // N.B. we can't use \\b as it chokes on unicode. however \\W seems to be okay\n // as shorthand for [^0-9A-Za-z_].\n const pat = new RegExp(\"(^|\\\\W)\" + escapeRegExp(displayName) + \"(\\\\W|$)\", \"i\");\n return content.body.search(pat) > -1;\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing against the condition's glob-based\n * pattern.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventMatchCondition(cond: IEventMatchCondition, ev: MatrixEvent): boolean {\n if (!cond.key) {\n return false;\n }\n\n const val = this.valueForDottedKey(cond.key, ev);\n if (typeof val !== \"string\") {\n return false;\n }\n\n // XXX This does not match in a case-insensitive manner.\n //\n // See https://spec.matrix.org/v1.5/client-server-api/#conditions-1\n if (cond.value) {\n return cond.value === val;\n }\n\n if (typeof cond.pattern !== \"string\") {\n return false;\n }\n\n const regex =\n cond.key === \"content.body\"\n ? this.createCachedRegex(\"(^|\\\\W)\", cond.pattern, \"(\\\\W|$)\")\n : this.createCachedRegex(\"^\", cond.pattern, \"$\");\n\n return !!val.match(regex);\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing exactly against the condition's\n * value.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventPropertyIsCondition(cond: IEventPropertyIsCondition, ev: MatrixEvent): boolean {\n if (!cond.key || cond.value === undefined) {\n return false;\n }\n return cond.value === this.valueForDottedKey(cond.key, ev);\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing exactly against the condition's\n * value.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventPropertyContains(cond: IEventPropertyContainsCondition, ev: MatrixEvent): boolean {\n if (!cond.key || cond.value === undefined) {\n return false;\n }\n const val = this.valueForDottedKey(cond.key, ev);\n if (!Array.isArray(val)) {\n return false;\n }\n return val.includes(cond.value);\n }\n\n private eventFulfillsCallStartedCondition(\n _cond: ICallStartedCondition | ICallStartedPrefixCondition,\n ev: MatrixEvent,\n ): boolean {\n // Since servers don't support properly sending push notification\n // about MSC3401 call events, we do the handling ourselves\n return (\n [\"m.ring\", \"m.prompt\"].includes(ev.getContent()[\"m.intent\"]) &&\n !(\"m.terminated\" in ev.getContent()) &&\n (ev.getPrevContent()[\"m.terminated\"] !== ev.getContent()[\"m.terminated\"] ||\n deepCompare(ev.getPrevContent(), {}))\n );\n }\n\n private createCachedRegex(prefix: string, glob: string, suffix: string): RegExp {\n if (PushProcessor.cachedGlobToRegex[glob]) {\n return PushProcessor.cachedGlobToRegex[glob];\n }\n PushProcessor.cachedGlobToRegex[glob] = new RegExp(\n prefix + globToRegexp(glob) + suffix,\n \"i\", // Case insensitive\n );\n return PushProcessor.cachedGlobToRegex[glob];\n }\n\n /**\n * Parse the key into the separate fields to search by splitting on\n * unescaped \".\", and then removing any escape characters.\n *\n * @param str - The key of the push rule condition: a dotted field.\n * @returns The unescaped parts to fetch.\n * @internal\n */\n public static partsForDottedKey(str: string): string[] {\n const result: string[] = [];\n\n // The current field and whether the previous character was the escape\n // character (a backslash).\n let part = \"\";\n let escaped = false;\n\n // Iterate over each character, and decide whether to append to the current\n // part (following the escape rules) or to start a new part (based on the\n // field separator).\n for (const c of str) {\n // If the previous character was the escape character (a backslash)\n // then decide what to append to the current part.\n if (escaped) {\n if (c === \"\\\\\" || c === \".\") {\n // An escaped backslash or dot just gets added.\n part += c;\n } else {\n // A character that shouldn't be escaped gets the backslash prepended.\n part += \"\\\\\" + c;\n }\n // This always resets being escaped.\n escaped = false;\n continue;\n }\n\n if (c == \".\") {\n // The field separator creates a new part.\n result.push(part);\n part = \"\";\n } else if (c == \"\\\\\") {\n // A backslash adds no characters, but starts an escape sequence.\n escaped = true;\n } else {\n // Otherwise, just add the current character.\n part += c;\n }\n }\n\n // Ensure the final part is included. If there's an open escape sequence\n // it should be included.\n if (escaped) {\n part += \"\\\\\";\n }\n result.push(part);\n\n return result;\n }\n\n /**\n * For a dotted field and event, fetch the value at that position, if one\n * exists.\n *\n * @param key - The key of the push rule condition: a dotted field to fetch.\n * @param ev - The matrix event to fetch the field from.\n * @returns The value at the dotted path given by key.\n */\n private valueForDottedKey(key: string, ev: MatrixEvent): any {\n // The key should already have been parsed via updateCachedPushRuleKeys,\n // but if it hasn't (maybe via an old consumer of the SDK which hasn't\n // been updated?) then lazily calculate it here.\n let parts = this.parsedKeys.get(key);\n if (parts === undefined) {\n parts = PushProcessor.partsForDottedKey(key);\n this.parsedKeys.set(key, parts);\n }\n let val: any;\n\n // special-case the first component to deal with encrypted messages\n const firstPart = parts[0];\n let currentIndex = 0;\n if (firstPart === \"content\") {\n val = ev.getContent();\n ++currentIndex;\n } else if (firstPart === \"type\") {\n val = ev.getType();\n ++currentIndex;\n } else {\n // use the raw event for any other fields\n val = ev.event;\n }\n\n for (; currentIndex < parts.length; ++currentIndex) {\n // The previous iteration resulted in null or undefined, bail (and\n // avoid the type error of attempting to retrieve a property).\n if (isNullOrUndefined(val)) {\n return undefined;\n }\n\n const thisPart = parts[currentIndex];\n val = val[thisPart];\n }\n return val;\n }\n\n private matchingRuleForEventWithRulesets(ev: MatrixEvent, rulesets?: IPushRules): IAnnotatedPushRule | null {\n if (!rulesets) {\n return null;\n }\n\n if (ev.getSender() === this.client.getSafeUserId()) {\n return null;\n }\n\n return this.matchingRuleFromKindSet(ev, rulesets.global);\n }\n\n private pushActionsForEventAndRulesets(\n ev: MatrixEvent,\n rulesets?: IPushRules,\n ): {\n actions?: IActionsObject;\n rule?: IAnnotatedPushRule;\n } {\n const rule = this.matchingRuleForEventWithRulesets(ev, rulesets);\n if (!rule) {\n return {};\n }\n\n const actionObj = PushProcessor.actionListToActionsObject(rule.actions);\n\n // Some actions are implicit in some situations: we add those here\n if (actionObj.tweaks.highlight === undefined) {\n // if it isn't specified, highlight if it's a content\n // rule but otherwise not\n actionObj.tweaks.highlight = rule.kind == PushRuleKind.ContentSpecific;\n }\n\n return { actions: actionObj, rule };\n }\n\n public ruleMatchesEvent(rule: Partial<IPushRule> & Pick<IPushRule, \"conditions\">, ev: MatrixEvent): boolean {\n // Disable the deprecated mentions push rules if the new mentions property exists.\n if (\n this.client.supportsIntentionalMentions() &&\n ev.getContent()[\"m.mentions\"] !== undefined &&\n (rule.rule_id === RuleId.ContainsUserName ||\n rule.rule_id === RuleId.ContainsDisplayName ||\n rule.rule_id === RuleId.AtRoomNotification)\n ) {\n return false;\n }\n\n return !rule.conditions?.some((cond) => !this.eventFulfillsCondition(cond, ev));\n }\n\n /**\n * Get the user's push actions for the given event\n */\n public actionsForEvent(ev: MatrixEvent): IActionsObject {\n const { actions } = this.pushActionsForEventAndRulesets(ev, this.client.pushRules);\n return actions || ({} as IActionsObject);\n }\n\n public actionsAndRuleForEvent(ev: MatrixEvent): {\n actions?: IActionsObject;\n rule?: IAnnotatedPushRule;\n } {\n return this.pushActionsForEventAndRulesets(ev, this.client.pushRules);\n }\n\n /**\n * Get one of the users push rules by its ID\n *\n * @param ruleId - The ID of the rule to search for\n * @returns The push rule, or null if no such rule was found\n */\n public getPushRuleById(ruleId: string): IPushRule | null {\n const result = this.getPushRuleAndKindById(ruleId);\n return result?.rule ?? null;\n }\n\n /**\n * Get one of the users push rules by its ID\n *\n * @param ruleId - The ID of the rule to search for\n * @returns rule The push rule, or null if no such rule was found\n * @returns kind - The PushRuleKind of the rule to search for\n */\n public getPushRuleAndKindById(ruleId: string): { rule: IPushRule; kind: PushRuleKind } | null {\n for (const scope of [\"global\"] as const) {\n if (this.client.pushRules?.[scope] === undefined) continue;\n\n for (const kind of RULEKINDS_IN_ORDER) {\n if (this.client.pushRules[scope][kind] === undefined) continue;\n\n for (const rule of this.client.pushRules[scope][kind]!) {\n if (rule.rule_id === ruleId) return { rule, kind };\n }\n }\n }\n return null;\n }\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,WAAW,EAAEC,YAAY,EAAEC,YAAY,EAAEC,iBAAiB,QAAQ,YAAY;AACvF,SAASC,MAAM,QAAQ,aAAa;AAGpC,SACIC,aAAa,EAabC,kBAAkB,EAElBC,YAAY,EAEZC,MAAM,EACNC,SAAS,QACN,uBAAuB;AAC9B,SAASC,SAAS,QAAQ,mBAAmB;AAE7C,IAAMC,kBAAkB,GAAG,CACvBJ,YAAY,CAACK,QAAQ,EACrBL,YAAY,CAACM,eAAe,EAC5BN,YAAY,CAACO,YAAY,EACzBP,YAAY,CAACQ,cAAc,EAC3BR,YAAY,CAACS,SAAS,CACzB;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,sBAAiD,GAAG;EACtD,yBAAyB,EAAE;IACvB;IACAC,OAAO,EAAE,yBAAyB;IAClCC,OAAO,EAAE,IAAI;IACbC,OAAO,EAAE,IAAI;IACbC,UAAU,EAAE,CACR;MACIC,IAAI,EAAEjB,aAAa,CAACkB,eAAe;MACnCC,GAAG,EAAE,2BAA2B;MAChCC,KAAK,EAAE;IACX,CAAC,EACD;MACIH,IAAI,EAAEjB,aAAa,CAACqB,4BAA4B;MAChDF,GAAG,EAAE;IACT,CAAC,CACJ;IACDG,OAAO,EAAE,CACLrB,kBAAkB,CAACsB,MAAM,EACzB;MACIC,SAAS,EAAEpB,SAAS,CAACqB;IACzB,CAAC;EAET,CAAC;EACD,kBAAkB,EAAE;IAChB;IACAZ,OAAO,EAAE,kBAAkB;IAC3BC,OAAO,EAAE,IAAI;IACbC,OAAO,EAAE,IAAI;IACbC,UAAU,E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AA;MACrC,IAAI,EAAAA,qBAAA,OAAI,CAAC7H,MAAM,CAACuH,SAAS,cAAAM,qBAAA,uBAArBA,qBAAA,CAAwBD,KAAK,CAAC,MAAKnH,SAAS,EAAE;MAElD,KAAK,IAAMhE,IAAI,IAAIX,kBAAkB,EAAE;QACnC,IAAI,IAAI,CAACkE,MAAM,CAACuH,SAAS,CAACK,KAAK,CAAC,CAACnL,IAAI,CAAC,KAAKgE,SAAS,EAAE;QAEtD,KAAK,IAAMxB,IAAI,IAAI,IAAI,CAACe,MAAM,CAACuH,SAAS,CAACK,KAAK,CAAC,CAACnL,IAAI,CAAC,EAAG;UACpD,IAAIwC,IAAI,CAAC5C,OAAO,KAAK+C,MAAM,EAAE,OAAO;YAAEH,IAAI;YAAExC;UAAK,CAAC;QACtD;MACJ;IACJ;IACA,OAAO,IAAI;EACf;AACJ;AAACwD,eAAA,CAvlBYH,aAAa,uBAwHqC,CAAC,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"pushprocessor.js","names":["deepCompare","escapeRegExp","globToRegexp","isNullOrUndefined","logger","ConditionKind","PushRuleActionName","PushRuleKind","RuleId","TweakName","EventType","RULEKINDS_IN_ORDER","Override","ContentSpecific","RoomSpecific","SenderSpecific","Underride","DEFAULT_OVERRIDE_RULES","rule_id","default","enabled","conditions","kind","EventPropertyIs","key","value","SenderNotificationPermission","actions","Notify","set_tweak","Highlight","EventMatch","pattern","DontNotify","RoomServerAcl","UserDefinedRules","Symbol","EXPECTED_DEFAULT_OVERRIDE_RULE_IDS","Master","SuppressNotices","InviteToSelf","MemberEvent","IsUserMention","ContainsDisplayName","IsRoomMention","AtRoomNotification","Tombstone","DEFAULT_UNDERRIDE_RULES","CallStarted","Sound","EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS","IncomingCall","EncryptedDM","DM","Message","EncryptedMessage","mergeRulesWithDefaults","incomingRules","defaultRules","orderedRuleIds","incomingDefaultRules","filter","rule","incomingCustomRules","insertDefaultPushRule","ruleId","newRules","push","warn","concat","nextExpectedRuleIdIndex","ruleIndex","indexOf","defaultRuleId","slice","PushProcessor","constructor","client","_defineProperty","Map","actionListToActionsObject","actionList","actionObj","notify","tweaks","action","undefined","rewriteDefaultRules","userId","arguments","length","JSON","parse","stringify","global","override","underride","getPushRuleGlobRegex","alignToWordBoundary","flags","prefix","suffix","cacheKey","cachedGlobToRegex","RegExp","updateCachedPushRuleKeys","room","sender","toRemoveKeys","Set","parsedKeys","keys","ruleset","condition","delete","set","partsForDottedKey","forEach","k","matchingRuleFromKindSet","ev","kindset","rawrule","templateRuleToRaw","ruleMatchesEvent","_objectSpread","tprule","eventFulfillsCondition","cond","eventFulfillsEventMatchCondition","eventFulfillsEventPropertyIsCondition","EventPropertyContains","eventFulfillsEventPropertyContains","eventFulfillsDisplayNameCondition","RoomMemberCount","eventFulfillsRoomMemberCountCondition","eventFulfillsSenderNotifPermCondition","CallStartedPrefix","eventFulfillsCallStartedCondition","notifLevelKey","getRoom","getRoomId","currentState","mayTriggerNotifOfType","getSender","is","members","memberCount","getJoinedMemberCount","m","match","ineq","rhs","parseInt","isNaN","_room$currentState","content","getContent","isEncrypted","getClearContent","body","member","getMember","credentials","displayName","name","pat","search","val","valueForDottedKey","regex","Array","isArray","includes","_cond","getPrevContent","str","result","part","escaped","c","parts","get","firstPart","currentIndex","getType","event","thisPart","matchingRuleForEventWithRulesets","rulesets","getSafeUserId","pushActionsForEventAndRulesets","highlight","_rule$conditions","supportsIntentionalMentions","ContainsUserName","some","actionsForEvent","pushRules","actionsAndRuleForEvent","getPushRuleById","_result$rule","getPushRuleAndKindById","scope","_this$client$pushRule"],"sources":["../src/pushprocessor.ts"],"sourcesContent":["/*\nCopyright 2015 - 2021 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 { deepCompare, escapeRegExp, globToRegexp, isNullOrUndefined } from \"./utils.ts\";\nimport { logger } from \"./logger.ts\";\nimport { type MatrixClient } from \"./client.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\nimport {\n ConditionKind,\n type IAnnotatedPushRule,\n type ICallStartedCondition,\n type ICallStartedPrefixCondition,\n type IContainsDisplayNameCondition,\n type IEventMatchCondition,\n type IEventPropertyContainsCondition,\n type IEventPropertyIsCondition,\n type IPushRule,\n type IPushRules,\n type IRoomMemberCountCondition,\n type ISenderNotificationPermissionCondition,\n type PushRuleAction,\n PushRuleActionName,\n type PushRuleCondition,\n PushRuleKind,\n type PushRuleSet,\n RuleId,\n TweakName,\n} from \"./@types/PushRules.ts\";\nimport { EventType } from \"./@types/event.ts\";\n\nconst RULEKINDS_IN_ORDER = [\n PushRuleKind.Override,\n PushRuleKind.ContentSpecific,\n PushRuleKind.RoomSpecific,\n PushRuleKind.SenderSpecific,\n PushRuleKind.Underride,\n];\n\n// The default override rules to apply to the push rules that arrive from the server.\n// We do this for two reasons:\n// 1. Synapse is unlikely to send us the push rule in an incremental sync - see\n// https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for\n// more details.\n// 2. We often want to start using push rules ahead of the server supporting them,\n// and so we can put them here.\nconst DEFAULT_OVERRIDE_RULES: Record<string, IPushRule> = {\n \".m.rule.is_room_mention\": {\n // Matrix v1.7\n rule_id: \".m.rule.is_room_mention\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventPropertyIs,\n key: \"content.m\\\\.mentions.room\",\n value: true,\n },\n {\n kind: ConditionKind.SenderNotificationPermission,\n key: \"room\",\n },\n ],\n actions: [\n PushRuleActionName.Notify,\n {\n set_tweak: TweakName.Highlight,\n },\n ],\n },\n \".m.rule.reaction\": {\n // For homeservers which don't support MSC2153 yet\n rule_id: \".m.rule.reaction\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: \"m.reaction\",\n },\n ],\n actions: [PushRuleActionName.DontNotify],\n },\n \".org.matrix.msc3786.rule.room.server_acl\": {\n // For homeservers which don't support MSC3786 yet\n rule_id: \".org.matrix.msc3786.rule.room.server_acl\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: EventType.RoomServerAcl,\n },\n {\n kind: ConditionKind.EventMatch,\n key: \"state_key\",\n pattern: \"\",\n },\n ],\n actions: [],\n },\n};\n\n// A special rule id for `EXPECTED_DEFAULT_OVERRIDE_RULE_IDS` and friends which denotes where user-defined rules live in the order.\nconst UserDefinedRules = Symbol(\"UserDefinedRules\");\n\ntype OrderedRules = Array<string | typeof UserDefinedRules>;\n\nconst EXPECTED_DEFAULT_OVERRIDE_RULE_IDS: OrderedRules = [\n RuleId.Master,\n UserDefinedRules,\n RuleId.SuppressNotices,\n RuleId.InviteToSelf,\n RuleId.MemberEvent,\n RuleId.IsUserMention,\n RuleId.ContainsDisplayName,\n RuleId.IsRoomMention,\n RuleId.AtRoomNotification,\n RuleId.Tombstone,\n \".m.rule.reaction\",\n \".m.rule.room.server_acl\",\n \".org.matrix.msc3786.rule.room.server_acl\",\n \".m.rule.suppress_edits\",\n];\n\nconst DEFAULT_UNDERRIDE_RULES: Record<string, IPushRule> = {\n \".org.matrix.msc3914.rule.room.call\": {\n // For homeservers which don't support MSC3914 yet\n rule_id: \".org.matrix.msc3914.rule.room.call\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: \"org.matrix.msc3401.call\",\n },\n {\n kind: ConditionKind.CallStarted,\n },\n ],\n actions: [PushRuleActionName.Notify, { set_tweak: TweakName.Sound, value: \"default\" }],\n },\n};\n\nconst EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS: OrderedRules = [\n UserDefinedRules,\n RuleId.IncomingCall,\n \".org.matrix.msc3914.rule.room.call\",\n RuleId.EncryptedDM,\n RuleId.DM,\n RuleId.Message,\n RuleId.EncryptedMessage,\n];\n\n/**\n * Make sure that each of the rules listed in `defaultRuleIds` is listed in the given set of push rules.\n *\n * @param kind - the kind of push rule set being merged.\n * @param incomingRules - the existing set of known push rules for the user.\n * @param defaultRules - a lookup table for the default definitions of push rules.\n * @param orderedRuleIds - the IDs of the expected push rules, in order.\n *\n * @returns A copy of `incomingRules`, with any missing default rules inserted in the right place.\n */\nfunction mergeRulesWithDefaults(\n kind: PushRuleKind,\n incomingRules: IPushRule[],\n defaultRules: Record<string, IPushRule>,\n orderedRuleIds: OrderedRules,\n): IPushRule[] {\n // Split the incomingRules into defaults and custom\n const incomingDefaultRules = incomingRules.filter((rule) => rule.default);\n const incomingCustomRules = incomingRules.filter((rule) => !rule.default);\n\n function insertDefaultPushRule(ruleId: OrderedRules[number]): void {\n if (ruleId === UserDefinedRules) {\n // Re-insert any user-defined rules that were in `incomingRules`\n newRules.push(...incomingCustomRules);\n } else if (ruleId in defaultRules) {\n logger.warn(`Adding default global ${kind} push rule ${ruleId}`);\n newRules.push(defaultRules[ruleId]);\n } else {\n logger.warn(`Missing default global ${kind} push rule ${ruleId}`);\n }\n }\n\n let nextExpectedRuleIdIndex = 0;\n const newRules: IPushRule[] = [];\n // Merge our expected rules (including the incoming custom rules) into the incoming default rules.\n for (const rule of incomingDefaultRules) {\n const ruleIndex = orderedRuleIds.indexOf(rule.rule_id);\n if (ruleIndex === -1) {\n // an unrecognised rule; copy it over\n newRules.push(rule);\n continue;\n }\n while (ruleIndex > nextExpectedRuleIdIndex) {\n // insert new rules\n const defaultRuleId = orderedRuleIds[nextExpectedRuleIdIndex];\n insertDefaultPushRule(defaultRuleId);\n nextExpectedRuleIdIndex += 1;\n }\n // copy over the existing rule\n newRules.push(rule);\n nextExpectedRuleIdIndex += 1;\n }\n\n // Now copy over any remaining default rules\n for (const ruleId of orderedRuleIds.slice(nextExpectedRuleIdIndex)) {\n insertDefaultPushRule(ruleId);\n }\n\n return newRules;\n}\n\nexport interface IActionsObject {\n /** Whether this event should notify the user or not. */\n notify: boolean;\n /** How this event should be notified. */\n tweaks: Partial<Record<TweakName, any>>;\n}\n\nexport class PushProcessor {\n /**\n * Construct a Push Processor.\n * @param client - The Matrix client object to use\n */\n public constructor(private readonly client: MatrixClient) {}\n\n /**\n * Maps the original key from the push rules to a list of property names\n * after unescaping.\n */\n private readonly parsedKeys = new Map<string, string[]>();\n\n /**\n * Convert a list of actions into a object with the actions as keys and their values\n * @example\n * eg. `[ 'notify', { set_tweak: 'sound', value: 'default' } ]`\n * becomes `{ notify: true, tweaks: { sound: 'default' } }`\n * @param actionList - The actions list\n *\n * @returns A object with key 'notify' (true or false) and an object of actions\n */\n public static actionListToActionsObject(actionList: PushRuleAction[]): IActionsObject {\n const actionObj: IActionsObject = { notify: false, tweaks: {} };\n for (const action of actionList) {\n if (action === PushRuleActionName.Notify) {\n actionObj.notify = true;\n } else if (typeof action === \"object\") {\n if (action.value === undefined) {\n action.value = true;\n }\n actionObj.tweaks[action.set_tweak] = action.value;\n }\n }\n return actionObj;\n }\n\n /**\n * Rewrites conditions on a client's push rules to match the defaults\n * where applicable. Useful for upgrading push rules to more strict\n * conditions when the server is falling behind on defaults.\n * @param incomingRules - The client's existing push rules\n * @param userId - The Matrix ID of the client.\n * @returns The rewritten rules\n */\n public static rewriteDefaultRules(incomingRules: IPushRules, userId: string | undefined = undefined): IPushRules {\n let newRules: IPushRules = JSON.parse(JSON.stringify(incomingRules)); // deep clone\n\n // These lines are mostly to make the tests happy. We shouldn't run into these\n // properties missing in practice.\n if (!newRules) newRules = {} as IPushRules;\n if (!newRules.global) newRules.global = {} as PushRuleSet;\n if (!newRules.global.override) newRules.global.override = [];\n if (!newRules.global.underride) newRules.global.underride = [];\n\n // Merge the client-level defaults with the ones from the server\n newRules.global.override = mergeRulesWithDefaults(\n PushRuleKind.Override,\n newRules.global.override,\n DEFAULT_OVERRIDE_RULES,\n EXPECTED_DEFAULT_OVERRIDE_RULE_IDS,\n );\n\n newRules.global.underride = mergeRulesWithDefaults(\n PushRuleKind.Underride,\n newRules.global.underride,\n DEFAULT_UNDERRIDE_RULES,\n EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS,\n );\n\n return newRules;\n }\n\n /**\n * Create a RegExp object for the given glob pattern with a single capture group around the pattern itself, caching the result.\n * No cache invalidation is present currently,\n * as this will be inherently bounded to the size of the user's own push rules.\n * @param pattern - the glob pattern to convert to a RegExp\n * @param alignToWordBoundary - whether to align the pattern to word boundaries,\n * as specified for `content.body` matches, will use lookaround assertions to ensure the match only includes the pattern\n * @param flags - the flags to pass to the RegExp constructor, defaults to case-insensitive\n */\n public static getPushRuleGlobRegex(pattern: string, alignToWordBoundary = false, flags = \"i\"): RegExp {\n const [prefix, suffix] = alignToWordBoundary ? [\"(?<=^|\\\\W)\", \"(?=\\\\W|$)\"] : [\"^\", \"$\"];\n const cacheKey = `${alignToWordBoundary}-${flags}-${pattern}`;\n\n if (!PushProcessor.cachedGlobToRegex[cacheKey]) {\n PushProcessor.cachedGlobToRegex[cacheKey] = new RegExp(\n prefix + \"(\" + globToRegexp(pattern) + \")\" + suffix,\n flags,\n );\n }\n return PushProcessor.cachedGlobToRegex[cacheKey];\n }\n\n /**\n * Pre-caches the parsed keys for push rules and cleans out any obsolete cache\n * entries. Should be called after push rules are updated.\n * @param newRules - The new push rules.\n */\n public updateCachedPushRuleKeys(newRules: IPushRules): void {\n // These lines are mostly to make the tests happy. We shouldn't run into these\n // properties missing in practice.\n if (!newRules) newRules = {} as IPushRules;\n if (!newRules.global) newRules.global = {} as PushRuleSet;\n if (!newRules.global.override) newRules.global.override = [];\n if (!newRules.global.room) newRules.global.room = [];\n if (!newRules.global.sender) newRules.global.sender = [];\n if (!newRules.global.underride) newRules.global.underride = [];\n\n // Process the 'key' property on event_match conditions pre-cache the\n // values and clean-out any unused values.\n const toRemoveKeys = new Set(this.parsedKeys.keys());\n for (const ruleset of [\n newRules.global.override,\n newRules.global.room,\n newRules.global.sender,\n newRules.global.underride,\n ]) {\n for (const rule of ruleset) {\n if (!rule.conditions) {\n continue;\n }\n\n for (const condition of rule.conditions) {\n if (condition.kind !== ConditionKind.EventMatch) {\n continue;\n }\n\n // Ensure we keep this key.\n toRemoveKeys.delete(condition.key);\n\n // Pre-process the key.\n this.parsedKeys.set(condition.key, PushProcessor.partsForDottedKey(condition.key));\n }\n }\n }\n // Any keys that were previously cached, but are no longer needed should\n // be removed.\n toRemoveKeys.forEach((k) => this.parsedKeys.delete(k));\n }\n\n private static cachedGlobToRegex: Record<string, RegExp> = {}; // $glob: RegExp\n\n private matchingRuleFromKindSet(ev: MatrixEvent, kindset: PushRuleSet): IAnnotatedPushRule | null {\n for (const kind of RULEKINDS_IN_ORDER) {\n const ruleset = kindset[kind];\n if (!ruleset) {\n continue;\n }\n\n for (const rule of ruleset) {\n if (!rule.enabled) {\n continue;\n }\n\n const rawrule = this.templateRuleToRaw(kind, rule);\n if (!rawrule) {\n continue;\n }\n\n if (this.ruleMatchesEvent(rawrule, ev)) {\n return {\n ...rule,\n kind,\n };\n }\n }\n }\n return null;\n }\n\n private templateRuleToRaw(\n kind: PushRuleKind,\n tprule: IPushRule,\n ): Pick<IPushRule, \"rule_id\" | \"actions\" | \"conditions\"> | null {\n const rawrule: Pick<IPushRule, \"rule_id\" | \"actions\" | \"conditions\"> = {\n rule_id: tprule.rule_id,\n actions: tprule.actions,\n conditions: [],\n };\n switch (kind) {\n case PushRuleKind.Underride:\n case PushRuleKind.Override:\n rawrule.conditions = tprule.conditions;\n break;\n case PushRuleKind.RoomSpecific:\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"room_id\",\n value: tprule.rule_id,\n });\n break;\n case PushRuleKind.SenderSpecific:\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"user_id\",\n value: tprule.rule_id,\n });\n break;\n case PushRuleKind.ContentSpecific:\n if (!tprule.pattern) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"content.body\",\n pattern: tprule.pattern,\n });\n break;\n }\n return rawrule;\n }\n\n private eventFulfillsCondition(cond: PushRuleCondition, ev: MatrixEvent): boolean {\n switch (cond.kind) {\n case ConditionKind.EventMatch:\n return this.eventFulfillsEventMatchCondition(cond, ev);\n case ConditionKind.EventPropertyIs:\n return this.eventFulfillsEventPropertyIsCondition(cond, ev);\n case ConditionKind.EventPropertyContains:\n return this.eventFulfillsEventPropertyContains(cond, ev);\n case ConditionKind.ContainsDisplayName:\n return this.eventFulfillsDisplayNameCondition(cond, ev);\n case ConditionKind.RoomMemberCount:\n return this.eventFulfillsRoomMemberCountCondition(cond, ev);\n case ConditionKind.SenderNotificationPermission:\n return this.eventFulfillsSenderNotifPermCondition(cond, ev);\n case ConditionKind.CallStarted:\n case ConditionKind.CallStartedPrefix:\n return this.eventFulfillsCallStartedCondition(cond, ev);\n }\n\n // unknown conditions: we previously matched all unknown conditions,\n // but given that rules can be added to the base rules on a server,\n // it's probably better to not match unknown conditions.\n return false;\n }\n\n private eventFulfillsSenderNotifPermCondition(\n cond: ISenderNotificationPermissionCondition,\n ev: MatrixEvent,\n ): boolean {\n const notifLevelKey = cond[\"key\"];\n if (!notifLevelKey) {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n if (!room?.currentState) {\n return false;\n }\n\n // Note that this should not be the current state of the room but the state at\n // the point the event is in the DAG. Unfortunately the js-sdk does not store\n // this.\n return room.currentState.mayTriggerNotifOfType(notifLevelKey, ev.getSender()!);\n }\n\n private eventFulfillsRoomMemberCountCondition(cond: IRoomMemberCountCondition, ev: MatrixEvent): boolean {\n if (!cond.is) {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n if (!room || !room.currentState || !room.currentState.members) {\n return false;\n }\n\n const memberCount = room.currentState.getJoinedMemberCount();\n\n const m = cond.is.match(/^([=<>]*)(\\d*)$/);\n if (!m) {\n return false;\n }\n const ineq = m[1];\n const rhs = parseInt(m[2]);\n if (isNaN(rhs)) {\n return false;\n }\n switch (ineq) {\n case \"\":\n case \"==\":\n return memberCount == rhs;\n case \"<\":\n return memberCount < rhs;\n case \">\":\n return memberCount > rhs;\n case \"<=\":\n return memberCount <= rhs;\n case \">=\":\n return memberCount >= rhs;\n default:\n return false;\n }\n }\n\n private eventFulfillsDisplayNameCondition(cond: IContainsDisplayNameCondition, ev: MatrixEvent): boolean {\n let content = ev.getContent();\n if (ev.isEncrypted() && ev.getClearContent()) {\n content = ev.getClearContent()!;\n }\n if (!content || !content.body || typeof content.body != \"string\") {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n const member = room?.currentState?.getMember(this.client.credentials.userId!);\n if (!member) {\n return false;\n }\n\n const displayName = member.name;\n\n // N.B. we can't use \\b as it chokes on unicode. however \\W seems to be okay\n // as shorthand for [^0-9A-Za-z_].\n const pat = new RegExp(\"(^|\\\\W)\" + escapeRegExp(displayName) + \"(\\\\W|$)\", \"i\");\n return content.body.search(pat) > -1;\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing against the condition's glob-based\n * pattern.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventMatchCondition(cond: IEventMatchCondition, ev: MatrixEvent): boolean {\n if (!cond.key) {\n return false;\n }\n\n const val = this.valueForDottedKey(cond.key, ev);\n if (typeof val !== \"string\") {\n return false;\n }\n\n // XXX This does not match in a case-insensitive manner.\n //\n // See https://spec.matrix.org/v1.5/client-server-api/#conditions-1\n if (cond.value) {\n return cond.value === val;\n }\n\n if (typeof cond.pattern !== \"string\") {\n return false;\n }\n\n // Align to word boundary on `content.body` matches, whole string otherwise\n // https://spec.matrix.org/v1.13/client-server-api/#conditions-1\n const regex = PushProcessor.getPushRuleGlobRegex(cond.pattern, cond.key === \"content.body\");\n return !!val.match(regex);\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing exactly against the condition's\n * value.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventPropertyIsCondition(cond: IEventPropertyIsCondition, ev: MatrixEvent): boolean {\n if (!cond.key || cond.value === undefined) {\n return false;\n }\n return cond.value === this.valueForDottedKey(cond.key, ev);\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing exactly against the condition's\n * value.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventPropertyContains(cond: IEventPropertyContainsCondition, ev: MatrixEvent): boolean {\n if (!cond.key || cond.value === undefined) {\n return false;\n }\n const val = this.valueForDottedKey(cond.key, ev);\n if (!Array.isArray(val)) {\n return false;\n }\n return val.includes(cond.value);\n }\n\n private eventFulfillsCallStartedCondition(\n _cond: ICallStartedCondition | ICallStartedPrefixCondition,\n ev: MatrixEvent,\n ): boolean {\n // Since servers don't support properly sending push notification\n // about MSC3401 call events, we do the handling ourselves\n return (\n [\"m.ring\", \"m.prompt\"].includes(ev.getContent()[\"m.intent\"]) &&\n !(\"m.terminated\" in ev.getContent()) &&\n (ev.getPrevContent()[\"m.terminated\"] !== ev.getContent()[\"m.terminated\"] ||\n deepCompare(ev.getPrevContent(), {}))\n );\n }\n\n /**\n * Parse the key into the separate fields to search by splitting on\n * unescaped \".\", and then removing any escape characters.\n *\n * @param str - The key of the push rule condition: a dotted field.\n * @returns The unescaped parts to fetch.\n * @internal\n */\n public static partsForDottedKey(str: string): string[] {\n const result: string[] = [];\n\n // The current field and whether the previous character was the escape\n // character (a backslash).\n let part = \"\";\n let escaped = false;\n\n // Iterate over each character, and decide whether to append to the current\n // part (following the escape rules) or to start a new part (based on the\n // field separator).\n for (const c of str) {\n // If the previous character was the escape character (a backslash)\n // then decide what to append to the current part.\n if (escaped) {\n if (c === \"\\\\\" || c === \".\") {\n // An escaped backslash or dot just gets added.\n part += c;\n } else {\n // A character that shouldn't be escaped gets the backslash prepended.\n part += \"\\\\\" + c;\n }\n // This always resets being escaped.\n escaped = false;\n continue;\n }\n\n if (c == \".\") {\n // The field separator creates a new part.\n result.push(part);\n part = \"\";\n } else if (c == \"\\\\\") {\n // A backslash adds no characters, but starts an escape sequence.\n escaped = true;\n } else {\n // Otherwise, just add the current character.\n part += c;\n }\n }\n\n // Ensure the final part is included. If there's an open escape sequence\n // it should be included.\n if (escaped) {\n part += \"\\\\\";\n }\n result.push(part);\n\n return result;\n }\n\n /**\n * For a dotted field and event, fetch the value at that position, if one\n * exists.\n *\n * @param key - The key of the push rule condition: a dotted field to fetch.\n * @param ev - The matrix event to fetch the field from.\n * @returns The value at the dotted path given by key.\n */\n private valueForDottedKey(key: string, ev: MatrixEvent): any {\n // The key should already have been parsed via updateCachedPushRuleKeys,\n // but if it hasn't (maybe via an old consumer of the SDK which hasn't\n // been updated?) then lazily calculate it here.\n let parts = this.parsedKeys.get(key);\n if (parts === undefined) {\n parts = PushProcessor.partsForDottedKey(key);\n this.parsedKeys.set(key, parts);\n }\n let val: any;\n\n // special-case the first component to deal with encrypted messages\n const firstPart = parts[0];\n let currentIndex = 0;\n if (firstPart === \"content\") {\n val = ev.getContent();\n ++currentIndex;\n } else if (firstPart === \"type\") {\n val = ev.getType();\n ++currentIndex;\n } else {\n // use the raw event for any other fields\n val = ev.event;\n }\n\n for (; currentIndex < parts.length; ++currentIndex) {\n // The previous iteration resulted in null or undefined, bail (and\n // avoid the type error of attempting to retrieve a property).\n if (isNullOrUndefined(val)) {\n return undefined;\n }\n\n const thisPart = parts[currentIndex];\n val = val[thisPart];\n }\n return val;\n }\n\n private matchingRuleForEventWithRulesets(ev: MatrixEvent, rulesets?: IPushRules): IAnnotatedPushRule | null {\n if (!rulesets) {\n return null;\n }\n\n if (ev.getSender() === this.client.getSafeUserId()) {\n return null;\n }\n\n return this.matchingRuleFromKindSet(ev, rulesets.global);\n }\n\n private pushActionsForEventAndRulesets(\n ev: MatrixEvent,\n rulesets?: IPushRules,\n ): {\n actions?: IActionsObject;\n rule?: IAnnotatedPushRule;\n } {\n const rule = this.matchingRuleForEventWithRulesets(ev, rulesets);\n if (!rule) {\n return {};\n }\n\n const actionObj = PushProcessor.actionListToActionsObject(rule.actions);\n\n // Some actions are implicit in some situations: we add those here\n if (actionObj.tweaks.highlight === undefined) {\n // if it isn't specified, highlight if it's a content\n // rule but otherwise not\n actionObj.tweaks.highlight = rule.kind == PushRuleKind.ContentSpecific;\n }\n\n return { actions: actionObj, rule };\n }\n\n public ruleMatchesEvent(rule: Partial<IPushRule> & Pick<IPushRule, \"conditions\">, ev: MatrixEvent): boolean {\n // Disable the deprecated mentions push rules if the new mentions property exists.\n if (\n this.client.supportsIntentionalMentions() &&\n ev.getContent()[\"m.mentions\"] !== undefined &&\n (rule.rule_id === RuleId.ContainsUserName ||\n rule.rule_id === RuleId.ContainsDisplayName ||\n rule.rule_id === RuleId.AtRoomNotification)\n ) {\n return false;\n }\n\n return !rule.conditions?.some((cond) => !this.eventFulfillsCondition(cond, ev));\n }\n\n /**\n * Get the user's push actions for the given event\n */\n public actionsForEvent(ev: MatrixEvent): IActionsObject {\n const { actions } = this.pushActionsForEventAndRulesets(ev, this.client.pushRules);\n return actions || ({} as IActionsObject);\n }\n\n public actionsAndRuleForEvent(ev: MatrixEvent): {\n actions?: IActionsObject;\n rule?: IAnnotatedPushRule;\n } {\n return this.pushActionsForEventAndRulesets(ev, this.client.pushRules);\n }\n\n /**\n * Get one of the users push rules by its ID\n *\n * @param ruleId - The ID of the rule to search for\n * @returns The push rule, or null if no such rule was found\n */\n public getPushRuleById(ruleId: string): IPushRule | null {\n const result = this.getPushRuleAndKindById(ruleId);\n return result?.rule ?? null;\n }\n\n /**\n * Get one of the users push rules by its ID\n *\n * @param ruleId - The ID of the rule to search for\n * @returns rule The push rule, or null if no such rule was found\n * @returns kind - The PushRuleKind of the rule to search for\n */\n public getPushRuleAndKindById(ruleId: string): { rule: IPushRule; kind: PushRuleKind } | null {\n for (const scope of [\"global\"] as const) {\n if (this.client.pushRules?.[scope] === undefined) continue;\n\n for (const kind of RULEKINDS_IN_ORDER) {\n if (this.client.pushRules[scope][kind] === undefined) continue;\n\n for (const rule of this.client.pushRules[scope][kind]!) {\n if (rule.rule_id === ruleId) return { rule, kind };\n }\n }\n }\n return null;\n }\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,WAAW,EAAEC,YAAY,EAAEC,YAAY,EAAEC,iBAAiB,QAAQ,YAAY;AACvF,SAASC,MAAM,QAAQ,aAAa;AAGpC,SACIC,aAAa,EAabC,kBAAkB,EAElBC,YAAY,EAEZC,MAAM,EACNC,SAAS,QACN,uBAAuB;AAC9B,SAASC,SAAS,QAAQ,mBAAmB;AAE7C,IAAMC,kBAAkB,GAAG,CACvBJ,YAAY,CAACK,QAAQ,EACrBL,YAAY,CAACM,eAAe,EAC5BN,YAAY,CAACO,YAAY,EACzBP,YAAY,CAACQ,cAAc,EAC3BR,YAAY,CAACS,SAAS,CACzB;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,sBAAiD,GAAG;EACtD,yBAAyB,EAAE;IACvB;IACAC,OAAO,EAAE,yBAAyB;IAClCC,OAAO,EAAE,IAAI;IACbC,OAAO,EAAE,IAAI;IACbC,UAAU,EAAE,CACR;MACIC,IAAI,EAAEjB,aAAa,CAACkB,eAAe;MACnCC,GAAG,EAAE,2BAA2B;MAChCC,KAAK,EAAE;IACX,CAAC,EACD;MACIH,IAAI,EAAEjB,aAAa,CAACqB,4BAA4B;MAChDF,GAAG,EAAE;IACT,CAAC,CACJ;IACDG,OAAO,EAAE,CACLrB,kBAAkB,CAACsB,MAAM,EACzB;MACIC,SAAS,EAAEpB,SAAS,CAACqB;IACzB,CAAC;EAET,CAAC;EACD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AC3C,MAAM,CAACyH,SAAS,CAAC;EACzE;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACWE,eAAeA,CAACvI,MAAc,EAAoB;IAAA,IAAAwI,YAAA;IACrD,IAAMxB,MAAM,GAAG,IAAI,CAACyB,sBAAsB,CAACzI,MAAM,CAAC;IAClD,QAAAwI,YAAA,GAAOxB,MAAM,aAANA,MAAM,uBAANA,MAAM,CAAEnH,IAAI,cAAA2I,YAAA,cAAAA,YAAA,GAAI,IAAI;EAC/B;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;EACWC,sBAAsBA,CAACzI,MAAc,EAAkD;IAC1F,KAAK,IAAM0I,KAAK,IAAI,CAAC,QAAQ,CAAC,EAAW;MAAA,IAAAC,qBAAA;MACrC,IAAI,EAAAA,qBAAA,OAAI,CAAC/H,MAAM,CAACyH,SAAS,cAAAM,qBAAA,uBAArBA,qBAAA,CAAwBD,KAAK,CAAC,MAAKrH,SAAS,EAAE;MAElD,KAAK,IAAMhE,IAAI,IAAIX,kBAAkB,EAAE;QACnC,IAAI,IAAI,CAACkE,MAAM,CAACyH,SAAS,CAACK,KAAK,CAAC,CAACrL,IAAI,CAAC,KAAKgE,SAAS,EAAE;QAEtD,KAAK,IAAMxB,IAAI,IAAI,IAAI,CAACe,MAAM,CAACyH,SAAS,CAACK,KAAK,CAAC,CAACrL,IAAI,CAAC,EAAG;UACpD,IAAIwC,IAAI,CAAC5C,OAAO,KAAK+C,MAAM,EAAE,OAAO;YAAEH,IAAI;YAAExC;UAAK,CAAC;QACtD;MACJ;IACJ;IACA,OAAO,IAAI;EACf;AACJ;AAACwD,eAAA,CAhmBYH,aAAa,uBA8IqC,CAAC,CAAC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"OutgoingRequestProcessor.d.ts","sourceRoot":"","sources":["../../src/rust-crypto/OutgoingRequestProcessor.ts"],"names":[],"mappings":"AAgBA,OAAO,EAKH,KAAK,UAAU,EACf,KAAK,eAAe,EACpB,0BAA0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KAAE,CAAC;IAG3D,mBAAmB,CAAC,CAAC,EAC9B,GAAG,EAAE,eAAe,GAAG,wBAAwB,GAAG,0BAA0B,EAC5E,WAAW,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,GAChC,OAAO,CAAC,IAAI,CAAC;IAsEhB;;;;;OAKG;YACW,mBAAmB;YAsBnB,kBAAkB;YA2BlB,gBAAgB;YAyBhB,cAAc;CAuB/B"}
@@ -180,7 +180,12 @@ export class OutgoingRequestProcessor {
180
180
  "Accept": "application/json"
181
181
  },
182
182
  // we use the full prefix
183
- prefix: ""
183
+ prefix: "",
184
+ // We set a timeout of 60 seconds to guard against requests getting stuck forever and wedging the
185
+ // request loop (cf https://github.com/element-hq/element-web/issues/29534).
186
+ //
187
+ // (XXX: should we do this in the whole of the js-sdk?)
188
+ localTimeoutMs: 60000
184
189
  };
185
190
  return yield _this5.http.authedRequest(method, path, queryParams, body, opts);
186
191
  })();
@@ -1 +1 @@
1
- {"version":3,"file":"OutgoingRequestProcessor.js","names":["KeysBackupRequest","KeysClaimRequest","KeysQueryRequest","KeysUploadRequest","PutDehydratedDeviceRequest","RoomMessageRequest","SignatureUploadRequest","ToDeviceRequest","UploadSigningKeysRequest","logger","calculateRetryBackoff","Method","logDuration","sleep","ToDeviceMessageId","UnstablePrefix","DehydrationUnstablePrefix","OutgoingRequestProcessor","constructor","olmMachine","http","makeOutgoingRequest","msg","uiaCallback","_this","_asyncToGenerator","resp","requestWithRetry","Post","body","Put","version","sendToDeviceRequest","path","concat","encodeURIComponent","room_id","event_type","txn_id","makeRequestWithUIA","rawJsonRequest","warn","Object","getPrototypeOf","id","type","markRequestAsSent","e","Error","message","log","trace","request","_this2","parsedBody","JSON","parse","messageList","userId","perUserMessages","entries","messages","deviceId","push","info","method","queryParams","_this3","makeRequest","_ref2","auth","newBody","_objectSpread","stringify","_x","apply","arguments","_this4","currentRetryCount","backoff","_this5","opts","json","headers","prefix","authedRequest"],"sources":["../../src/rust-crypto/OutgoingRequestProcessor.ts"],"sourcesContent":["/*\nCopyright 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\nimport {\n KeysBackupRequest,\n KeysClaimRequest,\n KeysQueryRequest,\n KeysUploadRequest,\n type OlmMachine,\n type OutgoingRequest,\n PutDehydratedDeviceRequest,\n RoomMessageRequest,\n SignatureUploadRequest,\n ToDeviceRequest,\n UploadSigningKeysRequest,\n} from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport { logger } from \"../logger.ts\";\nimport { calculateRetryBackoff, type IHttpOpts, type MatrixHttpApi, Method } from \"../http-api/index.ts\";\nimport { logDuration, type QueryDict, sleep } from \"../utils.ts\";\nimport { type AuthDict, type UIAuthCallback } from \"../interactive-auth.ts\";\nimport { ToDeviceMessageId } from \"../@types/event.ts\";\nimport { UnstablePrefix as DehydrationUnstablePrefix } from \"./DehydratedDeviceManager.ts\";\n\n/**\n * OutgoingRequestManager: turns `OutgoingRequest`s from the rust sdk into HTTP requests\n *\n * We have one of these per `RustCrypto` (and hence per `MatrixClient`), not that it does anything terribly complicated.\n * It's responsible for:\n *\n * * holding the reference to the `MatrixHttpApi`\n * * turning `OutgoingRequest`s from the rust backend into HTTP requests, and sending them\n * * sending the results of such requests back to the rust backend.\n *\n * @internal\n */\nexport class OutgoingRequestProcessor {\n public constructor(\n private readonly olmMachine: OlmMachine,\n private readonly http: MatrixHttpApi<IHttpOpts & { onlyData: true }>,\n ) {}\n\n public async makeOutgoingRequest<T>(\n msg: OutgoingRequest | UploadSigningKeysRequest | PutDehydratedDeviceRequest,\n uiaCallback?: UIAuthCallback<T>,\n ): Promise<void> {\n let resp: string;\n\n /* refer https://docs.rs/matrix-sdk-crypto/0.6.0/matrix_sdk_crypto/requests/enum.OutgoingRequests.html\n * for the complete list of request types\n */\n if (msg instanceof KeysUploadRequest) {\n resp = await this.requestWithRetry(Method.Post, \"/_matrix/client/v3/keys/upload\", {}, msg.body);\n } else if (msg instanceof KeysQueryRequest) {\n resp = await this.requestWithRetry(Method.Post, \"/_matrix/client/v3/keys/query\", {}, msg.body);\n } else if (msg instanceof KeysClaimRequest) {\n resp = await this.requestWithRetry(Method.Post, \"/_matrix/client/v3/keys/claim\", {}, msg.body);\n } else if (msg instanceof SignatureUploadRequest) {\n resp = await this.requestWithRetry(Method.Post, \"/_matrix/client/v3/keys/signatures/upload\", {}, msg.body);\n } else if (msg instanceof KeysBackupRequest) {\n resp = await this.requestWithRetry(\n Method.Put,\n \"/_matrix/client/v3/room_keys/keys\",\n { version: msg.version },\n msg.body,\n );\n } else if (msg instanceof ToDeviceRequest) {\n resp = await this.sendToDeviceRequest(msg);\n } else if (msg instanceof RoomMessageRequest) {\n const path =\n `/_matrix/client/v3/rooms/${encodeURIComponent(msg.room_id)}/send/` +\n `${encodeURIComponent(msg.event_type)}/${encodeURIComponent(msg.txn_id)}`;\n resp = await this.requestWithRetry(Method.Put, path, {}, msg.body);\n } else if (msg instanceof UploadSigningKeysRequest) {\n await this.makeRequestWithUIA(\n Method.Post,\n \"/_matrix/client/v3/keys/device_signing/upload\",\n {},\n msg.body,\n uiaCallback,\n );\n // SigningKeysUploadRequest does not implement OutgoingRequest and does not need to be marked as sent.\n return;\n } else if (msg instanceof PutDehydratedDeviceRequest) {\n const path = DehydrationUnstablePrefix + \"/dehydrated_device\";\n await this.rawJsonRequest(Method.Put, path, {}, msg.body);\n // PutDehydratedDeviceRequest does not implement OutgoingRequest and does not need to be marked as sent.\n return;\n } else {\n logger.warn(\"Unsupported outgoing message\", Object.getPrototypeOf(msg));\n resp = \"\";\n }\n\n if (msg.id) {\n try {\n await logDuration(logger, `Mark Request as sent ${msg.type}`, async () => {\n await this.olmMachine.markRequestAsSent(msg.id!, msg.type, resp);\n });\n } catch (e) {\n // Ignore errors which are caused by the olmMachine having been freed. The exact error message depends\n // on whether we are using a release or develop build of rust-sdk-crypto-wasm.\n if (\n e instanceof Error &&\n (e.message === \"Attempt to use a moved value\" || e.message === \"null pointer passed to rust\")\n ) {\n logger.log(`Ignoring error '${e.message}': client is likely shutting down`);\n } else {\n throw e;\n }\n }\n } else {\n logger.trace(`Outgoing request type:${msg.type} does not have an ID`);\n }\n }\n\n /**\n * Send the HTTP request for a `ToDeviceRequest`\n *\n * @param request - request to send\n * @returns JSON-serialized body of the response, if successful\n */\n private async sendToDeviceRequest(request: ToDeviceRequest): Promise<string> {\n // a bit of extra logging, to help trace to-device messages through the system\n const parsedBody: { messages: Record<string, Record<string, Record<string, any>>> } = JSON.parse(request.body);\n\n const messageList = [];\n for (const [userId, perUserMessages] of Object.entries(parsedBody.messages)) {\n for (const [deviceId, message] of Object.entries(perUserMessages)) {\n messageList.push(`${userId}/${deviceId} (msgid ${message[ToDeviceMessageId]})`);\n }\n }\n\n logger.info(\n `Sending batch of to-device messages. type=${request.event_type} txnid=${request.txn_id}`,\n messageList,\n );\n\n const path =\n `/_matrix/client/v3/sendToDevice/${encodeURIComponent(request.event_type)}/` +\n encodeURIComponent(request.txn_id);\n return await this.requestWithRetry(Method.Put, path, {}, request.body);\n }\n\n private async makeRequestWithUIA<T>(\n method: Method,\n path: string,\n queryParams: QueryDict,\n body: string,\n uiaCallback: UIAuthCallback<T> | undefined,\n ): Promise<string> {\n if (!uiaCallback) {\n return await this.requestWithRetry(method, path, queryParams, body);\n }\n\n const parsedBody = JSON.parse(body);\n const makeRequest = async (auth: AuthDict | null): Promise<T> => {\n const newBody: Record<string, any> = {\n ...parsedBody,\n };\n if (auth !== null) {\n newBody.auth = auth;\n }\n const resp = await this.requestWithRetry(method, path, queryParams, JSON.stringify(newBody));\n return JSON.parse(resp) as T;\n };\n\n const resp = await uiaCallback(makeRequest);\n return JSON.stringify(resp);\n }\n\n private async requestWithRetry(\n method: Method,\n path: string,\n queryParams: QueryDict,\n body: string,\n ): Promise<string> {\n let currentRetryCount = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n return await this.rawJsonRequest(method, path, queryParams, body);\n } catch (e) {\n currentRetryCount++;\n const backoff = calculateRetryBackoff(e, currentRetryCount, true);\n if (backoff < 0) {\n // Max number of retries reached, or error is not retryable. rethrow the error\n throw e;\n }\n // wait for the specified time and then retry the request\n await sleep(backoff);\n }\n }\n }\n\n private async rawJsonRequest(method: Method, path: string, queryParams: QueryDict, body: string): Promise<string> {\n const opts = {\n // inhibit the JSON stringification and parsing within HttpApi.\n json: false,\n\n // nevertheless, we are sending, and accept, JSON.\n headers: {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\",\n },\n\n // we use the full prefix\n prefix: \"\",\n };\n\n return await this.http.authedRequest<string>(method, path, queryParams, body, opts);\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SACIA,iBAAiB,EACjBC,gBAAgB,EAChBC,gBAAgB,EAChBC,iBAAiB,EAGjBC,0BAA0B,EAC1BC,kBAAkB,EAClBC,sBAAsB,EACtBC,eAAe,EACfC,wBAAwB,QACrB,oCAAoC;AAE3C,SAASC,MAAM,QAAQ,cAAc;AACrC,SAASC,qBAAqB,EAAsCC,MAAM,QAAQ,sBAAsB;AACxG,SAASC,WAAW,EAAkBC,KAAK,QAAQ,aAAa;AAEhE,SAASC,iBAAiB,QAAQ,oBAAoB;AACtD,SAASC,cAAc,IAAIC,yBAAyB,QAAQ,8BAA8B;;AAE1F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,wBAAwB,CAAC;EAC3BC,WAAWA,CACGC,UAAsB,EACtBC,IAAmD,EACtE;IAAA,KAFmBD,UA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;EAChC;EAEcC,gBAAgBA,CAC1BsC,MAAc,EACdhC,IAAY,EACZiC,WAAsB,EACtBrC,IAAY,EACG;IAAA,IAAAgD,MAAA;IAAA,OAAApD,iBAAA;MACf,IAAIqD,iBAAiB,GAAG,CAAC;;MAEzB;MACA,OAAO,IAAI,EAAE;QACT,IAAI;UACA,aAAaD,MAAI,CAACrC,cAAc,CAACyB,MAAM,EAAEhC,IAAI,EAAEiC,WAAW,EAAErC,IAAI,CAAC;QACrE,CAAC,CAAC,OAAOkB,CAAC,EAAE;UACR+B,iBAAiB,EAAE;UACnB,IAAMC,OAAO,GAAGrE,qBAAqB,CAACqC,CAAC,EAAE+B,iBAAiB,EAAE,IAAI,CAAC;UACjE,IAAIC,OAAO,GAAG,CAAC,EAAE;YACb;YACA,MAAMhC,CAAC;UACX;UACA;UACA,MAAMlC,KAAK,CAACkE,OAAO,CAAC;QACxB;MACJ;IAAC;EACL;EAEcvC,cAAcA,CAACyB,MAAc,EAAEhC,IAAY,EAAEiC,WAAsB,EAAErC,IAAY,EAAmB;IAAA,IAAAmD,MAAA;IAAA,OAAAvD,iBAAA;MAC9G,IAAMwD,IAAI,GAAG;QACT;QACAC,IAAI,EAAE,KAAK;QAEX;QACAC,OAAO,EAAE;UACL,cAAc,EAAE,kBAAkB;UAClC,QAAQ,EAAE;QACd,CAAC;QAED;QACAC,MAAM,EAAE;MACZ,CAAC;MAED,aAAaJ,MAAI,CAAC5D,IAAI,CAACiE,aAAa,CAASpB,MAAM,EAAEhC,IAAI,EAAEiC,WAAW,EAAErC,IAAI,EAAEoD,IAAI,CAAC;IAAC;EACxF;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"OutgoingRequestProcessor.js","names":["KeysBackupRequest","KeysClaimRequest","KeysQueryRequest","KeysUploadRequest","PutDehydratedDeviceRequest","RoomMessageRequest","SignatureUploadRequest","ToDeviceRequest","UploadSigningKeysRequest","logger","calculateRetryBackoff","Method","logDuration","sleep","ToDeviceMessageId","UnstablePrefix","DehydrationUnstablePrefix","OutgoingRequestProcessor","constructor","olmMachine","http","makeOutgoingRequest","msg","uiaCallback","_this","_asyncToGenerator","resp","requestWithRetry","Post","body","Put","version","sendToDeviceRequest","path","concat","encodeURIComponent","room_id","event_type","txn_id","makeRequestWithUIA","rawJsonRequest","warn","Object","getPrototypeOf","id","type","markRequestAsSent","e","Error","message","log","trace","request","_this2","parsedBody","JSON","parse","messageList","userId","perUserMessages","entries","messages","deviceId","push","info","method","queryParams","_this3","makeRequest","_ref2","auth","newBody","_objectSpread","stringify","_x","apply","arguments","_this4","currentRetryCount","backoff","_this5","opts","json","headers","prefix","localTimeoutMs","authedRequest"],"sources":["../../src/rust-crypto/OutgoingRequestProcessor.ts"],"sourcesContent":["/*\nCopyright 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\nimport {\n KeysBackupRequest,\n KeysClaimRequest,\n KeysQueryRequest,\n KeysUploadRequest,\n type OlmMachine,\n type OutgoingRequest,\n PutDehydratedDeviceRequest,\n RoomMessageRequest,\n SignatureUploadRequest,\n ToDeviceRequest,\n UploadSigningKeysRequest,\n} from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport { logger } from \"../logger.ts\";\nimport { calculateRetryBackoff, type IHttpOpts, type MatrixHttpApi, Method } from \"../http-api/index.ts\";\nimport { logDuration, type QueryDict, sleep } from \"../utils.ts\";\nimport { type AuthDict, type UIAuthCallback } from \"../interactive-auth.ts\";\nimport { ToDeviceMessageId } from \"../@types/event.ts\";\nimport { UnstablePrefix as DehydrationUnstablePrefix } from \"./DehydratedDeviceManager.ts\";\n\n/**\n * OutgoingRequestManager: turns `OutgoingRequest`s from the rust sdk into HTTP requests\n *\n * We have one of these per `RustCrypto` (and hence per `MatrixClient`), not that it does anything terribly complicated.\n * It's responsible for:\n *\n * * holding the reference to the `MatrixHttpApi`\n * * turning `OutgoingRequest`s from the rust backend into HTTP requests, and sending them\n * * sending the results of such requests back to the rust backend.\n *\n * @internal\n */\nexport class OutgoingRequestProcessor {\n public constructor(\n private readonly olmMachine: OlmMachine,\n private readonly http: MatrixHttpApi<IHttpOpts & { onlyData: true }>,\n ) {}\n\n public async makeOutgoingRequest<T>(\n msg: OutgoingRequest | UploadSigningKeysRequest | PutDehydratedDeviceRequest,\n uiaCallback?: UIAuthCallback<T>,\n ): Promise<void> {\n let resp: string;\n\n /* refer https://docs.rs/matrix-sdk-crypto/0.6.0/matrix_sdk_crypto/requests/enum.OutgoingRequests.html\n * for the complete list of request types\n */\n if (msg instanceof KeysUploadRequest) {\n resp = await this.requestWithRetry(Method.Post, \"/_matrix/client/v3/keys/upload\", {}, msg.body);\n } else if (msg instanceof KeysQueryRequest) {\n resp = await this.requestWithRetry(Method.Post, \"/_matrix/client/v3/keys/query\", {}, msg.body);\n } else if (msg instanceof KeysClaimRequest) {\n resp = await this.requestWithRetry(Method.Post, \"/_matrix/client/v3/keys/claim\", {}, msg.body);\n } else if (msg instanceof SignatureUploadRequest) {\n resp = await this.requestWithRetry(Method.Post, \"/_matrix/client/v3/keys/signatures/upload\", {}, msg.body);\n } else if (msg instanceof KeysBackupRequest) {\n resp = await this.requestWithRetry(\n Method.Put,\n \"/_matrix/client/v3/room_keys/keys\",\n { version: msg.version },\n msg.body,\n );\n } else if (msg instanceof ToDeviceRequest) {\n resp = await this.sendToDeviceRequest(msg);\n } else if (msg instanceof RoomMessageRequest) {\n const path =\n `/_matrix/client/v3/rooms/${encodeURIComponent(msg.room_id)}/send/` +\n `${encodeURIComponent(msg.event_type)}/${encodeURIComponent(msg.txn_id)}`;\n resp = await this.requestWithRetry(Method.Put, path, {}, msg.body);\n } else if (msg instanceof UploadSigningKeysRequest) {\n await this.makeRequestWithUIA(\n Method.Post,\n \"/_matrix/client/v3/keys/device_signing/upload\",\n {},\n msg.body,\n uiaCallback,\n );\n // SigningKeysUploadRequest does not implement OutgoingRequest and does not need to be marked as sent.\n return;\n } else if (msg instanceof PutDehydratedDeviceRequest) {\n const path = DehydrationUnstablePrefix + \"/dehydrated_device\";\n await this.rawJsonRequest(Method.Put, path, {}, msg.body);\n // PutDehydratedDeviceRequest does not implement OutgoingRequest and does not need to be marked as sent.\n return;\n } else {\n logger.warn(\"Unsupported outgoing message\", Object.getPrototypeOf(msg));\n resp = \"\";\n }\n\n if (msg.id) {\n try {\n await logDuration(logger, `Mark Request as sent ${msg.type}`, async () => {\n await this.olmMachine.markRequestAsSent(msg.id!, msg.type, resp);\n });\n } catch (e) {\n // Ignore errors which are caused by the olmMachine having been freed. The exact error message depends\n // on whether we are using a release or develop build of rust-sdk-crypto-wasm.\n if (\n e instanceof Error &&\n (e.message === \"Attempt to use a moved value\" || e.message === \"null pointer passed to rust\")\n ) {\n logger.log(`Ignoring error '${e.message}': client is likely shutting down`);\n } else {\n throw e;\n }\n }\n } else {\n logger.trace(`Outgoing request type:${msg.type} does not have an ID`);\n }\n }\n\n /**\n * Send the HTTP request for a `ToDeviceRequest`\n *\n * @param request - request to send\n * @returns JSON-serialized body of the response, if successful\n */\n private async sendToDeviceRequest(request: ToDeviceRequest): Promise<string> {\n // a bit of extra logging, to help trace to-device messages through the system\n const parsedBody: { messages: Record<string, Record<string, Record<string, any>>> } = JSON.parse(request.body);\n\n const messageList = [];\n for (const [userId, perUserMessages] of Object.entries(parsedBody.messages)) {\n for (const [deviceId, message] of Object.entries(perUserMessages)) {\n messageList.push(`${userId}/${deviceId} (msgid ${message[ToDeviceMessageId]})`);\n }\n }\n\n logger.info(\n `Sending batch of to-device messages. type=${request.event_type} txnid=${request.txn_id}`,\n messageList,\n );\n\n const path =\n `/_matrix/client/v3/sendToDevice/${encodeURIComponent(request.event_type)}/` +\n encodeURIComponent(request.txn_id);\n return await this.requestWithRetry(Method.Put, path, {}, request.body);\n }\n\n private async makeRequestWithUIA<T>(\n method: Method,\n path: string,\n queryParams: QueryDict,\n body: string,\n uiaCallback: UIAuthCallback<T> | undefined,\n ): Promise<string> {\n if (!uiaCallback) {\n return await this.requestWithRetry(method, path, queryParams, body);\n }\n\n const parsedBody = JSON.parse(body);\n const makeRequest = async (auth: AuthDict | null): Promise<T> => {\n const newBody: Record<string, any> = {\n ...parsedBody,\n };\n if (auth !== null) {\n newBody.auth = auth;\n }\n const resp = await this.requestWithRetry(method, path, queryParams, JSON.stringify(newBody));\n return JSON.parse(resp) as T;\n };\n\n const resp = await uiaCallback(makeRequest);\n return JSON.stringify(resp);\n }\n\n private async requestWithRetry(\n method: Method,\n path: string,\n queryParams: QueryDict,\n body: string,\n ): Promise<string> {\n let currentRetryCount = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n return await this.rawJsonRequest(method, path, queryParams, body);\n } catch (e) {\n currentRetryCount++;\n const backoff = calculateRetryBackoff(e, currentRetryCount, true);\n if (backoff < 0) {\n // Max number of retries reached, or error is not retryable. rethrow the error\n throw e;\n }\n // wait for the specified time and then retry the request\n await sleep(backoff);\n }\n }\n }\n\n private async rawJsonRequest(method: Method, path: string, queryParams: QueryDict, body: string): Promise<string> {\n const opts = {\n // inhibit the JSON stringification and parsing within HttpApi.\n json: false,\n\n // nevertheless, we are sending, and accept, JSON.\n headers: {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\",\n },\n\n // we use the full prefix\n prefix: \"\",\n\n // We set a timeout of 60 seconds to guard against requests getting stuck forever and wedging the\n // request loop (cf https://github.com/element-hq/element-web/issues/29534).\n //\n // (XXX: should we do this in the whole of the js-sdk?)\n localTimeoutMs: 60000,\n };\n\n return await this.http.authedRequest<string>(method, path, queryParams, body, opts);\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A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D,MAAA;IAAA,OAAAvD,iBAAA;MAC9G,IAAMwD,IAAI,GAAG;QACT;QACAC,IAAI,EAAE,KAAK;QAEX;QACAC,OAAO,EAAE;UACL,cAAc,EAAE,kBAAkB;UAClC,QAAQ,EAAE;QACd,CAAC;QAED;QACAC,MAAM,EAAE,EAAE;QAEV;QACA;QACA;QACA;QACAC,cAAc,EAAE;MACpB,CAAC;MAED,aAAaL,MAAI,CAAC5D,IAAI,CAACkE,aAAa,CAASrB,MAAM,EAAEhC,IAAI,EAAEiC,WAAW,EAAErC,IAAI,EAAEoD,IAAI,CAAC;IAAC;EACxF;AACJ","ignoreList":[]}
@@ -438,11 +438,14 @@ export declare class RustCrypto extends TypedEventEmitter<RustCryptoEvents, Cryp
438
438
  onCryptoEvent(room: Room, event: MatrixEvent): Promise<void>;
439
439
  /** called by the sync loop after processing each sync.
440
440
  *
441
- * TODO: figure out something equivalent for sliding sync.
442
441
  *
443
442
  * @param syncState - information on the completed sync.
444
443
  */
445
444
  onSyncCompleted(syncState: OnSyncCompletedData): void;
445
+ /**
446
+ * Implementation of {@link CryptoApi#markAllTrackedUsersAsDirty}.
447
+ */
448
+ markAllTrackedUsersAsDirty(): Promise<void>;
446
449
  /**
447
450
  * Handle an incoming m.key.verification.request event, received either in-room or in a to-device message.
448
451
  *