You've already forked matrix-js-sdk
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:
@ -63,6 +63,10 @@ module.exports = {
|
|||||||
name: "setImmediate",
|
name: "setImmediate",
|
||||||
message: "Use setTimeout instead.",
|
message: "Use setTimeout instead.",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "global",
|
||||||
|
message: "Use globalThis instead.",
|
||||||
|
},
|
||||||
],
|
],
|
||||||
|
|
||||||
"import/no-restricted-paths": [
|
"import/no-restricted-paths": [
|
||||||
|
@ -66,7 +66,7 @@ export class TestClient implements IE2EKeyReceiver, ISyncResponder {
|
|||||||
userId: userId,
|
userId: userId,
|
||||||
accessToken: accessToken,
|
accessToken: accessToken,
|
||||||
deviceId: deviceId,
|
deviceId: deviceId,
|
||||||
fetchFn: this.httpBackend.fetchFn as typeof global.fetch,
|
fetchFn: this.httpBackend.fetchFn as typeof globalThis.fetch,
|
||||||
...options,
|
...options,
|
||||||
};
|
};
|
||||||
if (!fullOptions.cryptoStore) {
|
if (!fullOptions.cryptoStore) {
|
||||||
|
@ -136,7 +136,7 @@ async function expectSendRoomKey(
|
|||||||
recipientOlmAccount: Olm.Account,
|
recipientOlmAccount: Olm.Account,
|
||||||
recipientOlmSession: Olm.Session | null = null,
|
recipientOlmSession: Olm.Session | null = null,
|
||||||
): Promise<Olm.InboundGroupSession> {
|
): Promise<Olm.InboundGroupSession> {
|
||||||
const Olm = global.Olm;
|
const Olm = globalThis.Olm;
|
||||||
const testRecipientKey = JSON.parse(recipientOlmAccount.identity_keys())["curve25519"];
|
const testRecipientKey = JSON.parse(recipientOlmAccount.identity_keys())["curve25519"];
|
||||||
|
|
||||||
function onSendRoomKey(content: any): Olm.InboundGroupSession {
|
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) => {
|
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.
|
// 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");
|
logger.warn("not running megolm tests: Olm not present");
|
||||||
return;
|
return;
|
||||||
@ -230,7 +230,7 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string,
|
|||||||
const oldBackendOnly = backend === "rust-sdk" ? test.skip : test;
|
const oldBackendOnly = backend === "rust-sdk" ? test.skip : test;
|
||||||
const newBackendOnly = 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 testOlmAccount = {} as unknown as Olm.Account;
|
||||||
let testSenderKey = "";
|
let testSenderKey = "";
|
||||||
@ -1897,13 +1897,13 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string,
|
|||||||
const aliceOtks = await keyReceiver.awaitOneTimeKeyUpload();
|
const aliceOtks = await keyReceiver.awaitOneTimeKeyUpload();
|
||||||
const aliceOtkId = Object.keys(aliceOtks)[0];
|
const aliceOtkId = Object.keys(aliceOtks)[0];
|
||||||
const aliceOtk = aliceOtks[aliceOtkId];
|
const aliceOtk = aliceOtks[aliceOtkId];
|
||||||
const p2pSession = new global.Olm.Session();
|
const p2pSession = new globalThis.Olm.Session();
|
||||||
await beccaTestClient.client.crypto!.cryptoStore.doTxn(
|
await beccaTestClient.client.crypto!.cryptoStore.doTxn(
|
||||||
"readonly",
|
"readonly",
|
||||||
[IndexedDBCryptoStore.STORE_ACCOUNT],
|
[IndexedDBCryptoStore.STORE_ACCOUNT],
|
||||||
(txn) => {
|
(txn) => {
|
||||||
beccaTestClient.client.crypto!.cryptoStore.getAccount(txn, (pickledAccount: string | null) => {
|
beccaTestClient.client.crypto!.cryptoStore.getAccount(txn, (pickledAccount: string | null) => {
|
||||||
const account = new global.Olm.Account();
|
const account = new globalThis.Olm.Account();
|
||||||
try {
|
try {
|
||||||
account.unpickle(beccaTestClient.client.crypto!.olmDevice.pickleKey, pickledAccount!);
|
account.unpickle(beccaTestClient.client.crypto!.olmDevice.pickleKey, pickledAccount!);
|
||||||
p2pSession.create_outbound(account, keyReceiver.getDeviceKey(), aliceOtk.key);
|
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 aliceOtks = await keyReceiver.awaitOneTimeKeyUpload();
|
||||||
const aliceOtkId = Object.keys(aliceOtks)[0];
|
const aliceOtkId = Object.keys(aliceOtks)[0];
|
||||||
const aliceOtk = aliceOtks[aliceOtkId];
|
const aliceOtk = aliceOtks[aliceOtkId];
|
||||||
const p2pSession = new global.Olm.Session();
|
const p2pSession = new globalThis.Olm.Session();
|
||||||
await beccaTestClient.client.crypto!.cryptoStore.doTxn(
|
await beccaTestClient.client.crypto!.cryptoStore.doTxn(
|
||||||
"readonly",
|
"readonly",
|
||||||
[IndexedDBCryptoStore.STORE_ACCOUNT],
|
[IndexedDBCryptoStore.STORE_ACCOUNT],
|
||||||
(txn) => {
|
(txn) => {
|
||||||
beccaTestClient.client.crypto!.cryptoStore.getAccount(txn, (pickledAccount: string | null) => {
|
beccaTestClient.client.crypto!.cryptoStore.getAccount(txn, (pickledAccount: string | null) => {
|
||||||
const account = new global.Olm.Account();
|
const account = new globalThis.Olm.Account();
|
||||||
try {
|
try {
|
||||||
account.unpickle(beccaTestClient.client.crypto!.olmDevice.pickleKey, pickledAccount!);
|
account.unpickle(beccaTestClient.client.crypto!.olmDevice.pickleKey, pickledAccount!);
|
||||||
p2pSession.create_outbound(account, keyReceiver.getDeviceKey(), aliceOtk.key);
|
p2pSession.create_outbound(account, keyReceiver.getDeviceKey(), aliceOtk.key);
|
||||||
|
@ -85,15 +85,15 @@ export function bootstrapCrossSigningTestOlmAccount(
|
|||||||
deviceId: string,
|
deviceId: string,
|
||||||
keyBackupInfo: KeyBackupInfo[] = [],
|
keyBackupInfo: KeyBackupInfo[] = [],
|
||||||
): Partial<IDownloadKeyResult> {
|
): Partial<IDownloadKeyResult> {
|
||||||
const olmAliceMSK = new global.Olm.PkSigning();
|
const olmAliceMSK = new globalThis.Olm.PkSigning();
|
||||||
const masterPrivkey = olmAliceMSK.generate_seed();
|
const masterPrivkey = olmAliceMSK.generate_seed();
|
||||||
const masterPubkey = olmAliceMSK.init_with_seed(masterPrivkey);
|
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 userPrivkey = olmAliceUSK.generate_seed();
|
||||||
const userPubkey = olmAliceUSK.init_with_seed(userPrivkey);
|
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 sskPrivkey = olmAliceSSK.generate_seed();
|
||||||
const sskPubkey = olmAliceSSK.init_with_seed(sskPrivkey);
|
const sskPubkey = olmAliceSSK.init_with_seed(sskPrivkey);
|
||||||
|
|
||||||
@ -181,7 +181,7 @@ export async function createOlmSession(
|
|||||||
const otkId = Object.keys(keys)[0];
|
const otkId = Object.keys(keys)[0];
|
||||||
const otk = keys[otkId];
|
const otk = keys[otkId];
|
||||||
|
|
||||||
const session = new global.Olm.Session();
|
const session = new globalThis.Olm.Session();
|
||||||
session.create_outbound(olmAccount, recipientTestClient.getDeviceKey(), otk.key);
|
session.create_outbound(olmAccount, recipientTestClient.getDeviceKey(), otk.key);
|
||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
|
@ -90,7 +90,7 @@ jest.useFakeTimers({ doNotFake: ["queueMicrotask"] });
|
|||||||
|
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
// we use the libolm primitives in the test, so init the Olm library
|
// 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.
|
// 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'
|
// 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
|
// 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()));
|
returnToDeviceMessageFromSync(buildSasKeyMessage(transactionId, olmSAS.get_pubkey()));
|
||||||
|
|
||||||
// alice responds with a 'key' ...
|
// 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'
|
// 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
|
// 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);
|
const commitmentStr = olmSAS.get_pubkey() + anotherjson.stringify(toDeviceMessage);
|
||||||
|
|
||||||
sendToDevicePromise = expectSendToDeviceMessage("m.key.verification.key");
|
sendToDevicePromise = expectSendToDeviceMessage("m.key.verification.key");
|
||||||
|
@ -67,7 +67,7 @@ function getSyncResponse(roomMembers: string[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("DeviceList management:", function () {
|
describe("DeviceList management:", function () {
|
||||||
if (!global.Olm) {
|
if (!globalThis.Olm) {
|
||||||
logger.warn("not running deviceList tests: Olm not present");
|
logger.warn("not running deviceList tests: Olm not present");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -80,7 +80,7 @@ describe("MatrixClient opts", function () {
|
|||||||
let client: MatrixClient;
|
let client: MatrixClient;
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
client = new MatrixClient({
|
client = new MatrixClient({
|
||||||
fetchFn: httpBackend.fetchFn as typeof global.fetch,
|
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
|
||||||
store: undefined,
|
store: undefined,
|
||||||
baseUrl: baseUrl,
|
baseUrl: baseUrl,
|
||||||
userId: userId,
|
userId: userId,
|
||||||
@ -135,7 +135,7 @@ describe("MatrixClient opts", function () {
|
|||||||
let client: MatrixClient;
|
let client: MatrixClient;
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
client = new MatrixClient({
|
client = new MatrixClient({
|
||||||
fetchFn: httpBackend.fetchFn as typeof global.fetch,
|
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
|
||||||
store: new MemoryStore() as IStore,
|
store: new MemoryStore() as IStore,
|
||||||
baseUrl: baseUrl,
|
baseUrl: baseUrl,
|
||||||
userId: userId,
|
userId: userId,
|
||||||
|
@ -2406,7 +2406,7 @@ describe("MatrixClient syncing (IndexedDB version)", () => {
|
|||||||
|
|
||||||
it("should emit ClientEvent.Room when invited while using indexeddb crypto store", async () => {
|
it("should emit ClientEvent.Room when invited while using indexeddb crypto store", async () => {
|
||||||
const idbTestClient = new TestClient(selfUserId, "DEVICE", selfAccessToken, undefined, {
|
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 idbHttpBackend = idbTestClient.httpBackend;
|
||||||
const idbClient = idbTestClient.client;
|
const idbClient = idbTestClient.client;
|
||||||
@ -2486,7 +2486,7 @@ describe("MatrixClient syncing (IndexedDB version)", () => {
|
|||||||
|
|
||||||
let idbTestClient = new TestClient(selfUserId, "DEVICE", selfAccessToken, undefined, {
|
let idbTestClient = new TestClient(selfUserId, "DEVICE", selfAccessToken, undefined, {
|
||||||
store: new IndexedDBStore({
|
store: new IndexedDBStore({
|
||||||
indexedDB: global.indexedDB,
|
indexedDB: globalThis.indexedDB,
|
||||||
dbName: "test",
|
dbName: "test",
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@ -2558,7 +2558,7 @@ describe("MatrixClient syncing (IndexedDB version)", () => {
|
|||||||
|
|
||||||
idbTestClient = new TestClient(selfUserId, "DEVICE", selfAccessToken, undefined, {
|
idbTestClient = new TestClient(selfUserId, "DEVICE", selfAccessToken, undefined, {
|
||||||
store: new IndexedDBStore({
|
store: new IndexedDBStore({
|
||||||
indexedDB: global.indexedDB,
|
indexedDB: globalThis.indexedDB,
|
||||||
dbName: "test",
|
dbName: "test",
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
@ -266,7 +266,7 @@ describe("MSC4108SignInWithQR", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should abort if device doesn't come up by timeout", async () => {
|
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();
|
fn();
|
||||||
// TODO: mock timers properly
|
// TODO: mock timers properly
|
||||||
return -1 as any;
|
return -1 as any;
|
||||||
@ -319,7 +319,7 @@ describe("MSC4108SignInWithQR", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should not send secrets if user cancels", async () => {
|
it("should not send secrets if user cancels", async () => {
|
||||||
jest.spyOn(global, "setTimeout").mockImplementation((fn) => {
|
jest.spyOn(globalThis, "setTimeout").mockImplementation((fn) => {
|
||||||
fn();
|
fn();
|
||||||
// TODO: mock timers properly
|
// TODO: mock timers properly
|
||||||
return -1 as any;
|
return -1 as any;
|
||||||
|
@ -560,7 +560,7 @@ export const CRYPTO_BACKENDS: Record<string, InitCrypto> = {};
|
|||||||
export type InitCrypto = (_: MatrixClient) => Promise<void>;
|
export type InitCrypto = (_: MatrixClient) => Promise<void>;
|
||||||
|
|
||||||
CRYPTO_BACKENDS["rust-sdk"] = (client: MatrixClient) => client.initRustCrypto();
|
CRYPTO_BACKENDS["rust-sdk"] = (client: MatrixClient) => client.initRustCrypto();
|
||||||
if (global.Olm) {
|
if (globalThis.Olm) {
|
||||||
CRYPTO_BACKENDS["libolm"] = (client: MatrixClient) => client.initCrypto();
|
CRYPTO_BACKENDS["libolm"] = (client: MatrixClient) => client.initCrypto();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -582,11 +582,11 @@ export class MockCallFeed {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function installWebRTCMocks() {
|
export function installWebRTCMocks() {
|
||||||
global.navigator = {
|
globalThis.navigator = {
|
||||||
mediaDevices: new MockMediaDevices().typed(),
|
mediaDevices: new MockMediaDevices().typed(),
|
||||||
} as unknown as Navigator;
|
} as unknown as Navigator;
|
||||||
|
|
||||||
global.window = {
|
globalThis.window = {
|
||||||
// @ts-ignore Mock
|
// @ts-ignore Mock
|
||||||
RTCPeerConnection: MockRTCPeerConnection,
|
RTCPeerConnection: MockRTCPeerConnection,
|
||||||
// @ts-ignore Mock
|
// @ts-ignore Mock
|
||||||
@ -596,13 +596,13 @@ export function installWebRTCMocks() {
|
|||||||
getUserMedia: () => new MockMediaStream("local_stream"),
|
getUserMedia: () => new MockMediaStream("local_stream"),
|
||||||
};
|
};
|
||||||
// @ts-ignore Mock
|
// @ts-ignore Mock
|
||||||
global.document = {};
|
globalThis.document = {};
|
||||||
|
|
||||||
// @ts-ignore Mock
|
// @ts-ignore Mock
|
||||||
global.AudioContext = MockAudioContext;
|
globalThis.AudioContext = MockAudioContext;
|
||||||
|
|
||||||
// @ts-ignore Mock
|
// @ts-ignore Mock
|
||||||
global.RTCRtpReceiver = {
|
globalThis.RTCRtpReceiver = {
|
||||||
getCapabilities: jest.fn<RTCRtpCapabilities, [string]>().mockReturnValue({
|
getCapabilities: jest.fn<RTCRtpCapabilities, [string]>().mockReturnValue({
|
||||||
codecs: [],
|
codecs: [],
|
||||||
headerExtensions: [],
|
headerExtensions: [],
|
||||||
@ -610,7 +610,7 @@ export function installWebRTCMocks() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// @ts-ignore Mock
|
// @ts-ignore Mock
|
||||||
global.RTCRtpSender = {
|
globalThis.RTCRtpSender = {
|
||||||
getCapabilities: jest.fn<RTCRtpCapabilities, [string]>().mockReturnValue({
|
getCapabilities: jest.fn<RTCRtpCapabilities, [string]>().mockReturnValue({
|
||||||
codecs: [],
|
codecs: [],
|
||||||
headerExtensions: [],
|
headerExtensions: [],
|
||||||
|
@ -22,12 +22,12 @@ import { AutoDiscovery } from "../../src/autodiscovery";
|
|||||||
|
|
||||||
// keep to reset the fetch function after using MockHttpBackend
|
// keep to reset the fetch function after using MockHttpBackend
|
||||||
// @ts-ignore private property
|
// @ts-ignore private property
|
||||||
const realAutoDiscoveryFetch: typeof global.fetch = AutoDiscovery.fetchFn;
|
const realAutoDiscoveryFetch: typeof globalThis.fetch = AutoDiscovery.fetchFn;
|
||||||
|
|
||||||
describe("AutoDiscovery", function () {
|
describe("AutoDiscovery", function () {
|
||||||
const getHttpBackend = (): MockHttpBackend => {
|
const getHttpBackend = (): MockHttpBackend => {
|
||||||
const httpBackend = new MockHttpBackend();
|
const httpBackend = new MockHttpBackend();
|
||||||
AutoDiscovery.setFetchFn(httpBackend.fetchFn as typeof global.fetch);
|
AutoDiscovery.setFetchFn(httpBackend.fetchFn as typeof globalThis.fetch);
|
||||||
return httpBackend;
|
return httpBackend;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -29,8 +29,8 @@ describe.each(["browser", "node"])("Base64 encoding (%s)", (env) => {
|
|||||||
// eslint-disable-next-line no-global-assign
|
// eslint-disable-next-line no-global-assign
|
||||||
Buffer = undefined;
|
Buffer = undefined;
|
||||||
|
|
||||||
global.atob = NodeBuffer.atob;
|
globalThis.atob = NodeBuffer.atob;
|
||||||
global.btoa = NodeBuffer.btoa;
|
globalThis.btoa = NodeBuffer.btoa;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -38,9 +38,9 @@ describe.each(["browser", "node"])("Base64 encoding (%s)", (env) => {
|
|||||||
// eslint-disable-next-line no-global-assign
|
// eslint-disable-next-line no-global-assign
|
||||||
Buffer = origBuffer;
|
Buffer = origBuffer;
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
global.atob = undefined;
|
globalThis.atob = undefined;
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
global.btoa = undefined;
|
globalThis.btoa = undefined;
|
||||||
});
|
});
|
||||||
|
|
||||||
it("Should decode properly encoded data", () => {
|
it("Should decode properly encoded data", () => {
|
||||||
|
@ -29,10 +29,10 @@ describe("Beacon content helpers", () => {
|
|||||||
describe("makeBeaconInfoContent()", () => {
|
describe("makeBeaconInfoContent()", () => {
|
||||||
const mockDateNow = 123456789;
|
const mockDateNow = 123456789;
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
jest.spyOn(global.Date, "now").mockReturnValue(mockDateNow);
|
jest.spyOn(globalThis.Date, "now").mockReturnValue(mockDateNow);
|
||||||
});
|
});
|
||||||
afterAll(() => {
|
afterAll(() => {
|
||||||
jest.spyOn(global.Date, "now").mockRestore();
|
jest.spyOn(globalThis.Date, "now").mockRestore();
|
||||||
});
|
});
|
||||||
it("create fully defined event content", () => {
|
it("create fully defined event content", () => {
|
||||||
expect(makeBeaconInfoContent(1234, true, "nice beacon_info", LocationAssetType.Pin)).toEqual({
|
expect(makeBeaconInfoContent(1234, true, "nice beacon_info", LocationAssetType.Pin)).toEqual({
|
||||||
|
@ -28,7 +28,7 @@ import * as testData from "../test-utils/test-data";
|
|||||||
import { KnownMembership } from "../../src/@types/membership";
|
import { KnownMembership } from "../../src/@types/membership";
|
||||||
import type { DeviceInfoMap } from "../../src/crypto/DeviceList";
|
import type { DeviceInfoMap } from "../../src/crypto/DeviceList";
|
||||||
|
|
||||||
const Olm = global.Olm;
|
const Olm = globalThis.Olm;
|
||||||
|
|
||||||
function awaitEvent(emitter: EventEmitter, event: string): Promise<void> {
|
function awaitEvent(emitter: EventEmitter, event: string): Promise<void> {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
|
@ -44,13 +44,13 @@ badKey[0] ^= 1;
|
|||||||
const masterKeyPub = "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk";
|
const masterKeyPub = "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk";
|
||||||
|
|
||||||
describe("CrossSigningInfo.getCrossSigningKey", function () {
|
describe("CrossSigningInfo.getCrossSigningKey", function () {
|
||||||
if (!global.Olm) {
|
if (!globalThis.Olm) {
|
||||||
logger.warn("Not running megolm backup unit tests: libolm not present");
|
logger.warn("Not running megolm backup unit tests: libolm not present");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
beforeAll(function () {
|
beforeAll(function () {
|
||||||
return global.Olm.init();
|
return globalThis.Olm.init();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should throw if no callback is provided", async () => {
|
it("should throw if no callback is provided", async () => {
|
||||||
@ -80,7 +80,7 @@ describe("CrossSigningInfo.getCrossSigningKey", function () {
|
|||||||
expect(pubKey).toEqual(masterKeyPub);
|
expect(pubKey).toEqual(masterKeyPub);
|
||||||
// check that the pkSigning object corresponds to the pubKey
|
// check that the pkSigning object corresponds to the pubKey
|
||||||
const signature = pkSigning.sign("message");
|
const signature = pkSigning.sign("message");
|
||||||
const util = new global.Olm.Utility();
|
const util = new globalThis.Olm.Utility();
|
||||||
try {
|
try {
|
||||||
util.ed25519_verify(pubKey, "message", signature);
|
util.ed25519_verify(pubKey, "message", signature);
|
||||||
} finally {
|
} 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.
|
* it's not possible to get one in normal execution unless you hack as we do here.
|
||||||
*/
|
*/
|
||||||
describe.each([
|
describe.each([
|
||||||
["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(global.indexedDB, "tests")],
|
["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(globalThis.indexedDB, "tests")],
|
||||||
["LocalStorageCryptoStore", () => new IndexedDBCryptoStore(undefined!, "tests")],
|
["LocalStorageCryptoStore", () => new IndexedDBCryptoStore(undefined!, "tests")],
|
||||||
[
|
[
|
||||||
"MemoryCryptoStore",
|
"MemoryCryptoStore",
|
||||||
|
@ -43,10 +43,10 @@ const MegolmEncryption = algorithms.ENCRYPTION_CLASSES.get("m.megolm.v1.aes-sha2
|
|||||||
|
|
||||||
const ROOM_ID = "!ROOM:ID";
|
const ROOM_ID = "!ROOM:ID";
|
||||||
|
|
||||||
const Olm = global.Olm;
|
const Olm = globalThis.Olm;
|
||||||
|
|
||||||
describe("MegolmDecryption", function () {
|
describe("MegolmDecryption", function () {
|
||||||
if (!global.Olm) {
|
if (!globalThis.Olm) {
|
||||||
logger.warn("Not running megolm unit tests: libolm not present");
|
logger.warn("Not running megolm unit tests: libolm not present");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -101,7 +101,7 @@ describe("MegolmDecryption", function () {
|
|||||||
describe("receives some keys:", function () {
|
describe("receives some keys:", function () {
|
||||||
let groupSession: OutboundGroupSession;
|
let groupSession: OutboundGroupSession;
|
||||||
beforeEach(async function () {
|
beforeEach(async function () {
|
||||||
groupSession = new global.Olm.OutboundGroupSession();
|
groupSession = new globalThis.Olm.OutboundGroupSession();
|
||||||
groupSession.create();
|
groupSession.create();
|
||||||
|
|
||||||
// construct a fake decrypted key event via the use of a mocked
|
// construct a fake decrypted key event via the use of a mocked
|
||||||
|
@ -47,13 +47,13 @@ function alwaysSucceed<T>(promise: Promise<T>): Promise<T | void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("OlmDevice", function () {
|
describe("OlmDevice", function () {
|
||||||
if (!global.Olm) {
|
if (!globalThis.Olm) {
|
||||||
logger.warn("Not running megolm unit tests: libolm not present");
|
logger.warn("Not running megolm unit tests: libolm not present");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
beforeAll(function () {
|
beforeAll(function () {
|
||||||
return global.Olm.init();
|
return globalThis.Olm.init();
|
||||||
});
|
});
|
||||||
|
|
||||||
let aliceOlmDevice: OlmDevice;
|
let aliceOlmDevice: OlmDevice;
|
||||||
|
@ -33,7 +33,7 @@ import { CryptoStore } from "../../../src/crypto/store/base";
|
|||||||
import { MegolmDecryption as MegolmDecryptionClass } from "../../../src/crypto/algorithms/megolm";
|
import { MegolmDecryption as MegolmDecryptionClass } from "../../../src/crypto/algorithms/megolm";
|
||||||
import { IKeyBackupInfo } from "../../../src/crypto/keybackup";
|
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")!;
|
const MegolmDecryption = algorithms.DECRYPTION_CLASSES.get("m.megolm.v1.aes-sha2")!;
|
||||||
|
|
||||||
@ -155,7 +155,7 @@ function makeTestClient(cryptoStore: CryptoStore) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("MegolmBackup", function () {
|
describe("MegolmBackup", function () {
|
||||||
if (!global.Olm) {
|
if (!globalThis.Olm) {
|
||||||
logger.warn("Not running megolm backup unit tests: libolm not present");
|
logger.warn("Not running megolm backup unit tests: libolm not present");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -205,14 +205,14 @@ describe("MegolmBackup", function () {
|
|||||||
// clobber the setTimeout function to run 100x faster.
|
// clobber the setTimeout function to run 100x faster.
|
||||||
// ideally we would use lolex, but we have no oportunity
|
// ideally we would use lolex, but we have no oportunity
|
||||||
// to tick the clock between the first try and the retry.
|
// to tick the clock between the first try and the retry.
|
||||||
const realSetTimeout = global.setTimeout;
|
const realSetTimeout = globalThis.setTimeout;
|
||||||
jest.spyOn(global, "setTimeout").mockImplementation(function (f, n) {
|
jest.spyOn(globalThis, "setTimeout").mockImplementation(function (f, n) {
|
||||||
return realSetTimeout(f!, n! / 100);
|
return realSetTimeout(f!, n! / 100);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(function () {
|
afterEach(function () {
|
||||||
jest.spyOn(global, "setTimeout").mockRestore();
|
jest.spyOn(globalThis, "setTimeout").mockRestore();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("fail if crypto not enabled", async () => {
|
test("fail if crypto not enabled", async () => {
|
||||||
|
@ -84,13 +84,13 @@ async function makeTestClient(
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("Cross Signing", function () {
|
describe("Cross Signing", function () {
|
||||||
if (!global.Olm) {
|
if (!globalThis.Olm) {
|
||||||
logger.warn("Not running megolm backup unit tests: libolm not present");
|
logger.warn("Not running megolm backup unit tests: libolm not present");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
beforeAll(function () {
|
beforeAll(function () {
|
||||||
return global.Olm.init();
|
return globalThis.Olm.init();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should sign the master key with the device key", async function () {
|
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
|
// set Alice's cross-signing key
|
||||||
await resetCrossSigningKeys(alice);
|
await resetCrossSigningKeys(alice);
|
||||||
// Alice downloads Bob's ssk and device key
|
// 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 bobMasterPrivkey = bobMasterSigning.generate_seed();
|
||||||
const bobMasterPubkey = bobMasterSigning.init_with_seed(bobMasterPrivkey);
|
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 bobPrivkey = bobSigning.generate_seed();
|
||||||
const bobPubkey = bobSigning.init_with_seed(bobPrivkey);
|
const bobPubkey = bobSigning.init_with_seed(bobPrivkey);
|
||||||
const bobSSK: CrossSigningKeyInfo = {
|
const bobSSK: CrossSigningKeyInfo = {
|
||||||
@ -488,7 +488,7 @@ describe("Cross Signing", function () {
|
|||||||
};
|
};
|
||||||
await alice.crypto!.signObject(aliceDevice);
|
await alice.crypto!.signObject(aliceDevice);
|
||||||
|
|
||||||
const bobOlmAccount = new global.Olm.Account();
|
const bobOlmAccount = new globalThis.Olm.Account();
|
||||||
bobOlmAccount.create();
|
bobOlmAccount.create();
|
||||||
const bobKeys = JSON.parse(bobOlmAccount.identity_keys());
|
const bobKeys = JSON.parse(bobOlmAccount.identity_keys());
|
||||||
const bobDeviceUnsigned = {
|
const bobDeviceUnsigned = {
|
||||||
@ -622,10 +622,10 @@ describe("Cross Signing", function () {
|
|||||||
await resetCrossSigningKeys(alice);
|
await resetCrossSigningKeys(alice);
|
||||||
// Alice downloads Bob's ssk and device key
|
// Alice downloads Bob's ssk and device key
|
||||||
// (NOTE: device key is not signed by ssk)
|
// (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 bobMasterPrivkey = bobMasterSigning.generate_seed();
|
||||||
const bobMasterPubkey = bobMasterSigning.init_with_seed(bobMasterPrivkey);
|
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 bobPrivkey = bobSigning.generate_seed();
|
||||||
const bobPubkey = bobSigning.init_with_seed(bobPrivkey);
|
const bobPubkey = bobSigning.init_with_seed(bobPrivkey);
|
||||||
const bobSSK: CrossSigningKeyInfo = {
|
const bobSSK: CrossSigningKeyInfo = {
|
||||||
@ -688,10 +688,10 @@ describe("Cross Signing", function () {
|
|||||||
alice.uploadKeySignatures = async () => ({ failures: {} });
|
alice.uploadKeySignatures = async () => ({ failures: {} });
|
||||||
await resetCrossSigningKeys(alice);
|
await resetCrossSigningKeys(alice);
|
||||||
// Alice downloads Bob's keys
|
// Alice downloads Bob's keys
|
||||||
const bobMasterSigning = new global.Olm.PkSigning();
|
const bobMasterSigning = new globalThis.Olm.PkSigning();
|
||||||
const bobMasterPrivkey = bobMasterSigning.generate_seed();
|
const bobMasterPrivkey = bobMasterSigning.generate_seed();
|
||||||
const bobMasterPubkey = bobMasterSigning.init_with_seed(bobMasterPrivkey);
|
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 bobPrivkey = bobSigning.generate_seed();
|
||||||
const bobPubkey = bobSigning.init_with_seed(bobPrivkey);
|
const bobPubkey = bobSigning.init_with_seed(bobPrivkey);
|
||||||
const bobSSK: CrossSigningKeyInfo = {
|
const bobSSK: CrossSigningKeyInfo = {
|
||||||
@ -755,10 +755,10 @@ describe("Cross Signing", function () {
|
|||||||
expect(bobDeviceTrust.isTofu()).toBeTruthy();
|
expect(bobDeviceTrust.isTofu()).toBeTruthy();
|
||||||
|
|
||||||
// Alice downloads new SSK for Bob
|
// Alice downloads new SSK for Bob
|
||||||
const bobMasterSigning2 = new global.Olm.PkSigning();
|
const bobMasterSigning2 = new globalThis.Olm.PkSigning();
|
||||||
const bobMasterPrivkey2 = bobMasterSigning2.generate_seed();
|
const bobMasterPrivkey2 = bobMasterSigning2.generate_seed();
|
||||||
const bobMasterPubkey2 = bobMasterSigning2.init_with_seed(bobMasterPrivkey2);
|
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 bobPrivkey2 = bobSigning2.generate_seed();
|
||||||
const bobPubkey2 = bobSigning2.init_with_seed(bobPrivkey2);
|
const bobPubkey2 = bobSigning2.init_with_seed(bobPrivkey2);
|
||||||
const bobSSK2: CrossSigningKeyInfo = {
|
const bobSSK2: CrossSigningKeyInfo = {
|
||||||
@ -905,10 +905,10 @@ describe("Cross Signing", function () {
|
|||||||
alice.uploadKeySignatures = async () => ({ failures: {} });
|
alice.uploadKeySignatures = async () => ({ failures: {} });
|
||||||
|
|
||||||
// Generate Alice's SSK etc
|
// Generate Alice's SSK etc
|
||||||
const aliceMasterSigning = new global.Olm.PkSigning();
|
const aliceMasterSigning = new globalThis.Olm.PkSigning();
|
||||||
const aliceMasterPrivkey = aliceMasterSigning.generate_seed();
|
const aliceMasterPrivkey = aliceMasterSigning.generate_seed();
|
||||||
const aliceMasterPubkey = aliceMasterSigning.init_with_seed(aliceMasterPrivkey);
|
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 alicePrivkey = aliceSigning.generate_seed();
|
||||||
const alicePubkey = aliceSigning.init_with_seed(alicePrivkey);
|
const alicePubkey = aliceSigning.init_with_seed(alicePrivkey);
|
||||||
const aliceSSK: CrossSigningKeyInfo = {
|
const aliceSSK: CrossSigningKeyInfo = {
|
||||||
@ -980,10 +980,10 @@ describe("Cross Signing", function () {
|
|||||||
alice.uploadKeySignatures = async () => ({ failures: {} });
|
alice.uploadKeySignatures = async () => ({ failures: {} });
|
||||||
|
|
||||||
// Generate Alice's SSK etc
|
// Generate Alice's SSK etc
|
||||||
const aliceMasterSigning = new global.Olm.PkSigning();
|
const aliceMasterSigning = new globalThis.Olm.PkSigning();
|
||||||
const aliceMasterPrivkey = aliceMasterSigning.generate_seed();
|
const aliceMasterPrivkey = aliceMasterSigning.generate_seed();
|
||||||
const aliceMasterPubkey = aliceMasterSigning.init_with_seed(aliceMasterPrivkey);
|
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 alicePrivkey = aliceSigning.generate_seed();
|
||||||
const alicePubkey = aliceSigning.init_with_seed(alicePrivkey);
|
const alicePubkey = aliceSigning.init_with_seed(alicePrivkey);
|
||||||
const aliceSSK: CrossSigningKeyInfo = {
|
const aliceSSK: CrossSigningKeyInfo = {
|
||||||
@ -1040,10 +1040,10 @@ describe("Cross Signing", function () {
|
|||||||
alice.uploadKeySignatures = async () => ({ failures: {} });
|
alice.uploadKeySignatures = async () => ({ failures: {} });
|
||||||
|
|
||||||
// Generate Alice's SSK etc
|
// Generate Alice's SSK etc
|
||||||
const aliceMasterSigning = new global.Olm.PkSigning();
|
const aliceMasterSigning = new globalThis.Olm.PkSigning();
|
||||||
const aliceMasterPrivkey = aliceMasterSigning.generate_seed();
|
const aliceMasterPrivkey = aliceMasterSigning.generate_seed();
|
||||||
const aliceMasterPubkey = aliceMasterSigning.init_with_seed(aliceMasterPrivkey);
|
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 alicePrivkey = aliceSigning.generate_seed();
|
||||||
const alicePubkey = aliceSigning.init_with_seed(alicePrivkey);
|
const alicePubkey = aliceSigning.init_with_seed(alicePrivkey);
|
||||||
const aliceSSK: CrossSigningKeyInfo = {
|
const aliceSSK: CrossSigningKeyInfo = {
|
||||||
@ -1088,12 +1088,12 @@ describe("Cross Signing", function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("userHasCrossSigningKeys", function () {
|
describe("userHasCrossSigningKeys", function () {
|
||||||
if (!global.Olm) {
|
if (!globalThis.Olm) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
return global.Olm.init();
|
return globalThis.Olm.init();
|
||||||
});
|
});
|
||||||
|
|
||||||
let aliceClient: MatrixClient;
|
let aliceClient: MatrixClient;
|
||||||
|
@ -32,7 +32,7 @@ export async function resetCrossSigningKeys(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function createSecretStorageKey(): Promise<IRecoveryKey> {
|
export async function createSecretStorageKey(): Promise<IRecoveryKey> {
|
||||||
const decryption = new global.Olm.PkDecryption();
|
const decryption = new globalThis.Olm.PkDecryption();
|
||||||
decryption.generate_key();
|
decryption.generate_key();
|
||||||
const storagePrivateKey = decryption.get_private_key();
|
const storagePrivateKey = decryption.get_private_key();
|
||||||
decryption.free();
|
decryption.free();
|
||||||
|
@ -19,16 +19,16 @@ import { TestClient } from "../../TestClient";
|
|||||||
import { logger } from "../../../src/logger";
|
import { logger } from "../../../src/logger";
|
||||||
import { DEHYDRATION_ALGORITHM } from "../../../src/crypto/dehydration";
|
import { DEHYDRATION_ALGORITHM } from "../../../src/crypto/dehydration";
|
||||||
|
|
||||||
const Olm = global.Olm;
|
const Olm = globalThis.Olm;
|
||||||
|
|
||||||
describe("Dehydration", () => {
|
describe("Dehydration", () => {
|
||||||
if (!global.Olm) {
|
if (!globalThis.Olm) {
|
||||||
logger.warn("Not running dehydration unit tests: libolm not present");
|
logger.warn("Not running dehydration unit tests: libolm not present");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
beforeAll(function () {
|
beforeAll(function () {
|
||||||
return global.Olm.init();
|
return globalThis.Olm.init();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should rehydrate a dehydrated device", async () => {
|
it("should rehydrate a dehydrated device", async () => {
|
||||||
|
@ -51,7 +51,7 @@ const requests = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
describe.each([
|
describe.each([
|
||||||
["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(global.indexedDB, "tests")],
|
["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(globalThis.indexedDB, "tests")],
|
||||||
["LocalStorageCryptoStore", () => new LocalStorageCryptoStore(localStorage)],
|
["LocalStorageCryptoStore", () => new LocalStorageCryptoStore(localStorage)],
|
||||||
["MemoryCryptoStore", () => new MemoryCryptoStore()],
|
["MemoryCryptoStore", () => new MemoryCryptoStore()],
|
||||||
])("Outgoing room key requests [%s]", function (name, dbFactory) {
|
])("Outgoing room key requests [%s]", function (name, dbFactory) {
|
||||||
|
@ -69,20 +69,20 @@ function sign<T extends IObject | ICurve25519AuthData>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("Secrets", function () {
|
describe("Secrets", function () {
|
||||||
if (!global.Olm) {
|
if (!globalThis.Olm) {
|
||||||
logger.warn("Not running megolm backup unit tests: libolm not present");
|
logger.warn("Not running megolm backup unit tests: libolm not present");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
beforeAll(function () {
|
beforeAll(function () {
|
||||||
return global.Olm.init();
|
return globalThis.Olm.init();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should store and retrieve a secret", async function () {
|
it("should store and retrieve a secret", async function () {
|
||||||
const key = new Uint8Array(16);
|
const key = new Uint8Array(16);
|
||||||
for (let i = 0; i < 16; i++) key[i] = i;
|
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 signingKey = signing.generate_seed();
|
||||||
const signingPubKey = signing.init_with_seed(signingKey);
|
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 () {
|
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 storagePrivateKey = decryption.get_private_key();
|
||||||
|
|
||||||
const bob: MatrixClient = await makeTestClient(
|
const bob: MatrixClient = await makeTestClient(
|
||||||
|
@ -20,7 +20,7 @@ import { IndexedDBCryptoStore, LocalStorageCryptoStore, MemoryCryptoStore } from
|
|||||||
import { CryptoStore, MigrationState, SESSION_BATCH_SIZE } from "../../../../src/crypto/store/base";
|
import { CryptoStore, MigrationState, SESSION_BATCH_SIZE } from "../../../../src/crypto/store/base";
|
||||||
|
|
||||||
describe.each([
|
describe.each([
|
||||||
["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(global.indexedDB, "tests")],
|
["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(globalThis.indexedDB, "tests")],
|
||||||
["LocalStorageCryptoStore", () => new LocalStorageCryptoStore(localStorage)],
|
["LocalStorageCryptoStore", () => new LocalStorageCryptoStore(localStorage)],
|
||||||
["MemoryCryptoStore", () => new MemoryCryptoStore()],
|
["MemoryCryptoStore", () => new MemoryCryptoStore()],
|
||||||
])("CryptoStore tests for %s", function (name, dbFactory) {
|
])("CryptoStore tests for %s", function (name, dbFactory) {
|
||||||
|
@ -27,21 +27,21 @@ describe("IndexedDBCryptoStore", () => {
|
|||||||
|
|
||||||
it("Should be true if there is a legacy database", async () => {
|
it("Should be true if there is a legacy database", async () => {
|
||||||
// should detect a store that is not migrated
|
// 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.startup();
|
||||||
|
|
||||||
const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(global.indexedDB, "tests");
|
const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(globalThis.indexedDB, "tests");
|
||||||
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("Should be true if there is a legacy database in non migrated state", async () => {
|
it("Should be true if there is a legacy database in non migrated state", async () => {
|
||||||
// should detect a store that is not migrated
|
// 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.startup();
|
||||||
await store.setMigrationState(MigrationState.NOT_STARTED);
|
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);
|
expect(result).toBe(true);
|
||||||
});
|
});
|
||||||
@ -54,18 +54,18 @@ describe("IndexedDBCryptoStore", () => {
|
|||||||
])("Exists and Migration state is %s", (migrationState) => {
|
])("Exists and Migration state is %s", (migrationState) => {
|
||||||
it("Should be false if migration has started", async () => {
|
it("Should be false if migration has started", async () => {
|
||||||
// should detect a store that is not migrated
|
// 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.startup();
|
||||||
await store.setMigrationState(migrationState);
|
await store.setMigrationState(migrationState);
|
||||||
|
|
||||||
const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(global.indexedDB, "tests");
|
const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(globalThis.indexedDB, "tests");
|
||||||
|
|
||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("Should be false if there is no legacy database", async () => {
|
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);
|
expect(result).toBe(false);
|
||||||
});
|
});
|
||||||
|
@ -17,10 +17,10 @@ limitations under the License.
|
|||||||
import "../../../olm-loader";
|
import "../../../olm-loader";
|
||||||
import { logger } from "../../../../src/logger";
|
import { logger } from "../../../../src/logger";
|
||||||
|
|
||||||
const Olm = global.Olm;
|
const Olm = globalThis.Olm;
|
||||||
|
|
||||||
describe("QR code verification", function () {
|
describe("QR code verification", function () {
|
||||||
if (!global.Olm) {
|
if (!globalThis.Olm) {
|
||||||
logger.warn("Not running device verification tests: libolm not present");
|
logger.warn("Not running device verification tests: libolm not present");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -20,12 +20,12 @@ import { logger } from "../../../../src/logger";
|
|||||||
import { SAS } from "../../../../src/crypto/verification/SAS";
|
import { SAS } from "../../../../src/crypto/verification/SAS";
|
||||||
import { makeTestClients } from "./util";
|
import { makeTestClients } from "./util";
|
||||||
|
|
||||||
const Olm = global.Olm;
|
const Olm = globalThis.Olm;
|
||||||
|
|
||||||
jest.useFakeTimers();
|
jest.useFakeTimers();
|
||||||
|
|
||||||
describe("verification request integration tests with crypto layer", function () {
|
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");
|
logger.warn("Not running device verification unit tests: libolm not present");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -29,13 +29,13 @@ import { MatrixClient } from "../../../../src";
|
|||||||
import { VerificationRequest } from "../../../../src/crypto/verification/request/VerificationRequest";
|
import { VerificationRequest } from "../../../../src/crypto/verification/request/VerificationRequest";
|
||||||
import { TestClient } from "../../../TestClient";
|
import { TestClient } from "../../../TestClient";
|
||||||
|
|
||||||
const Olm = global.Olm;
|
const Olm = globalThis.Olm;
|
||||||
|
|
||||||
let ALICE_DEVICES: Record<string, IDevice>;
|
let ALICE_DEVICES: Record<string, IDevice>;
|
||||||
let BOB_DEVICES: Record<string, IDevice>;
|
let BOB_DEVICES: Record<string, IDevice>;
|
||||||
|
|
||||||
describe("SAS verification", function () {
|
describe("SAS verification", function () {
|
||||||
if (!global.Olm) {
|
if (!globalThis.Olm) {
|
||||||
logger.warn("Not running device verification unit tests: libolm not present");
|
logger.warn("Not running device verification unit tests: libolm not present");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -34,7 +34,7 @@ const testKeyPub = "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk";
|
|||||||
|
|
||||||
describe("self-verifications", () => {
|
describe("self-verifications", () => {
|
||||||
beforeAll(function () {
|
beforeAll(function () {
|
||||||
return global.Olm.init();
|
return globalThis.Olm.init();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("triggers a request for key sharing upon completion", async () => {
|
it("triggers a request for key sharing upon completion", async () => {
|
||||||
|
@ -29,12 +29,12 @@ describe("sha256", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("throws if webcrypto is not available", async () => {
|
it("throws if webcrypto is not available", async () => {
|
||||||
const oldCrypto = global.crypto;
|
const oldCrypto = globalThis.crypto;
|
||||||
try {
|
try {
|
||||||
global.crypto = {} as any;
|
globalThis.crypto = {} as any;
|
||||||
await expect(sha256("test")).rejects.toThrow();
|
await expect(sha256("test")).rejects.toThrow();
|
||||||
} finally {
|
} finally {
|
||||||
global.crypto = oldCrypto;
|
globalThis.crypto = oldCrypto;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -57,7 +57,7 @@ describe("MatrixError", () => {
|
|||||||
|
|
||||||
it("should retrieve Date Retry-After header from rate-limit error", () => {
|
it("should retrieve Date Retry-After header from rate-limit error", () => {
|
||||||
headers.set("Retry-After", `${new Date(160000).toUTCString()}`);
|
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 });
|
const err = makeMatrixError(429, { errcode: "M_LIMIT_EXCEEDED", retry_after_ms: 150000 });
|
||||||
expect(err.isRateLimitError()).toBe(true);
|
expect(err.isRateLimitError()).toBe(true);
|
||||||
// prefer Retry-After header over retry_after_ms
|
// prefer Retry-After header over retry_after_ms
|
||||||
|
@ -60,11 +60,11 @@ describe("FetchHttpApi", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should fall back to global fetch if fetchFn not provided", () => {
|
it("should fall back to global fetch if fetchFn not provided", () => {
|
||||||
global.fetch = jest.fn();
|
globalThis.fetch = jest.fn();
|
||||||
expect(global.fetch).not.toHaveBeenCalled();
|
expect(globalThis.fetch).not.toHaveBeenCalled();
|
||||||
const api = new FetchHttpApi(new TypedEventEmitter<any, any>(), { baseUrl, prefix });
|
const api = new FetchHttpApi(new TypedEventEmitter<any, any>(), { baseUrl, prefix });
|
||||||
api.fetch("test");
|
api.fetch("test");
|
||||||
expect(global.fetch).toHaveBeenCalled();
|
expect(globalThis.fetch).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should update identity server base url", () => {
|
it("should update identity server base url", () => {
|
||||||
|
@ -45,9 +45,9 @@ describe("MatrixHttpApi", () => {
|
|||||||
} as unknown as XMLHttpRequest;
|
} as unknown as XMLHttpRequest;
|
||||||
// We stub out XHR here as it is not available in JSDOM
|
// We stub out XHR here as it is not available in JSDOM
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
global.XMLHttpRequest = jest.fn().mockReturnValue(xhr);
|
globalThis.XMLHttpRequest = jest.fn().mockReturnValue(xhr);
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
global.XMLHttpRequest.DONE = DONE;
|
globalThis.XMLHttpRequest.DONE = DONE;
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@ -60,7 +60,7 @@ describe("MatrixHttpApi", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should fall back to `fetch` where xhr is unavailable", () => {
|
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 fetchFn = jest.fn().mockResolvedValue({ ok: true, json: jest.fn().mockResolvedValue({}) });
|
||||||
const api = new MatrixHttpApi(new TypedEventEmitter<any, any>(), { baseUrl, prefix, fetchFn });
|
const api = new MatrixHttpApi(new TypedEventEmitter<any, any>(), { baseUrl, prefix, fetchFn });
|
||||||
upload = api.uploadContent({} as File);
|
upload = api.uploadContent({} as File);
|
||||||
|
@ -70,7 +70,7 @@ describe("Beacon", () => {
|
|||||||
|
|
||||||
const advanceDateAndTime = (ms: number) => {
|
const advanceDateAndTime = (ms: number) => {
|
||||||
// bc liveness check uses Date.now we have to advance this mock
|
// 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
|
// then advance time for the interval by the same amount
|
||||||
jest.advanceTimersByTime(ms);
|
jest.advanceTimersByTime(ms);
|
||||||
};
|
};
|
||||||
@ -108,11 +108,11 @@ describe("Beacon", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// back to 'now'
|
// back to 'now'
|
||||||
jest.spyOn(global.Date, "now").mockReturnValue(now);
|
jest.spyOn(globalThis.Date, "now").mockReturnValue(now);
|
||||||
});
|
});
|
||||||
|
|
||||||
afterAll(() => {
|
afterAll(() => {
|
||||||
jest.spyOn(global.Date, "now").mockRestore();
|
jest.spyOn(globalThis.Date, "now").mockRestore();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("creates beacon from event", () => {
|
it("creates beacon from event", () => {
|
||||||
|
@ -56,7 +56,7 @@ describe("oidc authorization", () => {
|
|||||||
delegatedAuthConfig.metadata.issuer + ".well-known/openid-configuration",
|
delegatedAuthConfig.metadata.issuer + ".well-known/openid-configuration",
|
||||||
mockOpenIdConfiguration(),
|
mockOpenIdConfiguration(),
|
||||||
);
|
);
|
||||||
global.TextEncoder = TextEncoder;
|
globalThis.TextEncoder = TextEncoder;
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
@ -35,7 +35,7 @@ describe("Pushers", () => {
|
|||||||
client = new MatrixClient({
|
client = new MatrixClient({
|
||||||
baseUrl: "https://my.home.server",
|
baseUrl: "https://my.home.server",
|
||||||
accessToken: "my.access.token",
|
accessToken: "my.access.token",
|
||||||
fetchFn: httpBackend.fetchFn as typeof global.fetch,
|
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -82,7 +82,7 @@ describe.each([[StoreType.Memory], [StoreType.IndexedDB]])("queueToDevice (%s st
|
|||||||
client = new MatrixClient({
|
client = new MatrixClient({
|
||||||
baseUrl: "https://my.home.server",
|
baseUrl: "https://my.home.server",
|
||||||
accessToken: "my.access.token",
|
accessToken: "my.access.token",
|
||||||
fetchFn: httpBackend.fetchFn as typeof global.fetch,
|
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
|
||||||
store,
|
store,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -256,7 +256,7 @@ describe.each([[StoreType.Memory], [StoreType.IndexedDB]])("queueToDevice (%s st
|
|||||||
client = new MatrixClient({
|
client = new MatrixClient({
|
||||||
baseUrl: "https://my.home.server",
|
baseUrl: "https://my.home.server",
|
||||||
accessToken: "my.access.token",
|
accessToken: "my.access.token",
|
||||||
fetchFn: httpBackend.fetchFn as typeof global.fetch,
|
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
|
||||||
store,
|
store,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -54,7 +54,7 @@ describe("Read receipt", () => {
|
|||||||
userId: "@user:server",
|
userId: "@user:server",
|
||||||
baseUrl: "https://my.home.server",
|
baseUrl: "https://my.home.server",
|
||||||
accessToken: "my.access.token",
|
accessToken: "my.access.token",
|
||||||
fetchFn: httpBackend.fetchFn as typeof global.fetch,
|
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
|
||||||
});
|
});
|
||||||
client.isGuest = () => false;
|
client.isGuest = () => false;
|
||||||
client.supportsThreads = () => true;
|
client.supportsThreads = () => true;
|
||||||
|
@ -53,8 +53,8 @@ describe("realtime-callbacks", function () {
|
|||||||
|
|
||||||
it("should set 'this' to the global object", function () {
|
it("should set 'this' to the global object", function () {
|
||||||
let passed = false;
|
let passed = false;
|
||||||
const callback = function (this: typeof global) {
|
const callback = function (this: typeof globalThis) {
|
||||||
expect(this).toBe(global); // eslint-disable-line @typescript-eslint/no-invalid-this
|
expect(this).toBe(globalThis); // eslint-disable-line @typescript-eslint/no-invalid-this
|
||||||
expect(this.console).toBeTruthy(); // eslint-disable-line @typescript-eslint/no-invalid-this
|
expect(this.console).toBeTruthy(); // eslint-disable-line @typescript-eslint/no-invalid-this
|
||||||
passed = true;
|
passed = true;
|
||||||
};
|
};
|
||||||
|
@ -61,7 +61,7 @@ describe("OutgoingRequestProcessor", () => {
|
|||||||
const httpApi = new MatrixHttpApi(dummyEventEmitter, {
|
const httpApi = new MatrixHttpApi(dummyEventEmitter, {
|
||||||
baseUrl: "https://example.com",
|
baseUrl: "https://example.com",
|
||||||
prefix: "/_matrix",
|
prefix: "/_matrix",
|
||||||
fetchFn: httpBackend.fetchFn as typeof global.fetch,
|
fetchFn: httpBackend.fetchFn as typeof globalThis.fetch,
|
||||||
onlyData: true,
|
onlyData: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -794,7 +794,7 @@ describe("SyncAccumulator", function () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
jest.spyOn(global.Date, "now").mockRestore();
|
jest.spyOn(globalThis.Date, "now").mockRestore();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should copy summary properties", function () {
|
it("should copy summary properties", function () {
|
||||||
@ -851,11 +851,11 @@ describe("SyncAccumulator", function () {
|
|||||||
const delta = 1000;
|
const delta = 1000;
|
||||||
const startingTs = 1000;
|
const startingTs = 1000;
|
||||||
|
|
||||||
jest.spyOn(global.Date, "now").mockReturnValue(startingTs);
|
jest.spyOn(globalThis.Date, "now").mockReturnValue(startingTs);
|
||||||
|
|
||||||
sa.accumulate(RES_WITH_AGE);
|
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();
|
const output = sa.getJSON();
|
||||||
expect(output.roomsData.join["!foo:bar"].timeline.events[0].unsigned?.age).toEqual(
|
expect(output.roomsData.join["!foo:bar"].timeline.events[0].unsigned?.age).toEqual(
|
||||||
|
@ -119,9 +119,9 @@ describe("Call", function () {
|
|||||||
const errorListener = () => {};
|
const errorListener = () => {};
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
prevNavigator = global.navigator;
|
prevNavigator = globalThis.navigator;
|
||||||
prevDocument = global.document;
|
prevDocument = globalThis.document;
|
||||||
prevWindow = global.window;
|
prevWindow = globalThis.window;
|
||||||
|
|
||||||
installWebRTCMocks();
|
installWebRTCMocks();
|
||||||
|
|
||||||
@ -159,9 +159,9 @@ describe("Call", function () {
|
|||||||
call.hangup(CallErrorCode.UserHangup, true);
|
call.hangup(CallErrorCode.UserHangup, true);
|
||||||
|
|
||||||
client.stop();
|
client.stop();
|
||||||
global.navigator = prevNavigator;
|
globalThis.navigator = prevNavigator;
|
||||||
global.window = prevWindow;
|
globalThis.window = prevWindow;
|
||||||
global.document = prevDocument;
|
globalThis.document = prevDocument;
|
||||||
|
|
||||||
jest.useRealTimers();
|
jest.useRealTimers();
|
||||||
});
|
});
|
||||||
@ -788,17 +788,17 @@ describe("Call", function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should return false if window or document are undefined", () => {
|
it("should return false if window or document are undefined", () => {
|
||||||
global.window = undefined!;
|
globalThis.window = undefined!;
|
||||||
expect(supportsMatrixCall()).toBe(false);
|
expect(supportsMatrixCall()).toBe(false);
|
||||||
global.window = prevWindow;
|
globalThis.window = prevWindow;
|
||||||
global.document = undefined!;
|
globalThis.document = undefined!;
|
||||||
expect(supportsMatrixCall()).toBe(false);
|
expect(supportsMatrixCall()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return false if RTCPeerConnection throws", () => {
|
it("should return false if RTCPeerConnection throws", () => {
|
||||||
// @ts-ignore - writing to window as we are simulating browser edge-cases
|
// @ts-ignore - writing to window as we are simulating browser edge-cases
|
||||||
global.window = {};
|
globalThis.window = {};
|
||||||
Object.defineProperty(global.window, "RTCPeerConnection", {
|
Object.defineProperty(globalThis.window, "RTCPeerConnection", {
|
||||||
get: () => {
|
get: () => {
|
||||||
throw Error("Secure mode, naaah!");
|
throw Error("Secure mode, naaah!");
|
||||||
},
|
},
|
||||||
@ -810,11 +810,11 @@ describe("Call", function () {
|
|||||||
"should return false if RTCPeerConnection & RTCSessionDescription " +
|
"should return false if RTCPeerConnection & RTCSessionDescription " +
|
||||||
"& RTCIceCandidate & mediaDevices are unavailable",
|
"& RTCIceCandidate & mediaDevices are unavailable",
|
||||||
() => {
|
() => {
|
||||||
global.window.RTCPeerConnection = undefined!;
|
globalThis.window.RTCPeerConnection = undefined!;
|
||||||
global.window.RTCSessionDescription = undefined!;
|
globalThis.window.RTCSessionDescription = undefined!;
|
||||||
global.window.RTCIceCandidate = undefined!;
|
globalThis.window.RTCIceCandidate = undefined!;
|
||||||
// @ts-ignore - writing to a read-only property as we are simulating faulty browsers
|
// @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);
|
expect(supportsMatrixCall()).toBe(false);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@ -1305,7 +1305,7 @@ describe("Call", function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("removes RTX codec from screen sharing transcievers", async () => {
|
it("removes RTX codec from screen sharing transcievers", async () => {
|
||||||
mocked(global.RTCRtpSender.getCapabilities).mockReturnValue({
|
mocked(globalThis.RTCRtpSender.getCapabilities).mockReturnValue({
|
||||||
codecs: [
|
codecs: [
|
||||||
{ mimeType: "video/rtx", clockRate: 90000 },
|
{ mimeType: "video/rtx", clockRate: 90000 },
|
||||||
{ mimeType: "video/somethingelse", 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 () => {
|
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
|
// @ts-ignore - writing to window as we are simulating browser edge-cases
|
||||||
global.window = {};
|
globalThis.window = {};
|
||||||
Object.defineProperty(global.window, "RTCPeerConnection", {
|
Object.defineProperty(globalThis.window, "RTCPeerConnection", {
|
||||||
get: () => {
|
get: () => {
|
||||||
throw Error("Secure mode, naaah!");
|
throw Error("Secure mode, naaah!");
|
||||||
},
|
},
|
||||||
|
@ -31,7 +31,7 @@ describe("Media Handler", function () {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
mockMediaDevices = new MockMediaDevices();
|
mockMediaDevices = new MockMediaDevices();
|
||||||
|
|
||||||
global.navigator = {
|
globalThis.navigator = {
|
||||||
mediaDevices: mockMediaDevices.typed(),
|
mediaDevices: mockMediaDevices.typed(),
|
||||||
} as unknown as Navigator;
|
} as unknown as Navigator;
|
||||||
|
|
||||||
|
@ -126,7 +126,7 @@ describe("GroupCallStats", () => {
|
|||||||
|
|
||||||
it("doing nothing if process already running", async () => {
|
it("doing nothing if process already running", async () => {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
jest.spyOn(global, "setInterval").mockReturnValue(22);
|
jest.spyOn(globalThis, "setInterval").mockReturnValue(22);
|
||||||
stats.start();
|
stats.start();
|
||||||
expect(setInterval).toHaveBeenCalledTimes(1);
|
expect(setInterval).toHaveBeenCalledTimes(1);
|
||||||
stats.start();
|
stats.start();
|
||||||
@ -146,8 +146,8 @@ describe("GroupCallStats", () => {
|
|||||||
});
|
});
|
||||||
it("finish stats process if was started", async () => {
|
it("finish stats process if was started", async () => {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
jest.spyOn(global, "setInterval").mockReturnValue(22);
|
jest.spyOn(globalThis, "setInterval").mockReturnValue(22);
|
||||||
jest.spyOn(global, "clearInterval");
|
jest.spyOn(globalThis, "clearInterval");
|
||||||
stats.start();
|
stats.start();
|
||||||
expect(setInterval).toHaveBeenCalledTimes(1);
|
expect(setInterval).toHaveBeenCalledTimes(1);
|
||||||
stats.stop();
|
stats.stop();
|
||||||
@ -155,7 +155,7 @@ describe("GroupCallStats", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("do nothing if stats process was not started", async () => {
|
it("do nothing if stats process was not started", async () => {
|
||||||
jest.spyOn(global, "clearInterval");
|
jest.spyOn(globalThis, "clearInterval");
|
||||||
stats.stop();
|
stats.stop();
|
||||||
expect(clearInterval).not.toHaveBeenCalled();
|
expect(clearInterval).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
4
src/@types/global.d.ts
vendored
4
src/@types/global.d.ts
vendored
@ -14,13 +14,13 @@ See the License for the specific language governing permissions and
|
|||||||
limitations under the License.
|
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";
|
import "@matrix-org/olm";
|
||||||
|
|
||||||
export {};
|
export {};
|
||||||
|
|
||||||
declare global {
|
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.
|
// 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.
|
// 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.
|
// We use `ReturnType<typeof setTimeout>` in the code to be agnostic of if this definition gets loaded.
|
||||||
|
@ -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) {
|
if (this.fetchFn) {
|
||||||
return this.fetchFn(resource, options);
|
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;
|
AutoDiscovery.fetchFn = fetchFn;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -307,7 +307,7 @@ export interface ICreateClientOpts {
|
|||||||
* The function to invoke for HTTP requests.
|
* The function to invoke for HTTP requests.
|
||||||
* Most supported environments have a global `fetch` registered to which this will fall back.
|
* Most supported environments have a global `fetch` registered to which this will fall back.
|
||||||
*/
|
*/
|
||||||
fetchFn?: typeof global.fetch;
|
fetchFn?: typeof globalThis.fetch;
|
||||||
|
|
||||||
userId?: string;
|
userId?: string;
|
||||||
|
|
||||||
@ -1581,11 +1581,11 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
|
|||||||
this.callEventHandler = undefined;
|
this.callEventHandler = undefined;
|
||||||
this.groupCallEventHandler = undefined;
|
this.groupCallEventHandler = undefined;
|
||||||
|
|
||||||
global.clearInterval(this.checkTurnServersIntervalID);
|
globalThis.clearInterval(this.checkTurnServersIntervalID);
|
||||||
this.checkTurnServersIntervalID = undefined;
|
this.checkTurnServersIntervalID = undefined;
|
||||||
|
|
||||||
if (this.clientWellKnownIntervalID !== undefined) {
|
if (this.clientWellKnownIntervalID !== undefined) {
|
||||||
global.clearInterval(this.clientWellKnownIntervalID);
|
globalThis.clearInterval(this.clientWellKnownIntervalID);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.toDeviceMessageQueue.stop();
|
this.toDeviceMessageQueue.stop();
|
||||||
@ -1625,7 +1625,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const account = new global.Olm.Account();
|
const account = new globalThis.Olm.Account();
|
||||||
try {
|
try {
|
||||||
const deviceData = getDeviceResult.device_data;
|
const deviceData = getDeviceResult.device_data;
|
||||||
if (deviceData.algorithm !== DEHYDRATION_ALGORITHM) {
|
if (deviceData.algorithm !== DEHYDRATION_ALGORITHM) {
|
||||||
@ -1781,7 +1781,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
|
|||||||
const deleteRustSdkStore = async (): Promise<void> => {
|
const deleteRustSdkStore = async (): Promise<void> => {
|
||||||
let indexedDB: IDBFactory;
|
let indexedDB: IDBFactory;
|
||||||
try {
|
try {
|
||||||
indexedDB = global.indexedDB;
|
indexedDB = globalThis.indexedDB;
|
||||||
if (!indexedDB) return; // No indexedDB support
|
if (!indexedDB) return; // No indexedDB support
|
||||||
} catch {
|
} catch {
|
||||||
// No indexedDB support
|
// No indexedDB support
|
||||||
@ -1799,7 +1799,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
|
|||||||
resolve(0);
|
resolve(0);
|
||||||
};
|
};
|
||||||
req.onerror = (e): void => {
|
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
|
// (even a non-existent one) fail with "DOMException: A mutation operation was attempted on a
|
||||||
// database that did not allow mutations."
|
// database that did not allow mutations."
|
||||||
//
|
//
|
||||||
@ -7548,7 +7548,9 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
|
|||||||
if ((<HTTPError>err).httpStatus === 403) {
|
if ((<HTTPError>err).httpStatus === 403) {
|
||||||
// We got a 403, so there's no point in looping forever.
|
// We got a 403, so there's no point in looping forever.
|
||||||
this.logger.info("TURN access unavailable for this account: stopping credentials checks");
|
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.checkTurnServersIntervalID = undefined;
|
||||||
this.emit(ClientEvent.TurnServersError, <HTTPError>err, true); // fatal
|
this.emit(ClientEvent.TurnServersError, <HTTPError>err, true); // fatal
|
||||||
} else {
|
} else {
|
||||||
|
@ -125,7 +125,7 @@ export class CrossSigningInfo {
|
|||||||
|
|
||||||
function validateKey(key: Uint8Array | null): [string, PkSigning] | undefined {
|
function validateKey(key: Uint8Array | null): [string, PkSigning] | undefined {
|
||||||
if (!key) return;
|
if (!key) return;
|
||||||
const signing = new global.Olm.PkSigning();
|
const signing = new globalThis.Olm.PkSigning();
|
||||||
const gotPubkey = signing.init_with_seed(key);
|
const gotPubkey = signing.init_with_seed(key);
|
||||||
if (gotPubkey === expectedPubkey) {
|
if (gotPubkey === expectedPubkey) {
|
||||||
return [gotPubkey, signing];
|
return [gotPubkey, signing];
|
||||||
@ -307,7 +307,7 @@ export class CrossSigningInfo {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (level & CrossSigningLevel.MASTER) {
|
if (level & CrossSigningLevel.MASTER) {
|
||||||
masterSigning = new global.Olm.PkSigning();
|
masterSigning = new globalThis.Olm.PkSigning();
|
||||||
privateKeys.master = masterSigning.generate_seed();
|
privateKeys.master = masterSigning.generate_seed();
|
||||||
masterPub = masterSigning.init_with_seed(privateKeys.master);
|
masterPub = masterSigning.init_with_seed(privateKeys.master);
|
||||||
keys.master = {
|
keys.master = {
|
||||||
@ -322,7 +322,7 @@ export class CrossSigningInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (level & CrossSigningLevel.SELF_SIGNING) {
|
if (level & CrossSigningLevel.SELF_SIGNING) {
|
||||||
const sskSigning = new global.Olm.PkSigning();
|
const sskSigning = new globalThis.Olm.PkSigning();
|
||||||
try {
|
try {
|
||||||
privateKeys.self_signing = sskSigning.generate_seed();
|
privateKeys.self_signing = sskSigning.generate_seed();
|
||||||
const sskPub = sskSigning.init_with_seed(privateKeys.self_signing);
|
const sskPub = sskSigning.init_with_seed(privateKeys.self_signing);
|
||||||
@ -340,7 +340,7 @@ export class CrossSigningInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (level & CrossSigningLevel.USER_SIGNING) {
|
if (level & CrossSigningLevel.USER_SIGNING) {
|
||||||
const uskSigning = new global.Olm.PkSigning();
|
const uskSigning = new globalThis.Olm.PkSigning();
|
||||||
try {
|
try {
|
||||||
privateKeys.user_signing = uskSigning.generate_seed();
|
privateKeys.user_signing = uskSigning.generate_seed();
|
||||||
const uskPub = uskSigning.init_with_seed(privateKeys.user_signing);
|
const uskPub = uskSigning.init_with_seed(privateKeys.user_signing);
|
||||||
|
@ -167,7 +167,7 @@ export class OlmDevice {
|
|||||||
* @returns The version of Olm.
|
* @returns The version of Olm.
|
||||||
*/
|
*/
|
||||||
public static getOlmVersion(): [number, number, number] {
|
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> {
|
public async init({ pickleKey, fromExportedDevice }: IInitOpts = {}): Promise<void> {
|
||||||
let e2eKeys;
|
let e2eKeys;
|
||||||
const account = new global.Olm.Account();
|
const account = new globalThis.Olm.Account();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (fromExportedDevice) {
|
if (fromExportedDevice) {
|
||||||
@ -268,7 +268,7 @@ export class OlmDevice {
|
|||||||
*/
|
*/
|
||||||
private getAccount(txn: unknown, func: (account: Account) => void): void {
|
private getAccount(txn: unknown, func: (account: Account) => void): void {
|
||||||
this.cryptoStore.getAccount(txn, (pickledAccount: string | null) => {
|
this.cryptoStore.getAccount(txn, (pickledAccount: string | null) => {
|
||||||
const account = new global.Olm.Account();
|
const account = new globalThis.Olm.Account();
|
||||||
try {
|
try {
|
||||||
account.unpickle(this.pickleKey, pickledAccount!);
|
account.unpickle(this.pickleKey, pickledAccount!);
|
||||||
func(account);
|
func(account);
|
||||||
@ -352,7 +352,7 @@ export class OlmDevice {
|
|||||||
sessionInfo: ISessionInfo,
|
sessionInfo: ISessionInfo,
|
||||||
func: (unpickledSessionInfo: IUnpickledSessionInfo) => void,
|
func: (unpickledSessionInfo: IUnpickledSessionInfo) => void,
|
||||||
): void {
|
): void {
|
||||||
const session = new global.Olm.Session();
|
const session = new globalThis.Olm.Session();
|
||||||
try {
|
try {
|
||||||
session.unpickle(this.pickleKey, sessionInfo.session!);
|
session.unpickle(this.pickleKey, sessionInfo.session!);
|
||||||
const unpickledSessInfo: IUnpickledSessionInfo = Object.assign({}, sessionInfo, { session });
|
const unpickledSessInfo: IUnpickledSessionInfo = Object.assign({}, sessionInfo, { session });
|
||||||
@ -390,7 +390,7 @@ export class OlmDevice {
|
|||||||
* @internal
|
* @internal
|
||||||
*/
|
*/
|
||||||
private getUtility<T>(func: (utility: Utility) => T): T {
|
private getUtility<T>(func: (utility: Utility) => T): T {
|
||||||
const utility = new global.Olm.Utility();
|
const utility = new globalThis.Olm.Utility();
|
||||||
try {
|
try {
|
||||||
return func(utility);
|
return func(utility);
|
||||||
} finally {
|
} finally {
|
||||||
@ -517,7 +517,7 @@ export class OlmDevice {
|
|||||||
[IndexedDBCryptoStore.STORE_ACCOUNT, IndexedDBCryptoStore.STORE_SESSIONS],
|
[IndexedDBCryptoStore.STORE_ACCOUNT, IndexedDBCryptoStore.STORE_SESSIONS],
|
||||||
(txn) => {
|
(txn) => {
|
||||||
this.getAccount(txn, (account: Account) => {
|
this.getAccount(txn, (account: Account) => {
|
||||||
const session = new global.Olm.Session();
|
const session = new globalThis.Olm.Session();
|
||||||
try {
|
try {
|
||||||
session.create_outbound(account, theirIdentityKey, theirOneTimeKey);
|
session.create_outbound(account, theirIdentityKey, theirOneTimeKey);
|
||||||
newSessionId = session.session_id();
|
newSessionId = session.session_id();
|
||||||
@ -567,7 +567,7 @@ export class OlmDevice {
|
|||||||
[IndexedDBCryptoStore.STORE_ACCOUNT, IndexedDBCryptoStore.STORE_SESSIONS],
|
[IndexedDBCryptoStore.STORE_ACCOUNT, IndexedDBCryptoStore.STORE_SESSIONS],
|
||||||
(txn) => {
|
(txn) => {
|
||||||
this.getAccount(txn, (account: Account) => {
|
this.getAccount(txn, (account: Account) => {
|
||||||
const session = new global.Olm.Session();
|
const session = new globalThis.Olm.Session();
|
||||||
try {
|
try {
|
||||||
session.create_inbound_from(account, theirDeviceIdentityKey, ciphertext);
|
session.create_inbound_from(account, theirDeviceIdentityKey, ciphertext);
|
||||||
account.remove_one_time_keys(session);
|
account.remove_one_time_keys(session);
|
||||||
@ -889,7 +889,7 @@ export class OlmDevice {
|
|||||||
throw new Error("Unknown outbound group session " + sessionId);
|
throw new Error("Unknown outbound group session " + sessionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
const session = new global.Olm.OutboundGroupSession();
|
const session = new globalThis.Olm.OutboundGroupSession();
|
||||||
try {
|
try {
|
||||||
session.unpickle(this.pickleKey, pickled);
|
session.unpickle(this.pickleKey, pickled);
|
||||||
return func(session);
|
return func(session);
|
||||||
@ -904,7 +904,7 @@ export class OlmDevice {
|
|||||||
* @returns sessionId for the outbound session.
|
* @returns sessionId for the outbound session.
|
||||||
*/
|
*/
|
||||||
public createOutboundGroupSession(): string {
|
public createOutboundGroupSession(): string {
|
||||||
const session = new global.Olm.OutboundGroupSession();
|
const session = new globalThis.Olm.OutboundGroupSession();
|
||||||
try {
|
try {
|
||||||
session.create();
|
session.create();
|
||||||
this.saveOutboundGroupSession(session);
|
this.saveOutboundGroupSession(session);
|
||||||
@ -966,7 +966,7 @@ export class OlmDevice {
|
|||||||
sessionData: InboundGroupSessionData,
|
sessionData: InboundGroupSessionData,
|
||||||
func: (session: InboundGroupSession) => T,
|
func: (session: InboundGroupSession) => T,
|
||||||
): T {
|
): T {
|
||||||
const session = new global.Olm.InboundGroupSession();
|
const session = new globalThis.Olm.InboundGroupSession();
|
||||||
try {
|
try {
|
||||||
session.unpickle(this.pickleKey, sessionData.session);
|
session.unpickle(this.pickleKey, sessionData.session);
|
||||||
return func(session);
|
return func(session);
|
||||||
@ -1068,7 +1068,7 @@ export class OlmDevice {
|
|||||||
existingSessionData: InboundGroupSessionData | null,
|
existingSessionData: InboundGroupSessionData | null,
|
||||||
) => {
|
) => {
|
||||||
// new session.
|
// new session.
|
||||||
const session = new global.Olm.InboundGroupSession();
|
const session = new globalThis.Olm.InboundGroupSession();
|
||||||
try {
|
try {
|
||||||
if (exportFormat) {
|
if (exportFormat) {
|
||||||
session.import_session(sessionKey);
|
session.import_session(sessionKey);
|
||||||
|
@ -666,13 +666,13 @@ export class Curve25519 implements BackupAlgorithm {
|
|||||||
if (!authData || !("public_key" in authData)) {
|
if (!authData || !("public_key" in authData)) {
|
||||||
throw new Error("auth_data missing required information");
|
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);
|
publicKey.set_recipient_key(authData.public_key);
|
||||||
return new Curve25519(authData as ICurve25519AuthData, publicKey, getKey);
|
return new Curve25519(authData as ICurve25519AuthData, publicKey, getKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async prepare(key?: string | Uint8Array | null): Promise<[Uint8Array, AuthData]> {
|
public static async prepare(key?: string | Uint8Array | null): Promise<[Uint8Array, AuthData]> {
|
||||||
const decryption = new global.Olm.PkDecryption();
|
const decryption = new globalThis.Olm.PkDecryption();
|
||||||
try {
|
try {
|
||||||
const authData: Partial<ICurve25519AuthData> = {};
|
const authData: Partial<ICurve25519AuthData> = {};
|
||||||
if (!key) {
|
if (!key) {
|
||||||
@ -685,7 +685,7 @@ export class Curve25519 implements BackupAlgorithm {
|
|||||||
authData.private_key_iterations = derivation.iterations;
|
authData.private_key_iterations = derivation.iterations;
|
||||||
authData.public_key = decryption.init_with_private_key(derivation.key);
|
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);
|
publicKey.set_recipient_key(authData.public_key);
|
||||||
|
|
||||||
return [decryption.get_private_key(), authData as AuthData];
|
return [decryption.get_private_key(), authData as AuthData];
|
||||||
@ -716,7 +716,7 @@ export class Curve25519 implements BackupAlgorithm {
|
|||||||
sessions: Record<string, IKeyBackupSession<Curve25519SessionData>>,
|
sessions: Record<string, IKeyBackupSession<Curve25519SessionData>>,
|
||||||
): Promise<IMegolmSessionData[]> {
|
): Promise<IMegolmSessionData[]> {
|
||||||
const privKey = await this.getKey();
|
const privKey = await this.getKey();
|
||||||
const decryption = new global.Olm.PkDecryption();
|
const decryption = new globalThis.Olm.PkDecryption();
|
||||||
try {
|
try {
|
||||||
const backupPubKey = decryption.init_with_private_key(privKey);
|
const backupPubKey = decryption.init_with_private_key(privKey);
|
||||||
|
|
||||||
@ -748,7 +748,7 @@ export class Curve25519 implements BackupAlgorithm {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async keyMatches(key: Uint8Array): Promise<boolean> {
|
public async keyMatches(key: Uint8Array): Promise<boolean> {
|
||||||
const decryption = new global.Olm.PkDecryption();
|
const decryption = new globalThis.Olm.PkDecryption();
|
||||||
let pubKey: string;
|
let pubKey: string;
|
||||||
try {
|
try {
|
||||||
pubKey = decryption.init_with_private_key(key);
|
pubKey = decryption.init_with_private_key(key);
|
||||||
|
@ -68,7 +68,7 @@ export class DehydrationManager {
|
|||||||
this.deviceDisplayName = deviceDisplayName;
|
this.deviceDisplayName = deviceDisplayName;
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const delay = Math.max(1, time + oneweek - 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",
|
"dehydration",
|
||||||
@ -97,7 +97,7 @@ export class DehydrationManager {
|
|||||||
if (!key) {
|
if (!key) {
|
||||||
// unsetting the key -- cancel any pending dehydration task
|
// unsetting the key -- cancel any pending dehydration task
|
||||||
if (this.timeoutId) {
|
if (this.timeoutId) {
|
||||||
global.clearTimeout(this.timeoutId);
|
globalThis.clearTimeout(this.timeoutId);
|
||||||
this.timeoutId = undefined;
|
this.timeoutId = undefined;
|
||||||
}
|
}
|
||||||
// clear storage
|
// clear storage
|
||||||
@ -135,7 +135,7 @@ export class DehydrationManager {
|
|||||||
}
|
}
|
||||||
this.inProgress = true;
|
this.inProgress = true;
|
||||||
if (this.timeoutId) {
|
if (this.timeoutId) {
|
||||||
global.clearTimeout(this.timeoutId);
|
globalThis.clearTimeout(this.timeoutId);
|
||||||
this.timeoutId = undefined;
|
this.timeoutId = undefined;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@ -155,7 +155,7 @@ export class DehydrationManager {
|
|||||||
|
|
||||||
logger.log("Creating account");
|
logger.log("Creating account");
|
||||||
// create the account and all the necessary keys
|
// create the account and all the necessary keys
|
||||||
const account = new global.Olm.Account();
|
const account = new globalThis.Olm.Account();
|
||||||
account.create();
|
account.create();
|
||||||
const e2eKeys = JSON.parse(account.identity_keys());
|
const e2eKeys = JSON.parse(account.identity_keys());
|
||||||
|
|
||||||
@ -255,7 +255,7 @@ export class DehydrationManager {
|
|||||||
logger.log("Done dehydrating");
|
logger.log("Done dehydrating");
|
||||||
|
|
||||||
// dehydrate again in a week
|
// 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;
|
return deviceId;
|
||||||
} finally {
|
} finally {
|
||||||
@ -265,7 +265,7 @@ export class DehydrationManager {
|
|||||||
|
|
||||||
public stop(): void {
|
public stop(): void {
|
||||||
if (this.timeoutId) {
|
if (this.timeoutId) {
|
||||||
global.clearTimeout(this.timeoutId);
|
globalThis.clearTimeout(this.timeoutId);
|
||||||
this.timeoutId = undefined;
|
this.timeoutId = undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -537,7 +537,7 @@ export class Crypto extends TypedEventEmitter<CryptoEvent, CryptoEventHandlerMap
|
|||||||
*/
|
*/
|
||||||
public async init({ exportedOlmDevice, pickleKey }: IInitOpts = {}): Promise<void> {
|
public async init({ exportedOlmDevice, pickleKey }: IInitOpts = {}): Promise<void> {
|
||||||
logger.log("Crypto: initialising Olm...");
|
logger.log("Crypto: initialising Olm...");
|
||||||
await global.Olm.init();
|
await globalThis.Olm.init();
|
||||||
logger.log(
|
logger.log(
|
||||||
exportedOlmDevice
|
exportedOlmDevice
|
||||||
? "Crypto: initialising Olm device from exported device..."
|
? "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.
|
* and raw private key to avoid round tripping if needed.
|
||||||
*/
|
*/
|
||||||
public async createRecoveryKeyFromPassphrase(password?: string): Promise<IRecoveryKey> {
|
public async createRecoveryKeyFromPassphrase(password?: string): Promise<IRecoveryKey> {
|
||||||
const decryption = new global.Olm.PkDecryption();
|
const decryption = new globalThis.Olm.PkDecryption();
|
||||||
try {
|
try {
|
||||||
if (password) {
|
if (password) {
|
||||||
const derivation = await keyFromPassphrase(password);
|
const derivation = await keyFromPassphrase(password);
|
||||||
@ -1252,7 +1252,7 @@ export class Crypto extends TypedEventEmitter<CryptoEvent, CryptoEventHandlerMap
|
|||||||
public checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {
|
public checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {
|
||||||
let decryption: PkDecryption | null = null;
|
let decryption: PkDecryption | null = null;
|
||||||
try {
|
try {
|
||||||
decryption = new global.Olm.PkDecryption();
|
decryption = new globalThis.Olm.PkDecryption();
|
||||||
const gotPubkey = decryption.init_with_private_key(privateKey);
|
const gotPubkey = decryption.init_with_private_key(privateKey);
|
||||||
// make sure it agrees with the given pubkey
|
// make sure it agrees with the given pubkey
|
||||||
return gotPubkey === expectedPublicKey;
|
return gotPubkey === expectedPublicKey;
|
||||||
@ -1354,7 +1354,7 @@ export class Crypto extends TypedEventEmitter<CryptoEvent, CryptoEventHandlerMap
|
|||||||
public checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {
|
public checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {
|
||||||
let signing: PkSigning | null = null;
|
let signing: PkSigning | null = null;
|
||||||
try {
|
try {
|
||||||
signing = new global.Olm.PkSigning();
|
signing = new globalThis.Olm.PkSigning();
|
||||||
const gotPubkey = signing.init_with_seed(privateKey);
|
const gotPubkey = signing.init_with_seed(privateKey);
|
||||||
// make sure it agrees with the given pubkey
|
// make sure it agrees with the given pubkey
|
||||||
return gotPubkey === expectedPublicKey;
|
return gotPubkey === expectedPublicKey;
|
||||||
|
@ -471,7 +471,7 @@ export async function verifySignature(
|
|||||||
export function pkSign(obj: object & IObject, key: Uint8Array | PkSigning, userId: string, pubKey: string): string {
|
export function pkSign(obj: object & IObject, key: Uint8Array | PkSigning, userId: string, pubKey: string): string {
|
||||||
let createdKey = false;
|
let createdKey = false;
|
||||||
if (key instanceof Uint8Array) {
|
if (key instanceof Uint8Array) {
|
||||||
const keyObj = new global.Olm.PkSigning();
|
const keyObj = new globalThis.Olm.PkSigning();
|
||||||
pubKey = keyObj.init_with_seed(key);
|
pubKey = keyObj.init_with_seed(key);
|
||||||
key = keyObj;
|
key = keyObj;
|
||||||
createdKey = true;
|
createdKey = true;
|
||||||
@ -506,7 +506,7 @@ export function pkVerify(obj: IObject, pubKey: string, userId: string): void {
|
|||||||
throw new Error("No signature");
|
throw new Error("No signature");
|
||||||
}
|
}
|
||||||
const signature = obj.signatures[userId][keyId];
|
const signature = obj.signatures[userId][keyId];
|
||||||
const util = new global.Olm.Utility();
|
const util = new globalThis.Olm.Utility();
|
||||||
const sigs = obj.signatures;
|
const sigs = obj.signatures;
|
||||||
delete obj.signatures;
|
delete obj.signatures;
|
||||||
const unsigned = obj.unsigned;
|
const unsigned = obj.unsigned;
|
||||||
|
@ -210,7 +210,7 @@ export class IndexedDBCryptoStore implements CryptoStore {
|
|||||||
);
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return new LocalStorageCryptoStore(global.localStorage);
|
return new LocalStorageCryptoStore(globalThis.localStorage);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn(`unable to open localStorage: falling back to in-memory store: ${e}`);
|
logger.warn(`unable to open localStorage: falling back to in-memory store: ${e}`);
|
||||||
return new MemoryCryptoStore();
|
return new MemoryCryptoStore();
|
||||||
|
@ -242,8 +242,8 @@ export class SAS extends Base {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected doVerification = async (): Promise<void> => {
|
protected doVerification = async (): Promise<void> => {
|
||||||
await global.Olm.init();
|
await globalThis.Olm.init();
|
||||||
olmutil = olmutil || new global.Olm.Utility();
|
olmutil = olmutil || new globalThis.Olm.Utility();
|
||||||
|
|
||||||
// make sure user's keys are downloaded
|
// make sure user's keys are downloaded
|
||||||
await this.baseApis.downloadKeys([this.userId]);
|
await this.baseApis.downloadKeys([this.userId]);
|
||||||
@ -369,7 +369,7 @@ export class SAS extends Base {
|
|||||||
const keyAgreement = content.key_agreement_protocol;
|
const keyAgreement = content.key_agreement_protocol;
|
||||||
const macMethod = content.message_authentication_code;
|
const macMethod = content.message_authentication_code;
|
||||||
const hashCommitment = content.commitment;
|
const hashCommitment = content.commitment;
|
||||||
const olmSAS = new global.Olm.SAS();
|
const olmSAS = new globalThis.Olm.SAS();
|
||||||
try {
|
try {
|
||||||
this.ourSASPubKey = olmSAS.get_pubkey();
|
this.ourSASPubKey = olmSAS.get_pubkey();
|
||||||
await this.send(EventType.KeyVerificationKey, {
|
await this.send(EventType.KeyVerificationKey, {
|
||||||
@ -411,7 +411,7 @@ export class SAS extends Base {
|
|||||||
throw newUnknownMethodError();
|
throw newUnknownMethodError();
|
||||||
}
|
}
|
||||||
|
|
||||||
const olmSAS = new global.Olm.SAS();
|
const olmSAS = new globalThis.Olm.SAS();
|
||||||
try {
|
try {
|
||||||
const commitmentStr = olmSAS.get_pubkey() + anotherjson.stringify(content);
|
const commitmentStr = olmSAS.get_pubkey() + anotherjson.stringify(content);
|
||||||
await this.send(EventType.KeyVerificationAccept, {
|
await this.send(EventType.KeyVerificationAccept, {
|
||||||
|
@ -53,11 +53,11 @@ export class FetchHttpApi<O extends IHttpOpts> {
|
|||||||
this.abortController = new AbortController();
|
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) {
|
if (this.opts.fetchFn) {
|
||||||
return this.opts.fetchFn(resource, options);
|
return this.opts.fetchFn(resource, options);
|
||||||
}
|
}
|
||||||
return global.fetch(resource, options);
|
return globalThis.fetch(resource, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -60,8 +60,8 @@ export class MatrixHttpApi<O extends IHttpOpts> extends FetchHttpApi<O> {
|
|||||||
} as Upload;
|
} as Upload;
|
||||||
const deferred = defer<UploadResponse>();
|
const deferred = defer<UploadResponse>();
|
||||||
|
|
||||||
if (global.XMLHttpRequest) {
|
if (globalThis.XMLHttpRequest) {
|
||||||
const xhr = new global.XMLHttpRequest();
|
const xhr = new globalThis.XMLHttpRequest();
|
||||||
|
|
||||||
const timeoutFn = function (): void {
|
const timeoutFn = function (): void {
|
||||||
xhr.abort();
|
xhr.abort();
|
||||||
@ -73,7 +73,7 @@ export class MatrixHttpApi<O extends IHttpOpts> extends FetchHttpApi<O> {
|
|||||||
|
|
||||||
xhr.onreadystatechange = function (): void {
|
xhr.onreadystatechange = function (): void {
|
||||||
switch (xhr.readyState) {
|
switch (xhr.readyState) {
|
||||||
case global.XMLHttpRequest.DONE:
|
case globalThis.XMLHttpRequest.DONE:
|
||||||
callbacks.clearTimeout(timeoutTimer);
|
callbacks.clearTimeout(timeoutTimer);
|
||||||
try {
|
try {
|
||||||
if (xhr.status === 0) {
|
if (xhr.status === 0) {
|
||||||
|
@ -36,7 +36,7 @@ export type AccessTokens = {
|
|||||||
*/
|
*/
|
||||||
export type TokenRefreshFunction = (refreshToken: string) => Promise<AccessTokens>;
|
export type TokenRefreshFunction = (refreshToken: string) => Promise<AccessTokens>;
|
||||||
export interface IHttpOpts {
|
export interface IHttpOpts {
|
||||||
fetchFn?: typeof global.fetch;
|
fetchFn?: typeof globalThis.fetch;
|
||||||
|
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
idBaseUrl?: string;
|
idBaseUrl?: string;
|
||||||
|
@ -16,10 +16,10 @@ limitations under the License.
|
|||||||
|
|
||||||
import * as matrixcs from "./matrix.ts";
|
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!");
|
throw new Error("Multiple matrix-js-sdk entrypoints detected!");
|
||||||
}
|
}
|
||||||
global.__js_sdk_entrypoint = true;
|
globalThis.__js_sdk_entrypoint = true;
|
||||||
|
|
||||||
export * from "./matrix.ts";
|
export * from "./matrix.ts";
|
||||||
export default matrixcs;
|
export default matrixcs;
|
||||||
|
@ -130,7 +130,7 @@ function amendClientOpts(opts: ICreateClientOpts): ICreateClientOpts {
|
|||||||
opts.store =
|
opts.store =
|
||||||
opts.store ??
|
opts.store ??
|
||||||
new MemoryStore({
|
new MemoryStore({
|
||||||
localStorage: global.localStorage,
|
localStorage: globalThis.localStorage,
|
||||||
});
|
});
|
||||||
opts.scheduler = opts.scheduler ?? new MatrixScheduler();
|
opts.scheduler = opts.scheduler ?? new MatrixScheduler();
|
||||||
opts.cryptoStore = opts.cryptoStore ?? cryptoStoreFactory();
|
opts.cryptoStore = opts.cryptoStore ?? cryptoStoreFactory();
|
||||||
|
@ -33,7 +33,7 @@ const TIMER_CHECK_PERIOD_MS = 1000;
|
|||||||
// counter, for making up ids to return from setTimeout
|
// counter, for making up ids to return from setTimeout
|
||||||
let count = 0;
|
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;
|
let realCallbackKey: NodeJS.Timeout | number;
|
||||||
|
|
||||||
type Callback = {
|
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 {
|
function scheduleRealCallback(): void {
|
||||||
if (realCallbackKey) {
|
if (realCallbackKey) {
|
||||||
global.clearTimeout(realCallbackKey as NodeJS.Timeout);
|
globalThis.clearTimeout(realCallbackKey as NodeJS.Timeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
const first = callbackList[0];
|
const first = callbackList[0];
|
||||||
@ -131,7 +131,7 @@ function scheduleRealCallback(): void {
|
|||||||
const delayMs = Math.min(first.runAt - timestamp, TIMER_CHECK_PERIOD_MS);
|
const delayMs = Math.min(first.runAt - timestamp, TIMER_CHECK_PERIOD_MS);
|
||||||
|
|
||||||
debuglog("scheduleRealCallback: now:", timestamp, "delay:", delayMs);
|
debuglog("scheduleRealCallback: now:", timestamp, "delay:", delayMs);
|
||||||
realCallbackKey = global.setTimeout(runCallbacks, delayMs);
|
realCallbackKey = globalThis.setTimeout(runCallbacks, delayMs);
|
||||||
}
|
}
|
||||||
|
|
||||||
function runCallbacks(): void {
|
function runCallbacks(): void {
|
||||||
@ -158,7 +158,7 @@ function runCallbacks(): void {
|
|||||||
|
|
||||||
for (const cb of callbacksToRun) {
|
for (const cb of callbacksToRun) {
|
||||||
try {
|
try {
|
||||||
cb.func.apply(global, cb.params);
|
cb.func.apply(globalThis, cb.params);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.error("Uncaught exception in callback function", e);
|
logger.error("Uncaught exception in callback function", e);
|
||||||
}
|
}
|
||||||
|
@ -29,7 +29,7 @@ export class MSC4108RendezvousSession {
|
|||||||
public url?: string;
|
public url?: string;
|
||||||
private readonly client?: MatrixClient;
|
private readonly client?: MatrixClient;
|
||||||
private readonly fallbackRzServer?: string;
|
private readonly fallbackRzServer?: string;
|
||||||
private readonly fetchFn?: typeof global.fetch;
|
private readonly fetchFn?: typeof globalThis.fetch;
|
||||||
private readonly onFailure?: RendezvousFailureListener;
|
private readonly onFailure?: RendezvousFailureListener;
|
||||||
private etag?: string;
|
private etag?: string;
|
||||||
private expiresAt?: Date;
|
private expiresAt?: Date;
|
||||||
@ -42,7 +42,7 @@ export class MSC4108RendezvousSession {
|
|||||||
url,
|
url,
|
||||||
fetchFn,
|
fetchFn,
|
||||||
}: {
|
}: {
|
||||||
fetchFn?: typeof global.fetch;
|
fetchFn?: typeof globalThis.fetch;
|
||||||
onFailure?: RendezvousFailureListener;
|
onFailure?: RendezvousFailureListener;
|
||||||
url: string;
|
url: string;
|
||||||
});
|
});
|
||||||
@ -52,7 +52,7 @@ export class MSC4108RendezvousSession {
|
|||||||
fallbackRzServer,
|
fallbackRzServer,
|
||||||
fetchFn,
|
fetchFn,
|
||||||
}: {
|
}: {
|
||||||
fetchFn?: typeof global.fetch;
|
fetchFn?: typeof globalThis.fetch;
|
||||||
onFailure?: RendezvousFailureListener;
|
onFailure?: RendezvousFailureListener;
|
||||||
client?: MatrixClient;
|
client?: MatrixClient;
|
||||||
fallbackRzServer?: string;
|
fallbackRzServer?: string;
|
||||||
@ -64,7 +64,7 @@ export class MSC4108RendezvousSession {
|
|||||||
client,
|
client,
|
||||||
fallbackRzServer,
|
fallbackRzServer,
|
||||||
}: {
|
}: {
|
||||||
fetchFn?: typeof global.fetch;
|
fetchFn?: typeof globalThis.fetch;
|
||||||
onFailure?: RendezvousFailureListener;
|
onFailure?: RendezvousFailureListener;
|
||||||
url?: string;
|
url?: string;
|
||||||
client?: MatrixClient;
|
client?: MatrixClient;
|
||||||
@ -91,11 +91,11 @@ export class MSC4108RendezvousSession {
|
|||||||
return this._cancelled;
|
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) {
|
if (this.fetchFn) {
|
||||||
return this.fetchFn(resource, options);
|
return this.fetchFn(resource, options);
|
||||||
}
|
}
|
||||||
return global.fetch(resource, options);
|
return globalThis.fetch(resource, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getPostEndpoint(): Promise<string | undefined> {
|
private async getPostEndpoint(): Promise<string | undefined> {
|
||||||
|
10
src/sync.ts
10
src/sync.ts
@ -694,7 +694,7 @@ export class SyncApi {
|
|||||||
this.running = true;
|
this.running = true;
|
||||||
this.abortController = new AbortController();
|
this.abortController = new AbortController();
|
||||||
|
|
||||||
global.window?.addEventListener?.("online", this.onOnline, false);
|
globalThis.window?.addEventListener?.("online", this.onOnline, false);
|
||||||
|
|
||||||
if (this.client.isGuest()) {
|
if (this.client.isGuest()) {
|
||||||
// no push rules for guests, no access to POST filter for guests.
|
// no push rules for guests, no access to POST filter for guests.
|
||||||
@ -779,10 +779,10 @@ export class SyncApi {
|
|||||||
public stop(): void {
|
public stop(): void {
|
||||||
debuglog("SyncApi.stop");
|
debuglog("SyncApi.stop");
|
||||||
// It is necessary to check for the existance of
|
// It is necessary to check for the existance of
|
||||||
// global.window AND global.window.removeEventListener.
|
// globalThis.window AND globalThis.window.removeEventListener.
|
||||||
// Some platforms (e.g. React Native) register global.window,
|
// Some platforms (e.g. React Native) register globalThis.window,
|
||||||
// but do not have global.window.removeEventListener.
|
// but do not have globalThis.window.removeEventListener.
|
||||||
global.window?.removeEventListener?.("online", this.onOnline, false);
|
globalThis.window?.removeEventListener?.("online", this.onOnline, false);
|
||||||
this.running = false;
|
this.running = false;
|
||||||
this.abortController?.abort();
|
this.abortController?.abort();
|
||||||
if (this.keepAliveTimer) {
|
if (this.keepAliveTimer) {
|
||||||
|
Reference in New Issue
Block a user