1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2025-07-30 04:23:07 +03:00

Replace usages of global with globalThis (#4489)

* Update src with globalThis

* Update spec with globalThis

* Replace in more spec/ places

* More changes to src/

* Add a linter rule for global

* Prettify

* lint
This commit is contained in:
Will Hunt
2024-11-01 09:15:21 +00:00
committed by GitHub
parent d04135cc1c
commit f6a169b5a5
64 changed files with 224 additions and 218 deletions

View File

@ -63,6 +63,10 @@ module.exports = {
name: "setImmediate",
message: "Use setTimeout instead.",
},
{
name: "global",
message: "Use globalThis instead.",
},
],
"import/no-restricted-paths": [

View File

@ -66,7 +66,7 @@ export class TestClient implements IE2EKeyReceiver, ISyncResponder {
userId: userId,
accessToken: accessToken,
deviceId: deviceId,
fetchFn: this.httpBackend.fetchFn as typeof global.fetch,
fetchFn: this.httpBackend.fetchFn as typeof globalThis.fetch,
...options,
};
if (!fullOptions.cryptoStore) {

View File

@ -136,7 +136,7 @@ async function expectSendRoomKey(
recipientOlmAccount: Olm.Account,
recipientOlmSession: Olm.Session | null = null,
): Promise<Olm.InboundGroupSession> {
const Olm = global.Olm;
const Olm = globalThis.Olm;
const testRecipientKey = JSON.parse(recipientOlmAccount.identity_keys())["curve25519"];
function onSendRoomKey(content: any): Olm.InboundGroupSession {
@ -219,7 +219,7 @@ async function expectSendMegolmMessage(
}
describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, initCrypto: InitCrypto) => {
if (!global.Olm) {
if (!globalThis.Olm) {
// currently we use libolm to implement the crypto in the tests, so need it to be present.
logger.warn("not running megolm tests: Olm not present");
return;
@ -230,7 +230,7 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string,
const oldBackendOnly = backend === "rust-sdk" ? test.skip : test;
const newBackendOnly = backend !== "rust-sdk" ? test.skip : test;
const Olm = global.Olm;
const Olm = globalThis.Olm;
let testOlmAccount = {} as unknown as Olm.Account;
let testSenderKey = "";
@ -1897,13 +1897,13 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string,
const aliceOtks = await keyReceiver.awaitOneTimeKeyUpload();
const aliceOtkId = Object.keys(aliceOtks)[0];
const aliceOtk = aliceOtks[aliceOtkId];
const p2pSession = new global.Olm.Session();
const p2pSession = new globalThis.Olm.Session();
await beccaTestClient.client.crypto!.cryptoStore.doTxn(
"readonly",
[IndexedDBCryptoStore.STORE_ACCOUNT],
(txn) => {
beccaTestClient.client.crypto!.cryptoStore.getAccount(txn, (pickledAccount: string | null) => {
const account = new global.Olm.Account();
const account = new globalThis.Olm.Account();
try {
account.unpickle(beccaTestClient.client.crypto!.olmDevice.pickleKey, pickledAccount!);
p2pSession.create_outbound(account, keyReceiver.getDeviceKey(), aliceOtk.key);
@ -2045,13 +2045,13 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string,
const aliceOtks = await keyReceiver.awaitOneTimeKeyUpload();
const aliceOtkId = Object.keys(aliceOtks)[0];
const aliceOtk = aliceOtks[aliceOtkId];
const p2pSession = new global.Olm.Session();
const p2pSession = new globalThis.Olm.Session();
await beccaTestClient.client.crypto!.cryptoStore.doTxn(
"readonly",
[IndexedDBCryptoStore.STORE_ACCOUNT],
(txn) => {
beccaTestClient.client.crypto!.cryptoStore.getAccount(txn, (pickledAccount: string | null) => {
const account = new global.Olm.Account();
const account = new globalThis.Olm.Account();
try {
account.unpickle(beccaTestClient.client.crypto!.olmDevice.pickleKey, pickledAccount!);
p2pSession.create_outbound(account, keyReceiver.getDeviceKey(), aliceOtk.key);

View File

@ -85,15 +85,15 @@ export function bootstrapCrossSigningTestOlmAccount(
deviceId: string,
keyBackupInfo: KeyBackupInfo[] = [],
): Partial<IDownloadKeyResult> {
const olmAliceMSK = new global.Olm.PkSigning();
const olmAliceMSK = new globalThis.Olm.PkSigning();
const masterPrivkey = olmAliceMSK.generate_seed();
const masterPubkey = olmAliceMSK.init_with_seed(masterPrivkey);
const olmAliceUSK = new global.Olm.PkSigning();
const olmAliceUSK = new globalThis.Olm.PkSigning();
const userPrivkey = olmAliceUSK.generate_seed();
const userPubkey = olmAliceUSK.init_with_seed(userPrivkey);
const olmAliceSSK = new global.Olm.PkSigning();
const olmAliceSSK = new globalThis.Olm.PkSigning();
const sskPrivkey = olmAliceSSK.generate_seed();
const sskPubkey = olmAliceSSK.init_with_seed(sskPrivkey);
@ -181,7 +181,7 @@ export async function createOlmSession(
const otkId = Object.keys(keys)[0];
const otk = keys[otkId];
const session = new global.Olm.Session();
const session = new globalThis.Olm.Session();
session.create_outbound(olmAccount, recipientTestClient.getDeviceKey(), otk.key);
return session;
}

View File

@ -90,7 +90,7 @@ jest.useFakeTimers({ doNotFake: ["queueMicrotask"] });
beforeAll(async () => {
// we use the libolm primitives in the test, so init the Olm library
await global.Olm.init();
await globalThis.Olm.init();
});
// load the rust library. This can take a few seconds on a slow GH worker.
@ -264,7 +264,7 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("verification (%s)", (backend: st
// The dummy device makes up a curve25519 keypair and sends the public bit back in an `m.key.verification.key'
// We use the Curve25519, HMAC and HKDF implementations in libolm, for now
const olmSAS = new global.Olm.SAS();
const olmSAS = new globalThis.Olm.SAS();
returnToDeviceMessageFromSync(buildSasKeyMessage(transactionId, olmSAS.get_pubkey()));
// alice responds with a 'key' ...
@ -358,7 +358,7 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("verification (%s)", (backend: st
// The dummy device makes up a curve25519 keypair and uses the hash in an 'm.key.verification.accept'
// We use the Curve25519, HMAC and HKDF implementations in libolm, for now
const olmSAS = new global.Olm.SAS();
const olmSAS = new globalThis.Olm.SAS();
const commitmentStr = olmSAS.get_pubkey() + anotherjson.stringify(toDeviceMessage);
sendToDevicePromise = expectSendToDeviceMessage("m.key.verification.key");

View File

@ -67,7 +67,7 @@ function getSyncResponse(roomMembers: string[]) {
}
describe("DeviceList management:", function () {
if (!global.Olm) {
if (!globalThis.Olm) {
logger.warn("not running deviceList tests: Olm not present");
return;
}

View File

@ -80,7 +80,7 @@ describe("MatrixClient opts", function () {
let client: MatrixClient;
beforeEach(function () {
client = new MatrixClient({
fetchFn: httpBackend.fetchFn as typeof global.fetch,
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
store: undefined,
baseUrl: baseUrl,
userId: userId,
@ -135,7 +135,7 @@ describe("MatrixClient opts", function () {
let client: MatrixClient;
beforeEach(function () {
client = new MatrixClient({
fetchFn: httpBackend.fetchFn as typeof global.fetch,
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
store: new MemoryStore() as IStore,
baseUrl: baseUrl,
userId: userId,

View File

@ -2406,7 +2406,7 @@ describe("MatrixClient syncing (IndexedDB version)", () => {
it("should emit ClientEvent.Room when invited while using indexeddb crypto store", async () => {
const idbTestClient = new TestClient(selfUserId, "DEVICE", selfAccessToken, undefined, {
cryptoStore: new IndexedDBCryptoStore(global.indexedDB, "tests"),
cryptoStore: new IndexedDBCryptoStore(globalThis.indexedDB, "tests"),
});
const idbHttpBackend = idbTestClient.httpBackend;
const idbClient = idbTestClient.client;
@ -2486,7 +2486,7 @@ describe("MatrixClient syncing (IndexedDB version)", () => {
let idbTestClient = new TestClient(selfUserId, "DEVICE", selfAccessToken, undefined, {
store: new IndexedDBStore({
indexedDB: global.indexedDB,
indexedDB: globalThis.indexedDB,
dbName: "test",
}),
});
@ -2558,7 +2558,7 @@ describe("MatrixClient syncing (IndexedDB version)", () => {
idbTestClient = new TestClient(selfUserId, "DEVICE", selfAccessToken, undefined, {
store: new IndexedDBStore({
indexedDB: global.indexedDB,
indexedDB: globalThis.indexedDB,
dbName: "test",
}),
});

View File

@ -266,7 +266,7 @@ describe("MSC4108SignInWithQR", () => {
});
it("should abort if device doesn't come up by timeout", async () => {
jest.spyOn(global, "setTimeout").mockImplementation((fn) => {
jest.spyOn(globalThis, "setTimeout").mockImplementation((fn) => {
fn();
// TODO: mock timers properly
return -1 as any;
@ -319,7 +319,7 @@ describe("MSC4108SignInWithQR", () => {
});
it("should not send secrets if user cancels", async () => {
jest.spyOn(global, "setTimeout").mockImplementation((fn) => {
jest.spyOn(globalThis, "setTimeout").mockImplementation((fn) => {
fn();
// TODO: mock timers properly
return -1 as any;

View File

@ -560,7 +560,7 @@ export const CRYPTO_BACKENDS: Record<string, InitCrypto> = {};
export type InitCrypto = (_: MatrixClient) => Promise<void>;
CRYPTO_BACKENDS["rust-sdk"] = (client: MatrixClient) => client.initRustCrypto();
if (global.Olm) {
if (globalThis.Olm) {
CRYPTO_BACKENDS["libolm"] = (client: MatrixClient) => client.initCrypto();
}

View File

@ -582,11 +582,11 @@ export class MockCallFeed {
}
export function installWebRTCMocks() {
global.navigator = {
globalThis.navigator = {
mediaDevices: new MockMediaDevices().typed(),
} as unknown as Navigator;
global.window = {
globalThis.window = {
// @ts-ignore Mock
RTCPeerConnection: MockRTCPeerConnection,
// @ts-ignore Mock
@ -596,13 +596,13 @@ export function installWebRTCMocks() {
getUserMedia: () => new MockMediaStream("local_stream"),
};
// @ts-ignore Mock
global.document = {};
globalThis.document = {};
// @ts-ignore Mock
global.AudioContext = MockAudioContext;
globalThis.AudioContext = MockAudioContext;
// @ts-ignore Mock
global.RTCRtpReceiver = {
globalThis.RTCRtpReceiver = {
getCapabilities: jest.fn<RTCRtpCapabilities, [string]>().mockReturnValue({
codecs: [],
headerExtensions: [],
@ -610,7 +610,7 @@ export function installWebRTCMocks() {
};
// @ts-ignore Mock
global.RTCRtpSender = {
globalThis.RTCRtpSender = {
getCapabilities: jest.fn<RTCRtpCapabilities, [string]>().mockReturnValue({
codecs: [],
headerExtensions: [],

View File

@ -22,12 +22,12 @@ import { AutoDiscovery } from "../../src/autodiscovery";
// keep to reset the fetch function after using MockHttpBackend
// @ts-ignore private property
const realAutoDiscoveryFetch: typeof global.fetch = AutoDiscovery.fetchFn;
const realAutoDiscoveryFetch: typeof globalThis.fetch = AutoDiscovery.fetchFn;
describe("AutoDiscovery", function () {
const getHttpBackend = (): MockHttpBackend => {
const httpBackend = new MockHttpBackend();
AutoDiscovery.setFetchFn(httpBackend.fetchFn as typeof global.fetch);
AutoDiscovery.setFetchFn(httpBackend.fetchFn as typeof globalThis.fetch);
return httpBackend;
};

View File

@ -29,8 +29,8 @@ describe.each(["browser", "node"])("Base64 encoding (%s)", (env) => {
// eslint-disable-next-line no-global-assign
Buffer = undefined;
global.atob = NodeBuffer.atob;
global.btoa = NodeBuffer.btoa;
globalThis.atob = NodeBuffer.atob;
globalThis.btoa = NodeBuffer.btoa;
}
});
@ -38,9 +38,9 @@ describe.each(["browser", "node"])("Base64 encoding (%s)", (env) => {
// eslint-disable-next-line no-global-assign
Buffer = origBuffer;
// @ts-ignore
global.atob = undefined;
globalThis.atob = undefined;
// @ts-ignore
global.btoa = undefined;
globalThis.btoa = undefined;
});
it("Should decode properly encoded data", () => {

View File

@ -29,10 +29,10 @@ describe("Beacon content helpers", () => {
describe("makeBeaconInfoContent()", () => {
const mockDateNow = 123456789;
beforeEach(() => {
jest.spyOn(global.Date, "now").mockReturnValue(mockDateNow);
jest.spyOn(globalThis.Date, "now").mockReturnValue(mockDateNow);
});
afterAll(() => {
jest.spyOn(global.Date, "now").mockRestore();
jest.spyOn(globalThis.Date, "now").mockRestore();
});
it("create fully defined event content", () => {
expect(makeBeaconInfoContent(1234, true, "nice beacon_info", LocationAssetType.Pin)).toEqual({

View File

@ -28,7 +28,7 @@ import * as testData from "../test-utils/test-data";
import { KnownMembership } from "../../src/@types/membership";
import type { DeviceInfoMap } from "../../src/crypto/DeviceList";
const Olm = global.Olm;
const Olm = globalThis.Olm;
function awaitEvent(emitter: EventEmitter, event: string): Promise<void> {
return new Promise((resolve) => {

View File

@ -44,13 +44,13 @@ badKey[0] ^= 1;
const masterKeyPub = "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk";
describe("CrossSigningInfo.getCrossSigningKey", function () {
if (!global.Olm) {
if (!globalThis.Olm) {
logger.warn("Not running megolm backup unit tests: libolm not present");
return;
}
beforeAll(function () {
return global.Olm.init();
return globalThis.Olm.init();
});
it("should throw if no callback is provided", async () => {
@ -80,7 +80,7 @@ describe("CrossSigningInfo.getCrossSigningKey", function () {
expect(pubKey).toEqual(masterKeyPub);
// check that the pkSigning object corresponds to the pubKey
const signature = pkSigning.sign("message");
const util = new global.Olm.Utility();
const util = new globalThis.Olm.Utility();
try {
util.ed25519_verify(pubKey, "message", signature);
} finally {
@ -199,7 +199,7 @@ describe("CrossSigningInfo.getCrossSigningKey", function () {
* it's not possible to get one in normal execution unless you hack as we do here.
*/
describe.each([
["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(global.indexedDB, "tests")],
["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(globalThis.indexedDB, "tests")],
["LocalStorageCryptoStore", () => new IndexedDBCryptoStore(undefined!, "tests")],
[
"MemoryCryptoStore",

View File

@ -43,10 +43,10 @@ const MegolmEncryption = algorithms.ENCRYPTION_CLASSES.get("m.megolm.v1.aes-sha2
const ROOM_ID = "!ROOM:ID";
const Olm = global.Olm;
const Olm = globalThis.Olm;
describe("MegolmDecryption", function () {
if (!global.Olm) {
if (!globalThis.Olm) {
logger.warn("Not running megolm unit tests: libolm not present");
return;
}
@ -101,7 +101,7 @@ describe("MegolmDecryption", function () {
describe("receives some keys:", function () {
let groupSession: OutboundGroupSession;
beforeEach(async function () {
groupSession = new global.Olm.OutboundGroupSession();
groupSession = new globalThis.Olm.OutboundGroupSession();
groupSession.create();
// construct a fake decrypted key event via the use of a mocked

View File

@ -47,13 +47,13 @@ function alwaysSucceed<T>(promise: Promise<T>): Promise<T | void> {
}
describe("OlmDevice", function () {
if (!global.Olm) {
if (!globalThis.Olm) {
logger.warn("Not running megolm unit tests: libolm not present");
return;
}
beforeAll(function () {
return global.Olm.init();
return globalThis.Olm.init();
});
let aliceOlmDevice: OlmDevice;

View File

@ -33,7 +33,7 @@ import { CryptoStore } from "../../../src/crypto/store/base";
import { MegolmDecryption as MegolmDecryptionClass } from "../../../src/crypto/algorithms/megolm";
import { IKeyBackupInfo } from "../../../src/crypto/keybackup";
const Olm = global.Olm;
const Olm = globalThis.Olm;
const MegolmDecryption = algorithms.DECRYPTION_CLASSES.get("m.megolm.v1.aes-sha2")!;
@ -155,7 +155,7 @@ function makeTestClient(cryptoStore: CryptoStore) {
}
describe("MegolmBackup", function () {
if (!global.Olm) {
if (!globalThis.Olm) {
logger.warn("Not running megolm backup unit tests: libolm not present");
return;
}
@ -205,14 +205,14 @@ describe("MegolmBackup", function () {
// clobber the setTimeout function to run 100x faster.
// ideally we would use lolex, but we have no oportunity
// to tick the clock between the first try and the retry.
const realSetTimeout = global.setTimeout;
jest.spyOn(global, "setTimeout").mockImplementation(function (f, n) {
const realSetTimeout = globalThis.setTimeout;
jest.spyOn(globalThis, "setTimeout").mockImplementation(function (f, n) {
return realSetTimeout(f!, n! / 100);
});
});
afterEach(function () {
jest.spyOn(global, "setTimeout").mockRestore();
jest.spyOn(globalThis, "setTimeout").mockRestore();
});
test("fail if crypto not enabled", async () => {

View File

@ -84,13 +84,13 @@ async function makeTestClient(
}
describe("Cross Signing", function () {
if (!global.Olm) {
if (!globalThis.Olm) {
logger.warn("Not running megolm backup unit tests: libolm not present");
return;
}
beforeAll(function () {
return global.Olm.init();
return globalThis.Olm.init();
});
it("should sign the master key with the device key", async function () {
@ -369,10 +369,10 @@ describe("Cross Signing", function () {
// set Alice's cross-signing key
await resetCrossSigningKeys(alice);
// Alice downloads Bob's ssk and device key
const bobMasterSigning = new global.Olm.PkSigning();
const bobMasterSigning = new globalThis.Olm.PkSigning();
const bobMasterPrivkey = bobMasterSigning.generate_seed();
const bobMasterPubkey = bobMasterSigning.init_with_seed(bobMasterPrivkey);
const bobSigning = new global.Olm.PkSigning();
const bobSigning = new globalThis.Olm.PkSigning();
const bobPrivkey = bobSigning.generate_seed();
const bobPubkey = bobSigning.init_with_seed(bobPrivkey);
const bobSSK: CrossSigningKeyInfo = {
@ -488,7 +488,7 @@ describe("Cross Signing", function () {
};
await alice.crypto!.signObject(aliceDevice);
const bobOlmAccount = new global.Olm.Account();
const bobOlmAccount = new globalThis.Olm.Account();
bobOlmAccount.create();
const bobKeys = JSON.parse(bobOlmAccount.identity_keys());
const bobDeviceUnsigned = {
@ -622,10 +622,10 @@ describe("Cross Signing", function () {
await resetCrossSigningKeys(alice);
// Alice downloads Bob's ssk and device key
// (NOTE: device key is not signed by ssk)
const bobMasterSigning = new global.Olm.PkSigning();
const bobMasterSigning = new globalThis.Olm.PkSigning();
const bobMasterPrivkey = bobMasterSigning.generate_seed();
const bobMasterPubkey = bobMasterSigning.init_with_seed(bobMasterPrivkey);
const bobSigning = new global.Olm.PkSigning();
const bobSigning = new globalThis.Olm.PkSigning();
const bobPrivkey = bobSigning.generate_seed();
const bobPubkey = bobSigning.init_with_seed(bobPrivkey);
const bobSSK: CrossSigningKeyInfo = {
@ -688,10 +688,10 @@ describe("Cross Signing", function () {
alice.uploadKeySignatures = async () => ({ failures: {} });
await resetCrossSigningKeys(alice);
// Alice downloads Bob's keys
const bobMasterSigning = new global.Olm.PkSigning();
const bobMasterSigning = new globalThis.Olm.PkSigning();
const bobMasterPrivkey = bobMasterSigning.generate_seed();
const bobMasterPubkey = bobMasterSigning.init_with_seed(bobMasterPrivkey);
const bobSigning = new global.Olm.PkSigning();
const bobSigning = new globalThis.Olm.PkSigning();
const bobPrivkey = bobSigning.generate_seed();
const bobPubkey = bobSigning.init_with_seed(bobPrivkey);
const bobSSK: CrossSigningKeyInfo = {
@ -755,10 +755,10 @@ describe("Cross Signing", function () {
expect(bobDeviceTrust.isTofu()).toBeTruthy();
// Alice downloads new SSK for Bob
const bobMasterSigning2 = new global.Olm.PkSigning();
const bobMasterSigning2 = new globalThis.Olm.PkSigning();
const bobMasterPrivkey2 = bobMasterSigning2.generate_seed();
const bobMasterPubkey2 = bobMasterSigning2.init_with_seed(bobMasterPrivkey2);
const bobSigning2 = new global.Olm.PkSigning();
const bobSigning2 = new globalThis.Olm.PkSigning();
const bobPrivkey2 = bobSigning2.generate_seed();
const bobPubkey2 = bobSigning2.init_with_seed(bobPrivkey2);
const bobSSK2: CrossSigningKeyInfo = {
@ -905,10 +905,10 @@ describe("Cross Signing", function () {
alice.uploadKeySignatures = async () => ({ failures: {} });
// Generate Alice's SSK etc
const aliceMasterSigning = new global.Olm.PkSigning();
const aliceMasterSigning = new globalThis.Olm.PkSigning();
const aliceMasterPrivkey = aliceMasterSigning.generate_seed();
const aliceMasterPubkey = aliceMasterSigning.init_with_seed(aliceMasterPrivkey);
const aliceSigning = new global.Olm.PkSigning();
const aliceSigning = new globalThis.Olm.PkSigning();
const alicePrivkey = aliceSigning.generate_seed();
const alicePubkey = aliceSigning.init_with_seed(alicePrivkey);
const aliceSSK: CrossSigningKeyInfo = {
@ -980,10 +980,10 @@ describe("Cross Signing", function () {
alice.uploadKeySignatures = async () => ({ failures: {} });
// Generate Alice's SSK etc
const aliceMasterSigning = new global.Olm.PkSigning();
const aliceMasterSigning = new globalThis.Olm.PkSigning();
const aliceMasterPrivkey = aliceMasterSigning.generate_seed();
const aliceMasterPubkey = aliceMasterSigning.init_with_seed(aliceMasterPrivkey);
const aliceSigning = new global.Olm.PkSigning();
const aliceSigning = new globalThis.Olm.PkSigning();
const alicePrivkey = aliceSigning.generate_seed();
const alicePubkey = aliceSigning.init_with_seed(alicePrivkey);
const aliceSSK: CrossSigningKeyInfo = {
@ -1040,10 +1040,10 @@ describe("Cross Signing", function () {
alice.uploadKeySignatures = async () => ({ failures: {} });
// Generate Alice's SSK etc
const aliceMasterSigning = new global.Olm.PkSigning();
const aliceMasterSigning = new globalThis.Olm.PkSigning();
const aliceMasterPrivkey = aliceMasterSigning.generate_seed();
const aliceMasterPubkey = aliceMasterSigning.init_with_seed(aliceMasterPrivkey);
const aliceSigning = new global.Olm.PkSigning();
const aliceSigning = new globalThis.Olm.PkSigning();
const alicePrivkey = aliceSigning.generate_seed();
const alicePubkey = aliceSigning.init_with_seed(alicePrivkey);
const aliceSSK: CrossSigningKeyInfo = {
@ -1088,12 +1088,12 @@ describe("Cross Signing", function () {
});
describe("userHasCrossSigningKeys", function () {
if (!global.Olm) {
if (!globalThis.Olm) {
return;
}
beforeAll(() => {
return global.Olm.init();
return globalThis.Olm.init();
});
let aliceClient: MatrixClient;

View File

@ -32,7 +32,7 @@ export async function resetCrossSigningKeys(
}
export async function createSecretStorageKey(): Promise<IRecoveryKey> {
const decryption = new global.Olm.PkDecryption();
const decryption = new globalThis.Olm.PkDecryption();
decryption.generate_key();
const storagePrivateKey = decryption.get_private_key();
decryption.free();

View File

@ -19,16 +19,16 @@ import { TestClient } from "../../TestClient";
import { logger } from "../../../src/logger";
import { DEHYDRATION_ALGORITHM } from "../../../src/crypto/dehydration";
const Olm = global.Olm;
const Olm = globalThis.Olm;
describe("Dehydration", () => {
if (!global.Olm) {
if (!globalThis.Olm) {
logger.warn("Not running dehydration unit tests: libolm not present");
return;
}
beforeAll(function () {
return global.Olm.init();
return globalThis.Olm.init();
});
it("should rehydrate a dehydrated device", async () => {

View File

@ -51,7 +51,7 @@ const requests = [
];
describe.each([
["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(global.indexedDB, "tests")],
["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(globalThis.indexedDB, "tests")],
["LocalStorageCryptoStore", () => new LocalStorageCryptoStore(localStorage)],
["MemoryCryptoStore", () => new MemoryCryptoStore()],
])("Outgoing room key requests [%s]", function (name, dbFactory) {

View File

@ -69,20 +69,20 @@ function sign<T extends IObject | ICurve25519AuthData>(
}
describe("Secrets", function () {
if (!global.Olm) {
if (!globalThis.Olm) {
logger.warn("Not running megolm backup unit tests: libolm not present");
return;
}
beforeAll(function () {
return global.Olm.init();
return globalThis.Olm.init();
});
it("should store and retrieve a secret", async function () {
const key = new Uint8Array(16);
for (let i = 0; i < 16; i++) key[i] = i;
const signing = new global.Olm.PkSigning();
const signing = new globalThis.Olm.PkSigning();
const signingKey = signing.generate_seed();
const signingPubKey = signing.init_with_seed(signingKey);
@ -332,7 +332,7 @@ describe("Secrets", function () {
});
it("bootstraps when cross-signing keys in secret storage", async function () {
const decryption = new global.Olm.PkDecryption();
const decryption = new globalThis.Olm.PkDecryption();
const storagePrivateKey = decryption.get_private_key();
const bob: MatrixClient = await makeTestClient(

View File

@ -20,7 +20,7 @@ import { IndexedDBCryptoStore, LocalStorageCryptoStore, MemoryCryptoStore } from
import { CryptoStore, MigrationState, SESSION_BATCH_SIZE } from "../../../../src/crypto/store/base";
describe.each([
["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(global.indexedDB, "tests")],
["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(globalThis.indexedDB, "tests")],
["LocalStorageCryptoStore", () => new LocalStorageCryptoStore(localStorage)],
["MemoryCryptoStore", () => new MemoryCryptoStore()],
])("CryptoStore tests for %s", function (name, dbFactory) {

View File

@ -27,21 +27,21 @@ describe("IndexedDBCryptoStore", () => {
it("Should be true if there is a legacy database", async () => {
// should detect a store that is not migrated
const store = new IndexedDBCryptoStore(global.indexedDB, "tests");
const store = new IndexedDBCryptoStore(globalThis.indexedDB, "tests");
await store.startup();
const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(global.indexedDB, "tests");
const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(globalThis.indexedDB, "tests");
expect(result).toBe(true);
});
it("Should be true if there is a legacy database in non migrated state", async () => {
// should detect a store that is not migrated
const store = new IndexedDBCryptoStore(global.indexedDB, "tests");
const store = new IndexedDBCryptoStore(globalThis.indexedDB, "tests");
await store.startup();
await store.setMigrationState(MigrationState.NOT_STARTED);
const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(global.indexedDB, "tests");
const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(globalThis.indexedDB, "tests");
expect(result).toBe(true);
});
@ -54,18 +54,18 @@ describe("IndexedDBCryptoStore", () => {
])("Exists and Migration state is %s", (migrationState) => {
it("Should be false if migration has started", async () => {
// should detect a store that is not migrated
const store = new IndexedDBCryptoStore(global.indexedDB, "tests");
const store = new IndexedDBCryptoStore(globalThis.indexedDB, "tests");
await store.startup();
await store.setMigrationState(migrationState);
const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(global.indexedDB, "tests");
const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(globalThis.indexedDB, "tests");
expect(result).toBe(false);
});
});
it("Should be false if there is no legacy database", async () => {
const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(global.indexedDB, "tests");
const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(globalThis.indexedDB, "tests");
expect(result).toBe(false);
});

View File

@ -17,10 +17,10 @@ limitations under the License.
import "../../../olm-loader";
import { logger } from "../../../../src/logger";
const Olm = global.Olm;
const Olm = globalThis.Olm;
describe("QR code verification", function () {
if (!global.Olm) {
if (!globalThis.Olm) {
logger.warn("Not running device verification tests: libolm not present");
return;
}

View File

@ -20,12 +20,12 @@ import { logger } from "../../../../src/logger";
import { SAS } from "../../../../src/crypto/verification/SAS";
import { makeTestClients } from "./util";
const Olm = global.Olm;
const Olm = globalThis.Olm;
jest.useFakeTimers();
describe("verification request integration tests with crypto layer", function () {
if (!global.Olm) {
if (!globalThis.Olm) {
logger.warn("Not running device verification unit tests: libolm not present");
return;
}

View File

@ -29,13 +29,13 @@ import { MatrixClient } from "../../../../src";
import { VerificationRequest } from "../../../../src/crypto/verification/request/VerificationRequest";
import { TestClient } from "../../../TestClient";
const Olm = global.Olm;
const Olm = globalThis.Olm;
let ALICE_DEVICES: Record<string, IDevice>;
let BOB_DEVICES: Record<string, IDevice>;
describe("SAS verification", function () {
if (!global.Olm) {
if (!globalThis.Olm) {
logger.warn("Not running device verification unit tests: libolm not present");
return;
}

View File

@ -34,7 +34,7 @@ const testKeyPub = "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk";
describe("self-verifications", () => {
beforeAll(function () {
return global.Olm.init();
return globalThis.Olm.init();
});
it("triggers a request for key sharing upon completion", async () => {

View File

@ -29,12 +29,12 @@ describe("sha256", () => {
});
it("throws if webcrypto is not available", async () => {
const oldCrypto = global.crypto;
const oldCrypto = globalThis.crypto;
try {
global.crypto = {} as any;
globalThis.crypto = {} as any;
await expect(sha256("test")).rejects.toThrow();
} finally {
global.crypto = oldCrypto;
globalThis.crypto = oldCrypto;
}
});
});

View File

@ -57,7 +57,7 @@ describe("MatrixError", () => {
it("should retrieve Date Retry-After header from rate-limit error", () => {
headers.set("Retry-After", `${new Date(160000).toUTCString()}`);
jest.spyOn(global.Date, "now").mockImplementationOnce(() => 100000);
jest.spyOn(globalThis.Date, "now").mockImplementationOnce(() => 100000);
const err = makeMatrixError(429, { errcode: "M_LIMIT_EXCEEDED", retry_after_ms: 150000 });
expect(err.isRateLimitError()).toBe(true);
// prefer Retry-After header over retry_after_ms

View File

@ -60,11 +60,11 @@ describe("FetchHttpApi", () => {
});
it("should fall back to global fetch if fetchFn not provided", () => {
global.fetch = jest.fn();
expect(global.fetch).not.toHaveBeenCalled();
globalThis.fetch = jest.fn();
expect(globalThis.fetch).not.toHaveBeenCalled();
const api = new FetchHttpApi(new TypedEventEmitter<any, any>(), { baseUrl, prefix });
api.fetch("test");
expect(global.fetch).toHaveBeenCalled();
expect(globalThis.fetch).toHaveBeenCalled();
});
it("should update identity server base url", () => {

View File

@ -45,9 +45,9 @@ describe("MatrixHttpApi", () => {
} as unknown as XMLHttpRequest;
// We stub out XHR here as it is not available in JSDOM
// @ts-ignore
global.XMLHttpRequest = jest.fn().mockReturnValue(xhr);
globalThis.XMLHttpRequest = jest.fn().mockReturnValue(xhr);
// @ts-ignore
global.XMLHttpRequest.DONE = DONE;
globalThis.XMLHttpRequest.DONE = DONE;
});
afterEach(() => {
@ -60,7 +60,7 @@ describe("MatrixHttpApi", () => {
});
it("should fall back to `fetch` where xhr is unavailable", () => {
global.XMLHttpRequest = undefined!;
globalThis.XMLHttpRequest = undefined!;
const fetchFn = jest.fn().mockResolvedValue({ ok: true, json: jest.fn().mockResolvedValue({}) });
const api = new MatrixHttpApi(new TypedEventEmitter<any, any>(), { baseUrl, prefix, fetchFn });
upload = api.uploadContent({} as File);

View File

@ -70,7 +70,7 @@ describe("Beacon", () => {
const advanceDateAndTime = (ms: number) => {
// bc liveness check uses Date.now we have to advance this mock
jest.spyOn(global.Date, "now").mockReturnValue(Date.now() + ms);
jest.spyOn(globalThis.Date, "now").mockReturnValue(Date.now() + ms);
// then advance time for the interval by the same amount
jest.advanceTimersByTime(ms);
};
@ -108,11 +108,11 @@ describe("Beacon", () => {
);
// back to 'now'
jest.spyOn(global.Date, "now").mockReturnValue(now);
jest.spyOn(globalThis.Date, "now").mockReturnValue(now);
});
afterAll(() => {
jest.spyOn(global.Date, "now").mockRestore();
jest.spyOn(globalThis.Date, "now").mockRestore();
});
it("creates beacon from event", () => {

View File

@ -56,7 +56,7 @@ describe("oidc authorization", () => {
delegatedAuthConfig.metadata.issuer + ".well-known/openid-configuration",
mockOpenIdConfiguration(),
);
global.TextEncoder = TextEncoder;
globalThis.TextEncoder = TextEncoder;
});
beforeEach(() => {

View File

@ -35,7 +35,7 @@ describe("Pushers", () => {
client = new MatrixClient({
baseUrl: "https://my.home.server",
accessToken: "my.access.token",
fetchFn: httpBackend.fetchFn as typeof global.fetch,
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
});
});

View File

@ -82,7 +82,7 @@ describe.each([[StoreType.Memory], [StoreType.IndexedDB]])("queueToDevice (%s st
client = new MatrixClient({
baseUrl: "https://my.home.server",
accessToken: "my.access.token",
fetchFn: httpBackend.fetchFn as typeof global.fetch,
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
store,
});
});
@ -256,7 +256,7 @@ describe.each([[StoreType.Memory], [StoreType.IndexedDB]])("queueToDevice (%s st
client = new MatrixClient({
baseUrl: "https://my.home.server",
accessToken: "my.access.token",
fetchFn: httpBackend.fetchFn as typeof global.fetch,
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
store,
});
});

View File

@ -54,7 +54,7 @@ describe("Read receipt", () => {
userId: "@user:server",
baseUrl: "https://my.home.server",
accessToken: "my.access.token",
fetchFn: httpBackend.fetchFn as typeof global.fetch,
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
});
client.isGuest = () => false;
client.supportsThreads = () => true;

View File

@ -53,8 +53,8 @@ describe("realtime-callbacks", function () {
it("should set 'this' to the global object", function () {
let passed = false;
const callback = function (this: typeof global) {
expect(this).toBe(global); // eslint-disable-line @typescript-eslint/no-invalid-this
const callback = function (this: typeof globalThis) {
expect(this).toBe(globalThis); // eslint-disable-line @typescript-eslint/no-invalid-this
expect(this.console).toBeTruthy(); // eslint-disable-line @typescript-eslint/no-invalid-this
passed = true;
};

View File

@ -61,7 +61,7 @@ describe("OutgoingRequestProcessor", () => {
const httpApi = new MatrixHttpApi(dummyEventEmitter, {
baseUrl: "https://example.com",
prefix: "/_matrix",
fetchFn: httpBackend.fetchFn as typeof global.fetch,
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
onlyData: true,
});

View File

@ -794,7 +794,7 @@ describe("SyncAccumulator", function () {
}
afterEach(() => {
jest.spyOn(global.Date, "now").mockRestore();
jest.spyOn(globalThis.Date, "now").mockRestore();
});
it("should copy summary properties", function () {
@ -851,11 +851,11 @@ describe("SyncAccumulator", function () {
const delta = 1000;
const startingTs = 1000;
jest.spyOn(global.Date, "now").mockReturnValue(startingTs);
jest.spyOn(globalThis.Date, "now").mockReturnValue(startingTs);
sa.accumulate(RES_WITH_AGE);
jest.spyOn(global.Date, "now").mockReturnValue(startingTs + delta);
jest.spyOn(globalThis.Date, "now").mockReturnValue(startingTs + delta);
const output = sa.getJSON();
expect(output.roomsData.join["!foo:bar"].timeline.events[0].unsigned?.age).toEqual(

View File

@ -119,9 +119,9 @@ describe("Call", function () {
const errorListener = () => {};
beforeEach(function () {
prevNavigator = global.navigator;
prevDocument = global.document;
prevWindow = global.window;
prevNavigator = globalThis.navigator;
prevDocument = globalThis.document;
prevWindow = globalThis.window;
installWebRTCMocks();
@ -159,9 +159,9 @@ describe("Call", function () {
call.hangup(CallErrorCode.UserHangup, true);
client.stop();
global.navigator = prevNavigator;
global.window = prevWindow;
global.document = prevDocument;
globalThis.navigator = prevNavigator;
globalThis.window = prevWindow;
globalThis.document = prevDocument;
jest.useRealTimers();
});
@ -788,17 +788,17 @@ describe("Call", function () {
});
it("should return false if window or document are undefined", () => {
global.window = undefined!;
globalThis.window = undefined!;
expect(supportsMatrixCall()).toBe(false);
global.window = prevWindow;
global.document = undefined!;
globalThis.window = prevWindow;
globalThis.document = undefined!;
expect(supportsMatrixCall()).toBe(false);
});
it("should return false if RTCPeerConnection throws", () => {
// @ts-ignore - writing to window as we are simulating browser edge-cases
global.window = {};
Object.defineProperty(global.window, "RTCPeerConnection", {
globalThis.window = {};
Object.defineProperty(globalThis.window, "RTCPeerConnection", {
get: () => {
throw Error("Secure mode, naaah!");
},
@ -810,11 +810,11 @@ describe("Call", function () {
"should return false if RTCPeerConnection & RTCSessionDescription " +
"& RTCIceCandidate & mediaDevices are unavailable",
() => {
global.window.RTCPeerConnection = undefined!;
global.window.RTCSessionDescription = undefined!;
global.window.RTCIceCandidate = undefined!;
globalThis.window.RTCPeerConnection = undefined!;
globalThis.window.RTCSessionDescription = undefined!;
globalThis.window.RTCIceCandidate = undefined!;
// @ts-ignore - writing to a read-only property as we are simulating faulty browsers
global.navigator.mediaDevices = undefined;
globalThis.navigator.mediaDevices = undefined;
expect(supportsMatrixCall()).toBe(false);
},
);
@ -1305,7 +1305,7 @@ describe("Call", function () {
});
it("removes RTX codec from screen sharing transcievers", async () => {
mocked(global.RTCRtpSender.getCapabilities).mockReturnValue({
mocked(globalThis.RTCRtpSender.getCapabilities).mockReturnValue({
codecs: [
{ mimeType: "video/rtx", clockRate: 90000 },
{ mimeType: "video/somethingelse", clockRate: 90000 },
@ -1816,8 +1816,8 @@ describe("Call", function () {
it("should emit IceFailed error on the successor call if RTCPeerConnection throws", async () => {
// @ts-ignore - writing to window as we are simulating browser edge-cases
global.window = {};
Object.defineProperty(global.window, "RTCPeerConnection", {
globalThis.window = {};
Object.defineProperty(globalThis.window, "RTCPeerConnection", {
get: () => {
throw Error("Secure mode, naaah!");
},

View File

@ -31,7 +31,7 @@ describe("Media Handler", function () {
beforeEach(() => {
mockMediaDevices = new MockMediaDevices();
global.navigator = {
globalThis.navigator = {
mediaDevices: mockMediaDevices.typed(),
} as unknown as Navigator;

View File

@ -126,7 +126,7 @@ describe("GroupCallStats", () => {
it("doing nothing if process already running", async () => {
// @ts-ignore
jest.spyOn(global, "setInterval").mockReturnValue(22);
jest.spyOn(globalThis, "setInterval").mockReturnValue(22);
stats.start();
expect(setInterval).toHaveBeenCalledTimes(1);
stats.start();
@ -146,8 +146,8 @@ describe("GroupCallStats", () => {
});
it("finish stats process if was started", async () => {
// @ts-ignore
jest.spyOn(global, "setInterval").mockReturnValue(22);
jest.spyOn(global, "clearInterval");
jest.spyOn(globalThis, "setInterval").mockReturnValue(22);
jest.spyOn(globalThis, "clearInterval");
stats.start();
expect(setInterval).toHaveBeenCalledTimes(1);
stats.stop();
@ -155,7 +155,7 @@ describe("GroupCallStats", () => {
});
it("do nothing if stats process was not started", async () => {
jest.spyOn(global, "clearInterval");
jest.spyOn(globalThis, "clearInterval");
stats.stop();
expect(clearInterval).not.toHaveBeenCalled();
});

View File

@ -14,13 +14,13 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// this is needed to tell TS about global.Olm
// this is needed to tell TS about globalThis.Olm
import "@matrix-org/olm";
export {};
declare global {
// use `number` as the return type in all cases for global.set{Interval,Timeout},
// use `number` as the return type in all cases for globalThis.set{Interval,Timeout},
// so we don't accidentally use the methods on NodeJS.Timeout - they only exist in a subset of environments.
// The overload for clear{Interval,Timeout} is resolved as expected.
// We use `ReturnType<typeof setTimeout>` in the code to be agnostic of if this definition gets loaded.

View File

@ -414,16 +414,16 @@ export class AutoDiscovery {
}
}
private static fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof global.fetch> {
private static fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {
if (this.fetchFn) {
return this.fetchFn(resource, options);
}
return global.fetch(resource, options);
return globalThis.fetch(resource, options);
}
private static fetchFn?: typeof global.fetch;
private static fetchFn?: typeof globalThis.fetch;
public static setFetchFn(fetchFn: typeof global.fetch): void {
public static setFetchFn(fetchFn: typeof globalThis.fetch): void {
AutoDiscovery.fetchFn = fetchFn;
}

View File

@ -307,7 +307,7 @@ export interface ICreateClientOpts {
* The function to invoke for HTTP requests.
* Most supported environments have a global `fetch` registered to which this will fall back.
*/
fetchFn?: typeof global.fetch;
fetchFn?: typeof globalThis.fetch;
userId?: string;
@ -1581,11 +1581,11 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
this.callEventHandler = undefined;
this.groupCallEventHandler = undefined;
global.clearInterval(this.checkTurnServersIntervalID);
globalThis.clearInterval(this.checkTurnServersIntervalID);
this.checkTurnServersIntervalID = undefined;
if (this.clientWellKnownIntervalID !== undefined) {
global.clearInterval(this.clientWellKnownIntervalID);
globalThis.clearInterval(this.clientWellKnownIntervalID);
}
this.toDeviceMessageQueue.stop();
@ -1625,7 +1625,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
return;
}
const account = new global.Olm.Account();
const account = new globalThis.Olm.Account();
try {
const deviceData = getDeviceResult.device_data;
if (deviceData.algorithm !== DEHYDRATION_ALGORITHM) {
@ -1781,7 +1781,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
const deleteRustSdkStore = async (): Promise<void> => {
let indexedDB: IDBFactory;
try {
indexedDB = global.indexedDB;
indexedDB = globalThis.indexedDB;
if (!indexedDB) return; // No indexedDB support
} catch {
// No indexedDB support
@ -1799,7 +1799,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
resolve(0);
};
req.onerror = (e): void => {
// In private browsing, Firefox has a global.indexedDB, but attempts to delete an indexeddb
// In private browsing, Firefox has a globalThis.indexedDB, but attempts to delete an indexeddb
// (even a non-existent one) fail with "DOMException: A mutation operation was attempted on a
// database that did not allow mutations."
//
@ -7548,7 +7548,9 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
if ((<HTTPError>err).httpStatus === 403) {
// We got a 403, so there's no point in looping forever.
this.logger.info("TURN access unavailable for this account: stopping credentials checks");
if (this.checkTurnServersIntervalID !== null) global.clearInterval(this.checkTurnServersIntervalID);
if (this.checkTurnServersIntervalID !== null) {
globalThis.clearInterval(this.checkTurnServersIntervalID);
}
this.checkTurnServersIntervalID = undefined;
this.emit(ClientEvent.TurnServersError, <HTTPError>err, true); // fatal
} else {

View File

@ -125,7 +125,7 @@ export class CrossSigningInfo {
function validateKey(key: Uint8Array | null): [string, PkSigning] | undefined {
if (!key) return;
const signing = new global.Olm.PkSigning();
const signing = new globalThis.Olm.PkSigning();
const gotPubkey = signing.init_with_seed(key);
if (gotPubkey === expectedPubkey) {
return [gotPubkey, signing];
@ -307,7 +307,7 @@ export class CrossSigningInfo {
try {
if (level & CrossSigningLevel.MASTER) {
masterSigning = new global.Olm.PkSigning();
masterSigning = new globalThis.Olm.PkSigning();
privateKeys.master = masterSigning.generate_seed();
masterPub = masterSigning.init_with_seed(privateKeys.master);
keys.master = {
@ -322,7 +322,7 @@ export class CrossSigningInfo {
}
if (level & CrossSigningLevel.SELF_SIGNING) {
const sskSigning = new global.Olm.PkSigning();
const sskSigning = new globalThis.Olm.PkSigning();
try {
privateKeys.self_signing = sskSigning.generate_seed();
const sskPub = sskSigning.init_with_seed(privateKeys.self_signing);
@ -340,7 +340,7 @@ export class CrossSigningInfo {
}
if (level & CrossSigningLevel.USER_SIGNING) {
const uskSigning = new global.Olm.PkSigning();
const uskSigning = new globalThis.Olm.PkSigning();
try {
privateKeys.user_signing = uskSigning.generate_seed();
const uskPub = uskSigning.init_with_seed(privateKeys.user_signing);

View File

@ -167,7 +167,7 @@ export class OlmDevice {
* @returns The version of Olm.
*/
public static getOlmVersion(): [number, number, number] {
return global.Olm.get_library_version();
return globalThis.Olm.get_library_version();
}
/**
@ -186,7 +186,7 @@ export class OlmDevice {
*/
public async init({ pickleKey, fromExportedDevice }: IInitOpts = {}): Promise<void> {
let e2eKeys;
const account = new global.Olm.Account();
const account = new globalThis.Olm.Account();
try {
if (fromExportedDevice) {
@ -268,7 +268,7 @@ export class OlmDevice {
*/
private getAccount(txn: unknown, func: (account: Account) => void): void {
this.cryptoStore.getAccount(txn, (pickledAccount: string | null) => {
const account = new global.Olm.Account();
const account = new globalThis.Olm.Account();
try {
account.unpickle(this.pickleKey, pickledAccount!);
func(account);
@ -352,7 +352,7 @@ export class OlmDevice {
sessionInfo: ISessionInfo,
func: (unpickledSessionInfo: IUnpickledSessionInfo) => void,
): void {
const session = new global.Olm.Session();
const session = new globalThis.Olm.Session();
try {
session.unpickle(this.pickleKey, sessionInfo.session!);
const unpickledSessInfo: IUnpickledSessionInfo = Object.assign({}, sessionInfo, { session });
@ -390,7 +390,7 @@ export class OlmDevice {
* @internal
*/
private getUtility<T>(func: (utility: Utility) => T): T {
const utility = new global.Olm.Utility();
const utility = new globalThis.Olm.Utility();
try {
return func(utility);
} finally {
@ -517,7 +517,7 @@ export class OlmDevice {
[IndexedDBCryptoStore.STORE_ACCOUNT, IndexedDBCryptoStore.STORE_SESSIONS],
(txn) => {
this.getAccount(txn, (account: Account) => {
const session = new global.Olm.Session();
const session = new globalThis.Olm.Session();
try {
session.create_outbound(account, theirIdentityKey, theirOneTimeKey);
newSessionId = session.session_id();
@ -567,7 +567,7 @@ export class OlmDevice {
[IndexedDBCryptoStore.STORE_ACCOUNT, IndexedDBCryptoStore.STORE_SESSIONS],
(txn) => {
this.getAccount(txn, (account: Account) => {
const session = new global.Olm.Session();
const session = new globalThis.Olm.Session();
try {
session.create_inbound_from(account, theirDeviceIdentityKey, ciphertext);
account.remove_one_time_keys(session);
@ -889,7 +889,7 @@ export class OlmDevice {
throw new Error("Unknown outbound group session " + sessionId);
}
const session = new global.Olm.OutboundGroupSession();
const session = new globalThis.Olm.OutboundGroupSession();
try {
session.unpickle(this.pickleKey, pickled);
return func(session);
@ -904,7 +904,7 @@ export class OlmDevice {
* @returns sessionId for the outbound session.
*/
public createOutboundGroupSession(): string {
const session = new global.Olm.OutboundGroupSession();
const session = new globalThis.Olm.OutboundGroupSession();
try {
session.create();
this.saveOutboundGroupSession(session);
@ -966,7 +966,7 @@ export class OlmDevice {
sessionData: InboundGroupSessionData,
func: (session: InboundGroupSession) => T,
): T {
const session = new global.Olm.InboundGroupSession();
const session = new globalThis.Olm.InboundGroupSession();
try {
session.unpickle(this.pickleKey, sessionData.session);
return func(session);
@ -1068,7 +1068,7 @@ export class OlmDevice {
existingSessionData: InboundGroupSessionData | null,
) => {
// new session.
const session = new global.Olm.InboundGroupSession();
const session = new globalThis.Olm.InboundGroupSession();
try {
if (exportFormat) {
session.import_session(sessionKey);

View File

@ -666,13 +666,13 @@ export class Curve25519 implements BackupAlgorithm {
if (!authData || !("public_key" in authData)) {
throw new Error("auth_data missing required information");
}
const publicKey = new global.Olm.PkEncryption();
const publicKey = new globalThis.Olm.PkEncryption();
publicKey.set_recipient_key(authData.public_key);
return new Curve25519(authData as ICurve25519AuthData, publicKey, getKey);
}
public static async prepare(key?: string | Uint8Array | null): Promise<[Uint8Array, AuthData]> {
const decryption = new global.Olm.PkDecryption();
const decryption = new globalThis.Olm.PkDecryption();
try {
const authData: Partial<ICurve25519AuthData> = {};
if (!key) {
@ -685,7 +685,7 @@ export class Curve25519 implements BackupAlgorithm {
authData.private_key_iterations = derivation.iterations;
authData.public_key = decryption.init_with_private_key(derivation.key);
}
const publicKey = new global.Olm.PkEncryption();
const publicKey = new globalThis.Olm.PkEncryption();
publicKey.set_recipient_key(authData.public_key);
return [decryption.get_private_key(), authData as AuthData];
@ -716,7 +716,7 @@ export class Curve25519 implements BackupAlgorithm {
sessions: Record<string, IKeyBackupSession<Curve25519SessionData>>,
): Promise<IMegolmSessionData[]> {
const privKey = await this.getKey();
const decryption = new global.Olm.PkDecryption();
const decryption = new globalThis.Olm.PkDecryption();
try {
const backupPubKey = decryption.init_with_private_key(privKey);
@ -748,7 +748,7 @@ export class Curve25519 implements BackupAlgorithm {
}
public async keyMatches(key: Uint8Array): Promise<boolean> {
const decryption = new global.Olm.PkDecryption();
const decryption = new globalThis.Olm.PkDecryption();
let pubKey: string;
try {
pubKey = decryption.init_with_private_key(key);

View File

@ -68,7 +68,7 @@ export class DehydrationManager {
this.deviceDisplayName = deviceDisplayName;
const now = Date.now();
const delay = Math.max(1, time + oneweek - now);
this.timeoutId = global.setTimeout(this.dehydrateDevice.bind(this), delay);
this.timeoutId = globalThis.setTimeout(this.dehydrateDevice.bind(this), delay);
}
},
"dehydration",
@ -97,7 +97,7 @@ export class DehydrationManager {
if (!key) {
// unsetting the key -- cancel any pending dehydration task
if (this.timeoutId) {
global.clearTimeout(this.timeoutId);
globalThis.clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
// clear storage
@ -135,7 +135,7 @@ export class DehydrationManager {
}
this.inProgress = true;
if (this.timeoutId) {
global.clearTimeout(this.timeoutId);
globalThis.clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
try {
@ -155,7 +155,7 @@ export class DehydrationManager {
logger.log("Creating account");
// create the account and all the necessary keys
const account = new global.Olm.Account();
const account = new globalThis.Olm.Account();
account.create();
const e2eKeys = JSON.parse(account.identity_keys());
@ -255,7 +255,7 @@ export class DehydrationManager {
logger.log("Done dehydrating");
// dehydrate again in a week
this.timeoutId = global.setTimeout(this.dehydrateDevice.bind(this), oneweek);
this.timeoutId = globalThis.setTimeout(this.dehydrateDevice.bind(this), oneweek);
return deviceId;
} finally {
@ -265,7 +265,7 @@ export class DehydrationManager {
public stop(): void {
if (this.timeoutId) {
global.clearTimeout(this.timeoutId);
globalThis.clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
}

View File

@ -537,7 +537,7 @@ export class Crypto extends TypedEventEmitter<CryptoEvent, CryptoEventHandlerMap
*/
public async init({ exportedOlmDevice, pickleKey }: IInitOpts = {}): Promise<void> {
logger.log("Crypto: initialising Olm...");
await global.Olm.init();
await globalThis.Olm.init();
logger.log(
exportedOlmDevice
? "Crypto: initialising Olm device from exported device..."
@ -668,7 +668,7 @@ export class Crypto extends TypedEventEmitter<CryptoEvent, CryptoEventHandlerMap
* and raw private key to avoid round tripping if needed.
*/
public async createRecoveryKeyFromPassphrase(password?: string): Promise<IRecoveryKey> {
const decryption = new global.Olm.PkDecryption();
const decryption = new globalThis.Olm.PkDecryption();
try {
if (password) {
const derivation = await keyFromPassphrase(password);
@ -1252,7 +1252,7 @@ export class Crypto extends TypedEventEmitter<CryptoEvent, CryptoEventHandlerMap
public checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {
let decryption: PkDecryption | null = null;
try {
decryption = new global.Olm.PkDecryption();
decryption = new globalThis.Olm.PkDecryption();
const gotPubkey = decryption.init_with_private_key(privateKey);
// make sure it agrees with the given pubkey
return gotPubkey === expectedPublicKey;
@ -1354,7 +1354,7 @@ export class Crypto extends TypedEventEmitter<CryptoEvent, CryptoEventHandlerMap
public checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {
let signing: PkSigning | null = null;
try {
signing = new global.Olm.PkSigning();
signing = new globalThis.Olm.PkSigning();
const gotPubkey = signing.init_with_seed(privateKey);
// make sure it agrees with the given pubkey
return gotPubkey === expectedPublicKey;

View File

@ -471,7 +471,7 @@ export async function verifySignature(
export function pkSign(obj: object & IObject, key: Uint8Array | PkSigning, userId: string, pubKey: string): string {
let createdKey = false;
if (key instanceof Uint8Array) {
const keyObj = new global.Olm.PkSigning();
const keyObj = new globalThis.Olm.PkSigning();
pubKey = keyObj.init_with_seed(key);
key = keyObj;
createdKey = true;
@ -506,7 +506,7 @@ export function pkVerify(obj: IObject, pubKey: string, userId: string): void {
throw new Error("No signature");
}
const signature = obj.signatures[userId][keyId];
const util = new global.Olm.Utility();
const util = new globalThis.Olm.Utility();
const sigs = obj.signatures;
delete obj.signatures;
const unsigned = obj.unsigned;

View File

@ -210,7 +210,7 @@ export class IndexedDBCryptoStore implements CryptoStore {
);
try {
return new LocalStorageCryptoStore(global.localStorage);
return new LocalStorageCryptoStore(globalThis.localStorage);
} catch (e) {
logger.warn(`unable to open localStorage: falling back to in-memory store: ${e}`);
return new MemoryCryptoStore();

View File

@ -242,8 +242,8 @@ export class SAS extends Base {
}
protected doVerification = async (): Promise<void> => {
await global.Olm.init();
olmutil = olmutil || new global.Olm.Utility();
await globalThis.Olm.init();
olmutil = olmutil || new globalThis.Olm.Utility();
// make sure user's keys are downloaded
await this.baseApis.downloadKeys([this.userId]);
@ -369,7 +369,7 @@ export class SAS extends Base {
const keyAgreement = content.key_agreement_protocol;
const macMethod = content.message_authentication_code;
const hashCommitment = content.commitment;
const olmSAS = new global.Olm.SAS();
const olmSAS = new globalThis.Olm.SAS();
try {
this.ourSASPubKey = olmSAS.get_pubkey();
await this.send(EventType.KeyVerificationKey, {
@ -411,7 +411,7 @@ export class SAS extends Base {
throw newUnknownMethodError();
}
const olmSAS = new global.Olm.SAS();
const olmSAS = new globalThis.Olm.SAS();
try {
const commitmentStr = olmSAS.get_pubkey() + anotherjson.stringify(content);
await this.send(EventType.KeyVerificationAccept, {

View File

@ -53,11 +53,11 @@ export class FetchHttpApi<O extends IHttpOpts> {
this.abortController = new AbortController();
}
public fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof global.fetch> {
public fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {
if (this.opts.fetchFn) {
return this.opts.fetchFn(resource, options);
}
return global.fetch(resource, options);
return globalThis.fetch(resource, options);
}
/**

View File

@ -60,8 +60,8 @@ export class MatrixHttpApi<O extends IHttpOpts> extends FetchHttpApi<O> {
} as Upload;
const deferred = defer<UploadResponse>();
if (global.XMLHttpRequest) {
const xhr = new global.XMLHttpRequest();
if (globalThis.XMLHttpRequest) {
const xhr = new globalThis.XMLHttpRequest();
const timeoutFn = function (): void {
xhr.abort();
@ -73,7 +73,7 @@ export class MatrixHttpApi<O extends IHttpOpts> extends FetchHttpApi<O> {
xhr.onreadystatechange = function (): void {
switch (xhr.readyState) {
case global.XMLHttpRequest.DONE:
case globalThis.XMLHttpRequest.DONE:
callbacks.clearTimeout(timeoutTimer);
try {
if (xhr.status === 0) {

View File

@ -36,7 +36,7 @@ export type AccessTokens = {
*/
export type TokenRefreshFunction = (refreshToken: string) => Promise<AccessTokens>;
export interface IHttpOpts {
fetchFn?: typeof global.fetch;
fetchFn?: typeof globalThis.fetch;
baseUrl: string;
idBaseUrl?: string;

View File

@ -16,10 +16,10 @@ limitations under the License.
import * as matrixcs from "./matrix.ts";
if (global.__js_sdk_entrypoint) {
if (globalThis.__js_sdk_entrypoint) {
throw new Error("Multiple matrix-js-sdk entrypoints detected!");
}
global.__js_sdk_entrypoint = true;
globalThis.__js_sdk_entrypoint = true;
export * from "./matrix.ts";
export default matrixcs;

View File

@ -130,7 +130,7 @@ function amendClientOpts(opts: ICreateClientOpts): ICreateClientOpts {
opts.store =
opts.store ??
new MemoryStore({
localStorage: global.localStorage,
localStorage: globalThis.localStorage,
});
opts.scheduler = opts.scheduler ?? new MatrixScheduler();
opts.cryptoStore = opts.cryptoStore ?? cryptoStoreFactory();

View File

@ -33,7 +33,7 @@ const TIMER_CHECK_PERIOD_MS = 1000;
// counter, for making up ids to return from setTimeout
let count = 0;
// the key for our callback with the real global.setTimeout
// the key for our callback with the real globalThis.setTimeout
let realCallbackKey: NodeJS.Timeout | number;
type Callback = {
@ -114,10 +114,10 @@ export function clearTimeout(key: number): void {
}
}
// use the real global.setTimeout to schedule a callback to runCallbacks.
// use the real globalThis.setTimeout to schedule a callback to runCallbacks.
function scheduleRealCallback(): void {
if (realCallbackKey) {
global.clearTimeout(realCallbackKey as NodeJS.Timeout);
globalThis.clearTimeout(realCallbackKey as NodeJS.Timeout);
}
const first = callbackList[0];
@ -131,7 +131,7 @@ function scheduleRealCallback(): void {
const delayMs = Math.min(first.runAt - timestamp, TIMER_CHECK_PERIOD_MS);
debuglog("scheduleRealCallback: now:", timestamp, "delay:", delayMs);
realCallbackKey = global.setTimeout(runCallbacks, delayMs);
realCallbackKey = globalThis.setTimeout(runCallbacks, delayMs);
}
function runCallbacks(): void {
@ -158,7 +158,7 @@ function runCallbacks(): void {
for (const cb of callbacksToRun) {
try {
cb.func.apply(global, cb.params);
cb.func.apply(globalThis, cb.params);
} catch (e) {
logger.error("Uncaught exception in callback function", e);
}

View File

@ -29,7 +29,7 @@ export class MSC4108RendezvousSession {
public url?: string;
private readonly client?: MatrixClient;
private readonly fallbackRzServer?: string;
private readonly fetchFn?: typeof global.fetch;
private readonly fetchFn?: typeof globalThis.fetch;
private readonly onFailure?: RendezvousFailureListener;
private etag?: string;
private expiresAt?: Date;
@ -42,7 +42,7 @@ export class MSC4108RendezvousSession {
url,
fetchFn,
}: {
fetchFn?: typeof global.fetch;
fetchFn?: typeof globalThis.fetch;
onFailure?: RendezvousFailureListener;
url: string;
});
@ -52,7 +52,7 @@ export class MSC4108RendezvousSession {
fallbackRzServer,
fetchFn,
}: {
fetchFn?: typeof global.fetch;
fetchFn?: typeof globalThis.fetch;
onFailure?: RendezvousFailureListener;
client?: MatrixClient;
fallbackRzServer?: string;
@ -64,7 +64,7 @@ export class MSC4108RendezvousSession {
client,
fallbackRzServer,
}: {
fetchFn?: typeof global.fetch;
fetchFn?: typeof globalThis.fetch;
onFailure?: RendezvousFailureListener;
url?: string;
client?: MatrixClient;
@ -91,11 +91,11 @@ export class MSC4108RendezvousSession {
return this._cancelled;
}
private fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof global.fetch> {
private fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {
if (this.fetchFn) {
return this.fetchFn(resource, options);
}
return global.fetch(resource, options);
return globalThis.fetch(resource, options);
}
private async getPostEndpoint(): Promise<string | undefined> {

View File

@ -694,7 +694,7 @@ export class SyncApi {
this.running = true;
this.abortController = new AbortController();
global.window?.addEventListener?.("online", this.onOnline, false);
globalThis.window?.addEventListener?.("online", this.onOnline, false);
if (this.client.isGuest()) {
// no push rules for guests, no access to POST filter for guests.
@ -779,10 +779,10 @@ export class SyncApi {
public stop(): void {
debuglog("SyncApi.stop");
// It is necessary to check for the existance of
// global.window AND global.window.removeEventListener.
// Some platforms (e.g. React Native) register global.window,
// but do not have global.window.removeEventListener.
global.window?.removeEventListener?.("online", this.onOnline, false);
// globalThis.window AND globalThis.window.removeEventListener.
// Some platforms (e.g. React Native) register globalThis.window,
// but do not have globalThis.window.removeEventListener.
globalThis.window?.removeEventListener?.("online", this.onOnline, false);
this.running = false;
this.abortController?.abort();
if (this.keepAliveTimer) {