element-web-synapse01pim.gr.jp

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

sw.js.map (77625B)


      1 {"version":3,"file":"sw.js","mappings":"oGAAA,IAAAA,EAAAC,GAMA,WACA,aAEQD,EAMP,WAID,IAAAE,EAAA,aACAC,EAAA,YACAC,SAAAC,SAAAF,UAAAE,OAAAC,YAAAH,GACA,kBAAAI,KAAAF,OAAAC,UAAAE,WAGAC,EAAA,CACA,QACA,QACA,OACA,OACA,SAGAC,EAAA,GACAC,EAAA,KAGA,SAAAC,EAAAC,EAAAC,GACA,IAAAC,EAAAF,EAAAC,GACA,sBAAAC,EAAAC,KACA,OAAAD,EAAAC,KAAAH,GAEA,IACA,OAAAI,SAAAC,UAAAF,KAAAG,KAAAJ,EAAAF,EACA,CAAc,MAAAO,GAEd,kBACA,OAAAH,SAAAC,UAAAG,MAAAA,MAAAN,EAAA,CAAAF,EAAAS,WACA,CACA,CAEA,CAGA,SAAAC,IACAC,QAAAC,MACAD,QAAAC,IAAAJ,MACAG,QAAAC,IAAAJ,MAAAG,QAAAF,WAGAL,SAAAC,UAAAG,MAAAA,MAAAG,QAAAC,IAAA,CAAAD,QAAAF,aAGAE,QAAAE,OAAAF,QAAAE,OACA,CAIA,SAAAC,EAAAb,GAKA,MAJA,UAAAA,IACAA,EAAA,cAGAU,UAAArB,IAEU,UAAAW,GAAAV,EACVmB,OACUK,IAAAJ,QAAAV,GACVF,EAAAY,QAAAV,QACUc,IAAAJ,QAAAC,IACVb,EAAAY,QAAA,OAEAtB,EAEA,CAIA,SAAA2B,IAKA,IAHA,IAAAC,EAAAC,KAAAC,WAGAC,EAAA,EAAwBA,EAAAxB,EAAAyB,OAAuBD,IAAA,CAC/C,IAAAnB,EAAAL,EAAAwB,GACAF,KAAAjB,GAAAmB,EAAAH,EACA5B,EACA6B,KAAAI,cAAArB,EAAAgB,EAAAC,KAAAK,KACA,CAMA,GAHAL,KAAAN,IAAAM,KAAAM,aAGAb,UAAArB,GAAA2B,EAAAC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AOhP,GACL,MAAM,IAAI0H,MAAM,qCAAsC,CAAEuI,MAAOjQ,GACnE,CACJ,CAzE6BkQ,CAAYrB,GAIzB,KAD8BV,EAAIO,SAAW,IAAIN,IAAII,EAAKQ,YAAYN,QAElE,MAAM,IAAIhH,MAAM,wEAwBpCF,eAAyC2I,EAAsB1C,GAAqC,IAAA2C,EAAAC,EAEhG,IAAkC,QAA9BD,EAAA7C,EAAiB4C,UAAa,IAAAC,OAAA,EAA9BA,EAAgCE,oBAAoB,IAAIpJ,MAAOqJ,UAC/D,OAGJ,MAAMC,EAAShD,EAAoBC,GAC7BgD,cAAwBC,MAAM,GAAGP,4BAAwCK,IAASG,OACxFvQ,QAAQC,IAAI,2CAA2C8P,OAAkBS,KAAKC,UAAUJ,MAExFlD,EAAiB4C,GAAgB,CAC7BW,oBAAqBC,QAAQN,SAAkB,QAAVJ,EAARI,EAAUA,gBAAQ,IAAAJ,OAAA,EAAlBA,EAAoBW,SAAS,UAC1DV,mBAAmB,IAAIpJ,MAAOqJ,UAAY,MAE9CnQ,QAAQC,IACJ,gDAAgD8P,OAAkBS,KAAKC,UAAUtD,EAAiB4C,MAE1G,CArCsBc,CAA0BxC,EAAOD,EAAKf,aAGxCF,EAAiBkB,GAAOqC,qBAAuBtC,EAAKf,cACpDU,EAAI+C,KAAO/C,EAAI+C,KAAKjH,QAAQ,sBAAuB,wBAE3D,CAAE,MAAOkH,GAEL3C,OAAOhO,EACPJ,QAAQqG,MAAM,gCAAiC0K,EACnD,CAKA,OAAOT,MAAMvC,EAAKX,EAAwB,QAAL4D,EAAC5C,SAAI,IAAA4C,OAAA,EAAJA,EAAM3D,aAC/C,EArCD","sources":["webpack://element-web/../node_modules/.pnpm/source-map-loader@5.0.0_webpack@5.108.4/node_modules/source-map-loader/dist/node_modules/.pnpm/loglevel@1.9.2/node_modules/loglevel/lib/loglevel.js","webpack://element-web/webpack/bootstrap","webpack://element-web/webpack/runtime/compat get default export","webpack://element-web/webpack/runtime/define property getters","webpack://element-web/webpack/runtime/global","webpack://element-web/webpack/runtime/hasOwnProperty shorthand","webpack://element-web/webpack/runtime/compat","webpack://element-web/./src/utils/StorageAccess.ts","webpack://element-web/../node_modules/.pnpm/matrix-js-sdk@42.0.0/node_modules/matrix-js-sdk/src/logger.ts","webpack://element-web/../node_modules/.pnpm/matrix-js-sdk@42.0.0/node_modules/matrix-js-sdk/src/base64.ts","webpack://element-web/../node_modules/.pnpm/matrix-js-sdk@42.0.0/node_modules/matrix-js-sdk/src/utils/internal/deriveKeys.ts","webpack://element-web/../node_modules/.pnpm/matrix-js-sdk@42.0.0/node_modules/matrix-js-sdk/src/utils/decryptAESSecretStorageItem.ts","webpack://element-web/./src/utils/tokens/tokens.ts","webpack://element-web/./src/utils/tokens/pickling.ts","webpack://element-web/./src/serviceworker/index.ts"],"sourcesContent":["/*\n* loglevel - https://github.com/pimterry/loglevel\n*\n* Copyright (c) 2013 Tim Perry\n* Licensed under the MIT license.\n*/\n(function (root, definition) {\n    \"use strict\";\n    if (typeof define === 'function' && define.amd) {\n        define(definition);\n    } else if (typeof module === 'object' && module.exports) {\n        module.exports = definition();\n    } else {\n        root.log = definition();\n    }\n}(this, function () {\n    \"use strict\";\n\n    // Slightly dubious tricks to cut down minimized file size\n    var noop = function() {};\n    var undefinedType = \"undefined\";\n    var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (\n        /Trident\\/|MSIE /.test(window.navigator.userAgent)\n    );\n\n    var logMethods = [\n        \"trace\",\n        \"debug\",\n        \"info\",\n        \"warn\",\n        \"error\"\n    ];\n\n    var _loggersByName = {};\n    var defaultLogger = null;\n\n    // Cross-browser bind equivalent that works at least back to IE6\n    function bindMethod(obj, methodName) {\n        var method = obj[methodName];\n        if (typeof method.bind === 'function') {\n            return method.bind(obj);\n        } else {\n            try {\n                return Function.prototype.bind.call(method, obj);\n            } catch (e) {\n                // Missing bind shim or IE8 + Modernizr, fallback to wrapping\n                return function() {\n                    return Function.prototype.apply.apply(method, [obj, arguments]);\n                };\n            }\n        }\n    }\n\n    // Trace() doesn't print the message in IE, so for that case we need to wrap it\n    function traceForIE() {\n        if (console.log) {\n            if (console.log.apply) {\n                console.log.apply(console, arguments);\n            } else {\n                // In old IE, native console methods themselves don't have apply().\n                Function.prototype.apply.apply(console.log, [console, arguments]);\n            }\n        }\n        if (console.trace) console.trace();\n    }\n\n    // Build the best logging method possible for this env\n    // Wherever possible we want to bind, not wrap, to preserve stack traces\n    function realMethod(methodName) {\n        if (methodName === 'debug') {\n            methodName = 'log';\n        }\n\n        if (typeof console === undefinedType) {\n            return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives\n        } else if (methodName === 'trace' && isIE) {\n            return traceForIE;\n        } else if (console[methodName] !== undefined) {\n            return bindMethod(console, methodName);\n        } else if (console.log !== undefined) {\n            return bindMethod(console, 'log');\n        } else {\n            return noop;\n        }\n    }\n\n    // These private functions always need `this` to be set properly\n\n    function replaceLoggingMethods() {\n        /*jshint validthis:true */\n        var level = this.getLevel();\n\n        // Replace the actual methods.\n        for (var i = 0; i < logMethods.length; i++) {\n            var methodName = logMethods[i];\n            this[methodName] = (i < level) ?\n                noop :\n                this.methodFactory(methodName, level, this.name);\n        }\n\n        // Define log.log as an alias for log.debug\n        this.log = this.debug;\n\n        // Return any important warnings.\n        if (typeof console === undefinedType && level < this.levels.SILENT) {\n            return \"No console available for logging\";\n        }\n    }\n\n    // In old IE versions, the console isn't present until you first open it.\n    // We build realMethod() replacements here that regenerate logging methods\n    function enableLoggingWhenConsoleArrives(methodName) {\n        return function () {\n            if (typeof console !== undefinedType) {\n                replaceLoggingMethods.call(this);\n                this[methodName].apply(this, arguments);\n            }\n        };\n    }\n\n    // By default, we use closely bound real methods wherever possible, and\n    // otherwise we wait for a console to appear, and then try again.\n    function defaultMethodFactory(methodName, _level, _loggerName) {\n        /*jshint validthis:true */\n        return realMethod(methodName) ||\n               enableLoggingWhenConsoleArrives.apply(this, arguments);\n    }\n\n    function Logger(name, factory) {\n      // Private instance variables.\n      var self = this;\n      /**\n       * The level inherited from a parent logger (or a global default). We\n       * cache this here rather than delegating to the parent so that it stays\n       * in sync with the actual logging methods that we have installed (the\n       * parent could change levels but we might not have rebuilt the loggers\n       * in this child yet).\n       * @type {number}\n       */\n      var inheritedLevel;\n      /**\n       * The default level for this logger, if any. If set, this overrides\n       * `inheritedLevel`.\n       * @type {number|null}\n       */\n      var defaultLevel;\n      /**\n       * A user-specific level for this logger. If set, this overrides\n       * `defaultLevel`.\n       * @type {number|null}\n       */\n      var userLevel;\n\n      var storageKey = \"loglevel\";\n      if (typeof name === \"string\") {\n        storageKey += \":\" + name;\n      } else if (typeof name === \"symbol\") {\n        storageKey = undefined;\n      }\n\n      function persistLevelIfPossible(levelNum) {\n          var levelName = (logMethods[levelNum] || 'silent').toUpperCase();\n\n          if (typeof window === undefinedType || !storageKey) return;\n\n          // Use localStorage if available\n          try {\n              window.localStorage[storageKey] = levelName;\n              return;\n          } catch (ignore) {}\n\n          // Use session cookie as fallback\n          try {\n              window.document.cookie =\n                encodeURIComponent(storageKey) + \"=\" + levelName + \";\";\n          } catch (ignore) {}\n      }\n\n      function getPersistedLevel() {\n          var storedLevel;\n\n          if (typeof window === undefinedType || !storageKey) return;\n\n          try {\n              storedLevel = window.localStorage[storageKey];\n          } catch (ignore) {}\n\n          // Fallback to cookies if local storage gives us nothing\n          if (typeof storedLevel === undefinedType) {\n              try {\n                  var cookie = window.document.cookie;\n                  var cookieName = encodeURIComponent(storageKey);\n                  var location = cookie.indexOf(cookieName + \"=\");\n                  if (location !== -1) {\n                      storedLevel = /^([^;]+)/.exec(\n                          cookie.slice(location + cookieName.length + 1)\n                      )[1];\n                  }\n              } catch (ignore) {}\n          }\n\n          // If the stored level is not valid, treat it as if nothing was stored.\n          if (self.levels[storedLevel] === undefined) {\n              storedLevel = undefined;\n          }\n\n          return storedLevel;\n      }\n\n      function clearPersistedLevel() {\n          if (typeof window === undefinedType || !storageKey) return;\n\n          // Use localStorage if available\n          try {\n              window.localStorage.removeItem(storageKey);\n          } catch (ignore) {}\n\n          // Use session cookie as fallback\n          try {\n              window.document.cookie =\n                encodeURIComponent(storageKey) + \"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\";\n          } catch (ignore) {}\n      }\n\n      function normalizeLevel(input) {\n          var level = input;\n          if (typeof level === \"string\" && self.levels[level.toUpperCase()] !== undefined) {\n              level = self.levels[level.toUpperCase()];\n          }\n          if (typeof level === \"number\" && level >= 0 && level <= self.levels.SILENT) {\n              return level;\n          } else {\n              throw new TypeError(\"log.setLevel() called with invalid level: \" + input);\n          }\n      }\n\n      /*\n       *\n       * Public logger API - see https://github.com/pimterry/loglevel for details\n       *\n       */\n\n      self.name = name;\n\n      self.levels = { \"TRACE\": 0, \"DEBUG\": 1, \"INFO\": 2, \"WARN\": 3,\n          \"ERROR\": 4, \"SILENT\": 5};\n\n      self.methodFactory = factory || defaultMethodFactory;\n\n      self.getLevel = function () {\n          if (userLevel != null) {\n            return userLevel;\n          } else if (defaultLevel != null) {\n            return defaultLevel;\n          } else {\n            return inheritedLevel;\n          }\n      };\n\n      self.setLevel = function (level, persist) {\n          userLevel = normalizeLevel(level);\n          if (persist !== false) {  // defaults to true\n              persistLevelIfPossible(userLevel);\n          }\n\n          // NOTE: in v2, this should call rebuild(), which updates children.\n          return replaceLoggingMethods.call(self);\n      };\n\n      self.setDefaultLevel = function (level) {\n          defaultLevel = normalizeLevel(level);\n          if (!getPersistedLevel()) {\n              self.setLevel(level, false);\n          }\n      };\n\n      self.resetLevel = function () {\n          userLevel = null;\n          clearPersistedLevel();\n          replaceLoggingMethods.call(self);\n      };\n\n      self.enableAll = function(persist) {\n          self.setLevel(self.levels.TRACE, persist);\n      };\n\n      self.disableAll = function(persist) {\n          self.setLevel(self.levels.SILENT, persist);\n      };\n\n      self.rebuild = function () {\n          if (defaultLogger !== self) {\n              inheritedLevel = normalizeLevel(defaultLogger.getLevel());\n          }\n          replaceLoggingMethods.call(self);\n\n          if (defaultLogger === self) {\n              for (var childName in _loggersByName) {\n                _loggersByName[childName].rebuild();\n              }\n          }\n      };\n\n      // Initialize all the internal levels.\n      inheritedLevel = normalizeLevel(\n          defaultLogger ? defaultLogger.getLevel() : \"WARN\"\n      );\n      var initialLevel = getPersistedLevel();\n      if (initialLevel != null) {\n          userLevel = normalizeLevel(initialLevel);\n      }\n      replaceLoggingMethods.call(self);\n    }\n\n    /*\n     *\n     * Top-level API\n     *\n     */\n\n    defaultLogger = new Logger();\n\n    defaultLogger.getLogger = function getLogger(name) {\n        if ((typeof name !== \"symbol\" && typeof name !== \"string\") || name === \"\") {\n            throw new TypeError(\"You must supply a name when creating a logger.\");\n        }\n\n        var logger = _loggersByName[name];\n        if (!logger) {\n            logger = _loggersByName[name] = new Logger(\n                name,\n                defaultLogger.methodFactory\n            );\n        }\n        return logger;\n    };\n\n    // Grab the current global log variable in case of overwrite\n    var _log = (typeof window !== undefinedType) ? window.log : undefined;\n    defaultLogger.noConflict = function() {\n        if (typeof window !== undefinedType &&\n               window.log === defaultLogger) {\n            window.log = _log;\n        }\n\n        return defaultLogger;\n    };\n\n    defaultLogger.getLoggers = function getLoggers() {\n        return _loggersByName;\n    };\n\n    // ES6 default export, for compatibility\n    defaultLogger['default'] = defaultLogger;\n\n    return defaultLogger;\n}));\n","// The module cache\nconst __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tconst cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tconst module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tconst getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter/value functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tif(Array.isArray(definition)) {\n\t\tvar i = 0;\n\t\twhile(i < definition.length) {\n\t\t\tvar key = definition[i++];\n\t\t\tvar binding = definition[i++];\n\t\t\tif(!__webpack_require__.o(exports, key)) {\n\t\t\t\tif(binding === 0) {\n\t\t\t\t\tObject.defineProperty(exports, key, { enumerable: true, value: definition[i++] });\n\t\t\t\t} else {\n\t\t\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: binding });\n\t\t\t\t}\n\t\t\t} else if(binding === 0) { i++; }\n\t\t}\n\t} else {\n\t\tfor(var key in definition) {\n\t\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t\t}\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","(() => {\n  if (typeof __webpack_require__ !== 'undefined') {\n    var oldGetScript = __webpack_require__.u;\n    var oldLoadScript = __webpack_require__.e;\n    var queryMap = {};\n    var countMap = {};\n    var getRetryDelay = function () {\n      return 500;\n    };\n    __webpack_require__.u = function (chunkId) {\n      var result = oldGetScript(chunkId);\n      return (\n        result +\n        (queryMap.hasOwnProperty(chunkId) ? '?' + queryMap[chunkId] : '')\n      );\n    };\n    __webpack_require__.e = function (chunkId) {\n      var result = oldLoadScript(chunkId);\n      return result.catch(function (error) {\n        var retries = countMap.hasOwnProperty(chunkId) ? countMap[chunkId] : 3;\n        if (retries < 1) {\n          var realSrc = oldGetScript(chunkId);\n          error.message =\n            'Loading chunk ' +\n            chunkId +\n            ' failed after 3 retries.\\n(' +\n            realSrc +\n            ')';\n          error.request = realSrc;\n          throw error;\n        }\n        return new Promise(function (resolve) {\n          var retryAttempt = 3 - retries + 1;\n          setTimeout(function () {\n            var retryAttemptString = '&retry-attempt=' + retryAttempt;\n            var cacheBust = (() => Date.now())();\n            +retryAttemptString;\n            queryMap[chunkId] = cacheBust;\n            countMap[chunkId] = retries - 1;\n            resolve(__webpack_require__.e(chunkId));\n          }, getRetryDelay(retryAttempt));\n        });\n      });\n    };\n  }\n})();\n","/*\nCopyright 2024 New Vector Ltd.\nCopyright 2019-2021 , 2024 The Matrix.org Foundation C.I.C.\n\nSPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial\nPlease see LICENSE files in the repository root for full details.\n*/\n\n/**\n * Retrieves the IndexedDB factory object.\n *\n * @returns {IDBFactory | undefined} The IndexedDB factory object if available, or undefined if it is not supported.\n */\nexport function getIDBFactory(): IDBFactory | undefined {\n    // IndexedDB loading is lazy for easier testing.\n\n    // just *accessing* _indexedDB throws an exception in firefox with\n    // indexeddb disabled.\n    try {\n        // `self` is preferred for service workers, which access this file's functions.\n        // We check `self` first because `window` returns something which doesn't work for service workers.\n        // Note: `self?.indexedDB ?? window.indexedDB` breaks in service workers for unknown reasons.\n        return self?.indexedDB ? self.indexedDB : window.indexedDB;\n    } catch {}\n}\n\nlet idb: IDBDatabase | null = null;\n\nasync function idbInit(): Promise<void> {\n    if (!getIDBFactory()) {\n        throw new Error(\"IndexedDB not available\");\n    }\n    idb = await new Promise((resolve, reject) => {\n        const request = getIDBFactory()!.open(\"matrix-react-sdk\", 1);\n        request.onerror = reject;\n        request.onsuccess = (): void => {\n            resolve(request.result);\n        };\n        request.onupgradeneeded = (): void => {\n            const db = request.result;\n            db.createObjectStore(\"pickleKey\");\n            db.createObjectStore(\"account\");\n        };\n    });\n}\n\nasync function idbTransaction(\n    table: string,\n    mode: IDBTransactionMode,\n    fn: (objectStore: IDBObjectStore) => IDBRequest<any>,\n): Promise<any> {\n    if (!idb) {\n        await idbInit();\n    }\n    return new Promise((resolve, reject) => {\n        const txn = idb!.transaction([table], mode);\n        txn.onerror = reject;\n\n        const objectStore = txn.objectStore(table);\n        const request = fn(objectStore);\n        request.onerror = reject;\n        request.onsuccess = (): void => {\n            resolve(request.result);\n        };\n    });\n}\n\n/**\n * Loads an item from an IndexedDB table within the underlying `matrix-react-sdk` database.\n *\n * If IndexedDB access is not supported in the environment, an error is thrown.\n *\n * @param {string} table The name of the object store in IndexedDB.\n * @param {string | string[]} key The key where the data is stored.\n * @returns {Promise<any>} A promise that resolves with the retrieved item from the table.\n */\nexport async function idbLoad(table: string, key: string | string[]): Promise<any> {\n    if (!idb) {\n        await idbInit();\n    }\n    return idbTransaction(table, \"readonly\", (objectStore) => objectStore.get(key));\n}\n\n/**\n * Saves data to an IndexedDB table within the underlying `matrix-react-sdk` database.\n *\n * If IndexedDB access is not supported in the environment, an error is thrown.\n *\n * @param {string} table The name of the object store in the IndexedDB.\n * @param {string|string[]} key The key to use for storing the data.\n * @param {*} data The data to be saved.\n * @returns {Promise<void>} A promise that resolves when the data is saved successfully.\n */\nexport async function idbSave(table: string, key: string | string[], data: any): Promise<void> {\n    if (!idb) {\n        await idbInit();\n    }\n    return idbTransaction(table, \"readwrite\", (objectStore) => objectStore.put(data, key));\n}\n\n/**\n * Deletes a record from an IndexedDB table within the underlying `matrix-react-sdk` database.\n *\n * If IndexedDB access is not supported in the environment, an error is thrown.\n *\n * @param {string} table The name of the object store where the record is stored.\n * @param {string|string[]} key The key of the record to be deleted.\n * @returns {Promise<void>} A Promise that resolves when the record(s) have been successfully deleted.\n */\nexport async function idbDelete(table: string, key: string | string[]): Promise<void> {\n    if (!idb) {\n        await idbInit();\n    }\n    return idbTransaction(table, \"readwrite\", (objectStore) => objectStore.delete(key));\n}\n\n/**\n * Clears all records from an IndexedDB table within the underlying `matrix-react-sdk` database.\n *\n * If IndexedDB access is not supported in the environment, an error is thrown.\n *\n * @param {string} table The name of the object store where the records are stored.\n * @returns {Promise<void>} A Promise that resolves when the record(s) have been successfully deleted.\n */\nexport async function idbClear(table: string): Promise<void> {\n    if (!idb) {\n        await idbInit();\n    }\n    return idbTransaction(table, \"readwrite\", (objectStore) => objectStore.clear());\n}\n","/*\nCopyright 2018 André Jaenisch\nCopyright 2019-2025 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 loglevel from \"loglevel\";\n\n/** Backwards-compatibility hack to expose `log` to applications that might still be relying on it. */\ninterface LoggerWithLogMethod extends Logger {\n    /**\n     * Output debug message to the logger.\n     *\n     * @param msg - Data to log.\n     *\n     * @deprecated prefer {@link Logger.debug}.\n     */\n    log(...msg: any[]): void;\n}\n\n/** Logger interface used within the js-sdk codebase */\nexport interface Logger extends BaseLogger {\n    /**\n     * Create a child logger.\n     *\n     * This child will use the `methodFactory` of the parent, so any log extensions applied to the parent\n     * at the time of calling `getChild` will be applied to the child as well.\n     * It will NOT apply changes to the parent's `methodFactory` after the child was created.\n     * Those changes need to be applied to the child manually.\n     *\n     * @param namespace - name to add to the current logger to generate the child. Some implementations of `Logger`\n     *    use this as a prefix; others use a different mechanism.\n     */\n    getChild(namespace: string): Logger;\n}\n\n/** The basic interface for a logger which doesn't support children */\nexport interface BaseLogger {\n    /**\n     * Output trace message to the logger, with stack trace.\n     *\n     * @param msg - Data to log.\n     */\n    trace(this: void, ...msg: any[]): void;\n\n    /**\n     * Output debug message to the logger.\n     *\n     * @param msg - Data to log.\n     */\n    debug(this: void, ...msg: any[]): void;\n\n    /**\n     * Output info message to the logger.\n     *\n     * @param msg - Data to log.\n     */\n    info(this: void, ...msg: any[]): void;\n\n    /**\n     * Output warn message to the logger.\n     *\n     * @param msg - Data to log.\n     */\n    warn(this: void, ...msg: any[]): void;\n\n    /**\n     * Output error message to the logger.\n     *\n     * @param msg - Data to log.\n     */\n    error(this: void, ...msg: any[]): void;\n}\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nconst DEFAULT_NAMESPACE = \"matrix\";\n\n// because rageshakes in react-sdk hijack the console log, also at module load time,\n// initializing the logger here races with the initialization of rageshakes.\n// to avoid the issue, we override the methodFactory of loglevel that binds to the\n// console methods at initialization time by a factory that looks up the console methods\n// when logging so we always get the current value of console methods.\nloglevel.methodFactory = function (methodName, logLevel, loggerName) {\n    return function (this: PrefixedLogger, ...args): void {\n        /* eslint-disable @typescript-eslint/no-invalid-this */\n        if (this.prefix) {\n            args.unshift(this.prefix);\n        }\n        /* eslint-enable @typescript-eslint/no-invalid-this */\n        const supportedByConsole =\n            methodName === \"error\" ||\n            methodName === \"warn\" ||\n            methodName === \"trace\" ||\n            methodName === \"info\" ||\n            methodName === \"debug\";\n        /* eslint-disable no-console */\n        if (supportedByConsole) {\n            return console[methodName](...args);\n        } else {\n            return console.log(...args);\n        }\n        /* eslint-enable no-console */\n    };\n};\n\n/**\n * Implementation of {@link Logger} based on `loglevel`.\n */\ninterface PrefixedLogger extends loglevel.Logger, LoggerWithLogMethod {\n    prefix?: string;\n}\n\n/**\n * Internal utility function: gets a {@link Logger} based on `loglevel`.\n *\n * Child loggers produced by {@link Logger.getChild} add the name of the child logger as a prefix on each log line.\n *\n * @param prefix Prefix to add to each logged line. If undefined, no prefix will be added.\n */\nfunction getPrefixedLogger(prefix?: string): PrefixedLogger {\n    const loggerName = DEFAULT_NAMESPACE + (prefix === undefined ? \"\" : `-${prefix}`);\n    const prefixLogger = loglevel.getLogger(loggerName) as PrefixedLogger;\n\n    if (prefixLogger.getChild === undefined) {\n        // This is a new loglevel Logger which has not been turned into a PrefixedLogger yet.\n        prefixLogger.prefix = prefix;\n        prefixLogger.getChild = (childPrefix): Logger => {\n            // create the new child logger\n            const childLogger = getPrefixedLogger((prefix ?? \"\") + childPrefix);\n            // Assign the methodFactory from the parent logger.\n            // This is useful if we add extensions to the parent logger that modifies\n            // its methodFactory. (An example extension is: storing each log to a rageshake db)\n            childLogger.methodFactory = prefixLogger.methodFactory;\n            // Rebuild the child logger with the new methodFactory.\n            childLogger.rebuild();\n            return childLogger;\n        };\n        prefixLogger.setLevel(loglevel.levels.DEBUG, false);\n    }\n\n    return prefixLogger;\n}\n\n/**\n * Drop-in replacement for `console` using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n *\n * @deprecated avoid the use of this unless you are the constructor of `MatrixClient`: you should be using the logger\n *    associated with `MatrixClient`.\n */\nexport const logger = getPrefixedLogger() as LoggerWithLogMethod;\n\n/**\n * A \"span\" for grouping related log lines together.\n *\n * The current implementation just adds the name at the start of each log line.\n *\n * This offers a lighter-weight alternative to 'child' loggers returned by {@link Logger#getChild}. In particular,\n * it's not possible to apply individual filters to the LogSpan such as setting the verbosity level. On the other hand,\n * no reference to the LogSpan is retained in the logging framework, so it is safe to make lots of them over the course\n * of an application's life and just drop references to them when the job is done.\n */\nexport class LogSpan implements BaseLogger {\n    private readonly name;\n\n    public constructor(\n        private readonly parent: BaseLogger,\n        name: string,\n    ) {\n        this.name = name + \":\";\n    }\n\n    public trace(...msg: any[]): void {\n        this.parent.trace(this.name, ...msg);\n    }\n\n    public debug(...msg: any[]): void {\n        this.parent.debug(this.name, ...msg);\n    }\n\n    public info(...msg: any[]): void {\n        this.parent.info(this.name, ...msg);\n    }\n\n    public warn(...msg: any[]): void {\n        this.parent.warn(this.name, ...msg);\n    }\n\n    public error(...msg: any[]): void {\n        this.parent.error(this.name, ...msg);\n    }\n}\n\n/**\n * A simplification of the `Debugger` type exposed by the `debug` library. We reimplement the bits we need here\n * to avoid a dependency on `debug`.\n */\ninterface Debugger {\n    (formatter: any, ...args: any[]): void;\n    extend: (namespace: string, delimiter?: string) => Debugger;\n}\n\n/**\n * A `Logger` instance, suitable for use in {@link ICreateClientOpts.logger}, which will write to the `debug` library.\n *\n * @example\n * ```js\n *     import debug from \"debug\";\n *\n *     const client = createClient({\n *         baseUrl: homeserverUrl,\n *         userId: userId,\n *         accessToken: \"akjgkrgjs\",\n *         deviceId: \"xzcvb\",\n *         logger: new DebugLogger(debug(`matrix-js-sdk:${userId}`)),\n *     });\n * ```\n */\nexport class DebugLogger implements Logger {\n    public constructor(private debugInstance: Debugger) {}\n\n    public trace(...msg: any[]): void {\n        this.debugWithPrefix(\"[TRACE]\", ...msg);\n    }\n\n    public debug(...msg: any[]): void {\n        this.debugWithPrefix(\"[DEBUG]\", ...msg);\n    }\n\n    public info(...msg: any[]): void {\n        this.debugWithPrefix(\"[INFO]\", ...msg);\n    }\n\n    public warn(...msg: any[]): void {\n        this.debugWithPrefix(\"[WARN]\", ...msg);\n    }\n\n    public error(...msg: any[]): void {\n        this.debugWithPrefix(\"[ERROR]\", ...msg);\n    }\n\n    public getChild(namespace: string): DebugLogger {\n        return new DebugLogger(this.debugInstance.extend(namespace));\n    }\n\n    private debugWithPrefix(prefix: string, ...msg: any[]): void {\n        let formatter: string;\n\n        // Convert the first argument to a string, so that we can safely add a prefix. This is much the same logic that\n        // `debug()` uses.\n        if (msg.length === 0) {\n            formatter = \"\";\n        } else if (msg[0] instanceof Error) {\n            const err = msg.shift();\n            formatter = err.stack || err.message;\n        } else if (typeof msg[0] == \"string\") {\n            formatter = msg.shift();\n        } else {\n            formatter = \"%O\";\n        }\n        this.debugInstance(prefix + \" \" + formatter, ...msg);\n    }\n}\n","/*\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\n/**\n * Base64 encoding and decoding utilities\n */\n\nfunction toBase64(uint8Array: Uint8Array, options: Uint8ArrayToBase64Options): string {\n    if (typeof uint8Array.toBase64 === \"function\") {\n        // Currently this is only supported in Firefox,\n        // but we match the options in the hope in the future we can rely on it for all environments.\n        // https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.tobase64\n        return uint8Array.toBase64(options);\n    }\n\n    let base64 = btoa(uint8Array.reduce((acc, current) => acc + String.fromCharCode(current), \"\"));\n    if (options.omitPadding) {\n        base64 = base64.replace(/={1,2}$/, \"\");\n    }\n    if (options.alphabet === \"base64url\") {\n        base64 = base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n    }\n\n    return base64;\n}\n\n/**\n * Encode a typed array of uint8 as base64.\n * @param uint8Array - The data to encode.\n * @returns The base64.\n */\nexport function encodeBase64(uint8Array: Uint8Array): string {\n    return toBase64(uint8Array, { alphabet: \"base64\", omitPadding: false });\n}\n\n/**\n * Encode a typed array of uint8 as unpadded base64.\n * @param uint8Array - The data to encode.\n * @returns The unpadded base64.\n */\nexport function encodeUnpaddedBase64(uint8Array: Uint8Array): string {\n    return toBase64(uint8Array, { alphabet: \"base64\", omitPadding: true });\n}\n\n/**\n * Encode a typed array of uint8 as unpadded base64 using the URL-safe encoding.\n * @param uint8Array - The data to encode.\n * @returns The unpadded base64.\n */\nexport function encodeUnpaddedBase64Url(uint8Array: Uint8Array): string {\n    return toBase64(uint8Array, { alphabet: \"base64url\", omitPadding: true });\n}\n\nfunction fromBase64(base64: string, options: Uint8ArrayFromBase64Options): Uint8Array<ArrayBuffer> {\n    if (typeof Uint8Array.fromBase64 === \"function\") {\n        // Currently this is only supported in Firefox,\n        // but we match the options in the hope in the future we can rely on it for all environments.\n        // https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.frombase64\n        return Uint8Array.fromBase64(base64, options);\n    }\n\n    return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));\n}\n\n/**\n * Decode a base64 (or base64url) string to a typed array of uint8.\n * @param base64 - The base64 to decode.\n * @returns The decoded data.\n */\nexport function decodeBase64(base64: string): Uint8Array<ArrayBuffer> {\n    // The function requires us to select an alphabet, but we don't know if base64url was used so we convert.\n    return fromBase64(base64.replace(/-/g, \"+\").replace(/_/g, \"/\"), { alphabet: \"base64\", lastChunkHandling: \"loose\" });\n}\n","/*\n * Copyright 2024 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// salt for HKDF, with 8 bytes of zeros\nconst zeroSalt = new Uint8Array(8);\n\n/**\n * Derive AES and HMAC keys from a master key.\n *\n * This is used for deriving secret storage keys: see https://spec.matrix.org/v1.11/client-server-api/#msecret_storagev1aes-hmac-sha2 (step 1).\n *\n * @param key\n * @param name\n */\nexport async function deriveKeys(key: Uint8Array<ArrayBuffer>, name: string): Promise<[CryptoKey, CryptoKey]> {\n    const hkdfkey = await globalThis.crypto.subtle.importKey(\"raw\", key, { name: \"HKDF\" }, false, [\"deriveBits\"]);\n    const keybits = await globalThis.crypto.subtle.deriveBits(\n        {\n            name: \"HKDF\",\n            salt: zeroSalt,\n            // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n            // @ts-ignore: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/879\n            info: new TextEncoder().encode(name),\n            hash: \"SHA-256\",\n        },\n        hkdfkey,\n        512,\n    );\n\n    const aesKey = keybits.slice(0, 32);\n    const hmacKey = keybits.slice(32);\n\n    const aesProm = globalThis.crypto.subtle.importKey(\"raw\", aesKey, { name: \"AES-CTR\" }, false, [\n        \"encrypt\",\n        \"decrypt\",\n    ]);\n\n    const hmacProm = globalThis.crypto.subtle.importKey(\n        \"raw\",\n        hmacKey,\n        {\n            name: \"HMAC\",\n            hash: { name: \"SHA-256\" },\n        },\n        false,\n        [\"sign\", \"verify\"],\n    );\n\n    return Promise.all([aesProm, hmacProm]);\n}\n","/*\n * Copyright 2024 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64 } from \"../base64.ts\";\nimport { deriveKeys } from \"./internal/deriveKeys.ts\";\nimport { type AESEncryptedSecretStoragePayload } from \"../@types/AESEncryptedSecretStoragePayload.ts\";\n\n/**\n * Decrypt an AES-encrypted Secret Storage item.\n *\n * @param data - the encrypted data, returned by {@link utils/encryptAESSecretStorageItem.default | encryptAESSecretStorageItem}.\n * @param key - the encryption key to use as an input to the HKDF function which is used to derive the AES key. Must\n *    be the same as provided to {@link utils/encryptAESSecretStorageItem.default | encryptAESSecretStorageItem}.\n * @param name - the name of the secret. Also used as an input to the HKDF operation which is used to derive the AES\n *    key, so again must be the same as provided to {@link utils/encryptAESSecretStorageItem.default | encryptAESSecretStorageItem}.\n */\nexport default async function decryptAESSecretStorageItem(\n    data: AESEncryptedSecretStoragePayload,\n    key: Uint8Array<ArrayBuffer>,\n    name: string,\n): Promise<string> {\n    const [aesKey, hmacKey] = await deriveKeys(key, name);\n\n    const ciphertext = decodeBase64(data.ciphertext);\n\n    if (!(await globalThis.crypto.subtle.verify({ name: \"HMAC\" }, hmacKey, decodeBase64(data.mac), ciphertext))) {\n        throw new Error(`Error decrypting secret ${name}: bad MAC`);\n    }\n\n    const plaintext = await globalThis.crypto.subtle.decrypt(\n        {\n            name: \"AES-CTR\",\n            counter: decodeBase64(data.iv),\n            length: 64,\n        },\n        aesKey,\n        ciphertext,\n    );\n\n    return new TextDecoder().decode(new Uint8Array(plaintext));\n}\n","/*\nCopyright 2024 New Vector Ltd.\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nSPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial\nPlease see LICENSE files in the repository root for full details.\n*/\n\nimport { logger } from \"matrix-js-sdk/src/logger\";\nimport { type AccessTokens } from \"matrix-js-sdk/src/matrix\";\nimport decryptAESSecretStorageItem from \"matrix-js-sdk/src/utils/decryptAESSecretStorageItem\";\nimport encryptAESSecretStorageItem from \"matrix-js-sdk/src/utils/encryptAESSecretStorageItem\";\nimport { type AESEncryptedSecretStoragePayload } from \"matrix-js-sdk/src/types\";\n\nimport * as StorageAccess from \"../StorageAccess\";\n\n/**\n * Utility functions related to the storage and retrieval of access tokens\n */\n\n/*\n * Names used when storing the tokens in indexeddb or localstorage\n */\nexport const ACCESS_TOKEN_STORAGE_KEY = \"mx_access_token\";\nexport const REFRESH_TOKEN_STORAGE_KEY = \"mx_refresh_token\";\n/*\n * Names of the tokens. Used as part of the calculation to derive AES keys during encryption in persistTokenInStorage,\n * and decryption in restoreSessionFromStorage.\n */\nexport const ACCESS_TOKEN_IV = \"access_token\";\nexport const REFRESH_TOKEN_IV = \"refresh_token\";\n/*\n * Keys for localstorage items which indicate whether we expect a token in indexeddb.\n */\nexport const HAS_ACCESS_TOKEN_STORAGE_KEY = \"mx_has_access_token\";\nexport const HAS_REFRESH_TOKEN_STORAGE_KEY = \"mx_has_refresh_token\";\n\n/**\n * The pickle key is a string of unspecified length and format.  For AES, we need a 256-bit Uint8Array. So we HKDF the pickle key to generate the AES key.  The AES key should be zeroed after it is used.\n * @param pickleKey\n * @returns AES key\n */\nasync function pickleKeyToAesKey(pickleKey: string): Promise<Uint8Array<ArrayBuffer>> {\n    const pickleKeyBuffer = new Uint8Array(pickleKey.length);\n    for (let i = 0; i < pickleKey.length; i++) {\n        pickleKeyBuffer[i] = pickleKey.charCodeAt(i);\n    }\n    const hkdfKey = await crypto.subtle.importKey(\"raw\", pickleKeyBuffer, \"HKDF\", false, [\"deriveBits\"]);\n    pickleKeyBuffer.fill(0);\n    return new Uint8Array(\n        await crypto.subtle.deriveBits(\n            {\n                name: \"HKDF\",\n                hash: \"SHA-256\",\n                // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n                // @ts-ignore: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/879\n                salt: new Uint8Array(32),\n                info: new Uint8Array(0),\n            },\n            hkdfKey,\n            256,\n        ),\n    );\n}\n\n/**\n * Try to decrypt a token retrieved from storage\n *\n * Where token is not encrypted (plain text) returns the plain text token.\n *\n * Where token is encrypted, attempts decryption. Returns successfully decrypted token, or throws if\n * decryption failed.\n *\n * @param pickleKey Pickle key: used to derive the encryption key, or undefined if the token is not encrypted.\n *   Must be the same as provided to {@link persistTokenInStorage}.\n * @param token token to be decrypted.\n * @param tokenName Name of the token. Used in logging, but also used as an input when generating the actual AES key,\n *    so the same value must be provided to {@link persistTokenInStorage}.\n *\n * @returns the decrypted token, or the plain text token.\n */\nexport async function tryDecryptToken(\n    pickleKey: string | undefined,\n    token: AESEncryptedSecretStoragePayload | string,\n    tokenName: string,\n): Promise<string> {\n    if (typeof token === \"string\") {\n        // Looks like an unencrypted token\n        return token;\n    }\n\n    // Otherwise, it must be an encrypted token.\n    if (!pickleKey) {\n        throw new Error(`Error decrypting secret ${tokenName}: no pickle key found.`);\n    }\n\n    const encrKey = await pickleKeyToAesKey(pickleKey);\n    const decryptedToken = await decryptAESSecretStorageItem(token, encrKey, tokenName);\n    encrKey.fill(0);\n    return decryptedToken;\n}\n\n/**\n * Persist a token in storage\n *\n * When pickle key is present, will attempt to encrypt the token. If encryption fails (typically because\n * WebCrypto is unavailable), the key will be stored unencrypted.\n *\n * Stores in IndexedDB, falling back to localStorage.\n *\n * @param storageKey key used to store the token. Note: not an encryption key; rather a localstorage or indexeddb key.\n * @param tokenName Name of the token. Used in logging, but also used as an input when generating the actual AES key,\n *    so the same value must be provided to {@link tryDecryptToken} when decrypting.\n * @param token the token to store. When undefined, any existing token at the `storageKey` is removed from storage.\n * @param pickleKey Pickle key: used to derive the key used to encrypt token. If `undefined`, the token will be stored\n *    unencrypted.\n * @param hasTokenStorageKey Localstorage key for an item which stores whether we expect to have a token in indexeddb,\n *    eg \"mx_has_access_token\".\n */\nasync function persistTokenInStorage(\n    storageKey: string,\n    tokenName: string,\n    token: string | undefined,\n    pickleKey: string | undefined,\n    hasTokenStorageKey: string,\n): Promise<void> {\n    // store whether we expect to find a token, to detect the case\n    // where IndexedDB is blown away\n    if (token) {\n        localStorage.setItem(hasTokenStorageKey, \"true\");\n    } else {\n        localStorage.removeItem(hasTokenStorageKey);\n    }\n\n    if (pickleKey) {\n        let encryptedToken: AESEncryptedSecretStoragePayload | undefined;\n        if (token) {\n            try {\n                // try to encrypt the access token using the pickle key\n                const encrKey = await pickleKeyToAesKey(pickleKey);\n                encryptedToken = await encryptAESSecretStorageItem(token, encrKey, tokenName);\n                encrKey.fill(0);\n            } catch (e) {\n                // This is likely due to the browser not having WebCrypto or somesuch.\n                // Warn about it, but fall back to storing the unencrypted token.\n                logger.warn(`Could not encrypt token for ${tokenName}`, e);\n            }\n        }\n        try {\n            // Save either the encrypted access token, or the plain access\n            // token if there is no token or we were unable to encrypt (e.g. if the browser doesn't\n            // have WebCrypto).\n            await StorageAccess.idbSave(\"account\", storageKey, encryptedToken || token);\n        } catch {\n            // if we couldn't save to indexedDB, fall back to localStorage.  We\n            // store the access token unencrypted since localStorage only saves\n            // strings.\n            if (!!token) {\n                localStorage.setItem(storageKey, token);\n            } else {\n                localStorage.removeItem(storageKey);\n            }\n        }\n    } else {\n        try {\n            await StorageAccess.idbSave(\"account\", storageKey, token);\n        } catch {\n            if (!!token) {\n                localStorage.setItem(storageKey, token);\n            } else {\n                localStorage.removeItem(storageKey);\n            }\n        }\n    }\n}\n\n/**\n * Wraps {@link persistTokenInStorage} with accessToken & refreshToken storage keys\n *\n * @param tokens - The tokens to persist\n * @param pickleKey - Pickle key: used to derive the key used to encrypt token.\n *     If `undefined`, the token will be stored unencrypted.\n */\nexport async function persistTokens(pickleKey: string | undefined, tokens: AccessTokens): Promise<void> {\n    await persistTokenInStorage(\n        ACCESS_TOKEN_STORAGE_KEY,\n        ACCESS_TOKEN_IV,\n        tokens.accessToken,\n        pickleKey,\n        HAS_ACCESS_TOKEN_STORAGE_KEY,\n    );\n    await persistTokenInStorage(\n        REFRESH_TOKEN_STORAGE_KEY,\n        REFRESH_TOKEN_IV,\n        tokens.refreshToken,\n        pickleKey,\n        HAS_REFRESH_TOKEN_STORAGE_KEY,\n    );\n}\n","/*\nCopyright 2024 New Vector Ltd.\nCopyright 2020-2024 The Matrix.org Foundation C.I.C.\nCopyright 2018 New Vector Ltd\nCopyright 2016 Aviral Dasgupta\nCopyright 2016 OpenMarket Ltd\n\nSPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial\nPlease see LICENSE files in the repository root for full details.\n*/\n\n// Note: we don't import the base64 utils from `matrix-js-sdk/src/matrix` because this file\n// is used by Element Web's service worker, and importing `matrix` brings in ~1mb of stuff\n// we don't need. Instead, we ignore the import restriction and only bring in what we actually\n// need.\n// Note: `base64` is not public in the js-sdk, so if it changes/breaks, that's on us. We should\n// be okay with our frequent tests, locked versioning, etc though. We'll pick up problems well\n// before release.\n// eslint-disable-next-line no-restricted-imports\nimport { encodeUnpaddedBase64 } from \"matrix-js-sdk/src/base64\";\nimport { logger } from \"matrix-js-sdk/src/logger\";\n\n/**\n * Encrypted format of a pickle key, as stored in IndexedDB.\n */\nexport interface EncryptedPickleKey {\n    /** The encrypted payload. */\n    encrypted?: BufferSource;\n\n    /** Initialisation vector for the encryption. */\n    iv?: BufferSource;\n\n    /** The encryption key which was used to encrypt the payload. */\n    cryptoKey?: CryptoKey;\n}\n\n/**\n * Calculates the `additionalData` for the AES-GCM key used by the pickling processes. This\n * additional data is *not* encrypted, but *is* authenticated. The additional data is constructed\n * from the user ID and device ID provided.\n *\n * The later-constructed pickle key is used to decrypt values, such as access tokens, from IndexedDB.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/AesGcmParams for more information on\n * `additionalData`.\n *\n * @param {string} userId The user ID who owns the pickle key.\n * @param {string} deviceId The device ID which owns the pickle key.\n * @returns {Uint8Array} The additional data as a Uint8Array.\n */\nexport function getPickleAdditionalData(userId: string, deviceId: string): Uint8Array<ArrayBuffer> {\n    const additionalData = new Uint8Array(userId.length + deviceId.length + 1);\n    for (let i = 0; i < userId.length; i++) {\n        additionalData[i] = userId.charCodeAt(i);\n    }\n    additionalData[userId.length] = 124; // \"|\"\n    for (let i = 0; i < deviceId.length; i++) {\n        additionalData[userId.length + 1 + i] = deviceId.charCodeAt(i);\n    }\n    return additionalData;\n}\n\n/**\n * Encrypt the given pickle key, ready for storage in the database.\n *\n * @param pickleKey - The key to be encrypted.\n * @param userId - The user ID the pickle key belongs to.\n * @param deviceId - The device ID the pickle key belongs to.\n *\n * @returns Data object ready for storing in indexeddb.\n */\nexport async function encryptPickleKey(\n    pickleKey: Uint8Array<ArrayBuffer>,\n    userId: string,\n    deviceId: string,\n): Promise<EncryptedPickleKey | undefined> {\n    if (!crypto?.subtle) {\n        return undefined;\n    }\n    const cryptoKey = await crypto.subtle.generateKey({ name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n    const iv = new Uint8Array(32);\n    crypto.getRandomValues(iv);\n\n    const additionalData = getPickleAdditionalData(userId, deviceId);\n    const encrypted = await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData }, cryptoKey, pickleKey);\n    return { encrypted, iv, cryptoKey };\n}\n\n/**\n * Decrypts the provided data into a pickle key and base64-encodes it ready for use elsewhere.\n *\n * If `data` is undefined in part or in full, returns undefined.\n *\n *  If crypto functions are not available, returns undefined regardless of input.\n *\n * @param data An object containing the encrypted pickle key data: encrypted payload, initialization vector (IV), and crypto key. Typically loaded from indexedDB.\n * @param userId The user ID the pickle key belongs to.\n * @param deviceId The device ID the pickle key belongs to.\n * @returns A promise that resolves to the encoded pickle key, or undefined if the key cannot be built and encoded.\n */\nexport async function buildAndEncodePickleKey(\n    data: EncryptedPickleKey | undefined,\n    userId: string,\n    deviceId: string,\n): Promise<string | undefined> {\n    if (!crypto?.subtle) {\n        return undefined;\n    }\n    if (!data || !data.encrypted || !data.iv || !data.cryptoKey) {\n        return undefined;\n    }\n\n    try {\n        const additionalData = getPickleAdditionalData(userId, deviceId);\n        const pickleKeyBuf = await crypto.subtle.decrypt(\n            { name: \"AES-GCM\", iv: data.iv, additionalData },\n            data.cryptoKey,\n            data.encrypted,\n        );\n        if (pickleKeyBuf) {\n            return encodeUnpaddedBase64(new Uint8Array(pickleKeyBuf));\n        }\n    } catch {\n        logger.error(\"Error decrypting pickle key\");\n    }\n\n    return undefined;\n}\n","/*\nCopyright 2024 New Vector Ltd.\n\nSPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial\nPlease see LICENSE files in the repository root for full details.\n*/\n\nimport { idbLoad } from \"../utils/StorageAccess\";\nimport { ACCESS_TOKEN_IV, tryDecryptToken } from \"../utils/tokens/tokens\";\nimport { buildAndEncodePickleKey } from \"../utils/tokens/pickling\";\n\nconst serverSupportMap: {\n    [serverUrl: string]: {\n        supportsAuthedMedia: boolean;\n        cacheExpiryTimeMs: number;\n    };\n} = {};\n\nglobal.addEventListener(\"install\", (event) => {\n    // We skipWaiting() to update the service worker more frequently, particularly in development environments.\n    // @ts-expect-error - service worker types are not available. See 'fetch' event handler.\n    event.waitUntil(skipWaiting());\n});\n\nglobal.addEventListener(\"activate\", (event) => {\n    // We force all clients to be under our control, immediately. This could be old tabs.\n    // @ts-expect-error - service worker types are not available. See 'fetch' event handler.\n    event.waitUntil(clients.claim());\n});\n\n// @ts-expect-error - the service worker types conflict with the DOM types available through TypeScript. Many hours\n// have been spent trying to convince the type system that there's no actual conflict, but it has yet to work. Instead\n// of trying to make it do the thing, we force-cast to something close enough where we can (and ignore errors otherwise).\nglobal.addEventListener(\"fetch\", (event: FetchEvent) => {\n    // This is the authenticated media (MSC3916) check, proxying what was unauthenticated to the authenticated variants.\n\n    if (event.request.method !== \"GET\") {\n        return; // not important to us\n    }\n\n    // Note: ideally we'd keep the request headers etc, but in practice we can't even see those details.\n    // See https://stackoverflow.com/a/59152482\n    const url = new URL(event.request.url);\n\n    // We only intercept v3 download and thumbnail requests as presumably everything else is deliberate.\n    // For example, `/_matrix/media/unstable` or `/_matrix/media/v3/preview_url` are something well within\n    // the control of the application, and appear to be choices made at a higher level than us.\n    if (\n        !url.pathname.startsWith(\"/_matrix/media/v3/download\") &&\n        !url.pathname.startsWith(\"/_matrix/media/v3/thumbnail\")\n    ) {\n        return; // not a URL we care about\n    }\n\n    // We need to call respondWith synchronously, otherwise we may never execute properly. This means\n    // later on we need to proxy the request through if it turns out the server doesn't support authentication.\n    event.respondWith(\n        (async (): Promise<Response> => {\n            let auth: { accessToken?: string; homeserver: string } | undefined;\n            try {\n                // Figure out which homeserver we're communicating with\n                const csApi = url.origin;\n\n                // Add jitter to reduce request spam, particularly to `/versions` on initial page load\n                await new Promise<void>((resolve) => setTimeout(() => resolve(), Math.random() * 10));\n\n                // Locate the access token and homeserver url\n                // @ts-expect-error - service worker types are not available. See 'fetch' event handler.\n                const client = await global.clients.get(event.clientId);\n                auth = await getAuthData(client);\n\n                // Is this request actually going to the homeserver?\n                const isRequestToHomeServer = url.origin === new URL(auth.homeserver).origin;\n                if (!isRequestToHomeServer) {\n                    throw new Error(\"Request appears to be for media endpoint but wrong homeserver!\");\n                }\n\n                // Update or populate the server support map using a (usually) authenticated `/versions` call.\n                await tryUpdateServerSupportMap(csApi, auth.accessToken);\n\n                // If we have server support (and a means of authentication), rewrite the URL to use MSC3916 endpoints.\n                if (serverSupportMap[csApi].supportsAuthedMedia && auth.accessToken) {\n                    url.href = url.href.replace(/\\/media\\/v3\\/(.*)\\//, \"/client/v1/media/$1/\");\n                } // else by default we make no changes\n            } catch (err) {\n                // In case of some error, we stay safe by not adding the access-token to the request.\n                auth = undefined;\n                console.error(\"SW: Error in request rewrite.\", err);\n            }\n\n            // Add authentication and send the request. We add authentication even if MSC3916 endpoints aren't\n            // being used to ensure patches like this work:\n            // https://github.com/matrix-org/synapse/commit/2390b66bf0ec3ff5ffb0c7333f3c9b239eeb92bb\n            return fetch(url, fetchConfigForToken(auth?.accessToken));\n        })(),\n    );\n});\n\nasync function tryUpdateServerSupportMap(clientApiUrl: string, accessToken?: string): Promise<void> {\n    // only update if we don't know about it, or if the data is stale\n    if (serverSupportMap[clientApiUrl]?.cacheExpiryTimeMs > new Date().getTime()) {\n        return; // up to date\n    }\n\n    const config = fetchConfigForToken(accessToken);\n    const versions = await (await fetch(`${clientApiUrl}/_matrix/client/versions`, config)).json();\n    console.log(`[ServiceWorker] /versions response for '${clientApiUrl}': ${JSON.stringify(versions)}`);\n\n    serverSupportMap[clientApiUrl] = {\n        supportsAuthedMedia: Boolean(versions?.versions?.includes(\"v1.11\")),\n        cacheExpiryTimeMs: new Date().getTime() + 2 * 60 * 60 * 1000, // 2 hours from now\n    };\n    console.log(\n        `[ServiceWorker] serverSupportMap update for '${clientApiUrl}': ${JSON.stringify(serverSupportMap[clientApiUrl])}`,\n    );\n}\n\n// Ideally we'd use the `Client` interface for `client`, but since it's not available (see 'fetch' listener), we use\n// unknown for now and force-cast it to something close enough later.\nasync function getAuthData(client: unknown): Promise<{ accessToken: string; homeserver: string }> {\n    // Access tokens are encrypted at rest, so while we can grab the \"access token\", we'll need to do work to get the\n    // real thing.\n    const encryptedAccessToken = await idbLoad(\"account\", \"mx_access_token\");\n\n    // We need to extract a user ID and device ID from localstorage, which means calling WebPlatform for the\n    // read operation. Service workers can't access localstorage.\n    const { userId, deviceId, homeserver } = await askClientForUserIdParams(client);\n\n    // ... and this is why we need the user ID and device ID: they're index keys for the pickle key table.\n    const pickleKeyData = await idbLoad(\"pickleKey\", [userId, deviceId]);\n    if (pickleKeyData && (!pickleKeyData.encrypted || !pickleKeyData.iv || !pickleKeyData.cryptoKey)) {\n        throw new Error(\"SW: Invalid pickle key loaded - ignoring\");\n    }\n\n    // Finally, try decrypting the thing and return that. This may fail, but that's okay.\n    try {\n        const pickleKey = await buildAndEncodePickleKey(pickleKeyData, userId, deviceId);\n        const accessToken = await tryDecryptToken(pickleKey, encryptedAccessToken, ACCESS_TOKEN_IV);\n        return { accessToken, homeserver };\n    } catch (e) {\n        throw new Error(\"SW: Error decrypting access token.\", { cause: e });\n    }\n}\n\n// Ideally we'd use the `Client` interface for `client`, but since it's not available (see 'fetch' listener), we use\n// unknown for now and force-cast it to something close enough inside the function.\nasync function askClientForUserIdParams(\n    client: unknown,\n): Promise<{ userId: string; deviceId: string; homeserver: string }> {\n    return new Promise((resolve, reject) => {\n        // Dev note: this uses postMessage, which is a highly insecure channel. postMessage is typically visible to other\n        // tabs, windows, browser extensions, etc, making it far from ideal for sharing sensitive information. This is\n        // why our service worker calculates/decrypts the access token manually: we don't want the user's access token\n        // to be available to (potentially) malicious listeners. We do require some information for that decryption to\n        // work though, and request that in the least sensitive way possible.\n        //\n        // We could also potentially use some version of TLS to encrypt postMessage, though that feels way more involved\n        // than just reading IndexedDB ourselves.\n\n        // Avoid stalling the tab in case something goes wrong.\n        const timeoutId = setTimeout(() => reject(new Error(\"timeout in postMessage\")), 1000);\n\n        // We don't need particularly good randomness here - we just use this to generate a request ID, so we know\n        // which postMessage reply is for our active request.\n        const responseKey = Math.random().toString(36);\n\n        // Add the listener first, just in case the tab is *really* fast.\n        const listener = (event: MessageEvent): void => {\n            if (event.data?.responseKey !== responseKey) return; // not for us\n            clearTimeout(timeoutId); // do this as soon as possible, avoiding a race between resolve and reject.\n            resolve(event.data); // \"unblock\" the remainder of the thread, if that were such a thing in JavaScript.\n            global.removeEventListener(\"message\", listener); // cleanup, since we're not going to do anything else.\n        };\n        global.addEventListener(\"message\", listener);\n\n        // Ask the tab for the information we need. This is handled by WebPlatform.\n        (client as Window).postMessage({ responseKey, type: \"userinfo\" });\n    });\n}\n\nfunction fetchConfigForToken(accessToken?: string): RequestInit | undefined {\n    if (!accessToken) {\n        return undefined; // no headers/config to specify\n    }\n\n    return {\n        headers: {\n            Authorization: `Bearer ${accessToken}`,\n        },\n    };\n}\n"],"names":["__WEBPACK_AMD_DEFINE_FACTORY__","__WEBPACK_AMD_DEFINE_RESULT__","noop","undefinedType","isIE","window","navigator","test","userAgent","logMethods","_loggersByName","defaultLogger","bindMethod","obj","methodName","method","bind","Function","prototype","call","e","apply","arguments","traceForIE","console","log","trace","realMethod","undefined","replaceLoggingMethods","level","this","getLevel","i","length","methodFactory","name","debug","levels","SILENT","enableLoggingWhenConsoleArrives","defaultMethodFactory","_level","_loggerName","Logger","factory","inheritedLevel","defaultLevel","userLevel","self","storageKey","persistLevelIfPossible","levelNum","levelName","toUpperCase","localStorage","ignore","document","cookie","encodeURIComponent","getPersistedLevel","storedLevel","cookieName","location","indexOf","exec","slice","clearPersistedLevel","removeItem","normalizeLevel","input","TypeError","TRACE","DEBUG","INFO","WARN","ERROR","setLevel","persist","setDefaultLevel","resetLevel","enableAll","disableAll","rebuild","childName","initialLevel","getLogger","logger","_log","noConflict","getLoggers","exports","__webpack_require__","module","__webpack_module_cache__","moduleId","cachedModule","__webpack_modules__","n","getter","__esModule","d","a","definition","Array","isArray","key","binding","o","Object","defineProperty","enumerable","value","get","g","globalThis","prop","hasOwnProperty","oldGetScript","u","oldLoadScript","queryMap","countMap","chunkId","catch","error","retries","realSrc","message","request","Promise","resolve","setTimeout","cacheBust","Date","now","getIDBFactory","_self","indexedDB","idb","async","idbInit","Error","reject","open","onerror","onsuccess","result","onupgradeneeded","db","createObjectStore","idbTransaction","table","mode","fn","txn","transaction","objectStore","idbLoad","loglevel","logLevel","loggerName","args","prefix","unshift","getPrefixedLogger","prefixLogger","getChild","childPrefix","childLogger","toBase64","uint8Array","options","base64","btoa","reduce","acc","current","String","fromCharCode","omitPadding","replace","alphabet","decodeBase64","Uint8Array","fromBase64","from","atob","c","charCodeAt","lastChunkHandling","zeroSalt","decryptAESSecretStorageItem","data","aesKey","hmacKey","hkdfkey","crypto","subtle","importKey","keybits","deriveBits","salt","info","TextEncoder","encode","hash","aesProm","hmacProm","all","deriveKeys","ciphertext","verify","mac","plaintext","decrypt","counter","iv","TextDecoder","decode","ACCESS_TOKEN_IV","pickleKeyToAesKey","pickleKey","pickleKeyBuffer","hkdfKey","fill","getPickleAdditionalData","userId","deviceId","additionalData","buildAndEncodePickleKey","_crypto2","encrypted","cryptoKey","pickleKeyBuf","serverSupportMap","fetchConfigForToken","accessToken","headers","Authorization","global","addEventListener","event","waitUntil","skipWaiting","clients","claim","url","URL","pathname","startsWith","respondWith","auth","csApi","origin","Math","random","client","clientId","encryptedAccessToken","homeserver","timeoutId","responseKey","toString","listener","_event$data","clearTimeout","removeEventListener","postMessage","type","askClientForUserIdParams","pickleKeyData","token","tokenName","encrKey","decryptedToken","tryDecryptToken","cause","getAuthData","clientApiUrl","_serverSupportMap$cli","_versions$versions","cacheExpiryTimeMs","getTime","config","versions","fetch","json","JSON","stringify","supportsAuthedMedia","Boolean","includes","tryUpdateServerSupportMap","href","err","_auth"],"sourceRoot":""}