Skip to content

Commit 963c769

Browse files
authored
Iterate typing to work towards noImplicitAny (#2061)
1 parent aeec4aa commit 963c769

File tree

16 files changed

+161
-140
lines changed

16 files changed

+161
-140
lines changed

spec/unit/models/MSC3089Branch.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ describe("MSC3089Branch", () => {
312312
} as MatrixEvent);
313313

314314
const events = [await branch.getFileEvent(), await branch2.getFileEvent(), {
315-
replacingEventId: () => null,
315+
replacingEventId: (): string => null,
316316
getId: () => "$unknown",
317317
}];
318318
staticRoom.getLiveTimeline = () => ({ getEvents: () => events }) as EventTimeline;

src/@types/global.d.ts

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,6 @@ declare global {
6262
};
6363
}
6464

65-
interface HTMLAudioElement {
66-
// sinkId & setSinkId are experimental and typescript doesn't know about them
67-
sinkId: string;
68-
setSinkId(outputId: string);
69-
}
70-
7165
interface DummyInterfaceWeShouldntBeUsingThis {}
7266

7367
interface Navigator {

src/client.ts

Lines changed: 46 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -621,7 +621,7 @@ export interface IMyDevice {
621621
last_seen_ts?: number;
622622
}
623623

624-
interface IDownloadKeyResult {
624+
export interface IDownloadKeyResult {
625625
failures: { [serverName: string]: object };
626626
device_keys: {
627627
[userId: string]: {
@@ -632,13 +632,42 @@ interface IDownloadKeyResult {
632632
};
633633
};
634634
};
635+
// the following three fields were added in 1.1
636+
master_keys?: {
637+
[userId: string]: {
638+
keys: { [keyId: string]: string };
639+
usage: string[];
640+
user_id: string;
641+
};
642+
};
643+
self_signing_keys?: {
644+
[userId: string]: {
645+
keys: { [keyId: string]: string };
646+
signatures: ISignatures;
647+
usage: string[];
648+
user_id: string;
649+
};
650+
};
651+
user_signing_keys?: {
652+
[userId: string]: {
653+
keys: { [keyId: string]: string };
654+
signatures: ISignatures;
655+
usage: string[];
656+
user_id: string;
657+
};
658+
};
635659
}
636660

637-
interface IClaimOTKsResult {
661+
export interface IClaimOTKsResult {
638662
failures: { [serverName: string]: object };
639663
one_time_keys: {
640664
[userId: string]: {
641-
[deviceId: string]: string;
665+
[deviceId: string]: {
666+
[keyId: string]: {
667+
key: string;
668+
signatures: ISignatures;
669+
};
670+
};
642671
};
643672
};
644673
}
@@ -1421,14 +1450,12 @@ export class MatrixClient extends EventEmitter {
14211450
}
14221451
}
14231452

1424-
// We swallow errors because we need a default object anyhow
14251453
return this.http.authedRequest(
14261454
undefined, "GET", "/capabilities",
1427-
).catch((e: Error) => {
1455+
).catch((e: Error): void => {
1456+
// We swallow errors because we need a default object anyhow
14281457
logger.error(e);
1429-
return null; // otherwise consume the error
1430-
}).then((r) => {
1431-
if (!r) r = {};
1458+
}).then((r: { capabilities?: ICapabilities } = {}) => {
14321459
const capabilities: ICapabilities = r["capabilities"] || {};
14331460

14341461
// If the capabilities missed the cache, cache it for a shorter amount
@@ -2836,7 +2863,7 @@ export class MatrixClient extends EventEmitter {
28362863
}
28372864

28382865
let totalKeyCount = 0;
2839-
let keys = [];
2866+
let keys: IMegolmSessionData[] = [];
28402867

28412868
const path = this.makeKeyBackupPath(targetRoomId, targetSessionId, backupInfo.version);
28422869

@@ -5692,18 +5719,14 @@ export class MatrixClient extends EventEmitter {
56925719
searchResults.count = roomEvents.count;
56935720
searchResults.next_batch = roomEvents.next_batch;
56945721

5695-
// combine the highlight list with our existing list; build an object
5696-
// to avoid O(N^2) fail
5697-
const highlights = {};
5698-
roomEvents.highlights.forEach((hl) => {
5699-
highlights[hl] = 1;
5700-
});
5722+
// combine the highlight list with our existing list;
5723+
const highlights = new Set<string>(roomEvents.highlights);
57015724
searchResults.highlights.forEach((hl) => {
5702-
highlights[hl] = 1;
5725+
highlights.add(hl);
57035726
});
57045727

57055728
// turn it back into a list.
5706-
searchResults.highlights = Object.keys(highlights);
5729+
searchResults.highlights = Array.from(highlights);
57075730

57085731
// append the new results to our existing results
57095732
const resultsLength = roomEvents.results ? roomEvents.results.length : 0;
@@ -5794,11 +5817,9 @@ export class MatrixClient extends EventEmitter {
57945817

57955818
return this.http.authedRequest(
57965819
undefined, "GET", path, undefined, undefined,
5797-
).then((response) => {
5820+
).then((response: IFilterDefinition) => {
57985821
// persist the filter
5799-
const filter = Filter.fromJson(
5800-
userId, filterId, response,
5801-
);
5822+
const filter = Filter.fromJson(userId, filterId, response);
58025823
this.store.storeFilter(filter);
58035824
return filter;
58045825
});
@@ -6096,7 +6117,7 @@ export class MatrixClient extends EventEmitter {
60966117
{
60976118
prefix: '',
60986119
},
6099-
).catch((e) => {
6120+
).catch((e: Error) => {
61006121
// Need to unset this if it fails, otherwise we'll never retry
61016122
this.serverVersionsPromise = null;
61026123
// but rethrow the exception to anything that was waiting
@@ -6420,7 +6441,7 @@ export class MatrixClient extends EventEmitter {
64206441
public isUsernameAvailable(username: string): Promise<true> {
64216442
return this.http.authedRequest(
64226443
undefined, "GET", '/register/available', { username: username },
6423-
).then((response) => {
6444+
).then((response: { available: boolean }) => {
64246445
return response.available;
64256446
});
64266447
}
@@ -7741,11 +7762,11 @@ export class MatrixClient extends EventEmitter {
77417762
* an error response ({@link module:http-api.MatrixError}).
77427763
*/
77437764
public claimOneTimeKeys(
7744-
devices: string[],
7765+
devices: [string, string][],
77457766
keyAlgorithm = "signed_curve25519",
77467767
timeout?: number,
77477768
): Promise<IClaimOTKsResult> {
7748-
const queries = {};
7769+
const queries: Record<string, Record<string, string>> = {};
77497770

77507771
if (keyAlgorithm === undefined) {
77517772
keyAlgorithm = "signed_curve25519";

src/crypto/CrossSigning.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import { OlmDevice } from "./OlmDevice";
3333
import { ICryptoCallbacks } from "../matrix";
3434
import { ISignatures } from "../@types/signed";
3535
import { CryptoStore } from "./store/base";
36+
import { ISecretStorageKeyInfo } from "./api";
3637

3738
const KEY_REQUEST_TIMEOUT_MS = 1000 * 60;
3839

@@ -175,7 +176,7 @@ export class CrossSigningInfo extends EventEmitter {
175176
// check what SSSS keys have encrypted the master key (if any)
176177
const stored = await secretStorage.isStored("m.cross_signing.master", false) || {};
177178
// then check which of those SSSS keys have also encrypted the SSK and USK
178-
function intersect(s) {
179+
function intersect(s: Record<string, ISecretStorageKeyInfo>) {
179180
for (const k of Object.keys(stored)) {
180181
if (!s[k]) {
181182
delete stored[k];

src/crypto/DeviceList.ts

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import { CrossSigningInfo, ICrossSigningInfo } from './CrossSigning';
2828
import * as olmlib from './olmlib';
2929
import { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';
3030
import { chunkPromises, defer, IDeferred, sleep } from '../utils';
31-
import { MatrixClient } from "../client";
31+
import { IDownloadKeyResult, MatrixClient } from "../client";
3232
import { OlmDevice } from "./OlmDevice";
3333
import { CryptoStore } from "./store/base";
3434

@@ -756,17 +756,21 @@ class DeviceListUpdateSerialiser {
756756
opts.token = this.syncToken;
757757
}
758758

759-
const factories = [];
759+
const factories: Array<() => Promise<IDownloadKeyResult>> = [];
760760
for (let i = 0; i < downloadUsers.length; i += this.deviceList.keyDownloadChunkSize) {
761761
const userSlice = downloadUsers.slice(i, i + this.deviceList.keyDownloadChunkSize);
762762
factories.push(() => this.baseApis.downloadKeysForUsers(userSlice, opts));
763763
}
764764

765-
chunkPromises(factories, 3).then(async (responses: any[]) => {
766-
const dk = Object.assign({}, ...(responses.map(res => res.device_keys || {})));
767-
const masterKeys = Object.assign({}, ...(responses.map(res => res.master_keys || {})));
768-
const ssks = Object.assign({}, ...(responses.map(res => res.self_signing_keys || {})));
769-
const usks = Object.assign({}, ...(responses.map(res => res.user_signing_keys || {})));
765+
chunkPromises(factories, 3).then(async (responses: IDownloadKeyResult[]) => {
766+
const dk: IDownloadKeyResult["device_keys"]
767+
= Object.assign({}, ...(responses.map(res => res.device_keys || {})));
768+
const masterKeys: IDownloadKeyResult["master_keys"]
769+
= Object.assign({}, ...(responses.map(res => res.master_keys || {})));
770+
const ssks: IDownloadKeyResult["self_signing_keys"]
771+
= Object.assign({}, ...(responses.map(res => res.self_signing_keys || {})));
772+
const usks: IDownloadKeyResult["user_signing_keys"]
773+
= Object.assign({}, ...(responses.map(res => res.user_signing_keys || {})));
770774

771775
// yield to other things that want to execute in between users, to
772776
// avoid wedging the CPU
@@ -811,8 +815,12 @@ class DeviceListUpdateSerialiser {
811815

812816
private async processQueryResponseForUser(
813817
userId: string,
814-
dkResponse: object,
815-
crossSigningResponse: any, // TODO types
818+
dkResponse: IDownloadKeyResult["device_keys"]["user_id"],
819+
crossSigningResponse: {
820+
master: IDownloadKeyResult["master_keys"]["user_id"];
821+
self_signing: IDownloadKeyResult["master_keys"]["user_id"]; // eslint-disable-line camelcase
822+
user_signing: IDownloadKeyResult["user_signing_keys"]["user_id"]; // eslint-disable-line camelcase
823+
},
816824
): Promise<void> {
817825
logger.log('got device keys for ' + userId + ':', dkResponse);
818826
logger.log('got cross-signing keys for ' + userId + ':', crossSigningResponse);
@@ -869,7 +877,7 @@ async function updateStoredDeviceKeysForUser(
869877
olmDevice: OlmDevice,
870878
userId: string,
871879
userStore: Record<string, DeviceInfo>,
872-
userResult: object,
880+
userResult: IDownloadKeyResult["device_keys"]["user_id"],
873881
localUserId: string,
874882
localDeviceId: string,
875883
): Promise<boolean> {

src/crypto/backup.ts

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import { encryptAES, decryptAES, calculateKeyCheck } from './aes';
3333
import { getCrypto } from '../utils';
3434
import { ICurve25519AuthData, IAes256AuthData, IKeyBackupInfo, IKeyBackupSession } from "./keybackup";
3535
import { UnstableValue } from "../NamespacedValue";
36+
import { IMegolmSessionData } from "./index";
3637

3738
const KEY_BACKUP_KEYS_PER_REQUEST = 200;
3839

@@ -87,7 +88,7 @@ interface BackupAlgorithmClass {
8788
interface BackupAlgorithm {
8889
untrusted: boolean;
8990
encryptSession(data: Record<string, any>): Promise<any>;
90-
decryptSessions(ciphertexts: Record<string, IKeyBackupSession>): Promise<Record<string, any>[]>;
91+
decryptSessions(ciphertexts: Record<string, IKeyBackupSession>): Promise<IMegolmSessionData[]>;
9192
authData: AuthData;
9293
keyMatches(key: ArrayLike<number>): Promise<boolean>;
9394
free(): void;
@@ -300,7 +301,7 @@ export class BackupManager {
300301
const ret = {
301302
usable: false,
302303
trusted_locally: false,
303-
sigs: [],
304+
sigs: [] as SigInfo[],
304305
};
305306

306307
if (
@@ -320,7 +321,7 @@ export class BackupManager {
320321
ret.trusted_locally = true;
321322
}
322323

323-
const mySigs = backupInfo.auth_data.signatures[this.baseApis.getUserId()] || [];
324+
const mySigs = backupInfo.auth_data.signatures[this.baseApis.getUserId()] || {};
324325

325326
for (const keyId of Object.keys(mySigs)) {
326327
const keyIdParts = keyId.split(':');
@@ -645,9 +646,7 @@ export class Curve25519 implements BackupAlgorithm {
645646
return this.publicKey.encrypt(JSON.stringify(plainText));
646647
}
647648

648-
public async decryptSessions(
649-
sessions: Record<string, IKeyBackupSession>,
650-
): Promise<Record<string, any>[]> {
649+
public async decryptSessions(sessions: Record<string, IKeyBackupSession>): Promise<IMegolmSessionData[]> {
651650
const privKey = await this.getKey();
652651
const decryption = new global.Olm.PkDecryption();
653652
try {
@@ -658,7 +657,7 @@ export class Curve25519 implements BackupAlgorithm {
658657
throw { errcode: MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY };
659658
}
660659

661-
const keys = [];
660+
const keys: IMegolmSessionData[] = [];
662661

663662
for (const [sessionId, sessionData] of Object.entries(sessions)) {
664663
try {
@@ -777,8 +776,8 @@ export class Aes256 implements BackupAlgorithm {
777776
return await encryptAES(JSON.stringify(plainText), this.key, data.session_id);
778777
}
779778

780-
async decryptSessions(sessions: Record<string, IKeyBackupSession>): Promise<Record<string, any>[]> {
781-
const keys = [];
779+
async decryptSessions(sessions: Record<string, IKeyBackupSession>): Promise<IMegolmSessionData[]> {
780+
const keys: IMegolmSessionData[] = [];
782781

783782
for (const [sessionId, sessionData] of Object.entries(sessions)) {
784783
try {

src/crypto/dehydration.ts

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,7 @@ import { decryptAES, encryptAES } from './aes';
2222
import { logger } from '../logger';
2323
import { ISecretStorageKeyInfo } from "./api";
2424
import { Crypto } from "./index";
25-
26-
// FIXME: these types should eventually go in a different file
27-
type Signatures = Record<string, Record<string, string>>;
25+
import { ISignatures } from "../@types/signed";
2826

2927
export interface IDehydratedDevice {
3028
device_id: string; // eslint-disable-line camelcase
@@ -43,13 +41,13 @@ export interface IDeviceKeys {
4341
device_id: string; // eslint-disable-line camelcase
4442
user_id: string; // eslint-disable-line camelcase
4543
keys: Record<string, string>;
46-
signatures?: Signatures;
44+
signatures?: ISignatures;
4745
}
4846

4947
export interface IOneTimeKey {
5048
key: string;
5149
fallback?: boolean;
52-
signatures?: Signatures;
50+
signatures?: ISignatures;
5351
}
5452

5553
export const DEHYDRATION_ALGORITHM = "org.matrix.msc2697.v1.olm.libolm_pickle";
@@ -244,7 +242,7 @@ export class DehydrationManager {
244242
}
245243

246244
logger.log("Preparing one-time keys");
247-
const oneTimeKeys = {};
245+
const oneTimeKeys: Record<string, IOneTimeKey> = {};
248246
for (const [keyId, key] of Object.entries(otks.curve25519)) {
249247
const k: IOneTimeKey = { key };
250248
const signature = account.sign(anotherjson.stringify(k));

0 commit comments

Comments
 (0)