Skip to content

Commit

Permalink
fix(deps): Upgrade to TypeScript 4 (#405)
Browse files Browse the repository at this point in the history
  • Loading branch information
gnarea authored Mar 3, 2022
1 parent f44a2b5 commit f98fa63
Show file tree
Hide file tree
Showing 22 changed files with 1,841 additions and 4,826 deletions.
6,535 changes: 1,787 additions & 4,748 deletions package-lock.json

Large diffs are not rendered by default.

12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,16 @@
"@types/pkijs": "0.0.12",
"date-fns": "^2.28.0",
"del-cli": "^4.0.1",
"jest": "^26.6.3",
"jest": "^27.5.1",
"jest-date-mock": "^1.0.8",
"jest-extended": "^1.2.1",
"jest-extended": "^2.0.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.5.1",
"ts-jest": "^26.5.6",
"ts-jest": "^27.1.3",
"ts-node": "^10.6.0",
"tslint": "^5.20.1",
"typedoc": "^0.20.37",
"typescript": "^3.9.10"
"tslint": "^6.1.3",
"typedoc": "^0.22.12",
"typescript": "^4.6.2"
},
"prettier": "@relaycorp/shared-config/.prettierrc.json",
"publishConfig": {
Expand Down
2 changes: 1 addition & 1 deletion src/lib/_test_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export async function getPromiseRejection<ErrorType extends Error>(
try {
await promise;
} catch (error) {
return error;
return error as ErrorType;
}
throw new Error('Expected promise to throw');
}
Expand Down
22 changes: 0 additions & 22 deletions src/lib/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,3 @@ export function makeDateWithSecondPrecision(date?: Date): Date {
dateWithoutMilliseconds.setMilliseconds(0);
return dateWithoutMilliseconds;
}

/**
* Try/catch block as a expression, a la Kotlin.
*
* @param tryCallback
* @param catchCallback
*
* To avoid using `let`.
*/
export async function tryCatchAsync<T>(
tryCallback: () => Promise<T>,
catchCallback: (error: Error) => Error,
): Promise<T> {
// tslint:disable-next-line:no-let
let result: T;
try {
result = await tryCallback();
} catch (error) {
throw catchCallback(error);
}
return result;
}
2 changes: 1 addition & 1 deletion src/lib/asn1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,6 @@ export function asn1DateTimeToDate(dateASN1: Primitive): Date {
const generalizedTimeBlock = new GeneralizedTime({ value: dateString });
return generalizedTimeBlock.toDate();
} catch (error) {
throw new InvalidMessageError(error, 'Date is not serialized as an ASN.1 DATE-TIME');
throw new InvalidMessageError(error as Error, 'Date is not serialized as an ASN.1 DATE-TIME');
}
}
8 changes: 4 additions & 4 deletions src/lib/bindings/gsc/PrivateNodeRegistration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ export class PrivateNodeRegistration {
privateNodeCertificate = Certificate.deserialize(
registrationASN1.privateNodeCertificate.valueBlock.valueHex,
);
} catch (exc) {
throw new InvalidMessageError(exc, 'Private node certificate is invalid');
} catch (err) {
throw new InvalidMessageError(err as Error, 'Private node certificate is invalid');
}

let gatewayCertificate: Certificate;
Expand All @@ -30,7 +30,7 @@ export class PrivateNodeRegistration {
registrationASN1.gatewayCertificate.valueBlock.valueHex,
);
} catch (err) {
throw new InvalidMessageError(err, 'Gateway certificate is invalid');
throw new InvalidMessageError(err as Error, 'Gateway certificate is invalid');
}

const sessionKey = await deserializeSessionKey(registrationASN1.sessionKey);
Expand Down Expand Up @@ -87,7 +87,7 @@ async function deserializeSessionKey(sessionKeySequence: any): Promise<SessionKe
let sessionPublicKey: CryptoKey;
try {
sessionPublicKey = await derDeserializeECDHPublicKey(sessionPublicKeyASN1.valueBlock.valueHex);
} catch (err) {
} catch (err: any) {
throw new InvalidMessageError(
new Error(err), // The original error could be a string 🤦
'Session key is not a valid ECDH public key',
Expand Down
15 changes: 9 additions & 6 deletions src/lib/bindings/gsc/PrivateNodeRegistrationRequest.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { ObjectIdentifier, OctetString, Primitive, verifySchema } from 'asn1js';

import { derDeserializeRSAPublicKey, derSerializePublicKey } from '../../../index';
import { tryCatchAsync } from '../../_utils';
import { makeHeterogeneousSequenceSchema, makeImplicitlyTaggedSequence } from '../../asn1';
import { derDeserializeRSAPublicKey, derSerializePublicKey } from '../../crypto_wrappers/keys';
import { sign, verify } from '../../crypto_wrappers/rsaSigning';
import InvalidMessageError from '../../messages/InvalidMessageError';
import { RELAYNET_OIDS } from '../../oids';
Expand All @@ -18,10 +17,14 @@ export class PrivateNodeRegistrationRequest {

const request = (result.result as any).PrivateNodeRegistrationRequest;

const privateNodePublicKey = await tryCatchAsync(
async () => derDeserializeRSAPublicKey(request.privateNodePublicKey.valueBlock.valueHex),
(error) => new InvalidMessageError('Private node public key is not valid', error),
);
let privateNodePublicKey: CryptoKey;
try {
privateNodePublicKey = await derDeserializeRSAPublicKey(
request.privateNodePublicKey.valueBlock.valueHex,
);
} catch (err) {
throw new InvalidMessageError('Private node public key is not valid', err);
}

const authorizationSerializedASN1 = request.pnraSerialized;
const countersignature = request.countersignature.valueBlock.valueHex;
Expand Down
2 changes: 1 addition & 1 deletion src/lib/crypto_wrappers/cms/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ export function deserializeContentInfo(derValue: ArrayBuffer): pkijs.ContentInfo
const asn1Value = derDeserialize(derValue);
return new pkijs.ContentInfo({ schema: asn1Value });
} catch (error) {
throw new CMSError(error, 'Could not deserialize CMS ContentInfo');
throw new CMSError(error as Error, 'Could not deserialize CMS ContentInfo');
}
}
4 changes: 2 additions & 2 deletions src/lib/crypto_wrappers/cms/envelopedData.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ describe('SessionlessEnvelopedData', () => {
expect.hasAssertions();
try {
await envelopedData.decrypt(nodePrivateKey);
} catch (error) {
} catch (error: any) {
expect(error).toBeInstanceOf(CMSError);
expect(error.message).toStartWith(`Decryption failed: ${error.cause().message}`);
}
Expand Down Expand Up @@ -446,7 +446,7 @@ describe('SessionEnvelopedData', () => {
expect.hasAssertions();
try {
await envelopedData.decrypt(differentDhKeyPair.privateKey);
} catch (error) {
} catch (error: any) {
expect(error).toBeInstanceOf(CMSError);
expect(error.message).toStartWith(`Decryption failed: ${error.cause().message}`);
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib/crypto_wrappers/cms/envelopedData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export abstract class EnvelopedData {
try {
pkijsEnvelopedData = new pkijs.EnvelopedData({ schema: contentInfo.content });
} catch (error) {
throw new CMSError(error, 'Invalid EnvelopedData value');
throw new CMSError(error as Error, 'Invalid EnvelopedData value');
}
const recipientInfosLength = pkijsEnvelopedData.recipientInfos.length;
if (recipientInfosLength !== 1) {
Expand Down Expand Up @@ -112,7 +112,7 @@ export abstract class EnvelopedData {
recipientPrivateKey: bufferToArray(privateKeyDer),
});
} catch (error) {
throw new CMSError(error, 'Decryption failed');
throw new CMSError(error as Error, 'Decryption failed');
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/lib/crypto_wrappers/cms/signedData.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ describe('sign', () => {
await SignedData.sign(plaintext, keyPair.privateKey, certificate, [], {
hashingAlgorithmName: 'SHA-1',
});
} catch (error) {
} catch (error: any) {
expect(error).toBeInstanceOf(CMSError);
expect(error.message).toEqual('SHA-1 is disallowed by RS-018');
}
Expand Down Expand Up @@ -354,6 +354,7 @@ describe('verify', () => {
describe('plaintext', () => {
test('Nothing should be output if plaintext is absent', async () => {
const signedData = await SignedData.sign(plaintext, keyPair.privateKey, certificate);
// @ts-ignore
// tslint:disable-next-line:no-delete
delete signedData.pkijsSignedData.encapContentInfo.eContent;

Expand Down
4 changes: 2 additions & 2 deletions src/lib/crypto_wrappers/cms/signedData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,8 @@ export class SignedData {
if (!verificationResult.signatureVerified) {
throw verificationResult;
}
} catch (e) {
throw new CMSError(`Invalid signature: ${e.message} (PKI.js code: ${e.code})`);
} catch (err: any) {
throw new CMSError(`Invalid signature: ${err.message} (PKI.js code: ${err.code})`);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib/crypto_wrappers/x509/Certificate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ describe('issue()', () => {
});

test('should import the public key into the certificate', async () => {
spyOn(pkijs.PublicKeyInfo.prototype, 'importKey');
jest.spyOn(pkijs.PublicKeyInfo.prototype, 'importKey');
await Certificate.issue({
...baseCertificateOptions,
issuerPrivateKey: keyPair.privateKey,
Expand All @@ -90,7 +90,7 @@ describe('issue()', () => {
});

test('should be signed with the specified private key', async () => {
spyOn(pkijs.Certificate.prototype, 'sign');
jest.spyOn(pkijs.Certificate.prototype, 'sign');
await Certificate.issue({
...baseCertificateOptions,
issuerPrivateKey: keyPair.privateKey,
Expand Down
20 changes: 8 additions & 12 deletions src/lib/keyStores/privateKeyStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export abstract class PrivateKeyStore {
try {
await this.saveIdentityKeySerialized(privateAddress, privateKeyDer);
} catch (err) {
throw new PrivateKeyStoreError(err, `Failed to save key for ${privateAddress}`);
throw new PrivateKeyStoreError(err as Error, `Failed to save key for ${privateAddress}`);
}
return privateAddress;
}
Expand All @@ -54,7 +54,7 @@ export abstract class PrivateKeyStore {
try {
keySerialized = await this.retrieveIdentityKeySerialized(privateAddress);
} catch (err) {
throw new PrivateKeyStoreError(err, `Failed to retrieve key for ${privateAddress}`);
throw new PrivateKeyStoreError(err as Error, `Failed to retrieve key for ${privateAddress}`);
}

if (!keySerialized) {
Expand Down Expand Up @@ -124,18 +124,14 @@ export abstract class PrivateKeyStore {

//endregion

protected abstract async retrieveIdentityKeySerialized(
privateAddress: string,
): Promise<Buffer | null>;
protected abstract async retrieveSessionKeyData(
keyId: string,
): Promise<SessionPrivateKeyData | null>;
protected abstract retrieveIdentityKeySerialized(privateAddress: string): Promise<Buffer | null>;
protected abstract retrieveSessionKeyData(keyId: string): Promise<SessionPrivateKeyData | null>;

protected abstract async saveIdentityKeySerialized(
protected abstract saveIdentityKeySerialized(
privateAddress: string,
keySerialized: Buffer,
): Promise<void>;
protected abstract async saveSessionKeySerialized(
protected abstract saveSessionKeySerialized(
keyId: string,
keySerialized: Buffer,
peerPrivateAddress?: string,
Expand All @@ -147,7 +143,7 @@ export abstract class PrivateKeyStore {
try {
key = await this.retrieveSessionKeyData(keyIdHex);
} catch (error) {
throw new PrivateKeyStoreError(error, `Failed to retrieve key`);
throw new PrivateKeyStoreError(error as Error, `Failed to retrieve key`);
}
if (key === null) {
throw new UnknownKeyError(`Key ${keyIdHex} does not exist`);
Expand All @@ -165,7 +161,7 @@ export abstract class PrivateKeyStore {
try {
await this.saveSessionKeySerialized(keyIdString, privateKeyDer, peerPrivateAddress);
} catch (error) {
throw new PrivateKeyStoreError(error, `Failed to save key ${keyIdString}`);
throw new PrivateKeyStoreError(error as Error, `Failed to save key ${keyIdString}`);
}
}
}
10 changes: 4 additions & 6 deletions src/lib/keyStores/publicKeyStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,13 @@ export abstract class PublicKeyStore {
try {
await this.saveKey(keyData, peerPrivateAddress);
} catch (error) {
throw new PublicKeyStoreError(error, 'Failed to save public session key');
throw new PublicKeyStoreError(error as Error, 'Failed to save public session key');
}
}

protected abstract async fetchKey(
peerPrivateAddress: string,
): Promise<SessionPublicKeyData | null>;
protected abstract fetchKey(peerPrivateAddress: string): Promise<SessionPublicKeyData | null>;

protected abstract async saveKey(
protected abstract saveKey(
keyData: SessionPublicKeyData,
peerPrivateAddress: string,
): Promise<void>;
Expand All @@ -55,7 +53,7 @@ export abstract class PublicKeyStore {
try {
return await this.fetchKey(peerPrivateAddress);
} catch (error) {
throw new PublicKeyStoreError(error, 'Failed to retrieve key');
throw new PublicKeyStoreError(error as Error, 'Failed to retrieve key');
}
}
}
4 changes: 2 additions & 2 deletions src/lib/messages/RAMFMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export default abstract class RAMFMessage<Payload extends PayloadPlaintext> {
* @param senderPrivateKey
* @param signatureOptions
*/
public abstract async serialize(
public abstract serialize(
// This method would be concrete if TS allowed us to store the message type and version as
// properties
senderPrivateKey: CryptoKey,
Expand Down Expand Up @@ -179,7 +179,7 @@ export default abstract class RAMFMessage<Payload extends PayloadPlaintext> {
try {
certificationPath = await this.getSenderCertificationPath(trustedCertificates);
} catch (error) {
throw new InvalidMessageError(error, 'Sender is not authorized');
throw new InvalidMessageError(error as Error, 'Sender is not authorized');
}

if (this.isRecipientAddressPrivate) {
Expand Down
2 changes: 1 addition & 1 deletion src/lib/messages/payloads/CargoCollectionRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export class CargoCollectionRequest implements PayloadPlaintext {
cda = Certificate.deserialize(cdaSerialized);
} catch (error) {
throw new InvalidMessageError(
error,
error as Error,
'CargoCollectionRequest contains a malformed Cargo Delivery Authorization',
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/lib/messages/payloads/CargoMessageSet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export default class CargoMessageSet implements PayloadPlaintext {
try {
return await messageClass.deserialize(itemSerialized);
} catch (error) {
throw new InvalidMessageError(error, 'Value is not a valid Cargo Message Set item');
throw new InvalidMessageError(error as Error, 'Value is not a valid Cargo Message Set item');
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/lib/nodes/PublicNodeConnectionParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class PublicNodeConnectionParams {
let identityKey: CryptoKey;
try {
identityKey = await derDeserializeRSAPublicKey(paramsASN1.identityKey.valueBlock.valueHex);
} catch (err) {
} catch (err: any) {
throw new InvalidPublicNodeConnectionParams(
new Error(err), // The original error could be a string 🤦
'Identity key is not a valid RSA public key',
Expand All @@ -52,7 +52,7 @@ export class PublicNodeConnectionParams {
sessionPublicKey = await derDeserializeECDHPublicKey(
sessionPublicKeyASN1.valueBlock.valueHex,
);
} catch (err) {
} catch (err: any) {
throw new InvalidPublicNodeConnectionParams(
new Error(err), // The original error could be a string 🤦
'Session key is not a valid ECDH public key',
Expand Down
2 changes: 1 addition & 1 deletion src/lib/publicAddressing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export async function resolvePublicAddress(
let result: LookupResult;
try {
result = await doh.getDNS({ dnssec: true, name, rrtype: 'SRV', decode: true });
} catch (error) {
} catch (error: any) {
throw error.errno === 'ENOTFOUND'
? new UnreachableResolverError(error, 'Failed to reach DoH resolver')
: error;
Expand Down
4 changes: 2 additions & 2 deletions src/lib/ramf/serialization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ function getDateFromPrimitiveBlock(block: asn1js.Primitive): Date {
try {
return asn1DateTimeToDate(block);
} catch (exc) {
throw new RAMFValidationError(exc, 'Message date is invalid');
throw new RAMFValidationError(exc as Error, 'Message date is invalid');
}
}

Expand All @@ -293,7 +293,7 @@ async function verifySignature(
try {
return await cmsSignedData.verifySignature(cmsSignedDataSerialized);
} catch (error) {
throw new RAMFValidationError(error, 'Invalid RAMF message signature');
throw new RAMFValidationError(error as Error, 'Invalid RAMF message signature');
}
}

Expand Down
2 changes: 1 addition & 1 deletion typedoc.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
"exclude": ["**/*.spec.ts"],
"excludePrivate": true,
"excludeProtected": true,
"theme": "minimal"
"theme": "default"
}

0 comments on commit f98fa63

Please sign in to comment.